Repository navigation
Description
Overview
Every inference round in the ReAct loop calls ctx.clear_kv_cache() before processing, discarding the KV cache from the previous turn. This means the full system prompt (5362 tokens on a fresh DB) is re-tokenized and re-processed on every iteration. With a 5-iteration ReAct loop, the same 5362-token prefix is decoded 5× per user message.
Problem Statement
packages/nlp-engine/src/chat/mod.rs — generate_blocking():
ctx.clear_kv_cache();
// ... full prompt tokenized and decoded from scratch every callThe system prompt + tool definitions are stable within a session (same content every iteration). Only the conversation history grows. Clearing the KV cache forces llama.cpp to recompute attention for the entire stable prefix on every turn.
Cost on M2 Pro 16GB with Gemma 4 E4B:
- 5362 prompt tokens × 5 iterations = 26,810 tokens of redundant KV computation per user message
- Observed TTFT: ~7.8s — almost entirely prompt processing
Proposed Solution
Preserve the KV cache across iterations within a session by tracking how many tokens of the prompt prefix are stable between turns:
- After the first inference pass, record
n_cached = system_prompt_tokens + tool_tokens - On subsequent passes, only decode tokens beyond
n_cached(the new conversation history) - Clear the cache only when the system prompt changes (new session, schema change) or context window approaches capacity
llama.cpp supports this natively — ctx.clear_kv_cache() is the nuclear option; more precise APIs allow partial cache invalidation.
Acceptance Criteria
- System prompt tokens are decoded only once per session (not once per ReAct iteration)
- Subsequent iterations only process the delta (new tool results + user turn)
- TTFT on second+ iteration measurably lower than first
- No correctness regression (tool calls still parse correctly, responses unchanged)
- KV cache is cleared on session end or context overflow
Technical Specifications
Reference Files
- Generation loop:
packages/nlp-engine/src/chat/mod.rs—generate_blocking(),ctx.clear_kv_cache()call - Agent loop:
packages/agent/src/local_agent/agent_loop.rs—ChatInferenceEngine::generatecalled per iteration - Context state:
packages/nlp-engine/src/chat/mod.rs—ChatLlamaStatestruct
Key change
ChatLlamaState needs a cached_prompt_len: usize field. On first call, populate and cache. On subsequent calls with the same system prompt prefix, only add the delta tokens to the batch.
Related Issues
- Daemon should bind gRPC socket before embedding model loads #1287 (daemon startup — same theme of reducing cold-start latency)
- Verify Gemma 4 and Mistral chat-template path on real Apple Silicon hardware (follow-up to #1094) #1142 (discovered during Gemma 4 verification)
Activity
malibio commentedon Jun 1, 2026
Frontend baseline: 132 test files, 3836 tests passed
Reuse KV cache across ReAct loop iterations to eliminate prompt re-pr…
Reuse KV cache across ReAct loop iterations to eliminate prompt re-pr…