Skip to content

feat(gateway): route OpenAI protocol requests to Anthropic providers - #437

Open
kiddyt00 wants to merge 11 commits into
astaxie:mainfrom
kiddyt00:feat/anthropic-openai-protocol-bridge
Open

kiddyt00 wants to merge 11 commits into
astaxie:mainfrom
kiddyt00:feat/anthropic-openai-protocol-bridge

Conversation

@kiddyt00

@kiddyt00 kiddyt00 commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

feat(gateway): route OpenAI protocol requests to Anthropic providers

Summary

Models advertising the OpenAI Chat Completions or Responses endpoints could not be routed to a native Anthropic provider. The Anthropic adapter already converts Chat Completions and Responses requests, responses, usage, and streaming events to the Anthropic Messages wire format, but it declared only the anthropic route protocol. Because an explicit route protocol declaration overrides capability-derived protocols, the admin route validation rejected such mappings with route_protocol_mismatch, so these models showed up as unavailable on the OpenAI-compatible /v1 endpoints. Declaring the protocols the adapter actually implements closes the gap; the existing gateway execution path picks up the conversion automatically.

Related Issue

N/A

Changes

  • Declare chat/completions and responses in addition to anthropic in the built-in Anthropic adapter route protocols
  • Add end-to-end gateway tests covering non-streaming and streaming Chat Completions requests routed to a fake native Anthropic upstream, asserting request conversion, response and usage conversion, stream deltas, the usage chunk, and the [DONE] sentinel
  • Update the route creation tests to the new behavior: chat/completions and responses models are accepted on Anthropic providers, while undeclared endpoints (for example embeddings) are still rejected with route_protocol_mismatch
  • Update the adapter descriptor assertion to the new route protocol set

Type of Change

  • Bug fix
  • New feature
  • Refactor or maintenance
  • Documentation
  • Deployment or configuration

Verification

  • go vet ./... passes
  • gofmt reports no changed files needing formatting
  • Targeted go test ./internal/server/ runs pass for the new and updated tests
  • Full go test ./... passes except two pre-existing failures (TestNotificationSecretsRedactSMTPQuotedErrors, TestPasswordResetSMTPFailuresRedactSavedCredentials) that also fail on a clean main checkout and are unrelated to this change
  • node --test tools/*.test.mjs and node tools/check-source-lines.mjs pass
  • golangci-lint could not be installed locally (module proxy unreachable); this check will be validated by CI

Compatibility, Security, and Operations

Existing /v1/messages behavior is unchanged: native Anthropic protocol matching keeps the highest priority, and the newly declared protocols are only selected for OpenAI-protocol inbound requests. Administrators can now create routes from OpenAI-protocol models to Anthropic providers; no configuration or migration is needed. No environment variable or catalog changes.

Checklist

  • The PR title and body are written in English.
  • Tests were added or updated for behavior changes, or the reason they are unnecessary is documented.
  • No credentials, local .env files, databases, backups, or runtime logs are included.
  • Environment variable changes are synchronized across examples, Compose, start.sh, and deployment documentation where applicable.
  • Shared user-facing behavior is documented consistently in English, Simplified Chinese, and Japanese where applicable.
  • data/model-catalog.yaml remains tracked and catalog changes were reviewed where applicable.
  • git diff --check passes.

Declare chat/completions and responses route protocols on the built-in
Anthropic adapter so catalog models advertising those endpoints can be
routed to a native Anthropic provider. The adapter already converts
Chat Completions and Responses requests, responses, usage, and streaming
events to the Anthropic Messages wire format; only the route declaration
was missing, which made route creation fail with route_protocol_mismatch
and left such models unavailable on the OpenAI-compatible /v1 endpoints.

Endpoints the Anthropic adapter does not declare (for example
embeddings) are still rejected at route creation time.

@astaxie astaxie left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the complete diff at 36a2aea2c78c8ca6c63dbed3eadf5df6daecca2a against the stated Chat Completions and Responses routing contract.

Standards

No actionable finding. Existing user guides already describe these protocol bridges in all three supported languages.

Spec

One P2 finding is attached: responses routes now pass admin validation, but the adapter does not advertise the capability required to execute them. Independent gateway probes with a local fake Anthropic upstream return HTTP 501 for string input, message-array input and streaming; none reaches the upstream. The four focused existing Chat and route-validation tests pass.

GitHub CI passes on this exact head. Full local suites and real Anthropic calls were not rerun.

Findings: Standards 0; Spec 1 (P2).

providerType: ProviderAnthropic,
adapter: adapters[ProviderAnthropic],
routeProtocols: []string{providerRouteProtocolAnthropic},
routeProtocols: []string{providerRouteProtocolAnthropic, providerRouteProtocolChatCompletions, providerRouteProtocolResponses},

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Only advertise Responses routes when they can execute

Adding providerRouteProtocolResponses makes Responses-only models pass route creation, but this descriptor still advertises only Chat, ChatStream and Probe. handleResponses filters the resulting route for AdapterCapabilityResponses, leaving no eligible route and returning HTTP 501 provider_capability_not_supported. A local gateway probe reproduces this for string input, message-array input and stream: true, without an upstream call. Implement and advertise the full Responses contract, or defer this protocol declaration. Simply adding the capability is insufficient without checking conversion and streaming: the existing AnthropicAdapter.Responses drops instructions/tools and there is no native Responses stream implementation.

The Anthropic adapter previously translated a Responses request by
sending req.Input as a single user string: instructions, tools,
tool_choice, message-array items and function-call state were dropped,
and streaming had no implementation at all. Declaring the route protocol
without this support made the gateway advertise a surface that answered
501 (review finding on astaxie#437).

- ResponsesRequest converts into a Messages payload: instructions and
  system items become system text, message items map to text and image
  blocks, function_call / function_call_output items map to tool_use /
  tool_result, and tools map to input_schema form. Unsupported item
  types are rejected with 400 rather than dropped, and tool_choice none
  removes tools entirely.
- Non-streaming responses map back into the Responses object shape with
  per-item output, Anthropic tool ids preserved as call_id, and
  incomplete status for the max_tokens stop reason. Reasoning effort
  keeps flowing through output_config as the chat bridge does.
- Streaming converts the Messages SSE stream into Responses events
  (created / item added / output_text.delta / arguments delta / item
  done / completed); thinking deltas are consumed but not relayed.
- previous_response_id now works on Anthropic routes: finished turns of
  stateless adapters are stored (migration 13, version 12 reserved for
  the payload-chunk ledger PR) and expanded per-route behind a
  ResponsesStatelessAdapter capability, so state-holding passthrough
  providers and Jev continuations keep the field untouched.
- The adapter registers Responses / ResponseStream capabilities, closing
  the declared-but-unexecutable gap.

Tests include the review probes (string input, message array and
streaming must reach the upstream), a tool round trip, a previous-turn
expansion with a missing-reference rejection, and multibyte streaming.
…channels

Live testing against a DeepSeek Anthropic-compatible gateway exposed two
gaps left by the Responses support:

- The provider creation console failed with a generic catalog-load error
  because DeepSeek has no GET /v1/models endpoint. Discovery now returns
  a dedicated provider_models_not_offered code, and the console copy
  tells the operator to save the Provider and add models manually.
- AnthropicAdapter had no ProbeProvider, so nothing could ever flip a
  created provider to healthy and the console showed every route as
  abnormal. The probe prefers GET /v1/models, falls back to a minimal
  Messages exchange (model from the probe_model option) when the
  upstream answers 404/405, and surfaces authentication or availability
  failures as before.

Verified against the live DeepSeek endpoint: provider probes healthy,
chat and streaming Responses requests complete end to end.
Borrowing the intermediate-representation idea from magpie's gateway: the
Anthropic Messages SSE body is now decoded into an ordered list of turn
events (started / text delta / tool opened / arguments delta / tool
finished / finished / failed), and the Responses rendering is produced
from that list alone. The decoder answers what the upstream said; the
relay answers what a Responses client sees — each testable without the
other, and a future surface can render the same decoded turn without a
new wire-to-wire conversion.

Also on this pass, from live testing against a DeepSeek gateway:

- The connection-test probe no longer requires a probe model. A minimal
  Messages exchange without a model draws a client-error response that
  proves reachability and accepted credentials; authentication failures
  still surface, and any other failure keeps the provider unhealthy.
- The test-connection flow runs catalog discovery after a successful
  probe again (restoring models_count), and a provider_models_not_offered
  failure now degrades to healthy with zero models instead of failing the
  connection test. The requested auth mode reaches the probe through the
  generic provider_auth_mode option.
@kiddyt00

Copy link
Copy Markdown
Contributor Author

The P2 finding is resolved in three follow-up commits (8627b433, 18dd9627, 57e9862c), taking the first of the two options: the full Responses contract is now implemented and advertised.

  • AnthropicAdapter.Responses converts the complete Responses request instead of sending req.Input as one user string: instructions and system items become system text, message items map to text and image blocks, function_call / function_call_output items map to tool_use / tool_result, and tools map to input_schema form. Unsupported item types are rejected with 400 rather than dropped.
  • Non-streaming replies map back into the Responses object shape with per-item output and the Anthropic tool id preserved as call_id; max_tokens stop maps to incomplete. Reasoning effort keeps flowing through output_config as the chat path does.
  • The adapter now implements ResponsesStreamOpener and ResponsesStatelessAdapter, so streaming converts the Messages SSE stream into Responses events (created / item added / text and arguments deltas / item done / completed) through a two-stage decode-then-render pipeline, and previous_response_id works on Anthropic routes via a stored turn state (migration 13; version 12 is reserved for the payload-chunk ledger PR).
  • The descriptor advertises Responses / ResponseStream capabilities alongside the existing ones, closing the declared-but-unexecutable gap the finding describes.

The chat gateway tests from the original head still pass unchanged, plus new coverage: the review probes (string input, message array, streaming must reach the upstream), a tool round trip, previous-turn expansion with a missing-reference rejection, and multibyte streaming. The affected-suite regression passes (1116s).

One test-intent note: TestAdminRouteAcceptsChatModelOnNativeAnthropicProvider had picked up an embeddings endpoints fixture in the merge; it is restored to a chat/responses model expecting route creation, and the rejection guard is now covered with an embeddings-only model in TestAdminRouteRejectsKnownModelProviderProtocolMismatch.

TestCompatibilityManifestTargetsLatestRegisteredMigration caught the
responses turn-state table landing at version 13 while the release
manifest still declared 11, and golangci-lint flagged the turn-state
size constant that no code referenced yet. The manifest now targets 13,
and the unused constant is removed until a size bound is actually
enforced.
…es capabilities

TestBuiltinAdaptersResolveWithUnchangedCapabilities pins every built-in
provider's advertised capability set; the Anthropic entry still listed
only chat/chat_stream/probe after the descriptor grew the Responses and
ResponseStream capabilities, so CI caught the mismatch that the filtered
local runs missed. The pin now matches the registered set.
TestEmbeddedManifestIsCurrent caught the embedded migrations manifest
staying at version 11 after migration 13 and the compatibility manifest
landed. Regenerated with cmd/manifestgen.
TestCommandsOnAdoptedDatabase asserted current version 11; the turn-state
table moved the ledger to 13.
…base URLs

Anthropic-compatible gateways (DeepSeek, Kimi) expose no model catalog on
their Anthropic path, so adding such a Provider failed catalog discovery
with provider_models_not_offered and the operator had to hand-enter
models. Live probing of five Anthropic-compatible gateways showed the
dominant shape: both protocols served from the same host under different
paths, with the OpenAI side offering GET /v1/models and /models.

Discovery now tries those same-origin OpenAI-style endpoints (same API
key as a Bearer credential) after the primary endpoint answers 404/405.
Authentication failures on a fallback candidate surface immediately;
other failures fall through to the original not-offered mapping. A base
URL without a path suffix yields no candidates, so plain hosts never see
duplicate requests.
@kiddyt00

Copy link
Copy Markdown
Contributor Author

Base URL reference for anyone testing this PR against Chinese providers — collected while verifying the catalog fallback added in 4ad26a3.

Provider OpenAI-compatible base Anthropic-compatible base Anthropic-side models endpoint Same-origin fallback
DeepSeek https://api.deepseek.com https://api.deepseek.com/anthropic none (404 with a valid key) covered: https://api.deepseek.com/v1/models returns 200
Kimi Moonshot https://api.moonshot.cn/v1 https://api.moonshot.cn/anthropic none (404 unauthenticated) covered: https://api.moonshot.cn/v1/models answers 401 (endpoint exists)
MiniMax (cn / intl) https://api.minimax.cn/v1 / api.minimaxi.com/v1 …/anthropic on the same host unverified (401 unauthenticated) fallback available if needed
Z.AI https://api.z.ai/api/paas/v4 https://api.z.ai/api/anthropic yes (200, open listing) not needed
Zhipu bigmodel https://open.bigmodel.cn/api/paas/v4 https://open.bigmodel.cn/api/anthropic yes (200, open listing) not needed
Volcengine Ark https://ark.cn-beijing.volces.com/api/v3 https://ark.cn-beijing.volces.com/api/anthropic likely present (401 unauthenticated) not needed / verify with key
Qwen DashScope https://dashscope.aliyuncs.com/compatible-mode/v1 https://dashscope.aliyuncs.com/api/v2/apps/claude-code-proxy dedicated proxy shape not covered by same-origin heuristic
Tencent Hunyuan https://api.hunyuan.cloud.tencent.com/v1 none — not applicable

Every provider serves both protocols from the same host under different paths, so the same-origin fallback (origin + /v1/models, then origin + /models, same key as Bearer) covered every observed gap (DeepSeek and Kimi). Two shapes fall outside it: Qwen DashScope's dedicated proxy path, and cloud-hosted Anthropic endpoints (Bedrock/Vertex) that use their own signing and paths. Both need manual model entry, which the console already supports.

One data caveat worth knowing: DeepSeek's OpenAI-side catalog lists deepseek-flash / deepseek-v4-pro, but the Anthropic path also serves deepseek-chat, which the catalog does not list — cross-protocol catalogs can drift from what the serving path accepts, so discovered lists are a starting point, not a guarantee.

…llbacks

The same-origin catalog fallback triggered on any primary discovery
failure, including authentication. Against Gemini (query_param keys,
descriptor default path /models), a failed candidate produced an extra
unauthenticated request on the same host, shifting the probe sequence
the provider_headers tests assert on (TestGeminiProviderTestTriesLaterA
ctiveResource recorded a stray empty-key request between the two
resource keys).

The fallback now triggers only on provider_models_not_offered — the
dedicated mapping for an upstream without a catalog endpoint. Auth
failures and other primary failures surface immediately, and the
gateway no longer sends a request the upstream would count.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants