Repository navigation
Conversation
Preserve fields with equivalent Responses representations. Reject unsupported values explicitly and compare converter classifications with the pinned SDK schemas. Signed-off-by: Ananth Subramaniam <[email protected]>
|
Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually. Contributors can view more details about this message here. |
Map Claude Code's output effort into Responses reasoning and tolerate prompt-cache hints that do not affect generated content. Retain explicit schema classification so new SDK fields still require a conversion decision. Signed-off-by: Ananth Subramaniam <[email protected]>
Signed-off-by: Ananth Subramaniam <[email protected]>
Signed-off-by: Ananth Subramaniam <[email protected]>
Signed-off-by: Ananth Subramaniam <[email protected]>
246fa9e to
0657ad2
Compare
Reuse request classifications and immutable field collections. Defer error-list allocation to invalid requests so valid content blocks stay on the fast path. Signed-off-by: Ananth Subramaniam <[email protected]>
|
/claude review |
| raise ValueError("Responses cached_tokens cannot exceed input_tokens.") | ||
| reasoning_tokens = ((usage or {}).get("output_tokens_details") or {}).get("reasoning_tokens", 0) | ||
| if reasoning_tokens: | ||
| raise NotImplementedError("Anthropic usage cannot represent Responses reasoning_tokens.") |
There was a problem hiding this comment.
RISK — reasoning_tokens>0 now hard-500s the ingress proxy.
WHAT BREAKS: responses_to_anthropic_response is the live ingress response path (base_responses_api_model.messages() → here, no try/except → FastAPI 500). This raises whenever the downstream Gym model reports output_tokens_details.reasoning_tokens > 0.
BLAST RADIUS: The ingress proxy fronts arbitrary Gym model servers — including reasoning/open models — for the Claude Code CLI. Any such model reporting a nonzero reasoning-token count turns every response into an opaque 500. Previously this field simply wasn't carried into Anthropic usage (Anthropic has no reasoning_tokens field) — a harmless metric gap, not corruption.
FIX: Drop reasoning_tokens instead of raising (its absence in Anthropic usage is lossless). If you want strictness, the proxy endpoint must at least catch converter NotImplementedError and return a 4xx/422 naming the field rather than a 500.
| "container", # Responses cannot select Anthropic container state. | ||
| "inference_geo", # Responses has no equivalent inference-routing field. | ||
| "stop_sequences", # Responses create params have no stop-sequence field. | ||
| "thinking", # Anthropic thinking budgets cannot be represented by Responses reasoning config. |
There was a problem hiding this comment.
RISK — rejecting thinking may 500 real Claude Code CLI requests.
WHAT BREAKS: thinking is now in REJECTED_ANTHROPIC_REQUEST_FIELDS, so _validate_anthropic_request raises NotImplementedError for any request with a non-null thinking block. The removed docstring (line ~470) previously stated the proxy stayed permissive toward such fields and dropped them.
BLAST RADIUS: The Claude Code CLI — the stated primary ingress client — sends a thinking budget when extended thinking is enabled. Under this change every such request becomes an opaque HTTP 500 (messages() does not catch this), where before it succeeded by ignoring the hint. Same concern for stop_sequences, which Anthropic clients commonly set.
This fail-loud tradeoff is the center of the PR and may be intended — but it converts a previously-working CLI path into a hard failure. Confirm the CLI never sends thinking/stop_sequences in target flows, or map them (ignore the budget / translate to reasoning.effort) rather than reject.
|
SHIP WITH CARE Bidirectional Anthropic↔Responses converter refactor: replaces silent field-dropping with explicit classification (mapped / ignored / rejected) for request fields, content blocks, tool variants, and stop reasons, plus SDK-drift tests that fail if the pinned The design choice — fail loud (
Neither is silent data corruption, so not a hold. But before this is live in front of the CLI, either (a) wrap the No async/httpx/ray issues; the module stays transport-free and SDK-types-only as documented. |
| raise ValueError("Responses cached_tokens cannot exceed input_tokens.") | ||
| reasoning_tokens = ((usage or {}).get("output_tokens_details") or {}).get("reasoning_tokens", 0) | ||
| if reasoning_tokens: | ||
| raise NotImplementedError("Anthropic usage cannot represent Responses reasoning_tokens.") |
There was a problem hiding this comment.
RISK — reasoning_tokens>0 now hard-500s the ingress proxy.
WHAT BREAKS: responses_to_anthropic_response is the live ingress response path (base_responses_api_model.messages() → here, no try/except → FastAPI 500). This raises whenever the downstream Gym model reports output_tokens_details.reasoning_tokens > 0.
BLAST RADIUS: The ingress proxy is meant to front arbitrary Gym model servers, including reasoning/open models, for the Claude Code CLI. Any such model that reports a nonzero reasoning-token count turns every response into an opaque 500 for the CLI. Previously this field was simply not carried into Anthropic usage (there is no Anthropic reasoning_tokens field) — a harmless metric gap, not corruption.
FIX: Drop reasoning_tokens instead of raising (it's a count, and its absence in Anthropic usage is lossless). If you want to keep it strict, at minimum the proxy endpoint must catch converter NotImplementedError and return a 4xx/422 with the field name rather than a 500.
| "container", # Responses cannot select Anthropic container state. | ||
| "inference_geo", # Responses has no equivalent inference-routing field. | ||
| "stop_sequences", # Responses create params have no stop-sequence field. | ||
| "thinking", # Anthropic thinking budgets cannot be represented by Responses reasoning config. |
There was a problem hiding this comment.
RISK — rejecting thinking may 500 real Claude Code CLI requests.
WHAT BREAKS: thinking is now in REJECTED_ANTHROPIC_REQUEST_FIELDS, so _validate_anthropic_request raises NotImplementedError for any request carrying a non-null thinking block. The removed docstring text (line ~470) previously stated the proxy stayed permissive toward such fields and dropped them.
BLAST RADIUS: The Claude Code CLI is the stated primary ingress client, and it sends a thinking budget when extended thinking is enabled. Under this change every such request becomes an opaque HTTP 500 (the messages() endpoint does not catch this), where before it succeeded by ignoring the hint.
This is the deliberate fail-loud tradeoff at the center of the PR, so it may be intended — but it converts a previously-working CLI path into a hard failure. Confirm the CLI never sends thinking in your target flows, or map it (ignore the budget, or translate to reasoning.effort) rather than reject. Same concern applies to stop_sequences, which Anthropic clients commonly set.
Summary
The Anthropic converter previously handled its supported subset but silently dropped several request fields, nested content attributes, response metadata, and usage details. That behavior made a successful conversion look lossless when the target API could not represent the source value.
The motivation is to prepare for OpenAI SDK version changes by failing loudly on unrecognized types, part of #2452 .
This change defines a loss-aware contract for all four converter paths. Values with equivalent Anthropic Messages and OpenAI Responses representations are preserved. Prompt-cache hints that do not affect generated content are accepted without blocking the Claude Code harness. Values without an equivalent representation raise a named conversion error.
The request path reuses import-time field classifications and immutable allowed-field collections. Structural validation allocates error details only when it finds invalid input.
flowchart LR AnthropicRequest["Anthropic Messages request"] --> RequestAudit{"Mapped, ignored, or rejected?"} RequestAudit -->|"Mapped"| ResponsesRequest["OpenAI Responses request"] RequestAudit -->|"Cache hint"| ResponsesRequest RequestAudit -->|"Rejected"| RequestError["Explicit conversion error"] ResponsesOutput["OpenAI Responses output"] --> ResponseAudit{"Mapped or rejected?"} ResponseAudit -->|"Mapped"| AnthropicResponse["Anthropic Message response"] ResponseAudit -->|"Mapped"| AnthropicSSE["Anthropic SSE events"] ResponseAudit -->|"Rejected"| ResponseError["Explicit conversion error"] SDKSchema["Pinned SDK schemas"] --> DriftTests["Field and union classification tests"] DriftTests --> RequestAudit DriftTests --> ResponseAuditRequest conversion
Anthropic Messages requests now preserve:
metadata.user_idas Responsesuser.service_tier="auto".output_config.effortas Responsesreasoning.effortforlow,medium, andhigh.strictsettings.disable_parallel_tool_usethrough Responsesparallel_tool_calls.tool_resultcontent as ordered Responsesinput_text,input_image, andinput_fileparts.redacted_thinkingas reasoning with empty summaries and opaqueencrypted_content.Responses requests now preserve the inverse forms, including structured
function_call_outputcontent, tool settings, user metadata, service tier, media sources, documents, and redacted reasoning.Claude Code sends
output_config.effort, prompt-cache controls, andis_error=falseon successful tool results in normal/v1/messagesrequests. Effort maps to the corresponding Responses reasoning setting. Top-level and nestedcache_controlvalues are classified as ignored transport hints because the Responses target cannot preserve Anthropic cache breakpoints, but dropping them does not alter generated content. A false or omittedis_errorvalue maps to a normal Responsesfunction_call_output.The converter rejects present values that cannot be represented without loss. These include Anthropic
top_k, stop sequences, containers, inference geography, request thinking configuration, structured output formats, unsupported effort levels, citations, document metadata,tool_result.is_error=true, and hosted tools. Responses-only request fields, hosted tool items, non-default media detail, file IDs, filenames, and unsupported reasoning forms are rejected by name.Response and streaming conversion
Anthropic responses now preserve adjacent text blocks as separate Responses content parts. Cached and uncached input tokens are combined into Responses
input_tokens, whilecache_read_input_tokensis retained ininput_tokens_details.cached_tokens.Responses usage maps cached tokens back to Anthropic
cache_read_input_tokensand uncachedinput_tokens. Invalid cached-token totals and non-zero reasoning-token details fail explicitly.Extended-thinking signatures are emitted as
signature_deltaevents in synthesized Anthropic streams. Redacted thinking remains aredacted_thinkingblock and emits no content delta.Stop reasons with direct equivalents remain mapped:
end_turn,tool_use,max_tokens, andrefusal. Anthropicpause_turnandstop_sequence, unknown stop reasons, unsupported Responses incomplete reasons, output annotations, output log probabilities, and response usage details without a Responses equivalent fail explicitly.SDK drift checks
The tests partition each audited SDK surface into mapped, ignored where explicitly safe, and rejected sets:
The classification sets must be disjoint and must cover the installed SDK schema exactly. A new SDK field or union member therefore fails the audit until the converter records a mapping, a safe ignored hint, or an explicit rejection.
Compatibility scope
This PR targets the current Gym pins: OpenAI 2.7.2 and Anthropic 0.109.2. OpenAI 2.44.0 adds request fields and item variants that will be classified in the dependency-upgrade follow-up.
The
/v1/messagesingress remains compatible with the Claude Code agent harness. The harness can send its default output effort, prompt-cache hints, and successful tool-result markers through a Gym model server to a vLLM Chat Completions backend. Multi-turn Bash execution can therefore return tool results to the model for subsequent tool calls and a final answer.Existing transport behavior remains unchanged. The proxy still buffers a complete Responses result before synthesizing Anthropic SSE. It still regenerates response and item IDs, merges consecutive same-role messages, normalizes system and developer input to Anthropic's top-level
system, and carries training token metadata outside the Anthropic wire response.References