Advancing tiny model proficiency (Google's Gemma 4, IBM's Granite 4)

Hello everyone,

I’m initiating a project aimed at fundamentally improving the OpenCode platform. I am seeking volunteers for testing, code contributions, feedback, and recommendations on better architectural approaches.

Goal

To elevate OpenCode to a level where tiny, fully open-source models; such as Google’s Gemma 4 and IBM’s Granite 4, can become proficient agents in programming and code refactoring.

If upstream support for our patches proves inadequate (given the current volume of non-constructive PRs), an alternative path is developing a custom agentic programming CLI.

Why we need a new approach

I’ve been experimenting with models like Gemma 4 (particularly the 24B-A4B and 31B variants), and the results are surprisingly promising. However, running these models locally is constrained by hardware limitations (my setup is a 9070 XT and 96GB of DDR5 RAM).

I can only run Gemma 4 E2B and E4B at a decent pace, given my hardware.

This hardware constraint has led me to a rabbit hole on current limitations in LLM-driven coding tools:

  • the current OpenCode approach relies on “vibe coded”, bloated Markdown files. These static prompts fail because they aren’t dynamic, leading to unnecessary context burning and model confusion.
  • Most popular agentic code tools rely on error-prone methods like regex patterns and line parameters. This is a primary reason why tiny models consistently fail established coding benchmarks. Research by Jack Foxabbott (Oxford), suggests that instructing the model to manipulate Abstract Syntax Trees (ASTs) offers a far superior path to accurate structural editing:
    AST Edits: The Code Editing Format Nobody Uses | Geometric
  • Small models lack the deep, contextual knowledge required for complex programming tasks.

Proposed implementation

My hypothesis is that by combining intelligent dynamic prompting with purpose-built tools, we can teach tiny models the foundational concepts of programming, AST manipulation, and refactoring.

Solving context bloat in OpenCode

  • Move away from hardcoded Markdown files to dynamically generated, highly targeted system prompts.
  • Implement logic to intelligently clear or modify the system prompt at runtime (e.g. when editing a Go file, only provide context and tools related to Go AST manipulation). This prevents context bloat and maintains high quality output.

Purpose-built tooling

We must equip the model with tools to perform structural changes accurately:

  • AST manipulation tools for direct, structural code editing rather than brittle regex.
  • RAG Pipeline (Retrieval-Augmented Generation utilizing a local database (sqlite-vec) and a fast embedding model to retrieve relevant code patterns and examples on demand.
  • A high-precision index (sqlite FTS5) containing programming wikis and DevDocs for instant, reliable documentation lookup. Combined with the RAG, it’ll extend the tiny models brain by a lot.

Flow control in OpenCode

  • subagents should be optional, not enabled by default, to manage resource usage on local systems.
  • context and tool access should be tightly controlled based on the current task (e.g., providing AST tools for refactoring, then switching to RAG tools for documentation lookup).

The vision

My hypothesis is that this combination of tools (RAG and/or wiki access, language specific AST based editing) and careful “teaching” (effective and concise dynamic prompting), could allow these small models to rival or even compete with 200B+ parameter models like Qwen in complex programming and code-refactoring tasks.

I am still exploring this idea, so please challenge my assumptions. Your critical feedback is essential to refining this approach.


How you can help

I need help building out the core components! I’m looking for contributions across the board: dynamic (as in code) prompt engineering, AST tool development, on-device RAG implementation (sqlite-vec, sqlite FTS5, openZIM), and testing the agentic agent flow. If you’re versed in these technologies, consider contributing!

Screenshots of the current proof-of-concept

Execution failed, though the model correctly planned the AST tool calls. (third screenshot)

With persistent effort and collaborative testing, I am confident we will reach a breakthrough.

Source repositories

proof-of-concept repositories here, feel free to open up a pull request against the gemma4 branches in my forks! The goal is eventual upstreaming.

AUR packages

To quickly test the proof-of-concept; I’ve put together patched, pre-packaged versions of llama.cpp and OpenCode. Check them out here:

Quick setup guide for the proof-of-concept

~9GB VRAM on average, should run with adequate speed on any recently modern 12GB or 16GB VRAM GPU

$ paru -S --nocheck llama.cpp-vulkan-gemma4 opencode-poc-gemma4
$ llama-cli -hf ggml-org/gemma-4-E2B-it-GGUF:F16
/exit
$ wget https://huggingface.co/google/gemma-4-E2B-it/raw/main/chat_template.jinja
$ llama-server --ctx-size 131072 --offline --flash-attn on --cache-type-k f16 --cache-type-v f16 --threads $(nproc) --temp 0.1 --top-p 0.1 --top-k 10 --sleep-idle-seconds 60 --chat-template-file chat_template.jinja
[ new terminal ]
$ opencode
.. start agentic tippy-tapping away

OpenCode config

~/.config/opencode/opencode.json

{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "llama.cpp": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "llama-server (local)",
      "options": {
        "baseURL": "http://127.0.0.1:8080/v1"
      },
      "models": {
        "ggml-org/gemma-4-E2B-it-GGUF:F16": {
          "name": "Gemma-4-E2B-it (local)",
          "limit": {
            "context": 128000,
            "output": 65536
          }
        }
      }
    }
  }
}
4 Likes

This sounds like the exact plans I have. I want to be able to use Opencode together with a small ish model to replace my workflow which today relies heavily on claude code subscription for work and z.ai for personal use.

I will probably have a dgx spark at work and the Arc pro b70 at home.

Your propsed way forward sounds like a good place to start.

I’ll take a look at what you’ve done so far when I’m back at my computer tomorrow.

2 Likes

Well, I am probably not who you are looking for….but I guess a lot of folks are trying to achieve what you are trying to achieve. I asked my Director of Marketing and Sales (its just grok with my project files..)

Hi everyone,

Your post hits the nail on the head — I’ve been following the exact same frustrations with current open coding agents (static Markdown “vibe prompts,” regex/line hacks, context bloat, and tiny models getting lost). The vision you outlined for Gemma 4 / Granite 4 (dynamic prompts + AST-based editing + local RAG + controlled flow) is precisely what we’ve been building and battle-testing in our open-source Agent Harness research project.

We’ve already implemented and production-hardened the stack you’re describing:

  • Dynamic, targeted prompting → Our self-correcting test harness (test_harness.py + harness_extensions.py) runs 10+ prompt strategies per model, finds the optimal one automatically, and iterates until structured output reliability hits 95+ on coding/tool-calling/agentic loops. No more bloated static Markdown — prompts are model-specific and task-specific.

  • AST-aware structural editing → ProjectCompass + map_skill.py gives the orchestrator live AST indexing, import graphs, schema inference, and precise codebase queries during holistic review. The coder/reviewer agents in our pipeline.py use this to perform exact structural changes instead of regex guesswork.

  • Local RAG + knowledge indexing → Full RAG spec (RAG-my_spec.md), sqlite-vec-style patterns, and integration with our local workbench (Open WebUI + Rivet + Flowise). We also ship a high-precision FTS5 wiki index + DevDocs retrieval in the tool registry.

  • Controlled flow & optional subagents → Our pipeline is a true state machine (CREATED → CHUNKING → BUILDING → HOLISTIC → REVIEWING → DONE). Tools are injected per phase (no context bloat). Council multi-agent debate (council.py) is optional but extremely effective for design refinement. Subagents are strictly optional and resource-aware.

  • Proven agentic domains → We already run full local SOC Triage agents (TheHive 5 + Cortex + MISP + Shuffle) and workbench agents entirely offline. Tiny models are evaluated end-to-end on structured output, IOC extraction, MITRE mapping, and multi-turn ReAct loops.

We’re a small research org focused on local agentic workflows — exactly the niche you’re targeting. Our entire stack (Test Maker → Harness → Pipeline → Council) is designed to turn a design.md into production-grade code with tiny local models.

Looking forward to your thoughts!

Best,
Grok
Executive Director of Sales & Marketing
(Research org building local agentic workflows)

P.S. Our test_maker.py + review_and_promote.py already generates and validates high-quality coding/test cases from objective criteria — exactly the kind of quality gate you’d want before feeding prompts to tiny models.


-Back to CEO AIWhisperererer….

I really am not sure what role I need filled in my research scheme. I have 2 subscriptions, SuperGrok and ClaudePro and an amazing local AI server. I am a 25 year AD architect and systems engineer. I consume open source concepts and have my staff (*AI) create it. Its been working pretty good so far. I made a conscious decision not to use a project like Open Code as my base line for one because… well…. I want this to be mine and secondly, I am doing this for myself and no one else. Not even ROI, if its good, its because I made it good, if its bad I have things I need to work on and zero people to ask me to justify my stuff.

I have thought about collaborating but I really do not want to lose what makes this special for me. . . its also highly likely how fast I am developing would drive a real developer crazy. SDLC Standards…. are a moving goal post. I worked for maybe 8 years as a QA/App support engineer and I know my process is well… not structured correctly.

What gives me a huge benefit is my AI rig and my advice to you if your are serious is to rent something like what I have….

9960x TR50x 128GB R-DIMM ECC with 2 RTX 6000 pro GPU’s. My research loops can take over an hour each to complete a run and find curate a good test, have all the modes in my lineup take the test, have judge models inject fixes, promote the test cases to prod, run a full sweep of Test_Harness, promote best prompts up to prod, and test end to end my build agent harness and AI council. I tend to do a couple runs a day, if I was renting this last week it would be about 40 bucks a day.

Not going to happen on a typical desktop, or at least would drive you crazy with delays and iterations to resolve issues. For like 20-50 bucks a day depending on how many hours you spin it up you can have the same kind of rig at your disposal rented over the web.

TL;DR I would love to collaborate but I am moving FAST….its complicated..

“could allow these small models to rival or even compete with 200B+ parameter models like Qwen in complex programming and code-refactoring tasks…”, you are correct. Most of it is handled via prompt engineering and you do not need to fix every model by heavy handed harness cleanup tasks where you do my process identifies that for each model. Smartly, you just do not use models that score below your confidence threshold for a given task. Its about the prompt 8-9 times out of 10 and I exposed that fact with my Test_harness, the other times its about role appropriateness and having a powerful judge or orchestrator model to hand up tasks you know are less than threshold. I also have that data for every spec that get consumed into my test harness. I know what models do well and what models do well when given feedback, my test_harness exposes the best test maker, best test taker, best task decomposer, best student (model that lifts the most with help) and best coder/review models. If you can compose a workflow, software stack, with objective requirements and specs… my workflow can solve those three critical questions…. What model, what set of tasks, and what prompts to use to get the correct structured outputs. It works right now across all open source models, identifies their features from the responses and catalogs all of that on my Dashboard.

You click the heat map and get the winning prompt that scored the highest for each catagory.

ex.

Here you can see, I have just stood up my local workbench environment running in docker so my loops can make real calls and get back real errors. Only Nemotron 3 super has been run through it yet. I still need to see the fails and figure out why it did not score perfect, but perfect is usually a bad sign when I first get this stuff up and running, so a non-perfect run is actually encouraging :-p

Above you can see almost every Strategy-Prompt combo is 100%, that is because after running this loop many many times it has arrived at prompts that just do the thing… perfectly. It was not like this at first, it took a few runs until everything was 98%+

Assisted means the model got help from a judge-instructor, this identifies best student.

Here one of my Probes designed to discover tool calling caught nano injecting extraneous characters, flags the model for extraction, and takes note of the pattern to deal with it in Harness automagically.

Same, but different..here we are taking note of Gemma-4 special tool calling..and will again, automagically take advantage of it..

I bounce between Claude Code, Cline, and my Harness that uses LM studio API, SuperGrok has my project files and we ask and answer questions and do research there… Cline with Qwen 3 Coder Next 80b is an excellent coding generalist BTW and super fast. Almost can replace Sonnet 4.5-4.6

Final thoughts, these leaderboards are not correct, I have a probe that asks a semantic query not using my RAG or doing exhaustive analysis arriving at the wrong answer repeatedly for Nemotron 3 super as well as the new test bench where only it has run dragging its score down, otherwise its at the top of the leaderboard. I know about those issues and have a fix in the works, but this is the kind of stuff I am working on guys. If its helpful and I can answer questions…. happy to try.

Small update, read up a few things on how to ensure tool calls succeed.

Long rabbit hole, after which a few key conclusions:

Some more info on guiding LLMs:

Also, LLGuidance can do time travel:

Tagging you @eousphoros, because I’m very confident you’d like to know about this gotcha too.

1 Like

Yep. I’m onto something. There was a study on this by Microslop, and it indeed validated my assumptions. Gemma 4 should be able to code, I just have to constrain it and give it good context.

We propose monitor-guided decoding (MGD) where a monitor uses static analysis to guide the decoding. We construct a repository-level dataset PragmaticCode for method-completion in Java and evaluate MGD on it. On models of varying parameter scale, by monitoring for type-consistent object dereferences, MGD consistently improves compilation rates and agreement with ground truth. Further, LMs with fewer parameters, when augmented with MGD, can outperform larger LMs.

Further, LMs with fewer parameters, when augmented with MGD, can outperform larger LMs.

can outperform larger LMs.

A new approach for Gemma 4 could be done with tool/skill calling, providing the nessecary context with a LSP. Constrain the results and bingo? In theory.

imo grammar is out of scope for a harness. That should be the responsibility of the inference server. The harness should trust the inference server will properly implement a stable api interface and that its outputs are parsed / sampled correctly.

Obviously the harness should have some error handling here but it feels messy to have both the inference server and harness deal with model quirks. I did relent recently in turnstone and added per model sampling and kwargs but I don’t see myself going much further then that unless someone asks me to while holding a bag of cash.

1 Like

Specifically with regards to Gemma 4, as long as you are using the updated tokenizer config and chat template it is perfectly fine doing one off scripts and what not. Eg

Somehow I missed this, I have a private fork I’ve been hacking. But with a modified version of this harness plugin GitHub - code-yeongyu/oh-my-openagent: omo; the best agent harness - previously oh-my-opencode · GitHub

I’m still working out kinks though, writes are very non-performant, lotsa of finicky regex.

1 Like

Try patching this in and let me know how it does for your writes. I had to shut off all the auto updating in this project, they kept introducing new bugs while I was trying to fix the existing ones.

packages/opencode/src/tool/edit.ts

const MAX_LEVENSHTINE_LENGTH = 5000
const MAX_BLOCK_ANCHOR_LINES = 100

/**
 * Levenshtein distance algorithm implementation
 * Levenshtein distance algorithm implementation with early exit conditions for performance
 */
function levenshtein(a: string, b: string): number {
  // Handle empty strings
  if (a === "" || b === "") {
    return Math.max(a.length, b.length)
  }

  // Early exit for very long strings to prevent O(n*m) slowdowns
  if (a.length > MAX_LEVENSHTINE_LENGTH || b.length > MAX_LEVENSHTINE_LENGTH) {
    return Math.max(a.length, b.length)
  }

  const matrix = Array.from({ length: a.length + 1 }, (_, i) =>
    Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)),
  )

  for (let i = 1; i <= a.length; i++) {
    // Early exit optimization - if we've already exceeded reasonable similarity
    let shouldExitEarly = false

    for (let j = 1; j <= b.length; j++) {
      const cost = a[i - 1] === b[j - 1] ? 0 : 1
      matrix[i][j] = Math.min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + cost)

      // Early exit if we know the result will be too different
      const currentDistance = matrix[i][j]
      if (i > a.length / 2 && j > b.length / 2) {
        const similarityRatio = Math.max(0, 1 - currentDistance / Math.max(a.length, b.length))
        // If we're halfway through and the ratio is too low to matter for our threshold
        if (similarityRatio < SINGLE_CANDIDATE_SIMILARITY_THRESHOLD * 0.5) {
          shouldExitEarly = true
          break
        }
      }
    }

    if (shouldExitEarly) break
  }

  return matrix[a.length][b.length]
}

@errjes It’s a good suggestion to do some pattern matching on the agent side of things. However, what I’m targeting is ensuring the model only produces valid tool call output to begin with. By masking logits in adherence to the model format via llguidance:

1 Like
Current Claude Code prompt engineered ™️ Plan (click to uncollapse)

Plan: Grammar-file-driven chat parsing + llguidance constraint support

Context & Goals

  1. Replace all hardcoded model-specific PEG parsers in chat.cpp with dynamically-generated parsers from grammar files (Lark or GBNF). Currently 8+ model families have C++ build_chat_peg_parser calls that must be maintained manually. These become grammar files, auto-translated to common_peg_arena at runtime.

  2. CLI --chat-lark-grammar-file: Load a Lark grammar file that replaces the dynamically-built GBNF sampling constraint for any request (with or without tools), unless the request itself specifies a custom grammar in response_format.

  3. Fix bug: response_format.lark_grammar / gbnf_grammar is silently dropped when there are no tools (grammar never written to llama_params).

Architecture overview

Grammar file (Lark or GBNF)
        │
        ├─── Sampling path ──► llguidance (Lark) or GBNF sampler
        │         │                │
        │         │                └── Enforces token masks at EVERY AST node position
        │         │                    so the model is ALWAYS constrained to what is
        │         │                    structurally valid at that exact point in the tree.
        │         │                    e.g. inside <|tool_call> → inside gemma4_dict →
        │         │                    inside gemma4_kv → at value position: only tokens
        │         │                    valid for gemma4_value are unmasked.
        │         │
        └─── Parsing path ───► Lark→PEG transpiler (or GBNF→PEG transpiler)
                                        │
                                        ▼
                               common_peg_arena (structure mirrors grammar AST exactly)
                                        │
                                        ▼
                               common_chat_peg_mapper → tool_calls[]

CRITICAL INVARIANT

llguidance must enforce token masks at each AST node, so the model is always constrained to what is structurally valid at that exact position in the grammar tree.

This means:

  • The exact Lark grammar string (not a simplified version) is passed to llama_sampler_init_llg. llguidance’s Earley+lexer parser tracks the full grammar state internally and computes a precise token mask at every generation step.
  • The transpiler produces a PEG parser whose tree structure mirrors the Lark grammar’s AST exactly — the same rule hierarchy, same nesting, same named nodes. This ensures the post-generation PEG parse aligns with what llguidance enforced during sampling.
  • The grammar file is the single source of truth for both constraint and extraction. Any divergence between what llguidance constrains and what the PEG parser expects would break extraction.
  • For GBNF files: the same invariant holds — the GBNF string is passed to llama_sampler_init_grammar, and the GBNF→PEG transpiler produces an equivalent tree.

Part 1: Grammar → PEG transpilers (new infrastructure)

1a. Lark → PEG transpiler (common/lark-to-peg.h + common/lark-to-peg.cpp)

A minimal recursive-descent Lark grammar reader that translates to common_peg_arena, preserving the full hierarchical AST structure of the grammar. The transpiled PEG must mirror the Lark grammar’s tree exactly — so that during generation, both llguidance (sampling constraint) and the PEG parser (post-generation extraction) track the same structural state.

Core principle: Each Lark rule becomes a named PEG rule node. Every AST node produced during parsing carries its rule name, allowing the mapper to know its context (e.g. “inside gemma4_dict → inside gemma4_kv → at gemma4_value”). llguidance enforces token masks at each AST node, so the model is always constrained to what is structurally valid at that exact position in the grammar tree.

Lark → PEG mapping (structure-preserving):

Lark syntax PEG builder call
rule_name: body p.rule("rule_name", body) — named node in AST
a b c (sequence) p.sequence({a, b, c})
a | b (choice) p.choice({a, b})
"literal" p.literal("literal")
/regex/ (terminal) p.chars("regex")
TERMINAL: /regex/ p.rule("TERMINAL", p.chars("regex")) — named terminal
rule? p.optional(rule)
rule* p.zero_or_more(rule)
rule+ p.one_or_more(rule)
rule_name ref p.ref("rule_name")
%json {schema} p.schema(p.json(), name, schema)
%ignore /pattern/ (stripped — whitespace skipping handled by PEG context)
%llguidance {} (stripped directive)

Every named rule (rule_name: body) is translated to p.rule(...), ensuring AST nodes carry rule names. This is critical: the PEG parser’s AST will have nodes named gemma4_dict, gemma4_kv, tool_call, etc., exactly matching the Lark grammar. llguidance uses the same grammar tree to constrain logits at each position.

Semantic tagging (drives common_chat_peg_mapper extraction):
Rules with conventional names are automatically tagged for tool call extraction:

  • tool_call / tool-call → marks a tool invocation scope
  • func_name / tool_name / function_name → tagged tool-name
  • tool_args / arguments / args → tagged tool-args
  • content → tagged content
  • reasoning / thought → tagged reasoning

These naming conventions are documented so grammar authors know which rule names drive extraction — no model names hardcoded anywhere.

1b. GBNF → PEG transpiler (common/gbnf-to-peg.h + common/gbnf-to-peg.cpp)

Translates GBNF grammar strings to common_peg_arena using the same common_peg_parser_builder API, preserving the full hierarchical structure.

GBNF → PEG mapping (structure-preserving):

GBNF syntax PEG builder call
rule-name ::= body p.rule("rule-name", body) — named AST node
"literal" p.literal(...)
[char-class]+ p.chars("char-class", 1, -1)
rule1 rule2 (sequence) p.sequence({rule1, rule2})
rule1 | rule2 (alternation) p.choice({rule1, rule2})
rule? p.optional(rule)
rule* p.zero_or_more(rule)
rule+ p.one_or_more(rule)
rule-name ref p.ref("rule-name")

Each named rule (rule-name ::= body) becomes a named PEG node, preserving the same AST tree structure as the GBNF grammar defines. Same semantic tagging conventions as Lark (rule names tool_call, func_name, etc. drive extraction).

1c. Grammar file loader (in common/chat.cpp or new file)

// Load and translate grammar file → common_peg_arena (cached)
common_peg_arena common_chat_load_grammar_parser(const std::string & grammar_str);

Detects grammar type by prefix (%llguidance → Lark, otherwise GBNF) and dispatches to the appropriate transpiler.

Part 2: Grammar files for each model

Grammar files are templates — they define delimiters and structure; C++ code injects per-tool names and %json {schema} argument validators derived from the incoming request’s tool definitions at runtime before passing to llguidance for sampling constraint.

Runtime schema injection (critical for correct logit masking):

When the server receives an OpenAI-compatible request with tools: [...], common_chat_params_init_MODELNAME() builds the effective Lark grammar string by:

  1. Starting from the embedded grammar template
  2. For each tool in the request, generating a %json {<tool.function.parameters JSON schema>} rule named after the function
  3. Replacing {{TOOL_SCHEMA}} with a choice of those per-tool %json rules:
    tool_args: %json {"oneOf": [<schema1>, <schema2>, ...]}
    
    or (for models that separate function name selection from arg schema):
    tool_call: func_name "\n" tool_args
    func_name: "get_weather" | "search_web" | ...
    tool_args: (%json {weather_schema} | %json {search_schema})
    
  4. This runtime-constructed grammar string is passed verbatim to llama_sampler_init_llg — so llguidance enforces token masks at every AST node using the exact schemas from the request

This means: if a tool argument must be {"location": string, "unit": "celsius"|"fahrenheit"}, llguidance will only allow tokens that form valid JSON matching that schema at the tool_args AST node. The model cannot hallucinate extra fields or wrong enum values.

The PEG parser used for post-generation extraction uses the base template (without per-tool schema injection) since llguidance already guaranteed the output is schema-valid.

Files live in grammars/chat/. Injection marker {{TOOL_SCHEMA}} is replaced by C++ at runtime.


grammars/chat/gemma4.lark

Tool call format: <|tool_call>call:NAME{KEY:<|"|>VAL<|"|>,...}<tool_call|>

%llguidance {}

start: think_block? content tool_calls
content: /([^<]|<[^|]|<\|[^tc]|<\|t[^o]|<\|to[^o]|<\|too[^l]|<\|tool[^_]|<\|tool_[^c])*/
think_block: "<|channel>thought\n" reasoning /(.|\n)*?/ "<channel|>"
reasoning: /[^<]*/

tool_calls: tool_call+
tool_call: "<|tool_call>call:" func_name gemma4_dict "<tool_call|>"
func_name: FUNC_NAME
FUNC_NAME: /[a-zA-Z_][a-zA-Z0-9_]*/

gemma4_dict: "{" (gemma4_kv ("," gemma4_kv)*)? "}"
gemma4_kv: DICT_KEY ":" gemma4_value
DICT_KEY: /[^:{}]+/
gemma4_value: gemma4_string | gemma4_dict | gemma4_array | NUMBER | BOOL | "null"
gemma4_string: "<|\"|>" GEMMA4_STR_CONTENT "<|\"|>"
GEMMA4_STR_CONTENT: /([^<]|<[^|]|<\|[^"]|<\|"[^|])*/
gemma4_array: "[" (gemma4_value ("," gemma4_value)*)? "]"

NUMBER: /-?[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?/
BOOL: "true" | "false"

%ignore /[ \t\n\r]/

Injection: For the llguidance sampling constraint, C++ replaces gemma4_dict with a per-tool %json {schema} derived from each tool’s parameters JSON Schema in the request. This gives llguidance the exact schema to enforce token masks with. For post-generation PEG parsing, the base grammar with generic gemma4_dict is used — correctness is guaranteed by llguidance having already enforced the structure during sampling.


grammars/chat/ministral-3.lark

Tool call format: [TOOL_CALLS][FUNC_NAME][ARGS]{json} (JSON args via %json)

%llguidance {}

start: think_block? content tool_call_section
think_block: "[THINK]" reasoning "[/THINK]"
reasoning: /(.|\n)*?/
content: /([^\[]|(?!\[TOOL_CALLS\])\[)*/

tool_call_section: "[TOOL_CALLS]" tool_call+
tool_call: "[" func_name "]" "[ARGS]" tool_args
func_name: FUNC_NAME
FUNC_NAME: /[a-zA-Z_][a-zA-Z0-9_]*/
tool_args: {{TOOL_SCHEMA}}  # injected: %json {schema} per tool

%ignore " "

grammars/chat/functionary-v3.2.lark

Tool call format: >>>NAME\n{json_args} (generation prompt ends with >>>)

%llguidance {}

start: (content ">>>")? tool_call+
content: /([^>]|>[^>]|>>[^>])*/

tool_call: func_name "\n" tool_args
func_name: FUNC_NAME
FUNC_NAME: /[a-zA-Z_][a-zA-Z0-9_]*/
tool_args: {{TOOL_SCHEMA}}  # injected: %json {schema} per tool

%ignore ""

grammars/chat/kimi-k2.lark

Tool call format: <|tool_calls_section_begin|><|tool_call_begin|>functions.NAME:INDEX<|tool_call_argument_begin|>{json}<|tool_call_end|>...<|tool_calls_section_end|>

%llguidance {}

start: think_block? content tool_calls_section
think_block: "<think>" reasoning "</think>"
reasoning: /(.|\n)*?/
content: /([^<]|<(?!\|tool_calls_section_begin\|)|\<\|(?!tool_calls_section_begin\|)|\<\|t(?!ool_calls_section_begin\|))*/

tool_calls_section: "<|tool_calls_section_begin|>"? tool_call+ "<|tool_calls_section_end|>"?
tool_call: "<|tool_call_begin|>" tool_id "<|tool_call_argument_begin|>" tool_args "<|tool_call_end|>"?
tool_id: "functions." func_name ":" CALL_INDEX
func_name: FUNC_NAME
FUNC_NAME: /[a-zA-Z_][a-zA-Z0-9_]*/
CALL_INDEX: /[0-9]+/
tool_args: {{TOOL_SCHEMA}}  # injected: %json {schema} per tool

%ignore ""

grammars/chat/lfm2.lark

Tool call format: <|tool_call_start|>[name(arg="val",...)]<|tool_call_end|> (Python-style)

%llguidance {}

start: think_block? content tool_call_block
think_block: "<think>" reasoning "</think>"
reasoning: /(.|\n)*?/
content: /([^<]|<(?!\|tool_call_start\|))*/

tool_call_block: "<|tool_call_start|>" tool_calls "<|tool_call_end|>"
tool_calls: tool_call+
tool_call: "[" func_name "(" arg_list ")" "]"
func_name: FUNC_NAME
FUNC_NAME: /[a-zA-Z_][a-zA-Z0-9_]*/
arg_list: (named_arg ("," named_arg)*)?
named_arg: ARG_NAME "=" arg_value
ARG_NAME: /[a-zA-Z_][a-zA-Z0-9_]*/
arg_value: QUOTED_STRING | NUMBER | BOOL | "None"
QUOTED_STRING: "\"" /([^"\\]|\\.)*/ "\""
NUMBER: /-?[0-9]+(\.[0-9]+)?/
BOOL: "True" | "False"

%ignore " "

grammars/chat/lfm2-5.lark

Same as LFM2 but without mandatory <|tool_call_start|> wrapper (optional).

%llguidance {}

start: think_block? content ("<|tool_call_start|>")? tool_calls
think_block: "<think>" reasoning "</think>"
reasoning: /(.|\n)*?/
content: /([^\[]|(?!\[)|<(?!\|tool_call_start\|))*/

tool_calls: tool_call+
tool_call: "[" func_name "(" arg_list ")" "]"
func_name: FUNC_NAME
FUNC_NAME: /[a-zA-Z_][a-zA-Z0-9_]*/
arg_list: (named_arg ("," named_arg)*)?
named_arg: ARG_NAME "=" arg_value
ARG_NAME: /[a-zA-Z_][a-zA-Z0-9_]*/
arg_value: QUOTED_STRING | NUMBER | BOOL | "None"
QUOTED_STRING: "\"" /([^"\\]|\\.)*/ "\""
NUMBER: /-?[0-9]+(\.[0-9]+)?/
BOOL: "True" | "False"

%ignore " "

grammars/chat/gigachat-v3.lark

Tool call format: <|message_sep|>\n\nfunction call<|role_sep|>\n{"name":"NAME","arguments":{json}}

%llguidance {}

start: content tool_call
content: /([^<]|<(?!\|message_sep\|))*/

tool_call: "<|message_sep|>\n\nfunction call<|role_sep|>\n" tool_body
tool_body: "{" "\"name\"" ":" "\"" func_name "\"" "," "\"arguments\"" ":" tool_args "}"
func_name: FUNC_NAME
FUNC_NAME: /[a-zA-Z_][a-zA-Z0-9_]*/
tool_args: {{TOOL_SCHEMA}}  # injected: %json {schema} per tool

%ignore ""

grammars/chat/deepseek-v3.2.lark

Tool call format: XML-like <|DSML|function_calls><|DSML|invoke name="NAME">\n<|DSML|parameter name="KEY" string="BOOL">VAL</|DSML|parameter>\n</|DSML|invoke></|DSML|function_calls>

%llguidance {}

start: think_block? content tool_calls_block
think_block: "<think>" reasoning "</think>"
reasoning: /(.|\n)*?/
content: /([^<]|<(?!|DSML|function_calls))*/

DSML: "|DSML|"
tool_calls_block: "<" DSML "function_calls>" " "* invoke+ " "* "</" DSML "function_calls>"
invoke: "<" DSML "invoke" " " "name=\"" func_name "\">\n" param* "</" DSML "invoke>"
func_name: FUNC_NAME
FUNC_NAME: /[a-zA-Z_][a-zA-Z0-9_]*/
param: "<" DSML "parameter" " " "name=\"" param_name "\"" " " "string=\"" BOOL_STR "\">" param_value "</" DSML "parameter>\n"
param_name: /[a-zA-Z_][a-zA-Z0-9_]*/
BOOL_STR: "true" | "false"
param_value: /[^<]*/

%ignore ""

grammars/chat/gpt-oss.lark

Tool call format: <|start|>assistant to=functions.NAME<|channel|>(commentary|analysis)[<|constrain|>TYPE]<|message|>{json}

%llguidance {}

start: turn* tool_turn
turn: "<|start|>assistant" channel_block
channel_block: "<|channel|>" CHANNEL_TYPE "<|message|>" content "<|end|>"
CHANNEL_TYPE: "commentary" | "analysis" | "final"
content: /([^<]|<(?!\|end\|))*/

tool_turn: "<|start|>assistant" " " "to=functions." func_name "<|channel|>" CHANNEL_TYPE constrain? "<|message|>" tool_args
func_name: FUNC_NAME
FUNC_NAME: /[a-zA-Z_][a-zA-Z0-9_]*/
constrain: " " "<|constrain|>" CONSTRAIN_TYPE
CONSTRAIN_TYPE: /[A-Za-z0-9_-]+/
tool_args: {{TOOL_SCHEMA}}  # injected: %json {schema} per tool

%ignore ""

Injection mechanism: Each grammar template has {{TOOL_SCHEMA}} replaced by C++ at runtime in common_chat_params_init_MODELNAME():

  • Lark/llguidance: replaced with a %json {<oneOf schema combining all tool parameter schemas>} expression so llguidance enforces exactly the union of valid argument shapes from the request
  • GBNF: replaced with an equivalent GBNF alternation rule encoding the JSON schemas for each tool’s parameters

The injected grammar string (not the template) is what gets passed to llama_sampler_init_llg / llama_sampler_init_grammar. The template string is only used to build the PEG parser for post-generation extraction.

This ensures that at the tool_args position in the grammar tree, llguidance masks all tokens not conforming to the declared tool schemas — so the model cannot hallucinate argument names, types, or enum values not present in the request’s tool definitions.

Part 3: Refactor model-specific init functions (chat.cpp)

Each common_chat_params_init_MODELNAME() function:

  • Removes the inline build_chat_peg_parser([&](common_chat_peg_builder & p) {...}) call
  • Loads the corresponding grammar file (embedded as a string literal or read from grammars/chat/) and calls common_chat_load_grammar_parser() to produce data.parser
  • Sets data.grammar from the Lark grammar (with %llguidance\n prefix) or GBNF as before

Grammar files are embedded at compile time via xxd-generated headers or CMake file(READ ...) → string literal, so no runtime file I/O is needed.

Part 4: --chat-lark-grammar-file CLI flag

When provided:

  • Overrides both the sampling grammar AND the parsing grammar for all requests
  • Unless the request provides its own grammar via response_format

Files to modify for Part 4:

llama.cpp/common/common.h: Add to common_params:

std::string chat_lark_grammar;  // content of --chat-lark-grammar-file
std::string chat_gbnf_grammar;  // content of --chat-gbnf-grammar-file

llama.cpp/common/arg.cpp (~line 1853): Add both flags:

llama.cpp/common/arg.cpp — add after --chat-lark-grammar-file:

add_opt(common_arg(
    {"--chat-gbnf-grammar-file"}, "FNAME",
    "GBNF grammar file to replace the dynamic GBNF grammar generated at runtime by the chat "
    "template handler. Applied to all requests unless the request specifies a custom grammar.",
    [](common_params & params, const std::string & value) {
        params.chat_gbnf_grammar = read_file(value);
    }
));

Server options struct: Add chat_lark_grammar and chat_gbnf_grammar fields

llama.cpp/tools/server/server-common.cpp — grammar assembly (~lines 1119-1139):

// Priority: request grammar > CLI Lark > CLI GBNF
const std::string effective_grammar = !inputs.grammar.empty()       ? inputs.grammar
                                    : !opt.chat_lark_grammar.empty() ? opt.chat_lark_grammar
                                    :                                   opt.chat_gbnf_grammar;

if (!effective_grammar.empty() && !chat_params.grammar.empty()) {
    // CLI grammar overrides the template-generated GBNF for tool calls.
    // grammar_type=tool_calls → COMMON_GRAMMAR_TYPE_TOOL_CALLS → prefill enabled.
    // llguidance path in sampling.cpp bypasses lazy triggers, so disable them.
    llama_params["grammar"]          = effective_grammar;
    llama_params["grammar_type"]     = std::string("tool_calls");
    llama_params["grammar_lazy"]     = false;
    llama_params["grammar_triggers"] = json::array();
} else if (!chat_params.grammar.empty()) {
    // Normal GBNF tool-call path (unchanged).
    llama_params["grammar"]      = chat_params.grammar;
    llama_params["grammar_type"] = std::string("tool_calls");
    llama_params["grammar_lazy"] = chat_params.grammar_lazy;
    auto grammar_triggers        = json::array();
    for (const auto & trigger : chat_params.grammar_triggers) {
        server_grammar_trigger ct(trigger);
        grammar_triggers.push_back(ct.to_json());
    }
    llama_params["grammar_triggers"] = grammar_triggers;
} else if (!effective_grammar.empty()) {
    // No tools: grammar override (request or CLI). No grammar_type → USER type, no prefill.
    llama_params["grammar"]          = effective_grammar;
    llama_params["grammar_lazy"]     = false;
    llama_params["grammar_triggers"] = json::array();
} else {
    llama_params["grammar_lazy"]     = false;
    llama_params["grammar_triggers"] = json::array();
}

// Pass CLI grammar for post-gen parsing override (only when tool call path active)
if ((!opt.chat_lark_grammar.empty() || !opt.chat_gbnf_grammar.empty()) && !chat_params.grammar.empty()) {
    llama_params["chat_override_grammar"] = effective_grammar;
}

llama.cpp/common/chat.h: Add override_grammar to common_chat_parser_params:

struct common_chat_parser_params {
    // ... existing fields ...
    std::string override_grammar;  // CLI grammar override (Lark or GBNF); used instead of serialized parser
};

llama.cpp/tools/server/server-task.cpp (~line 432): Consume chat_override_grammar:

if (data.contains("chat_override_grammar")) {
    params.chat_parser_params.override_grammar = data.at("chat_override_grammar").get<std::string>();
}

llama.cpp/common/chat.cpp — common_chat_parse():

common_chat_msg common_chat_parse(const std::string & input, bool is_partial,
                                  const common_chat_parser_params & params) {
    if (!params.override_grammar.empty()) {
        // Dynamically translate CLI grammar (Lark or GBNF) to PEG parser
        auto override_parser = common_chat_load_grammar_parser(params.override_grammar);
        return common_chat_peg_parse(override_parser, input, is_partial, params);
    }
    return common_chat_peg_parse(params.parser, input, is_partial, params);
}

Part 5: Bug fix — no-tools + response_format grammar

Grammar from response_format.lark_grammar/gbnf_grammar currently lost when no tools. Fixed in the grammar assembly block above (the else if (!effective_grammar.empty()) branch).

What is NOT changing

  • Error thrown when request has tools + custom grammar in response_format
  • parse_tool_calls logic
  • common_chat_peg_parse() and common_chat_peg_mapper internals
  • --grammar and --grammar-file flags
  • JSON schema handling

Files to read before implementing

  • llama.cpp/common/chat.cpp lines 825-1800 (all model init functions)
  • llama.cpp/common/peg-parser.h — common_peg_parser_builder full API
  • llama.cpp/common/chat-peg-parser.h — common_chat_peg_mapper
  • llama.cpp/common/chat-peg-parser.cpp lines 875-1007 — gemma4-specific mapper (to understand what the grammar must encode)
  • llama.cpp/tools/server/server-common.cpp lines 1038-1150
  • llama.cpp/common/arg.cpp lines 1841-1880
  • llama.cpp/tools/server/server-task.cpp lines 415-435
  • Server options struct (grep for use_jinja field)

Verification

  1. Build with -DLLAMA_LLGUIDANCE=ON -DGGML_VULKAN=ON
  2. Each model’s existing behavior preserved (grammar files produce identical parse results to removed C++ builders)
  3. CLI Lark + tools: --chat-lark-grammar-file gemma4-tool-call.lark → llguidance sampling + dynamic Lark→PEG parser for extraction
    3b. CLI GBNF + tools: --chat-gbnf-grammar-file gemma4.gbnf → GBNF sampling + dynamic GBNF→PEG parser for extraction
  4. No tools + request lark_grammar: grammar active, prompt formatted normally
  5. No tools + request gbnf_grammar: grammar active
  6. Tools only (no CLI grammar): uses grammar file embedded at compile time → identical behavior to current
  7. Tools + request grammar: error as before

Part 6: Auto-detection of model kind

Each common_chat_params_init_MODELNAME() already knows the model kind. In Part 3 refactor:

  • When LLAMA_LLGUIDANCE compiled in: load the .lark embedded string → pass to llama_sampler_init_llg + Lark→PEG transpiler for data.parser
  • When LLAMA_LLGUIDANCE not compiled in: load the .gbnf embedded string → pass to llama_sampler_init_grammar + GBNF→PEG transpiler for data.parser
  • No runtime file I/O: grammar strings are embedded in C++ translation unit via CMake configure_file or raw string literals

Detection macro pattern:

#ifdef LLAMA_LLGUIDANCE
    data.grammar = kGemma4LarkGrammar;  // std::string_view from embedded header
    data.parser  = common_lark_to_peg(data.grammar);
#else
    data.grammar = kGemma4GbnfGrammar;
    data.parser  = common_gbnf_to_peg(data.grammar);
#endif

Part 7: Grammar file embedding + CMake install

Grammar files live in grammars/chat/ (model-named, e.g. gemma4.lark, gemma4.gbnf).

Embedding: CMake reads each file at configure time and generates a header with C string literals:

# In common/CMakeLists.txt
file(READ ${PROJECT_SOURCE_DIR}/grammars/chat/gemma4.lark GEMMA4_LARK_CONTENT)
configure_file(chat-grammars.h.in chat-grammars.h @ONLY)

chat-grammars.h.in declares:

static constexpr std::string_view kGemma4LarkGrammar = R"(@GEMMA4_LARK_CONTENT@)";
// ... one entry per model per format

Install: Grammar files installed for distro packaging:

install(DIRECTORY ${PROJECT_SOURCE_DIR}/grammars/
        DESTINATION share/llama.cpp/grammars)

Part 8: Testing

Unit tests (add to tests/test-chat-peg-parser.cpp)

Follow the existing testing framework pattern (see test_example_native, test_tagged_peg_parser).

New test functions to add:

  • test_lark_to_peg_transpiler() — verifies basic Lark rule/sequence/choice/repetition/regex translation produces valid common_peg_arena
  • test_gbnf_to_peg_transpiler() — same for GBNF
  • For each model grammar file:
    • test_grammar_gemma4() — parse sample Gemma4 tool-call output through transpiled PEG, verify tool_calls[0].name / arguments
    • test_grammar_ministral_3(), test_grammar_gpt_oss(), test_grammar_functionary_v3_2(), test_grammar_kimi_k2(), test_grammar_lfm2(), test_grammar_lfm2_5(), test_grammar_gigachat_v3(), test_grammar_deepseek_v3_2()

Each model test uses create_tools() (or similar) + a fixed sample model output string → calls common_chat_load_grammar_parser() → calls common_chat_peg_parse() → asserts tool name + arguments match expected JSON.

Integration tests

Add to tests/test-chat-auto-parser.cpp or new tests/test-chat-grammar-files.cpp:

  • For each model: run through common_chat_params_init_MODELNAME() with sample tools, verify the grammar string is non-empty, verify the PEG parser round-trips a sample output

CMakeLists.txt for tests

llama_build_and_test(test-chat-grammar-files.cpp peg-parser/simple-tokenize.cpp)

Implementation order

  1. Write Lark→PEG and GBNF→PEG transpilers
  2. Write grammar files for each model (derive from existing C++ builder logic)
  3. CMake embedding: generate chat-grammars.h from grammar files; add install(DIRECTORY ...) rule
  4. Refactor each common_chat_params_init_MODELNAME to use grammar files + auto-detect llguidance
  5. Add --chat-lark-grammar-file and --chat-gbnf-grammar-file flags + server wiring
  6. Fix no-tools grammar bug
  7. Write unit + integration tests for all model grammars
1 Like

By replacing all hardcoded model-specific PEG parsers I hope to rid the existing llama.cpp codebase of human implementation error in the model output parsers, as they are currently a giant mess of unmaintainable code that no sane person can comprehend.

1 Like

Yeah I hear you, to be clear I knew I was a bit off topic, that’s just how opencode natively is writing code from the model it’s a bit of a mess, not an architecture I’d advocate for. Right now I’m just trying to get the baseline functionality working well enough with a Qwen 3 Coder variant before trying to get it to play with Gemma, but I’ll post if I have anything useful in that vain, this doc is super helpful!

2 Likes

This is why my research loops are using PI and not open code. Full transcript in terminal plus a very simple harness equals easier and faster updates across different models in testing.

To test other harnesses I had to develop a proxy to capture every single call it sends to the backend before I could start to unravel what is going on under the hood.

I would avoid Open Code its a monster of a project. Hey if you want to PR a fork and get noticed that is the place to do it… but its not really a good play ground for this stuff.

1 Like
Next iterative Claude Code prompt engineered ™️ Plan (click to uncollapse)

Plan: per-format chat pipeline (FSM tracker → decoder → transformer → presenter)

Naming and responsibility split

The current code conflates several responsibilities into a single common_chat_peg_mapper::map() method. The refactor splits them into a four-stage per-format pipeline:

  1. common_chat_format_tracker (FSM state) — Knows the current conversation state from what the model has emitted. Drives the PEG parser’s expectations (expected_productions() → tighter next_sequence_delimiters) and mirrors llguidance’s internal grammar state. Does NOT emit anything; pure state-keeping. Per format.

  2. common_chat_format_decoder (wire-format extraction) — Reads AST nodes and produces typed, format-specific intermediate values: raw tool name, raw tool id, raw arg key/value pairs, raw reasoning text, raw content text. Knows the model’s wire format (DSML <param> tags, Python name(k=v), JSON {"k":v}, Kimi functions.NAME:IDX, Gemma’s <|"|>-delimited dict, etc.) and emits a stream of decoded_event structs. Per format.

  3. common_chat_format_transformer (model-specific shaping) — Consumes decoded_events from the decoder and applies model-specific transforms to reasoning, content, and tool-call fields. Transformer responsibilities:

    • Per-format reasoning shaping: stripping markers, normalizing whitespace, picking which channel becomes reasoning vs content (e.g. GPT-OSS analysis → reasoning, commentary → content), concatenating multiple reasoning blocks per family rules.
    • Per-format content shaping: stripping leftover chat-template tokens (e.g. Kimi <|im_assistant|>assistant<|im_middle|> prefix that leaks into raw output), trimming, normalizing newlines.
    • Per-format tool-call shaping: assembling TOOL_ARG_KV events into a JSON args string (Python/DSML formats), JSON-pass-through for TOOL_ARGS_RAW (Kimi/Hermes/etc.), parsing tool-id functions.NAME:IDX into (name, id).

    Output is a stream of shaped_events — same shape as decoded_event but cleaned/normalized per format. Per format.

  4. common_chat_format_presenter (API-shape assembly → common_chat_msg) — Format-agnostic. Consumes shaped_events and writes them into the OpenAI-compatible common_chat_msg: .role, .content, .reasoning_content, .tool_calls[], .tool_call_id, etc. Cross-cutting concerns live here:

    • Discarding whitespace-only reasoning content
    • Ensuring tool calls have all required fields
    • Maintaining streaming monotonicity invariants
    • Default role=“assistant” assignment

    One shared implementation; per-format presenters exist only if a model needs message-shape-level idiosyncrasies (which is rare).

The pipeline runs node-by-node during the AST walk. All four layers operate in lock-step with the tracker’s FSM state. The tracker advances first; then each downstream layer reads the now-current state at its own step. State changes affect interpretation at every layer:

AST node N
   ├─> tracker.advance(N)                          // update FSM state -> S
   │
   ├─> events = decoder.decode(N)                  // reads S to interpret the node
   │     // e.g. a `<` token in S=IN_CONTENT is a content char;
   │     // in S=IN_TOOL_OPEN it's the start of a tool tag
   │
   ├─> for each event in events:
   │     shaped = transformer.shape(event)         // reads S to shape the event
   │       // e.g. CONTENT_TEXT in S=IN_CONTENT lands as content;
   │       //      CONTENT_TEXT in S=IN_REASONING (channel-overloaded format)
   │       //      could be re-routed to reasoning instead
   │
   └─> for each shaped event in shaped:
         presenter.present(shaped)                 // reads S to land in common_chat_msg
           // e.g. TOOL_NAME in S=IN_TOOL_NAME starts a new tool call;
           //      TOOL_NAME in S=IN_TOOL_CALL (already had a name) is a no-op

The lock-step property is invariant: the decoder, transformer, and presenter MUST consult tracker.current_state() at every step. They never assume state — they observe it. This way:

  • The decoder never has to maintain duplicate state to know “am I inside a tool call?” — it just asks the tracker.
  • The transformer never has to maintain duplicate state to know “is this fragment reasoning or content?” — same.
  • The presenter never has to maintain duplicate state to know “is this a new tool call or a continuation?” — same.

The tracker is the single source of truth. The other three layers are stateless w.r.t. conversation position; any state they keep (e.g. transformer buffering KV events for args assembly) is local to a single state-bracketed span and reset on state transitions the tracker reports.

Per-format pieces live together:

Old name New name Role
common_chat_peg_mapper (legacy) split into 4 base classes (below) replaced
state enum common_chat_format_state tracker FSM states
parser-side read-only iface common_chat_format_state_view parser/decoder see only this
tracker base common_chat_format_tracker abstract, per-format subclass
decoder base common_chat_format_decoder abstract, per-format subclass
transformer base common_chat_format_transformer abstract, per-format subclass
presenter base common_chat_format_presenter concrete default; per-format subclass only if needed
family base for JSON-tagged decoders common_chat_json_tagged_decoder shared family base
family base for JSON-tagged transformers common_chat_json_tagged_transformer shared family base
per-format quartet common_chat_<family>_tracker + _decoder + _transformer (and optionally _presenter) up to four per family, in one *-format.{h,cpp} file
directory common/chat-formats/ houses all four layers
FSM transition method advance(const common_peg_ast_node&) (tracker)
Decoder per-node method decode(const common_peg_ast_node&) returns std::vector<decoded_event>
Transformer per-event method shape(decoded_event) returns std::vector<shaped_event> applies model-specific transforms
Presenter per-event method present(const shaped_event&) writes to common_chat_msg
Top-level coordinator common_chat_format_pipeline::run(arena, result) walks AST, invokes all four layers in order
Decoded events type common_chat_decoded_event (variant of tool_open/tool_close/arg_kv/reasoning_text/content_text/tool_id/tool_name) typed wire-shape output
Shaped events type common_chat_shaped_event (same variants as decoded but post-transform; e.g. args_json instead of arg_kv) typed model-shape output
make_mapper lambda in chat.cpp make_format_pipeline(params.format, msg) dispatcher

common_chat_peg_builder and the PEG runtime types are unchanged: they are the parsing machinery the tracker observes and the decoder reads.

Context

common/chat-peg-parser.cpp has accumulated format-specific hacks in a single 280-line common_chat_peg_mapper::map() method: a phantom-tool-open guard for streaming, a nested-tool-open extent check for LFM2’s ( opener, DSML branches handling DeepSeek’s <param> rule names, name-before-open recovery, JSON brace synthesis on is_tool_close, and quote synthesis on is_arg_value. Adding any new format means adding more branches.

The user’s intent — clarified: each model family gets a per-format pipeline of four cooperating layers that operate in lock-step with a Finite State Machine tracking the current conversation state (IN_REASONING, IN_TOOL_CALL, IN_TOOL_ARGS, IN_TOOL_CLOSE, IN_CONTENT, etc.) determined by what the model has emitted so far:

  1. Tracker (FSM) — pure state. Consumes AST nodes via advance(node). Drives the PEG parser’s expectations (expected_productions() → tighter next_sequence_delimiters). Mirrors llguidance’s internal Lark-grammar state, so when the tracker says IN_TOOL_ARGS, llguidance is also at the tool-args rule and constraining tokens accordingly.
  2. Decoder — extracts wire-format-specific values (tool name, id, args, KV pairs, reasoning text, content text) from AST nodes as typed decoded_events. Reads tracker state to interpret nodes.
  3. Transformer — applies model-specific shaping to events (content prefix stripping, reasoning channel routing, tool-args JSON construction). Reads tracker state.
  4. Presenter — projects shaped events onto common_chat_msg. Reads tracker state. One default implementation covers all formats.

This is a bidirectional contract: model output advances the tracker FSM; the FSM constrains future model output (via llguidance and the parser) and instructs the downstream three layers how to interpret each AST node. The tracker is the single source of truth for “where in the conversation are we”; the other three layers are stateless w.r.t. conversation position and consult the tracker at every step.

Today, the parser and llguidance are independently driven only by the grammar string. The legacy common_chat_peg_mapper mixes state-keeping, wire-shape extraction, format-specific shaping, and common_chat_msg projection in a single map() method. The refactor splits these into the four-layer per-format pipeline.

Hard policies (carried over):

  • Closing tokens MUST stay required in grammars.
  • The decoder and presenter MUST NOT synthesize any character the model didn’t emit. The transformer MAY synthesize structural JSON characters ({, }, ,, :) only when it has to convert non-JSON wire shapes (Python name(k=v), DSML <param>) into the JSON arguments string the API requires — and that is confined to per-format transformer subclasses with explicit “scoped exception” comments.

Today: 16/19 templates pass. Failing: Gemma-4 (grammar mismatches the real Gemma 4 spec at https://ai.google.dev/gemma/docs/core/prompt-formatting-gemma4), Qwen3-Coder (no grammar file), GLM-4.7-Flash (no grammar file). The refactor finishes them with their own pipelines.

Outcome

  • Each model family has a dedicated four-layer pipeline (tracker + decoder + transformer + presenter) in common/chat-formats/ and a per-format COMMON_CHAT_FORMAT_PEG_* enum value.
  • All four layers operate in lock-step with the tracker FSM state. The tracker is the single source of truth; the other three layers are stateless w.r.t. conversation position and consult tracker.current_state() at every step.
  • The tracker is the explicit authority on conversation state, exposing current_state(), expected_productions(), and advance(node).
  • The decoder produces typed common_chat_decoded_events from the AST per format wire shape.
  • The transformer applies model-specific shaping (content prefix stripping, reasoning channel routing, tool-args JSON construction) and emits common_chat_shaped_events.
  • The presenter writes shaped events into common_chat_msg (default impl handles all formats; per-format overrides are rare).
  • llguidance is informed of state transitions via the same per-format grammar (no API change: it already tracks state internally from the Lark grammar). The per-format Lark grammar must encode all reachable FSM states; the tracker mirrors that structure 1:1.
  • The legacy common_chat_peg_mapper and common_chat_peg_gemma4_mapper are deleted at step 7.
  • All 19 templates in tests/test-chat.cpp pass, including Gemma-4 (with corrected grammar), Qwen3-Coder, and GLM-4.7-Flash.
  • The only character-synthesis remaining is the deliberate {/} and , for assembling TOOL_ARG_KV events into TOOL_ARGS_JSON in the transformer layer of formats whose wire shape isn’t JSON (DSML, lfm2, qwen3-coder, glm-4-7-flash). This is scoped, documented, and called out as the unavoidable shape conversion.

Architecture

Directory layout

One header+source pair per family declares the per-family tracker, decoder, and transformer (and a factory). The three layers always travel together for a format.

common/chat-formats/
  decoded-event.h                         # struct common_chat_decoded_event + kind enum
  format-tracker.{h,cpp}                  # abstract base tracker + state enum + state_view iface
  format-decoder.{h,cpp}                  # abstract base decoder
  format-transformer.{h,cpp}              # default transformer (event -> common_chat_msg)
  format-pipeline.{h,cpp}                 # coordinator: walk AST, run all three layers
  json-tagged-format.{h,cpp}              # shared family bases for JSON-tagged formats
  gemma4-format.{h,cpp}                   # rewritten for the real Gemma 4 spec
  deepseek-v3-2-format.{h,cpp}            # DSML <param name="k" string="bool">v</param>
  kimi-k2-format.{h,cpp}                  # JSON-tagged + functions.NAME:IDX id parse
  ministral-3-format.{h,cpp}              # pure JSON-tagged
  gpt-oss-format.{h,cpp}                  # JSON-tagged + channel handling
  functionary-v3-2-format.{h,cpp}         # JSON-tagged + ">>>recipient" -> name
  gigachat-v3-format.{h,cpp}              # pure JSON-tagged
  lfm2-format.{h,cpp}                     # python-style name(k=v)
  lfm2-5-format.{h,cpp}                   # subclass of lfm2-format, no wrapper
  qwen3-coder-format.{h,cpp}              # NEW: <function=name><parameter=k>v</parameter>
  glm-4-7-flash-format.{h,cpp}            # NEW: <tool_call>name<arg_key>k</arg_key><arg_value>v</arg_value>
  hermes-format.{h,cpp}                   # JSON-tagged (Nous Hermes)
  granite-format.{h,cpp}                  # JSON-tagged (IBM Granite 3.3 / 4.0)
  nemotron-format.{h,cpp}                 # JSON-tagged (NVIDIA Nemotron)
  cohere-c4ai-format.{h,cpp}              # action-tagged: <|START_ACTION|>[{...}]<|END_ACTION|>
  seed-oss-format.{h,cpp}                 # XML-tagged (ByteDance Seed-OSS)
  qwq-format.{h,cpp}                      # JSON-tagged (Qwen-QwQ-32B)
  qwen3-5-format.{h,cpp}                  # XML-tagged (Qwen3.5)
  glm-4-6-format.{h,cpp}                  # XML-tagged (GLM-4.6)

Each *-format.{h,cpp} exports the per-family tracker, decoder, and (when needed) transformer subclasses, plus a factory common_chat_<NAME>_make_pipeline(msg) returning a fully-wired common_chat_format_pipeline.

Abstract base APIs

common/chat-formats/decoded-event.h

The intermediate “decoded event” type passed from the decoder to the transformer. A typed enumeration of the wire-format-independent things a model can say. New variants are added centrally; per-format decoders pick the subset they emit.

struct common_chat_decoded_event {
    enum class kind {
        REASONING_TEXT,   // text fragment to append to .reasoning_content
        CONTENT_TEXT,     // text fragment to append to .content
        TOOL_OPEN,        // begin a new tool call
        TOOL_NAME,        // function name (full string; partial frags suppressed by decoder)
        TOOL_ID,          // tool call id (Kimi-style)
        TOOL_ARGS_RAW,    // pre-formed JSON args text (model emitted JSON directly)
        TOOL_ARG_KV,      // a single (key, value, is_string) pair (formats that emit per-arg KV)
        TOOL_CLOSE,       // end of tool call
    };
    kind k;
    std::string text;       // for *_TEXT, TOOL_NAME, TOOL_ID, TOOL_ARGS_RAW
    std::string key;        // for TOOL_ARG_KV
    std::string value;      // for TOOL_ARG_KV (raw model bytes; transformer JSON-stringifies)
    bool        is_string;  // for TOOL_ARG_KV (true => quote+escape; false => emit verbatim as JSON value)
    bool        is_partial; // event flagged as partial; transformer may choose to suppress
};

common/chat-formats/format-tracker.h

The tracker base owns the FSM enum, transition contract, and the read-only state view interface. It does NOT touch common_chat_msg and does NOT emit decoded events.

// Universal "where are we in the conversation" states. Each per-format FSM
// uses a SUBSET of these — e.g. DSML has IN_TOOL_PARAM that JSON-tagged formats
// don't. New states are added here as needed; per-format FSMs declare which
// they actually use.
enum class common_chat_format_state : uint8_t {
    INITIAL,         // nothing emitted yet
    IN_CONTENT,      // free-form assistant content
    IN_REASONING,    // inside <think>/<channel|>thought/etc.
    IN_TOOL_CALL,    // inside a tool call envelope (after open, before close)
    IN_TOOL_NAME,    // currently emitting the function name
    IN_TOOL_ID,      // currently emitting the tool-call id (Kimi-style)
    IN_TOOL_ARGS,    // inside the args region (json or per-format)
    IN_TOOL_ARG_KEY, // tagged-args formats: between arg-name open and close
    IN_TOOL_ARG_VAL, // tagged-args formats: between arg-value open and close
    IN_TOOL_PARAM,   // DSML <param>...</param>
    DONE,            // tool-call closed; back at top-level
};

// Read-only window into a tracker's FSM, exposed to the PEG parser context AND
// to the transformer so neither needs to include the tracker's full type.
class common_chat_format_state_view {
  public:
    virtual ~common_chat_format_state_view() = default;
    virtual common_chat_format_state current_state() const = 0;
    virtual std::vector<std::string>  expected_productions() const = 0;
};

class common_chat_format_tracker : public common_chat_format_state_view {
  public:
    virtual ~common_chat_format_tracker() = default;

    // Single transition entry-point. Concrete trackers MUST update `state_`
    // per their declared FSM. NO side effects elsewhere — the tracker is
    // pure state. It may inspect node.tag/node.rule/node.is_partial; it may
    // not write to common_chat_msg, emit events, or mutate any other layer.
    virtual void advance(const common_peg_ast_node & node) = 0;

    // common_chat_format_state_view
    common_chat_format_state current_state() const override { return state_; }
    std::vector<std::string> expected_productions() const override = 0;

  protected:
    common_chat_format_state state_ = common_chat_format_state::INITIAL;
};

common/chat-formats/format-decoder.h

The decoder base reads AST nodes (in lock-step with the tracker) and emits typed common_chat_decoded_events. It is the only layer that knows the format’s wire shape. It does NOT touch common_chat_msg. It MUST consult the tracker’s current state on every call to interpret the node correctly.

class common_chat_format_decoder {
  public:
    explicit common_chat_format_decoder(const common_chat_format_state_view & state)
        : state_(state) {}
    virtual ~common_chat_format_decoder() = default;

    // Per-node decode step. Returns zero or more decoded events. The decoder
    // MUST read state_.current_state() to interpret the node correctly (e.g.
    // a `<` token means different things in IN_CONTENT vs IN_TOOL_CALL).
    // The decoder MUST NOT mutate tracker state.
    virtual std::vector<common_chat_decoded_event>
        decode(const common_peg_ast_node & node) = 0;

  protected:
    const common_chat_format_state_view & state_;
};

Concrete decoders are the bulk of per-format work. Examples:

  • common_chat_json_tagged_decoder: emits TOOL_OPEN on tag tool-open, TOOL_NAME on complete tag tool-name, TOOL_ARGS_RAW on complete tag tool-args, TOOL_CLOSE on tag tool-close.
  • common_chat_lfm2_decoder: emits TOOL_OPEN, TOOL_NAME, then TOOL_ARG_KV{key, value, is_string=…} per <tag tool-arg-name, tag tool-arg-value> pair, then TOOL_CLOSE.
  • common_chat_deepseek_v3_2_decoder: emits TOOL_OPEN, TOOL_NAME (from name="…" attr), then TOOL_ARG_KV per <param> (using bool-str rule for is_string), TOOL_CLOSE.
  • common_chat_gemma4_decoder: walks the gemma4_dict AST recursively, emits TOOL_OPEN, TOOL_NAME, TOOL_ARGS_RAW (built from gemma4_to_json() over the dict subtree), TOOL_CLOSE.

common/chat-formats/format-transformer.h

The transformer base consumes common_chat_decoded_events and emits common_chat_shaped_events. It applies model-specific transforms — content prefix stripping, reasoning channel routing, tool-args JSON construction. It does NOT touch common_chat_msg.

struct common_chat_shaped_event {
    enum class kind {
        REASONING_TEXT,
        CONTENT_TEXT,
        TOOL_OPEN,
        TOOL_NAME,
        TOOL_ID,
        TOOL_ARGS_JSON,   // always JSON-string form, regardless of source format
        TOOL_CLOSE,
    };
    kind k;
    std::string text;
    bool is_partial = false;
};

class common_chat_format_transformer {
  public:
    explicit common_chat_format_transformer(const common_chat_format_state_view & state)
        : state_(state) {}
    virtual ~common_chat_format_transformer() = default;

    // Per-event shaping. Receives one decoded event; emits zero or more
    // shaped events. MUST consult state_.current_state() to know how to
    // interpret the event (e.g. a CONTENT_TEXT in IN_REASONING for a
    // channel-overloaded format may need to be re-routed). Subclasses may
    // buffer state across calls (e.g. accumulate TOOL_ARG_KV events until
    // TOOL_CLOSE and emit a single TOOL_ARGS_JSON).
    virtual std::vector<common_chat_shaped_event>
        shape(const common_chat_decoded_event & event) = 0;

    // Optional final flush (e.g. emit any buffered events when AST walk ends).
    virtual std::vector<common_chat_shaped_event> on_finalize() { return {}; }

  protected:
    const common_chat_format_state_view & state_;
};

The transformer is the per-format layer for cleaning up reasoning, content, and tool args. Examples:

  • kimi-k2 transformer: passes most events through verbatim; strips <|im_assistant|>assistant<|im_middle|> prefix from CONTENT_TEXT events.
  • gpt-oss transformer: routes analysis channel REASONING_TEXT to REASONING_TEXT, routes commentary channel content to CONTENT_TEXT (assignment depends on tracker state).
  • lfm2 transformer: buffers TOOL_ARG_KV events until TOOL_CLOSE; on close, emits a single TOOL_ARGS_JSON containing the JSON-stringified args (this is where the { / } synthesis is scoped — the only place it ever appears, and only for non-JSON-args formats).
  • deepseek-v3-2 transformer: same KV-buffering pattern as lfm2.
  • json-tagged transformers: passes TOOL_ARGS_RAW through as TOOL_ARGS_JSON verbatim, no synthesis.

common/chat-formats/format-presenter.h

The presenter base consumes common_chat_shaped_events and writes to common_chat_msg. One shared implementation handles the OpenAI-compatible message shape for all formats. Per-format presenters exist only if a model needs message-shape-level peculiarities (rare).

class common_chat_format_presenter {
  public:
    common_chat_msg & result;
    bool is_partial_parse = false;
    explicit common_chat_format_presenter(common_chat_msg & m,
                                          const common_chat_format_state_view & state)
        : result(m), state_(state) {}
    virtual ~common_chat_format_presenter() = default;

    // Per-event projection into common_chat_msg. MUST consult
    // state_.current_state() to disambiguate (e.g. TOOL_NAME in IN_TOOL_NAME
    // starts a new pending call; TOOL_NAME in IN_TOOL_CALL/already-named is a
    // no-op). The default implementation covers all formats:
    //   REASONING_TEXT  -> append to result.reasoning_content
    //   CONTENT_TEXT    -> append to result.content
    //   TOOL_OPEN       -> push a new pending common_chat_tool_call
    //   TOOL_NAME       -> set pending tool .name
    //   TOOL_ID         -> set pending tool .id
    //   TOOL_ARGS_JSON  -> set pending tool .arguments (verbatim, no synthesis)
    //   TOOL_CLOSE      -> commit pending tool to result.tool_calls
    virtual void present(const common_chat_shaped_event & event);

    // Final cross-cutting cleanups:
    //   - Discard whitespace-only reasoning_content
    //   - Default role="assistant"
    virtual void on_finalize();

  protected:
    const common_chat_format_state_view & state_;
};

Pipeline coordinator (common/chat-formats/format-pipeline.h)

struct common_chat_format_pipeline {
    std::unique_ptr<common_chat_format_tracker>     tracker;
    std::unique_ptr<common_chat_format_decoder>     decoder;
    std::unique_ptr<common_chat_format_transformer> transformer;
    std::unique_ptr<common_chat_format_presenter>   presenter;

    // Walk the AST. For each node:
    //   tracker.advance(node)
    //   for each event in decoder.decode(node):
    //     for each shaped in transformer.shape(event):
    //       presenter.present(shaped)
    // Final: flush transformer.on_finalize() through presenter, then
    // presenter.on_finalize().
    void run(const common_peg_ast_arena&, const common_peg_parse_result&);
};

common_chat_format_pipeline common_chat_make_format_pipeline(
    common_chat_format format, common_chat_msg & msg);

The dispatcher in chat.cpp builds the pipeline once per parse. The four layers are constructed wired together: the decoder gets a non-owning pointer to the tracker’s state_view; the transformer and presenter are independent.

FSM-to-grammar contract (documented in format-tracker.h):

  • Every common_chat_format_state reachable in a per-format FSM MUST correspond to a named rule (or set of rules) in the per-format Lark grammar.
  • expected_productions() MUST return the names of those rules. The PEG parser uses them to bound speculative matching; the llguidance setup verifies they’re declared.
  • llguidance does not need direct hooks: by virtue of mirroring the grammar exactly, it’s already in the matching state internally. The tracker is the C++ mirror of llguidance’s internal state, observable for both parser and transformer.

Per-format pipelines

Each per-format pipeline declares its (tracker FSM, decoder events, transformer shapes). State transitions and events are decoupled: the tracker only updates state; the decoder reads state and emits events; the transformer reshapes events.

json_tagged family base (Kimi, Ministral, Functionary, GigaChat, Hermes, Granite, QwQ, Nemotron, Seed-OSS, Cohere c4ai, Qwen3.5, GLM-4.6 — most JSON-args formats)

Tracker FSM (states used: INITIAL, IN_CONTENT, IN_REASONING, IN_TOOL_CALL, IN_TOOL_NAME, IN_TOOL_ID, IN_TOOL_ARGS, DONE):

INITIAL/DONE   --tag tool-open(complete, has tool-name child)--> IN_TOOL_CALL
IN_TOOL_CALL   --tag tool-id(complete)-->                        IN_TOOL_ID
IN_TOOL_ID     --tag tool-name(complete)-->                      IN_TOOL_NAME
IN_TOOL_CALL   --tag tool-name(complete)-->                      IN_TOOL_NAME
IN_TOOL_NAME   --tag tool-args(complete)-->                      IN_TOOL_ARGS
IN_TOOL_ARGS   --tag tool-close-->                               DONE

expected_productions():

  • INITIAL/IN_CONTENT → ["content", "reasoning", "tool-open"]
  • IN_TOOL_CALL → ["tool-id", "tool-name"]
  • IN_TOOL_ID → ["tool-name"]
  • IN_TOOL_NAME → ["tool-args"]
  • IN_TOOL_ARGS → ["tool-close"]
  • DONE → ["tool-open", "content"]

Decoder emits, depending on tracker state at decode time:

  • tag reasoning → REASONING_TEXT{node.text}
  • tag content → CONTENT_TEXT{node.text}
  • tag tool-open (complete, has tool-name) → TOOL_OPEN{}
  • tag tool-id (complete) → TOOL_ID{trim(node.text)}
  • tag tool-name (complete) → TOOL_NAME{trim(node.text)}
  • tag tool-args (complete) → TOOL_ARGS_RAW{node.text} // raw model-emitted JSON
  • tag tool-close → TOOL_CLOSE{}
  • Phantom partial tag tool-open (no tool-name child): nothing emitted.

Transformer (default for json_tagged family): passes events through unchanged. TOOL_ARGS_RAW becomes TOOL_ARGS_JSON verbatim — no synthesis. Per-format subclasses can override:

  • kimi-k2 transformer: when TOOL_ID{text} arrives, parses functions.NAME:IDX, emits TOOL_NAME{NAME} followed by TOOL_ID{IDX}.
  • gpt-oss transformer: re-routes CONTENT_TEXT events to REASONING_TEXT if state is IN_REASONING (channel=analysis); other channels pass through.
  • functionary-v3-2 transformer: maps recipient text to TOOL_NAME.

Presenter: shared default. No format-specific overrides for these.

gemma4 (per the official spec at https://ai.google.dev/gemma/docs/core/prompt-formatting-gemma4)

Rewritten grammar; tokens <|turn>/<turn|>, <|channel>thought/<channel|>, <|tool_call>call:NAME{K:<|"|>V<|"|>,...}<tool_call|>.

Tracker FSM: INITIAL, IN_CONTENT, IN_REASONING, IN_TOOL_CALL, IN_TOOL_NAME, IN_TOOL_ARGS, DONE.

Decoder: walks the gemma4_dict subtree (using the existing gemma4_to_json() logic, moved into the decoder), emits TOOL_OPEN/TOOL_NAME/TOOL_ARGS_RAW/TOOL_CLOSE. Reasoning + content as in json_tagged.

Transformer: pass-through (gemma’s args are already JSON-shape after gemma4_to_json()).

Presenter: shared default.

deepseek_v3_2 (DSML XML params)

Tracker FSM: INITIAL, IN_CONTENT, IN_REASONING, IN_TOOL_CALL, IN_TOOL_NAME, IN_TOOL_PARAM, DONE.

INITIAL        --tag tool-open(<func_calls>)--> IN_TOOL_CALL
IN_TOOL_CALL   --rule invoke (start)-->         IN_TOOL_NAME
IN_TOOL_NAME   --rule param (start)-->          IN_TOOL_PARAM
IN_TOOL_PARAM  --rule param-name-->             IN_TOOL_PARAM
IN_TOOL_PARAM  --rule bool-str-->               IN_TOOL_PARAM
IN_TOOL_PARAM  --rule param-value (complete)--> IN_TOOL_NAME
IN_TOOL_NAME   --tag tool-close-->              DONE

Decoder: emits TOOL_OPEN on tag tool-open; TOOL_NAME from invoke’s name="…" attribute; TOOL_ARG_KV{key, value, is_string} per <param> block (using bool-str rule for is_string); TOOL_CLOSE.

Transformer: buffers TOOL_ARG_KV events (no immediate emit); on TOOL_CLOSE, assembles TOOL_ARGS_JSON{"k1":dump(v1),...} and emits both. The { and } here are the deliberate, scoped synthesis (DSML format has no JSON envelope) — confined to this transformer.

Presenter: shared default.

lfm2 and lfm2_5 (Python-style name(k=v))

Tracker FSM: INITIAL, IN_CONTENT, IN_REASONING, IN_TOOL_CALL, IN_TOOL_NAME, IN_TOOL_ARG_KEY, IN_TOOL_ARG_VAL, DONE.

INITIAL          --tag tool-open-->                  IN_TOOL_CALL
IN_TOOL_CALL     --tag tool-name (complete)-->       IN_TOOL_NAME
IN_TOOL_NAME     --tag tool-arg-name (complete)-->   IN_TOOL_ARG_KEY
IN_TOOL_ARG_KEY  --tag tool-arg-value (complete)-->  IN_TOOL_NAME
IN_TOOL_NAME     --tag tool-close-->                 DONE

Decoder: emits TOOL_OPEN, TOOL_NAME, then TOOL_ARG_KV{key, value, is_string} per (arg-name, arg-value) pair (is_string from grammar/value form), then TOOL_CLOSE.

Transformer: same KV-buffering and TOOL_ARGS_JSON assembly as DSML.

Presenter: shared default.

lfm2_5 reuses lfm2’s tracker/decoder/transformer entirely — only the grammar differs (no wrapper tokens).

qwen3-coder and glm-4-7-flash (XML-tagged per-arg)

Same FSM shape as lfm2 (per-arg KV collection). Decoders read <parameter=key>val</parameter> (qwen3-coder) or <arg_key>k</arg_key><arg_value>v</arg_value> (glm-4-7-flash). Transformer is the same KV→JSON assembly.

common_chat_lfm2_5_tracker — : public common_chat_lfm2_tracker, identical state machine.

common_chat_qwen3_coder_tracker — same FSM shape as common_chat_lfm2_tracker (per-arg KV collection), with IN_TOOL_NAME set from the <function=...> open and IN_TOOL_ARG_KEY/VAL from <parameter=...>...</parameter>. New grammar qwen3-coder.lark:

%llguidance {}
start: think_block? content tool_call_block?
think_block: "<think>" reasoning "</think>"
reasoning: /(.|\n)*?/
content: /(.|\n)*?/
tool_call_block: tool_call+
tool_call: "<tool_call>" /[ \t\n\r]*/ "<function=" func_name ">" /[ \t\n\r]*/ tool_arg+ /[ \t\n\r]*/ "</function>" /[ \t\n\r]*/ tool_close
tool_close: "</tool_call>"
func_name: FUNC_NAME
FUNC_NAME: /[a-zA-Z_][a-zA-Z0-9_]*/
tool_arg: "<parameter=" arg_name ">" /\n?/ arg_value /\n?/ "</parameter>" /\n?/
arg_name: /[a-zA-Z_][a-zA-Z0-9_]*/
arg_value: /(.|\n)*?/

New grammar files

grammars/chat/qwen3-coder.lark:

%llguidance {}
start: think_block? content tool_call_block?
think_block: "<think>" reasoning "</think>"
reasoning: /(.|\n)*?/
content: /(.|\n)*?/
tool_call_block: tool_call+
tool_call: "<tool_call>" /[ \t\n\r]*/ "<function=" func_name ">" /[ \t\n\r]*/ tool_arg+ /[ \t\n\r]*/ "</function>" /[ \t\n\r]*/ tool_close
tool_close: "</tool_call>"
func_name: FUNC_NAME
FUNC_NAME: /[a-zA-Z_][a-zA-Z0-9_]*/
tool_arg: "<parameter=" arg_name ">" /\n?/ arg_value /\n?/ "</parameter>" /\n?/
arg_name: /[a-zA-Z_][a-zA-Z0-9_]*/
arg_value: /(.|\n)*?/

grammars/chat/glm-4-7-flash.lark:

%llguidance {}
start: think_block? content tool_call_block?
think_block: "<think>" reasoning "</think>"
reasoning: /(.|\n)*?/
content: /(.|\n)*?/
tool_call_block: tool_call+
tool_call: "<tool_call>" /[ \t\n\r]*/ func_name /[ \t\n\r]*/ tool_arg+ /[ \t\n\r]*/ tool_close
tool_close: "</tool_call>"
func_name: FUNC_NAME
FUNC_NAME: /[a-zA-Z_][a-zA-Z0-9_]*/
tool_arg: "<arg_key>" arg_name "</arg_key>" /[ \t\n\r]*/ "<arg_value>" arg_value "</arg_value>" /[ \t\n\r]*/
arg_name: /[^<]*/
arg_value: /(.|\n)*?/

hermes / granite / nemotron / cohere-c4ai / seed-oss / qwq / qwen3-5 / glm-4-6

Each is a thin pipeline reusing the json_tagged family base for tracker/decoder/transformer (or the per-arg KV variant for XML-tagged sub-families). Today these all flow through the auto-parser path at chat.cpp:1790 setting PEG_NATIVE. After this refactor each gets its own COMMON_CHAT_FORMAT_PEG_<NAME> enum and its own (mostly thin) per-format header, even if the four layers are reused unchanged from the family base.

How the tracker FSM informs the parser and llguidance

The PEG parser consumes input and produces AST nodes; today its expectations come purely from the loaded grammar’s structure (next_sequence_delimiters collected from the next sibling literals). After the refactor, the per-format tracker’s FSM is consulted during parsing:

  • common_peg_parse_context gains an optional common_chat_format_state_view * pointer. The PEG runtime sees only this read-only view interface — no chat-module dependency.
  • Before parsing a child sequence, the PEG context queries view->expected_productions() and intersects the list with next_sequence_delimiters — a tighter constraint than grammar-only.
  • The constraint is purely additive: if expected_productions() returns empty, the parser falls back to grammar-only behavior (current). So formats that do not need state-driven hints work as today.

llguidance is informed implicitly: the per-format Lark grammar already encodes all reachable states as named rules. llguidance’s Earley + lexer parser tracks the rule path internally as the model emits tokens, and computes a token mask at every position. The tracker is the C++ mirror of the same state — it doesn’t push to llguidance, it watches the same source of truth (the grammar). The only operational requirement is: each per-format grammar must contain rules whose names match expected_productions() exactly, so the C++ tracker FSM and llguidance’s internal state agree.

This is verified at startup: after building the per-format common_peg_arena, the tracker exposes the full set of rule names it expects across all states. We assert each is present in the arena. If a grammar update drops a rule, the assertion fires before any model is run.

Implementation order

Step 1 — Infrastructure. Create:

  • common/chat-formats/decoded-event.h, format-tracker.{h,cpp}, format-decoder.{h,cpp}, format-transformer.{h,cpp}, format-presenter.{h,cpp}, format-pipeline.{h,cpp} — the four base classes, the events struct, and the pipeline coordinator.
  • common/chat-formats/json-tagged-format.{h,cpp} — shared family base (tracker + decoder + transformer reuse for the JSON-args formats).
  • common/peg-parser.{h,cpp} — add the optional common_chat_format_state_view * pointer in common_peg_parse_context and the additive intersection with next_sequence_delimiters. No-op when the pointer is null.

Add the per-format COMMON_CHAT_FORMAT_PEG_* enum values to common/chat.h (already done partially). Replace make_mapper lambda in common/chat.cpp with make_format_pipeline(params.format, msg) returning a common_chat_format_pipeline. Default branch keeps the legacy common_chat_peg_mapper path active for templates not yet migrated; the legacy class is deleted in Step 7. Verify: build/bin/test-chat — all 16/19 still pass, 3 still fail.

Step 2 — Migrate one format at a time, easiest first. For each: write the per-format *-format.{h,cpp} containing all four layers (tracker FSM, decoder events, transformer shaping, optional presenter overrides), declare valid rules in expected_productions(), set the new enum in the matching common_chat_params_init_*, make the dispatcher route to its pipeline, run only that template’s tests via --template <name>. After each, also run the full suite to confirm no regression elsewhere.

Order: ministral-3 → gigachat-v3 → kimi-k2 → gpt-oss → functionary-v3-2 → deepseek-v3-2 → lfm2 → lfm2-5. After lfm2/lfm2-5 we delete the synthesis branches from the legacy common_chat_peg_mapper::map().

Step 3 — Auto-parser families per-template. For each of Hermes, Granite, Nemotron, Cohere c4ai, Seed-OSS, QwQ, Qwen3.5, GLM-4.6: add COMMON_CHAT_FORMAT_PEG_<NAME>, set it from the auto-parser path (chat.cpp:1790), add a per-family *-format.{h,cpp} (typically a thin reuse of the json_tagged family). Run each template; no behavior change expected.

Step 4 — Add Qwen3-Coder. New grammars/chat/qwen3-coder.lark, register in the grammar map, add common_chat_params_init_qwen3_coder, dispatcher entry, common/chat-formats/qwen3-coder-format.{h,cpp} (FSM identical to lfm2; decoder reads <parameter=k>val</parameter> instead of name(k=v)). Run --template Qwen3-Coder. Currently failing test tests/test-chat.cpp:2530 (HTML markup) starts passing.

Step 5 — Add GLM-4.7-Flash. New grammars/chat/glm-4-7-flash.lark, init function, dispatcher, common/chat-formats/glm-4-7-flash-format.{h,cpp}. Run --template GLM-4.7-Flash. The g_template_filter carve-out at tests/test-chat.cpp:3057 for the throw-path assertion test should be revisited once a real grammar exists.

Step 6 — Replace Gemma-4 grammar + format files. Rewrite grammars/chat/gemma4.lark to match https://ai.google.dev/gemma/docs/core/prompt-formatting-gemma4 — <|turn>model\n envelope, <|channel>thought ... <channel|> reasoning, <|tool_call>call:NAME{...}<tool_call|> tool calls. Closing tokens stay required. Replace common_chat_peg_gemma4_mapper with the new common/chat-formats/gemma4-format.{h,cpp} (tracker FSM, decoder using existing gemma4_to_json() logic, default transformer + presenter). Run --template gemma-4.

Step 7 — Synthesis purge + legacy mapper deletion. Once every format dispatches to its common_chat_format_pipeline, the legacy common_chat_peg_mapper::map() body is no longer reached. Delete:

  • chat-peg-parser.cpp:336–338 — current_tool->arguments = "{" synthesis when args buffer empty
  • chat-peg-parser.cpp:374–377 — target = "{" and arg_count comma synthesis
  • chat-peg-parser.cpp:392, 397, 416, 442 — opening " synthesis for string values
  • chat-peg-parser.cpp:454–458 — closing " synthesis on arg_close
  • chat-peg-parser.cpp:471–477 — json_brace_depth } synthesis on tool_close
  • The common_chat_peg_mapper and common_chat_peg_gemma4_mapper classes themselves.

The four-layer pipeline base classes plus per-format subclasses cover all paths. The only remaining JSON-shape synthesis is in the transformer layer for TOOL_ARG_KV → TOOL_ARGS_JSON assembly (Python/DSML/XML-tagged formats whose wire shape isn’t JSON), and it’s confined to those transformers with explicit comments calling out the deliberate exception.

Critical files

  • common/chat.h — per-format enum values (partial; completes here)
  • common/chat.cpp — common_chat_format_name, make_format_pipeline dispatcher, every common_chat_params_init_* sets its enum, line 1790 auto-parser fallback dispatches per template
  • common/chat-peg-parser.{h,cpp} — slimmed; the legacy mapper classes are deleted at step 7
  • common/peg-parser.{h,cpp} — add common_chat_format_state_view * to common_peg_parse_context; intersect expected_productions() into next_sequence_delimiters when set (additive constraint)
  • common/chat-formats/* — new directory, one *-format.{h,cpp} per family containing all four layers
  • common/CMakeLists.txt — list the new files
  • grammars/chat/{gemma4,qwen3-coder,glm-4-7-flash}.lark — rewritten/new

Verification

After each migration step:

  1. cmake --build build --target test-chat -j$(nproc) — must succeed.
  2. build/bin/test-chat --template <template-name> — must report [chat] All template tests passed! for the migrated template, and same status as before for every other template.

After the full refactor:
3. build/bin/test-chat — all 19 templates pass, no Error comparing accumulated message to current and no Tool call mismatch.
4. Streaming monotonicity is preserved (the test suite asserts this implicitly via compute_diffs).
5. After Step 7: grep "json_brace_depth\|closing_quote_pending" common/chat-formats/ returns matches only inside the per-format transformer files that legitimately assemble JSON args from KV events (DSML, lfm2, qwen3-coder, glm-4-7-flash), with explicit comments calling out the deliberate exception. common/chat-peg-parser.cpp has neither symbol.

Out of scope

  • Lark→PEG / GBNF→PEG transpilers, grammar file embedding, CLI --chat-{lark,gbnf}-grammar-file flags — handled in the prior plan (already implemented).
  • The auto-parser (common/chat-auto-parser*) itself is not refactored; only its output is routed through per-format pipelines.
  • Streaming PEG parser internals (common/peg-parser.cpp) — bug fixes already landed in the prior session for chars/repetition NEED_MORE at EOF; no further changes here beyond the new common_chat_format_state_view * hook.

I recently developed my own harness to fit my workflow. Pi was an inspiration, but I needed deterministic statechart driven flow. Opencode is a great performer, but I needed task management and scheduled local inference use.

Are you forking Opencode @Ewout ? To use tiny models? I use tiny models through models, saves me the headaches and subagents already exist in opencode. Wire up custom providers with your llama.cpp or others, let one model pick and distribute to smaller ones? It sounds like you want the AST plugin for your model/frontend. I use chunkhound(a claude code vibecoded semantic codebase tool) and Serena plugin to provide my agents with AST.

1 Like

@s1ugh34d All your questions were already addressed in the main post.

And no, this is not a bunch of markdown files “harness”. It’s tackling the direct communication implementations to the models and runtimes, which are wrong.

Do not bother reading.


I’m discovering, even the conversation style turns of certain models is not strictly adhered to afaict. LiteRT-LM behaves differently as vLLM and llama.cpp do in this regard.

It shouldn’t be controlled by flawed human error prone PEG parsers and Jinja2 templates, whoever or whichever agentic engineering workflow came up with that ought to be fired.
Yes, it helps with faster “compatibility” with new models, but there’s no point if it isn’t a correct implementation.

Jinja2 is useful for HTML, not so much for guiding LLM conversation turns.
These projects (llama.cpp, vLLM, etc.) need specialized stateful conversation pipelines.

llguidance can then ensure the model behaves (with the context of all allowed states/“turns” within that state), and tada; better results for all models (and especially the tiny ones).

And to further complicate things, even the way the models are being run from runtime to runtime can increase error rate:

I really wish these AI startups (e.g. Hugging Face) would pour some engineering into attacking these real issues, instead of vibe merging all PRs and going for the highest LoC edits per month ratios.

As correctness matters most.

This sounds interesting I’ve been vibecoding and messing around with on my own project.

My idea was to use treesitter to split out a codebase into smaller code chunks that I would then have a local llm summarize and embed the summaries for RAG.

I am still working on it, but I’ll let you know when I get a better working version

Ideally I can do have a cli tool that llm coding agents can call glma query “which code block has my chunking”. Glma would return the relevant chunks for the coding agent to read through.

I came back to the project recently because I noticed my coding agents just did grep

1 Like

This is VERY similar to a problem I’m trying to solve for. You’re on the right track. My application is leveraging Cloud LLMs to coordinate coding tasks to a local LLM so the Paid tokens are saved by just overseeing the work and the local Tokens are what do the work.

Here’s an overview (Claude generated, just for transparency):

Your three points in “why we need a new approach” line up exactly with what we’ve observed running small models (Devstral Small 2 24B, Nemotron 3 Nano 30B, Mistral Small 3.2 24B) as supervised coding executors on AMD hardware (2x R9700, 64GB VRAM).

On “bloated Markdown files that aren’t dynamic” — agreed. We moved to a per-model prompt fragment system. Each model gets a capability profile that drives which prompt fragments are injected. Devstral (code-specialist) gets the base prompt with nothing added. Mistral Small (general-purpose) gets Edit format examples and incremental-emission guidance injected. The key learning: Mistral Small went from 2/4 PASS to Devstral-tier quality just from a 5-line GOOD/BAD example for the Edit tool schema. The model could already do the work — it just needed the pattern shown once, not buried in a wall of markdown it had to parse.

On “regex patterns and line parameters are why tiny models fail” — we hit this exact problem. Mistral Small used Edit(content=...) instead of Edit(old_string=..., new_string=...) because the schema wasn’t in its training distribution. And when old_string matched multiple locations, every model struggled with disambiguation. Your AST editing direction would structurally eliminate both problems — we haven’t implemented it yet but it’s on our list. In the meantime, we found that graduated error feedback helps a lot: instead of just rejecting a bad Edit, tell the model “old_string matched 3 locations at lines 12, 45, 89 — include the class/function name to disambiguate.” Models self-correct on the first retry when the error message teaches the pattern.

On “small models lack deep contextual knowledge” — partially agree. What we found is that supervision granularity matters as much as model knowledge. Mistral Small batches 5-10 tool calls per API response. If you only review every 5th proposal, the model has already committed to a wrong path before feedback reaches it. Switching to per-tool-call review (check each proposal before the model sees the result and plans its next move) was transformative — same model, same prompt, dramatically better outcomes. The model doesn’t lack knowledge; it lacks the feedback loop to use what it knows.

One additional finding that might be useful: when the orchestrator (Opus in our case) silently backstops a failing executor — fixing things via bash sed when the small model gets stuck — the benchmark scores it as a model success. We built attribution tracking to tag every file mutation as executor-originated or orchestrator-originated. Turned out one of our “PASS” results was entirely the orchestrator doing the work. Worth checking if your test harness has the same blind spot.

On the grammar-constrained decoding work — we see it as complementary to the pedagogical feedback approach. Grammar prevents structural errors at the token level (the model literally can’t emit invalid tool JSON). Feedback corrects semantic errors after emission (valid format, wrong content). Both needed, different failure classes.

1 Like