Skip to content

fix(anthropic): make Messages conversion loss-aware - #2507

Draft
ananthsub wants to merge 6 commits into
NVIDIA-NeMo:mainfrom
ananthsub:ananthsub/anthropic-converter-audit
Draft

ananthsub wants to merge 6 commits into
NVIDIA-NeMo:mainfrom
ananthsub:ananthsub/anthropic-converter-audit

Conversation

@ananthsub

@ananthsub ananthsub commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

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 --> ResponseAudit
Loading

Request conversion

Anthropic Messages requests now preserve:

  • metadata.user_id as Responses user.
  • service_tier="auto".
  • output_config.effort as Responses reasoning.effort for low, medium, and high.
  • Function tool strict settings.
  • disable_parallel_tool_use through Responses parallel_tool_calls.
  • URL and base64 image sources.
  • URL and base64 PDF document sources.
  • Structured tool_result content as ordered Responses input_text, input_image, and input_file parts.
  • redacted_thinking as reasoning with empty summaries and opaque encrypted_content.

Responses requests now preserve the inverse forms, including structured function_call_output content, tool settings, user metadata, service tier, media sources, documents, and redacted reasoning.

Claude Code sends output_config.effort, prompt-cache controls, and is_error=false on successful tool results in normal /v1/messages requests. Effort maps to the corresponding Responses reasoning setting. Top-level and nested cache_control values 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 omitted is_error value maps to a normal Responses function_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, while cache_read_input_tokens is retained in input_tokens_details.cached_tokens.

Responses usage maps cached tokens back to Anthropic cache_read_input_tokens and uncached input_tokens. Invalid cached-token totals and non-zero reasoning-token details fail explicitly.

Extended-thinking signatures are emitted as signature_delta events in synthesized Anthropic streams. Redacted thinking remains a redacted_thinking block and emits no content delta.

Stop reasons with direct equivalents remain mapped: end_turn, tool_use, max_tokens, and refusal. Anthropic pause_turn and stop_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:

  • Anthropic request fields.
  • Anthropic input content-block types.
  • Anthropic tool variants.
  • Anthropic stop reasons.
  • Responses request fields.
  • Responses input item types.

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/messages ingress 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

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]>
@copy-pr-bot

copy-pr-bot Bot commented Aug 12, 2026

Copy link
Copy Markdown

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]>
@ananthsub
ananthsub force-pushed the ananthsub/anthropic-converter-audit branch from 246fa9e to 0657ad2 Compare August 12, 2026 20:02
@ananthsub
ananthsub marked this pull request as ready for review August 12, 2026 20:10
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]>
@cmunley1

Copy link
Copy Markdown
Contributor

/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.")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@claude

claude Bot commented Aug 15, 2026

Copy link
Copy Markdown
Contributor

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 anthropic<=0.109.2 surface changes. This is a genuine correctness win — the token-accounting fix (ingress input_tokens = uncached + cached, egress inverting it with a cached > input guard) closes a real prior under-count, and structured tool_result / document / URL-image support is well covered by round-trip tests. Coverage is thorough on both directions.

The design choice — fail loud (NotImplementedError) on anything not losslessly representable, rather than drop it — is defensible for a converter that feeds training/eval, but it lands on a live path with no error handling: base_responses_api_model.messages() (nemo_gym/base_responses_api_model.py:207-210) calls the converter directly, so every new raise becomes an opaque HTTP 500 to the Claude Code CLI. Two spots flagged inline where that regresses previously-working requests:

  • RISK nemo_gym/anthropic_converter.py:106 — thinking (and stop_sequences) are now rejected; the removed docstring explicitly said the proxy stayed permissive and dropped them. The CLI sends thinking when extended thinking is on.
  • RISK nemo_gym/anthropic_converter.py:784 — downstream models reporting reasoning_tokens > 0 now 500 on the response path; this was previously a harmless metric gap.

Neither is silent data corruption, so not a hold. But before this is live in front of the CLI, either (a) wrap the messages() converter calls to translate NotImplementedError into a 422 naming the field, or (b) downgrade the specific hint-only fields (thinking, stop_sequences, reasoning_tokens) back to ignore. Confirm against a real CLI rollout, not just the unit tests — green tests here do not exercise the CLI request shape.

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.")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@ananthsub
ananthsub marked this pull request as draft August 24, 2026 07:47
@github-actions github-actions Bot removed the sla:review-overdue Review response is over the one-business-day SLA label Aug 24, 2026
@ananthsub

Copy link
Copy Markdown
Contributor Author

Related to the performance roadmap in #2998. The converter parity contract in this PR is required when removing duplicate model dialect conversions in #3042.

This branch was previously deployed

1 inactive deployment
public — 0d250df5 Deployed Aug 12, 2026 by copy-pr-bot[bot] via release / finalize / notify #1379
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:model Model servers, inference providers, and model adapters bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants