Repository navigation
feat: Implement Gym agent server for Codex CLI agent harness. - #2095
Merged
Merged
Conversation
Contributor
|
🌿 Preview your docs: https://nvidia-preview-ffrujeri-feat-codex-agent.docs.buildwithfern.com/nemo/gym Here are the markdown pages you've updated: |
Signed-off-by: Felipe Vieira Frujeri <[email protected]>
Signed-off-by: Felipe Vieira Frujeri <[email protected]>
ffrujeri
force-pushed
the
ffrujeri/feat/codex-agent
branch
from
July 21, 2026 21:32
1e1ec18 to
a6f53f3
Compare
Signed-off-by: Felipe Vieira Frujeri <[email protected]>
ffrujeri
marked this pull request as ready for review
July 22, 2026 16:48
ananthsub
previously approved these changes
Jul 23, 2026
ananthsub
left a comment
Contributor
There was a problem hiding this comment.
LGTM! a few small comments inline, but overall this is great!
…eam error, effective model name, npm prefix -g, doc multi-turn collapse). Signed-off-by: Felipe Vieira Frujeri <[email protected]>
ananthsub
approved these changes
Jul 23, 2026
ananthsub
added a commit
to ananthsub/Gym
that referenced
this pull request
Jul 28, 2026
Blackbox harnesses that speak the OpenAI Chat Completions API over SSE (e.g. the OpenClaw agent PinchBench runs) send stream:true, which the strict NeMoGymChatCompletionCreateParamsNonStreaming model rejects. Mirror the /v1/responses streaming seam (NVIDIA-NeMo#2095) for chat/completions: a shared chat_completions_dispatch route validates requests through the same strict model (unchanged 422 behavior, including byte-for-byte detail parity via include_url=False) and, for a genuine stream:true, sanitizes the wire body, delegates to the server's existing non-streaming chat_completions(), and re-emits the complete response as chat.completion.chunk SSE terminated by data: [DONE]. The backend call stays non-streaming, so retries and error handling are unaffected. This path is for eval-only streaming clients: token ids/logprobs are not carried in the chunk schema, and a client that does not request usage (stream_options.include_usage) yields a captured record without token counts. Signed-off-by: Ananth Subramaniam <[email protected]>
ananthsub
added a commit
that referenced
this pull request
Jul 28, 2026
…2130) ## Summary fixes #2099 Some tools that run a model through Gym only work if the model server accepts streaming requests. They send `stream: true` on `/v1/chat/completions` and expect the reply back as a series of small events. Today Gym model servers reject `stream: true` — the request fails validation — so these tools can't point at a Gym model server and have to call the model endpoint directly. When they do that, they lose what the Gym model server adds: one consistent request format across providers, and per-call capture. The OpenClaw agent that PinchBench runs is the case that prompted this. This change makes `/v1/chat/completions` accept `stream: true`. The model server still calls its backend exactly as it does now: one normal request, wait for the complete reply. Once it has the full reply, it sends it back to the caller as a stream of standard `chat.completion.chunk` events ending with `data: [DONE]`. This is the same approach already used for `/v1/messages` (Claude Code) and, in #2095, for `/v1/responses` (Codex). Because the server still waits for the whole reply before sending anything, this does not make responses arrive sooner — the only goal is to accept the streaming request shape these tools require. Two useful consequences of keeping the backend call non-streaming: the existing retry and error handling still apply (nothing has been sent to the caller yet when a failure happens), and token id / logprob capture is unchanged (streaming here is for eval-only tools, and those fields aren't part of the chunk format anyway). ## How it works - Non-streaming requests are unchanged, including the same validation errors. - For `stream: true`, the server removes the streaming-only fields (`stream`, `stream_options`) and any unknown fields the tool added, validates the rest against the normal request model, calls the server's existing `chat_completions()`, then turns the complete reply into chunks: the role, then reasoning / content / tool calls when present, then a final chunk carrying the finish reason, then a usage chunk if the caller asked for usage, then `data: [DONE]`. New file `nemo_gym/chat_streaming.py` does the request cleanup, validation, and chunk generation. The routing change is in `SimpleResponsesAPIModel`. This covers only `/v1/chat/completions`; streaming for `/v1/responses` is a separate change (#2095). ## Test plan - New `tests/unit_tests/test_chat_completions_streaming.py` (23 tests): request cleanup, validation, chunk generation (content, reasoning, tool calls, usage, multiple choices, empty choices), and the route over an HTTP test client (non-streaming JSON, strict 422, streaming SSE, dropping unknown fields, invalid params → 422, and servers whose `chat_completions()` takes a leading `request` argument). Fidelity is checked by feeding the generated stream back through the capture code that rebuilds a reply from chunks. - No regressions: `test_base_responses_api_model.py` and `test_openai_utils.py` (71 passed), and the `openai_model` and `vllm_model` server suites (80 passed), which exercise both `chat_completions()` argument shapes over real HTTP. - Live check: a real uvicorn server driven by the real `openai` Python client with `stream: true` and `include_usage` rebuilt the full reply (content, reasoning, tool call, finish reason, usage) from the streamed chunks. - ruff and pre-commit are clean. Signed-off-by: Ananth Subramaniam <[email protected]>
OlegSudakov
pushed a commit
to OlegSudakov/Gym
that referenced
this pull request
Aug 7, 2026
…-NeMo#2095) ## Summary Integrates the OpenAI Codex CLI (`codex exec`) as a built-in NeMo Gym agent harness, mirroring the Claude Code agent's architecture (NVIDIA-NeMo#1336, NVIDIA-NeMo#1603). Any Gym environment can now evaluate models inside the Codex harness — against OpenAI directly, or against any backend Gym serves via a model server. Implements NVIDIA-NeMo#1389 (part of NVIDIA-NeMo#1042). The central constraint: Codex removed `wire_api = "chat"` (openai/codex#7782) and only speaks the **Responses API over SSE**. Where Claude Code needed a Messages ↔ Responses mapping (`/v1/messages`), Codex needs Gym's *native* format plus a streaming envelope and tolerance for its wire dialect. So this PR has two parts: **Core seam — every Gym model server speaks the streaming Responses dialect** (`nemo_gym/responses_streaming.py`, dispatch route on `SimpleResponsesAPIModel`): - Non-streaming `/v1/responses` requests are unchanged (strict validation, same 422 shape). - `stream: true` requests are sanitized onto the strict params model and the complete response is re-emitted as synthesized SSE (`response.created` → `response.output_item.done` per item → `response.completed` — the minimal sequence streaming clients require, verified against codex-cli 0.144.4). - The sanitizer degrades gracefully instead of 422-ing the rollout: drops unknown bookkeeping fields (`client_metadata`, `prompt_cache_key`), flattens `namespace` tool specs to `<ns>__<tool>` functions (and splits the names back into `namespace` + `name` on the way out — the wire shape Codex's tool router requires), hoists function tools out of code-mode `additional_tools` carriers, hoists leading developer messages into `instructions` (strict chat backends admit exactly one system message at position 0), and prunes SDK-unknown nested fields via generic `extra_forbidden` retry (e.g. `reasoning.context`). - Converter fixes in `responses_converter.py`: `instructions` was silently dropped in Responses → ChatCompletions conversion — now mapped to a leading system message (also fixes the latent loss of Claude Code's system prompt on the vLLM path); when `instructions` is present, the leading system/developer run is folded into that single system message. **Agent — `responses_api_agents/codex_agent/`:** - Runs `codex exec --json --ephemeral --skip-git-repo-check` per request with a fresh generated `CODEX_HOME` (config.toml) and scratch `--cd` workdir, both removed afterwards. - Gym-owned model provider with `env_key` auth — no `codex login`/auth.json needed. `model_server` ref (with `/ng-rollout/<id>` capture correlation) or direct `openai_base_url`. - Isolation defaults: `approval_policy=never`, analytics/history/update-checks off, `web_search` disabled, `features.multi_agent/code_mode` off. `sandbox_mode` configurable (default `danger-full-access`, mirroring the Claude agent's skip-permissions default — Gym envs provide their own isolation). - Model-name pinning: for models Codex recognizes, model-family gating enables code mode, which moves tools into carriers chat-served models cannot drive; `model: null` + `model_server` writes a `gym-policy-model` placeholder to keep classic function tools (Gym servers substitute their configured model anyway). - Gym MCP tools: `/seed_session` metadata becomes a per-rollout streamable-HTTP `mcp_servers` entry with the session token on `http_headers`. - Skills staged into `CODEX_HOME/skills/` from the run-level `skills_ref` (native discovery, no `--bare` analog needed). - Timeout is the runaway bound (no `--max-turns` equivalent): kill on timeout → empty response → verify still runs (reward 0). Codex runs in its own process group and timeout kills the whole group — the npm shim's vendored-binary child otherwise survives and holds the stdout pipe open past the kill. - JSONL events map to a uniform trajectory shape (`agent_message`/`reasoning` → messages with `<think>` prefixes; `command_execution`/`mcp_tool_call`/`file_change`/`web_search`/`todo_list` → `function_call` + `function_call_output` pairs; `turn.completed` → usage incl. cached/reasoning details). A run ending on buffered reasoning is surfaced as a think-tagged message (vLLM reasoning parsers sometimes route the final answer there). - `extra_config` deep-merge knob for arbitrary `config.toml` content; per-rollout Gym MCP entries win name collisions. Also: composed showcase configs `reasoning_gym_codex_agent[_model_server].yaml`, README(s), agent-skills docs updated with the Codex staging location. ## Test plan Unit tests pass (full suite `1270 passed, 31 skipped`; ruff + pre-commit clean). New coverage: ~45 agent tests (command/config/TOML generation, `CODEX_HOME` staging + cleanup, timeout/process-group kill, MCP config, rollout correlation, skills forwarding, event parsing) and ~28 core tests (sanitizer, SSE synthesis, dispatch route incl. non-streaming strict-validation regression, converter `instructions` mapping). Unit tests mock `asyncio.create_subprocess_exec`; the real CLI and full stack were smoke-tested against codex-cli 0.144.4 with a vLLM-dialect model server (`inference-api` Qwen3.6-35B backend): - [x] **Streaming dialect via curl**: `stream: true` + codex bookkeeping fields against a live `vllm_model` server returns `response.created` / `output_item.done` / `response.completed` SSE. - [x] **Real CLI shell round trip**: `codex exec` against the Gym model server — model called `exec_command`, Codex executed `` /bin/bash -lc 'echo $((17*23))' `` → `391`, multi-turn replay (reasoning + function_call + output) validated, `turn.completed` usage reported. - [x] **MCP round trip**: header-gated streamable-HTTP FastMCP server (the Gym resources-server stack) — namespaced `function_call` routed to the MCP tool with the per-rollout session token, result returned to the model. - [x] **Full eval loop**: `gym env start --resources-server reasoning_gym/reasoning_gym_codex_agent_model_server --model-type vllm_model` + `gym eval run --no-serve ... --limit 2` → 2/2 rollouts with rewards, `turns_used`, token usage, and aggregate metrics. - [x] **Timeout degradation**: one live rollout exceeded the 600 s budget and landed as an empty, reward-0 rollout (and exposed the orphaned-child kill bug this PR fixes with process-group kill). ### Smoke test details (reproducible) `env.yaml` (any OpenAI-compatible chat endpoint): ```yaml policy_base_url: https://<host>/v1 policy_api_key: <key> policy_model_name: <model> ``` ```bash gym env start \ --resources-server reasoning_gym/reasoning_gym_codex_agent_model_server \ --model-type vllm_model gym eval run --no-serve \ --agent reasoning_gym_codex_agent_model_server \ --input resources_servers/reasoning_gym/data/example.jsonl \ --output codex_rollout.jsonl --limit 1 ``` Standalone CLI seam check (no resources server) — take the model server URL from the `gym env start` log: ```bash mkdir -p /tmp/codex_home && cat > /tmp/codex_home/config.toml <<EOF model = "<policy_model_name>" # explicit name avoids model-family code-mode gating model_provider = "gym" approval_policy = "never" sandbox_mode = "danger-full-access" [model_providers.gym] name = "gym" base_url = "$URL/v1" env_key = "GYM_API_KEY" wire_api = "responses" EOF CODEX_HOME=/tmp/codex_home GYM_API_KEY=local \ codex exec --json --ephemeral --skip-git-repo-check "Compute 17*23 with a shell command." < /dev/null ``` ## Limitations - Eval only — token IDs / logprobs not wired up (same as the Claude Code agent). - Token counts come from Codex's own `turn.completed` usage reporting; `turns_used` counts assistant messages. - Code mode (JS tool orchestration) is fundamentally incompatible with chat-served backends; the seam degrades it gracefully (function tools preserved, JS `exec` dropped with a warning), but the supported path is classic function tools via explicit model naming. - `reasoning_gym_codex_agent*` configs are `verified: false` pending reward-profile baselining. Closes NVIDIA-NeMo#1389. --------- Signed-off-by: Felipe Vieira Frujeri <[email protected]>
OlegSudakov
pushed a commit
to OlegSudakov/Gym
that referenced
this pull request
Aug 7, 2026
…VIDIA-NeMo#2130) ## Summary fixes NVIDIA-NeMo#2099 Some tools that run a model through Gym only work if the model server accepts streaming requests. They send `stream: true` on `/v1/chat/completions` and expect the reply back as a series of small events. Today Gym model servers reject `stream: true` — the request fails validation — so these tools can't point at a Gym model server and have to call the model endpoint directly. When they do that, they lose what the Gym model server adds: one consistent request format across providers, and per-call capture. The OpenClaw agent that PinchBench runs is the case that prompted this. This change makes `/v1/chat/completions` accept `stream: true`. The model server still calls its backend exactly as it does now: one normal request, wait for the complete reply. Once it has the full reply, it sends it back to the caller as a stream of standard `chat.completion.chunk` events ending with `data: [DONE]`. This is the same approach already used for `/v1/messages` (Claude Code) and, in NVIDIA-NeMo#2095, for `/v1/responses` (Codex). Because the server still waits for the whole reply before sending anything, this does not make responses arrive sooner — the only goal is to accept the streaming request shape these tools require. Two useful consequences of keeping the backend call non-streaming: the existing retry and error handling still apply (nothing has been sent to the caller yet when a failure happens), and token id / logprob capture is unchanged (streaming here is for eval-only tools, and those fields aren't part of the chunk format anyway). ## How it works - Non-streaming requests are unchanged, including the same validation errors. - For `stream: true`, the server removes the streaming-only fields (`stream`, `stream_options`) and any unknown fields the tool added, validates the rest against the normal request model, calls the server's existing `chat_completions()`, then turns the complete reply into chunks: the role, then reasoning / content / tool calls when present, then a final chunk carrying the finish reason, then a usage chunk if the caller asked for usage, then `data: [DONE]`. New file `nemo_gym/chat_streaming.py` does the request cleanup, validation, and chunk generation. The routing change is in `SimpleResponsesAPIModel`. This covers only `/v1/chat/completions`; streaming for `/v1/responses` is a separate change (NVIDIA-NeMo#2095). ## Test plan - New `tests/unit_tests/test_chat_completions_streaming.py` (23 tests): request cleanup, validation, chunk generation (content, reasoning, tool calls, usage, multiple choices, empty choices), and the route over an HTTP test client (non-streaming JSON, strict 422, streaming SSE, dropping unknown fields, invalid params → 422, and servers whose `chat_completions()` takes a leading `request` argument). Fidelity is checked by feeding the generated stream back through the capture code that rebuilds a reply from chunks. - No regressions: `test_base_responses_api_model.py` and `test_openai_utils.py` (71 passed), and the `openai_model` and `vllm_model` server suites (80 passed), which exercise both `chat_completions()` argument shapes over real HTTP. - Live check: a real uvicorn server driven by the real `openai` Python client with `stream: true` and `include_usage` rebuilt the full reply (content, reasoning, tool call, finish reason, usage) from the streamed chunks. - ruff and pre-commit are clean. Signed-off-by: Ananth Subramaniam <[email protected]>
5 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Integrates the OpenAI Codex CLI (
codex exec) as a built-in NeMo Gym agent harness, mirroring the Claude Code agent's architecture (#1336, #1603). Any Gym environment can now evaluate models inside the Codex harness — against OpenAI directly, or against any backend Gym serves via a model server. Implements #1389 (part of #1042).The central constraint: Codex removed
wire_api = "chat"(openai/codex#7782) and only speaks the Responses API over SSE. Where Claude Code needed a Messages ↔ Responses mapping (/v1/messages), Codex needs Gym's native format plus a streaming envelope and tolerance for its wire dialect. So this PR has two parts:Core seam — every Gym model server speaks the streaming Responses dialect (
nemo_gym/responses_streaming.py, dispatch route onSimpleResponsesAPIModel):/v1/responsesrequests are unchanged (strict validation, same 422 shape).stream: truerequests are sanitized onto the strict params model and the complete response is re-emitted as synthesized SSE (response.created→response.output_item.doneper item →response.completed— the minimal sequence streaming clients require, verified against codex-cli 0.144.4).client_metadata,prompt_cache_key), flattensnamespacetool specs to<ns>__<tool>functions (and splits the names back intonamespace+nameon the way out — the wire shape Codex's tool router requires), hoists function tools out of code-modeadditional_toolscarriers, hoists leading developer messages intoinstructions(strict chat backends admit exactly one system message at position 0), and prunes SDK-unknown nested fields via genericextra_forbiddenretry (e.g.reasoning.context).responses_converter.py:instructionswas silently dropped in Responses → ChatCompletions conversion — now mapped to a leading system message (also fixes the latent loss of Claude Code's system prompt on the vLLM path); wheninstructionsis present, the leading system/developer run is folded into that single system message.Agent —
responses_api_agents/codex_agent/:codex exec --json --ephemeral --skip-git-repo-checkper request with a fresh generatedCODEX_HOME(config.toml) and scratch--cdworkdir, both removed afterwards.env_keyauth — nocodex login/auth.json needed.model_serverref (with/ng-rollout/<id>capture correlation) or directopenai_base_url.approval_policy=never, analytics/history/update-checks off,web_searchdisabled,features.multi_agent/code_modeoff.sandbox_modeconfigurable (defaultdanger-full-access, mirroring the Claude agent's skip-permissions default — Gym envs provide their own isolation).model: null+model_serverwrites agym-policy-modelplaceholder to keep classic function tools (Gym servers substitute their configured model anyway)./seed_sessionmetadata becomes a per-rollout streamable-HTTPmcp_serversentry with the session token onhttp_headers.CODEX_HOME/skills/from the run-levelskills_ref(native discovery, no--bareanalog needed).--max-turnsequivalent): kill on timeout → empty response → verify still runs (reward 0). Codex runs in its own process group and timeout kills the whole group — the npm shim's vendored-binary child otherwise survives and holds the stdout pipe open past the kill.agent_message/reasoning→ messages with<think>prefixes;command_execution/mcp_tool_call/file_change/web_search/todo_list→function_call+function_call_outputpairs;turn.completed→ usage incl. cached/reasoning details). A run ending on buffered reasoning is surfaced as a think-tagged message (vLLM reasoning parsers sometimes route the final answer there).extra_configdeep-merge knob for arbitraryconfig.tomlcontent; per-rollout Gym MCP entries win name collisions.Also: composed showcase configs
reasoning_gym_codex_agent[_model_server].yaml, README(s), agent-skills docs updated with the Codex staging location.Test plan
Unit tests pass (full suite
1270 passed, 31 skipped; ruff + pre-commit clean). New coverage: ~45 agent tests (command/config/TOML generation,CODEX_HOMEstaging + cleanup, timeout/process-group kill, MCP config, rollout correlation, skills forwarding, event parsing) and ~28 core tests (sanitizer, SSE synthesis, dispatch route incl. non-streaming strict-validation regression, converterinstructionsmapping).Unit tests mock
asyncio.create_subprocess_exec; the real CLI and full stack were smoke-tested against codex-cli 0.144.4 with a vLLM-dialect model server (inference-apiQwen3.6-35B backend):stream: true+ codex bookkeeping fields against a livevllm_modelserver returnsresponse.created/output_item.done/response.completedSSE.codex execagainst the Gym model server — model calledexec_command, Codex executed/bin/bash -lc 'echo $((17*23))'→391, multi-turn replay (reasoning + function_call + output) validated,turn.completedusage reported.function_callrouted to the MCP tool with the per-rollout session token, result returned to the model.gym env start --resources-server reasoning_gym/reasoning_gym_codex_agent_model_server --model-type vllm_model+gym eval run --no-serve ... --limit 2→ 2/2 rollouts with rewards,turns_used, token usage, and aggregate metrics.Smoke test details (reproducible)
env.yaml(any OpenAI-compatible chat endpoint):gym env start \ --resources-server reasoning_gym/reasoning_gym_codex_agent_model_server \ --model-type vllm_model gym eval run --no-serve \ --agent reasoning_gym_codex_agent_model_server \ --input resources_servers/reasoning_gym/data/example.jsonl \ --output codex_rollout.jsonl --limit 1Standalone CLI seam check (no resources server) — take the model server URL from the
gym env startlog:Limitations
turn.completedusage reporting;turns_usedcounts assistant messages.execdropped with a warning), but the supported path is classic function tools via explicit model naming.reasoning_gym_codex_agent*configs areverified: falsepending reward-profile baselining.Closes #1389.