Skip to content

feat: cache-stable system prompt, gateway-sourced model metadata, and cached-token visibility - #941

Merged
edenreich merged 11 commits into
mainfrom
feat/938-cache-stable-prompt
Jul 21, 2026
Merged

edenreich merged 11 commits into
mainfrom
feat/938-cache-stable-prompt

Conversation

@edenreich

@edenreich edenreich commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes #938.

The agent rebuilt message[0] (system prompt) every user turn with volatile content, so local LLM servers (Ollama, llama.cpp) re-prefilled the entire ~8k-token prompt on every request. This PR keeps the context fresh AND the prefix stable:

  • buildSystemPromptText is now static — the five volatile pieces (git context, project tree, memory index, active skill, current date) are removed from the system prompt, making message[0] byte-identical across turns (including day rollover).
  • New volatileTailMessage builds a per-request <system-reminder> user message from the volatile sections (split into volatileContextSections) plus the date, appended at the tail of the outbound payload only:
    • sync path (Run): appended to the request-local slice — covers headless infer agent;
    • streaming path: stashed on EventDrivenAgent and appended in openStream via append(slices.Clone(conv), tail), so the shared persisted conversation is never mutated — including on reconnects and tool-loop turns.
  • The tail is never persisted and never enters the TUI; mockgateway scenario anchoring already skips <system-reminder> user messages.
  • agent.context.* / memory.enabled flags keep working — the builders self-gate, a disabled section is absent from the tail.
  • infer debug agent system_prompt still renders the full picture (static prompt + tail), and --tokens accounts for the volatile sections.

Acceptance criteria (from #938)

  • message[0] byte-identical across turns (unit + integration: TestStreamSystemPromptStableWithVolatileTail asserts byte-equality across all 3 requests of a tool-loop session)
  • Volatile context still reaches the model each turn at the tail (TestSyncRunAppendsVolatileTail, TestVolatileTailMessage)
  • Tail not persisted / not rendered (TestOutboundConversation_AppendsTailWithoutMutatingShared)
  • mockgateway anchoring unaffected (existing skip covers it; integration suite green)
  • agent.context.* flags keep working (TestVolatileTailMessage gating subtests)
  • Manual verification with examples/working-offline against local Ollama (the feat(agent): reasoning_effort config + working-offline example #937 workaround env vars remain valid but are no longer necessary)

Gateway model metadata + cached-token visibility

The caching this PR makes possible is now also observable and priced correctly:

  • Cached-token display: C.<n> status-bar segment next to T.<n> (hidden at zero) and Cached: n tokens in per-request metrics; mockgateway scenarios accept usage.cached_tokens.
  • Deterministic tools order: GetToolDefinitions sorts by function name, so the outbound tools array (and the system-prompt roster) stays byte-stable across turns and restarts — required for provider KV-cache hits beyond message[0].
  • Gateway model metadata (SDK v1.23.0 → v1.25.0): /v1/models is fetched with include=context_window,pricing; gateway-reported context windows and prices are the primary source of truth. The status-bar Context: %, the /model picker rows and pricing tabs, and cost calculation all use live per-model data.
  • Cache-aware cost: CalculateCost bills cached prompt tokens at the gateway cache_read_per_token rate (full input rate when unknown); telemetry emits a cache_read token datapoint and infer stats / /stats gain a Cached column.

Removed

  • config.DefaultModelPricing (~910 lines): the hardcoded model pricing map, superseded by gateway-sourced pricing. The config.ModelPricing type (used only by this map) is also removed.
  • config.ContextMatchers (~40 lines): the pattern-based context window matchers, superseded by gateway-sourced context windows. The config.ModelMatcher type is also removed.
  • Corresponding test coverage: per-family context window tests (Qwen, Claude, Moonshot, Gemini, Deep Research, Gemma, DeepSeek, Mistral, MiniMax, GLM, Nemotron, GPT-OSS, llama, phi), Ollama Cloud Pro defaults test, and static default price assertions in Google model defaults and Minimax defaults tests — all updated or deleted.
  • config.DefaultContextWindow (8192 fallback): models with no gateway-reported and no user-configured (context_windows:) window are now unknown — auto-compaction and token-triggered session rollover gate off (manual /compact still works), the status-bar context indicator is hidden, and /context says compaction is disabled for the model.
  • freeLocalProviders: llamacpp/ollama models are no longer assumed free; they resolve as unknown pricing unless declared via custom_prices:.
  • IsVisionModel + the 25-pattern vision table: the "model may not support vision" chat warning is removed; images are always forwarded and the provider decides.

The only remaining curated entries are knownProModels (2 lines) — the gateway does not report requires_pro yet; moving that server-side (schemas → sdk → gateway) is a drafted follow-up.

Cross-repo impact

  • schemas v0.9.0 → sdk v1.25.0 → gateway v0.35.1 already ship the CompletionUsage token details and the /v1/models metadata this PR consumes.
  • Gateway follow-up (prepared, not yet pushed): drop ollama_cloud from the streaming stream_options exception — the [BUG] Multiple tools getting executed are rendered in flickery order #207 rationale is stale (Ollama now supports include_usage), and without it ollama_cloud streams carry no usage/cached-token chunk at all.

Testing

task test, task test:e2e, and task lint all green.

Move the volatile context sections (git context, project tree, memory
index, active skill, current date) out of the system prompt into a
per-request <system-reminder> user message appended at the tail of the
outbound payload. message[0] is now byte-identical across turns, so
local LLM servers (Ollama, llama.cpp) get KV-cache prefix hits instead
of re-prefilling the full prompt every turn.

The tail is never persisted to the conversation store and never added
to the shared conversation slice, so it is invisible to the TUI and to
later turns; mockgateway scenario anchoring already skips
<system-reminder> user messages. Existing agent.context.* flags keep
working - a disabled section is simply absent from the tail. The
'infer debug agent system_prompt' view still renders the full picture
(static prompt plus tail).

Closes #938
@edenreich
edenreich requested a review from a team as a code owner July 19, 2026 23:36
Bumps the SDK to v1.23.0 (CompletionUsage now carries
prompt_tokens_details) and threads provider-reported cache hits through
to the TUI: storeIterationMetrics accumulates them via the new
AddCachedTokens into SessionTokenStats.TotalCachedTokens, and the
status bar renders a C.<n> segment next to T.<n>, hidden while zero,
under the existing session_tokens indicator toggle. FormatMetrics gains
a guarded Cached part. The mock gateway accepts cached_tokens in
scenario usage so the flow is asserted end-to-end over real HTTP.
@edenreich edenreich moved this from Todo to In progress in 2026 Jul 20, 2026
@edenreich edenreich moved this from In progress to QA in 2026 Jul 20, 2026
Bump the SDK to v1.25.0 and fetch /v1/models with
include=context_window,pricing. Gateway-reported windows and prices feed
the shared lookups (user config still wins; the static tables remain the
fallback), so the status bar Context %, the model picker, and cost
calculation all use live per-model data. CalculateCost gains a
cachedTokens param billed at the gateway cache-read rate, telemetry
records a cache_read datapoint, and the stats Token Usage views gain a
Cached column.
@edenreich edenreich changed the title feat(agent): cache-stable system prompt with volatile context tail feat: cache-stable system prompt, gateway-sourced model metadata, and cached-token visibility Jul 21, 2026
The refactor that removed hardcoded model context matchers
(cc32ef5) left consumers gating on the 'known' flag from
LookupContextWindow. For models not reported by the gateway
and not configured by the user, this meant:

- Session rollover never fired (conversations grew unbounded)
- Context usage indicator was empty
- /context shortcut showed 'unknown for this model'
- Auto-compaction was silently disabled

Fix: remove the !known guard from all four consumers so they
use the default fallback (8192) instead of disabling their
feature. The default is conservative — it'll trigger rollover
early for large-context models — but that's safer than never
triggering.

Update tests to set up gateway context windows where they
expect specific percentages, and update the 'unlisted model'
rollover test to expect the default to be used.
…metadata

Remove the last hardcoded model defaults:

- DefaultContextWindow (8192) is gone; LookupContextWindow returns
  (0, false) for models the gateway does not report and the user has
  not configured, so auto-compaction, token-triggered rollover and the
  context indicator gate off instead of measuring against a guess.
- freeLocalProviders is gone; llamacpp/ollama models resolve as unknown
  pricing unless custom_prices declares them.

Tests seed models.SetGatewayContextWindows where they rely on a window.
@edenreich
edenreich merged commit ef0f69e into main Jul 21, 2026
1 check passed
@edenreich
edenreich deleted the feat/938-cache-stable-prompt branch July 21, 2026 01:21
@inference-gateway-releaser

Copy link
Copy Markdown
Contributor

🎉 This PR is included in version 0.151.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

@inference-gateway-releaser inference-gateway-releaser Bot added the released Shipped in a release label Jul 21, 2026
@edenreich edenreich moved this from QA to Done in 2026 Jul 21, 2026
edenreich added a commit that referenced this pull request Jul 28, 2026
…le adapter (#962)

Closes #942

## What

Anthropic models (`anthropic/*`) now reach the gateway through its
native `POST /v1/messages` passthrough instead of the OpenAI-compatible
`/v1/chat/completions`, enabling Anthropic prompt caching. Built as a
removable adapter per the issue's constraint: the endpoint is
non-OpenAI-standard, so pulling it out is deleting
`internal/infra/adapters/anthropic_messages.go` (+ test) and reverting
one line in the container, plus the small cache-write side-channel read
in the agent.

## How

- **`AnthropicMessages` adapter** decorates `sdk.Client` at the agent's
construction seam (`container.go`). Non-Anthropic providers delegate
verbatim. For Anthropic, `GenerateContent`/`GenerateContentStream` build
a `CreateMessagesRequest` and translate the native Anthropic SSE events
back into OpenAI-shaped chunks, so `processStreamEvent`, tool-call
accumulation, `finalizeStream` and the TUI stay byte-identical. All six
`With*` builders are overridden so chains never leak the inner client.
- **Cache breakpoints (3 of the 4 slots)**: system prompt block, last
tool definition (tool order is already deterministic per #941), and a
rolling breakpoint on the newest non-volatile content block - the
injected `<system-reminder>` tail is skipped per block so the volatile
content never consumes a cache slot.
- **Usage synthesis**: `prompt_tokens = input + cache_read +
cache_creation`, `prompt_tokens_details.cached_tokens = cache_read`, so
the existing `C.<n>` display works unchanged. Cache-creation tokens flow
through a side channel (`TakeCacheCreationTokens`, consumed via a named
`cacheCreationTokenSource` interface in the agent) into session stats
(`TotalCacheWriteTokens`), cost calculation (billed at the
gateway-advertised `cache_write_per_token` rate, fallback to the input
rate) and telemetry (`gen_ai.token.type=cache_write`).
- **SDK bumped** v1.28.0 -> v1.29.0 (types-only sync with schemas
v0.15.3, brings `CreateMessage`/`CreateMessageStream` types current).
- **Mock gateway** now serves `POST /v1/messages` with native Anthropic
SSE (message_start/content_block deltas/message_delta/message_stop, no
`[DONE]`), advertises `anthropic/claude-sonnet-4-5` with cache
read/write pricing, and ships an `anthropic-cache` scenario - the whole
path is hermetically testable.

## Tests

- Adapter unit tests: request mapping (breakpoints, tool_result
grouping, adjacent-role merging, volatile-tail skip), stream translation
goldens (multi-tool index remapping, usage synthesis, error events),
sync translation, passthrough, builder-chain identity.
- `tests/integration/agent_messages_test.go`: full tool loop over real
HTTP - thinking/text deltas, fragmented `input_json_delta` reassembly,
tool_result round-trip, 3 `cache_control` markers per request with the
tail uncached, session token accounting (cached + cache-write),
cache-write pricing, sync `Run` path.
- Full suite green: `task test`, `task test:e2e`, `task lint`, `task
fmt`.

## Cross-repo impact

None to ship - gateway passthrough, SDK v1.29.0 and schemas are already
released. Follow-up: `[DOCS]` note for inference-gateway/docs describing
the Anthropic routing and cache accounting.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

released Shipped in a release

Projects

No open projects
Status: Done

Development

Successfully merging this pull request may close these issues.

[FEATURE] Cache-stable prompts: move volatile context sections out of the system prompt

1 participant