Repository navigation
Description
Summary
Anthropic prompt caching still does not work end-to-end, but the reason has changed since this issue was filed. The gateway-side gap is closed: the gateway now exposes POST /v1/messages (Anthropic Messages API, native passthrough). The remaining work is entirely CLI-side: the CLI still sends every request - including Anthropic models - through the OpenAI-compatible /v1/chat/completions, which cannot carry cache_control breakpoints. For Anthropic models the CLI should route through /v1/messages to get prompt caching (cache reads billed at ~0.1x input rate) and native tool/thinking blocks.
Current state (verified against the code)
Gateway - shipped. POST /v1/messages is registered in cmd/gateway/main.go (handler MessagesHandler, api/routes.go). It is Anthropic-only (other providers get 400 not_supported_error) and a byte-for-byte passthrough: the body is forwarded verbatim (only the anthropic/ model prefix is rewritten), streaming relays native Anthropic SSE unchanged (message_start, content_block_start/delta/stop, message_delta, message_stop, ping), cache_control blocks pass through untouched (the gateway injects nothing), and usage - including cache_read_input_tokens / cache_creation_input_tokens - reaches the client exactly as Anthropic sends it. Same auth, middleware, and telemetry as /v1/chat/completions.
SDK - shipped, no work needed. Since v1.26.0 (the CLI is on v1.28.0) the Go SDK has CreateMessage / CreateMessageStream (-> POST /v1/messages) plus every generated type: CreateMessagesRequest, MessagesMessage and content blocks, MessagesTool, CacheControl (ephemeral), the full MessagesStreamEvent enum, and MessagesUsage with CacheCreationInputTokens / CacheReadInputTokens. sdk.Pricing also already carries CacheWritePerToken next to CacheReadPerToken. Working reference: examples/messages/main.go in the SDK repo.
CLI - cache-ready but on the wrong wire format. PR #941 delivered the prerequisites: byte-stable system prompt (volatile context split into a tail message), deterministically sorted tools, cached-token display (C.<n>), gateway-sourced cache-read pricing. But the request path is provider-agnostic OpenAI shape end to end: GenerateContent / GenerateContentStream only, the SSE parser (processStreamEvent, internal/agent/agent_streaming.go) understands only OpenAI chunk deltas, and usage capture (storeIterationMetrics, internal/agent/agent.go) reads only PromptTokensDetails.CachedTokens - cache reads, no cache-creation/write tokens.
Why /v1/chat/completions cannot deliver this
- The OpenAI request shape has no place for
cache_controlbreakpoints, and the gateway deliberately injects nothing. - OpenAI-shaped usage has no cache-creation field, so cache-write costs (billed at 1.25x input) would be invisible.
- Anthropic tool_use / thinking blocks are lossily flattened into OpenAI deltas.
Proposed scope (CLI only)
- Endpoint selection. In the agent request path (
internal/agent/agent_streaming.gostreaming;internal/agent/agent.gosyncRun): when the parsed provider isanthropic(parseProvider,internal/agent/agent_utils.go), callCreateMessageStream/CreateMessageinstead ofGenerateContentStream/GenerateContent. All other providers unchanged. Automatic per provider - no new config. - Request mapping (one conversion layer,
[]sdk.Message->sdk.CreateMessagesRequest):- system message[0] -> top-level
systemas[]MessagesTextBlockwithcache_control: ephemeralon the last block (this is exactly the stable prefix feat: cache-stable system prompt, gateway-sourced model metadata, and cached-token visibility #941 built); []ChatCompletionTool->[]MessagesTool(name/description/input_schema) withcache_controlon the last tool (tool order is already deterministic);- assistant
tool_calls->tool_useblocks;role: toolmessages -> usertool_resultblocks; - one rolling
cache_controlbreakpoint on the last message of the previous turn so conversation history caches incrementally (Anthropic allows 4 breakpoints; tools + system + rolling = 3 used); max_tokensis mandatory in the Messages API - always set from existing config.
- system message[0] -> top-level
- Streaming decode. A Messages branch in SSE handling: unmarshal
sdk.MessagesStreamEvent; mapcontent_block_deltatext -> content deltas,thinkingdeltas -> existing reasoning events,tool_usestart +input_json_delta-> the existing tool-call accumulator, usage frommessage_start(input + cache fields) andmessage_delta(output) -> the existingfinalizeStreampath. - Usage and cost. Extend usage capture and
SessionTokenStats(internal/domain/interfaces.go) with cache-creation tokens; mapCacheReadInputTokensonto the existing cached-tokens display; extendPricingServiceImpl.CalculateCostandparseGatewayPricing(internal/services/pricing_service.go) to use the already-availableCacheWritePerTokenrate. - Hermetic tests.
internal/mockgatewayserves only/v1/chat/completions; addPOST /v1/messageswith canned Anthropic SSE so integration (tests/integration) and e2e (tests/e2e) suites cover the new path.
Acceptance criteria
- With an Anthropic model via the gateway, turn 2+ of a session reports
cache_read_input_tokens > 0(visible asC.<n>), and cost reflects the cache-read rate. - Cache-creation tokens are captured and priced at the write rate, not silently dropped.
- A full tool loop (tool_use -> tool_result -> continuation) works over
/v1/messages, streaming and sync (infer agent). - Thinking deltas render as reasoning in the TUI.
- Non-Anthropic providers behave byte-identically to today.
- Integration + e2e coverage against the mockgateway
/v1/messagesendpoint.
Out of scope / open questions
- Secondary non-streaming callers (title generator, conversation optimizer, custom shortcuts) stay on
/v1/chat/completions: short, cheap calls with little cache benefit. Follow up only if the mapping layer makes it free. - Fallback when the gateway predates
/v1/messages(404/400): proposal is no silent fallback - surface a clear error naming the minimum gateway version. - Extended thinking over Messages requires round-tripping signed
thinkingblocks through the tool loop; initial version maps thinking for display only.
Cross-repo impact
- gateway / schemas / sdk: none - all shipped.
- docs:
[DOCS]follow-up ticket for inference-gateway/docs once the CLI PR lands (caching behavior + pricing visibility).
Metadata
Metadata
Assignees
Type
Projects
- StatusShow more project fieldsDone
Activity
[-][BUG] Anthropic cache not working - /v1/messages endpoint not implemented in gateway[/-][+][BUG] Anthropic prompt caching not working - route Anthropic models via the gateway /v1/messages endpoint[/+]feat: route anthropic models through gateway /v1/messages via removab…
feat: route anthropic models through gateway /v1/messages via removab…
inference-gateway-releaser commentedon Jul 28, 2026
🎉 This issue has been resolved in version 0.154.0 🎉
The release is available on:
Your semantic-release bot 📦🚀