Skip to content

Reuse KV cache across ReAct loop iterations to eliminate prompt re-processing #1288

Closed

Description

@malibio

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 call

The 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:

  1. After the first inference pass, record n_cached = system_prompt_tokens + tool_tokens
  2. On subsequent passes, only decode tokens beyond n_cached (the new conversation history)
  3. 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::generate called per iteration
  • Context state: packages/nlp-engine/src/chat/mod.rs — ChatLlamaState struct

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

Activity

  1. malibio commented on Jun 1, 2026

    @malibio
    CollaboratorAuthor

    Frontend baseline: 132 test files, 3836 tests passed

  2. self-assigned this
    on Jun 1, 2026
  3. added a commit that references this issue on Jun 2, 2026
    79b9a57
  4. added a commit that references this issue on Jun 22, 2026
    d6121e4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions