Skip to content

[BUG] Anthropic prompt caching not working - route Anthropic models via the gateway /v1/messages endpoint #942

Closed

Description

@edenreich

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_control breakpoints, 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)

  1. Endpoint selection. In the agent request path (internal/agent/agent_streaming.go streaming; internal/agent/agent.go sync Run): when the parsed provider is anthropic (parseProvider, internal/agent/agent_utils.go), call CreateMessageStream / CreateMessage instead of GenerateContentStream / GenerateContent. All other providers unchanged. Automatic per provider - no new config.
  2. Request mapping (one conversion layer, []sdk.Message -> sdk.CreateMessagesRequest):
    • system message[0] -> top-level system as []MessagesTextBlock with cache_control: ephemeral on 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) with cache_control on the last tool (tool order is already deterministic);
    • assistant tool_calls -> tool_use blocks; role: tool messages -> user tool_result blocks;
    • one rolling cache_control breakpoint on the last message of the previous turn so conversation history caches incrementally (Anthropic allows 4 breakpoints; tools + system + rolling = 3 used);
    • max_tokens is mandatory in the Messages API - always set from existing config.
  3. Streaming decode. A Messages branch in SSE handling: unmarshal sdk.MessagesStreamEvent; map content_block_delta text -> content deltas, thinking deltas -> existing reasoning events, tool_use start + input_json_delta -> the existing tool-call accumulator, usage from message_start (input + cache fields) and message_delta (output) -> the existing finalizeStream path.
  4. Usage and cost. Extend usage capture and SessionTokenStats (internal/domain/interfaces.go) with cache-creation tokens; map CacheReadInputTokens onto the existing cached-tokens display; extend PricingServiceImpl.CalculateCost and parseGatewayPricing (internal/services/pricing_service.go) to use the already-available CacheWritePerToken rate.
  5. Hermetic tests. internal/mockgateway serves only /v1/chat/completions; add POST /v1/messages with 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 as C.<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/messages endpoint.

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 thinking blocks 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).

Activity

  1. added
    bug
    on Jul 20, 2026
  2. added theissue type on Jul 20, 2026
  3. moved this to Todo in 2026on Jul 20, 2026
  4. moved this from Todo to In progress in 2026on Jul 21, 2026
  5. changed the title [-][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[/+] on Jul 28, 2026
  6. moved this from In progress to Todo in 2026on Jul 28, 2026
  7. moved this from Todo to In progress in 2026on Jul 28, 2026
  8. moved this from In progress to QA in 2026on Jul 28, 2026
  9. added a commit that references this issue on Jul 28, 2026
    edee858
  10. added a commit that references this issue on Jul 28, 2026
    6c99269
  11. moved this from QA to Done in 2026on Jul 28, 2026
  12. inference-gateway-releaser commented on Jul 28, 2026

    @inference-gateway-releaser
    Contributor

    🎉 This issue has been resolved in version 0.154.0 🎉

    The release is available on:

    Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugreleased

    Type

    Projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions