Repository navigation
Conversation
Closes NVIDIA-NeMo#1305. gym eval run --no-serve +agent_url=http://host:port (or --agent-url) dispatches each row's /run directly to an external agent endpoint instead of resolving a named Gym agent server. - agent_ref: {"url": ...} rows flow through collection, resume, aggregate metrics, and reward profiling via a shared row_agent_key() accessor (nemo_gym/global_config.py) - external dispatch uses the pooled aiohttp client with a per-request timeout (agent_run_timeout_secs, default 1800s) and bounded connect/disconnect retries; every failure — timeout, non-2xx, malformed or interrupted body — becomes an _ng_failure_class="external_agent_error" row in the failures sidecar (never a crash) and is retried on resume under the existing attempt cap - /aggregate_metrics on the external agent is skipped gracefully when not implemented (404/405/501 or connect failure); metrics artifacts carry url-form refs; wandb metric labels are sanitized to host_port - ServerClient construction is lazy in both run_examples and _call_aggregate_metrics: URL-only runs contact no head server and need no config_paths - row-level agent_ref.url values must match +agent_url, so a dataset cannot route tasks (and their answer keys) to arbitrary hosts - on resume, a changed agent_url is re-stamped onto pending rows, and completed rows' in-memory grouping is re-keyed so one live agent aggregates all hops Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: adil-a <[email protected]>
Fixes from the pr-review pass on the agent_url feature:
- exclude failure/no-persist rows from /aggregate_metrics grouping so the
payload matches what gym eval aggregate would read back and external
agents never receive reward-less failure stubs; skip aggregation
entirely when no successful rollouts remain
- require 'reward' and 'response' keys on external /run responses (agents
reporting failures via the sentinel contract are exempt), so a
nonconforming success row can no longer crash reward profiling later
- cap url-dispatch concurrency at the shared client's per-host connection
limit instead of warning: queued requests were burning their
agent_run_timeout_secs budget waiting for a pool slot
- resuming with pending url rows now requires +agent_url (frozen
materialized URLs are never dispatched unconfirmed)
- reject agent_url values carrying a query string or fragment ('/run'
would land inside the query)
- allow_redirects=False on external calls: aiohttp converts a redirected
POST into a body-less GET; fail loudly with the 3xx instead
- read the aggregate response body before early returns (connection
release); throttle external-failure logging via tqdm.write
- name-first canonical_agent_ref (global_config) keeps grouping, dispatch,
and emitted refs consistent for refs carrying both name and url;
reward profiling now raises loudly on rows with no usable agent_ref
instead of pandas silently dropping them
- share the 1800s timeout default via a module constant; include the URL
path in wandb metric labels; refresh stale docstrings and reword
insider comment phrasing; add --agent-url to the CLI flag-mapping test
table
Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: adil-a <[email protected]>
New page agent-server/drive-external-agent.mdx covering the +agent_url / --agent-url workflow from NVIDIA-NeMo#1305: the /run request and response contract (including the verifier_metadata trust boundary), the three-terminal quickstart, session-cookie threading for stateful environments, failure routing / timeouts / resume semantics, the optional _ng_failure_class sentinel contract for external agents, optional /aggregate_metrics, and concurrency notes. Touch-ups: --agent-url in the gym eval run flag table and examples (cli-commands.mdx), url-form agent_ref in the aggregate-metrics artifact schema, a pointer card on the evaluation index, and a README quickstart mention. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: adil-a <[email protected]>
Shorten the dispatch block comment, reword remaining insider phrasing in plain language, drop a comment restating its callee's docstring, and rename a test class whose name described the review process rather than what it tests. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: adil-a <[email protected]>
Contributor
Author
|
/ok to test e32e123 |
Contributor
|
🌿 Preview your docs: https://nvidia-preview-agent-url-rollout-collection.docs.buildwithfern.com/nemo/gym Here are the markdown pages you've updated: |
- derive _FALLBACK_PER_HOST_CONNECTION_LIMIT from GlobalAIOHTTPAsyncClientConfig (no drift) and correct its comment: the pre-initialization branch is the normal CLI path, not a test accommodation - print an end-of-run WARNING with the failure count and sidecar path when any rollout failed, so a non-resuming user cannot miss partial results - reject bare '?'/'#' delimiters in agent_url (urlparse reports them as empty query/fragment, slipping past the previous check with the same corruption) - soften the _agent_metric_label docstring: wandb sections on '/' (verified); ':' replacement is cosmetic only - simplify has_url_rows double negative to any(...), matching the dispatch-site predicate - pin malformed agent_ref shapes (str/list/int/null refs) to the consolidated missing-agent error; the pre-agent_url code crashed with AttributeError on truthy non-dict refs Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: adil-a <[email protected]>
Confirmed by an independent multi-lens review (finders with no development
context + two adversarial verifiers per finding):
- concurrency cap now reads the RUN's configured per-host limit (divided by
num_workers) when the shared client does not exist yet, instead of always
using the class default; consults the global config only if already loaded
(parsing would sys.exit in non-CLI processes) via new
is_global_config_dict_set()
- 3xx responses are explicit failures on /run and /aggregate_metrics
(aiohttp's response.ok passes them); /run failures name the Location target
- reject user:pass@ credentials in agent_url, and hide_input_in_errors on
RolloutCollectionConfig so validation errors cannot echo the secret
- /run success gate validates types, not just key presence: response must be
a JSON object and reward a number ('response': null previously poisoned the
main jsonl and crashed gym eval profile later)
- bounded retry now covers ClientOSError (mid-send ECONNRESET), the repo's
documented high-concurrency noise, alongside disconnects
- fresh runs clear the failures sidecar alongside the output file — stale
attempt rows were silently exhausting the resume retry budget (pre-existing,
amplified by external dispatch)
- resume URL-confirmation guard also covers completed url rows (aggregation
would POST result payloads to the frozen, unconfirmed URL)
- /run dispatch is name-first for refs carrying both name and url, matching
row_agent_key/aggregation precedence (shared _is_external_url_ref)
- url-shaped num_repeats dict keys get the same normalization as agent_url;
failure-log sampling counter resets per run; per-row error messages report
the row's real position (previously always 'Row 0' when limit was unset)
- docs: URL-keyed num_repeats dicts need a YAML config file (Hydra override
grammar cannot express them)
21 new tests, including an end-to-end sidecar-resume contract suite
(fail → sidecar → resume redispatch; attempt-cap gating; agent-set
_ng_failure_terminal honored) and a mutation-resistant concurrency-cap test
asserting the effective 'Querying with N' line.
Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: adil-a <[email protected]>
Remove narration and compress the load-bearing comments (constraints, non-obvious library behavior, trust rules) to one or two lines each. Pre-existing comments are untouched. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: adil-a <[email protected]>
# Conflicts: # nemo_gym/rollout_collection.py
- annotate the basic-auth-shaped test URL with 'pragma: allowlist secret' (the detect-secrets CI check flagged the intentional fixture) - drive-external-agent.mdx: note wrong-typed reward/response is also a failure; 'up to 3 attempts' not '3 retries'; document the user:pass@ credential rejection; note a row url mismatching --agent-url is an error Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: adil-a <[email protected]>
Contributor
Author
|
closing in favor of #2163 |
adil-a
added a commit
that referenced
this pull request
Jul 30, 2026
…gent services (#2163) Part of the external-agent-integration epic #1396. Supersedes the collector-side `agent_url` approach proposed in #2006 (closed unmerged in favor of this PR). ## What An agent server, `responses_api_agents/remote_agent/`, that drives an agent service running **outside Gym's process tree** (your own repo, your own infrastructure) through Gym's tool loop. The remote service implements one endpoint **compliant with the OpenAI `/v1/responses` contract**, and the two servers compose as Responses-speaking agents: `POST {agent_base_url}/v1/responses` — receives the conversation so far (the row's `responses_create_params` with accumulated output and tool results appended to `input`) and returns a Responses API object: unpaired `function_call` items to ask Gym to execute environment tools, paired call+output items as records of its own internal tools (passed through untouched), or a final assistant message to finish. Gym owns everything else: it seeds the session and holds its cookies, executes the asked-for tools against the resources server, appends results and calls the service again, validates each reply against the Responses API schema (failing the rollout on mismatch), verifies, and returns the verify response from `/run`. **The resources server is never exposed to the service** — tool execution, session cookies, and `verifier_metadata` all stay inside Gym. The service's own cookies are round-tripped per call so it can keep per-rollout state; the only network direction is Gym → service. To the collector it is a normal named agent — resume, aggregation, and profiling work unchanged. The loop is `simple_agent`'s `responses()` with two marked in-loop divergences — the model hop is a hardened POST to `agent_base_url`, and only *unpaired* function_calls are executed (a call the service already answered itself is its own record, not an ask) — plus the never-raise `/run` contract that turns transport/validation errors into failure rows, and one deliberate cookie difference: the service's own cookies are round-tripped to it but stay out of the outgoing Set-Cookie (they are its private session, not Gym's). `run()` mirrors `simple_agent`'s seed → self-post `/v1/responses` → verify. ## Why a server instead of collector-side `agent_url` (#2006) - The token-capture/training stack (#2124–#2128, unmerged) gates participation by the agent's **name in Gym's config**; a url-dispatched agent has no config entry and is excluded by construction. A named RemoteAgent is compatible by design — note this PR contains no capture wiring; a wiring example is a follow-up once that stack lands. - Failure handling, validation, timeouts, and session plumbing live in the agent-server layer — this server's `/run` implementation plus the shared SimpleServer/ServerClient plumbing — instead of being reimplemented inside the shared collection loop. - `/run` responsibilities stay in the agent-server layer; the collector stays agent-agnostic. - Same pattern as every other harness integration (claude_code_agent, codex, …). ## Failure contract Failures never raise out of `/run`: remote endpoint down (3 total connection attempts, `ClientOSError`/`ServerDisconnectedError` only; timeouts and all other errors fail after a single attempt), per-call and whole-rollout timeouts, malformed/interrupted replies, seed/verify errors, and internal bugs all become reward-0 sentinel verify-responses (`_ng_failure_class="remote_agent_error"`) that rollout collection routes to the failures sidecar and retries on resume — non-terminal failures only, up to `NEMO_GYM_MAX_ROLLOUT_ATTEMPTS` (default 3). An invalid Responses object from the service is terminal (a schema bug will not fix itself on retry); the terminal flag crosses the HTTP self-post boundary by exception name. Reused rollout/failures JSONL rows carrying stale result keys are sanitized rather than crashing or leaking routing flags. Tool-level errors are NOT rollout failures: an unknown tool name or malformed arguments come back to the service as that call's `function_call_output`, matching `simple_agent`'s semantics. ## Testing - 51 offline tests (mocked ServerClient + mocked aiohttp seam; the `/v1/responses` self-post is routed into the real `responses()` with the exception middleware emulated): config validation, loop mechanics (multi-turn tool execution, paired-call pass-through, unknown-tool feedback, malformed-arguments feedback, max_steps, service-cookie round-trip, usage accumulation), every transport failure mode → sentinel, terminal classification across the route boundary, semaphore bounds incl. release-on-failure, run-wallclock-after-semaphore semantics, aggregate proxy + bound, route-level serialization (HTTP 200, never 500). - **Stateful E2E in-suite**: the real `example_session_state_mgmt` counter server in-process; the service returns unpaired tool asks, GYM executes them on the seeded session, reward 1.0 through the real verifier — and the test asserts the service was fed the counter value Gym read back. - **Collector round-trip in-suite**: real `RolloutCollectionHelper.run_from_config` driving this agent — successes to the main JSONL, sentinel rows to the failures sidecar. - **Live E2E, off-host, real agent**: a containerized service (own network namespace) wrapping the **Claude CLI** (opus via an internal gateway) as the decision-maker, `agent_base_url` pointing at the container's bridge IP; the counter resources server stayed on loopback with a random port — unreachable from the container by construction. **5/5 rollouts reward 1.0**, trajectories reading `function_call → function_call_output → … → message`, real token usage accumulated across loop turns (~8.3k mean/rollout). The only network path was Gym → container. ## Follow-ups - run-mode (`/run`-exposing self-scoring services) as a config mode on this server - token-capture wiring example once #2124–#2128 land (the service would route its model calls through Gym's model server at the per-rollout prefixed URL) - per review discussion: opt-in bounded-retry/timeout kwargs on core `request()` (then this server's transport collapses onto core), and two additive core helpers with existing adopters — a failure-row builder (stirrup/pinchbench hand-roll the same) and an aggregate-metrics proxy helper (eight agents hand-roll it) 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: adil-a <[email protected]> Co-authored-by: Claude Fable 5 <[email protected]>
OlegSudakov
pushed a commit
to OlegSudakov/Gym
that referenced
this pull request
Aug 7, 2026
…gent services (NVIDIA-NeMo#2163) Part of the external-agent-integration epic NVIDIA-NeMo#1396. Supersedes the collector-side `agent_url` approach proposed in NVIDIA-NeMo#2006 (closed unmerged in favor of this PR). ## What An agent server, `responses_api_agents/remote_agent/`, that drives an agent service running **outside Gym's process tree** (your own repo, your own infrastructure) through Gym's tool loop. The remote service implements one endpoint **compliant with the OpenAI `/v1/responses` contract**, and the two servers compose as Responses-speaking agents: `POST {agent_base_url}/v1/responses` — receives the conversation so far (the row's `responses_create_params` with accumulated output and tool results appended to `input`) and returns a Responses API object: unpaired `function_call` items to ask Gym to execute environment tools, paired call+output items as records of its own internal tools (passed through untouched), or a final assistant message to finish. Gym owns everything else: it seeds the session and holds its cookies, executes the asked-for tools against the resources server, appends results and calls the service again, validates each reply against the Responses API schema (failing the rollout on mismatch), verifies, and returns the verify response from `/run`. **The resources server is never exposed to the service** — tool execution, session cookies, and `verifier_metadata` all stay inside Gym. The service's own cookies are round-tripped per call so it can keep per-rollout state; the only network direction is Gym → service. To the collector it is a normal named agent — resume, aggregation, and profiling work unchanged. The loop is `simple_agent`'s `responses()` with two marked in-loop divergences — the model hop is a hardened POST to `agent_base_url`, and only *unpaired* function_calls are executed (a call the service already answered itself is its own record, not an ask) — plus the never-raise `/run` contract that turns transport/validation errors into failure rows, and one deliberate cookie difference: the service's own cookies are round-tripped to it but stay out of the outgoing Set-Cookie (they are its private session, not Gym's). `run()` mirrors `simple_agent`'s seed → self-post `/v1/responses` → verify. ## Why a server instead of collector-side `agent_url` (NVIDIA-NeMo#2006) - The token-capture/training stack (NVIDIA-NeMo#2124–NVIDIA-NeMo#2128, unmerged) gates participation by the agent's **name in Gym's config**; a url-dispatched agent has no config entry and is excluded by construction. A named RemoteAgent is compatible by design — note this PR contains no capture wiring; a wiring example is a follow-up once that stack lands. - Failure handling, validation, timeouts, and session plumbing live in the agent-server layer — this server's `/run` implementation plus the shared SimpleServer/ServerClient plumbing — instead of being reimplemented inside the shared collection loop. - `/run` responsibilities stay in the agent-server layer; the collector stays agent-agnostic. - Same pattern as every other harness integration (claude_code_agent, codex, …). ## Failure contract Failures never raise out of `/run`: remote endpoint down (3 total connection attempts, `ClientOSError`/`ServerDisconnectedError` only; timeouts and all other errors fail after a single attempt), per-call and whole-rollout timeouts, malformed/interrupted replies, seed/verify errors, and internal bugs all become reward-0 sentinel verify-responses (`_ng_failure_class="remote_agent_error"`) that rollout collection routes to the failures sidecar and retries on resume — non-terminal failures only, up to `NEMO_GYM_MAX_ROLLOUT_ATTEMPTS` (default 3). An invalid Responses object from the service is terminal (a schema bug will not fix itself on retry); the terminal flag crosses the HTTP self-post boundary by exception name. Reused rollout/failures JSONL rows carrying stale result keys are sanitized rather than crashing or leaking routing flags. Tool-level errors are NOT rollout failures: an unknown tool name or malformed arguments come back to the service as that call's `function_call_output`, matching `simple_agent`'s semantics. ## Testing - 51 offline tests (mocked ServerClient + mocked aiohttp seam; the `/v1/responses` self-post is routed into the real `responses()` with the exception middleware emulated): config validation, loop mechanics (multi-turn tool execution, paired-call pass-through, unknown-tool feedback, malformed-arguments feedback, max_steps, service-cookie round-trip, usage accumulation), every transport failure mode → sentinel, terminal classification across the route boundary, semaphore bounds incl. release-on-failure, run-wallclock-after-semaphore semantics, aggregate proxy + bound, route-level serialization (HTTP 200, never 500). - **Stateful E2E in-suite**: the real `example_session_state_mgmt` counter server in-process; the service returns unpaired tool asks, GYM executes them on the seeded session, reward 1.0 through the real verifier — and the test asserts the service was fed the counter value Gym read back. - **Collector round-trip in-suite**: real `RolloutCollectionHelper.run_from_config` driving this agent — successes to the main JSONL, sentinel rows to the failures sidecar. - **Live E2E, off-host, real agent**: a containerized service (own network namespace) wrapping the **Claude CLI** (opus via an internal gateway) as the decision-maker, `agent_base_url` pointing at the container's bridge IP; the counter resources server stayed on loopback with a random port — unreachable from the container by construction. **5/5 rollouts reward 1.0**, trajectories reading `function_call → function_call_output → … → message`, real token usage accumulated across loop turns (~8.3k mean/rollout). The only network path was Gym → container. ## Follow-ups - run-mode (`/run`-exposing self-scoring services) as a config mode on this server - token-capture wiring example once NVIDIA-NeMo#2124–NVIDIA-NeMo#2128 land (the service would route its model calls through Gym's model server at the per-rollout prefixed URL) - per review discussion: opt-in bounded-retry/timeout kwargs on core `request()` (then this server's transport collapses onto core), and two additive core helpers with existing adopters — a failure-row builder (stirrup/pinchbench hand-roll the same) and an aggregate-metrics proxy helper (eight agents hand-roll it) 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: adil-a <[email protected]> Co-authored-by: Claude Fable 5 <[email protected]>
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.
Closes #1305 (part of the external-agent-integration epic #1396).
What
gym eval run --no-serve --agent-url http://host:port(or+agent_url=...) dispatches rollout collection directly to an external agent HTTP service — an agent living in your own repo and infrastructure, not packaged as a Gym agent server. The external agent's/runreceives the same JSONL row payload Gym agents receive and returns a result in the same JSON shape as a Gym/verifyresponse; the contract is documented in the newdrive-external-agent.mdxpage.Scope per the issue: trusted agents only — the full row, including
verifier_metadata(i.e. the task's answer key), is sent to the endpoint. This is warned about explicitly in the config field description and the docs.Design highlights
agent_ref: {"url": ...}, defaulted from+agent_urlonly onto rows without their own ref (same semantics as+agent_name); a sharedrow_agent_key()accessor (name-first for refs carrying both keys) is used everywhere agent identity is read — progress counting, dict-formnum_repeats, aggregation grouping, reward profiling — and resume keys its cache by task/rollout index, not by agent, so both ref shapes work unchanged.server_utils.request(), whose unbounded connection retries would hang the run on a down endpoint; connection errors get at most 3 tries, every request has a timeout (agent_run_timeout_secs, default 1800s), and every failure — connection, timeout, non-2xx, malformed or interrupted body, missing or wrongly-typedreward/response— becomes a_ng_failure_class="external_agent_error"row in the failures sidecar (a companion*_failures.jsonl; cleared on fresh runs, retried on resume up to the existing per-rollout attempt cap), never aborting the run or contaminating aggregate metrics; a run with failures ends with a console WARNING giving the counts.ServerClient— which needsconfig_pathsand a live head server, and whose only job is resolvingagent_ref.nameinto host:port — is now constructed only when a named ref actually needs resolving, in both the dispatch and aggregation paths, so a collector on a different machine than the Gym servers, a fully self-scoring external agent with no Gym servers at all, or offlinegym eval aggregateof url-ref rollout files after the servers are gone all need only the agent URL reachable.+agent_url(a dataset cannot route rows to arbitrary hosts); resuming a run whose rows — pending or completed — carry a frozen URL requires re-passing+agent_urlto confirm the destination; URLs with query strings, fragments, or embeddeduser:pass@credentials are rejected (validation errors never echo the URL); redirects are not followed — the request fails with the 3xx status, naming theLocationtarget, rather than letting the HTTP client silently convert the POST into a GET./aggregate_metricsoptional: any failure — 404/405/501 (reported as "not implemented"), other HTTP errors, connection failure, or a malformed body — warns and skips that agent's aggregate metrics; rollout artifacts andgym eval profileare unaffected.agent_urlshares a single per-host connection pool and time queued for a connection counts againstagent_run_timeout_secs, so dispatch caps concurrency at the pool limit (read from the shared HTTP client if already initialized, otherwise computed from the run's loaded global config, falling back to the 1024 default).Testing
_ng_failure_terminalhonored), resume re-stamping and guards, aggregation filtering and grouping, profiler url-ref round-trip, CLI flag mapping, and an in-process FastAPI/runintegration driving the fullrun_from_configloop. Full unit suite after mergingmain: 1421 passed, 31 skipped.nemo_gymimports) behindPOST /run, driving the statefulexample_session_state_mgmtenvironment with session-cookie propagation — 5/5 tasks reward 1.0, empty failures sidecar, graceful/aggregate_metricsskip,gym eval profileconsuming the url-ref artifacts, collector invoked with no config and no head-server contact; a run against a dead endpoint fails fast (~5s) into the sidecar instead of hanging.Docs
New
agent-server/drive-external-agent.mdx(contract, trust boundary, quickstart, session-cookie propagation, failure sentinels, resume, concurrency),--agent-urlin the CLI reference, url-formagent_refin the aggregate-metrics schema, a card on the evaluation index page, and a README mention.fern check: 0 errors.Known limitations (accepted)
/runthe agent already received.gym eval aggregategroups pre-resume rollouts under their historical URL if+agent_urlchanged between the original run and a resume.+agent_urlre-points dispatch and in-run aggregation, but on-disk artifacts (materialized inputs, already-written rollout rows) keep the historical URL.🤖 Generated with Claude Code