Repository navigation
Description
Overview
Manual on-device validation of the chat-template and tool-call paths that landed in PR #1134. Cannot be done in CI because it requires a real GGUF on disk and Metal acceleration, and our embedding integration tests already destabilize the suite when run in parallel.
Problem Statement
PR #1134 made two changes that touch the runtime inference path:
-
Chat template path changed for both families. Replaced the C-level
apply_chat_template(which hand-injected[AVAILABLE_TOOLS]...[/AVAILABLE_TOOLS]into the system prompt) withapply_chat_template_oaicompat(use_jinja: true), which passes tools viatools_jsonand lets the model's embedded Jinja template format them. Ministral 2512 GGUFs ship with a Jinja template that should produce the same[AVAILABLE_TOOLS]wrapper, but byte-for-byte equivalence to the old hand-injected form was not verified. -
Added Gemma 4 E4B and 31B as new model options. Validated end-to-end in
../nodespace-nlp-experimentonllama-cpp-2 v0.1.146, but not re-run against the production code innodespace-core.
Both paths are believed correct based on the experiment repo and unit-level parser tests, but neither was confirmed against the production code on a real machine.
The previous PR's code reviewer agreed that automated tests for this would be flaky (parallel Metal contention destabilizes integration runs), and the agreed mitigation was a manual smoke test before users see the change. NodeSpace has no users yet, so PR #1134 was merged ahead of verification — but the verification still needs to happen before any release that ships these models.
Proposed Solution
A short, scripted manual session on M2 Pro 16GB (or equivalent Apple Silicon) that exercises both code paths and one regression path.
Verification Approach
Phase 1: Ministral regression check (anti-regression for #1134's chat-template change)
- Launch the desktop app with a clean local model directory.
- Download Ministral 3B Q4_K_M (
ministral-3b-q4km). - Load it.
- Send a chat prompt that requires a tool call (any registered tool — e.g.
search_nodeswith a query). - Confirm:
- Tokens stream as expected.
- The streaming parser detects
[TOOL_CALLS]and emits aToolCallStart+ToolCallArgschunk. - The tool's name and arguments parse correctly via the Mistral
{name, arguments}schema.
Phase 2: Gemma 4 E4B end-to-end
- Without unloading Ministral, download Gemma 4 E4B Q4_K_M (
gemma-4-e4b-q4km) — exercises the resumable download flow against the newggml-org/gemma-4-E4B-it-GGUFURL. - Unload Ministral, load Gemma 4 E4B.
- Send a plain chat prompt. Confirm: no
ffi error -1in logs, tokens stream. - Send a tool-using chat prompt. Confirm the parser detects
[TOOL_CALLS]and successfully extracts a tool call using the Gemma 4{tool_name, tool_args}schema (Format C inchat/parser.rs).
Phase 3 (optional, requires 24GB+ machine): Gemma 4 31B
- Download
gemma-4-31b-q4km(~18.7 GB). - Load.
- Single chat round to confirm load + first-token generation succeeds.
Acceptance Criteria
- Ministral 3B (or 8B) tool-calling parses correctly under the new OAI-compat Jinja path
- Gemma 4 E4B downloads, loads, and streams without
ffi error -1 - Gemma 4 E4B tool-calling parses correctly via the Format C
{tool_name, tool_args}path - Results documented as a comment on this issue (parse rates, any errors, tokens/sec for confirmation against the experiment repo's published numbers)
- If any path fails, file a separate bug issue with the specific failure mode
Technical Specifications
Reference Files
- Chat template path:
packages/nlp-engine/src/chat/mod.rs(the rewrittenapply_chat_templatefunction and itsOpenAIChatTemplateParamssetup) - Tool-call parser:
packages/nlp-engine/src/chat/parser.rs(Format A/B/C handling;parse_tool_call_objectdual-deserialization) - Model registry:
packages/agent/src/local_agent/model_manager.rs(catalog entries for Ministral 3B/8B + Gemma 4 E4B/31B) - UI model manager:
packages/desktop-app/src/lib/components/settings/model-manager.svelte
Reference Validation Data
The experiment repo's published numbers for Gemma 4 E4B on M2 Pro 16GB are the comparison target:
- Tokens/sec: ~20.1
- TTFT: ~265ms
- Model load: ~0.67s
- Combined RSS with nomic-embed-text loaded: ~5.4 GB
If observed numbers diverge significantly, log it on this issue but do not block — the experiment numbers are a smoke check, not an SLA.
Logs to Capture
For each phase: snippet of stdout/stderr around chat-template application and tool-call parsing, plus any tracing::warn! or tracing::error! lines from nodespace-nlp-engine.
Dependencies
- Add Gemma 4 E4B and 27B as downloadable model options #1094 (parent — code already landed)
- Surface hardware-requirement labels in model selection UI (follow-up to #1094) #1140 (UI hardware-requirement labels; independent of this verification but related to the same Gemma 4 work)
Related Issues
- Add Gemma 4 E4B and 27B as downloadable model options #1094 (parent)
- Surface hardware-requirement labels in model selection UI (follow-up to #1094) #1140 (UI follow-up)
- Originating PR: Add Gemma 4 E4B and 31B as downloadable model options (#1094) #1134
- Originating PR review thread: Add Gemma 4 E4B and 31B as downloadable model options (#1094) #1134 (comment)
Non-Goals
- Benchmarking on non-Apple-Silicon hardware
- Multimodal (vision/audio) input — Gemma 4 supports it but NodeSpace has no vision pipeline yet
- Automated regression coverage — the agreed mitigation is manual; an automated version of this test would require an Ollama-style integration harness which doesn't exist yet
Activity
malibio commentedon May 31, 2026
Verification Results — Gemma 4 E4B Only (Ministral skipped per user preference)
Date: 2026-05-31
Machine: Apple Silicon M2 Pro 16GB
Model: Gemma 4 E4B Q4_K_M (
gemma-4-e4b-q4km)Daemon binary:
~/.nodespace/bin/nodespaced(built 2026-05-31 22:01)Phase 2a: Plain chat — ✅ PASS
EnsureModelReady→{ "eventType": "ready", "engineSwapped": true }— model loadedSendMessage("Hello! What is 2+2? Reply briefly.")— tokens streamed immediately, noffi error -1Phase 2b: Tool-call parsing — ❌ FAIL (new bug)
The agent loop log shows
tool_calls=0on a prompt that triggered tool use. The raw response was:Root cause: Gemma 4 E4B uses special tokens for tool calls (
<|tool_call>= token 106), not the plain-text[TOOL_CALLS]sentinel the streaming parser expects. The code callstoken_to_piece(..., special=false)which silently drops special tokens. The daemon log showsWARN: Failed to decode token 106: Unknown Token Typeon every tool call boundary.Additionally, the Gemma 4 tool call format after the special token is
call:<name>{args}with<|"|>special-token string delimiters — not the{"tool_name": ..., "tool_args": ...}JSON-object format the parser (Format C) was built for.The Format C assumption was wrong: the parser was written assuming Gemma 4 would emit
[TOOL_CALLS]{"tool_name":...}(same as Mistral sentinel + JSON). The actual model uses a completely different special-token-based encoding.Daemon binary verification
Daemon is the correct binary:
LocalAgentService/ListModelsreturns all 4 models with correct statusEnsureModelReadyworks end-to-endSummary
ffi error -1on first tokenNext step
Filed #1287: Fix Gemma 4 tool-call parser — handle
<|tool_call>special token andcall:name{args}wire format.Fix Gemma 4 tool-call parsing via llama.cpp native streaming parser
malibio commentedon May 31, 2026
Fix committed — Gemma 4 tool-call parsing (commit 3a4efd6)
Root cause confirmed: Gemma 4 E4B uses special tokens for tool calls (
<|tool_call>= token 106,<|"|>for string delimiters,<tool_call|>as end marker). The old code calledtoken_to_piece(..., special=false)which silently dropped these special tokens, so the[TOOL_CALLS]sentinel was never injected andtool_calls=0on every response.Fix: Replaced the custom sentinel detection with
ChatParseStateOaicompat— llama.cpp's own streaming parser, accessible via thellama-cpp-2Rust binding. Setparse_tool_calls: truein the chat template params so the parser state gets the model's nativechat_format+ PEG grammar. The generation loop now feeds accumulated text tooai_parser.update(text, is_partial)per token; the C++ layer handles all model-family-specific special tokens.This also removes all the
detect_tool_calls_token/tool_calls_token_idplumbing that was Mistral-specific. Future model families work automatically if llama.cpp knows them.Ready to re-verify — restart the Tauri app (which will install the new daemon binary) then re-run the tool-calling prompt via the chat UI or grpcurl.
malibio commentedon May 31, 2026
Session handoff — WIP commit a6f4a16
What was fixed this session
Tool-call parsing now works for Gemma 4 E4B (
tool_calls=1per inference round confirmed in daemon logs).Root cause: Gemma 4 emits
<|tool_call>as a special token (id 106). The old code usedtoken_to_piece(special=false)which silently dropped it, so the[TOOL_CALLS]sentinel was never injected andtool_calls=0on every response.Fix: replaced
StreamingToolCallParser+ custom sentinel detection withChatParseStateOaicompat— llama.cpp's native streaming parser backed byCOMMON_CHAT_FORMAT_PEG_GEMMA4PEG grammar. Handles all model families natively.Also fixed:
LocalAgentServiceServerwas accidentally dropped from daemon gRPC registration in PR #1161 (ea8849a) and had been missing for 13 days. Restored in 443bad0.Remaining before closing this issue
<|tool_call>tokens still stream asChatChunk::Tokenin the last plain-text generation round.contentdeltas fromoai_parser.update()may be dropping. Debug starting point: add logging inemit_oai_delta()(packages/nlp-engine/src/chat/mod.rs~line 465) to inspect raw delta JSON strings.malibio commentedon Jun 1, 2026
Code Review — commits 3a4efd6, 443bad0, a6f4a16
These commits were pushed directly to main during session verification of #1142. Review findings:
443bad0 — Restore LocalAgentService registration ✅
Correct.
node_service.clone()beforeImportServiceImpl::new(node_service)is right. Both server blocks (headless + tray) updated consistently.3a4efd6 — ChatParseStateOaicompat streaming parser
🟡
argsdefault of"{}"wrong for streaming partial deltaspackages/nlp-engine/src/chat/mod.rsline 487Early streaming deltas carry
namebut absent/emptyarguments; they arrive in subsequent deltas. Defaulting to"{}"emits a prematureToolCallArgswith empty args. Works for Gemma 4 (full args in one delta) but will break Mistral streaming. Fix: only emitToolCallArgsifargumentsis present and non-empty.🟡
token_to_piece(special=true)is a behavioral change for Mistralpackages/nlp-engine/src/chat/mod.rsline 380Mistral's
[TOOL_CALLS]special token now decodes as literal text and goes to the OAI parser directly instead of being intercepted. Functionally correct in theory (OAI parser handles it), but Mistral was not tested this session. Should be verified before closing #1142.🔴 Known unfixed: raw special tokens leak in plain-text pass
Gemma 4 special tokens (
<|tool_call>,<|"|>,<tool_call|>) stream asChatChunk::Tokenduring the final no-tools inference pass. The OAI parser (COMMON_CHAT_FORMAT_PEG_GEMMA4) appears to buffer content rather than emit content deltas incrementally for plain text, so raw pieces pass through unfiltered. Not yet diagnosed or fixed.Overall: The LocalAgent registration restore is clean. The parser approach is architecturally correct but has two issues to address (args default, raw token leak) and one regression risk (Mistral) before this can be considered complete.
Fix Gemma 4 stop sequence and special token handling
malibio commentedon Jun 1, 2026
Final Verification Results — Gemma 4 E4B (M2 Pro 16GB)
Date: 2026-06-01
Model: Gemma 4 E4B Q4_K_M (
gemma-4-e4b-q4km, 5.3GB)Commits: 3a4efd6, 443bad0, d918293, 8b5c842
Acceptance Criteria
ffi error -1on first tokentool_calls=1per inference round, correct name + argsadditional_stops+strip_gemma_special_tokensPerformance Numbers (M2 Pro 16GB)
The TTFT and tok/s diverge from the experiment baseline because the daemon runs the full ReAct agent with 13 registered tools (~7500 char system prompt, 5362 tokens). The experiment repo tested bare inference with a minimal prompt. This is expected — not a regression.
Fixes applied during this verification
StreamingToolCallParserwithChatParseStateOaicompat(llama.cpp native,COMMON_CHAT_FORMAT_PEG_GEMMA4)argsdefault"{}"wrong for streaming partial deltas — changed toOption<&str>strip_gemma_special_tokens()+additional_stopsstop sequence checkFiled
Fix Gemma 4 tool-call parsing via llama.cpp native streaming parser
WIP: Gemma 4 tool-call parsing via ChatParseStateOaicompat (closes #1142
Fix Gemma 4 stop sequence and special token handling