Repository navigation
feat: route anthropic models through gateway /v1/messages via removable adapter - #962
Merged
Merged
Conversation
…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
marked this pull request as ready for review
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
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.
Contributor
|
🎉 This PR is included in version 0.154.0 🎉 The release is available on: Your semantic-release bot 📦🚀 |
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.
Closes #942
What
Anthropic models (
anthropic/*) now reach the gateway through its nativePOST /v1/messagespassthrough 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 deletinginternal/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
AnthropicMessagesadapter decoratessdk.Clientat the agent's construction seam (container.go). Non-Anthropic providers delegate verbatim. For Anthropic,GenerateContent/GenerateContentStreambuild aCreateMessagesRequestand translate the native Anthropic SSE events back into OpenAI-shaped chunks, soprocessStreamEvent, tool-call accumulation,finalizeStreamand the TUI stay byte-identical. All sixWith*builders are overridden so chains never leak the inner client.<system-reminder>tail is skipped per block so the volatile content never consumes a cache slot.prompt_tokens = input + cache_read + cache_creation,prompt_tokens_details.cached_tokens = cache_read, so the existingC.<n>display works unchanged. Cache-creation tokens flow through a side channel (TakeCacheCreationTokens, consumed via a namedcacheCreationTokenSourceinterface in the agent) into session stats (TotalCacheWriteTokens), cost calculation (billed at the gateway-advertisedcache_write_per_tokenrate, fallback to the input rate) and telemetry (gen_ai.token.type=cache_write).CreateMessage/CreateMessageStreamtypes current).POST /v1/messageswith native Anthropic SSE (message_start/content_block deltas/message_delta/message_stop, no[DONE]), advertisesanthropic/claude-sonnet-4-5with cache read/write pricing, and ships ananthropic-cachescenario - the whole path is hermetically testable.Tests
tests/integration/agent_messages_test.go: full tool loop over real HTTP - thinking/text deltas, fragmentedinput_json_deltareassembly, tool_result round-trip, 3cache_controlmarkers per request with the tail uncached, session token accounting (cached + cache-write), cache-write pricing, syncRunpath.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.