Skip to content

feat: route anthropic models through gateway /v1/messages via removable adapter - #962

Merged
edenreich merged 2 commits into
mainfrom
feat/942-anthropic-messages-adapter
Jul 28, 2026
Merged

edenreich merged 2 commits into
mainfrom
feat/942-anthropic-messages-adapter

Conversation

@edenreich

Copy link
Copy Markdown
Contributor

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 feat: cache-stable system prompt, gateway-sourced model metadata, and cached-token visibility #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.

…le adapter

Anthropic prompt caching never engaged because every request went through
the OpenAI-compatible /v1/chat/completions endpoint, which cannot carry
cache_control breakpoints. The agent's SDK client is now wrapped in an
AnthropicMessages adapter that sends anthropic/* models to the gateway's
native POST /v1/messages passthrough and translates the Anthropic SSE
stream back into OpenAI-shaped chunks, leaving the downstream stream
processing, tool-call accumulation and TUI untouched. Non-Anthropic
providers delegate verbatim; removing the integration is deleting the
adapter files and reverting one container line.

The adapter places three cache breakpoints: the system prompt, the last
tool definition, and a rolling breakpoint on the newest non-volatile
content block, skipping the injected <system-reminder> tail so it never
consumes a cache slot. Cache-read tokens surface through the existing
cached-tokens path; cache-creation tokens flow through a new side channel
into session stats, cost calculation (billed at the gateway-advertised
cache_write_per_token rate) and telemetry.

The mock gateway now serves POST /v1/messages with native Anthropic SSE
and an anthropic-cache scenario, so the whole path is covered hermetically
by unit, integration and e2e tests.

Closes #942
@edenreich
edenreich marked this pull request as ready for review July 28, 2026 13:13
@edenreich
edenreich requested a review from a team as a code owner July 28, 2026 13:13
…le adapter

Anthropic prompt caching never engaged because every request went through
the OpenAI-compatible /v1/chat/completions endpoint, which cannot carry
cache_control breakpoints. The agent's SDK client is now wrapped in an
AnthropicMessages adapter that sends anthropic/* models to the gateway's
native POST /v1/messages passthrough and translates the Anthropic SSE
stream back into OpenAI-shaped chunks, leaving the downstream stream
processing, tool-call accumulation and TUI untouched. Non-Anthropic
providers delegate verbatim; removing the integration is deleting the
adapter files and reverting one container line.

The adapter places three cache breakpoints: the system prompt, the last
tool definition, and a rolling breakpoint on the newest non-volatile
content block, skipping the injected <system-reminder> tail so it never
consumes a cache slot. Cache-read tokens surface through the existing
cached-tokens path; cache-creation tokens flow through a new side channel
into session stats, cost calculation (billed at the gateway-advertised
cache_write_per_token rate) and telemetry.

The mock gateway now serves POST /v1/messages with native Anthropic SSE
and an anthropic-cache scenario, so the whole path is covered hermetically
by unit, integration and e2e tests.

Closes #942
@edenreich
edenreich merged commit 6c99269 into main Jul 28, 2026
1 check passed
@edenreich
edenreich deleted the feat/942-anthropic-messages-adapter branch July 28, 2026 16:02
edenreich added a commit that referenced this pull request Jul 28, 2026
#963)

Stacked on #962 (base branch `feat/942-anthropic-messages-adapter`).

## What

New `/effort` chat command that switches the reasoning effort level at
runtime for Anthropic models, delivered on the wire as
`output_config.effort` over the native `POST /v1/messages` path.
`/effort` with no argument shows the current level and the available
ones; `/effort <level>` switches it for subsequent requests. Levels
autocomplete (`low | medium | high | xhigh | max`). Non-Anthropic models
are rejected with `not supported`.

The CLI hardcodes `low` as its Anthropic default
(`config.DefaultAnthropicEffort`) - deliberately below the API default
of `high` - so every `/v1/messages` request carries an explicit
`output_config.effort`. A status-bar indicator (`Effort: <level>`, own
config toggle `chat.status_bar.indicators.effort`) shows the level in
effect next to the model, for Anthropic models only.

## How

- `agent.reasoning_effort` config remains the startup seed; the accepted
set is extended with `xhigh` and `max` (`config.ReasoningEffortLevels`
is now the single source for validation, the setter, and the shortcut).
- `domain.AgentService` gains `SetReasoningEffort`/`GetReasoningEffort`;
`AgentServiceImpl` guards the level with an RWMutex and both request
paths re-read it per request, so a mid-session switch applies to the
next turn.
- The `AnthropicMessages` adapter maps the captured `reasoning_effort`
onto `output_config.effort` in `buildMessagesRequest` (`minimal` maps to
`low` - Anthropic's scale starts at `low`; unset and unknown values fall
back to the hardcoded `low` default).
- The status bar reads the live level through a narrow `effortSource`
interface and gates on the current model's provider prefix, so the
indicator follows `/model` switches and mid-session `/effort` changes.
- Non-Anthropic providers clamp `xhigh`/`max` to `high` on the
chat-completions path as a safety net (relevant when effort was set on
an Anthropic model and the user then `/model`-switches away).
- Fixes a builder-chain drop on the sync path: `Run` restarted the chain
from the bare client when tools were present (`s.client.WithTools`),
silently discarding `MaxTokens`, `ReasoningEffort` and `SkipMCP`; it now
chains like the streaming path.
- SDK bumped v1.29.0 -> v1.30.0 (types-only sync with schemas v0.16.0,
brings `MessagesOutputConfig`).

## Tests

- Shortcut unit tests: show current/default, lowercased set on Anthropic
model, `not supported` rejection on non-Anthropic, invalid-level error,
arg bounds.
- Agent unit tests: setter validation/reset, per-provider effort mapping
(Anthropic passthrough incl. `minimal`, clamping elsewhere).
- Adapter table test: `output_config.effort` on the marshaled request
for every level, `minimal -> low`, absent when unset or unknown.
- Integration (`tests/integration/agent_messages_test.go`): runtime
switch to `xhigh` lands on both recorded `/v1/messages` bodies of a tool
round-trip.
- `task test`, `task test:e2e`, `task lint`, `task fmt` all green.

## Cross-repo impact

- `schemas` inference-gateway/schemas#161 (merged, v0.16.0) added
`output_config.effort` to `CreateMessagesRequest`.
- `sdk` inference-gateway/sdk#148 (merged, v1.30.0) synced the generated
types.
- Gateway needs no change: `/v1/messages` forwards bodies verbatim.
- Follow-up: `[DOCS]` issue for inference-gateway/docs covering
`/effort` and the extended `agent.reasoning_effort` values.
@inference-gateway-releaser

Copy link
Copy Markdown
Contributor

🎉 This PR is included in version 0.154.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 28, 2026
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

None yet

Development

Successfully merging this pull request may close these issues.

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

1 participant