Skip to navigation

nemo_gym.agents.base_responses_api_agent

View as MarkdownOpen in Claude

Module Contents

Classes

NameDescription
AgentCloseSessionRequestClose agent-server state.
AgentCloseSessionResponseConfirm closure and return captured observations.
AgentSeedRejectedErrorRefuse an agent session seed this agent cannot serve, such as a grant or sandbox it does not support.
AgentSeedSessionRequestIdempotently initialize agent-server state under a caller-assigned identifier.
AgentSeedSessionResponseConfirm the caller-assigned agent session identifier and declare what the harness can use.
AgentSessionCapabilitiesResponseWhat this adapter’s sessions can do, asked before any session is seeded.
AgentSessionConflictErrorRefuse an agent session request that conflicts with what this agent recorded for the session.
AgentSessionSetupErrorRetain incomplete setup for close while propagating the original setup error.
AgentSessionStateHarness-owned session state with the immutable caller-assigned seed binding.
BaseResponsesAPIAgentAn agent server: the harness Gym runs against the model for each task.
BaseResponsesAPIAgentConfig-
ModelEndpointThe OpenAI-compatible endpoint a harness sends its model calls to.
RolloutStopRequestBody of POST /rollouts/{rollout_id}/stop; the reason is recorded on the stopped run’s response.
RolloutStopResponsestopped is false when the rollout’s run already ended or a stop was already requested.
SimpleResponsesAPIAgent-
_AgentSessionRecord-

Functions

NameDescription
_agent_boundaryendpoint with its failures raised as one agent route failure caused by them.
_has_exception_handlerWhether app registers a handler for error’s type or a base of it, as Starlette dispatches.
_log_seed_refusal-
_without_token_captureendpoint with token capture off for the model calls it makes.
assert_model_url_reachable_from_sandboxRefuse a model URL that a sandboxed agent could not reach.
is_loopback_hostWhether url points at the caller’s own loopback interface (127.0.0.0/8, ::1, localhost).

Data

AGENT_ACTIVATION_HEADER

AGENT_SESSIONS

AGENT_SESSION_COOKIE_KEY

LOG

ROLLOUT_KEY_PREFIX

ROLLOUT_STOP_METADATA_KEY

ROLLOUT_STOP_TIMEOUT_SECONDS

_AGENT_CHECKPOINT_MODES

_HOST_NETWORK_SANDBOX_PROVIDERS

_LOCAL_DOCKER_SANDBOX_PROVIDERS

__getattr__

API

class nemo_gym.agents.base_responses_api_agent.AgentCloseSessionRequest()

Bases: BaseModel

Close agent-server state.

agent_session_id
str
episode_id
EpisodeId
model_config
= ConfigDict(extra='forbid')
class nemo_gym.agents.base_responses_api_agent.AgentCloseSessionResponse()

Bases: BaseModel

Confirm closure and return captured observations.

agent_observations
AgentObservationBundle | None = None
agent_session_id
str
cleanup_confirmed
bool | None
model_config
= ConfigDict(extra='forbid')
resources_cookies
dict[str, str] | None
trajectory
TrajectoryRecord | None
nemo_gym.agents.base_responses_api_agent.AgentCloseSessionResponse._serialize_optional_metadata(
handler: pydantic.SerializerFunctionWrapHandler
)
class nemo_gym.agents.base_responses_api_agent.AgentSeedRejectedError(
detail: str
)
Exception

Bases: HTTPException, ValueError

Refuse an agent session seed this agent cannot serve, such as a grant or sandbox it does not support.

FastAPI answers it with HTTP 422, which an Environment Server treats as terminal, so a configuration error fails the episode once with this message instead of being retried as if it were transient. It is also a ValueError, so code that validates a seed outside a request (a checkpoint restore, a direct call in a test) keeps catching it as before.

class nemo_gym.agents.base_responses_api_agent.AgentSeedSessionRequest()

Bases: BaseModel

Idempotently initialize agent-server state under a caller-assigned identifier.

Repeating the same identifier and episode must return the existing session. Closing an unknown identifier must prevent a racing seed within the close retry window. The shared implementation fences each closed session and keeps its close’s saved reply for session_close_retry_window_seconds, so callers must use unique IDs and finish retries within that window. External resources should use provider TTLs when available; there is no active-session expiry timer.

agent_context
AgentContext | None
agent_session_id
str = Field(min_length=1)
agent_timeout_sec
float | None = Field(default=None, gt=0)
continuation
AgentContinuationRequirements | None
episode_id
EpisodeId
model_config
= ConfigDict(extra='forbid')
sandbox_access
SandboxAccess | None = None
task_id
TaskId
tool_accesses
list[ToolAccess] = Field(default_factory=list)
nemo_gym.agents.base_responses_api_agent.AgentSeedSessionRequest._serialize_optional_metadata(
handler: pydantic.SerializerFunctionWrapHandler
)
nemo_gym.agents.base_responses_api_agent.AgentSeedSessionRequest.omit_empty_agent_context(
classmethod

An empty context is no context, so the seed goes out as one without the key, as older agents accept.

nemo_gym.agents.base_responses_api_agent.AgentSeedSessionRequest.require_unique_tool_names(
classmethod
class nemo_gym.agents.base_responses_api_agent.AgentSeedSessionResponse()

Bases: BaseModel

Confirm the caller-assigned agent session identifier and declare what the harness can use.

agent_session_id
str
capabilities
AgentContinuationCapabilities | None
model_config
= ConfigDict(extra='forbid')
supports_task_tool_context
bool = False
nemo_gym.agents.base_responses_api_agent.AgentSeedSessionResponse._serialize_optional_metadata(
handler: pydantic.SerializerFunctionWrapHandler
)
class nemo_gym.agents.base_responses_api_agent.AgentSessionCapabilitiesResponse()

Bases: BaseModel

What this adapter’s sessions can do, asked before any session is seeded.

An environment server reads it to refuse a run before provisioning anything: a multi-step task whose turns must continue one harness session needs continuation, as Harbor’s multi-step trial refuses resume_trajectory for an agent without SUPPORTS_RESUME before any environment spend.

continuation
AgentContinuationCapabilities | None = None
model_config
= ConfigDict(extra='forbid')
supports_task_tool_context
bool = False
class nemo_gym.agents.base_responses_api_agent.AgentSessionConflictError(
detail: str
)
Exception

Bases: HTTPException, ValueError

Refuse an agent session request that conflicts with what this agent recorded for the session.

Examples: an agent_session_id already bound to another seed request, a close that names another episode, or a seed for a closed session. FastAPI answers it with HTTP 409, which an environment server treats as terminal. It is also a ValueError for direct callers.

class nemo_gym.agents.base_responses_api_agent.AgentSessionSetupError(
error: BaseException
)
Exception

Bases: Exception

Retain incomplete setup for close while propagating the original setup error.

class nemo_gym.agents.base_responses_api_agent.AgentSessionState(
)
Dataclass

Harness-owned session state with the immutable caller-assigned seed binding.

request
AgentSeedSessionRequest
class nemo_gym.agents.base_responses_api_agent.BaseResponsesAPIAgent()

Bases: BaseServer

An agent server: the harness Gym runs against the model for each task.

calls_model_from_sandbox: declare True on the class the entrypoint runs when the harness calls the model server from inside the task sandbox, where the loopback address is the container itself. A Harbor run (gym eval run <target> --agent <name>) reads that literal from the entrypoint source, as Gym reads ray_enabled, and advertises a reachable host (use_absolute_ip) by default for such a harness. It is not read through inheritance: each such class declares it itself.

agent_context_model
type[BaseModel] | None = None
calls_model_from_sandbox
bool = False
config
BaseResponsesAPIAgentConfig
class nemo_gym.agents.base_responses_api_agent.BaseResponsesAPIAgentConfig()

Bases: BaseRunServerInstanceConfig

session_close_retry_window_seconds
float
session_close_timeout_seconds
float
skip_verification
bool = False
skip_verification_reward
float = 0.0
token_id_capture
bool = False
tool_accesses
list[ToolAccess] = Field(default_factory=list)
tool_servers
list[ResourcesServerRef] = Field(default_factory=list)
nemo_gym.agents.base_responses_api_agent.BaseResponsesAPIAgentConfig.require_unique_tool_names(
classmethod
class nemo_gym.agents.base_responses_api_agent.ModelEndpoint(
base_url: str,
model: str | None = None
)
Dataclass

The OpenAI-compatible endpoint a harness sends its model calls to.

base_url ends in the API version (for example /v1). model is set only when the endpoint dictates the model name; otherwise the harness keeps its own.

base_url
str
model
str | None = None
class nemo_gym.agents.base_responses_api_agent.RolloutStopRequest()

Bases: BaseModel

Body of POST /rollouts/{rollout_id}/stop; the reason is recorded on the stopped run’s response.

model_config
= ConfigDict(extra='forbid')
reason
str | None = Field(default=None, max_length=200)
class nemo_gym.agents.base_responses_api_agent.RolloutStopResponse()

Bases: BaseModel

stopped is false when the rollout’s run already ended or a stop was already requested.

rollout_id
str
stopped
bool
class nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent()

Bases: BaseResponsesAPIAgent, AggregateMetricsMixin, SimpleServer

_agent_session_owners
Optional[SessionOwners] = PrivateAttr(default=None)
_checkpoint_participant
Optional[AgentSessionParticipant] = PrivateAttr(default=None)
_failed_seed_records
OrderedDict[str, _AgentSessionRecord] = PrivateAttr(default_factory=OrderedDict)
_failed_seed_releases
set[Task] = PrivateAttr(default_factory=set)
_fenced_session_records
OrderedDict[str, _AgentSessionRecord] = PrivateAttr(default_factory=OrderedDict)
_restart_only
Optional[RestartOnlyAgentParticipant] = PrivateAttr(default=None)
_session_records
dict[str, _AgentSessionRecord] = PrivateAttr(default_factory=dict)
checkpoint_mode
CheckpointMode = 'restart_only'
checkpoint_participant
Optional[AgentSessionParticipant]

The checkpoint participant, or None when checkpointing is off for this agent.

config
BaseResponsesAPIAgentConfig
rebinds_tool_accesses
bool = False
nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._acquire_rollout_ownership(
) -> None

Own the rollout’s key on this worker, so a stop that names only the rollout reaches its session.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._activate_agent_session_state(
activation_id: int
async

Run one input delta with the retained harness session and sandbox.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._activation_index(
request: fastapi.Request
) -> typing.Optional[int]

Read the existing 1-based header for checkpointed or multi-turn continuation sessions.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._agent_continuation_capabilities() -> nemo_gym.agents.agent_activation_types.AgentContinuationCapabilities | None

Opt into multi-turn continuation; existing one-activation adapters stay unchanged.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._agent_session_id_from_request(
request: fastapi.Request | None
) -> str | None
staticmethod
nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._capture_correlation_enabled() -> bool

Return whether this agent needs rollout correlation.

Evaluation uses /ng-rollout/<id>/... for every agent. Training capture uses /ng-rollout/<id>/training-token-capture/.... rollout_correlation adds the prefix without any capture, e.g. so a model server can route by rollout. Training capture requires token_id_capture.enabled. It also requires the static agent flag or run-level all_agents. A rollout that skips capture keeps its correlation and drops only the training tag. Partial-rollout checkpointing also needs it for this agent. Missing global configuration disables correlation.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._close_agent_session_id(
session_id: str,
current: str | None = None
async
nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._close_agent_session_record(
async
nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._close_agent_session_state(
async

Release harness state, or raise without losing the handle needed for another close.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._close_continuation_session(
async
nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._close_session_state(
agent_session_id: str,
async

Stop the session’s activation, then release its state with the close hook.

A close cancelled while it stops the activation leaves the hook to its retry, so the hook runs once. A retire can release the session while the close awaits. The close then stops there and leaves the session to the retire.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._continuation_close_timeout() -> float

Return the adapter’s configured bound for stopping an active continuation.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._drain_sessions_on_shutdown(
app: fastapi.FastAPI
) -> collections.abc.AsyncIterator[None]
async
nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._install_restored_session(
agent_session_id: str,
) -> None

Install a session restored from a checkpoint, as its replacement attempt’s seed would have.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._keep_failed_seed(
agent_session_id: str,
) -> None

Keep a failed seed’s state for the caller’s close, for as long as a fence lasts.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._locked_agent_session(
session_id: str
async
nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._model_call_capture_enabled() -> bool

Whether evaluation model-call observability is enabled.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._open_rollout_record(
rollout_id: str

The record of the open session, seeded or still seeding, that runs the rollout.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._rebind_restored_agent_session_state(
async

Re-bind a restored session to the seed of the attempt that continues it, and return its state.

After a restore the environment server seeds the session again under the replacement attempt, with that attempt’s sandbox access and tool grants, which differ from the restored request. An agent whose session borrows a sandbox overrides this to connect the new sandbox, and to take the new grants if it declares rebinds_tool_accesses. The base sets state.request to body afterwards. The default refuses, as for any other seed that conflicts with the bound one.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._rebinds(
) -> bool

Whether body is the replacement attempt’s seed of a restored session that nothing has used yet.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._rebinds_restored_sessions() -> bool

Whether this agent re-binds restored sessions, by overriding _rebind_restored_agent_session_state.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._release_agent_session_ownership(
agent_session_id: str
) -> None
nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._release_failed_seed(
agent_session_id: str,
) -> None
async

Run the close hook on a failed seed’s state that no close reached, then drop the record.

The hook runs under the session’s own rollout, as it would for the caller’s close. If it fails, the record keeps its state for a later close, and the release is tried again a window later.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._release_retired_session(
agent_session_id: str
) -> None

Release a retired session that has no fence: its episode’s close then finds nothing to release.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._release_rollout_ownership(
) -> None

Release ownership of the rollout’s key once its session is no longer open here; a no-op while it is.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._require_agent_session(
agent_session_id: str
nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._require_current_session(
agent_session_id: str,
) -> None
nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._rollout_correlation_enabled() -> bool

Whether the run asked for rollout prefixes without capture.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._rollout_sandbox_session(

The sandbox session that runs state’s harness; an agent returns it to support rollout stops.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._run_captures(
body: typing.Any
) -> bool

Whether a run’s model calls carry the training tag.

The run’s own _ng_skip_token_capture applies even for an agent whose /run route does not set the rollout’s capture context.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._seed_agent_session_state(
async

Validate grants and initialize harness state.

Raise AgentSeedRejectedError for a seed this agent cannot serve, such as a sandbox or a required grant it does not support: the seed answers a terminal 422 and binds nothing. An HTTPException keeps its explicit status; any other, unexpected exception answers 500, which an Environment Server retries as transient. If setup fails and cleanup cannot finish, raise AgentSessionSetupError with the partial state and original error. The base retains it for close, never activation.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._seed_must_restart(
) -> bool

Whether the session body seeds could not continue after a restore, whatever _seed_restarts says.

  • A session granted MCP tools, unless the agent declares rebinds_tool_accesses: its MCP session token names the seeding attempt, and the Resources Server refuses it once a restore replaces that attempt.
  • A session lent a sandbox, unless the agent re-binds restored sessions: the replacement attempt seeds it with another sandbox, and the default _rebind_restored_agent_session_state refuses that seed.

Deciding it at the seed, before the session exists, keeps every checkpoint from exporting it.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._seed_restarts(
) -> bool

Whether this agent cannot capture the session body seeds, so its episode starts over after a crash.

An exported agent whose session state lives where no checkpoint reaches it, such as a sandbox it owns without a snapshot, says so here. The seed reply then carries the restart header, and the session is never exported nor waited for. It only adds restarts: whatever it returns, _seed_must_restart restarts a session the agent could not continue after a restore. The default adds none.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._session_state(
agent_session_id: str

The open state of a session, or None; checkpoint hooks export it.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._token_id_capture_configured() -> bool

Whether the run’s configuration has this agent capture training tokens, whatever the request.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._token_id_capture_enabled() -> bool

Whether this agent captures training tokens for the request it is handling.

The agent must opt in (or the run sets all_agents), and the request’s rollout must not skip capture: a /run with _ng_skip_token_capture: true, or an activation on a rollout path without the training tag.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._undo_seed(
agent_session_id: str,
) -> None
async

Release a seeded session’s state with the close hook, or keep it as a failed seed if the hook fails.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent._validate_agent_activation(
) -> None

Validate a delta without mutating the session or consuming its index.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.activate_agent_session(
request: fastapi.Request,
async

Run or replay one header-indexed delta in a seeded harness session.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.agent_session_capabilities() -> nemo_gym.agents.base_responses_api_agent.AgentSessionCapabilitiesResponse
async

Declare the session capabilities a seed would confirm, without seeding: the task-tool context and the multi-turn continuation this adapter supports (None for one-activation adapters and for agents that implement no sessions at all).

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.aggregate_metrics(
async

Default: same RewardProfiler aggregation as resources server. Override to proxy.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.base_url_for_run(
base_url: str,
body: typing.Any,
trained: bool = True
) -> str

Apply this run’s capture path and sampling segment to a model-server root URL.

Append the API-version suffix after this method returns. While traces export, the URL also names this run’s current span, so the model server parents calls that arrive without a traceparent header (a harness in a sandbox) to it. A role the framework does not train (trained=False) gets null instead of the run’s values.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.checkpoint_mode_in_effect() -> nemo_gym.server_runtime._checkpoint.control.CheckpointMode

How this instance takes part in checkpoints; the class’s checkpoint_mode unless an override knows better.

Status, discovery and seed replies report it. An agent whose capture depends on its configuration, such as on a sandbox provider that can snapshot, overrides it.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.classify_outcome(
native_result: collections.abc.Mapping[str, typing.Any]

Override to classify native failures; the environment decides grading and retry eligibility.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.close_agent_session(
request: fastapi.Request,
async

Fence the session and keep the close’s saved reply, observations included, for the close retry window.

Failed release keeps state for retry. Closing an unknown ID prevents a delayed seed within the same window. No timer cancels active sessions: the environment server that drives the episode and the sandbox provider retain responsibility for normal and crash cleanup.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.delete_external_state(
kept: frozenset[str]
) -> None
async

Delete what exports of checkpoints outside kept kept outside Gym, such as snapshots of sandboxes the agent owns. The default keeps nothing outside Gym.

Called after the controller published a checkpoint and pruned old ones, only in the exported mode; an empty kept means nothing will be restored again.

  • It holds the control lock: no prepare, commit, or restore runs meanwhile, and no checkpoint is open.
  • It is cancelled at the release request’s deadline, and the controller releases again later, so it must tolerate state an earlier call already deleted and resume a deletion one left half done.
  • Admission stays open: activations keep running, so it must not touch what live sessions use.
  • With several workers every worker runs it, so deleting what another worker already deleted must not fail.
  • Keep by reference, not by age: keep whatever a checkpoint in kept refers to, and delete the rest.
nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.effective_tool_accesses(

Overlay episode-scoped tool access onto configured declarations by name.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.expire_agent_session_records() -> None

Drop the fences that expired, and release the failed seeds nobody closed.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.export_agent_sessions(
session_keys: list[str],
checkpoint_id: str
) -> dict[str, dict[str, pydantic.JsonValue]]
async

Return the state of every session in session_keys for checkpoint checkpoint_id.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.holds_agent_session(
agent_session_id: str
) -> bool

Whether this worker keeps any record of the session: open, failed and awaiting close, or closed.

For a rollout’s key, /rollouts/<rollout id>, whether this worker runs the rollout’s open session.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.model_endpoint(
rollout_id: typing.Optional[str] = None,
base_url: typing.Optional[str] = None,

Choose the endpoint for a harness’s model calls.

In order: session_endpoint, an endpoint the episode’s session supplies (for example a component that records model calls from inside the task sandbox); the Gym model server, with this rollout’s capture prefix; the agent’s configured base_url, used verbatim because it has no prefix routing.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.model_sampling_segment_for_run(
body: typing.Any,
trained: bool = True
) -> typing.Optional[str]

Return the sampling segment for a run’s model calls: the run’s own values, else the current request’s.

A run carries values when a training framework trains this agent (nemo_gym.core.model_call_sampling). A role the agent runs that the framework does not train (trained=False), such as a simulated user or a judge, gets null wherever the run carries a segment, so it keeps its own sampling.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.owned_session_routing() -> dict[str, typing.Any]
nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.parse_agent_context(
) -> pydantic.BaseModel | None

The seed’s agent context as agent_context_model, or None for an agent that declares no model.

Raise AgentSeedRejectedError when the seed carries a key the model does not declare, misses a required one, or carries a value of the wrong type, and when an agent without a model is sent any context. The seed then answers a terminal 422, so an episode never runs without task data it was given.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.report_outcome(
native_result: collections.abc.Mapping[str, typing.Any]

Attach validated evidence through the existing string-valued response metadata.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.report_rollout_stop(

Mark the response of a run that POST /rollouts/{rollout_id}/stop ended.

The response keeps a timeout’s incomplete status, so it is verified like one, and gains the ng_rollout_stop marker that tells it apart from a timeout or a cancellation. A stop is not a failure, so the response carries no failure kind.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.resolve_model_base_url(
model_server_name: str,
rollout_id: typing.Optional[str] = None,
trace_context: bool = True,
trained: bool = True
) -> str

Resolve a model-server URL with an optional rollout prefix (and trace context and sampling segment, as base_url_for_run).

Pass trace_context=False for a URL that a client cached across rollouts will keep using, and trained=False for a role the training framework does not train, which keeps its own sampling.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.responses(
asyncabstract
nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.restore_agent_sessions(
sessions: list[nemo_gym.server_runtime._checkpoint.agent.RestoredAgentSession]
) -> None
async

Validate every session, then install all of them; never install a partial set.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.retire_agent_session(
session_key: str
) -> None
async

Discard a session whose attempt was retired.

The default releases the session with the agent’s close hook, without a fence, so a restart-only agent’s retire stops the sandbox a seed started.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.rollout_id_from_run(
body: typing.Any
) -> typing.Optional[str]

Return the capture id for a run request.

Return None when capture is disabled. Return None when the body has no usable identity.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.run(
async

Run a whole episode in the agent, including the resources server’s seed_session and verify.

Deprecated: rollout collection reaches an agent’s own /run only through the legacy_agent environment server. Agents implement agent sessions (/v1/agent_sessions) and need not override run(), so that an environment server drives the episode. To customize how an episode runs, implement an environment server on BaseEnvironmentServer instead of overriding run().

The default answers 422, not a 5xx: environment servers and rollout recovery retry every 5xx, and a missing /run does not go away on retry.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.seed_agent_session(
request: fastapi.Request,
response: fastapi.Response = None
async

Seed once per caller ID; identical retries reuse the same harness state.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.setup_agent_checkpoint(
app: fastapi.FastAPI
) -> None

Install this agent’s checkpoint participant on app, once.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.setup_checkpoint_participant(
app: fastapi.FastAPI
) -> None
nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.setup_webserver() -> fastapi.FastAPI
nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.stop_rollout(
rollout_id: str,
async

End a rollout’s harness as at its time limit, so the episode is verified and graded as a timeout.

For a caller that enforces its own budget (agent time, tokens, cost) or an operator’s cancel. rollout_id is the id in /ng-rollout/<id>. A stop that arrives while the session is still seeding takes effect when the harness would launch. With several workers, the request reaches the worker running the rollout without the session cookie (see nemo_gym.server_runtime.request_handling.session_routing).

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.supports_agent_sessions() -> bool
classmethod

Whether the agent implements session seed and close, directly or by inheritance.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.supports_task_tool_context() -> bool

Whether this harness uses the task’s own tool declarations.

Harbor tasks declare [[environment.mcp_servers]] and skills_dir. A harness that drives them from inside the sandbox answers True, and the seed response carries the answer to the environment server, which refuses such a task to a harness that would run it without its tools.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.url_path_for_request(
url_path: str,
request: typing.Optional[fastapi.Request]
) -> str

Carry an inbound capture path and sampling segment onto a downstream URL path.

Prefixed self-calls expose the rollout id as a path parameter. Training-capture requests preserve their dedicated path segment. A request that arrived with a sampling segment passes it on after the rollout prefix. Unprefixed requests remain unchanged.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.url_path_for_run(
url_path: str,
body: typing.Any,
trained: bool = True
) -> str

Apply this run’s capture path and sampling segment to a downstream URL path.

Evaluation uses /ng-rollout/<id>/.... Training capture uses /ng-rollout/<id>/training-token-capture/..., unless the run’s rollout skips capture with _ng_skip_token_capture: true. A run with sampling values adds /ng-sampling/<values> after the rollout prefix, or null for a role the framework does not train (trained=False). Calls without a rollout id or values remain unchanged.

nemo_gym.agents.base_responses_api_agent.SimpleResponsesAPIAgent.use_agent_session_owners(
) -> None

Release ownership of a session when this worker drops its last record.

See nemo_gym.server_runtime.request_handling.session_routing.

class nemo_gym.agents.base_responses_api_agent._AgentSessionRecord(
lock: asyncio.Lock = asyncio.Lock(),
closing: bool = False,
episode_id: nemo_gym.core.episode_types.EpisodeId | None = None,
expires_at: float = float('inf'),
stop_requested: bool = False,
stop_reason: str | None = None,
restored: bool = False
)
Dataclass
activations
OrderedOperationLedger[NeMoGymResponse] = field(default_factory=OrderedOperationLedger)
close_response
AgentCloseSessionResponse | None = None
close_task
Task[AgentCloseSessionResponse] | None = None
closing
bool = False
episode_id
EpisodeId | None = None
expires_at
float = float('inf')
lock
Lock = field(default_factory=(asyncio.Lock))
restored
bool = False
state
AgentSessionState | None = None
stop_reason
str | None = None
stop_requested
bool = False
nemo_gym.agents.base_responses_api_agent._agent_boundary(
endpoint: typing.Callable[..., typing.Awaitable[typing.Any]],
app: fastapi.FastAPI,
operation: str,
)

endpoint with its failures raised as one agent route failure caused by them.

A model reply that confirms a policy response timeout makes agent.responses raise the typed model_policy_response_timeout failure instead.

The reply body and status stay those of the original error. HTTPException, cancellation and any error app has a handler for (such as a checkpoint ControlError, answered 409) pass through to that handler. A failure an agent boundary already reported (/run calling this server’s /v1/responses) is not wrapped again.

nemo_gym.agents.base_responses_api_agent._has_exception_handler(
app: fastapi.FastAPI,
error: BaseException
) -> bool

Whether app registers a handler for error’s type or a base of it, as Starlette dispatches.

nemo_gym.agents.base_responses_api_agent._log_seed_refusal(
agent_session_id: str,
) -> None
nemo_gym.agents.base_responses_api_agent._without_token_capture(
endpoint: typing.Callable[..., typing.Awaitable[typing.Any]]
) -> typing.Callable[..., typing.Awaitable[typing.Any]]

endpoint with token capture off for the model calls it makes.

It serves a rollout path without the training tag. The caller that built the path decided not to capture this rollout’s calls (an Environment Server, or a /run whose rollout skips capture), so the agent’s own token_id_capture setting does not turn it back on.

nemo_gym.agents.base_responses_api_agent.assert_model_url_reachable_from_sandbox(
url: str,
provider_name: str | None
) -> None

Refuse a model URL that a sandboxed agent could not reach.

Agents that run inside a sandbox (Hermes, mini-SWE) hand the Model Server URL to code in the container. Inside a container on a remote provider (OpenSandbox, E2B, Daytona, …), a loopback host is the container itself, so every model call fails and the episode silently scores 0.

Raises:

  • ValueError: when url is loopback and provider_name is not a host-network or local Docker provider. Local Docker only logs a warning: loopback works there only when the daemon shares the host network.
nemo_gym.agents.base_responses_api_agent.is_loopback_host(
url: str
) -> bool

Whether url points at the caller’s own loopback interface (127.0.0.0/8, ::1, localhost).

nemo_gym.agents.base_responses_api_agent.AGENT_ACTIVATION_HEADER = 'x-ng-agent-activation'
nemo_gym.agents.base_responses_api_agent.AGENT_SESSIONS = SessionKind(cookie_key=AGENT_SESSION_COOKIE_KEY, id_field='agent_session_id', se...
nemo_gym.agents.base_responses_api_agent.AGENT_SESSION_COOKIE_KEY = 'agent_session_id'
nemo_gym.agents.base_responses_api_agent.LOG = logging.getLogger(__name__)
nemo_gym.agents.base_responses_api_agent.ROLLOUT_KEY_PREFIX = '/rollouts/'
nemo_gym.agents.base_responses_api_agent.ROLLOUT_STOP_METADATA_KEY = 'ng_rollout_stop'
nemo_gym.agents.base_responses_api_agent.ROLLOUT_STOP_TIMEOUT_SECONDS = 60.0
nemo_gym.agents.base_responses_api_agent._AGENT_CHECKPOINT_MODES = ('restart_only', 'exported')
nemo_gym.agents.base_responses_api_agent._HOST_NETWORK_SANDBOX_PROVIDERS = frozenset({'local'})
nemo_gym.agents.base_responses_api_agent._LOCAL_DOCKER_SANDBOX_PROVIDERS = frozenset({'docker'})
nemo_gym.agents.base_responses_api_agent.__getattr__ = moved_names_getattr(__name__)