Repository navigation
ai-chat agent quality: fix runaway/hang + tool-call template leaks, tune prompts - #1331
Conversation
…ness
## Completed in This Session
- [x] Fix release-build compile error on main: node_to_proto(node.clone(), None, None)
→ 1-arg call in packages/daemon/src/services/node_service.rs (leftover from #1322).
- [x] Fix embedding_service:None production bug: GraphToolExecutor in
local_agent_service.rs replace_engine was built with embedding_service:None,
so search_semantic ALWAYS errored and skill-based select_tools routing was
bypassed (full 13-tool list always sent). Now reads inner.embedding_service.
Durable fix tracked in #1328.
- [x] Add tool_calls to ChatMessage (agent_types.rs) + ChatMessageInput
(nlp-engine/chat/types.rs, new ToolCallInput), populate in agent_loop when
the assistant issues tool calls, plumb into apply_chat_template's messages
JSON so the assistant turn emits OpenAI-format tool_calls (was dropping them
→ orphan tool result in re-prompt history). Added ChatMessage constructors
(text / assistant_with_tool_calls / tool_result).
- [x] New CLI subcommand `nodespace model {list|load|recommended}` (cli/commands/model.rs)
— the CLI had no way to load a model; required for headless prompt testing.
- [x] New bun harness `bun run chat {new|send <id> <msg>|ask <msg>|show <id>}`
(scripts/aichat.ts) — drives an ai-chat node end-to-end via the CLI, no UI,
against a throwaway test daemon (/tmp/nodespaced-test).
- [x] Filed 4 parallel tech-debt issues: #1325 (unify ChatMessage/ChatMessageInput),
#1326 (single tool registry), #1327 (delete duplicated fallback prompt),
#1328 (embedding service wired by construction).
## Root Cause Found (NOT yet fixed) — the hang/runaway
On a greeting ("Hi there"), Gemma-4-E4B emits chatty prose AND a needless
search_semantic call in the SAME turn. On re-prompt, Gemma's chat template
collapses tool_call + tool_response + the greeting into ONE malformed `model`
turn, then opens a fresh empty `model` turn. With nothing to say and no token
cap, the model runs away to max_tokens=16384 (multi-minute hang → "no reply").
Verified by logging the full templated prompt (temp logging since removed).
## Remaining Work (user wants ALL three)
1. max_tokens safety cap: agent_loop.rs has max_tokens: Some(16384) at two
InferenceRequest sites — lower to ~2048 so any runaway is bounded to seconds.
2. Prompt/skill tuning (live in DB, then backport to seed_prompt_nodes() in
prompt_assembler.rs + skill seeds in skill_pipeline.rs): conversational turns
skip tools; empty tool result → answer directly, never retry; less verbosity;
"create an invoice tracking database" → create_schema. Build a fuller scenario
matrix (create several custom node types via NL + CRUD against them).
3. Turn-structure fix: stop sending chatty assistant prose alongside tool calls
so the template stops collapsing the turn. Deeper agent_loop surgery.
## Current State
- Files modified: agent_types.rs, agent_loop.rs, inference.rs, ollama_integration.rs,
local_agent_service.rs, node_service.rs, nlp-engine chat/{mod,types}.rs + lib.rs,
cli lib.rs/commands/{mod,model}.rs, package.json, scripts/aichat.ts.
- Builds: cargo check + release build of daemon/cli pass. NOT yet run: test:all, quality:fix (clippy).
- Tests status: not yet run (WIP checkpoint).
- The embedding + tool_calls fixes are verified working at runtime (search_semantic
now succeeds, find_skills runs); the runaway is the open problem.
## Context for Next Session
Resume the test loop per memory note project-aichat-prompting-session-handoff (how
to start a fresh test daemon on /tmp/nodespaced-test, load gemma-4-e4b-q4km via the
new `model` CLI command, and drive `bun run chat`). Do the 3 remaining items, then
run test:all + quality:fix, and open the PR. Eval-system + model-capability-guardrails
issues still to be filed (see memory).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Removes the infrastructure-level failure modes in the local ai-chat agent
loop that were independent of model size, and tunes the seeded prompts/skills.
Loop & sampling:
- Cap any single inference round at MAX_RESPONSE_TOKENS=2048 (was 16384), so a
runaway is bounded to seconds instead of a multi-minute hang.
- Add a repetition penalty to the sampler chain
(LlamaSampler::penalties(256, 1.3, 0, 0) before temp) — kills the degenerate
loops small models fall into at near-greedy temperature (e.g. repeating a
closing phrase until max_tokens).
- Persist assistant tool-call turns with empty content (drop chatty prose) so
the Gemma chat template stops collapsing prose+call+result into one
malformed turn.
Chat template (fixes ffi error -3 turn abort introduced by the empty-content
change above):
- Emit content:null (not "") for assistant tool-call turns — the shape the
OAI-compat path expects.
- Normalize non-object tool-call arguments to "{}" so a malformed/empty tool
call never feeds invalid JSON into the Jinja template.
Response normalization (all tested):
- Strip leaked Gemma tool-call/response prose (call:foo{...}response:foo{...},
nested braces handled).
- Strip Gemma channel/thought reasoning blocks (<|channel>...<channel|>, plus
dangling-opener and stray-marker variants). Reasoning capture/display is
tracked separately in #1330.
- Add <|channel>/<channel|> to strip_gemma_special_tokens for defense in depth.
Prompt/skill tuning (seeds re-seed a fresh DB, equivalent to live-editing):
- agent_guidance.rs: add "DATABASE = SCHEMA" routing rule (so
"create an invoice tracking database" → create_schema) and a loud
"conversational turns use NO tools" rule; byte-lock tests updated.
- prompt_assembler.rs Response Rules: 1-2 sentences; empty/error tool result →
state and stop, no retry, no compensating tool.
- skill_pipeline.rs Schema Creation: "ONE SCHEMA PER REQUEST" — no proactive
related-type creation.
Remaining capability-bound behavior (E4B calls tools on conversational turns,
keeps iterating after a complete answer, emits unmarked bare-"thought"
narration) is tracked for the 12B A/B in #1329.
Tests: agent 232, nlp-engine 61, core 890, frontend 3841, skill 17 — all pass.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Pragmatic Code Review — PR #1331Review Type: Initial Review SummaryThis is a strong, well-reasoned change that targets the right layer: it removes infrastructure-level failure modes (multi-minute hangs, degenerate repetition loops, chat-template token leaks) rather than papering over a small model's limitations. The commentary is exemplary — nearly every non-obvious decision explains why (the I verified the two highest-risk claims empirically:
Net assessment: clear net-positive to code health. Findings below are refinements, none blocking. Code Review Findings🟡 Important — Summarization can split an assistant tool-call turn from its tool results (orphan-history regression risk)📁
let keep_count = 3.min(session.messages.len());
let split_point = session.messages.len() - keep_count;
let older_messages = session.messages.drain(..split_point).collect();The whole premise of this PR is that the history must be structurally well-formed: every Recommendation: When choosing 🟡 Important — Empty-content tool-call turns are summarized losslessly to nothing📁
summary_input.push_str(&format!("{}: {}\n", role_str, msg.content));Now that assistant tool-call turns persist with empty content (the intentional turn-structure fix at line 334-339), any such turn that falls into Recommendation: When 🟡 Important —
|
malibio
left a comment
There was a problem hiding this comment.
Initial pragmatic review posted as a PR comment. Recommendation: COMMENT (approve-leaning) — no blocking issues. Please acknowledge/track the two Important findings on the summarization path (agent_loop.rs:587-591 orphan-history split, and 594-603 lossy summary of empty-content tool-call turns) before merge; both are fair as fast follow-ups.
…tranded DB prompt edit Code review (PR #1331) findings: 🟡 maybe_summarize_history could split an assistant tool-call turn from its tool results — the naive "keep last 3" drain can leave the kept window starting with an orphan Tool message, the exact malformed sequence that re-triggers the runaway this PR fixes. Walk the split point back past any leading Tool message so every tool result stays paired with its assistant turn. New test: summarization_never_orphans_a_tool_result. 🟡 Empty-content tool-call turns summarized to a bare "Assistant:", losing the signal of what the agent did. Render a synthetic "called tools: …" line from tool_calls when content is empty. 🟡 Documented why the summarization max_tokens (4096) intentionally differs from the chat-turn cap (MAX_RESPONSE_TOKENS=2048) so a future cleanup doesn't wrongly unify them; noted MAX_RESPONSE_TOKENS also bounds a single tool call's generated arguments and is sized for the largest realistic blob. 🟢 Extracted the OAI message-shaping into a pure, model-independent chat_message_to_oai_value() and added a direct test block covering empty-content→null and non-object-arguments→"{}" (the two shapings whose regression reintroduces the turn-aborting ffi error -3). 🟢 Corrected the tool-call-prose regex comment (two nested levels, not one; noted the truncated-blob fallthrough and the DFA/no-ReDoS property). Also backports a prompt edit that was made live in the real DB and never captured in code: the "Research & Search" skill's SEARCH FIRST guidance now includes "Skip search for conversational messages or capability questions" (found by diffing ~/.nodespace prompt/skill node content against the seeds). Skipped (with reasons): the repetition-penalty A/B note is already tracked in #1329; the content/tool_calls invariant the reviewer flagged needs no action (the null-content branch only fires when tool_calls is non-empty). Tests: agent 233, nlp-engine 66 — all pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`cargo fmt --all` (via quality:fix) repeatedly flagged a non-canonical multi-line struct variant in db/events.rs that predates this branch. Apply the canonical single-line form so the workspace is rustfmt-clean and a future `cargo fmt --check` in CI won't fail on it. Formatting-only; no logic change. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Review feedback addressed (commits
|
Pragmatic Code Review — PR #1331 (Re-Review)Review Type: Re-Review Previous Review SummaryThe initial review (COMMENTED, approve-leaning) raised 5 findings: 3 🟡 Important on the summarization path and 2 🟢 minor. This delta addresses all 5. 4 are properly addressed; 1 (the orphan-tool back-off) ships a correct fix but a non-exercising test. No new blocking issues. Per-Finding Verification🟡 #1 — Summarization could orphan a tool-call turn →
🟡 #2 — Empty-content tool-call turns summarized to bare "Assistant:" → ✅ Addressed
🟡 #3 — MAX_RESPONSE_TOKENS asymmetry → ✅ Addressed (docs)
🟢 #4 — Engine-side template test → ✅ Addressed
🟢 #5 — Regex comment accuracy → ✅ Addressed
Bonus — events.rs (
Bonus — skill_pipeline.rs prompt edit → ✅ Sensible
New Findings (introduced by the delta)🟡 [Improvement] — Nitpicks
RecommendationCOMMENT (approve-leaning). All five prior findings are resolved in the shipping code; the only material gap is that the headline orphan-prevention test is a tautology. The fix itself is correct and the runaway path is closed — but I recommend strengthening the test fixture before merge so the protection is actually guarded against regression. Not a blocker. |
malibio
left a comment
There was a problem hiding this comment.
Re-review posted as a PR comment. Recommendation: COMMENT (approve-leaning). All 5 prior findings resolved in shipping code; the back-off fix is correct, but its new test (summarization_never_orphans_a_tool_result) is a tautology — it passes even with the back-off loop removed (verified empirically), because the naive last-3 window lands on the assistant tool-call turn, not a Tool message. Recommend strengthening the fixture before merge. Not a blocker.
…he fix Re-review (PR #1331) found the new summarization_never_orphans_a_tool_result test was a tautology — its 3-message tail put the naive split on the assistant tool-call turn, so the back-off loop never fired and the test passed even with the fix removed. - Rework the fixture: tail is now [assistant tool-call, tool, user, user] so the "keep last 3" window STARTS on the orphan tool result, forcing the back-off to run. Verified the test FAILS when the back-off loop is disabled and passes when present — it now genuinely guards the fix. - Add an explicit assertion that the assistant tool-call turn was RETAINED (not drained), proving the back-off pulled it into the kept window. Also addresses the two re-review nits: - Short-circuit summarization when the back-off consumes the whole prefix (split_point == 0) — no model call on empty input. - Cap each tool-call argument blob to 120 chars in the summary input (a call can emit up to the generation token cap of JSON; the summary only needs the gist). Tests: agent 233 — all pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Re-review feedback addressed (commit pushed)🟡 Tautological orphan test → fixed. The fixture now uses a 4-message tail Nits, both addressed:
Tests: agent 233 — all pass. The summarization back-off (the runaway-prevention path) is now regression-guarded. |
…une prompts (#1331) * WIP: ai-chat agent quality — embedding/tool-call fixes + CLI test harness ## Completed in This Session - [x] Fix release-build compile error on main: node_to_proto(node.clone(), None, None) → 1-arg call in packages/daemon/src/services/node_service.rs (leftover from #1322). - [x] Fix embedding_service:None production bug: GraphToolExecutor in local_agent_service.rs replace_engine was built with embedding_service:None, so search_semantic ALWAYS errored and skill-based select_tools routing was bypassed (full 13-tool list always sent). Now reads inner.embedding_service. Durable fix tracked in #1328. - [x] Add tool_calls to ChatMessage (agent_types.rs) + ChatMessageInput (nlp-engine/chat/types.rs, new ToolCallInput), populate in agent_loop when the assistant issues tool calls, plumb into apply_chat_template's messages JSON so the assistant turn emits OpenAI-format tool_calls (was dropping them → orphan tool result in re-prompt history). Added ChatMessage constructors (text / assistant_with_tool_calls / tool_result). - [x] New CLI subcommand `nodespace model {list|load|recommended}` (cli/commands/model.rs) — the CLI had no way to load a model; required for headless prompt testing. - [x] New bun harness `bun run chat {new|send <id> <msg>|ask <msg>|show <id>}` (scripts/aichat.ts) — drives an ai-chat node end-to-end via the CLI, no UI, against a throwaway test daemon (/tmp/nodespaced-test). - [x] Filed 4 parallel tech-debt issues: #1325 (unify ChatMessage/ChatMessageInput), #1326 (single tool registry), #1327 (delete duplicated fallback prompt), #1328 (embedding service wired by construction). ## Root Cause Found (NOT yet fixed) — the hang/runaway On a greeting ("Hi there"), Gemma-4-E4B emits chatty prose AND a needless search_semantic call in the SAME turn. On re-prompt, Gemma's chat template collapses tool_call + tool_response + the greeting into ONE malformed `model` turn, then opens a fresh empty `model` turn. With nothing to say and no token cap, the model runs away to max_tokens=16384 (multi-minute hang → "no reply"). Verified by logging the full templated prompt (temp logging since removed). ## Remaining Work (user wants ALL three) 1. max_tokens safety cap: agent_loop.rs has max_tokens: Some(16384) at two InferenceRequest sites — lower to ~2048 so any runaway is bounded to seconds. 2. Prompt/skill tuning (live in DB, then backport to seed_prompt_nodes() in prompt_assembler.rs + skill seeds in skill_pipeline.rs): conversational turns skip tools; empty tool result → answer directly, never retry; less verbosity; "create an invoice tracking database" → create_schema. Build a fuller scenario matrix (create several custom node types via NL + CRUD against them). 3. Turn-structure fix: stop sending chatty assistant prose alongside tool calls so the template stops collapsing the turn. Deeper agent_loop surgery. ## Current State - Files modified: agent_types.rs, agent_loop.rs, inference.rs, ollama_integration.rs, local_agent_service.rs, node_service.rs, nlp-engine chat/{mod,types}.rs + lib.rs, cli lib.rs/commands/{mod,model}.rs, package.json, scripts/aichat.ts. - Builds: cargo check + release build of daemon/cli pass. NOT yet run: test:all, quality:fix (clippy). - Tests status: not yet run (WIP checkpoint). - The embedding + tool_calls fixes are verified working at runtime (search_semantic now succeeds, find_skills runs); the runaway is the open problem. ## Context for Next Session Resume the test loop per memory note project-aichat-prompting-session-handoff (how to start a fresh test daemon on /tmp/nodespaced-test, load gemma-4-e4b-q4km via the new `model` CLI command, and drive `bun run chat`). Do the 3 remaining items, then run test:all + quality:fix, and open the PR. Eval-system + model-capability-guardrails issues still to be filed (see memory). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * Fix ai-chat runaway/hang + tool-call template leaks; tune agent prompts Removes the infrastructure-level failure modes in the local ai-chat agent loop that were independent of model size, and tunes the seeded prompts/skills. Loop & sampling: - Cap any single inference round at MAX_RESPONSE_TOKENS=2048 (was 16384), so a runaway is bounded to seconds instead of a multi-minute hang. - Add a repetition penalty to the sampler chain (LlamaSampler::penalties(256, 1.3, 0, 0) before temp) — kills the degenerate loops small models fall into at near-greedy temperature (e.g. repeating a closing phrase until max_tokens). - Persist assistant tool-call turns with empty content (drop chatty prose) so the Gemma chat template stops collapsing prose+call+result into one malformed turn. Chat template (fixes ffi error -3 turn abort introduced by the empty-content change above): - Emit content:null (not "") for assistant tool-call turns — the shape the OAI-compat path expects. - Normalize non-object tool-call arguments to "{}" so a malformed/empty tool call never feeds invalid JSON into the Jinja template. Response normalization (all tested): - Strip leaked Gemma tool-call/response prose (call:foo{...}response:foo{...}, nested braces handled). - Strip Gemma channel/thought reasoning blocks (<|channel>...<channel|>, plus dangling-opener and stray-marker variants). Reasoning capture/display is tracked separately in #1330. - Add <|channel>/<channel|> to strip_gemma_special_tokens for defense in depth. Prompt/skill tuning (seeds re-seed a fresh DB, equivalent to live-editing): - agent_guidance.rs: add "DATABASE = SCHEMA" routing rule (so "create an invoice tracking database" → create_schema) and a loud "conversational turns use NO tools" rule; byte-lock tests updated. - prompt_assembler.rs Response Rules: 1-2 sentences; empty/error tool result → state and stop, no retry, no compensating tool. - skill_pipeline.rs Schema Creation: "ONE SCHEMA PER REQUEST" — no proactive related-type creation. Remaining capability-bound behavior (E4B calls tools on conversational turns, keeps iterating after a complete answer, emits unmarked bare-"thought" narration) is tracked for the 12B A/B in #1329. Tests: agent 232, nlp-engine 61, core 890, frontend 3841, skill 17 — all pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * Address review: protect tool-turn pairing in summarization; capture stranded DB prompt edit Code review (PR #1331) findings: 🟡 maybe_summarize_history could split an assistant tool-call turn from its tool results — the naive "keep last 3" drain can leave the kept window starting with an orphan Tool message, the exact malformed sequence that re-triggers the runaway this PR fixes. Walk the split point back past any leading Tool message so every tool result stays paired with its assistant turn. New test: summarization_never_orphans_a_tool_result. 🟡 Empty-content tool-call turns summarized to a bare "Assistant:", losing the signal of what the agent did. Render a synthetic "called tools: …" line from tool_calls when content is empty. 🟡 Documented why the summarization max_tokens (4096) intentionally differs from the chat-turn cap (MAX_RESPONSE_TOKENS=2048) so a future cleanup doesn't wrongly unify them; noted MAX_RESPONSE_TOKENS also bounds a single tool call's generated arguments and is sized for the largest realistic blob. 🟢 Extracted the OAI message-shaping into a pure, model-independent chat_message_to_oai_value() and added a direct test block covering empty-content→null and non-object-arguments→"{}" (the two shapings whose regression reintroduces the turn-aborting ffi error -3). 🟢 Corrected the tool-call-prose regex comment (two nested levels, not one; noted the truncated-blob fallthrough and the DFA/no-ReDoS property). Also backports a prompt edit that was made live in the real DB and never captured in code: the "Research & Search" skill's SEARCH FIRST guidance now includes "Skip search for conversational messages or capability questions" (found by diffing ~/.nodespace prompt/skill node content against the seeds). Skipped (with reasons): the repetition-penalty A/B note is already tracked in #1329; the content/tool_calls invariant the reviewer flagged needs no action (the null-content branch only fires when tool_calls is non-empty). Tests: agent 233, nlp-engine 66 — all pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * chore: rustfmt events.rs (pre-existing drift) `cargo fmt --all` (via quality:fix) repeatedly flagged a non-canonical multi-line struct variant in db/events.rs that predates this branch. Apply the canonical single-line form so the workspace is rustfmt-clean and a future `cargo fmt --check` in CI won't fail on it. Formatting-only; no logic change. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * Address re-review: make orphan-summarization test actually exercise the fix Re-review (PR #1331) found the new summarization_never_orphans_a_tool_result test was a tautology — its 3-message tail put the naive split on the assistant tool-call turn, so the back-off loop never fired and the test passed even with the fix removed. - Rework the fixture: tail is now [assistant tool-call, tool, user, user] so the "keep last 3" window STARTS on the orphan tool result, forcing the back-off to run. Verified the test FAILS when the back-off loop is disabled and passes when present — it now genuinely guards the fix. - Add an explicit assertion that the assistant tool-call turn was RETAINED (not drained), proving the back-off pulled it into the kept window. Also addresses the two re-review nits: - Short-circuit summarization when the back-off consumes the whole prefix (split_point == 0) — no model call on empty input. - Cap each tool-call argument blob to 120 chars in the summary input (a call can emit up to the generation token cap of JSON; the summary only needs the gist). Tests: agent 233 — all pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Michael Libio <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Summary
Improves local ai-chat agent response quality on Gemma 4 E4B, driven via a headless CLI harness (no UI). Removes the infrastructure-level failure modes that were independent of model size — multi-minute hangs, runaway/repetition loops, and chat-template token leaks — and tunes the seeded prompts/skills.
This builds on the prior WIP commit (
dff3b855: embedding-service fix,tool_callsplumbing,model/chatCLI harness).What changed
Loop & sampling (
agent_loop.rs,chat/mod.rs)MAX_RESPONSE_TOKENS=2048(was 16384) — a runaway is now bounded to seconds, not minutes.penalties(256, 1.3, 0, 0)before temp) — kills degenerate loops small models fall into at near-greedy temperature.Chat template (
chat/mod.rs) — fixes anffi error -3turn abort the empty-content change surfacedcontent: null(not"") for assistant tool-call turns.argumentsto"{}"so a malformed/empty tool call never feeds invalid JSON into the Jinja template.Response normalization (
response_processing.rs, tested)call:foo{...}response:foo{...}, nested braces handled).<|channel>…<channel|>+ dangling/stray variants).<|channel>/<channel|>tostrip_gemma_special_tokens.Prompt/skill tuning (
agent_guidance.rs,prompt_assembler.rs,skill_pipeline.rs)create_schema).Verification
Live matrix on
gemma-4-e4b-q4kmvia the CLI harness: greeting (multi-min hang → ~12s), capability question (no longer loops to the token cap), schema creation (routes tocreate_schema, recovers cleanly, no leaks), instance creation, listing, and empty-result query all functionally correct and clean.Tests: agent 232, nlp-engine 61, core 890, frontend 3841, skill 17 — all pass.
quality:fixclean.Follow-ups (filed)
thoughtnarration) are capability-bound, not infrastructural, and are documented there with the full scenario matrix and a special-token coverage check.🤖 Generated with Claude Code