Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md

Large diffs are not rendered by default.

18 changes: 18 additions & 0 deletions src/agent_env/config/model_call.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

from agentenv_protocol.a2a_agent import Usage

from agent_env.config.describe import is_secret_key, mask_value
from agent_env.config.errors import ConfigError
from agent_env.config.model import ModelCallConfig, ModelParam, api_root, endpoint_host, no_key_for
from agent_env.config.model_pricing import Cost, ReportedBy, Tokens, litellm_prices, price
Expand Down Expand Up @@ -108,6 +109,23 @@ 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 sent_params(route: ModelRoute, settings: Optional[dict[str, Any]] = None) -> dict[str, Any]:
"""The params a call by ``route`` with ``settings`` sends (``complete``), the config's ``[model.params]`` with
``settings`` over them, as a record of the call keeps them: a value under a secret-shaped key (``config show``'s
rule, which takes in ``extra_headers``) is left out, through tables and lists, unless it's a number, as
``max_tokens`` is, and a URL's userinfo is masked."""
return _without_secrets({**route.call.params, **(settings or {})})


def _without_secrets(value: Any) -> Any:
if isinstance(value, dict):
return {key: _without_secrets(item) for key, item in value.items()
if not is_secret_key(key) or isinstance(item, (int, float))}
if isinstance(value, list):
return [_without_secrets(item) for item in value]
return mask_value("", value)


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."""
Expand Down
3 changes: 2 additions & 1 deletion src/agent_env/task_step/task_steps/add_skills.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from agent_env.entity.refs import EntityRef
from agent_env.entity.scopes import FieldScope
from agent_env.task_step.task_step import TaskStep, TaskStepDependency
from agent_env.task_step.task_steps.load_artifact import LOADED_FILE_UNIVERSES

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -278,7 +279,7 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext:

loaded_universes_by_id: dict[str, dict] = {
e["id"]: e
for e in (context.metadata.get("loaded_file_artifact_universes") or [])
for e in (context.metadata.get(LOADED_FILE_UNIVERSES) or [])
if e.get("agent_name") == self.agent_name
}
for fau_id in self.file_artifact_universe_ids:
Expand Down
24 changes: 18 additions & 6 deletions src/agent_env/task_step/task_steps/load_artifact.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import shlex
import uuid
from dataclasses import dataclass
from typing import Callable, ClassVar, Optional
from typing import Any, Callable, ClassVar, Optional
from urllib.parse import unquote, urlparse

from agent_env.artifact import Artifact, EnvironmentArtifact, EnvironmentUniverseArtifact
Expand All @@ -27,6 +27,18 @@
from agent_env.task_step.task_steps.deploy_agent import bound_deployment
from agent_env.utils.paths import validate_relative_filename

#: What each load records in ``context.metadata``, one entry per load naming its target (``agent_name``, ``env_id``, ...).
LOADED_FILE_UNIVERSES = "loaded_file_artifact_universes"
LOADED_ENVIRONMENT_ARTIFACTS = "loaded_environment_artifacts"
LOADED_URLS = "loaded_urls"


def loads_into(context: TaskStepContext, agent_name: str) -> list[dict[str, Any]]:
"""Each load the run recorded into ``agent_name``'s sandbox, as recorded, with the key it's recorded under as
``record``."""
return [{"record": key, **entry} for key in (LOADED_FILE_UNIVERSES, LOADED_ENVIRONMENT_ARTIFACTS, LOADED_URLS)
for entry in context.metadata.get(key) or [] if entry.get("agent_name") == agent_name]

logger = logging.getLogger(__name__)

# Where producer steps record what they made, keyed by their own step id. Resolving
Expand Down Expand Up @@ -487,7 +499,7 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext:
files = await _load_universe_onto_vm(target_sandbox, artifact, destination)
else:
files = await _load_universe_into_sandbox_container(target_sandbox, artifact, destination)
context.metadata.setdefault("loaded_file_artifact_universes", []).append({
context.metadata.setdefault(LOADED_FILE_UNIVERSES, []).append({
"id": artifact.id,
"version": artifact.version,
"artifact_type": artifact.type,
Expand All @@ -510,7 +522,7 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext:
env_obj = Env.get(deployed.env_id, deployed.env_version)
env = await type(env_obj).from_deployed_env(deployed)
result = await env.load_file_artifact_universe(artifact, destination_path=destination_path)
context.metadata.setdefault("loaded_file_artifact_universes", []).append({
context.metadata.setdefault(LOADED_FILE_UNIVERSES, []).append({
"id": artifact.id,
"version": artifact.version,
"artifact_type": artifact.type,
Expand All @@ -527,7 +539,7 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext:
destination = (destination_path or "/tmp/file_artifacts").rstrip("/") or "/"
files = await A2AAgent.load_file_artifact_universe(
deployed_agent, artifact, destination, **_agent_files(agent))
context.metadata.setdefault("loaded_file_artifact_universes", []).append({
context.metadata.setdefault(LOADED_FILE_UNIVERSES, []).append({
"id": artifact.id,
"version": artifact.version,
"artifact_type": artifact.type,
Expand Down Expand Up @@ -574,7 +586,7 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext:
files = await _stage_environment_payload_into_container(
sandbox, container, artifact, destination,
)
context.metadata.setdefault("loaded_environment_artifacts", []).append({
context.metadata.setdefault(LOADED_ENVIRONMENT_ARTIFACTS, []).append({
"id": artifact.id,
"version": artifact.version,
"service_name": artifact.environment_name,
Expand Down Expand Up @@ -671,7 +683,7 @@ async def _load_one(url: str, filename: str) -> None:
logger.info(f"Loaded URL into {target_desc}: {url} -> {dest}")

await asyncio.gather(*(_load_one(u, f) for u, f in downloads))
context.metadata.setdefault("loaded_urls", []).append({
context.metadata.setdefault(LOADED_URLS, []).append({
"step_id": self.id,
"agent_name": None if self.sandbox_name is not None else self.agent_name,
"sandbox_name": self.sandbox_name,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
TurnEvents,
turn_events,
)
from agent_env.task_step.task_steps.verifiers.judge_utils import judge_usage
from agent_env.task_step.task_steps.verifiers.rubrics_verifier import (
RUN_CONTEXT_PARTS,
RubricsVerdict,
Expand Down Expand Up @@ -405,6 +406,10 @@ async def stage_trajectory(self, context: TaskStepContext, prompt_response: Prom
path = f"{STAGING_DIR}/{uuid.uuid4().hex[:12]}"
await self._write_files(sandbox, {f"{path}/{name}": text for name, text in staged.files.items()}, container)
self._log_staging(staged)
if (judge := judge_usage.current()) is not None:
# Its turns carry no labels: each trajectory's format is the one its shape reads as.
judge.read([{"format": fmt, "trajectories": count, "guessed": True}
for fmt, count in (staged.record.get("formats") or {}).items()])
return StagedTrajectory(path=path, prompt_note=_files_note(path, staged, context_loss=_CONTEXT_LOSS_RUN.get()),
record=staged.record)

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
"""What a judge was sent, stored by its sha256 under ``judge-inputs/`` in the object store, so a retried request's input
or a file another run staged is stored once and a reader checks it against the key it's stored under. A judge run's
uploads run in the background, off its judging's path (``Uploads``); its record waits for them once, before its grade is
written (``JudgeUsage.settle``), when an upload that failed or hadn't finished, or a store that couldn't be had, is marked
``input_error``, which never fails the grade."""

from __future__ import annotations

import asyncio
import functools
import hashlib
import json
import logging
from concurrent.futures import ThreadPoolExecutor
from typing import Any, Optional

from agent_env.config import get_config

logger = logging.getLogger(__name__)

INPUTS_PREFIX = "judge-inputs"
#: How many judge uploads run at once in the process, and how long a grade waits for its run's still running.
UPLOAD_CONCURRENCY = 16
SETTLE_SECONDS = 120.0
#: The process's judge uploads run on threads of their own, not the event loop's default pool, so a slow store holds up
#: only other judge uploads.
_POOL = ThreadPoolExecutor(max_workers=UPLOAD_CONCURRENCY, thread_name_prefix="judge-input")


class Uploads:
"""A judge run's uploads: each distinct body put once, in the background."""

def __init__(self) -> None:
self._tasks: dict[str, asyncio.Future] = {}
self._late: set[str] = set()

def put(self, data: bytes, content_type: str, digest: Optional[str] = None) -> dict[str, Any]:
"""``data`` stored under ``judge-inputs/<sha256>``, in the background and once however often the run sends it:
its reference (``object_url``, ``bytes``, ``sha256``) at once; without ``object_url`` when the store can't be
had, which ``failed`` then says."""
digest = digest or hashlib.sha256(data).hexdigest()
try:
config = get_config()
store, key = config.get_object_store(), f"{config.get_artifact_key_prefix()}{INPUTS_PREFIX}/{digest}"
url = store.object_url(key)
except Exception as exc:
self._tasks.setdefault(digest, _failed_with(exc))
return {"bytes": len(data), "sha256": digest}
if digest not in self._tasks:
task = asyncio.ensure_future(asyncio.get_running_loop().run_in_executor(
_POOL, functools.partial(_put_once, store, key, data, content_type)))
task.add_done_callback(_logged)
self._tasks[digest] = task
return {"object_url": url, "bytes": len(data), "sha256": digest}

async def put_json(self, body: Any) -> dict[str, Any]:
"""``body`` as JSON (``put``), encoded and hashed off the event loop, since a call's input may be tens of MB."""
data, digest = await asyncio.to_thread(_encoded, body)
return self.put(data, "application/json", digest)

@staticmethod
def deadline() -> float:
"""When a run that settles now stops waiting for its uploads."""
return asyncio.get_running_loop().time() + SETTLE_SECONDS

@staticmethod
def left(deadline: float) -> float:
"""The seconds left until ``deadline``, none once it's passed."""
return max(0.0, deadline - asyncio.get_running_loop().time())

async def wait(self, deadline: float) -> None:
"""Waits for the uploads still running until ``deadline``, then cancels those that haven't finished."""
pending = {digest: task for digest, task in self._tasks.items() if not task.done()}
if pending:
await asyncio.wait(pending.values(), timeout=self.left(deadline))
for digest, task in pending.items():
if not task.done():
task.cancel()
self._late.add(digest)

def failed(self, digest: Optional[str]) -> Optional[str]:
"""Why the upload of ``digest`` didn't store it, once ``wait`` has returned; None when it did, or the run
uploaded no such thing."""
task = self._tasks.get(digest) if digest else None
if task is None:
return None
if digest in self._late:
return f"TimeoutError: still uploading after {SETTLE_SECONDS:.0f}s"
if task.cancelled():
return "CancelledError: the upload was cancelled"
exc = task.exception()
return f"{type(exc).__name__}: {exc}"[:300] if exc is not None else None


class StagingRecorder:
"""A judge's sandbox, every file written into it kept in its run's manifest (``staged``): a file written as text
stored by its sha256 too (``Uploads.put``), one copied from a stored object named by that object's URL."""

def __init__(self, sandbox: Any, staged: list[dict[str, Any]], uploads: Uploads) -> None:
self._sandbox, self._staged, self._uploads = sandbox, staged, uploads

def __getattr__(self, name: str) -> Any:
return getattr(self._sandbox, name)

async def write_file_from_text(self, text: str, path: str, **kwargs: Any) -> Any:
written = await self._sandbox.write_file_from_text(text, path, **kwargs)
self._staged.append({"path": path, **self._uploads.put(text.encode(), "text/plain; charset=utf-8")})
return written

async def write_file_from_object(self, object_url: str, path: str, **kwargs: Any) -> Any:
written = await self._sandbox.write_file_from_object(object_url, path, **kwargs)
self._staged.append({"path": path, "object_url": object_url})
return written


def _encoded(body: Any) -> tuple[bytes, str]:
data = json.dumps(body, ensure_ascii=False, sort_keys=True).encode()
return data, hashlib.sha256(data).hexdigest()


def _put_once(store: Any, key: str, data: bytes, content_type: str) -> None:
if not store.exists(key):
store.put(key, data, content_type=content_type, allow_overwrite=True)


def _logged(task: asyncio.Future) -> None:
if not task.cancelled() and (exc := task.exception()) is not None:
logger.warning("a judge's input wasn't stored: %s: %s", type(exc).__name__, exc)


def _failed_with(exc: Exception) -> asyncio.Future:
failed = asyncio.get_running_loop().create_future()
failed.set_exception(exc)
_logged(failed)
return failed
Loading
Loading