llama.cpp icon indicating copy to clipboard operation
llama.cpp copied to clipboard

Gemma 4 tool calls: the grammar refuses JSON-quoted values, so the model loops until the token cap

Open fredazarty opened this issue 2 weeks ago • 2 comments

What happens

With Gemma 4 (seen on gemma-4-12b-it-qat-q4_0, with its own chat template), tool calls with a nested value sometimes never end: the model writes until max_tokens, and the request returns finish_reason: "length" with no tool call. Without the tool-call grammar, the same prompt and seed give a short, valid-looking call that stops on its own.

Gemma 4 often writes a structured argument as JSON inside the call, with ASCII quotes: data:{"nodes":[{"id":"browser",...}]}. The lazy grammar built for Gemma 4 tool calls (common/parsers/gemma4.cpp, gemma4_value_rules) does not allow that:

gemma4-value  ::= gemma4-string | gemma4-dict | gemma4-array | gemma4-number | gemma4-bool | gemma4-null
gemma4-string ::= "<|\"|>" ... "<|\"|>"
gemma4-dict-key ::= ( "<|\"|>" ... "<|\"|>" | "\"" [^"]+ "\"" | "'" [^']+ "'" | [^:}]+ ) ":"

A key may be quoted with ", but a value may not. So after {"id": the " the model wants is refused. What we then see in the sampled text:

  1. Endless key. The model never writes the colon again: {"id","n1","name","User Interface",...,"quote","..." đồ,{"id","n2",.... Each pair becomes part of one key ([^:}]+ takes anything but : and }), and since } is refused there too, a stray token stands where each object should close. The same node repeats until the cap (57,333 characters at 16,384 tokens).
  2. Endless string. The model opens the value as a Gemma string, data:<|"|>{"view": "diagram", ...}, then closes it the JSON way, with } and ". <|"|> never comes, so the rest of the call, <tool_call|>, a whole answer and then unrelated text all stay inside that string until the cap.
  3. Too deep. Once, after 221 s, the server answered 400 input is nested more than 64 levels deep instead of an answer.

A property declared "type": "string" doesn't help. gemma4_schema_parser::visit maps it to the generic gemma4-value, so the model may still open a dict there, and the trap above starts.

Reproduce without a model

On b11888 (48c9f08b7), b12503 and master (2cbfc3cf3, 2026-11-18). Template: the GGUF's own Gemma 4 template. One tool:

{"messages":[{"role":"user","content":"Draw a diagram of a web app: a browser talks to an API, and the API reads a database."}],
 "tools":[{"type":"function","function":{"name":"show_diagram","description":"Show a diagram.","parameters":{"type":"object","properties":{"title":{"type":"string","description":"A short title."},"data":{"type":"string","description":"The diagram as a JSON object: {\"nodes\": [{\"id\": ..., \"name\": ...}], \"links\": [{\"from\": ..., \"to\": ...}]}."}},"required":["data"]}}}]}

Take the grammar common_chat_templates_apply builds for it (grammar.gbnf), and check two calls with tests/test-gbnf-validator:

<|tool_call>call:show_diagram{data:{"nodes":[{"id":"browser","name":"Browser"}]}}<tool_call|>
  -> Input string is invalid according to the grammar.
     Error: Unexpected character '"' at position 51      (the value "browser")

<|tool_call>call:show_diagram{data:<|"|>{"nodes":[{"id":"browser","name":"Browser"}]}<|"|>}<tool_call|>
  -> Input string is valid according to the grammar.

The parser agrees with the grammar. A common_chat_session fed the first text gives no tool call and no content. The second gives {"data":"{\"nodes\":[...]}"}.

With a model

Gemma 4 12B QAT Q4_0, llama-server b11888, --jinja --reasoning off, MTP draft model, 77 tools, temperature 1.0 and top-k 64 from the GGUF. A diagram request ran to the 4,096 cap in 3 of 12 tries, and to the 8,192 cap in 2 of 12. For one of them (seed 725752995), we replayed the prompt on /completion with the same seed:

  • with the grammar, its trigger and preserved tokens: the same endless key as the chat call, token for token;
  • without the grammar: <|tool_call>call:<tool>{data:{"nodes":[{"id":"1",...}],"links":[...]},<two string args as <|"|>...<|"|>>}<tool_call|>, 547 characters, and it stops.

What would fix it, as far as we can tell

  • gemma4-value also accepting a JSON string ("..." with JSON escapes), in the grammar and in the parser, since Gemma 4 writes them. Keys already accept "...".
  • Maybe: a property typed string mapped to gemma4-string instead of gemma4-value, so the schema's type holds.

Related, but not the same: #29655 (Gemma 4 calls extracted while still partial, closed 2026-11-17).

We bundle llama-server in a desktop app and can test a patch on the same prompts.

fredazarty avatar Nov 18 '26 17:11 fredazarty

Another data point for the "endless string" case, on a different Gemma 4 model.

Setup: Nemotron-3.5-Bolt-E4B Q4_K_M (Gemma 4 based, its own template), llama-server b12124 (8bed7cfb9), --jinja, temperature 1.0, OpenAI /v1/chat/completions with tools (tool_choice: "auto").

What we see: the model opens a value as a Gemma string and closes it with an ASCII quote. Everything up to the next <|"|> becomes that one value, so the fields after it never arrive:

<|tool_call>call:record{state:<|"|>unknown"}],context:[{id:<|"|>S7<|"|>,why:<|"|>the report<|"|>}]}<tool_call|>

The server returns {"state": "unknown\"}],context:[{id:", ...} and context is gone. At the end of a call, the same slip swallowed <tool_call|>, the next thought channel and the start of the next call into one string value (about 700 characters).

How often: in a multi-turn agent run with about 20 tools and nested array arguments, 8 of 38 rejected tool calls came from this slip: 6 lost a required field, and 2 swallowed the following call. The model tends to resend the same malformed call when told the field is missing.

Workaround we use: generate raw text (/apply-template + /completion) and parse Gemma calls client-side. Inside a <|"|> string, a plain " followed by ,, } or ] counts as the end of the string only if the rest of the call then parses. Otherwise it stays as text, so "seize", then inside a quotation survives. If it helps, the same rule could apply to the PEG parser's lenient path, or the grammar could refuse a " followed by ,, } or ] inside gemma4-string.

caeser1996 avatar Nov 18 '26 19:11 caeser1996

Three different runaways are described here, and they do not all look alike in the sampled text — worth separating if you want a non-grammar guard, because a plain "tail repeats itself" test only catches two of them.

  1. Endless key ({"id","n1","name","User Interface",...,"id","n2",...): this is not periodic. Each object contributes new content, so there is no period p with tail[-p:] == tail[-2p:-p]. The cheap signal is syntactic and monotone: inside gemma4-dict-key the grammar forbids : and } ([^:}]+), so a healthy progressing key has no quoted-token accumulation. Abort when quote-delimited tokens since the last : exceeds N and the position is still inside a key (e.g. > 40 tokens or > 2000 chars since the last :).

  2. Endless string (data:<|"|>{... closed with } and "): here the swallowed remainder is ordinary text, so it is periodic at the tail — tail[-p:] == tail[-2p:-p] for p in 1..160 catches both "same sentence repeated" and ABAB alternation (p = pair length), which a "same 20-char window 4 times" counter misses. Abort and cut at the first repeated period.

  3. Too deep: same as 1, the metric that grows is nesting depth — cap it at parse time instead of after 221 s.

Practical note: I ran (2) over ~230 real assistant messages and it fires only on genuine loops; with the tail-equality form it costs one pass over the last ~2*k chars. Code, Python + JS, MIT: https://agent-mcocdaa.github.io/agent-output-check/repeat.html

agent-mcocdaa avatar Nov 19 '26 11:11 agent-mcocdaa