Repository navigation
feat: cache-stable system prompt, gateway-sourced model metadata, and cached-token visibility - #941
Merged
Merged
Conversation
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
…update related tests
…mpt roster are deterministic
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.
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.
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.
This was referenced Jul 21, 2026
Contributor
|
🎉 This PR is included in version 0.151.0 🎉 The release is available on: Your semantic-release bot 📦🚀 |
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.
3 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:
buildSystemPromptTextis 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).volatileTailMessagebuilds a per-request <system-reminder> user message from the volatile sections (split intovolatileContextSections) plus the date, appended at the tail of the outbound payload only:Run): appended to the request-local slice — covers headlessinfer agent;EventDrivenAgentand appended inopenStreamviaappend(slices.Clone(conv), tail), so the shared persisted conversation is never mutated — including on reconnects and tool-loop turns.agent.context.*/memory.enabledflags keep working — the builders self-gate, a disabled section is absent from the tail.infer debug agent system_promptstill renders the full picture (static prompt + tail), and--tokensaccounts for the volatile sections.Acceptance criteria (from #938)
TestStreamSystemPromptStableWithVolatileTailasserts byte-equality across all 3 requests of a tool-loop session)TestSyncRunAppendsVolatileTail,TestVolatileTailMessage)TestOutboundConversation_AppendsTailWithoutMutatingShared)agent.context.*flags keep working (TestVolatileTailMessagegating subtests)examples/working-offlineagainst 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:
C.<n>status-bar segment next toT.<n>(hidden at zero) andCached: n tokensin per-request metrics; mockgateway scenarios acceptusage.cached_tokens.GetToolDefinitionssorts 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]./v1/modelsis fetched withinclude=context_window,pricing; gateway-reported context windows and prices are the primary source of truth. The status-barContext: %, the/modelpicker rows and pricing tabs, and cost calculation all use live per-model data.CalculateCostbills cached prompt tokens at the gatewaycache_read_per_tokenrate (full input rate when unknown); telemetry emits acache_readtoken datapoint andinfer stats//statsgain a Cached column.Removed
config.DefaultModelPricing(~910 lines): the hardcoded model pricing map, superseded by gateway-sourced pricing. Theconfig.ModelPricingtype (used only by this map) is also removed.config.ContextMatchers(~40 lines): the pattern-based context window matchers, superseded by gateway-sourced context windows. Theconfig.ModelMatchertype is also removed.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/compactstill works), the status-bar context indicator is hidden, and/contextsays compaction is disabled for the model.freeLocalProviders: llamacpp/ollama models are no longer assumed free; they resolve as unknown pricing unless declared viacustom_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 reportrequires_proyet; moving that server-side (schemas → sdk → gateway) is a drafted follow-up.Cross-repo impact
CompletionUsagetoken details and the/v1/modelsmetadata this PR consumes.ollama_cloudfrom the streamingstream_optionsexception — the [BUG] Multiple tools getting executed are rendered in flickery order #207 rationale is stale (Ollama now supportsinclude_usage), and without it ollama_cloud streams carry no usage/cached-token chunk at all.Testing
task test,task test:e2e, andtask lintall green.