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.

9 changes: 4 additions & 5 deletions src/agent_env/bundle/plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
from agent_env.task_step.task_steps.deploy_agent import DeployAgentTaskStep
from agent_env.task_step.task_steps.install_agent import InstallAgentTaskStep
from agent_env.task_step.task_steps.load_artifact import LoadArtifactTaskStep
from agent_env.task_step.task_steps.prompt_agent import is_prompt_step, user_sim_agents
from agent_env.task_step.task_steps.prompt_agent import agent_name_of, solver_agents

from ._fs import fold, relative, with_article
from .authoring import AuthoringContext, entry_files, staged_build_context
Expand Down Expand Up @@ -1266,12 +1266,11 @@ def folder_files(bundle: Bundle, entry: BundleEntry) -> Mapping[str, Path]:

def solver_steps(steps: Any) -> tuple[str, ...]:
"""The ids of the steps in ``steps``, a task's config, that deploy or install an agent a step prompts as the agent
under test (``is_prompt_step``), and not as its user simulator: the solver's."""
prompts = [step for step in steps if isinstance(step, dict) and is_prompt_step(step)]
prompted = {step.get("agent_name") or TaskStep.DEFAULT_AGENT_NAME for step in prompts} - user_sim_agents(steps)
under test, and not as its user simulator: the solver's (``solver_agents``)."""
solver = solver_agents([step for step in steps if isinstance(step, dict)])
return tuple(step["id"] for step in steps if isinstance(step, dict) and isinstance(step.get("id"), str)
and step.get("type") in (DeployAgentTaskStep.type, InstallAgentTaskStep.type)
and (step.get("agent_name") or TaskStep.DEFAULT_AGENT_NAME) in prompted)
and agent_name_of(step) in solver)


def _leaves_an_agent_unset(task: ResolvedEntry) -> bool:
Expand Down
17 changes: 6 additions & 11 deletions src/agent_env/bundle/resolve.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
from agent_env.task_step.context import ENV_KEYED_METADATA, context_path, context_path_segments
from agent_env.task_step.registry import get_task_step_registry
from agent_env.task_step.task_step import TaskStep, attach_base_fields, dependencies
from agent_env.task_step.task_steps.prompt_agent import is_prompt_step, user_sim_agents
from agent_env.task_step.task_steps.prompt_agent import agent_name_of, solver_agents

from ._fs import fold, relative, show
from .authoring import AuthoringContext, default_dockerfile
Expand Down Expand Up @@ -133,16 +133,15 @@ def resolve_bundle(bundle: Bundle) -> ResolvedBundle:


def played_deploys(entry: ResolvedEntry) -> frozenset[str]:
"""The ``deploy_agent`` steps of a task's only agent under test, the one a step prompts as it and no step talks to
as its user (``user_sim_agents``), which a caller playing that agent itself (``EpisodeSpec``) stands in for; none
when the entry isn't a task, or prompts no agent or several."""
"""The ``deploy_agent`` steps of a task's only agent under test (``solver_agents``), which a caller playing that
agent itself (``EpisodeSpec``) stands in for; none when the entry isn't a task, or prompts no agent or several."""
if entry.entry.kind is not BundleKind.TASK:
return frozenset()
prompted = {_agent_name(step) for step in entry.config if is_prompt_step(step)} - user_sim_agents(entry.config)
if len(prompted) != 1:
solver = solver_agents(entry.config)
if len(solver) != 1:
return frozenset()
return frozenset(step.get("id") for step in entry.config
if step.get("type") == "deploy_agent" and _agent_name(step) in prompted)
if step.get("type") == "deploy_agent" and agent_name_of(step) in solver)


def without_played_agents(resolved: ResolvedBundle) -> ResolvedBundle:
Expand All @@ -158,10 +157,6 @@ def kept(entry: ResolvedEntry) -> ResolvedEntry:
return replace(resolved, entries=tuple(kept(entry) for entry in resolved.entries))


def _agent_name(step: dict) -> str:
return step.get("agent_name") or TaskStep.DEFAULT_AGENT_NAME


class _Skip(Exception):
"""An entry that can't be resolved; its problem is already recorded."""

Expand Down
18 changes: 18 additions & 0 deletions src/agent_env/task/lint.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,13 @@
from agent_env.task.task import Task, _ancestor_ids, _dependency_ids
from agent_env.task_step.registry import get_task_step_registry
from agent_env.task_step.task_step import StepRole, TaskStep, attach_base_fields
from agent_env.task_step.task_steps.prompt_agent import solver_agents
from agent_env.task_step.task_steps.verifiers.aggregate_verifiers import (
POOLED,
AggregateVerifiersTaskStep,
legacy_entry_writers,
)
from agent_env.task_step.task_steps.verifiers.rubrics_verifier import RubricsVerifierTaskStep
from agent_env.task_step.task_steps.verifiers.scoring import ScoreAggregator
from agent_env.task_step.task_steps.verifiers.verifier import VerifierTaskStep

Expand Down Expand Up @@ -59,6 +61,7 @@ def lint(task: Task, step_dicts: Sequence[Mapping[str, Any]] | None = None, *, c
*_step_warnings(task.steps),
*_headlines(task),
*_aggregate_sources(task.steps),
*_judge_as_solver(task.steps),
*_lopsided(task.steps),
*(_unpinned(task.steps) if unpinned else ()),
*_coverage(task),
Expand Down Expand Up @@ -274,6 +277,21 @@ def _named_sources(aggregate: AggregateVerifiersTaskStep, steps: Sequence[TaskSt
yield Finding(Severity.ERROR, "aggregate-source", f"{field} names {name!r}, {problem}", aggregate.id)


def judges_in_solver(steps: Sequence[TaskStep]) -> list[RubricsVerifierTaskStep]:
"""The agent judges that run in the solver's own agent: their ``agent_name`` names an agent a step prompts as the
agent under test (``solver_agents``), so the solver grades its own work."""
solver = solver_agents(steps)
return [step for step in steps if isinstance(step, RubricsVerifierTaskStep) and step.use_agent_judge
and isinstance(step.agent_name, str) and step.agent_name in solver]


def _judge_as_solver(steps: Sequence[TaskStep]) -> Iterator[Finding]:
for judge in judges_in_solver(steps):
yield Finding(Severity.ERROR, "judge-as-solver",
f"its judge runs in {judge.agent_name!r}, the agent under test, so the solver grades its own work; "
"leave agent_name unset for a judge agent of its own, or name another agent", judge.id)


def _lopsided(steps: Sequence[TaskStep]) -> Iterator[Finding]:
"""A pooled, weighted-average aggregate one of whose sources is under ``LOPSIDED_SHARE`` of its rows, so it barely
moves the score, counting only the sources whose rows their config says (``criterion_rows``). An aggregate of
Expand Down
25 changes: 20 additions & 5 deletions src/agent_env/task_step/task_steps/prompt_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -1536,9 +1536,24 @@ def is_prompt_step(step: Any) -> bool:

def user_sim_agents(steps: Any) -> set[str]:
"""The agents a task's prompting steps talk to as their user: an always_on step's ``user_sim``, a prompt_agent
step's ``user_agent_name`` (its default when unset). ``steps`` are steps or step dicts."""
def field(step: Any, name: str) -> Any:
return step.get(name) if isinstance(step, dict) else getattr(step, name, None)
step's ``user_agent_name`` (its default when unset). ``steps`` are steps or step dicts; a name that isn't a string
names no agent."""
return {name for step in steps if is_prompt_step(step)
if isinstance(name := _field(step, "user_sim") or _field(step, "user_agent_name")
or PromptAgentTaskStep.DEFAULT_USER_AGENT_NAME, str)}

return {field(step, "user_sim") or field(step, "user_agent_name") or PromptAgentTaskStep.DEFAULT_USER_AGENT_NAME
for step in steps if is_prompt_step(step)}

def solver_agents(steps: Any) -> set[str]:
"""The agents a task's prompting steps talk to as the agent under test, not as its user (``user_sim_agents``): the
solver's. ``steps`` are steps or step dicts; a name that isn't a string names no agent."""
prompted = {name for step in steps if is_prompt_step(step) if isinstance(name := agent_name_of(step), str)}
return prompted - user_sim_agents(steps)


def agent_name_of(step: Any) -> Any:
"""The agent ``step``, a step or a step dict, names: its ``agent_name``, else the default agent's name."""
return _field(step, "agent_name") or PromptAgentTaskStep.DEFAULT_AGENT_NAME


def _field(step: Any, name: str) -> Any:
return step.get(name) if isinstance(step, dict) else getattr(step, name, None)
12 changes: 5 additions & 7 deletions src/agent_env/training/harness.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,13 @@
from agent_env.bundle.run import planned_tasks, prepare_bundle, solver_params
from agent_env.store.routing import namespace_routing
from agent_env.openenv.reward import reward_of
from agent_env.task.lint import judges_in_solver
from agent_env.task.task import Task, recorded_scores
from agent_env.task.teardown import teardown_run
from agent_env.task_step.context import TaskStepContext, sandbox_overrides
from agent_env.task_step.task_steps.agent.user_sim_common import opening_parts, opening_text
from agent_env.task_step.task_steps.deploy_agent import DeployAgentTaskStep
from agent_env.task_step.task_steps.prompt_agent import is_prompt_step, user_sim_agents
from agent_env.task_step.task_steps.verifiers.rubrics_verifier import RubricsVerifierTaskStep
from agent_env.task_step.task_steps.prompt_agent import agent_name_of, is_prompt_step, solver_agents
from agent_env.training._openenv import on_session_loop

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -210,9 +210,7 @@ def _untrainable(config: list[dict[str, Any]]) -> str | None:
deploys = [step for step in steps if step.id in solver]
if not deploys or not all(isinstance(step, DeployAgentTaskStep) for step in deploys):
return "training needs the agent a step prompts deployed by a deploy_agent step"
agents = {step.agent_name for step in deploys}
if any(isinstance(step, RubricsVerifierTaskStep) and step.use_agent_judge and step.agent_name in agents
for step in steps):
if judges_in_solver(steps):
return "its rubric judge is its solver, whose grading would be trained on"
return None

Expand Down Expand Up @@ -240,9 +238,9 @@ def _first_prompt(task: Task) -> str:
names (an always_on step's ``user_sim``, a prompt_agent step's ``user_agent_name``), as it was written (its
text, for an opening with files). A step that prompts an agent another step talks to as its user (the user sim,
say a briefing) isn't the agent under test's."""
users = user_sim_agents(task.steps)
solver = solver_agents(task.steps)
step = next((each for each in task.steps
if is_prompt_step(each) and getattr(each, "agent_name", None) not in users), None)
if is_prompt_step(each) and agent_name_of(each) in solver), None)
if step is None:
return ""
if getattr(step, "prompt", None):
Expand Down
53 changes: 53 additions & 0 deletions tst/unit/task/lint_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,46 @@ def test_sources_given_as_objects_are_a_config_error_not_a_crash(sources):
assert ("error", "step-config", f"step 'final': sources must be a list of step ids, not {sources!r}") in found


SOLVER = {"id": "solver", "type": "deploy_agent", "agent_name": "default-agent"}
JUDGE_AGENT = {"id": "judge-agent", "type": "deploy_agent", "agent_name": "judge"}
ASK = {"id": "ask", "type": "prompt_agent", "prompt": "Help Linda.", "prompt_id": "ask", "user_agent_name": "linda"}
VERIFY = {"id": "verify", "type": "rubrics_verifier", "prompt_id": "ask", "verifier_id": "verify",
"criteria": [{"criterion": "helps"}]}


def _judging(**fields) -> list[tuple[str, str, str]]:
found = _found(_task(SOLVER, JUDGE_AGENT, ASK, {**VERIFY, **fields}, headline_verifiers=["verify"]))
return [finding for finding in found if finding[1] == "judge-as-solver"]


def test_an_agent_judge_in_the_agent_under_test_is_an_error():
assert _judging(agent_name="default-agent") == [(
"error", "judge-as-solver", "step 'verify': its judge runs in 'default-agent', the agent under test, so the "
"solver grades its own work; leave agent_name unset for a judge agent of its own, "
"or name another agent")]


@pytest.mark.parametrize("fields", [
{},
{"agent_name": "judge"},
{"agent_name": "linda"},
{"agent_name": "default-agent", "use_agent_judge": False},
])
def test_a_judge_of_its_own_in_the_user_simulator_or_calling_its_model_directly_is_not_the_solver(fields):
assert _judging(**fields) == []


@pytest.mark.parametrize(("ask", "judge"), [
({}, {"agent_name": ["default-agent"]}),
({"agent_name": ["default-agent"]}, {"agent_name": "default-agent"}),
({"user_agent_name": {}}, {"agent_name": {}}),
])
def test_an_agent_name_that_isnt_a_string_names_no_agent_and_lint_still_answers(ask, judge):
task = _task(SOLVER, {**ASK, **ask}, {**VERIFY, **judge}, headline_verifiers=["verify"])

assert not [finding for finding in lint(task) if finding.rule == "judge-as-solver"]


def test_with_no_headline_an_aggregate_naming_every_other_verifier_by_step_id_is_the_one_to_name():
found = _found(_task(BOX, TESTS, MORE, _combined(combine="weighted_mean", sources=["tests"], gates=["more"])))

Expand Down Expand Up @@ -573,6 +613,19 @@ def test_a_run_of_a_bundle_with_a_lint_error_is_refused_unless_it_skips_lint_but
assert "--skip-lint" not in config.output


def test_a_run_of_a_bundle_whose_judge_is_its_solver_is_refused_unless_it_skips_lint(bundle_dir):
_write(bundle_dir, "j", {"headline_verifiers": ["verify"],
"steps": [SOLVER, ASK, {**VERIFY, "agent_name": "default-agent"}]})

refused = CliRunner().invoke(cli, ["run", str(bundle_dir), "--task", "j", "--dry-run"])
skipped = CliRunner().invoke(cli, ["run", str(bundle_dir), "--task", "j", "--dry-run", "--skip-lint"])

assert refused.exit_code != 0
assert "tasks/j.json: step 'verify': its judge runs in 'default-agent', the agent under test" in refused.output
assert skipped.exit_code == 0, skipped.output
assert "Would run:\n tasks/j.json v1\n" in skipped.output


def test_bundle_register_with_skip_lint_registers_a_task_lint_refuses_saying_why_once(bundle_dir):
_write(bundle_dir, "t", {"headline_verifiers": ["box"], "steps": [BOX, TESTS]})

Expand Down
31 changes: 30 additions & 1 deletion tst/unit/task_step/verifiers/test_rubrics_family_grades.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from agent_env.config import get_config
from agent_env.task_step.context import TaskStepContext, VerifierNotPassingError
from agent_env.task_step.task_steps.verifiers.always_on_agent_verifier import AlwaysOnAgentVerifier
from agent_env.task_step.task_steps.verifiers.rubrics_verifier import RubricsVerifierTaskStep
from agent_env.task_step.task_steps.verifiers.rubrics_verifier import JudgeTimeoutError, RubricsVerifierTaskStep
from agent_env.task_step.task_steps.verifiers.user_sim_judge import UserSimJudge
from tst.unit.task_step.verifiers.test_rubrics_verifier_golden import (
CASES,
Expand Down Expand Up @@ -178,6 +178,35 @@ def test_the_user_sim_judges_settings_leave_out_what_its_judge_never_uses():
assert settings["overridden"] == ["judge_batch_size", "judge_batch_concurrency", "judge_model"]


@pytest.mark.asyncio
async def test_a_direct_judge_out_of_retries_writes_a_failed_grade():
step, context = CASES["a_judge_that_cannot_be_reached"]()

with pytest.raises(RuntimeError, match="LLM judge failed after 3 attempts"):
await step.execute(context)

grade = context.metadata["grades"][step.id]
assert (grade["verifier_status"], grade["score"], grade["passed"]) == ("failed", None, False)
assert grade["verifier_error_reasoning"] == "RuntimeError: LLM judge failed after 3 attempts"


@pytest.mark.asyncio
async def test_an_agent_judge_out_of_timeout_retries_writes_a_failed_grade():
step, context = CASES["an_agent_judge_timing_out_once"]()

async def times_out(**_):
raise JudgeTimeoutError("ran out", "mem://judge/timed-out.json")

step._invoke_judge_a2a = times_out

with pytest.raises(JudgeTimeoutError):
await step.execute(context)

grade = context.metadata["grades"][step.id]
assert (grade["verifier_status"], grade["score"]) == ("failed", None)
assert grade["verifier_error_reasoning"].startswith("JudgeTimeoutError: ran out")


@pytest.mark.asyncio
async def test_an_always_on_verifier_refusing_a_runs_overrides_fails_its_grade_and_writes_no_entry():
step = AlwaysOnAgentVerifier(id="judge", version=1, criteria=_criteria(1), prompt_id="ask", use_agent_judge=False,
Expand Down
Loading