feat: claude model support
Use cases, pain points, and background
Users want to evaluate using Claude models using NeMo Gym environments. Anthropic's native /v1/messages API differs significantly from OpenAI's format — different message structure, tool use schema, thinking blocks, and response format. A dedicated model server is needed to handle this translation cleanly.
This is explicitly called out as a target in NVIDIA-NeMo/Gym#1285's model server target state:
| Server | Speaks | Use case |
|---|---|---|
claude_model |
Anthropic Messages API | Direct Anthropic |
Description
Create a new claude_model server under responses_api_models/ that speaks the Anthropic Messages API natively and translates to/from NeMo Gym's internal Responses API format.
Key translation concerns:
- Message format: Anthropic uses
role: "user" | "assistant"with content blocks (text, tool_use, tool_result, thinking) vs OpenAI's message/item structure - Tool use: Anthropic tool calls use
type: "tool_use"content blocks withid,name,input; tool results aretype: "tool_result"content blocks referencingtool_use_id - System prompt: Anthropic uses a top-level
systemparameter rather than a system message in the messages array - Thinking/reasoning: Anthropic's extended thinking uses
type: "thinking"content blocks with abudget_tokensparameter, which maps to NeMo Gym's reasoning items - Streaming: Not required for v1 (non-streaming only, matching other model servers)
Design
Files to create
responses_api_models/claude_model/app.py— server implementationresponses_api_models/claude_model/configs/claude_model.yaml— default configresponses_api_models/claude_model/requirements.txtresponses_api_models/claude_model/tests/test_app.py
Server structure
class ClaudeModelConfig(BaseResponsesAPIModelConfig):
anthropic_base_url: str # default: "https://api.anthropic.com"
anthropic_api_key: str
anthropic_model: str # e.g. "claude-sonnet-4-20250514"
max_tokens: int # required by Anthropic API
anthropic_version: str # default: "2023-06-01"
thinking_budget_tokens: Optional[int] # for extended thinking
max_concurrent_requests: Optional[int]
extra_body: Dict[str, Any]
Converter: Responses API ↔ Anthropic Messages API
responses_to_anthropic(): ConvertNeMoGymResponseCreateParamsNonStreaming→ Anthropicmessages.createparams- Map input items/messages to Anthropic message format
- Extract system prompt to top-level
systemparam - Convert tool definitions to Anthropic tool schema
- Map previous tool calls/results to content blocks
anthropic_to_responses(): Convert Anthropic response →NeMoGymResponse- Map
tool_usecontent blocks →NeMoGymResponseFunctionToolCall - Map
textcontent blocks →NeMoGymResponseOutputText - Map
thinkingcontent blocks →NeMoGymResponseReasoningItem - Map usage (input_tokens, output_tokens) →
NeMoGymResponseUsage
- Map
HTTP transport
Use nemo_gym.server_utils.request() (aiohttp) for upstream calls — do NOT use the anthropic Python SDK (it uses httpx internally which has O(n^2) connection pooling issues at scale per CLAUDE.md guidance). Construct raw HTTP requests to POST /v1/messages.
Out of scope
- Streaming support (can be added later)
- Token ID information for training (Anthropic doesn't expose this)
- Batch API support
- The generic
chat_completions_modelserver (NVIDIA-NeMo/Gym#1285) — that's for OAI-compatible hosted providers - Gemini native API support (NVIDIA-NeMo/Gym#1147)
Acceptance Criteria
- [ ]
claude_modelserver starts and passes health check - [ ]
responses()endpoint correctly translates Responses API → Anthropic Messages → Responses API - [ ] Tool use round-trips correctly (function calls and results)
- [ ] Extended thinking/reasoning maps to NeMo Gym reasoning items when enabled
- [ ] System/developer messages handled correctly (top-level
systemparam) - [ ] Rate limiting via
max_concurrent_requestssemaphore - [ ] Integration test confirming basic chat completion round-trip
- [ ] Integration test confirming tool use round-trip
- [ ] Works end-to-end with at least one existing resources server environment
References
- Anthropic Messages API: https://docs.anthropic.com/en/api/messages
- Related: NVIDIA-NeMo/Gym#1285 (chat_completions_model for hosted providers — explicitly defers Claude to this issue)
- Related: NVIDIA-NeMo/Gym#1384 (duplicate of this issue)
- Sibling: NVIDIA-NeMo/Gym#1147 (Gemini native support)
Anthropic Model Design Note
anthropic_model is a native Anthropic Messages API model server behind NeMo Gym's /v1/responses interface. It exists because Anthropic's /v1/messages format is not OpenAI-compatible: system prompts are top-level, content is block-based, tool calls are tool_use blocks, tool results are tool_result blocks, and extended thinking is represented as dedicated thinking blocks.
Key Design Points
The server translates directly between NeMo Gym Responses API objects and Anthropic Messages API payloads. It does not route through Chat Completions or the Anthropic Python SDK. The translation logic lives in the shared, transport-free module nemo_gym/anthropic_converter.py (AnthropicConverter); this server is a thin FastAPI shell around it plus Anthropic-API egress policy.
Key choices:
- Use
nemo_gym.server_utils.request()for raw aiohttp transport, matching Gym's high-concurrency guidance and avoiding SDK/httpx connection-pool behavior. - Keep a dedicated
AnthropicConverter— distinct from the OpenAI Chat CompletionsResponsesConverter, because Anthropic Messages has different semantics — but located innemo_gym/anthropic_converter.pyand made bidirectional so it can be shared by both this egress provider (Responses → Anthropic) and an inverse-direction Anthropic Messages ingress proxy (Anthropic → Responses). See "Bidirectional Shared Converter" below. - Preserve common Responses API fields where they map cleanly: text messages, system/developer instructions, base64 image inputs, function tools, tool calls/results, sampling parameters for models that support them, max tokens, usage, and reasoning/thinking.
- Use a typed
thinkingconfig for modern Anthropic thinking modes such as{"type": "adaptive"}. On Opus 4.7/4.8 and Fable 5, thinking summaries aredisplay: "omitted"by default — thinking blocks return with empty text, so reasoning items will carry empty summaries unless{"type": "adaptive", "display": "summarized"}is configured. - Keep
thinking_budget_tokensas a legacy/manual-budget compatibility path for older Claude models that still require{"type": "enabled", "budget_tokens": ...}. It must not be used with Opus 4.7/4.8 or Fable 5, which reject{"type": "enabled", "budget_tokens": ...}with a 400 — including theclaude-opus-4-8example in the README; those models use{"type": "adaptive"}plus effort controls. - Pass provider-specific fields that are not modeled as typed config through
extra_bodyinstead of expanding the shared Responses schema. - Reject ambiguous thinking configuration when
thinking,thinking_budget_tokens, and/orextra_body.thinkingare set at the same time. - Normalize both host-only and
/v1base URLs sohttps://api.anthropic.comandhttps://api.anthropic.com/v1both resolve to/v1/messages. - Fail loudly with
NotImplementedErrororValueErrorfor unsupported content types rather than silently dropping unknown blocks.
Bidirectional Shared Converter
AnthropicConverter lives in nemo_gym/anthropic_converter.py (alongside the precedent set by nemo_gym/responses_converter.py) and exposes both directions of the Anthropic ↔ Responses mapping. The same field-mapping rules (tool_use/tool_result, thinking/signature, base64 image, stop_reason, tool_choice) back two opposite-direction consumers, so the gnarly logic exists once and is guarded by round-trip tests:
- Egress — this
anthropic_modelprovider (NeMo Gym is the client, Anthropic is the backend):responses_to_anthropic(request) andanthropic_to_responses(response). - Ingress — an Anthropic Messages proxy for clients that speak Anthropic (e.g. the Claude Code CLI) but want to run against any Gym backend:
anthropic_request_to_responses(request),responses_to_anthropic_response(response), andanthropic_response_to_sse(synthesize the Anthropic SSE event stream from a complete, non-streaming downstream response).
Boundary: the converter is pure structural mapping (transport-free, SDK-free). Anthropic-API-as-backend policy stays in this server, not the shared converter — the sampling-restriction allowlist (_model_disallows_sampling_params), thinking-mode config/400-guards, base-URL normalization, and lossy cache-token usage accounting are all egress concerns and do not apply to an open-model ingress backend. (For now these policy helpers physically live on the converter but are invoked only by the egress responses_to_anthropic path; relocating them into the server is a marked follow-up.)
Comparison With Existing Model Servers
openai_model is a thin passthrough to OpenAI-compatible /responses and /chat/completions. It needs almost no conversion because the upstream API already speaks the expected shape.
vllm_model targets OpenAI-compatible vLLM endpoints. It converts Responses API to Chat Completions, handles vLLM-specific reasoning parsing, token IDs, audio side channels, endpoint selection, and context-limit behavior.
inference_provider from PR #1286 generalizes the OpenAI-compatible hosted-provider case. It reuses the shared Responses-to-Chat-Completions converter because those providers speak /v1/chat/completions.
anthropic_model is different: Anthropic Messages is neither Responses-native nor Chat-Completions-compatible. Reusing the shared Chat Completions converter would add an unnecessary intermediate representation and still require Anthropic-specific conversion afterward.
Comparison With Browser-Agent Anthropic Prototype
There is a separate browser-agent Anthropic model prototype at responses_api_models/turing_browser_agent_anthropic_model/app.py in the Turing Gym branch (commit c465bbe). It is useful prior art, but it solves a narrower problem than this server.
That implementation is specialized for Anthropic computer-use/browser workflows:
- It translates Responses
computer_use_previewtools into Anthropic computer tools and beta headers. - It maps Responses
computer_callto Anthropictool_usenamedcomputer. - It maps Responses
computer_call_outputscreenshots to Anthropictool_resultblocks containingimagecontent. - It has basic
input_imagesupport by extracting base64 from data URLs, but it hardcodesmedia_type: "image/png". - It uses the Anthropic Python SDK (
AsyncAnthropic) withDefaultAioHttpClient.
This anthropic_model is intended as the generic Anthropic Messages bridge for NeMo Gym policy models:
- It translates standard Responses text messages, base64 image inputs, function tools, function calls/results, system/developer instructions, Anthropic thinking blocks, usage, refusal, and stop reasons.
- It uses Gym's raw aiohttp transport through
nemo_gym.server_utils.request()rather than the Anthropic SDK. - It keeps browser/computer-use behavior out of scope for the first version.
- It implements the image part that is broadly useful for VLM tasks, with stricter media-type parsing and validation instead of assuming every image is PNG.
The main lesson from the prototype is that Anthropic image blocks fit naturally as content blocks inside role-scoped messages, including inside tool_result content for screenshots. The main reason not to copy it directly is scope: computer-use tools, beta headers, screenshot actions, and browser-specific action normalization are separate from the generic Responses API model translation implemented here.
API Shape Anatomy
At a high level, NeMo Gym uses the OpenAI Responses API shape: a request contains an ordered input list, and a response contains an ordered output list. Anthropic Messages is message-oriented instead: a request has top-level system, top-level tools, and a messages array where each message owns the role for all of its content blocks.
| Responses API Anatomy | Anthropic Messages Anatomy |
|---|---|
Request/input is item-oriented. The top-level `instructions` field is the usual Responses API system prompt path. Additional `system` or `developer` message items can also carry instruction-like content in the input trajectory.
Model output uses the same trajectory-item style.
|
Messages are role-scoped. Thinking, text, tool-use, and tool-result blocks inherit role from the enclosing message.
|
The converter's job is therefore mostly structural: flatten or group Responses items into Anthropic role-scoped messages, move instructions plus system/developer input messages to top-level system, translate function tools to Anthropic tools, and translate thinking blocks to Responses reasoning items on the way back.
Conversion Contract Examples
These examples show the intended field-level contract between NeMo Gym's OpenAI Responses API shape and Anthropic Messages. They are simplified for review; IDs, usage, and optional fields are omitted unless they are part of the mapping.
User Text Input
| Responses API | Anthropic Messages |
|---|---|
|
|
System Or Developer Instructions
| Responses API | Anthropic Messages |
|---|---|
|
|
Function Tool Schema
| Responses API | Anthropic Messages |
|---|---|
|
|
Tool Call And Tool Result
| Responses API | Anthropic Messages |
|---|---|
Assistant tool call:
|
Assistant message content:
|
Tool result input:
|
User message content:
|
Tool Choice
Responses API tool_choice maps onto Anthropic's typed tool_choice object: the string "required" becomes {"type": "any"}, "auto" and "none" pass through as {"type": "auto"} / {"type": "none"}, and a forced function ({"type": "function", "name": ...}) becomes {"type": "tool", "name": ...}. Any other shape raises NotImplementedError.
Thinking And Reasoning
| Responses API | Anthropic Messages |
|---|---|
|
|
The example above assumes summarized thinking. By default on Opus 4.7/4.8 and Fable 5 the thinking field is empty, so the reasoning item's summary_text is empty while encrypted_content (the block signature) is preserved. The round trip is faithful for the one-summary-per-reasoning-item shape this server emits, because thinking blocks must be replayed to the same model unchanged: the stored summary_text is replayed verbatim as the thinking field with its original signature. A reasoning item carrying multiple summary_text entries is expanded into multiple thinking blocks that share a single signature, which Anthropic will not validate — this only arises for cross-model trajectories produced elsewhere, not for this server's own output.
Stop Reasons
| Responses API | Anthropic Messages |
|---|---|
|
|
max_tokens maps the same way. refusal maps to content_filter; complete reasons such as end_turn, tool_use, and pause_turn do not set incomplete_details.
Multimodal Inputs
The implementation supports text plus base64 image data URLs because both protocols represent multimodal input as typed content blocks inside a user message. Remote image URLs, file IDs, PDFs as direct media, and computer-use screenshots remain out of scope.
| Responses API | Anthropic Messages |
|---|---|
|
|
The converter maps input_text to Anthropic text, and input_image to Anthropic image. For data URLs, it splits data:image/png;base64,... into media_type: "image/png" and base64 data. Supported media types are image/jpeg, image/png, image/gif, and image/webp.
Trade-Offs
Direct conversion keeps the implementation small and faithful to Anthropic's API. It deliberately does not reuse the OpenAI Chat Completions ResponsesConverter: routing Anthropic through Chat Completions would add an unnecessary intermediate representation and still require Anthropic-specific conversion afterward — the semantic mismatch is large. The Anthropic mapping is therefore its own converter, but it is not duplicated: it lives in the shared nemo_gym/anthropic_converter.py and is bidirectional, so the inverse-direction Anthropic Messages ingress proxy reuses the same rules rather than re-deriving them (which would drift on exactly the hardest cases — tool/thinking/stop_reason). The one-consumer "keep it local / accept duplication" stance was reconsidered once a second, inverse-direction consumer appeared; sharing the rules once and guarding them with round-trip tests is the lower-risk choice.
The config uses typed fields for stable, first-class behavior (max_tokens, anthropic_version, thinking, thinking_budget_tokens, concurrency limits) and keeps extra_body as an escape hatch for provider-specific or fast-moving options. The alternative is to mirror Anthropic's request schema with many typed config fields or a nested anthropic_options model. That would improve validation and discoverability, but it would also require ongoing API-schema maintenance. Common pass-through fields can be promoted to typed config later if they become routine.
Some Anthropic options are model-specific. Claude Opus 4.7/4.8 and Claude Fable 5 / Mythos 5 reject configurable sampling parameters (temperature, top_p, top_k), so this server fails fast for those models when sampling is explicitly configured instead of silently dropping user intent or forwarding a request that will 400 upstream. For those models, examples should omit sampling and use prompting plus adaptive thinking/effort controls. Older models that support sampling still receive the mapped Responses API sampling fields. The restricted-model set is a maintained allowlist (_model_disallows_sampling_params); it must be extended as new model families add the same restriction, and the same is true of the thinking-mode restrictions above — both are matched by substring against the configured model name.
Anthropic stop reasons are mapped only where OpenAI Responses has compatible fields. max_tokens and model_context_window_exceeded map to incomplete_details.reason = "max_output_tokens", while refusal maps to "content_filter". Stop reasons such as end_turn, tool_use, and pause_turn remain complete responses because Responses API does not expose equivalent incomplete-detail reasons for them.
Usage mapping is intentionally lossy. Anthropic reports input_tokens as the uncached remainder, with cache_read_input_tokens and cache_creation_input_tokens reported separately; this server maps cache_read_input_tokens to input_tokens_details.cached_tokens, drops cache_creation_input_tokens, and computes total_tokens as input_tokens + output_tokens. As a result total_tokens excludes cache tokens and the top-level input_tokens does not include the cached portion the way OpenAI Responses usage usually does. This is acceptable for current eval/accounting needs but should be revisited if cache-aware token accounting becomes load-bearing (e.g. for training cost attribution).
The first version is text/image/tool/thinking focused and non-streaming. Additional multimodal Anthropic blocks can be added later when Gym has a clear cross-provider representation for them. Because streaming is out of scope and transport is raw aiohttp (no SDK long-output guard), a single request with a large max_tokens — up to 128K on Opus 4.6+/Fable — can run long enough to hit ServerClient/connection timeouts; keep max_tokens modest until streaming is added, or expect to tune transport timeouts for big-output workloads. Request-level max_output_tokens overrides the config max_tokens per call.
Please check if this can be closed given https://github.com/NVIDIA-NeMo/Gym/tree/main/responses_api_agents/claude_code_agent