Skip to content

llama: the model's own chat handling in-process: templates, native tool calls, reasoning (serving S2a) - #6142

Merged
joelteply merged 3 commits into
canaryfrom
fable/llama-chat-shim
Nov 18, 2026
Merged

joelteply merged 3 commits into
canaryfrom
fable/llama-chat-shim

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Serving integration step 2a. Residents decode over llama-server today because that path gives them the GGUF's chat template, native tool_calls parsing, reasoning and JSON schema. The in-process adapter does tools by prompt only. This binds llama.cpp's own common/chat (already built into llama-common, unbound until now) so the in-process path can do the same.

  • chat_boundary.cpp: a C ABI over common_chat_templates_init/_apply and common_chat_parse. Exactly one JSON document crosses in each direction, in the OpenAI shape. C++ exceptions terminate on the native side.
  • llama::ChatTemplates and llama::chat_parse, with a typed ChatRefusal.
  • Model-free tests: content-only parse, malformed input refused rather than unwinding, and NUL text refused.

Next. Step 2b makes LlamaCppAdapter render and parse through this. It gets proven on a real model with a streamed native tool call, a schema, a reasoning budget and a resumed native prefix before step 2c routes residents in-process.

Measured

Nothing yet. This hasn't been built locally (the M5 is serving), so CI is the first compile. Owner: Fable.

🤖 Generated with Claude Code

https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

joelteply and others added 2 commits November 18, 2026 11:34
…ol calls, reasoning)

Serving integration S2a. Residents decode over llama-server today because that path gives them the
GGUF's jinja template, native tool_calls parsing (their hands), reasoning and JSON schema; the
in-process adapter has prompt-driven tools only and refuses think budgets and schemas. Before the
in-process scheduler can serve residents, it needs the same chat handling. llama.cpp's common/chat
already does it and is built into our llama-common; nothing outside vendor bound it (Codex checked).

- chat_boundary.cpp: a C ABI over common_chat_templates_init / _apply and common_chat_parse. One
  JSON document crosses each way in the OpenAI shape the adapters already speak (messages, tools,
  tool_choice, json_schema, enable_thinking, reasoning_format); apply returns the prompt, grammar
  and lazy triggers, preserved tokens, extra stops, thinking tags and the saved PEG parser; parse
  takes that back with the model's text and returns content / reasoning_content / tool_calls.
  Exceptions terminate on the C++ side (the decode_boundary pattern).
- llama::ChatTemplates (Send, not Sync) + llama::chat_parse, with typed ChatRefusal { step,
  message }; NUL-bearing text is refused before the native side.
- build.rs compiles the shim before llama-common is linked.
- Tests without a model: content-only output parses to its content; malformed JSON is a refusal,
  not an unwind; a NUL is refused.

Next (S2b): LlamaCppAdapter renders and parses through it (native tools, reasoning budget, schema
grammar), proven on a real model with a streamed native tool call, a schema, a reasoning budget and
a resumed native prefix (Codex) before residents route in-process (S2c). Not built locally (the M5
is serving); CI is the first compile.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…f; reasoning format typed

Codex on #6142 (dfb2707): parse took the whole apply result (prompt, grammar, parser, stops) as a
string, copied it through a CString and re-parsed its JSON on every streamed update, so each
partial cost as much as the original prompt; and an unknown reasoning format silently became AUTO.

- continuum_chat_render_new returns a native continuum_chat_render holding common_chat_params and
  its common_chat_parser_params (PEG parser loaded once). describe() returns the prompt, grammar,
  lazy triggers, preserved tokens, extra stops and thinking tags once; parse(text, partial) uses the
  render's own parser, the model's text crossing by pointer and length (no terminator, no copy into
  a CString, no render JSON).
- ReasoningFormat { None, Auto, Deepseek, DeepseekLegacy } is typed at the boundary; the native side
  throws on any other code, so an unknown format is refused, never defaulted.
- llama::ChatTemplates::render -> ChatRender { describe, parse }, both Send, neither Sync.
- Tests without a model (a test-only content-only render): content parses; one render parses a
  partial update and then the whole; text crosses by length, so an interior NUL is kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…rance (contract_shape)

source-hygiene contract_shape rose 2187 -> 2190 on #6142: the chat externs took five to seven
parameters (out pointer, error buffer, capacity, text, length, partial). A #[repr(C)] Reply { out,
error[512] } replaces the out/error/capacity triple on every call, and an Utterance { text, length,
partial } carries what the model wrote; no call takes more than four parameters now.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
@joelteply
joelteply merged commit 4231d34 into canary Nov 18, 2026
45 checks passed
@joelteply
joelteply deleted the fable/llama-chat-shim branch November 18, 2026 18:48
joelteply added a commit that referenced this pull request Nov 18, 2026
…changed (S2b prep) (#6144)

* llamacpp adapter: generate_text's body moves to its own module, unchanged

Serving S2b routes a resident's turn through the model's own chat handling (ChatRender, #6142):
render with tools and reasoning, parse native tool calls. That work lands in generate_text, a
392-line body inside the 853-line adapter file, which would cross the 1,000-line rule. This is the
move only: LlamaCppAdapter::generate in llamacpp_adapter/generate.rs (404 lines), the trait method
delegates. No line of the body changes; llamacpp_adapter.rs is 463 lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* llamacpp adapter: the whole provider impl moves to provider.rs instead (stringly_errors ratchet)

f556a46 moved generate_text's body into an inherent LlamaCppAdapter::generate, which added a
second Result<_, String> signature beside the trait's (stringly_errors 4245 -> 4246). The move is now
the whole AIProviderAdapter impl into llamacpp_adapter/provider.rs, the way openai_adapter/provider.rs
holds that adapter's: no new signature, generate.rs is gone. Verified byte-exact: provider.rs after
its header equals canary's llamacpp_adapter.rs lines 188-853; llamacpp_adapter.rs equals lines
1-187 plus 'mod provider;'. 853 -> 188 + 673 lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* Fix the one relative path the move put a module deeper: provider.rs names NO_TRAINED_CONTEXT by its crate path

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
joelteply added a commit that referenced this pull request Nov 18, 2026
…s own chat handling (S2b slice 1) (#6145)

* llamacpp adapter: generate_text's body moves to its own module, unchanged

Serving S2b routes a resident's turn through the model's own chat handling (ChatRender, #6142):
render with tools and reasoning, parse native tool calls. That work lands in generate_text, a
392-line body inside the 853-line adapter file, which would cross the 1,000-line rule. This is the
move only: LlamaCppAdapter::generate in llamacpp_adapter/generate.rs (404 lines), the trait method
delegates. No line of the body changes; llamacpp_adapter.rs is 463 lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* native tool calls: one assembler for every engine that reads them

The streamed OpenAI-compatible path assembled a model's native tool calls inline in
openai_adapter/stream.rs (name filter, UnparsedArguments::parse with the generation end, the
unparseable-arguments probe, ToolCall). The in-process engine reads the same calls from the
model's own chat parser (S2b), so the assembly moves to inference::native_tool_calls::assemble and
both call it: a call's fate reads the same whichever engine served her turn. Behavior unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* llamacpp adapter: her text turn renders and parses through the model's own chat handling (S2b slice 1)

A text turn now renders through ChatTemplates (llama.cpp common/chat, #6142) with her tools, from
the same wire_messages and openai_tools serving sends, and what she writes is parsed by that same
ChatRender into content, reasoning and native tool calls. The calls are assembled by
native_tool_calls::assemble, the owner the streamed path uses; content blocks come from
native_tool_calls::content_blocks, which the streamed path now uses too.

- LlamaCppBackend::render_chat_turn: templates load once beside the model (OnceLock, Mutex: the
  templates are Send, not Sync); the lock is held for the render alone, released before decode.
- One ChatRender per request, from render to final parse.
- A named tool_choice is refused (ChatTurnError::SpecificToolChoice): the model's own tool-choice
  parser takes a mode, and widening a name to any tool would be a silent change.
- Media turns keep the plain template until mtmd takes a chat render.

Not in this slice (slice 2): the render's grammar, lazy triggers, preserved tokens and extra stops
into the sampler, then the four proofs. No resident is routed here until then.

Tests: her_turn_renders_the_wire_messages_and_tools_serving_sends,
a_named_tool_choice_is_refused_not_widened, a_decode_that_reached_its_cap_ended_at_the_output_limit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* llamacpp adapter: the whole provider impl moves to provider.rs instead (stringly_errors ratchet)

f556a46 moved generate_text's body into an inherent LlamaCppAdapter::generate, which added a
second Result<_, String> signature beside the trait's (stringly_errors 4245 -> 4246). The move is now
the whole AIProviderAdapter impl into llamacpp_adapter/provider.rs, the way openai_adapter/provider.rs
holds that adapter's: no new signature, generate.rs is gone. Verified byte-exact: provider.rs after
its header equals canary's llamacpp_adapter.rs lines 188-853; llamacpp_adapter.rs equals lines
1-187 plus 'mod provider;'. 853 -> 188 + 673 lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* S2b slice 1: the model loads its own templates, a cut turn reports Length, only media turns build the plain-template messages (Codex on #6145)

- The registry template is the chat render's override only for a model without its own; with
  one, common/chat loads the GGUF's templates (its named tool_use one among them), which an
  explicit override suppresses (common/chat.cpp:761-776).
- finish_reason(end, called): the output limit first, so a turn the cap cut (even mid-call)
  reads Length, never ToolUse/Stop.
- carries_media decides the path before anything is built: a text turn no longer clones every
  message into ChatMsg to discard it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* S2b slice 1: the chat render decides its template once, from the GGUF's default OR named tool_use template (Codex on #6145)

A GGUF carrying only tokenizer.chat_template.tool_use read as having no template (chat_template()
queries the default only), so the registry template masked the model's own. Now the one-time
ChatTemplates init asks Model::has_chat_template (pointer check, no copy) for the default or the
named tool_use template, and asks for the registry template only when both are absent. The
registry lookup is a closure: a text turn copies no template string; the media path resolves its
plain template where it renders.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* Fix the one relative path the move put a module deeper: provider.rs names NO_TRAINED_CONTEXT by its crate path

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* S2b slice 1: the render's JSON reads as types, a named tool_choice refusal carries the choice, assemble takes the calls as they come

Pays back the three ratchets bb0a6f2 raised:
- string_identities (+3): prompt_of and parse_turn deserialize Described / ParsedMessage /
  ParsedCall instead of reading .get("prompt"|"tool_calls"|"id") by name.
- stringly_errors (+1): ChatTurnError::SpecificToolChoice carries the ToolChoice, not its name.
- contract_shape (+1): native_tool_calls::assemble takes impl IntoIterator<Item = StreamToolAccum>
  (it consumes them); parse_turn feeds its calls straight in, no intermediate Vec.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* Drop the ContentPart import the content-block move left unused (warnings 13 -> 12); the tests import it themselves

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
joelteply added a commit that referenced this pull request Nov 19, 2026
…'s ChatRender), the residents' contract ported onto it

Canary's serving S2a/S2b (#6142, #6145) and this branch's 75cea66 built the same capability twice
(chat_boundary.cpp + ChatRender + chat_turn.rs, and chat_template.cpp + chat_template.rs +
native_chat.rs); both defined continuum_chat_free, so they could not link together. Canary's stays
the owner (agreed with Codex, 06:07Z). Ported onto it, the three things residents need that it lacked:

- the think budget: chat_boundary's continuum_chat_reasoning_budget (llama.cpp's
  common_reasoning_budget, what llama-server ran) as llama::SamplerChainBuilder::reasoning_budget,
  bounded by the render's own thinking tags (chat_turn::Described::think_bound); a stated zero
  budget renders with enable_thinking off (chat_turn::thinking_request);
- the template's extra stops (Described::additional_stops) into the decode's stops;
- her view's end (chat_turn::view_text: her view rendered by the same templates, generation prompt
  off; describe now returns generation_prompt), passed as TurnPrompt.stable_prefix so the engine
  checkpoints her there (CONTINUUM-ENGINE 4.15).

Deleted: core/llama/chat_template.cpp, src/safe/chat_template.rs, llamacpp_adapter/native_chat.rs,
LlamaCppBackend::chat_templates and its second `chat` field, the inline AIProviderAdapter impl (it
lives in provider.rs on canary), and the llama crate's serde deps. The fork pin moves to 2869b164a7
(fable/persona-files merged with 51c7089eec, so it carries canary's 74be098b5 and #6156's pooled
graph).

Checked with serving down (06:08-06:13Z): cargo check of continuum-core, continuum-engine --tests,
the persona crates and the metal example; llama chat tests 3/3; persona-engine 21/21.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant