Skip to content

feat: claude model support #1146

Closed

Description

@cwing-nvidia

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 with id, name, input; tool results are type: "tool_result" content blocks referencing tool_use_id
  • System prompt: Anthropic uses a top-level system parameter rather than a system message in the messages array
  • Thinking/reasoning: Anthropic's extended thinking uses type: "thinking" content blocks with a budget_tokens parameter, 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 implementation
  • responses_api_models/claude_model/configs/claude_model.yaml — default config
  • responses_api_models/claude_model/requirements.txt
  • responses_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(): Convert NeMoGymResponseCreateParamsNonStreaming → Anthropic messages.create params
    • Map input items/messages to Anthropic message format
    • Extract system prompt to top-level system param
    • Convert tool definitions to Anthropic tool schema
    • Map previous tool calls/results to content blocks
  • anthropic_to_responses(): Convert Anthropic response → NeMoGymResponse
    • Map tool_use content blocks → NeMoGymResponseFunctionToolCall
    • Map text content blocks → NeMoGymResponseOutputText
    • Map thinking content blocks → NeMoGymResponseReasoningItem
    • Map usage (input_tokens, output_tokens) → NeMoGymResponseUsage

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

Acceptance Criteria

  • claude_model server 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 system param)
  • Rate limiting via max_concurrent_requests semaphore
  • 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

Activity

  1. added
    models
    on Apr 28, 2026
  2. ffrujeri commented on Jun 8, 2026

    @ffrujeri
    Contributor

    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 Completions ResponsesConverter, because Anthropic Messages has different semantics — but located in nemo_gym/anthropic_converter.py and 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 thinking config for modern Anthropic thinking modes such as {"type": "adaptive"}. On Opus 4.7/4.8 and Fable 5, thinking summaries are display: "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_tokens as 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 the claude-opus-4-8 example in the README; those models use {"type": "adaptive"} plus effort controls.
    • Pass provider-specific fields that are not modeled as typed config through extra_body instead of expanding the shared Responses schema.
    • Reject ambiguous thinking configuration when thinking, thinking_budget_tokens, and/or extra_body.thinking are set at the same time.
    • Normalize both host-only and /v1 base URLs so https://api.anthropic.com and https://api.anthropic.com/v1 both resolve to /v1/messages.
    • Fail loudly with NotImplementedError or ValueError for 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_model provider (NeMo Gym is the client, Anthropic is the backend): responses_to_anthropic (request) and anthropic_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), and anthropic_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_preview tools into Anthropic computer tools and beta headers.
    • It maps Responses computer_call to Anthropic tool_use named computer.
    • It maps Responses computer_call_output screenshots to Anthropic tool_result blocks containing image content.
    • It has basic input_image support by extracting base64 from data URLs, but it hardcodes media_type: "image/png".
    • It uses the Anthropic Python SDK (AsyncAnthropic) with DefaultAioHttpClient.

    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.
    {
      "instructions": "System instruction",
      "input": [
        {
          "type": "message",
          "role": "developer",
          "content": "Developer instruction"
        },
        {
          "type": "message",
          "role": "user",
          "content": "Ask a question"
        },
        {
          "type": "function_call_output",
          "call_id": "call_123",
          "output": "Tool result"
        }
      ],
      "tools": [
        {
          "type": "function",
          "name": "tool_name",
          "parameters": {}
        }
      ]
    }

    Model output uses the same trajectory-item style.

    {
      "output": [
        {
          "type": "reasoning",
          "summary": []
        },
        {
          "type": "message",
          "role": "assistant",
          "content": []
        },
        {
          "type": "function_call",
          "call_id": "call_123",
          "name": "tool_name",
          "arguments": "{}"
        }
      ]
    }
    Messages are role-scoped. Thinking, text, tool-use, and tool-result blocks inherit role from the enclosing message.
    {
      "system": [
        {
          "type": "text",
          "text": "System instruction"
        },
        {
          "type": "text",
          "text": "Developer instruction"
        }
      ],
      "messages": [
        {
          "role": "user",
          "content": [
            {
              "type": "text",
              "text": "Ask a question"
            }
          ]
        },
        {
          "role": "assistant",
          "content": [
            {
              "type": "thinking",
              "thinking": "Private reasoning"
            },
            {
              "type": "tool_use",
              "id": "call_123",
              "name": "tool_name",
              "input": {}
            }
          ]
        },
        {
          "role": "user",
          "content": [
            {
              "type": "tool_result",
              "tool_use_id": "call_123",
              "content": "Tool result"
            }
          ]
        }
      ],
      "tools": [
        {
          "name": "tool_name",
          "input_schema": {}
        }
      ]
    }

    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
    {
      "input": [
        {
          "type": "message",
          "role": "user",
          "content": "Hello"
        }
      ]
    }
    {
      "messages": [
        {
          "role": "user",
          "content": [
            {
              "type": "text",
              "text": "Hello"
            }
          ]
        }
      ]
    }

    System Or Developer Instructions

    Responses API Anthropic Messages
    {
      "instructions": "Answer concisely.",
      "input": [
        {
          "type": "message",
          "role": "developer",
          "content": "Use JSON when possible."
        },
        {
          "type": "message",
          "role": "user",
          "content": "Summarize this."
        }
      ]
    }
    {
      "system": [
        {
          "type": "text",
          "text": "Answer concisely."
        },
        {
          "type": "text",
          "text": "Use JSON when possible."
        }
      ],
      "messages": [
        {
          "role": "user",
          "content": [
            {
              "type": "text",
              "text": "Summarize this."
            }
          ]
        }
      ]
    }

    Function Tool Schema

    Responses API Anthropic Messages
    {
      "tools": [
        {
          "type": "function",
          "name": "lookup_weather",
          "description": "Look up weather.",
          "parameters": {
            "type": "object",
            "properties": {
              "city": {
                "type": "string"
              }
            },
            "required": ["city"]
          },
          "strict": true
        }
      ]
    }
    {
      "tools": [
        {
          "name": "lookup_weather",
          "description": "Look up weather.",
          "input_schema": {
            "type": "object",
            "properties": {
              "city": {
                "type": "string"
              }
            },
            "required": ["city"]
          }
        }
      ]
    }

    Tool Call And Tool Result

    Responses API Anthropic Messages
    Assistant tool call:
    {
      "output": [
        {
          "type": "function_call",
          "call_id": "toolu_123",
          "name": "lookup_weather",
          "arguments": "{\"city\":\"Paris\"}"
        }
      ]
    }
    Assistant message content:
    {
      "role": "assistant",
      "content": [
        {
          "type": "tool_use",
          "id": "toolu_123",
          "name": "lookup_weather",
          "input": {
            "city": "Paris"
          }
        }
      ]
    }
    Tool result input:
    {
      "input": [
        {
          "type": "function_call_output",
          "call_id": "toolu_123",
          "output": "Sunny"
        }
      ]
    }
    User message content:
    {
      "role": "user",
      "content": [
        {
          "type": "tool_result",
          "tool_use_id": "toolu_123",
          "content": "Sunny"
        }
      ]
    }

    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
    {
      "output": [
        {
          "type": "reasoning",
          "summary": [
            {
              "type": "summary_text",
              "text": "I should check the constraints first."
            }
          ],
          "encrypted_content": "encrypted-signature"
        },
        {
          "type": "message",
          "role": "assistant",
          "content": [
            {
              "type": "output_text",
              "text": "The answer is 42."
            }
          ]
        }
      ]
    }
    {
      "role": "assistant",
      "content": [
        {
          "type": "thinking",
          "thinking": "I should check the constraints first.",
          "signature": "encrypted-signature"
        },
        {
          "type": "text",
          "text": "The answer is 42."
        }
      ]
    }

    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
    {
      "incomplete_details": {
        "reason": "max_output_tokens"
      }
    }
    {
      "stop_reason": "model_context_window_exceeded"
    }

    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
    {
      "input": [
        {
          "type": "message",
          "role": "user",
          "content": [
            {
              "type": "input_text",
              "text": "What is in this image?"
            },
            {
              "type": "input_image",
              "image_url": "data:image/png;base64,..."
            }
          ]
        }
      ]
    }
    {
      "messages": [
        {
          "role": "user",
          "content": [
            {
              "type": "text",
              "text": "What is in this image?"
            },
            {
              "type": "image",
              "source": {
                "type": "base64",
                "media_type": "image/png",
                "data": "..."
              }
            }
          ]
        }
      ]
    }

    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.

  3. moved this from Dev WIP to Review WIP in NeMo Gym 0.4.0 - July 1on Jun 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

models

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions