Training on External Agent Harnesses
An external agent harness runs its own model-calling loop and returns a finished transcript to Gym. Claude Code is one example. The transcript contains the conversation text, but it does not contain the exact token ids and log probabilities produced by each model call.
Training needs those original token ids. Re-tokenizing the final text can produce a different sequence from the one sampled by the policy. Gym’s training-token capture records the ids while they are still available in the model server, associates the calls with their rollout, and rebuilds them into the token-bearing response expected by the trainer.
Decide whether you need token capture
Ordinary evaluation does not require training-token capture. Enable it when the collected rollouts will be used to optimize a policy.
How capture works
Every model call carries the rollout id. For a multi-call rollout, Gym verifies which earlier call the new request continues. After the harness finishes, Gym reads the captured calls and replaces the rollout’s text-only response.output with output items that carry the original token ids and log probabilities.
Gym does not guess when a call is missing or its parent cannot be proven. It sets mask_sample: true so the trainer can exclude that rollout from the loss.
Configure local capture
The default setup writes capture records to a node-local directory and lets Gym rebuild the response.
The YAML snippets in this section are Gym config. Put them in a file and pass it with --config to both gym env start and gym eval run, as shown in Run a first rollout with Claude Code. When NeMo RL starts Gym, place the same keys under env.nemo_gym in the NeMo RL config instead.
1. Configure the model server for training
Use responses_api_models/vllm_model/configs/vllm_model_for_training.yaml as the model-server config. It enables token information in model responses.
External harnesses often omit sampling parameters or send serving-oriented defaults, so the trained agent’s calls must get the trainer’s sampling values from Gym rather than from the harness. Where Gym gets them depends on what runs it:
- NeMo RL, or another framework that sends its values with each rollout. Set no sampling in Gym. NeMo RL sends
policy.generation: its training values, andval_temperatureandval_top_pfor validation rollouts. Gym carries them into the URL of every model call the trained agent makes, and the model server replaces the call’stemperatureandtop_pwith them. The framework’s output-token limit (max_new_tokensin NeMo RL) caps each call, and a smaller limit the harness asks for is kept. The trained agent’s model server must not pin sampling withsampling_overrides, andvllm_modelrefuses to start one that does; it may pin onlylogprobsandtop_logprobs, which change what the engine reports, not how it samples. These model calls keep the sampling they send, or their own model server’ssampling_overrides: roles an agent runs besides the one it trains, when the agent builds their model URLs withtrained=False, as tau2 does for its simulated user, pinchbench for its judge (withjudge_model_serverset),conversational_tool_use_policy_tool_generationfor its judge and Hermes for its compression helper; and model calls a resources server makes through Gym’s server client while handling a request, such as a verifier’s LLM judge. Judges that call a model through a client of their own, such as verifif’s and gdpval’s, are not marked yet. An environment server that does not apply the values refuses an episode that carries them;nemo_user_simandswe_togetherdo not apply them yet. - Gym on its own, or a training loop that sends no values. Pin the training values with
sampling_overrides, so every request uses them:
Replace the example values with the sampling settings used by the trainer. A training loop can also send its values with each rollout instead; see Send sampling values with each rollout.
The two ways differ:
If the training framework starts vLLM, keep its tokenizer enabled. For NeMo RL, set policy.generation.vllm_cfg.skip_tokenizer_init: false.
2. Enable the capture store
Add the run-wide capture settings:
delta_records: true avoids storing the growing full prompt again for every resolved continuation. Root and unresolved calls remain self-contained so Gym can diagnose a broken chain.
max_mask_fraction is an optional safety limit. After at least mask_fraction_min_samples finalized rollouts, collection stops if the masked fraction exceeds this value. Omit it to disable the limit.
mask_incomplete_when_attributed (default true) decides what happens when a model call registered its capture intent but never committed a record, which is what a harness killed at its timeout leaves behind. By default such an incomplete capture always sets mask_sample: true. Set it to false to keep the rollout when terminal attribution delivered the verifier-scored chain whole: a call with no record cannot sit inside a delivered chain, so the uncaptured call lies outside the scored trajectory. Without a delivered attribution the rollout is still masked.
A call the engine refuses because the prompt does not fit the context window is not a lost call. When the vLLM model server propagates the refusal (propagate_context_overflow_errors: true), it records the refusal in place of a token record, so the rollout is not incomplete and the harness can compact its history and continue. The record names the call the refused request continued (its request-time lineage, resolved before dispatch like a served call’s). A context-window refusal of the request that continued the delivered terminal call marks the rebuilt response incomplete with reason max_output_tokens; a refusal on another branch of the rollout, one the harness recovered from, or one that named only an output-token parameter (no code) does not. _ng_token_capture.engine_refusals lists every refused call either way. Under worker custody (external_staging: true) the refusal is a capture-ledger failure row that carries the call id and the reason engine_refused_request only. A framework that assembles receipts from the ledger must treat the reasons in nemo_gym.models.token_capture.UNSERVED_CALL_FAILURE_REASONS as off-chain rather than as poisoning (NeMo RL’s receipt builder does, through NVIDIA-NeMo/RL#4749); a rollout rebuilt from staged records is then not masked for the refusal but reports no truncation verdict either. NVIDIA-NeMo/Gym#4647 tracks carrying the code and the lineage on that row.
3. Opt in the external agent
Enable capture on each external harness that returns no token ids:
Both the run-wide enabled setting and the agent opt-in are required. To capture every configured agent, set token_id_capture.all_agents: true instead of setting the flag on each agent.
Some harnesses probe optional model-server endpoints such as /v1/models. Gym does not need to implement or predict these endpoints, and no per-harness route configuration is required. An unimplemented request that returns 404 or 405 cannot contribute policy-generated text and does not make capture incomplete. Any other response from an unrecognized route fails closed because its content could enter a later prompt; the rollout is marked with mask_sample: true.
If a custom model server implements a successful metadata, health, or tokenization route whose response cannot contain policy-generated content, declare the exact method and path once on that model server:
Declarations belong to the model server because the server owns the route and its response semantics. Gym rejects wildcards, query strings, non-string methods, and paths without a leading slash. Do not declare title generation, summarization, compaction, or another endpoint that can return policy-generated text. Unknown redirects, server errors, exceptions, and requests that finish without starting a response all mark the rollout incomplete.
Native Gym agents normally leave token_id_capture disabled because their responses already contain the token ids needed for training.
4. Enable tool calling in the inference server
A tool-call parser converts model output into structured calls that the harness can execute. Without the correct parser, an agentic rollout may stop after one model call even though capture itself is working.
vLLM needs two settings to return tool calls. The first turns on automatic tool choice. The second names the parser that matches the model’s tool-call format. Setting only the parser leaves tool calling disabled.
For a standalone vLLM server, pass both flags to vllm serve:
When NeMo RL starts vLLM, set both keys in its chat-serving settings:
Replace hermes with the parser that the model card recommends. Check n_calls on the first collected rollouts before relying on reward results.
5. Route model calls from a custom harness
Gym links each model call to its rollout through the URL path. A training-capture call goes to the Gym model server with this prefix in front of the usual API path:
For example, a harness that calls a chat-completions endpoint for rollout 3-0 sends its request to http://<model-server>/ng-rollout/3-0/training-token-capture/v1/chat/completions. The model server removes the prefix before routing the request. It records the call’s token ids under rollout 3-0.
The built-in external agents, such as Claude Code, add this prefix when token_id_capture is enabled for them and they call a Gym model server. A custom harness must add it to every model call of a rollout that does not skip capture. Without the training-token-capture segment, the call is not recorded for training, and Gym masks the rollout because it finds no captured calls.
Agents based on SimpleResponsesAPIAgent can build the prefixed URL with base_url_for_run(base_url, body) or url_path_for_run(url_path, body). While the agent exports traces, base_url_for_run also appends /ng-trace/<traceparent> after the prefix so the model server can parent the harness’s calls to the run’s span; the model server strips it, and a harness that inspects the URL should keep it (see Distributed Tracing). The built-in agents known to rewrite the model URL, harness_agent (replaces a loopback host) and vibench_agent (replaces the host and keeps the path), keep every path segment; the OpenHands capture overlay only appends to the base URL. Both helpers read the rollout id from the run request and add the training segment when the agent has opted into capture and the row does not set _ng_skip_token_capture: true. Model-Call Capture describes the same URL prefix for evaluation capture, along with the other routing helpers.
Run a first rollout with Claude Code
This example collects captured rollouts from the Claude Code agent on the reasoning_gym example tasks. It combines the settings from the previous section into one file. Run the commands from the root of the Gym repository.
Start a vLLM server with tool calling enabled:
Claude Code requests up to 32,000 output tokens on every model call. vLLM rejects a request whose prompt and requested output together exceed the context length, so --max-model-len must leave room for both. The value 65536 does that and also fits the model’s KV cache on a single 48 GB GPU.
Save the capture settings as token_capture.yaml:
The last block opts in the Claude Code agent that this environment defines. That agent sends its model calls through the Gym model server named policy_model, which capture requires. A Claude Code agent that calls an external anthropic_base_url directly bypasses the Gym model server, so its calls are never captured.
In a second terminal, start the Gym servers. The --model-type flag selects the training config of the vLLM model server. The --config flag adds the capture settings on top of it:
In a third terminal, collect rollouts against the running servers. Pass the same --config file again:
Print the capture result for each rollout:
The rollout collector reads the capture settings from the gym eval run command, not from the running servers. Without --config token_capture.yaml on this command, the model server still records the calls, but the collector never rebuilds them. It writes text-only rollouts that have no _ng_token_capture field and are not masked.
A mask_sample of false or null means that the rollout was not masked. Compare the other values with the table in Check the first run. A masked rollout with capture.n_calls of 0 has no captured calls. Its model calls did not reach the Gym model server with the training-capture prefix, and capture.error gives the reason.
Consume the rebuilt rollout
When rebuild_response remains at its default value of true, gym eval run performs the complete lifecycle:
- The model server records every correlated call.
- Gym freezes the records after the harness and verifier finish.
- Gym reconstructs one verified model-call chain and updates
response.output. - Gym writes the rollout result durably.
- Gym retires successfully consumed capture records.
The trainer reads the rebuilt response.output in the same way it reads output from a native agent. Prompt positions provide context, while generated positions retain the captured log probabilities used for policy optimization.
Masked or failed builds are retained for diagnosis. Successfully delivered records are removed after the output row is durable.
Check the first run
Gym adds capture metrics under _ng_token_capture on each rebuilt rollout.
Terminal attribution is how Gym finds the captured call that produced the response the verifier scored. When attribution succeeds, terminal_attribution.chain is delivered, and Gym trains on that call’s chain even if the harness also made side calls. When Gym cannot identify the final call, terminal_attribution.chain is empty and terminal_attribution.method is none. This is not an error by itself. Gym then keeps the rollout only if the capture contains exactly one chain with no unresolved calls, so chains greater than 1 masks an unattributed rollout.
A rollout with no _ng_token_capture field was not rebuilt. Unless its row set _ng_skip_token_capture: true, verify that capture is enabled for both gym env start and gym eval run, the agent is opted in, and its model calls use the rollout-correlated model-server URL.
Optionally supply exact prefix tokens
Some harnesses reshape an assistant turn before sending the next request. A chat template or reasoning template can also render the previous turn differently. In these cases, the next prompt may not begin with the tokens that the policy actually sampled.
Prefix supply asks a compatible inference backend to begin the next prompt with the verified parent’s exact tokens. Enable the Gym model-server side with this config overlay:
The backend must support Gym’s required-prefix request and return the prompt token ids actually used for generation. Gym verifies that evidence before accepting prefix supply. A missing or mismatched proof fails the model call instead of silently producing an off-policy capture.
Stock vLLM does not implement this prefix-supply extension. Leave the overlay disabled unless the inference backend supports both the required-prefix request and generation-time prompt-token response. Capture can still work without prefix supply when each rendered prompt naturally extends the preceding sampled tokens.
Prefix supply is not supported with use_completions_api: true or is_responses_native: true.
Current limitations
- Gym delivers one verified model-call chain per rollout. When Gym can attribute the verifier-scored response to a captured terminal call, it delivers that call’s intact ancestor chain and excludes unrelated calls. Without terminal attribution, multiple plausible chains cause masking.
- Harness-generated title, compaction, retry, or sub-agent calls can appear as additional chains. Inspect
terminal_attribution,chains, anddelivered_fractionto confirm that Gym selected the intended chain. - Full-tree training requires a trainer data contract that accepts multiple related trajectories.
- Prefix supply requires a compatible inference backend and is not available in stock vLLM.
Advanced framework integration
The sections above cover a run in which gym eval run captures, rebuilds, and writes the rollouts. This section is for authors who integrate Gym into a training framework. It applies when the framework stores capture records itself, reads them back in its own process, or drives rollouts from its own training loop.
Use framework-owned capture storage
The default file store is intended for a model server and rollout collector that share one node-local directory. A distributed training system can instead provide a shared transport.
Configure a sink and lineage resolver that connect to the same backend. In this example, my_package.capture stands for the framework’s own module:
The sink receives completed call records from each model-server worker. The lineage resolver lets any worker find a previously committed call from the same rollout. The framework creates a source in its rollout-consumer or trainer process to freeze and read the same records. The source implements the TokenSource protocol from nemo_gym.models.token_capture.
Configure sink and lineage classes by import path so Gym constructs them inside every model-server worker. Installing an object only in the launcher process does not configure separately spawned workers.
Rebuild and retire rollouts in the framework
With rebuild_response: false, Gym stops after capture. The framework then performs the consumer side for each finished rollout result:
- Rebuild the rollout’s
response.outputfrom its captured calls. - Write the rebuilt result to the framework’s durable storage.
- Retire the capture records that the rebuild used.
The following function performs these steps for one result whose row did not skip capture. The framework supplies source, which reads from the same backend as the configured sink, and write_durably, which returns only after the result is stored durably:
Exclude any result with mask_sample: true from the loss. Call retire_rollout_token_capture only after durable downstream storage has accepted the rebuilt result. If the framework retires the records first and the write then fails, the captured token ids are lost.
retire_rollout_token_capture only removes rollouts that were delivered, so it keeps masked and failed captures around for inspection and never sees an attempt you abandoned. To remove those captures, use the source’s two batched operations, which match the ones the external-staging capture ledger provides.
await source.retire(capture_keys)removes the rollouts’ records and leaves a fence, so any later write for those rollouts fails withTokenCaptureRetiredErrorand is dropped. Late writes come from an abandoned attempt that is still running, or from a second run of a finished rollout after a client retry. Retire masked or failed captures once you no longer need them, and retire abandoned attempts as soon as you give up on them.await source.delete(capture_keys)removes the records together with the fence. Because the fence is what stops late writes, delete retired rollouts only once no write from them can still arrive, for example at the end of the run. Also delete a rollout ID before reusing it.
Episodes with several agent instances
When an episode’s model calls name agent instances, such as assistant and judge, Gym keeps each agent instance’s calls apart. Parent search, retry grouping and terminal selection run within one lineage scope: the calls of one agent instance on one model server. A judge whose prompt replays the assistant’s turns therefore starts its own chain instead of continuing the assistant’s, and a continuation that moves to another model server starts a new chain with root reason model_server_changed.
finalize_rollout_token_capture returns one build for every named agent instance under agent_instances:
The finalizer writes only one build into result: the build of the primary agent instance, which is the one the scored response belongs to. Persist any other build yourself. Gym picks the primary in this order:
assistant, when the episode has an agent instance with that name.- The unnamed agent, when some calls name no agent instance.
- The only agent instance, when there is exactly one.
assistant is therefore the name to give the agent instance whose trajectory is the episode’s result. An episode whose agent instances are, for example, solver and judge has no primary: the top-level result is masked with the error no primary agent instance captured, and the per-agent builds are still returned.
A lost call masks only the agent instance that made it. A capture failure that cannot be placed on one agent instance masks every build of the episode: a mark with no identity, a conflicting write, or a failure with no agent instance in an episode that names them.
A custom lineage store receives the caller’s identity on every call: resolve(rollout_id, request_items, *, identity) and, for a capture ledger, has_rows(rollout_id, *, identity). It must search only the calls of that identity’s agent instance and model server. A store that does not accept the keyword raises TypeError on every call: under worker custody the model call fails, and under local capture every continuation is recorded as unresolved, so multi-call rollouts are masked. The conformance kit in the next section checks that resolve accepts and honors the identity.
Check a custom transport
Run run_conformance from nemo_gym.models.token_capture before using a custom transport for training. It takes factories rather than instances, because several checks need a fresh client. Each factory call must return a new client connected to the backend. The function is async, returns the names of the checks that passed, and raises ConformanceError on the first failure:
For a multi-process deployment, run the check against the real shared backend rather than a local stand-in.
A sink that implements begin_call but not the optional record_engine_refusal extension passes with a ConformanceWarning named engine_refusal_resolution in place of that check. Such a sink cannot resolve the capture intent of a call the engine refuses, so a rollout that runs into the context window freezes incomplete and is masked by default (see mask_incomplete_when_attributed above).
Let the framework own context reconstruction
For compaction-aware training with a compatible framework worker, enable
token_id_capture.parent_resolution: source_history together with external_staging: true,
external_staging_backend: vllm_worker, and rebuild_response: false.
See Source-history continuity and context compaction
for configuration prerequisites, supported APIs, measurement, and admission closure.
The harness keeps using rollout-correlated Responses, Chat, or Messages requests with explicit history.
It owns compaction of the next input and needs no special parent header or segment definition.
Return the complete accepted execution history or existing call references, including actions
before compaction. The shortened next input alone is not that history. NeMo RL joins the returned
evidence to captured calls and reconstructs their context chains; Gym does not replace response.output.
Concurrent capture is permitted, but selecting subagent calls for training remains the framework’s
responsibility. Capture alone cannot establish which calls the harness accepted.
The single-chain rebuilding steps and metrics above describe Gym’s local capture path. Framework-owned reconstruction has its own finalization and validity checks; it does not use that delivery function.
Provide unique rollout ids
Gym normally derives the capture id from the task and rollout indices. If a custom training loop restarts those indices on each step, explicitly provide a unique _ng_rollout_id:
The id may contain letters, digits, dots, dashes, and underscores, and it must begin with a letter or digit.
It must not end with -a followed by a positive number, such as -a2: that suffix names an attempt of a rollout, and rollout collection rejects dataset rows that use it.
Send sampling values with each rollout
A training loop that samples validation rollouts with different values than training ones, as NeMo RL does, sends the values for each rollout next to its id:
temperature and top_p replace the values of every model call the rollout’s agent makes. max_output_tokens caps each call’s output limit. Gym leaves a field you omit to the call. The task itself is unchanged.
Also add this block to the Gym config, naming the model servers of the agents you train:
A call to one of those model servers that arrives without the rollout’s values fails instead of sampling with others, so a harness that ignores its model URL is caught on its first call. Model calls a resources server makes through Gym’s server client while handling a request, such as a verifier’s LLM judge, carry a marker that tells the model server to keep the caller’s own sampling. A vLLM model server forwards that marker on its Chat Completions requests to its generation server as the header x-ng-sampling: null, so a server that checks every call against the training values can skip those calls.
A framework that instead writes temperature, top_p or max_output_tokens into each row’s responses_create_params reaches only agents that accept those request fields. Sandbox harnesses refuse them, because a harness cannot put them on every model call it makes. For task folders, the harbor environment server can move them for such a framework: with request_sampling_to_model_calls: true it removes the three fields from the request the harness receives and carries them on the turn’s model calls, the same way as _ng_model_sampling. A row that has _ng_model_sampling keeps those values and its request is sent unchanged.
Turn capture off for a rollout
A training framework that also runs rollouts it does not train on, such as validation rollouts, can skip capture for each of them. Set _ng_skip_token_capture: true on the row, next to _ng_rollout_id:
None of that rollout’s model calls carries the training-token-capture segment, so the model server records no token ids for it. A flat row keeps the key, which single_agent_turn_legacy and the agent’s /run read. A materialized task row carries the setting as skip_token_capture: true in the episode request, and the Environment Server activates its agents without the segment. An agent activated on a rollout path without the segment captures none of that activation’s calls, whatever its own token_id_capture setting.
false, null, or no key leaves capture to the run’s token_id_capture settings: a row can turn capture off, never on. A rollout that skips capture keeps its /ng-rollout/<id> prefix and otherwise runs like an uncaptured evaluation rollout: an agent whose output depends on capture returns its evaluation output, and Claude Code, for example, folds its thinking into the message text.
Rollout collection does not rebuild the response of a row that skips capture. A framework that rebuilds responses itself (see Rebuild and retire rollouts in the framework) must not finalize a row it marked: finalize_rollout_token_capture finds no records for it and masks it.
A custom harness sees the setting only through the agent’s URL helpers (resolve_model_base_url, model_endpoint, base_url_for_run and url_path_for_run), called while the agent handles the activation or /run. A URL built when a session is seeded, or in a thread that does not inherit the request’s context, such as one from loop.run_in_executor, keeps the segment. An agent that registers its own /run route must enter skip_token_capture_context(skips_token_capture(body)) from nemo_gym.core before it builds URLs, or build them with base_url_for_run or url_path_for_run from the original request: body.model_dump() leaves the key out.