Repository navigation
Description
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 #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 (Add inference provider server for hosted inference providers #1285) — that's for OAI-compatible hosted providers - Gemini native API support (feat: gemini model support #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: Add inference provider server for hosted inference providers #1285 (chat_completions_model for hosted providers — explicitly defers Claude to this issue)
- Related: support anthropic /v1/messages #1384 (duplicate of this issue)
- Sibling: feat: gemini model support #1147 (Gemini native support)
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity
ffrujeri commentedon Jun 8, 2026
Anthropic Model Design Note
anthropic_modelis a native Anthropic Messages API model server behind NeMo Gym's/v1/responsesinterface. It exists because Anthropic's/v1/messagesformat is not OpenAI-compatible: system prompts are top-level, content is block-based, tool calls aretool_useblocks, tool results aretool_resultblocks, 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:
nemo_gym.server_utils.request()for raw aiohttp transport, matching Gym's high-concurrency guidance and avoiding SDK/httpx connection-pool behavior.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.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.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.extra_bodyinstead of expanding the shared Responses schema.thinking,thinking_budget_tokens, and/orextra_body.thinkingare set at the same time./v1base URLs sohttps://api.anthropic.comandhttps://api.anthropic.com/v1both resolve to/v1/messages.NotImplementedErrororValueErrorfor unsupported content types rather than silently dropping unknown blocks.Bidirectional Shared Converter
AnthropicConverterlives innemo_gym/anthropic_converter.py(alongside the precedent set bynemo_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:anthropic_modelprovider (NeMo Gym is the client, Anthropic is the backend):responses_to_anthropic(request) andanthropic_to_responses(response).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 egressresponses_to_anthropicpath; relocating them into the server is a marked follow-up.)Comparison With Existing Model Servers
openai_modelis a thin passthrough to OpenAI-compatible/responsesand/chat/completions. It needs almost no conversion because the upstream API already speaks the expected shape.vllm_modeltargets 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_providerfrom 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_modelis 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.pyin the Turing Gym branch (commitc465bbe). It is useful prior art, but it solves a narrower problem than this server.That implementation is specialized for Anthropic computer-use/browser workflows:
computer_use_previewtools into Anthropic computer tools and beta headers.computer_callto Anthropictool_usenamedcomputer.computer_call_outputscreenshots to Anthropictool_resultblocks containingimagecontent.input_imagesupport by extracting base64 from data URLs, but it hardcodesmedia_type: "image/png".AsyncAnthropic) withDefaultAioHttpClient.This
anthropic_modelis intended as the generic Anthropic Messages bridge for NeMo Gym policy models:nemo_gym.server_utils.request()rather than the Anthropic SDK.The main lesson from the prototype is that Anthropic image blocks fit naturally as content blocks inside role-scoped messages, including inside
tool_resultcontent 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
inputlist, and a response contains an orderedoutputlist. Anthropic Messages is message-oriented instead: a request has top-levelsystem, top-leveltools, and amessagesarray where each message owns the role for all of its content blocks.Model output uses the same trajectory-item style.
The converter's job is therefore mostly structural: flatten or group Responses items into Anthropic role-scoped messages, move
instructionsplus system/developer input messages to top-levelsystem, translate function tools to Anthropictools, and translate thinking blocks to Responsesreasoningitems 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
System Or Developer Instructions
Function Tool Schema
Tool Call And Tool Result
Tool Choice
Responses API
tool_choicemaps onto Anthropic's typedtool_choiceobject: 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 raisesNotImplementedError.Thinking And Reasoning
The example above assumes summarized thinking. By default on Opus 4.7/4.8 and Fable 5 the
thinkingfield is empty, so the reasoning item'ssummary_textis empty whileencrypted_content(the blocksignature) 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 storedsummary_textis replayed verbatim as thethinkingfield with its original signature. A reasoning item carrying multiplesummary_textentries 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
max_tokensmaps the same way.refusalmaps tocontent_filter; complete reasons such asend_turn,tool_use, andpause_turndo not setincomplete_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.
The converter maps
input_textto Anthropictext, andinput_imageto Anthropicimage. For data URLs, it splitsdata:image/png;base64,...intomedia_type: "image/png"and base64data. Supported media types areimage/jpeg,image/png,image/gif, andimage/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 sharednemo_gym/anthropic_converter.pyand 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 keepsextra_bodyas 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 nestedanthropic_optionsmodel. 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_tokensandmodel_context_window_exceededmap toincomplete_details.reason = "max_output_tokens", whilerefusalmaps to"content_filter". Stop reasons such asend_turn,tool_use, andpause_turnremain complete responses because Responses API does not expose equivalent incomplete-detail reasons for them.Usage mapping is intentionally lossy. Anthropic reports
input_tokensas the uncached remainder, withcache_read_input_tokensandcache_creation_input_tokensreported separately; this server mapscache_read_input_tokenstoinput_tokens_details.cached_tokens, dropscache_creation_input_tokens, and computestotal_tokensasinput_tokens + output_tokens. As a resulttotal_tokensexcludes cache tokens and the top-levelinput_tokensdoes 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 hitServerClient/connection timeouts; keepmax_tokensmodest until streaming is added, or expect to tune transport timeouts for big-output workloads. Request-levelmax_output_tokensoverrides the configmax_tokensper call.feat: Add a default /v1/messages (Anthropic Messages) route to the ba…
feat: Add a default /v1/messages (Anthropic Messages) route to the ba…
anwithk commentedon Jun 30, 2026
Please check if this can be closed given https://github.com/NVIDIA-NeMo/Gym/tree/main/responses_api_agents/claude_code_agent