From 1878e43b1332f0c756128e18085c65a64f028a59 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 09:40:18 -0800 Subject: [PATCH 1/6] feat(verifiers): a judge sends the effort its route takes, and its grade records what each call carried The direct judge now sends the run's effort and thinking budget as LiteLLM's reasoning_effort and thinking where its route takes them (model_call.takes), leaving out and recording the rest; a value LiteLLM refuses fails the grade at once. A run's judge_effort and judge_max_thinking_tokens reach every judge. verifier_settings holds what the calls carried, not_sent what they couldn't, with the endpoint host and the config's temperature and seed. Each judge's grade keeps judge_calls, one record per call (JudgeUsage, beside the step's usage), and user_sim_judge's legacy calls, usage and cost come from those records. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- src/agent_env/config/model_call.py | 31 ++- .../task_steps/verifiers/rubrics_verifier.py | 175 +++++++++++++++-- .../task_steps/verifiers/user_sim_judge.py | 53 +++--- .../verifiers/user_sim_judge_core.py | 19 -- .../task_steps/verifiers/verifier.py | 12 +- .../verifier_golden/rubrics_subclasses.json | 108 ++++++----- .../task_step/judge_settings_wire_test.py | 90 +++++++++ .../verifiers/test_rubrics_family_grades.py | 8 +- .../test_rubrics_verifier_judge_settings.py | 176 ++++++++++++++++++ .../verifiers/test_user_sim_judge.py | 4 +- 11 files changed, 560 insertions(+), 118 deletions(-) create mode 100644 tst/integration/task_step/judge_settings_wire_test.py create mode 100644 tst/unit/task_step/verifiers/test_rubrics_verifier_judge_settings.py diff --git a/AGENTS.md b/AGENTS.md index 9da4ced94..d97fa7273 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -151,7 +151,7 @@ and deserialized through a registry. |---|---| | `env/` | `Env` base class: a subclass declares `type`, implements `from_dict` and `async deploy(...) -> DeployedEnv`, and may override `reset`, `close` and `load_file_artifact_universe`; teardown closes each env a run deployed before terminating its sandboxes by id. Built-ins in `env/envs/`: `MCPServerEnv` (`mcp_server`), `MultiEnv` (`multi`, MCP servers plus websites and computers; its website browser is the one its `browser_envs` names, none for `[]`, else the run's when it has websites: an MCP server env such as `playwright-mcp` runs among the gateway's MCP servers, and a browser computer such as `chromium` on a sandbox of its own as one more computer child, sized by its `child_envs` entry, its tools under its name and `_`, routing the multi env's synthetic sites unless that entry's `site_routing` says, its network its own env's, as any computer child's; a website env deployed alone refuses a browser computer as the run's browser), `ServiceDBEnv` (`service_db`, PostgreSQL), `WebsiteEnv` (`website`, one site: a server image, `backend_image` in its env.toml, serving the pages and API, ready when its card's `website/v1` `ready` answers a `WebsiteReadiness` that says so, as `agentenv_protocol.website` (`website_readiness`, `env_readiness`) defines a website env's health for the deploy and `DeployedEnv.readiness()` alike, or, for a card without `ready`, when its `health` path answers 200, which is deprecated; its env.toml's `ready_timeout_s`, how long it may take from its server's container starting to ready, is that container's health check `start_period` and what the deploy waits, or its card's `ready` timeout if longer, and its `shm_mb` is the container's `shm_size`, each left to the gateway and Docker without them; the gateway container's `env/gateway/constants.py` mirrors the URI and op, a test keeping them equal; a separate frontend image is deprecated, warned of at put and optional in a bundle, and a stored `backend_docker_image_artifact` reads as the server image; a live one, `live = true`, is a real site whose server serves none of its pages, its `live`, `domains` and `allow_hosts` read at put from its server's `@website(...)` (`utils/card_naming.py` `WebsiteSource`) unless given, its `settings`' secrets only as references the gateway resolves as it writes the site's container (`WEBSITE_SETTINGS_ENV`); the gateway gives it no site route, a computer's site table leaves it out, a computer whose network is an allowlist is let reach its names (`MultiEnv.live_hosts`), a browser alone's forward port takes them straight to the real site (`site_proxy.py` `direct`), as the browser base's stand-in proxy takes any host, refusing nothing, each proxy logging each such connection as a JSON line, and a run that deploys one is marked live, `reproducible: false`), `GatewayEnv` (`gateway_server`), `ComputerDriverEnv` (`computer_driver`, `env/envs/computer/driver_env.py`: a computer driver's files and what its class declares for each platform it supports, read at put in a process of its own, `agentenv_protocol.computer._declare`, where the driver's own dependencies needn't be installed, with the `port` it serves on and its install by OS, `[install.]`, or for one distribution `[install."/"]`, which replaces its OS type's there, as its `known_failures` do (`env/envs/computer/utils/install.py`): files, apt `packages` with extra `sources`, a `python` requirements file for a venv, `downloads` by URL and sha256, `run` scripts, the services the base's init runs, and `ports`; it deploys only as a computer env's driver), `ComputerEnv` (`computer`, in `env/envs/computer/`: a base computer and a driver, matched at put by gate 1 before anything is stored, then composed by `composer.py` into an image for each form and arch on a builder of the put's sandbox provider, by default the env's (`utils/builder.py`; `--sandbox` on `env build`): this machine's Docker for `local`, else a VM of the provider, which fetches the put's stored files by signed URL, takes the rest inline and pushes to the image store itself, so it builds only with stores a remote VM reaches; each arch goes to the first link that runs it natively, else one that emulates it (a VM registers QEMU; `--no-emulate` leaves it `skipped` instead, for a later put), and its pair records the provider that built it (`builder`); a run or register composes only the computer envs its tasks deploy (`materialize._composed_envs`: each env a task's steps name, and each env those hold but a computer env's own apps and driver, which run inside it) and those it pulls in from an installed bundle, whose one write every bundle shares, every one for a plan with no tasks, any other composing at its first deploy; one that reuses a computer env composes what it has left (`pending`), a run, and a register given a `--sandbox`, only the forms its sandbox's deploys boot (`booted_forms`: on each link, the first form it boots natively, by the deploy's own rule, `boot.first_native`; a compose of a disk adds its container), and a deploy composes first what it boots that no compose started, and a container it runs natively that was built but not probed, as one whose probe a setting that didn't resolve stopped, booting it only once ready (`ComputerEnv.compose_unstarted`); tagged `agentenv-computers:` in the image store by a key of the image's Dockerfile, build context and lock so any env with the same inputs reuses it; every layer's packages, requirements and downloads are resolved at put in a container of the base for each arch (`utils/packages.py`, `utils/resolve_in_base.py`), stored in the object store by sha256 under `agentenv-packages/`, and listed in a lock stored by a digest of its inputs, which any env with the same inputs reuses, and builds install only the lock's files, every install step `RUN --network=none`; each pair's status goes into its metadata, `composed`, the arches built are written as its computer, a `computer` artifact over one index, and `agent-env env build` resumes what a put left; gate 3 (`utils/probing.py`) then boots each native build on the put's sandbox provider and probes it at `full`, making it `ready` or `failed`, and a build no provider runs natively stays `unverified`. Its deploy, through the `computer` env provider (`providers/env_providers/env_computer_provider.py`), boots its first `ready` build on a sandbox provider that runs its arch natively (`native_platforms()`), with no gateway in front and the driver's card as the env card, its `/dev/shm` the most its apps' Linux installs ask for (`shm_mb`, in MiB, which its composed computer and the deploy record keep; `--shm-size` on a container, `AGENTENV_SHM_MB` read by a Linux disk's init, passed only to a provider whose `SHARED_MEMORY` says it gives that much, else the sandbox's default, which the deploy logs), then checks its `display`; `deploy_env` `env_params` take a `form`, `computer_settings` (deploy-phase values of the base's settings; a secret one, here or on the env, only as a bare `secret:`/`env:` reference) and `driver_settings` (the driver's `ComputerSettings`, such as its default coordinate space); a `network` that allows nothing runs it on local Docker's internal network behind a relay (`providers/sandbox_providers/local_docker/relay/`); `reset` and `close` have the driver end its recordings first (`computer-recording/v1` `end_all`, each uploading what's left and its manifest under the grant it started with), and `reset` then boots a fresh container in its place (`reset_container`), keeping the computer's address but not an agent's MCP session to the old driver; its `load_file_artifact_universe` writes files under the session user's home through the driver's `data/add`, `Downloads` by default, each file's bytes through a read grant when the store's grants reach it and its network allows everything, else inline (`env/envs/computer/utils/inside.py`)), `ComputerAppEnv` (`computer_app`, `env/envs/computer/app_env.py`: an app on a computer, a `ComputerAppEnvironment` class its env.toml's `module` names, read at put by the same `_declare`, which declares each OS with its own decorator (`@linux(...)`, or `@install(os_type, spec)` for any OS type; `@linux(distribution=...)` or `@install("/", spec)` for one distribution, which replaces its OS type's there) holding its install, its launch and, optionally, a skill and settings and build settings that add to the class's there, and install steps and ready checks for every OS or those their `os=` names; everything that reads its settings, launch or steps asks for the computer's OS type; deployed alone it is a one-app computer env, a `ComputerEnv` of the computer and driver its env.toml names, the composer installing it under `/opt/agentenv/apps//` with its services as supervisord programs beside its own server (`agentenv_protocol.computer.serve_app`, in a venv with the protocol's `app` extra, on `.agentenv/server.sock` in its folder), which adds its launcher, launches a `boot` app once per boot and says through `computer-app/v1` whether it's ready, as the driver's `computer-ready` asks, its card named after it, and `env_params` `app_settings` handing it values of its `Settings` in `AGENTENV_APP_SETTINGS`, a secret one only as a bare reference, over its env.toml's `[settings]` and a computer env's `settings` beside it in `apps`, each by top-level field (`params.app_settings`; checked at put, a required one left to the deploy; the deploy record keeps the merged values as `app_settings`, secrets withheld); its env.toml's `build_settings`, values of its `BuildSettings` checked at put, are written to `.agentenv/build_settings.json` in its folder, so they're part of the image's key, its install steps read them, and a deploy can't change them). An env type whose services take environment data defines `load_environment_artifact` and `load_environment_universe_artifact`; `load_artifact` refuses an environment artifact aimed at a type that doesn't, at save and before it loads. An env built on the protocol SDK can serve agents a skill (`@agent_skill`, `skill/v1`), which `add_skills` `env_ids` installs under its environment name (behind a gateway, each server's under that server's name); a skill with files beside its SKILL.md goes as a bundle stored once per content under `agentenv-env-skills/` in the object store. `env/gateway/gateway.py` is the env-side gateway server, container-only code. Its site route, `/website//`, never forwards a site's data plane or card (`/agentenv/…`, `/.well-known/agent-env.json`), which agentenv reaches through `/svc//`; a site with no frontend image is served by its server image there. A request from a computer's site proxy names its computer (`AgentEnv-Computer`, sent from the proxy's private upstream headers, a page's own copy and any `AgentEnv-Role` it sends dropped) and takes the role driving that computer now (the gateway's computers being those `COMPUTERS` names, a multi env's, with or without a control token): the last to make an input call to its tools, as the call starts, through `/mcp`, `/step` or a trigger action under its `as` (`Gateway._drive`); without one, or from a computer the gateway doesn't front, it is `default`, the role read once per request. `changes/v1` (`ChangeAttribution`) counts no write window for a call to a computer's tools, a trigger action's included, so a write the computer's browser made goes to its request and one another party made during the call to that party. Its CDP route, `/browser//cdp//` (`env/gateway/browser_proxy.py`), reaches the website browser behind the `/svc` child ``, found from that child's card (it, or an app among its children, offering `browser/v1` `cdp` with `/cdp/` in its `computer-app/v1` `agent_routes`): it relays the browser's discovery and WebSocket both ways, each leg pinged every 20 s, and every CDP address the browser hands out, in `json/version`, `json/list` and its `cdp` answer through `/svc//`, comes back at the gateway, everything before `/cdp//` becoming the address the caller reached the gateway at and `/browser/`, keeping the https or wss of an address the browser minted under an origin its caller named, as `browser_connect_cdp` names the agent's, since a tunnel that ends TLS, as Modal's, may send no `X-Forwarded-Proto`; each connection is a `browser_connection` trajectory event, without its token. Its clock (`env/gateway/clock.py`) has one opaque version, a per-boot id and a count, that every `set_time`, `advance` and `clear` changes; `set_rate` (`/clock/set-rate`) changes an armed clock's rate from its time at the write, keeping its `t0` and generation as `advance` does, so time triggers keep their marks. Every clock change goes through `Gateway._change_clock`, which wakes the triggers when the change kept the clock's generation, answers the held watches and waits for the followers. Its followers, the computers on it (`CLOCK_FOLLOWER_TOKENS`, each child whose card serves `clock/v1` `sync_time`, by its read token, its control token for now), long-poll `/clock/watch` naming the version they show, each watch held up to the card's `hold_s` (`env/gateway/clock_followers.py`), and a write given `wait_followers_s` waits for each, answering 504 naming those behind, but not for one that hasn't watched for longer than a hold and a reconnect (`ClockFollowers.QUIET_S`), which it names at once with when each last watched; a restarted gateway is unarmed. While its clock is armed it serves agents `get_time` (`env/gateway/get_time.py`), which answers in UTC and also in the universe's zone, the one `sync_env_clock`'s `timezone` armed it in, or in an IANA `time_zone` it's given; executors' working `hours` (`env/gateway/triggers.py`) take a fixed `utc_offset` or an IANA `time_zone`. | | `artifact/` | Immutable versioned artifacts; every `put()` creates a new version. The document goes to the document store, binary payloads to the object store. Every artifact but an environment universe, whose `metadata` key holds its legacy metadata file ids, carries a `metadata` dict outside its versioned fields, changed by compare-and-swap (`merge_metadata`). Built-ins: `CliArtifact` (`cli`), `ComputerArtifact` (`computer`, a base computer: its architectures, OS, session user, settings and container form, whose image `put` reads from its registry into `metadata.validated_images`), `FileArtifact` (`file`), `FileArtifactUniverse` (`file_artifact_universe`), `DockerImageArtifact` (`docker_image`), `EnvironmentArtifact` (`environment`: its environment's files by path, stored as the one wrapped `file_artifact_ref` every environment artifact had when it has one file at its filename, else as `file_artifact_refs`; `get_file_artifacts()` reads either, and a load hands each file to the env's `data/add` with its path, which a pre-v1 load, taking one file, refuses), `EnvironmentUniverseArtifact` (`environment_universe`), `SkillArtifact` (`skill`); `[artifacts] type_aliases` maps another stored spelling of a type onto one of them. A `DockerImageArtifact` holds a tar.gz of its image, or, written by `put_ref` (`--image-ref` on `env mcp-server put` and `a2a-agent put`), only a registry reference with its tag pinned to a digest, which sandboxes pull, or a published image's tag with its `image_digest` and its build context, which sandboxes pull by the digest and build from the context when they can't (the infra images, and a bundle agent built from a shipped agent's sources, `Plan.published`), or, written by `put_context`, only its build context, which a VM sandbox builds before running it (`VmSandbox.load_docker_images`) and Modal builds before creating its container (`ModalSandboxProvider.prepare_image`, outside a fallback chain's deadline); anything else that runs images by name (a container on the local provider, a lone server on any provider but Modal) refuses such an image. A build context (`utils/docker/context.py`) is what `docker build` would send, `.dockerignore` applied, written so equal files give equal bytes and an equal `source_digest`. | -| `task/`, `task_step/` | A `Task` holds its `TaskStep`s inline; `Task.run()` executes them as a DAG. Its `headline_verifiers`, step ids saved only when set, name the grades that are its reward: one is the reward, several a multi-reward over them, none a multi-reward over every grade; it refuses one that names no step of the task, or one named twice. `depends_on` (None means all prior steps) gates a step, independent steps run concurrently, `fail_task_on_error` makes a failure fatal or tolerated, `retry_config` rolls a failed span back through the step journal and re-dispatches it. `task/lint.py` is `agent-env task lint` (a bundle folder, a task file or a stored task): an error is what a task gets wrong before it runs (a field its step doesn't read, a step's own `config_problems`, a headline that grades nothing, an aggregate source no verifier writes) and refuses `agent-env run`, `bundle register`, `task create`, `task validate` and `eval run`, and the bundle plans `openenv`'s `build_app` and the trainers make (`run`, `register`, `build_app`, `prepare_bundle` and the trainers take `--skip-lint`/`skip_lint`, which lifts lint's own rules but not a step's `config_problems`, which refused a bundle before lint; `eval run`'s lifts every error, since it checked none before); a warning is what may be wrong (a step's `config_warnings`, a store entity read with no version, no verifier, several and no headline, a judge that runs in the solver's own agent, which training refuses) and is only printed, each kind once by a run (`task.lint.said`), an eval run's unpinned references as one count (`unpinned_summary`), every one by `task lint`. `aggregate_verifiers` names its sources by step id (`sources`, `gates`) and reads their named grades: `combine` `pooled` (the default) pools their rows, `weighted_mean` weighs their scores, equally unless `weights` gives every source one, and a failing gate scores it 0; a failed or missing source fails it, and its older `verifier_ids` pools legacy entries as it always has. Built-in steps live in `task_step/task_steps/` (`deploy_env`, `deploy_agent`, `prompt_agent`, the verifiers under `verifiers/`, among them `start_computer_recording` (its driver draws each input over the frames in its caller's colour, and a pointer per role where the frames lack one, unless `annotation_settings` says `is_enabled: false`; a driver whose card lists no `annotate` records it plain, with a warning, and the run's recording entry says `annotated`) and `end_computer_recording`, `start_browser_recording` and `end_browser_recording` (`browser-recording/v1`: one recording per context, a lease's or the default one's, with a video of the tab its agent is on, its context's log, the browser's network log as HAR and opt-in frames keyed to the action log, the contexts its agents make recorded with it, one universe per recording, anything missing failing the run), and more). Every built-in verifier is on the `VerifierTaskStep` base (`verifiers/verifier.py`): it implements `verify` and returns a `Verification`, and the base writes the step's named grade to `context.metadata["grades"][]` (score, `min_passing_score`, `passed`, `verifier_status` graded, skipped or failed, criteria rows, type, version, and `verifier_settings`, the values the run graded with, its overrides applied and named in `overridden`, with `scoring_rules`) beside the legacy `verifications` entries every reader still takes; an exception from `verify` or a `Verification` with an `error`, as a timed-out `run_container_unit_tests_verifier`, is a failed grade, and `rubrics_verifier` still writes its `-trajectory-mistakes` entry itself. On an env whose card serves computer-exec/v1 (a computer), `run_code` with `env_id` and `run_container_unit_tests_verifier` with `env_id` run inside it as its session user through the driver: files staged with `data/add` and read with `data/get`, commands run with `run`; `computer_exec` runs one command there through `run` (a program and its arguments, or a string through `sh -c`; in a multi env, the computer it names), recorded under `computer_exec` in the run's metadata, a non-zero exit or a timeout failing it unless `check` is off, or with `background` starts it and leaves it running, as an app launched for the agent, a program that isn't there exiting 127; with `scope: "system"` it runs as root instead, through the computer's sandbox (`RootChannel`, `docker exec -u 0`), in the session user's folder and `HOME`, its output capped in the computer, never with `background` and not on a computer booted from a disk; on a Windows computer, which has no `sh`, a string or `background` command is refused; on a multi env, `load_artifact` with `env_id` puts an environment artifact named after one of its computers, or after an app of one, into that computer, the computer's own as files at their paths under the session user's home; `env_outcome_verifier` hands a `verify` that takes an `env_url` keyword the env's address. A computer's framework-only routes (everything but MCP and the card) take the per-deploy control token its provider boots it with (`DeployedEnv.control_token`, `AGENTENV_CONTROL_TOKEN`), a multi env's computers the multi env's own, which its gateway passes on only on their `/svc` routes and its clock watch (`CONTROL_TOKEN_CHILDREN`); framework calls send `deployed.control_headers`, `Task.run` runs every step under `protocol_v1.authorized` with each deployed env's (a `verify` included), and a `run_code` script inside the computer gets `input["env"]["headers"]`. `teardown_run` and the `teardown_sandboxes` step share one core (`task/teardown.py` `tear_down`): the recordings the run left open end with fresh grants, each env still up closes (`Env.close`; a computer env ends any recording still open), what stayed open is registered from its namespace, then every sandbox is terminated by id. A run whose teardown leaves sandboxes up, stopped by a second signal or failing, keeps on its instance the context it ended with (`record_teardown`), and `agent-env run` and `task run --keep` name `agent-env task teardown --instance `, which tears down what that context still records up, a running one only with `--force`. `task/episode/` runs a task with some of its agents played from outside, as a training loop does (`EpisodeSpec`). | +| `task/`, `task_step/` | A `Task` holds its `TaskStep`s inline; `Task.run()` executes them as a DAG. Its `headline_verifiers`, step ids saved only when set, name the grades that are its reward: one is the reward, several a multi-reward over them, none a multi-reward over every grade; it refuses one that names no step of the task, or one named twice. `depends_on` (None means all prior steps) gates a step, independent steps run concurrently, `fail_task_on_error` makes a failure fatal or tolerated, `retry_config` rolls a failed span back through the step journal and re-dispatches it. `task/lint.py` is `agent-env task lint` (a bundle folder, a task file or a stored task): an error is what a task gets wrong before it runs (a field its step doesn't read, a step's own `config_problems`, a headline that grades nothing, an aggregate source no verifier writes) and refuses `agent-env run`, `bundle register`, `task create`, `task validate` and `eval run`, and the bundle plans `openenv`'s `build_app` and the trainers make (`run`, `register`, `build_app`, `prepare_bundle` and the trainers take `--skip-lint`/`skip_lint`, which lifts lint's own rules but not a step's `config_problems`, which refused a bundle before lint; `eval run`'s lifts every error, since it checked none before); a warning is what may be wrong (a step's `config_warnings`, a store entity read with no version, no verifier, several and no headline, a judge that runs in the solver's own agent, which training refuses) and is only printed, each kind once by a run (`task.lint.said`), an eval run's unpinned references as one count (`unpinned_summary`), every one by `task lint`. `aggregate_verifiers` names its sources by step id (`sources`, `gates`) and reads their named grades: `combine` `pooled` (the default) pools their rows, `weighted_mean` weighs their scores, equally unless `weights` gives every source one, and a failing gate scores it 0; a failed or missing source fails it, and its older `verifier_ids` pools legacy entries as it always has. Built-in steps live in `task_step/task_steps/` (`deploy_env`, `deploy_agent`, `prompt_agent`, the verifiers under `verifiers/`, among them `start_computer_recording` (its driver draws each input over the frames in its caller's colour, and a pointer per role where the frames lack one, unless `annotation_settings` says `is_enabled: false`; a driver whose card lists no `annotate` records it plain, with a warning, and the run's recording entry says `annotated`) and `end_computer_recording`, `start_browser_recording` and `end_browser_recording` (`browser-recording/v1`: one recording per context, a lease's or the default one's, with a video of the tab its agent is on, its context's log, the browser's network log as HAR and opt-in frames keyed to the action log, the contexts its agents make recorded with it, one universe per recording, anything missing failing the run), and more). Every built-in verifier is on the `VerifierTaskStep` base (`verifiers/verifier.py`): it implements `verify` and returns a `Verification`, and the base writes the step's named grade to `context.metadata["grades"][]` (score, `min_passing_score`, `passed`, `verifier_status` graded, skipped or failed, criteria rows, type, version, and `verifier_settings`, the values the run graded with, its overrides applied and named in `overridden`, with `scoring_rules`) beside the legacy `verifications` entries every reader still takes; a judge's grade also has `judge_calls`, a record of each model call it made (`JudgeUsage`), and its `verifier_settings` hold the effort and thinking budget its calls carried, with `not_sent` for those its route or agent card doesn't take (a value the model refuses fails the grade); an exception from `verify` or a `Verification` with an `error`, as a timed-out `run_container_unit_tests_verifier`, is a failed grade, and `rubrics_verifier` still writes its `-trajectory-mistakes` entry itself. On an env whose card serves computer-exec/v1 (a computer), `run_code` with `env_id` and `run_container_unit_tests_verifier` with `env_id` run inside it as its session user through the driver: files staged with `data/add` and read with `data/get`, commands run with `run`; `computer_exec` runs one command there through `run` (a program and its arguments, or a string through `sh -c`; in a multi env, the computer it names), recorded under `computer_exec` in the run's metadata, a non-zero exit or a timeout failing it unless `check` is off, or with `background` starts it and leaves it running, as an app launched for the agent, a program that isn't there exiting 127; with `scope: "system"` it runs as root instead, through the computer's sandbox (`RootChannel`, `docker exec -u 0`), in the session user's folder and `HOME`, its output capped in the computer, never with `background` and not on a computer booted from a disk; on a Windows computer, which has no `sh`, a string or `background` command is refused; on a multi env, `load_artifact` with `env_id` puts an environment artifact named after one of its computers, or after an app of one, into that computer, the computer's own as files at their paths under the session user's home; `env_outcome_verifier` hands a `verify` that takes an `env_url` keyword the env's address. A computer's framework-only routes (everything but MCP and the card) take the per-deploy control token its provider boots it with (`DeployedEnv.control_token`, `AGENTENV_CONTROL_TOKEN`), a multi env's computers the multi env's own, which its gateway passes on only on their `/svc` routes and its clock watch (`CONTROL_TOKEN_CHILDREN`); framework calls send `deployed.control_headers`, `Task.run` runs every step under `protocol_v1.authorized` with each deployed env's (a `verify` included), and a `run_code` script inside the computer gets `input["env"]["headers"]`. `teardown_run` and the `teardown_sandboxes` step share one core (`task/teardown.py` `tear_down`): the recordings the run left open end with fresh grants, each env still up closes (`Env.close`; a computer env ends any recording still open), what stayed open is registered from its namespace, then every sandbox is terminated by id. A run whose teardown leaves sandboxes up, stopped by a second signal or failing, keeps on its instance the context it ended with (`record_teardown`), and `agent-env run` and `task run --keep` name `agent-env task teardown --instance `, which tears down what that context still records up, a running one only with `--force`. `task/episode/` runs a task with some of its agents played from outside, as a training loop does (`EpisodeSpec`). | | `store/` | Four store ABCs with local and cloud implementations: `DocumentStore` (SQLite, MongoDB, DynamoDB, Firestore with MongoDB compatibility), `ObjectStore` (filesystem, S3, Cloud Storage), `ImageStore` (local OCI registry, ECR), `SecretStore` (env vars or file, AWS Secrets Manager, Google Cloud Secret Manager). `VersionedEntityStore` implements the shared versioned get/put logic, `QueryBuilder` is the immutable chained query API, `store/base.py` holds the error types. `store/routing.py` is the local namespaces, `@local` and `@hf` (`is_local_id`), each with a documents file of its own: while the CLI or a `build_app` server runs, a local id and what a local task's run records go to local stores beside the configured ones, and that run's writes to the configured stores are refused. A new backend must pass the conformance kits in `tst/store/`. | | `config/` | The `Config` singleton (`get_config`, `configure`, `reset_config`) in `config/runtime.py`, file discovery in `config/loader.py`, and `load_impl`, which resolves `module:Class` pointers. `agent_env.store` re-exports the config names for compatibility. | | `providers/` | `providers/sandbox_providers/` holds the sandbox providers `local`, `modal`, `modal_vm`, `e2b`, `sail_vm` (the `sail` extra), `smol_vm` (the `smol` extra), `tensorlake` (the `tensorlake` extra), `tenki` (the `tenki` extra), `vercel` (the `vercel` extra), `boxd` (the `boxd` extra), `coreweave` (the `coreweave` extra), `daytona` (the `daytona` extra), `boat` (the `boat` extra), `agent37` (no extra), `kosa8` (no extra); `[sandbox] default` and `agent_default` accept a comma-separated fallback chain, whose deploys skip a provider that can't run them. A sandbox provider declares what it runs (`ON_THIS_MACHINE`, and for VMs on this machine the address their requests to it arrive at, `REACHES_HOST_AT`; `CONTAINER_ACCEPTS`, `PRIVATE_NETWORK`, `WEBSOCKETS`; `SUPPORTED_SANDBOX_MODES`, derived from whether it implements `create_sandbox` and `create_vm`; and `SANDBOX_ACCEPTS`, the images an agent's sandbox runs, which defaults to those a VM loads when it implements `create_vm` and to `CONTAINER_ACCEPTS` otherwise, so only a provider that implements `create_vm` yet gives an agent a container, like the local one, declares it), each sandbox carries the `platform` of the images it runs (linux/amd64 unless its provider sets another when it creates it; None, any, unchecked, for a local sandbox), and code outside `providers/sandbox_providers/` reads those, never which provider it has. `providers/env_providers/` holds the environment providers: `EnvironmentProvider` (an env's containers and state store), `EnvironmentGatewayProvider` (`gateway`, an env's default), which renders a docker-compose for the gateway and its MCP servers inside the sandbox, and `EnvironmentServerProvider` (`server`), one MCP server in its own container with no gateway in front and no state store; `providers/env_state/` holds env-state providers (`local_postgres` built in). | diff --git a/src/agent_env/config/model_call.py b/src/agent_env/config/model_call.py index 2cc68a1f8..23309afaa 100644 --- a/src/agent_env/config/model_call.py +++ b/src/agent_env/config/model_call.py @@ -88,12 +88,14 @@ def litellm_route(model: str, api_base: Optional[str], provider_of: Callable[... async def complete(route: ModelRoute, messages: list[dict], *, timeout: Optional[float], - response_format: Optional[dict] = None) -> ModelReply: - """One chat completion by ``route``, raising what LiteLLM raises.""" + response_format: Optional[dict] = None, settings: Optional[dict[str, Any]] = None) -> ModelReply: + """One chat completion by ``route``, raising what LiteLLM raises. ``settings`` are LiteLLM params for this call, such + as ``reasoning_effort``, over the config's ``[model.params]``; a caller sends only those ``takes`` says the route + takes.""" import litellm request: dict[str, Any] = dict(model=route.litellm_model, messages=messages, timeout=timeout, - **route.call.client_kwargs()) + **route.call.client_kwargs(), **(settings or {})) if response_format is not None: request[ModelParam.RESPONSE_FORMAT] = response_format response = await litellm.acompletion(**request) @@ -106,6 +108,29 @@ async def complete(route: ModelRoute, messages: list[dict], *, timeout: Optional return ModelReply(response.choices[0].message.content or "", route.model, route.endpoint_host, usage, cost) +def takes(route: ModelRoute, param: str) -> bool: + """Whether LiteLLM sends ``param`` (``reasoning_effort``, ``thinking``) on ``route``: one of the params it takes for + the route's provider and model, as LiteLLM's own table says. A route it can't place takes none.""" + import litellm + + try: + with contextlib.redirect_stdout(io.StringIO()): + model, provider, _, _ = litellm.get_llm_provider( + route.litellm_model, custom_llm_provider=route.call.params.get("custom_llm_provider")) + supported = litellm.get_supported_openai_params(model=model, custom_llm_provider=provider) + except Exception: + return False + return param in (supported or ()) + + +def refused_setting(exc: BaseException) -> bool: + """Whether ``exc`` is LiteLLM refusing a param's value for the model before sending the call, as GPT-5 refuses + ``reasoning_effort="xhigh"``: the call wasn't made, so nothing was spent.""" + import litellm + + return isinstance(exc, litellm.UnsupportedParamsError) + + def cut_off(exc: BaseException) -> bool: """Whether ``exc`` stopped a call that may have reached the model, so it may be billed with no answer: a cancel, or LiteLLM's ``Timeout``, raised itself or as the cause of a failure after retries. A timeout LiteLLM's client retried diff --git a/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py b/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py index 586808656..0e07303b2 100644 --- a/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py +++ b/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py @@ -8,6 +8,7 @@ import re import uuid from collections.abc import Mapping, Sequence +from contextvars import ContextVar from dataclasses import dataclass, field, replace from typing import Any, ClassVar, Optional @@ -24,7 +25,7 @@ from agent_env.config.errors import ConfigError from agent_env.config import model_call from agent_env.config.model import ModelRole, no_key_for -from agent_env.config.model_pricing import ReportedBy +from agent_env.config.model_pricing import ReportedBy, Tokens, price from agent_env.providers.sandbox_providers.sandbox import into_container from agent_env.task_step.context import ( PromptResponse, @@ -89,6 +90,74 @@ logger = logging.getLogger(__name__) # How a judge sent to a URL other than the configured endpoint is given that URL's key. _JUDGE_KEY_HOW = "judge_litellm_api_key, or litellm_api_key, in the run's overrides" +# The judge settings a call carries, besides its model. +_JUDGE_SETTINGS = ("effort", "max_thinking_tokens") +# A call's cost keys, as ``Cost.fields`` writes them. +_COST_KEYS = ("cost_usd", "cost_status", "cost_source", "reported_cost_usd") + + +class JudgeUsage(StepUsage): + """A judge step's usage, written as every step's is, and its own record of the run for its grade: each model call + it made (``calls``) and the settings those calls carried (``carried``): those sent, those it couldn't send, and the + endpoint host they reached.""" + + def __init__(self, context: TaskStepContext, step_id: str) -> None: + super().__init__(context, step_id) + self.calls: list[dict[str, Any]] = [] + self.sent: Optional[dict[str, Any]] = None + self.not_sent: dict[str, Any] = {} + self.endpoint_host: Optional[str] = None + self._cutting = False + + def call(self, role: ModelRole, usage: Optional[Usage], *, model: Optional[str], endpoint_host: Optional[str], + reported_by: ReportedBy = ReportedBy.HARNESS, cost: Optional[Mapping[str, Any]] = None) -> None: + """The base's, and the call in the record: ``cost``, the cost keys the call itself carried (a direct call's, + from ``model_call``), over its price from LiteLLM's map.""" + super().call(role, usage, model=model, endpoint_host=endpoint_host, reported_by=reported_by) + cut = self._cutting + self._record("cut_off" if cut else "answered", None if cut else usage, model, endpoint_host, reported_by, + cost=None if cut else cost) + + def cut_off_call(self, role: ModelRole, *, model: Optional[str], endpoint_host: Optional[str], + reported_by: ReportedBy = ReportedBy.HARNESS) -> None: + self._cutting = True + try: + super().cut_off_call(role, model=model, endpoint_host=endpoint_host, reported_by=reported_by) + finally: + self._cutting = False + + def refused_call(self, *, model: Optional[str], endpoint_host: Optional[str], error: str) -> None: + """A call that got no answer and cost nothing, as one LiteLLM refused before sending it or one the endpoint + refused: in the grade's record, not in the step's usage.""" + self._record("refused", None, model, endpoint_host, ReportedBy.PROVIDER, error=error) + + def carried(self, sent: dict[str, Any], not_sent: dict[str, Any], endpoint_host: Optional[str]) -> None: + """The settings the run's calls carried, kept from its first call, since every call of a run carries the same.""" + if self.sent is None: + self.sent, self.not_sent, self.endpoint_host = dict(sent), dict(not_sent), endpoint_host + + def _record(self, outcome: str, usage: Optional[Usage], model: Optional[str], endpoint_host: Optional[str], + reported_by: ReportedBy, *, error: Optional[str] = None, + cost: Optional[Mapping[str, Any]] = None) -> None: + priced = price(Tokens.of(usage.to_dict()) if usage is not None else None, + usage.cost_usd if usage is not None else None, model=model, prices=self._prices, + reported_by=reported_by) + self.calls.append({"outcome": outcome, "model": model, "endpoint_host": endpoint_host, + "usage": usage.to_dict() if usage is not None else None, + **priced.fields(), **(cost or {}), "batch": _BATCH.get(), "attempt": _ATTEMPT.get(), + **({"error": error} if error is not None else {})}) + + +# The run of a judge step this task is in, set by its execute; the judge batch and output attempt a call belongs to. +_JUDGE_USAGE: ContextVar[Optional[JudgeUsage]] = ContextVar("judge_usage", default=None) +_BATCH: ContextVar[Optional[int]] = ContextVar("judge_batch", default=None) +_ATTEMPT: ContextVar[Optional[int]] = ContextVar("judge_attempt", default=None) + + +def judge_calls() -> list[dict[str, Any]]: + """The record of each model call the judge step running in this task has made so far (``JudgeUsage.calls``).""" + judge = _JUDGE_USAGE.get() + return list(judge.calls) if judge is not None else [] # The judge echoes each criterion's id back and results are matched by exact string. @@ -293,6 +362,28 @@ def _caches_prompts(model: str) -> bool: return "claude" in model.lower() +def _direct_settings(route: model_call.ModelRoute, run: Mapping[str, Any] + ) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]: + """The LiteLLM params a direct judge call carries for the run's effort and thinking budget, where the route takes + them (``model_call.takes``); the settings sent, with any ``temperature`` and ``seed`` the config's + ``[model.params]`` give every call; and those the route doesn't take, left out.""" + params: dict[str, Any] = {} + sent = {key: route.call.params[key] for key in ("temperature", "seed") if key in route.call.params} + not_sent: dict[str, Any] = {} + for setting, param, value in (("effort", "reasoning_effort", run["effort"]), + ("max_thinking_tokens", "thinking", run["max_thinking_tokens"])): + if value is None: + continue + if not model_call.takes(route, param): + not_sent[setting] = value + continue + params[param] = value if param == "reasoning_effort" else {"type": "enabled", "budget_tokens": value} + sent[setting] = value + if not_sent: + logger.warning("%s takes no %s; the judge grades without them", route.model, sorted(not_sent)) + return params, sent, not_sent + + def _image_url_block(frame: ImageFrame) -> dict: """Adapt a neutral trajectory image to LiteLLM's image block shape.""" return { @@ -362,6 +453,11 @@ def __init__(self, message: str, trajectory_object_url: Optional[str]): self.trajectory_object_url = trajectory_object_url +class JudgeSettingRefused(RuntimeError): + """A direct judge's model refused a value of one of its settings, as GPT-5 refuses ``reasoning_effort="xhigh"``: + raised at once, not retried, so the grade fails with the refusal.""" + + # With timeout retries on, the judge is allowed this much longer than the poll waits, so it never stops itself first: # the poll's deadline (which cancels the task) is the one sign that it ran out of time, whatever the harness names its # own timeout. More than a poll interval plus a request; the judge's own limit stays behind it as a backstop. @@ -774,8 +870,8 @@ def _run_values(self, context: TaskStepContext) -> dict[str, Any]: """Each setting a run's ``step_params`` or ``user_overrides`` can change, by the step's own field name, at the value this run judges with: the judge reads these and ``verifier_settings`` records them, so the two can't disagree. Unvalidated; the judge checks them as it reads them. Never mutates ``self``, which concurrent runs - share. A ``step_params`` ``criteria`` replaces on presence, so ``[]`` replaces too; effort and the thinking - budget reach only an agent judge, and the agent sandbox only a judge the step deploys.""" + share. A ``step_params`` ``criteria`` replaces on presence, so ``[]`` replaces too; the run's effort and thinking + budget reach every judge, and the agent sandbox only a judge the step deploys.""" step_params = self.step_param_overrides(context) overrides = context.metadata.get("user_overrides") or {} use_agent_judge = self.use_agent_judge if overrides.get("use_agent_judge") is None else overrides["use_agent_judge"] @@ -789,9 +885,8 @@ def _run_values(self, context: TaskStepContext) -> dict[str, Any]: else self.grade_up_to_turn, "use_agent_judge": use_agent_judge, "trajectory_filter": trajectory_filter, - "effort": (overrides.get("judge_effort") or self.effort) if use_agent_judge else self.effort, - "max_thinking_tokens": (overrides.get("judge_max_thinking_tokens") or self.max_thinking_tokens) - if use_agent_judge else self.max_thinking_tokens, + "effort": overrides.get("judge_effort") or self.effort, + "max_thinking_tokens": overrides.get("judge_max_thinking_tokens") or self.max_thinking_tokens, "judge_batch_size": _override_or(overrides, "judge_batch_size", self.judge_batch_size), "judge_batch_concurrency": _override_or(overrides, "judge_batch_concurrency", self.judge_batch_concurrency), "judge_sandbox_type": (overrides.get("agent_sandbox") or self.judge_sandbox_type) @@ -808,7 +903,9 @@ def _recorded_values(self, context: TaskStepContext) -> dict[str, Any]: def verifier_settings(self, context: TaskStepContext) -> dict[str, Any]: """The step's fields as this run judges with them (``_recorded_values`` in place of the stored ones), the judge model the run recorded (else the one it resolves), the agent it deploys as its judge when it deploys one, and - ``overridden``, the settings this run's overrides changed. Never a key, header or base URL.""" + ``overridden``, the settings this run's overrides changed. Once the judge has called, its effort and thinking + budget are those its calls carried, ``not_sent`` those it couldn't send, with ``judge_endpoint_host`` and any + ``temperature`` and ``seed`` the config gave a direct call. Never a key, header or base URL.""" settings = super().verifier_settings(context) settings.pop("default_model_api_base", None) values, stored = self._recorded_values(context), self._recorded_values(TaskStepContext()) @@ -821,8 +918,30 @@ def verifier_settings(self, context: TaskStepContext) -> dict[str, Any]: settings["judge_a2a_agent_id"] = get_config().get_default_a2a_agent_id() recorded = (context.metadata.get("models") or {}).get(ModelRole.JUDGE.record_key) or {} settings["judge_model"] = recorded[self.id] if self.id in recorded else self._judge_model(context) + if (judge := _JUDGE_USAGE.get()) is not None and judge.sent is not None: + for key in _JUDGE_SETTINGS: + if key in settings or key in judge.sent or key in judge.not_sent: + settings[key] = judge.sent.get(key) + settings.update({key: value for key, value in judge.sent.items() if key not in _JUDGE_SETTINGS}) + if judge.not_sent: + settings["not_sent"] = dict(judge.not_sent) + if judge.endpoint_host: + settings["judge_endpoint_host"] = judge.endpoint_host return {**settings, "overridden": overridden} + def grade_fields(self, context: TaskStepContext) -> dict[str, Any]: + """``judge_calls``, the record of each model call the run's judge made, when it made any.""" + judge = _JUDGE_USAGE.get() + return {"judge_calls": list(judge.calls)} if judge is not None and judge.calls else {} + + async def execute(self, context: TaskStepContext) -> TaskStepContext: + """The base's, with this run's judge record scoped to it, so a grade reads only its own run's calls.""" + token = _JUDGE_USAGE.set(None) + try: + return await super().execute(context) + finally: + _JUDGE_USAGE.reset(token) + async def verify(self, context: TaskStepContext) -> Verification: verdict = self._gated(await self._judged(context)) if verdict.mistakes_entry is not None: @@ -1130,9 +1249,12 @@ def eval_prompt_for(batch: list[dict]) -> str: raise RuntimeError(f"Verifier '{self.verifier_id}': _criteria_batches gave {len(batches)} batches, but " f"output_format={self.output_format.value} is graded in one judge call.") concurrency = asyncio.Semaphore(batch_concurrency or self.DEFAULT_JUDGE_BATCH_CONCURRENCY) - usage = StepUsage(context, self.id) + usage = JudgeUsage(context, self.id) + _JUDGE_USAGE.set(usage) - async def grade(batch: list[dict]) -> tuple[list[dict], int, list[dict], Optional[str]]: + async def grade(batch: list[dict], number: Optional[int] = None + ) -> tuple[list[dict], int, list[dict], Optional[str]]: + _BATCH.set(number) prompt = eval_prompt_for(batch) if len(batches) > 1: prompt += self._BATCH_NOTE.format( @@ -1160,7 +1282,7 @@ async def grade(batch: list[dict]) -> tuple[list[dict], int, list[dict], Optiona else: try: async with asyncio.TaskGroup() as group: - graded = [group.create_task(grade(batch)) for batch in batches] + graded = [group.create_task(grade(batch, number)) for number, batch in enumerate(batches, 1)] except ExceptionGroup as failed: # The first batch's error, as an unbatched judge would raise it; the group cancels the rest. raise failed.exceptions[0] from failed @@ -1549,6 +1671,7 @@ async def _prompt_llm_judge( "strict": True, }, } + params, sent, not_sent = _direct_settings(route, self._run_values(context)) # Some endpoints reject json_schema with images. Fall back once on that exact # error shape; malformed JSON is handled by the outer output-retry loop. use_response_format = True @@ -1557,10 +1680,14 @@ async def _prompt_llm_judge( for attempt in range(1, self.DEFAULT_MAX_RETRIES + 1): try: reply = await model_call.complete(route, messages, timeout=self.judge_timeout_seconds, - response_format=response_format if use_response_format else None) - return {"response": reply.content, "trajectory_object_url": None, **reply.fields()} + response_format=response_format if use_response_format else None, + settings=params) + return {"response": reply.content, "trajectory_object_url": None, "sent": sent, "not_sent": not_sent, + **reply.fields()} except Exception as exc: last_exc = exc + if params and model_call.refused_setting(exc): + raise JudgeSettingRefused(f"{model} refused the judge's {sorted(sent)}: {exc}") from exc if image_blocks and use_response_format and _looks_like_response_format_error(exc): logger.warning( f"Multimodal judge call with json_schema failed for verifier " @@ -1586,9 +1713,11 @@ async def _configure_judge_a2a( judge_max_thinking_tokens: Optional[int], context: TaskStepContext, headers: Mapping[str, str], + endpoint_host: Optional[str] = None, ) -> Optional[str]: """Configure the judge agent through its agent-config extension; the model it took, None for one that runs its - own.""" + own. An effort or thinking budget its card doesn't take is left out and the run's judge record says so; a value + it refuses fails the post, so the grade.""" from agent_env.a2a_agent import A2AAgent from agent_env.a2a_agent import protocol @@ -1616,6 +1745,13 @@ async def _configure_judge_a2a( endpoint = (config_ext.get("params") or {}).get("endpoint", "/ext/agent-config") await protocol.post_agent_config(judge_a2a_url + endpoint, config_payload, headers=headers) logger.info(f"Set judge agent config: {list(config_payload.keys())}") + sent = {k: config_payload[k] for k in _JUDGE_SETTINGS if k in config_payload} + not_sent = {k: desired_config[k] for k in _JUDGE_SETTINGS if k in desired_config and k not in config_payload} + if not_sent: + logger.warning("Verifier '%s': the judge agent doesn't take %s; it grades without them", + self.verifier_id, sorted(not_sent)) + if (judge := _JUDGE_USAGE.get()) is not None: + judge.carried(sent, not_sent, endpoint_host) # What the judge agent took; one that doesn't accept a model grades on its own. context.record_model(ModelRole.JUDGE.record_key, self.id, config_payload.get("model")) return config_payload.get("model") @@ -1807,7 +1943,8 @@ async def _fetch_judge_trajectory( async def _judge_directly(self, prompt: str, *, model: str, context: TaskStepContext, image_blocks: Optional[list[dict]], usage: StepUsage) -> dict: """One direct judge call, its usage in ``usage``: what it answered, or, when a cancel or a time limit stopped - it, a call of unknown usage.""" + it, a call of unknown usage; a judge's record (``JudgeUsage``) also keeps a call that got no answer, and the + settings the calls carried.""" try: if image_blocks: data = await self._prompt_llm_judge(prompt, model=model, context=context, image_blocks=image_blocks) @@ -1816,7 +1953,11 @@ async def _judge_directly(self, prompt: str, *, model: str, context: TaskStepCon except BaseException as exc: if model_call.cut_off(exc): usage.cut_off_call(ModelRole.JUDGE, model=model, endpoint_host=None, reported_by=ReportedBy.PROVIDER) + elif isinstance(usage, JudgeUsage) and isinstance(exc, Exception): + usage.refused_call(model=model, endpoint_host=None, error=f"{type(exc).__name__}: {exc}") raise + if isinstance(usage, JudgeUsage) and "sent" in data: + usage.carried(data["sent"], data["not_sent"], data.get("endpoint_host")) self._record_direct_call(usage, data, model=model) return data @@ -1827,8 +1968,10 @@ def _record_direct_call(usage: StepUsage, data: dict, *, model: str) -> None: read = Usage.from_model_response(data["usage"]) if data.get("usage") else None if data.get("reported_cost_usd") is not None: read = replace(read or Usage(), cost_usd=data["reported_cost_usd"]) + extra = ({"cost": {key: data[key] for key in _COST_KEYS if key in data}} + if isinstance(usage, JudgeUsage) else {}) usage.call(ModelRole.JUDGE, read, model=data.get("model") or model, endpoint_host=data.get("endpoint_host"), - reported_by=ReportedBy.PROVIDER) + reported_by=ReportedBy.PROVIDER, **extra) async def _run_judge_with_output_retries( self, @@ -1870,9 +2013,11 @@ async def _run_judge_with_output_retries( judge_max_thinking_tokens=judge_max_thinking_tokens, context=context, headers=judge_agent.control_headers, + endpoint_host=getattr(judge_agent, "model_endpoint_host", None), ) for attempt in range(1, self.DEFAULT_MAX_RETRIES + 1): + _ATTEMPT.set(attempt) if use_agent_judge: data = await self._invoke_judge_retrying_timeouts( discrepancy_log=discrepancy_log, diff --git a/src/agent_env/task_step/task_steps/verifiers/user_sim_judge.py b/src/agent_env/task_step/task_steps/verifiers/user_sim_judge.py index 3d329d9b2..3cff27910 100644 --- a/src/agent_env/task_step/task_steps/verifiers/user_sim_judge.py +++ b/src/agent_env/task_step/task_steps/verifiers/user_sim_judge.py @@ -147,7 +147,7 @@ import json import logging import re -from dataclasses import dataclass, field +from dataclasses import dataclass from typing import Any, ClassVar, Optional from agent_env.config import model_call @@ -155,7 +155,11 @@ from agent_env.task_step.task_step import TaskStep, TaskStepDependency from agent_env.task_step.task_steps.verifiers import user_sim_judge_core as core from agent_env.task_step.task_steps.verifiers.judge_utils.judge_output_format import JudgeOutputFormat -from agent_env.task_step.task_steps.verifiers.rubrics_verifier import RubricsVerdict, RubricsVerifierTaskStep +from agent_env.task_step.task_steps.verifiers.rubrics_verifier import ( + RubricsVerdict, + RubricsVerifierTaskStep, + judge_calls, +) from agent_env.task_step.task_steps.verifiers.scoring import ScoreAggregator from agent_env.task_step.task_steps.verifiers.verifier import Verification @@ -200,16 +204,12 @@ @dataclass class _ThisRun: - """One run's judging: what it asks and what its calls cost. Held by the run's own copy of the step, never by the - step a task shares across runs.""" + """One run's judging: what it asks, and how its first call went. Held by the run's own copy of the step, never by + the step a task shares across runs.""" plan: core.Plan text: str # the run as the judge reads it first: Optional[asyncio.Event] = None # set once the run's first call is over first_error: Optional[BaseException] = None # what the first call raised, if it did - calls: int = 0 - usage: list[Any] = field(default_factory=list) - cost: float = 0.0 # the calls' costs that have a figure - unpriced: int = 0 # the calls whose cost has none class UserSimJudge(RubricsVerifierTaskStep): @@ -390,8 +390,9 @@ def _finish(self, judged: RubricsVerdict, entry: dict, this: _ThisRun) -> Verifi error["not_failing"] = NOT_FAILING_UNCONFIRMED else: error["fails_task"] = True - output = {**judged.output, **entry, "user_sim_error": error, "calls": this.calls, - "usage": core.usage_total(this.usage), **_cost(this)} + answered = [call for call in judge_calls() if call["outcome"] == "answered"] + output = {**judged.output, **entry, "user_sim_error": error, "calls": len(answered), + "usage": _usage(answered), **_cost(answered)} if error["value"] == "unknown": checks = [r for r in rows if r["id"] in core.CHECKS] output["flag"] = FLAG_NONE_DECIDED if checks and all(r["verdict"] == "error" for r in checks) \ @@ -450,16 +451,9 @@ async def _prompt_llm_judge(self, eval_prompt: str, *, model: str, context: Task head = eval_prompt[:end + len(this.text)] if end >= 0 else None async def call() -> dict: - got = await super(UserSimJudge, self)._prompt_llm_judge( + return await super(UserSimJudge, self)._prompt_llm_judge( eval_prompt, model=model, context=context, image_blocks=image_blocks, system=SYSTEM, cached_prefix=head) - this.calls += 1 - this.usage.append(got.get("usage")) - if got.get("cost_usd") is None: - this.unpriced += 1 - else: - this.cost += got["cost_usd"] - return got if this.first is None: this.first = asyncio.Event() @@ -519,12 +513,23 @@ def _setup_error(e: BaseException) -> Optional[BaseException]: return next((x for x in _chain(e) if isinstance(x, setup)), None) -def _cost(this: _ThisRun) -> dict[str, Any]: - """The run's ``cost``: its calls' costs summed, None when no call's cost has a figure, and ``unpriced_calls``, the - calls left out of the sum, when there are some.""" - priced = this.calls - this.unpriced - total = round(this.cost, COST_DECIMALS) if priced or not this.calls else None - return {"cost": total, **({"unpriced_calls": this.unpriced} if this.unpriced else {})} +def _cost(calls: list[dict[str, Any]]) -> dict[str, Any]: + """The run's ``cost``: its answered calls' costs summed, None when no call's cost has a figure, and + ``unpriced_calls``, the calls left out of the sum, when there are some.""" + priced = [call["cost_usd"] for call in calls if call.get("cost_usd") is not None] + unpriced = len(calls) - len(priced) + total = round(float(sum(priced)), COST_DECIMALS) if priced or not calls else None + return {"cost": total, **({"unpriced_calls": unpriced} if unpriced else {})} + + +def _usage(calls: list[dict[str, Any]]) -> dict[str, int]: + """The answered calls' token counts summed, as core reads each call's usage (``Usage``), input counting the cache.""" + keys = ("input_tokens", "output_tokens", "total_tokens", "cache_read_tokens", "cache_write_tokens") + total = dict.fromkeys(keys, 0) + for call in calls: + for key in keys: + total[key] += (call.get("usage") or {}).get(key) or 0 + return total def _problems(model: Any, items: Any, gate: Any, rubric_persona: Any = None) -> list[str]: diff --git a/src/agent_env/task_step/task_steps/verifiers/user_sim_judge_core.py b/src/agent_env/task_step/task_steps/verifiers/user_sim_judge_core.py index 551941114..56dffdfd0 100644 --- a/src/agent_env/task_step/task_steps/verifiers/user_sim_judge_core.py +++ b/src/agent_env/task_step/task_steps/verifiers/user_sim_judge_core.py @@ -722,22 +722,3 @@ def user_sim_error(rows: list[dict]) -> dict: NOT_JUDGED = {"value": "no", "because": [], "unknown": []} - - -def usage_total(usages: list[Any]) -> dict[str, int]: - """The token counts of several calls, summed; a cache read reported as ``prompt_tokens_details.cached_tokens`` - counts as one.""" - keys = ("prompt_tokens", "completion_tokens", "cache_read_input_tokens", "cache_creation_input_tokens") - total = dict.fromkeys(keys, 0) - for u in usages: - if not isinstance(u, dict): - continue - for k in keys: - v = u.get(k) - if isinstance(v, (int, float)): - total[k] += int(v) - details = u.get("prompt_tokens_details") - cached = details.get("cached_tokens") if isinstance(details, dict) else None - if isinstance(cached, int) and not u.get("cache_read_input_tokens"): - total["cache_read_input_tokens"] += cached - return total diff --git a/src/agent_env/task_step/task_steps/verifiers/verifier.py b/src/agent_env/task_step/task_steps/verifiers/verifier.py index 289776d80..544219bab 100644 --- a/src/agent_env/task_step/task_steps/verifiers/verifier.py +++ b/src/agent_env/task_step/task_steps/verifiers/verifier.py @@ -68,11 +68,13 @@ class _GradeFields(TypedDict): class Grade(_GradeFields, total=False): """A verifier step's named grade, as ``context.metadata["grades"][]`` holds it. ``verifier_status`` is a ``VerifierStatus`` value, and ``score`` is None unless it is ``graded``; each ``verifier_criteria`` row has ``id``, - ``score``, ``passed``, ``weight`` and ``skipped``, besides any other keys the verifier gave it. The two fields here - are written only for a large output.""" + ``score``, ``passed``, ``weight`` and ``skipped``, besides any other keys the verifier gave it. The two + ``verifier_output`` fields here are written only for a large output; ``judge_calls``, a judge's record of each model + call it made, only by a judge (``grade_fields``).""" verifier_output_ref: dict[str, Any] verifier_output_offload_error: str + judge_calls: list[dict[str, Any]] @dataclass @@ -159,6 +161,11 @@ def verifier_settings(self, context: TaskStepContext) -> dict[str, Any]: fields = {k: v for k, v in self.to_dict().items() if k not in _NOT_SETTINGS} return {**fields, "score_aggregator": self.score_aggregator.value} + def grade_fields(self, context: TaskStepContext) -> dict[str, Any]: + """Fields of the grade beside the base's, written whether the step graded, skipped or failed, so they say what + a failed run did too, as a judge's ``judge_calls``. None by default.""" + return {} + def criterion_rows(self) -> Optional[int]: """How many criterion rows a run of this verifier grades, when its config alone says, for lint to weigh a pooled aggregate's sources; None when only a run can tell, as for a script's or a test run's rows.""" @@ -210,6 +217,7 @@ def _grade(self, context: TaskStepContext, status: VerifierStatus, score: Option verifier_type=self.type, verifier_version=_providing_version(type(self).__module__), verifier_settings=self._settings(context), + **self.grade_fields(context), ) def _score(self, verification: Verification) -> Optional[float]: diff --git a/tst/data/verifier_golden/rubrics_subclasses.json b/tst/data/verifier_golden/rubrics_subclasses.json index dd62f4bd1..80ab76f8e 100644 --- a/tst/data/verifier_golden/rubrics_subclasses.json +++ b/tst/data/verifier_golden/rubrics_subclasses.json @@ -161,10 +161,11 @@ }, "calls": 7, "usage": { - "prompt_tokens": 700, - "completion_tokens": 140, - "cache_read_input_tokens": 0, - "cache_creation_input_tokens": 0 + "input_tokens": 700, + "output_tokens": 140, + "total_tokens": 840, + "cache_read_tokens": 0, + "cache_write_tokens": 0 }, "cost": 0.007 } @@ -361,10 +362,11 @@ }, "calls": 7, "usage": { - "prompt_tokens": 700, - "completion_tokens": 140, - "cache_read_input_tokens": 0, - "cache_creation_input_tokens": 0 + "input_tokens": 700, + "output_tokens": 140, + "total_tokens": 840, + "cache_read_tokens": 0, + "cache_write_tokens": 0 }, "cost": 0.007 } @@ -543,10 +545,11 @@ }, "calls": 7, "usage": { - "prompt_tokens": 700, - "completion_tokens": 140, - "cache_read_input_tokens": 0, - "cache_creation_input_tokens": 0 + "input_tokens": 700, + "output_tokens": 140, + "total_tokens": 840, + "cache_read_tokens": 0, + "cache_write_tokens": 0 }, "cost": 0.007 } @@ -757,10 +760,11 @@ }, "calls": 7, "usage": { - "prompt_tokens": 700, - "completion_tokens": 140, - "cache_read_input_tokens": 0, - "cache_creation_input_tokens": 0 + "input_tokens": 700, + "output_tokens": 140, + "total_tokens": 840, + "cache_read_tokens": 0, + "cache_write_tokens": 0 }, "cost": 0.007 } @@ -958,10 +962,11 @@ }, "calls": 7, "usage": { - "prompt_tokens": 700, - "completion_tokens": 140, - "cache_read_input_tokens": 0, - "cache_creation_input_tokens": 0 + "input_tokens": 700, + "output_tokens": 140, + "total_tokens": 840, + "cache_read_tokens": 0, + "cache_write_tokens": 0 }, "cost": 0.007, "flag": "user sim judge undecided" @@ -1138,10 +1143,11 @@ }, "calls": 6, "usage": { - "prompt_tokens": 600, - "completion_tokens": 120, - "cache_read_input_tokens": 0, - "cache_creation_input_tokens": 0 + "input_tokens": 600, + "output_tokens": 120, + "total_tokens": 720, + "cache_read_tokens": 0, + "cache_write_tokens": 0 }, "cost": 0.006, "flag": "user sim judge undecided" @@ -1323,10 +1329,11 @@ }, "calls": 0, "usage": { - "prompt_tokens": 0, - "completion_tokens": 0, - "cache_read_input_tokens": 0, - "cache_creation_input_tokens": 0 + "input_tokens": 0, + "output_tokens": 0, + "total_tokens": 0, + "cache_read_tokens": 0, + "cache_write_tokens": 0 }, "cost": 0.0, "flag": "the judge couldn't decide any check \u2014 check its setup" @@ -1521,10 +1528,11 @@ }, "calls": 8, "usage": { - "prompt_tokens": 800, - "completion_tokens": 160, - "cache_read_input_tokens": 0, - "cache_creation_input_tokens": 0 + "input_tokens": 800, + "output_tokens": 160, + "total_tokens": 960, + "cache_read_tokens": 0, + "cache_write_tokens": 0 }, "cost": 0.008 } @@ -1722,10 +1730,11 @@ }, "calls": 7, "usage": { - "prompt_tokens": 700, - "completion_tokens": 140, - "cache_read_input_tokens": 0, - "cache_creation_input_tokens": 0 + "input_tokens": 700, + "output_tokens": 140, + "total_tokens": 840, + "cache_read_tokens": 0, + "cache_write_tokens": 0 }, "cost": 0.007 } @@ -1900,10 +1909,11 @@ }, "calls": 7, "usage": { - "prompt_tokens": 700, - "completion_tokens": 140, - "cache_read_input_tokens": 0, - "cache_creation_input_tokens": 0 + "input_tokens": 700, + "output_tokens": 140, + "total_tokens": 840, + "cache_read_tokens": 0, + "cache_write_tokens": 0 }, "cost": 0.007 } @@ -2138,10 +2148,11 @@ }, "calls": 7, "usage": { - "prompt_tokens": 700, - "completion_tokens": 140, - "cache_read_input_tokens": 0, - "cache_creation_input_tokens": 0 + "input_tokens": 700, + "output_tokens": 140, + "total_tokens": 840, + "cache_read_tokens": 0, + "cache_write_tokens": 0 }, "cost": 0.007 } @@ -2326,10 +2337,11 @@ }, "calls": 7, "usage": { - "prompt_tokens": 700, - "completion_tokens": 140, - "cache_read_input_tokens": 0, - "cache_creation_input_tokens": 0 + "input_tokens": 700, + "output_tokens": 140, + "total_tokens": 840, + "cache_read_tokens": 0, + "cache_write_tokens": 0 }, "cost": 0.007 } diff --git a/tst/integration/task_step/judge_settings_wire_test.py b/tst/integration/task_step/judge_settings_wire_test.py new file mode 100644 index 000000000..b0dd1fedc --- /dev/null +++ b/tst/integration/task_step/judge_settings_wire_test.py @@ -0,0 +1,90 @@ +"""A direct judge's settings on the wire: through LiteLLM's real client to a fake OpenAI-compatible endpoint, the run's +effort goes out as ``reasoning_effort`` where LiteLLM takes it, a thinking budget the route doesn't take stays out and +the grade says so, a value LiteLLM refuses never reaches the endpoint, and the grade keeps each call with the usage the +endpoint reported.""" + +from __future__ import annotations + +import json +import re + +import pytest + +from agent_env.task_step.context import PromptResponse, TaskStepContext, VerifierNotPassingError +from agent_env.task_step.task_steps.verifiers.rubrics_verifier import JudgeSettingRefused, RubricsVerifierTaskStep +from tst.util.config import install_model_config +from tst.util.fake_openai import USAGE, FakeOpenAI, Text + +pytestmark = [pytest.mark.integration] + +CRITERIA = [{"id": "greets", "description": "It greets the user"}, {"id": "polite", "description": "It is polite"}] + + +def _verdict(body: dict) -> Text: + """Every criterion the request asks about passes.""" + ids = list(dict.fromkeys(re.findall(r'"id": "(c\d+)"', body["messages"][-1]["content"]))) + return Text(json.dumps({"results": [{"id": i, "score": 1.0, "justification": "It says hello."} for i in ids]})) + + +@pytest.fixture +def endpoint(monkeypatch): + with FakeOpenAI(respond=_verdict) as fake: + install_model_config(monkeypatch, base_url=f"{fake.url}/v1", api_key="test-key") + yield fake + + +def _judge(model: str, **fields) -> RubricsVerifierTaskStep: + return RubricsVerifierTaskStep(id="judge", version=1, criteria=CRITERIA, prompt_id="ask", use_agent_judge=False, + use_trajectory=False, verifier_id="judge", default_model=model, **fields) + + +def _context() -> TaskStepContext: + return TaskStepContext(prompt_responses=[PromptResponse(prompt_id="ask", response="Hello, nice to meet you!", + prompt_text="Greet me.")], instance_id="inst-1") + + +async def _grade(step: RubricsVerifierTaskStep, context: TaskStepContext) -> dict: + try: + await step.execute(context) + except VerifierNotPassingError: + pass + return context.metadata["grades"][step.id] + + +@pytest.mark.asyncio +async def test_gpt_5_gets_the_effort_on_the_wire_and_the_thinking_budget_is_recorded_as_not_sent(endpoint): + context = _context() + + grade = await _grade(_judge("gpt-5", effort="low", max_thinking_tokens=2048), context) + + [request] = endpoint.completions() + assert request.body["reasoning_effort"] == "low" and "thinking" not in request.body + settings = grade["verifier_settings"] + assert (settings["effort"], settings["max_thinking_tokens"], settings["not_sent"]) == ( + "low", None, {"max_thinking_tokens": 2048}) + [call] = grade["judge_calls"] + assert (call["outcome"], call["model"], call["usage"]["input_tokens"], call["usage"]["output_tokens"]) == ( + "answered", "gpt-5", USAGE["prompt_tokens"], USAGE["completion_tokens"]) + assert grade["verifier_status"] == "graded" and grade["score"] == 1.0 + + +@pytest.mark.asyncio +async def test_a_model_without_reasoning_control_grades_without_the_effort_and_says_so(endpoint): + grade = await _grade(_judge("gpt-4o-mini", effort="high"), _context()) + + [request] = endpoint.completions() + assert "reasoning_effort" not in request.body + assert grade["verifier_settings"]["not_sent"] == {"effort": "high"} and grade["verifier_status"] == "graded" + + +@pytest.mark.asyncio +async def test_a_value_litellm_refuses_never_reaches_the_endpoint_and_fails_the_grade(endpoint): + context = _context() + + with pytest.raises(JudgeSettingRefused, match="xhigh"): + await _judge("gpt-5", effort="xhigh").execute(context) + + assert endpoint.completions() == [] + grade = context.metadata["grades"]["judge"] + assert grade["verifier_status"] == "failed" + assert [call["outcome"] for call in grade["judge_calls"]] == ["refused"] diff --git a/tst/unit/task_step/verifiers/test_rubrics_family_grades.py b/tst/unit/task_step/verifiers/test_rubrics_family_grades.py index d15c7a3dd..554157608 100644 --- a/tst/unit/task_step/verifiers/test_rubrics_family_grades.py +++ b/tst/unit/task_step/verifiers/test_rubrics_family_grades.py @@ -44,8 +44,8 @@ async def test_the_settings_are_what_the_run_graded_with_and_say_what_its_overri settings = grade["verifier_settings"] assert (settings["criteria"], settings["judge_model"], settings["judge_batch_size"]) == (OVERRIDE, "judge-x", 1) assert settings["trajectory_filter"] is None and settings["default_model"] == "judge-model" - assert settings["effort"] is None - assert settings["overridden"] == ["criteria", "judge_batch_size", "judge_model"] + assert settings["effort"] == "high" + assert settings["overridden"] == ["criteria", "effort", "judge_batch_size", "judge_model"] assert "sk-run-key" not in json.dumps(grade) and "llm.example.test" not in json.dumps(grade) @@ -174,8 +174,8 @@ def test_the_user_sim_judges_settings_leave_out_what_its_judge_never_uses(): assert (settings["judge_model"], settings["judge_batch_size"], settings["judge_batch_concurrency"]) == ( "judge-x", 2, 3) - assert not {"criteria", "trajectory_filter", "effort"} & set(settings) - assert settings["overridden"] == ["judge_batch_size", "judge_batch_concurrency", "judge_model"] + assert not {"criteria", "trajectory_filter"} & set(settings) and settings["effort"] == "high" + assert settings["overridden"] == ["effort", "judge_batch_size", "judge_batch_concurrency", "judge_model"] @pytest.mark.asyncio diff --git a/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_settings.py b/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_settings.py new file mode 100644 index 000000000..3225a1e1e --- /dev/null +++ b/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_settings.py @@ -0,0 +1,176 @@ +"""A judge's settings as its calls carried them, and its record of each call: the direct judge sends the run's effort +and thinking budget where LiteLLM takes them on its route, leaves out and records those it doesn't, fails at once on a +value its model refuses, and every judge's grade keeps one record per call.""" + +from __future__ import annotations + +import logging +from types import SimpleNamespace + +import litellm +import pytest + +from agent_env.a2a_agent import A2AAgent, protocol +from agent_env.task_step.context import TaskStepContext, VerifierNotPassingError +from agent_env.task_step.task_steps.verifiers import rubrics_verifier +from agent_env.task_step.task_steps.verifiers.rubrics_verifier import JudgeSettingRefused, JudgeUsage +from tst.unit.task_step.verifiers.test_rubrics_verifier_golden import TWO, _binary, _context, _ids, _step +from tst.util.config import install_model_config + +ENDPOINT = "https://gw.test/v1" +USAGE = {"prompt_tokens": 100, "completion_tokens": 20, "total_tokens": 120} + + +def _llm(monkeypatch, *, answers=None, refuse_effort=False, **config) -> list[dict]: + """LiteLLM faked through the configured endpoint: each request kept, each answer a binary verdict for the ids its + prompt asks about (``answers`` overrides them in turn); ``refuse_effort`` raises as LiteLLM refuses a value.""" + install_model_config(monkeypatch, base_url=ENDPOINT, api_key="configured-key", **config) + requests: list[dict] = [] + queued = list(answers or []) + + async def acompletion(**kwargs): + requests.append(kwargs) + if refuse_effort and "reasoning_effort" in kwargs: + raise litellm.UnsupportedParamsError(message="reasoning_effort=xhigh is not supported for gpt-5", + llm_provider="openai", model="gpt-5") + prompt = kwargs["messages"][-1]["content"] + text = prompt if isinstance(prompt, str) else "".join(block.get("text", "") for block in prompt) + content = queued.pop(0) if queued else _binary(_ids(text)) + return SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content=content))], usage=dict(USAGE), + _hidden_params={}) + + monkeypatch.setattr(litellm, "acompletion", acompletion) + return requests + + +async def _grade(step, context: TaskStepContext) -> dict: + try: + await step.execute(context) + except VerifierNotPassingError: + pass + return context.metadata["grades"][step.id] + + +@pytest.mark.asyncio +async def test_the_direct_judge_sends_the_effort_and_thinking_budget_its_route_takes_and_records_them(monkeypatch): + requests = _llm(monkeypatch) + step = _step(default_model="claude-sonnet-4-6", effort="high", max_thinking_tokens=2048) + + grade = await _grade(step, _context()) + + assert {(r["reasoning_effort"], r["thinking"]["budget_tokens"]) for r in requests} == {("high", 2048)} + settings = grade["verifier_settings"] + assert (settings["effort"], settings["max_thinking_tokens"], settings["judge_endpoint_host"]) == ( + "high", 2048, "gw.test") + assert "not_sent" not in settings and grade["verifier_status"] == "graded" + + +@pytest.mark.asyncio +async def test_a_setting_the_route_doesnt_take_is_left_out_and_the_grade_says_so(monkeypatch, caplog): + requests = _llm(monkeypatch) + step = _step(default_model="gpt-4o-mini", effort="high", max_thinking_tokens=2048) + + with caplog.at_level(logging.WARNING): + grade = await _grade(step, _context()) + + assert not {"reasoning_effort", "thinking"} & set(requests[0]) + settings = grade["verifier_settings"] + assert (settings["effort"], settings["max_thinking_tokens"]) == (None, None) + assert settings["not_sent"] == {"effort": "high", "max_thinking_tokens": 2048} + assert grade["verifier_status"] == "graded" + assert "gpt-4o-mini takes no ['effort', 'max_thinking_tokens']; the judge grades without them" in caplog.text + + +@pytest.mark.asyncio +async def test_gpt_5_takes_effort_but_no_thinking_budget(monkeypatch): + requests = _llm(monkeypatch) + grade = await _grade(_step(default_model="gpt-5", effort="low", max_thinking_tokens=2048), _context()) + + assert requests[0]["reasoning_effort"] == "low" and "thinking" not in requests[0] + assert grade["verifier_settings"]["not_sent"] == {"max_thinking_tokens": 2048} + + +@pytest.mark.asyncio +async def test_a_value_the_model_refuses_fails_the_grade_at_once_with_the_call_in_its_record(monkeypatch): + requests = _llm(monkeypatch, refuse_effort=True) + context = _context() + + with pytest.raises(JudgeSettingRefused, match=r"gpt-5 refused the judge's \['effort'\]"): + await _step(default_model="gpt-5", effort="xhigh").execute(context) + + assert len(requests) == 1 + grade = context.metadata["grades"]["verify"] + assert grade["verifier_status"] == "failed" and "reasoning_effort=xhigh is not supported" in ( + grade["verifier_error_reasoning"]) + assert [(c["outcome"], c["model"], c["usage"]) for c in grade["judge_calls"]] == [("refused", "gpt-5", None)] + + +@pytest.mark.asyncio +async def test_the_runs_judge_effort_reaches_a_direct_judge(monkeypatch): + requests = _llm(monkeypatch) + + grade = await _grade(_step(default_model="claude-sonnet-4-6"), _context({"judge_effort": "low"})) + + assert requests[0]["reasoning_effort"] == "low" + assert grade["verifier_settings"]["effort"] == "low" and "effort" in grade["verifier_settings"]["overridden"] + + +@pytest.mark.asyncio +async def test_the_configs_temperature_and_seed_are_recorded_as_sent(monkeypatch): + _llm(monkeypatch, params={"temperature": 0, "seed": 7}) + + grade = await _grade(_step(default_model="gpt-4o-mini"), _context()) + + assert (grade["verifier_settings"]["temperature"], grade["verifier_settings"]["seed"]) == (0, 7) + + +@pytest.mark.asyncio +async def test_the_grade_keeps_one_record_per_call_with_its_batch_and_attempt(monkeypatch): + _llm(monkeypatch) + context = _context({"judge_batch_size": 1}) + + grade = await _grade(_step(default_model="gpt-4o-mini"), context) + + calls = grade["judge_calls"] + assert sorted((c["batch"], c["attempt"], c["outcome"]) for c in calls) == [(1, 1, "answered"), (2, 1, "answered")] + assert {(c["model"], c["endpoint_host"], c["usage"]["input_tokens"], c["usage"]["output_tokens"]) for c in calls} == { + ("gpt-4o-mini", "gw.test", 100, 20)} + assert all(c["cost_status"] == "priced" and c["cost_usd"] > 0 for c in calls) + [entry] = context.metadata["step_usage"]["verify"] + assert entry["role"] == "judge" and entry["turns"] == 2 + + +@pytest.mark.asyncio +async def test_an_output_retry_is_a_record_of_its_own(monkeypatch): + ids = [f"c{i}" for i in range(1, len(TWO) + 1)] + _llm(monkeypatch, answers=[_binary(ids[:1]), _binary(ids)]) + + grade = await _grade(_step(default_model="gpt-4o-mini"), _context()) + + assert [(c["attempt"], c["outcome"]) for c in grade["judge_calls"]] == [(1, "answered"), (2, "answered")] + + +@pytest.mark.asyncio +async def test_an_agent_judge_card_without_effort_leaves_it_out_and_the_record_says_so(monkeypatch, caplog): + posted: list[dict] = [] + + async def post(url, payload, headers=None): + posted.append(payload) + + monkeypatch.setattr(protocol, "post_agent_config", post) + card = {"capabilities": {"extensions": [{"uri": A2AAgent.EXT_AGENT_CONFIG, "params": { + "endpoint": "/ext/agent-config", "methods": {"set": {"request": {"supported": ["model"]}}}}}]}} + context = TaskStepContext() + judge = JudgeUsage(context, "verify") + token = rubrics_verifier._JUDGE_USAGE.set(judge) + try: + with caplog.at_level(logging.WARNING): + await _step(use_agent_judge=True)._configure_judge_a2a( + judge_a2a_url="http://judge.test", judge_agent_card=card, model="m", judge_effort="high", + judge_max_thinking_tokens=None, context=context, headers={}, endpoint_host="gw.test") + finally: + rubrics_verifier._JUDGE_USAGE.reset(token) + + assert posted == [{"model": "m"}] + assert (judge.sent, judge.not_sent, judge.endpoint_host) == ({}, {"effort": "high"}, "gw.test") + assert "the judge agent doesn't take ['effort']; it grades without them" in caplog.text diff --git a/tst/unit/task_step/verifiers/test_user_sim_judge.py b/tst/unit/task_step/verifiers/test_user_sim_judge.py index 9c612a8f7..8840e8bca 100644 --- a/tst/unit/task_step/verifiers/test_user_sim_judge.py +++ b/tst/unit/task_step/verifiers/test_user_sim_judge.py @@ -276,7 +276,7 @@ async def test_each_check_s_verdict_is_recorded_with_its_reason_and_turns(monkey "not_failing": usj.NOT_FAILING_OFF} assert entry["format"] == "user_sim_checks" and entry["score"] == 0.0 assert len(fake.calls) == 7 == entry["calls"] and {c["model"] for c in fake.calls} == {JUDGE} - assert entry["usage"]["prompt_tokens"] == 700 and entry["cost"] == pytest.approx(0.007) + assert entry["usage"]["input_tokens"] == 700 and entry["cost"] == pytest.approx(0.007) class _PricedFirst(FakeModel): @@ -770,7 +770,7 @@ async def test_a_claude_judge_gets_the_system_message_and_the_run_marked_for_the assert cached["text"].startswith('You check a user simulator ("the user sim")') assert rest["text"].startswith("\n\n# THE CRITERIA\n") and "cache_control" not in rest assert calls[0]["messages"][1]["content"][0] == calls[1]["messages"][1]["content"][0] - assert entry["usage"]["prompt_tokens"] > 0 and entry["cost"] > 0 + assert entry["usage"]["input_tokens"] > 0 and entry["cost"] > 0 _GPT = dict(llm_provider="openai", model="openai/gpt-4o") From e020745ff74650fdb53f638f77b0186a7e826b1e Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 09:54:58 -0800 Subject: [PATCH 2/6] fix(verifiers): a judge records each request it retried, the settings the merged request sent, and keeps them in a failed grade The request merges [model.params] and the judge's settings as a dict display, so a run's effort wins over the config's instead of raising. The settings recorded are read from that merged request, so an effort the config alone gives is recorded as sent. The settings and endpoint host are recorded before the first request, so a failed grade keeps them, and each request _prompt_llm_judge retries is a record of its own: a timed-out one a call of unknown usage, counted in the step's usage too, any other refused. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/config/model_call.py | 4 +- .../task_steps/verifiers/rubrics_verifier.py | 44 +++++++++++------ .../test_rubrics_verifier_judge_settings.py | 47 ++++++++++++++++++- 3 files changed, 76 insertions(+), 19 deletions(-) diff --git a/src/agent_env/config/model_call.py b/src/agent_env/config/model_call.py index 23309afaa..9b0a214ac 100644 --- a/src/agent_env/config/model_call.py +++ b/src/agent_env/config/model_call.py @@ -94,8 +94,8 @@ async def complete(route: ModelRoute, messages: list[dict], *, timeout: Optional takes.""" import litellm - request: dict[str, Any] = dict(model=route.litellm_model, messages=messages, timeout=timeout, - **route.call.client_kwargs(), **(settings or {})) + request: dict[str, Any] = {"model": route.litellm_model, "messages": messages, "timeout": timeout, + **route.call.client_kwargs(), **(settings or {})} if response_format is not None: request[ModelParam.RESPONSE_FORMAT] = response_format response = await litellm.acompletion(**request) diff --git a/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py b/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py index 0e07303b2..6529a4bcf 100644 --- a/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py +++ b/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py @@ -365,10 +365,9 @@ def _caches_prompts(model: str) -> bool: def _direct_settings(route: model_call.ModelRoute, run: Mapping[str, Any] ) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]: """The LiteLLM params a direct judge call carries for the run's effort and thinking budget, where the route takes - them (``model_call.takes``); the settings sent, with any ``temperature`` and ``seed`` the config's - ``[model.params]`` give every call; and those the route doesn't take, left out.""" + them (``model_call.takes``), over the config's ``[model.params]``; the settings the request then sends, read from + the two merged, with any ``temperature`` and ``seed``; and the run's settings the route doesn't take, left out.""" params: dict[str, Any] = {} - sent = {key: route.call.params[key] for key in ("temperature", "seed") if key in route.call.params} not_sent: dict[str, Any] = {} for setting, param, value in (("effort", "reasoning_effort", run["effort"]), ("max_thinking_tokens", "thinking", run["max_thinking_tokens"])): @@ -378,10 +377,23 @@ def _direct_settings(route: model_call.ModelRoute, run: Mapping[str, Any] not_sent[setting] = value continue params[param] = value if param == "reasoning_effort" else {"type": "enabled", "budget_tokens": value} - sent[setting] = value if not_sent: logger.warning("%s takes no %s; the judge grades without them", route.model, sorted(not_sent)) - return params, sent, not_sent + request = {**route.call.params, **params} + thinking = request.get("thinking") + sent = {"effort": request.get("reasoning_effort"), + "max_thinking_tokens": thinking.get("budget_tokens") if isinstance(thinking, Mapping) else None, + **{key: request[key] for key in ("temperature", "seed") if key in request}} + return params, {key: value for key, value in sent.items() if value is not None}, not_sent + + +def _record_failed_call(judge: JudgeUsage, exc: BaseException, *, model: str, endpoint_host: Optional[str]) -> None: + """A direct judge request that got no answer, in the run's record: cut off by a time limit (maybe billed, so a call + of unknown usage in the step's usage too), or refused, costing nothing.""" + if model_call.cut_off(exc): + judge.cut_off_call(ModelRole.JUDGE, model=model, endpoint_host=endpoint_host, reported_by=ReportedBy.PROVIDER) + else: + judge.refused_call(model=model, endpoint_host=endpoint_host, error=f"{type(exc).__name__}: {exc}") def _image_url_block(frame: ImageFrame) -> dict: @@ -1672,6 +1684,9 @@ async def _prompt_llm_judge( }, } params, sent, not_sent = _direct_settings(route, self._run_values(context)) + judge = _JUDGE_USAGE.get() + if judge is not None: + judge.carried(sent, not_sent, route.endpoint_host) # Some endpoints reject json_schema with images. Fall back once on that exact # error shape; malformed JSON is handled by the outer output-retry loop. use_response_format = True @@ -1682,12 +1697,14 @@ async def _prompt_llm_judge( reply = await model_call.complete(route, messages, timeout=self.judge_timeout_seconds, response_format=response_format if use_response_format else None, settings=params) - return {"response": reply.content, "trajectory_object_url": None, "sent": sent, "not_sent": not_sent, - **reply.fields()} + return {"response": reply.content, "trajectory_object_url": None, **reply.fields()} except Exception as exc: last_exc = exc + if judge is not None: + _record_failed_call(judge, exc, model=model, endpoint_host=route.endpoint_host) if params and model_call.refused_setting(exc): - raise JudgeSettingRefused(f"{model} refused the judge's {sorted(sent)}: {exc}") from exc + raise JudgeSettingRefused(f"{model} refused the judge's " + f"{sorted(key for key in _JUDGE_SETTINGS if key in sent)}: {exc}") from exc if image_blocks and use_response_format and _looks_like_response_format_error(exc): logger.warning( f"Multimodal judge call with json_schema failed for verifier " @@ -1943,21 +1960,18 @@ async def _fetch_judge_trajectory( async def _judge_directly(self, prompt: str, *, model: str, context: TaskStepContext, image_blocks: Optional[list[dict]], usage: StepUsage) -> dict: """One direct judge call, its usage in ``usage``: what it answered, or, when a cancel or a time limit stopped - it, a call of unknown usage; a judge's record (``JudgeUsage``) also keeps a call that got no answer, and the - settings the calls carried.""" + it, a call of unknown usage. Under a judge's record (``JudgeUsage``), each request that failed is already in + it, from ``_prompt_llm_judge``'s own retries; a cancel, which those don't see, is recorded here.""" try: if image_blocks: data = await self._prompt_llm_judge(prompt, model=model, context=context, image_blocks=image_blocks) else: data = await self._prompt_llm_judge(prompt, model=model, context=context) except BaseException as exc: - if model_call.cut_off(exc): + recorded = isinstance(exc, Exception) and _JUDGE_USAGE.get() is not None + if not recorded and model_call.cut_off(exc): usage.cut_off_call(ModelRole.JUDGE, model=model, endpoint_host=None, reported_by=ReportedBy.PROVIDER) - elif isinstance(usage, JudgeUsage) and isinstance(exc, Exception): - usage.refused_call(model=model, endpoint_host=None, error=f"{type(exc).__name__}: {exc}") raise - if isinstance(usage, JudgeUsage) and "sent" in data: - usage.carried(data["sent"], data["not_sent"], data.get("endpoint_host")) self._record_direct_call(usage, data, model=model) return data diff --git a/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_settings.py b/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_settings.py index 3225a1e1e..f62242b49 100644 --- a/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_settings.py +++ b/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_settings.py @@ -21,15 +21,19 @@ USAGE = {"prompt_tokens": 100, "completion_tokens": 20, "total_tokens": 120} -def _llm(monkeypatch, *, answers=None, refuse_effort=False, **config) -> list[dict]: +def _llm(monkeypatch, *, answers=None, refuse_effort=False, failures=(), **config) -> list[dict]: """LiteLLM faked through the configured endpoint: each request kept, each answer a binary verdict for the ids its - prompt asks about (``answers`` overrides them in turn); ``refuse_effort`` raises as LiteLLM refuses a value.""" + prompt asks about (``answers`` overrides them in turn); ``refuse_effort`` raises as LiteLLM refuses a value, and + ``failures`` are raised by the first requests, one each.""" install_model_config(monkeypatch, base_url=ENDPOINT, api_key="configured-key", **config) requests: list[dict] = [] queued = list(answers or []) + failing = list(failures) async def acompletion(**kwargs): requests.append(kwargs) + if failing: + raise failing.pop(0) if refuse_effort and "reasoning_effort" in kwargs: raise litellm.UnsupportedParamsError(message="reasoning_effort=xhigh is not supported for gpt-5", llm_provider="openai", model="gpt-5") @@ -124,6 +128,45 @@ async def test_the_configs_temperature_and_seed_are_recorded_as_sent(monkeypatch assert (grade["verifier_settings"]["temperature"], grade["verifier_settings"]["seed"]) == (0, 7) +@pytest.mark.asyncio +async def test_the_runs_effort_wins_over_the_configs_and_the_configs_alone_is_recorded_as_sent(monkeypatch): + requests = _llm(monkeypatch, params={"reasoning_effort": "low"}) + + over = await _grade(_step(default_model="claude-sonnet-4-6", effort="high"), _context()) + alone = await _grade(_step(default_model="claude-sonnet-4-6"), _context()) + + assert [request["reasoning_effort"] for request in requests] == ["high", "low"] + assert (over["verifier_settings"]["effort"], alone["verifier_settings"]["effort"]) == ("high", "low") + + +@pytest.mark.asyncio +async def test_a_request_retried_after_a_timeout_is_a_record_of_its_own(monkeypatch): + _llm(monkeypatch, failures=[litellm.Timeout("timed out", model="gpt-4o-mini", llm_provider="openai")]) + context = _context() + + grade = await _grade(_step(default_model="gpt-4o-mini"), context) + + assert [call["outcome"] for call in grade["judge_calls"]] == ["cut_off", "answered"] + [entry] = context.metadata["step_usage"]["verify"] + assert entry["turns"] == 2 and entry["partial"] is True + + +@pytest.mark.asyncio +async def test_a_judge_whose_requests_all_fail_keeps_its_settings_and_each_request_in_its_failed_grade(monkeypatch): + _llm(monkeypatch, failures=[litellm.RateLimitError("slow down", llm_provider="openai", model="gpt-4o-mini")] * 3) + context = _context() + + with pytest.raises(RuntimeError, match="failed after 3 attempts"): + await _step(default_model="gpt-4o-mini", effort="high").execute(context) + + grade = context.metadata["grades"]["verify"] + assert grade["verifier_status"] == "failed" + assert (grade["verifier_settings"]["not_sent"], grade["verifier_settings"]["judge_endpoint_host"]) == ( + {"effort": "high"}, "gw.test") + assert [call["outcome"] for call in grade["judge_calls"]] == ["refused"] * 3 + assert all("slow down" in call["error"] for call in grade["judge_calls"]) + + @pytest.mark.asyncio async def test_the_grade_keeps_one_record_per_call_with_its_batch_and_attempt(monkeypatch): _llm(monkeypatch) From b3085b580b8d4b0c06ecc0ef8c1a6fbb8576e420 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 10:53:30 -0800 Subject: [PATCH 3/6] refactor(verifiers): the judge's record moves to judge_utils/judge_usage, and StepUsage gives it one call path JudgeUsage, the run's scope and its accessors move out of rubrics_verifier into judge_utils/judge_usage. StepUsage's call and cut_off_call share one private path, so JudgeUsage overrides each directly instead of telling them apart by a flag. _judge_directly finds the record by the usage it's handed, as _record_direct_call does. A direct call's record keeps its whole cost by Cost.KEYS, every key Cost.fields writes, rather than a copy of four of them. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/config/model_pricing.py | 6 +- .../verifiers/judge_utils/judge_usage.py | 108 ++++++++++++++++++ .../task_steps/verifiers/rubrics_verifier.py | 97 +++------------- .../task_steps/verifiers/user_sim_judge.py | 9 +- src/agent_env/task_step/usage.py | 16 ++- .../test_rubrics_verifier_judge_settings.py | 18 ++- 6 files changed, 147 insertions(+), 107 deletions(-) create mode 100644 src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_usage.py diff --git a/src/agent_env/config/model_pricing.py b/src/agent_env/config/model_pricing.py index a37584313..c1e49e597 100644 --- a/src/agent_env/config/model_pricing.py +++ b/src/agent_env/config/model_pricing.py @@ -12,7 +12,7 @@ from dataclasses import dataclass, field from enum import StrEnum from pathlib import Path -from typing import Any, Mapping, Optional +from typing import Any, ClassVar, Mapping, Optional logger = logging.getLogger(__name__) @@ -165,6 +165,10 @@ class Cost: assumed: tuple[Assumed, ...] = () unpriced: Optional[Unpriced] = None + #: Every key ``fields`` can write, so a record built from them keeps a call's whole cost. + KEYS: ClassVar[tuple[str, ...]] = ("cost_usd", "cost_status", "cost_source", "reported_cost_usd", + "uncached_input_tokens", "unit_prices", "cost_assumed", "unpriced_reason") + def fields(self) -> dict[str, Any]: """The cost as a usage entry's keys.""" record: dict[str, Any] = {"cost_usd": self.usd, "cost_status": self.status.value, "cost_source": self.source, diff --git a/src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_usage.py b/src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_usage.py new file mode 100644 index 000000000..6d9c9ac38 --- /dev/null +++ b/src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_usage.py @@ -0,0 +1,108 @@ +"""A judge step's record of its run, beside its usage: each model call the judge made and the settings those calls +carried, for its grade (``judge_calls``, ``verifier_settings``). The record of the run in progress is held per task, +since a step is shared by every run of its task: a judge step's ``execute`` scopes it (``scope``) and its judging starts +it (``start``).""" + +from __future__ import annotations + +import contextlib +from collections.abc import Iterator, Mapping +from contextvars import ContextVar +from typing import Any, Optional + +from agentenv_protocol.a2a_agent import Usage + +from agent_env.config.model import ModelRole +from agent_env.config.model_pricing import ReportedBy, Tokens, price +from agent_env.task_step.context import TaskStepContext +from agent_env.task_step.usage import StepUsage + + +class JudgeUsage(StepUsage): + """A judge step's usage, written as every step's is, and its own record of the run: each model call it made + (``calls``) and the settings those calls carried (``carried``): those sent, those it couldn't send, and the endpoint + host they reached.""" + + def __init__(self, context: TaskStepContext, step_id: str) -> None: + super().__init__(context, step_id) + self.calls: list[dict[str, Any]] = [] + self.sent: Optional[dict[str, Any]] = None + self.not_sent: dict[str, Any] = {} + self.endpoint_host: Optional[str] = None + + def call(self, role: ModelRole, usage: Optional[Usage], *, model: Optional[str], endpoint_host: Optional[str], + reported_by: ReportedBy = ReportedBy.HARNESS, cost: Optional[Mapping[str, Any]] = None) -> None: + """The base's, and the answered call in the record: ``cost``, the cost keys the call itself carried (a direct + call's, from ``model_call``), else its price from LiteLLM's map.""" + super().call(role, usage, model=model, endpoint_host=endpoint_host, reported_by=reported_by) + self._record("answered", usage, model, endpoint_host, reported_by, cost=cost) + + def cut_off_call(self, role: ModelRole, *, model: Optional[str], endpoint_host: Optional[str], + reported_by: ReportedBy = ReportedBy.HARNESS) -> None: + super().cut_off_call(role, model=model, endpoint_host=endpoint_host, reported_by=reported_by) + self._record("cut_off", None, model, endpoint_host, reported_by) + + def refused_call(self, *, model: Optional[str], endpoint_host: Optional[str], error: str) -> None: + """A call that got no answer and cost nothing, as one LiteLLM refused before sending it or one the endpoint + refused: in the record, not in the step's usage.""" + self._record("refused", None, model, endpoint_host, ReportedBy.PROVIDER, error=error) + + def carried(self, sent: dict[str, Any], not_sent: dict[str, Any], endpoint_host: Optional[str]) -> None: + """The settings the run's calls carried, kept from its first call, since every call of a run carries the same.""" + if self.sent is None: + self.sent, self.not_sent, self.endpoint_host = dict(sent), dict(not_sent), endpoint_host + + def _record(self, outcome: str, usage: Optional[Usage], model: Optional[str], endpoint_host: Optional[str], + reported_by: ReportedBy, *, error: Optional[str] = None, + cost: Optional[Mapping[str, Any]] = None) -> None: + if cost is None: + cost = price(Tokens.of(usage.to_dict()) if usage is not None else None, + usage.cost_usd if usage is not None else None, model=model, prices=self._prices, + reported_by=reported_by).fields() + self.calls.append({"outcome": outcome, "model": model, "endpoint_host": endpoint_host, + "usage": usage.to_dict() if usage is not None else None, **cost, + "batch": _BATCH.get(), "attempt": _ATTEMPT.get(), + **({"error": error} if error is not None else {})}) + + +_RUN: ContextVar[Optional[JudgeUsage]] = ContextVar("judge_run", default=None) +_BATCH: ContextVar[Optional[int]] = ContextVar("judge_batch", default=None) +_ATTEMPT: ContextVar[Optional[int]] = ContextVar("judge_attempt", default=None) + + +@contextlib.contextmanager +def scope() -> Iterator[None]: + """One run of a judge step: a record started within it is the one ``current`` gives until the run ends.""" + token = _RUN.set(None) + try: + yield + finally: + _RUN.reset(token) + + +def start(context: TaskStepContext, step_id: str) -> JudgeUsage: + """The run's record, started: its usage written to ``context`` under ``step_id``.""" + judge = JudgeUsage(context, step_id) + _RUN.set(judge) + return judge + + +def current() -> Optional[JudgeUsage]: + """The record of the judge run this task is in, None outside one or before it started.""" + return _RUN.get() + + +def calls() -> list[dict[str, Any]]: + """The record of each model call the judge run this task is in has made so far.""" + judge = _RUN.get() + return list(judge.calls) if judge is not None else [] + + +def batch(number: Optional[int]) -> None: + """The judge batch the calls made from here in this task belong to (None for a run in one batch).""" + _BATCH.set(number) + + +def attempt(number: int) -> None: + """The output attempt the calls made from here in this task belong to.""" + _ATTEMPT.set(number) diff --git a/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py b/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py index 6529a4bcf..5b6aca762 100644 --- a/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py +++ b/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py @@ -8,7 +8,6 @@ import re import uuid from collections.abc import Mapping, Sequence -from contextvars import ContextVar from dataclasses import dataclass, field, replace from typing import Any, ClassVar, Optional @@ -25,7 +24,7 @@ from agent_env.config.errors import ConfigError from agent_env.config import model_call from agent_env.config.model import ModelRole, no_key_for -from agent_env.config.model_pricing import ReportedBy, Tokens, price +from agent_env.config.model_pricing import Cost, ReportedBy from agent_env.providers.sandbox_providers.sandbox import into_container from agent_env.task_step.context import ( PromptResponse, @@ -62,6 +61,8 @@ agent_error_text, fetch_container_logs, ) +from agent_env.task_step.task_steps.verifiers.judge_utils import judge_usage +from agent_env.task_step.task_steps.verifiers.judge_utils.judge_usage import JudgeUsage from agent_env.task_step.task_steps.verifiers.judge_utils.atif_turns import ( AtifDocuments, TurnSource, @@ -92,72 +93,6 @@ _JUDGE_KEY_HOW = "judge_litellm_api_key, or litellm_api_key, in the run's overrides" # The judge settings a call carries, besides its model. _JUDGE_SETTINGS = ("effort", "max_thinking_tokens") -# A call's cost keys, as ``Cost.fields`` writes them. -_COST_KEYS = ("cost_usd", "cost_status", "cost_source", "reported_cost_usd") - - -class JudgeUsage(StepUsage): - """A judge step's usage, written as every step's is, and its own record of the run for its grade: each model call - it made (``calls``) and the settings those calls carried (``carried``): those sent, those it couldn't send, and the - endpoint host they reached.""" - - def __init__(self, context: TaskStepContext, step_id: str) -> None: - super().__init__(context, step_id) - self.calls: list[dict[str, Any]] = [] - self.sent: Optional[dict[str, Any]] = None - self.not_sent: dict[str, Any] = {} - self.endpoint_host: Optional[str] = None - self._cutting = False - - def call(self, role: ModelRole, usage: Optional[Usage], *, model: Optional[str], endpoint_host: Optional[str], - reported_by: ReportedBy = ReportedBy.HARNESS, cost: Optional[Mapping[str, Any]] = None) -> None: - """The base's, and the call in the record: ``cost``, the cost keys the call itself carried (a direct call's, - from ``model_call``), over its price from LiteLLM's map.""" - super().call(role, usage, model=model, endpoint_host=endpoint_host, reported_by=reported_by) - cut = self._cutting - self._record("cut_off" if cut else "answered", None if cut else usage, model, endpoint_host, reported_by, - cost=None if cut else cost) - - def cut_off_call(self, role: ModelRole, *, model: Optional[str], endpoint_host: Optional[str], - reported_by: ReportedBy = ReportedBy.HARNESS) -> None: - self._cutting = True - try: - super().cut_off_call(role, model=model, endpoint_host=endpoint_host, reported_by=reported_by) - finally: - self._cutting = False - - def refused_call(self, *, model: Optional[str], endpoint_host: Optional[str], error: str) -> None: - """A call that got no answer and cost nothing, as one LiteLLM refused before sending it or one the endpoint - refused: in the grade's record, not in the step's usage.""" - self._record("refused", None, model, endpoint_host, ReportedBy.PROVIDER, error=error) - - def carried(self, sent: dict[str, Any], not_sent: dict[str, Any], endpoint_host: Optional[str]) -> None: - """The settings the run's calls carried, kept from its first call, since every call of a run carries the same.""" - if self.sent is None: - self.sent, self.not_sent, self.endpoint_host = dict(sent), dict(not_sent), endpoint_host - - def _record(self, outcome: str, usage: Optional[Usage], model: Optional[str], endpoint_host: Optional[str], - reported_by: ReportedBy, *, error: Optional[str] = None, - cost: Optional[Mapping[str, Any]] = None) -> None: - priced = price(Tokens.of(usage.to_dict()) if usage is not None else None, - usage.cost_usd if usage is not None else None, model=model, prices=self._prices, - reported_by=reported_by) - self.calls.append({"outcome": outcome, "model": model, "endpoint_host": endpoint_host, - "usage": usage.to_dict() if usage is not None else None, - **priced.fields(), **(cost or {}), "batch": _BATCH.get(), "attempt": _ATTEMPT.get(), - **({"error": error} if error is not None else {})}) - - -# The run of a judge step this task is in, set by its execute; the judge batch and output attempt a call belongs to. -_JUDGE_USAGE: ContextVar[Optional[JudgeUsage]] = ContextVar("judge_usage", default=None) -_BATCH: ContextVar[Optional[int]] = ContextVar("judge_batch", default=None) -_ATTEMPT: ContextVar[Optional[int]] = ContextVar("judge_attempt", default=None) - - -def judge_calls() -> list[dict[str, Any]]: - """The record of each model call the judge step running in this task has made so far (``JudgeUsage.calls``).""" - judge = _JUDGE_USAGE.get() - return list(judge.calls) if judge is not None else [] # The judge echoes each criterion's id back and results are matched by exact string. @@ -930,7 +865,7 @@ def verifier_settings(self, context: TaskStepContext) -> dict[str, Any]: settings["judge_a2a_agent_id"] = get_config().get_default_a2a_agent_id() recorded = (context.metadata.get("models") or {}).get(ModelRole.JUDGE.record_key) or {} settings["judge_model"] = recorded[self.id] if self.id in recorded else self._judge_model(context) - if (judge := _JUDGE_USAGE.get()) is not None and judge.sent is not None: + if (judge := judge_usage.current()) is not None and judge.sent is not None: for key in _JUDGE_SETTINGS: if key in settings or key in judge.sent or key in judge.not_sent: settings[key] = judge.sent.get(key) @@ -943,16 +878,13 @@ def verifier_settings(self, context: TaskStepContext) -> dict[str, Any]: def grade_fields(self, context: TaskStepContext) -> dict[str, Any]: """``judge_calls``, the record of each model call the run's judge made, when it made any.""" - judge = _JUDGE_USAGE.get() - return {"judge_calls": list(judge.calls)} if judge is not None and judge.calls else {} + calls = judge_usage.calls() + return {"judge_calls": calls} if calls else {} async def execute(self, context: TaskStepContext) -> TaskStepContext: """The base's, with this run's judge record scoped to it, so a grade reads only its own run's calls.""" - token = _JUDGE_USAGE.set(None) - try: + with judge_usage.scope(): return await super().execute(context) - finally: - _JUDGE_USAGE.reset(token) async def verify(self, context: TaskStepContext) -> Verification: verdict = self._gated(await self._judged(context)) @@ -1261,12 +1193,11 @@ def eval_prompt_for(batch: list[dict]) -> str: raise RuntimeError(f"Verifier '{self.verifier_id}': _criteria_batches gave {len(batches)} batches, but " f"output_format={self.output_format.value} is graded in one judge call.") concurrency = asyncio.Semaphore(batch_concurrency or self.DEFAULT_JUDGE_BATCH_CONCURRENCY) - usage = JudgeUsage(context, self.id) - _JUDGE_USAGE.set(usage) + usage = judge_usage.start(context, self.id) async def grade(batch: list[dict], number: Optional[int] = None ) -> tuple[list[dict], int, list[dict], Optional[str]]: - _BATCH.set(number) + judge_usage.batch(number) prompt = eval_prompt_for(batch) if len(batches) > 1: prompt += self._BATCH_NOTE.format( @@ -1684,7 +1615,7 @@ async def _prompt_llm_judge( }, } params, sent, not_sent = _direct_settings(route, self._run_values(context)) - judge = _JUDGE_USAGE.get() + judge = judge_usage.current() if judge is not None: judge.carried(sent, not_sent, route.endpoint_host) # Some endpoints reject json_schema with images. Fall back once on that exact @@ -1767,7 +1698,7 @@ async def _configure_judge_a2a( if not_sent: logger.warning("Verifier '%s': the judge agent doesn't take %s; it grades without them", self.verifier_id, sorted(not_sent)) - if (judge := _JUDGE_USAGE.get()) is not None: + if (judge := judge_usage.current()) is not None: judge.carried(sent, not_sent, endpoint_host) # What the judge agent took; one that doesn't accept a model grades on its own. context.record_model(ModelRole.JUDGE.record_key, self.id, config_payload.get("model")) @@ -1968,7 +1899,7 @@ async def _judge_directly(self, prompt: str, *, model: str, context: TaskStepCon else: data = await self._prompt_llm_judge(prompt, model=model, context=context) except BaseException as exc: - recorded = isinstance(exc, Exception) and _JUDGE_USAGE.get() is not None + recorded = isinstance(exc, Exception) and isinstance(usage, JudgeUsage) if not recorded and model_call.cut_off(exc): usage.cut_off_call(ModelRole.JUDGE, model=model, endpoint_host=None, reported_by=ReportedBy.PROVIDER) raise @@ -1982,7 +1913,7 @@ def _record_direct_call(usage: StepUsage, data: dict, *, model: str) -> None: read = Usage.from_model_response(data["usage"]) if data.get("usage") else None if data.get("reported_cost_usd") is not None: read = replace(read or Usage(), cost_usd=data["reported_cost_usd"]) - extra = ({"cost": {key: data[key] for key in _COST_KEYS if key in data}} + extra = ({"cost": {key: data[key] for key in Cost.KEYS if key in data}} if isinstance(usage, JudgeUsage) else {}) usage.call(ModelRole.JUDGE, read, model=data.get("model") or model, endpoint_host=data.get("endpoint_host"), reported_by=ReportedBy.PROVIDER, **extra) @@ -2031,7 +1962,7 @@ async def _run_judge_with_output_retries( ) for attempt in range(1, self.DEFAULT_MAX_RETRIES + 1): - _ATTEMPT.set(attempt) + judge_usage.attempt(attempt) if use_agent_judge: data = await self._invoke_judge_retrying_timeouts( discrepancy_log=discrepancy_log, diff --git a/src/agent_env/task_step/task_steps/verifiers/user_sim_judge.py b/src/agent_env/task_step/task_steps/verifiers/user_sim_judge.py index 3cff27910..de3e3e2c5 100644 --- a/src/agent_env/task_step/task_steps/verifiers/user_sim_judge.py +++ b/src/agent_env/task_step/task_steps/verifiers/user_sim_judge.py @@ -155,11 +155,8 @@ from agent_env.task_step.task_step import TaskStep, TaskStepDependency from agent_env.task_step.task_steps.verifiers import user_sim_judge_core as core from agent_env.task_step.task_steps.verifiers.judge_utils.judge_output_format import JudgeOutputFormat -from agent_env.task_step.task_steps.verifiers.rubrics_verifier import ( - RubricsVerdict, - RubricsVerifierTaskStep, - judge_calls, -) +from agent_env.task_step.task_steps.verifiers.judge_utils import judge_usage +from agent_env.task_step.task_steps.verifiers.rubrics_verifier import RubricsVerdict, RubricsVerifierTaskStep from agent_env.task_step.task_steps.verifiers.scoring import ScoreAggregator from agent_env.task_step.task_steps.verifiers.verifier import Verification @@ -390,7 +387,7 @@ def _finish(self, judged: RubricsVerdict, entry: dict, this: _ThisRun) -> Verifi error["not_failing"] = NOT_FAILING_UNCONFIRMED else: error["fails_task"] = True - answered = [call for call in judge_calls() if call["outcome"] == "answered"] + answered = [call for call in judge_usage.calls() if call["outcome"] == "answered"] output = {**judged.output, **entry, "user_sim_error": error, "calls": len(answered), "usage": _usage(answered), **_cost(answered)} if error["value"] == "unknown": diff --git a/src/agent_env/task_step/usage.py b/src/agent_env/task_step/usage.py index 0710d0b92..5199a3447 100644 --- a/src/agent_env/task_step/usage.py +++ b/src/agent_env/task_step/usage.py @@ -167,11 +167,7 @@ def call(self, role: ModelRole, usage: Optional[Usage], *, model: Optional[str], """One model call of ``role`` that isn't an agent's turn, as a judge's, written at once. The role starts at its first call, with the model and the endpoint host that call reached; ``reported_by`` says whose figure a call's ``cost_usd`` is, and the role keeps its first call's.""" - if role not in self._roles: - self._context.record_model_endpoint(role.value, self._step_id, model, endpoint_host) - self._roles[role] = RoleUsage(role.value, model, endpoint_host, reported_by=reported_by) - self._roles[role].add(usage) - self.entries() + self._add_call(role, usage, model, endpoint_host, reported_by) def cut_off(self, role: ModelRole) -> None: """A turn of ``role`` that was sent but never replied: cut off by a time limit, by a cancel, or by its agent no @@ -188,7 +184,15 @@ def cut_off_call(self, role: ModelRole, *, model: Optional[str], endpoint_host: """A model call of ``role`` that was sent but never answered, cut off by a time limit or a cancel: a call of unknown usage, marking the role's entry a lower bound as ``cut_off`` marks a turn's, recorded as ``call`` records one, so it starts the role when it's the first.""" - self.call(role, _unreported(), model=model, endpoint_host=endpoint_host, reported_by=reported_by) + self._add_call(role, _unreported(), model, endpoint_host, reported_by) + + def _add_call(self, role: ModelRole, usage: Optional[Usage], model: Optional[str], endpoint_host: Optional[str], + reported_by: ReportedBy) -> None: + if role not in self._roles: + self._context.record_model_endpoint(role.value, self._step_id, model, endpoint_host) + self._roles[role] = RoleUsage(role.value, model, endpoint_host, reported_by=reported_by) + self._roles[role].add(usage) + self.entries() def entries(self) -> Optional[list[UsageEntry]]: """The entries of the roles that ran turns, written to ``metadata["step_usage"]``; None, and nothing written, diff --git a/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_settings.py b/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_settings.py index f62242b49..767d5e08a 100644 --- a/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_settings.py +++ b/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_settings.py @@ -12,8 +12,8 @@ from agent_env.a2a_agent import A2AAgent, protocol from agent_env.task_step.context import TaskStepContext, VerifierNotPassingError -from agent_env.task_step.task_steps.verifiers import rubrics_verifier -from agent_env.task_step.task_steps.verifiers.rubrics_verifier import JudgeSettingRefused, JudgeUsage +from agent_env.task_step.task_steps.verifiers.judge_utils import judge_usage +from agent_env.task_step.task_steps.verifiers.rubrics_verifier import JudgeSettingRefused from tst.unit.task_step.verifiers.test_rubrics_verifier_golden import TWO, _binary, _context, _ids, _step from tst.util.config import install_model_config @@ -204,15 +204,11 @@ async def post(url, payload, headers=None): card = {"capabilities": {"extensions": [{"uri": A2AAgent.EXT_AGENT_CONFIG, "params": { "endpoint": "/ext/agent-config", "methods": {"set": {"request": {"supported": ["model"]}}}}}]}} context = TaskStepContext() - judge = JudgeUsage(context, "verify") - token = rubrics_verifier._JUDGE_USAGE.set(judge) - try: - with caplog.at_level(logging.WARNING): - await _step(use_agent_judge=True)._configure_judge_a2a( - judge_a2a_url="http://judge.test", judge_agent_card=card, model="m", judge_effort="high", - judge_max_thinking_tokens=None, context=context, headers={}, endpoint_host="gw.test") - finally: - rubrics_verifier._JUDGE_USAGE.reset(token) + with judge_usage.scope(), caplog.at_level(logging.WARNING): + judge = judge_usage.start(context, "verify") + await _step(use_agent_judge=True)._configure_judge_a2a( + judge_a2a_url="http://judge.test", judge_agent_card=card, model="m", judge_effort="high", + judge_max_thinking_tokens=None, context=context, headers={}, endpoint_host="gw.test") assert posted == [{"model": "m"}] assert (judge.sent, judge.not_sent, judge.endpoint_host) == ({}, {"effort": "high"}, "gw.test") From 6f669c956048a9d357096faaf22d30937d6db4d5 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 11:06:37 -0800 Subject: [PATCH 4/6] refactor(config): model_call's request names its keys by ModelParam Co-Authored-By: Claude Opus 5.5 --- src/agent_env/config/model_call.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/agent_env/config/model_call.py b/src/agent_env/config/model_call.py index 9b0a214ac..1b3e714eb 100644 --- a/src/agent_env/config/model_call.py +++ b/src/agent_env/config/model_call.py @@ -94,8 +94,8 @@ async def complete(route: ModelRoute, messages: list[dict], *, timeout: Optional takes.""" import litellm - request: dict[str, Any] = {"model": route.litellm_model, "messages": messages, "timeout": timeout, - **route.call.client_kwargs(), **(settings or {})} + request: dict[str, Any] = {ModelParam.MODEL: route.litellm_model, ModelParam.MESSAGES: messages, + ModelParam.TIMEOUT: timeout, **route.call.client_kwargs(), **(settings or {})} if response_format is not None: request[ModelParam.RESPONSE_FORMAT] = response_format response = await litellm.acompletion(**request) From fd479bf248b4b8aa07f712710674eb635b34a3f8 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 11:54:11 -0800 Subject: [PATCH 5/6] test(computers): the live-site browser tests load sites no bot challenge meets example.com, .org and .net are behind Cloudflare now, whose "Just a moment..." challenge meets CI's browsers, so the two tests that load them live failed on main and every branch. They load python.org, gnu.org and kernel.org beside wikipedia.org instead, none behind a challenge. Co-Authored-By: Claude Opus 5.5 --- tst/integration/computer/browser_clock_test.py | 4 ++-- tst/integration/computer/chromium_universe_test.py | 6 ++++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/tst/integration/computer/browser_clock_test.py b/tst/integration/computer/browser_clock_test.py index 0d88561ef..bcd836324 100644 --- a/tst/integration/computer/browser_clock_test.py +++ b/tst/integration/computer/browser_clock_test.py @@ -151,8 +151,8 @@ async def test_alone_the_browser_computer_keeps_real_time_and_its_live_sites_pas try: read = time.time() page = await _page_now(deployed) - loaded = await _load_all(deployed, {"https://example.com/": "Example Domain"}) - rows = [row for row in _egress_rows(deployed.sandbox_id) if row.get("host") == "example.com"] + loaded = await _load_all(deployed, {"https://www.python.org/": "Python"}) + rows = [row for row in _egress_rows(deployed.sandbox_id) if row.get("host") == "www.python.org"] finally: report = await teardown_run(context) diff --git a/tst/integration/computer/chromium_universe_test.py b/tst/integration/computer/chromium_universe_test.py index ee127de05..e55f6ce80 100644 --- a/tst/integration/computer/chromium_universe_test.py +++ b/tst/integration/computer/chromium_universe_test.py @@ -28,8 +28,10 @@ DAY = 86400 #: Live sites the browser hasn't visited, each with its page's title, opened in turn with the universe that many days #: from now: the last right after the jump back. -STOPS = [(-182, "https://example.com/", "Example Domain"), (730, "https://example.org/", "Example Domain"), - (6 * 365, "https://example.net/", "Example Domain"), (-182, "https://www.wikipedia.org/", "Wikipedia")] +#: None of them behind a bot challenge, as Cloudflare's "Just a moment..." meets CI's browsers at example.com now. +STOPS = [(-182, "https://www.python.org/", "Welcome to Python.org"), + (730, "https://www.gnu.org/", "The GNU Operating System and the Free Software Movement"), + (6 * 365, "https://www.kernel.org/", "The Linux Kernel Archives"), (-182, "https://www.wikipedia.org/", "Wikipedia")] #: How long a page may take to load before its tab counts as not loaded. LOAD_S = 45 POLICY = "/etc/opt/chrome_for_testing/policies/managed/agentenv-egress.json" From 798bdaab615046aa80f2fc0b8bd78542f39ce092 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 12:09:49 -0800 Subject: [PATCH 6/6] test(computers): the universe browser test's backward stops go 400 days back, before any live certificate Six months back was inside python.org's certificate, so the egress proxy spliced it instead of re-signing. A certificate valid today lives at most 398 days, so 400 days back is outside every live site's. Co-Authored-By: Claude Opus 5.5 --- tst/integration/computer/chromium_universe_test.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/tst/integration/computer/chromium_universe_test.py b/tst/integration/computer/chromium_universe_test.py index e55f6ce80..8537ed9a1 100644 --- a/tst/integration/computer/chromium_universe_test.py +++ b/tst/integration/computer/chromium_universe_test.py @@ -27,11 +27,12 @@ DAY = 86400 #: Live sites the browser hasn't visited, each with its page's title, opened in turn with the universe that many days -#: from now: the last right after the jump back. -#: None of them behind a bot challenge, as Cloudflare's "Just a moment..." meets CI's browsers at example.com now. -STOPS = [(-182, "https://www.python.org/", "Welcome to Python.org"), +#: from now: the last right after the jump back. None is behind a bot challenge, as Cloudflare's "Just a moment..." +#: meets CI's browsers at example.com now. Each date is outside any certificate valid today, whose life is at most 398 +#: days, so the egress proxy re-signs every site. +STOPS = [(-400, "https://www.python.org/", "Welcome to Python.org"), (730, "https://www.gnu.org/", "The GNU Operating System and the Free Software Movement"), - (6 * 365, "https://www.kernel.org/", "The Linux Kernel Archives"), (-182, "https://www.wikipedia.org/", "Wikipedia")] + (6 * 365, "https://www.kernel.org/", "The Linux Kernel Archives"), (-400, "https://www.wikipedia.org/", "Wikipedia")] #: How long a page may take to load before its tab counts as not loaded. LOAD_S = 45 POLICY = "/etc/opt/chrome_for_testing/policies/managed/agentenv-egress.json"