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
11 changes: 11 additions & 0 deletions src/agent_env/config/model_call.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from __future__ import annotations

import asyncio
import contextlib
import io
import math
Expand Down Expand Up @@ -105,6 +106,16 @@ 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 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
on its own and then answered (the OpenAI SDK's ``max_retries``) never reaches the caller, so it isn't seen."""
import litellm

return isinstance(exc, asyncio.CancelledError) or any(
isinstance(e, litellm.Timeout) for e in (exc, exc.__cause__))


def setup_errors() -> tuple[type[BaseException], ...]:
"""What a call raises when it can't work as set up, as opposed to a flaky failure: agent-env's ConfigError (no key,
missing config) and LiteLLM's AuthenticationError, PermissionDeniedError, NotFoundError (an unknown model),
Expand Down
54 changes: 37 additions & 17 deletions src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -1484,16 +1484,23 @@ async def _invoke_judge_a2a(
usage: StepUsage,
) -> dict:
"""Send one evaluation prompt to an A2A judge and return its response. The turn's reported usage goes into
``usage`` as soon as the judge replies, a failed reply's too."""
``usage`` as soon as the judge replies, a failed reply's too; a turn cut off waiting for the reply (a time
limit, a cancel, a judge that stopped answering) goes in as a call of unknown usage."""
from agent_env.a2a_agent import protocol

task_id, _ = await protocol.send_a2a_message(
judge_a2a_url,
parts=[{"kind": "text", "text": eval_prompt}],
message_id=uuid.uuid4().hex,
context_id=None,
timeout_seconds=self.judge_timeout_seconds,
)
host = getattr(judge_agent, "model_endpoint_host", None)
try:
task_id, _ = await protocol.send_a2a_message(
judge_a2a_url,
parts=[{"kind": "text", "text": eval_prompt}],
message_id=uuid.uuid4().hex,
context_id=None,
timeout_seconds=self.judge_timeout_seconds,
)
except (TimeoutError, asyncio.CancelledError):
# The judge may have taken the message before its task id came back; with no id, it can't be cancelled.
usage.cut_off_call(ModelRole.JUDGE, model=model, endpoint_host=host)
raise
try:
result = await protocol.poll_a2a_task(
judge_a2a_url,
Expand All @@ -1503,20 +1510,22 @@ async def _invoke_judge_a2a(
sandbox_id=getattr(judge_agent, "sandbox_id", None),
)
except asyncio.CancelledError:
usage.cut_off_call(ModelRole.JUDGE, model=model, endpoint_host=host)
Comment thread
earakely-scale marked this conversation as resolved.
Resolved
# A sibling batch failed: stop this judge too, or it keeps working on a reused judge sandbox.
await asyncio.shield(protocol.cancel_a2a_task(judge_a2a_url, task_id))
raise
except protocol.AgentUnreachableError:
usage.cut_off_call(ModelRole.JUDGE, model=model, endpoint_host=host)
raise
except TimeoutError as e:
usage.cut_off_call(ModelRole.JUDGE, model=model, endpoint_host=host)
if self.judge_timeout_retries is None:
raise
raise await self._judge_timed_out(str(e), judge_a2a_url, judge_agent_card, task_id, judge_agent) from e
state = result["status"]["state"]
status_msg = (result.get("status") or {}).get("message") or {}
tr = protocol.TerminalResponse.from_message(status_msg)
usage.call(ModelRole.JUDGE, tr.usage, model=model,
endpoint_host=getattr(judge_agent, "model_endpoint_host", None))
usage.call(ModelRole.JUDGE, tr.usage, model=model, endpoint_host=host)
if state == "failed":
sandbox_id = getattr(judge_agent, "sandbox_id", None)
logger.error(
Expand Down Expand Up @@ -1648,6 +1657,22 @@ async def _fetch_judge_trajectory(
)
return None

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."""
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):
usage.cut_off_call(ModelRole.JUDGE, model=model, endpoint_host=None, reported_by=ReportedBy.PROVIDER)
raise
self._record_direct_call(usage, data, model=model)
return data

@staticmethod
def _record_direct_call(usage: StepUsage, data: dict, *, model: str) -> None:
"""One direct judge call's usage in the step's ``judge`` entry, as the response carried it, the endpoint's
Expand Down Expand Up @@ -1711,14 +1736,9 @@ async def _run_judge_with_output_retries(
model=agent_model,
usage=usage,
)
elif 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)
if not use_agent_judge:
self._record_direct_call(usage, data, model=model)
data = await self._judge_directly(prompt, model=model, context=context, image_blocks=image_blocks,
usage=usage)

logger.info(f"Judge response: {data['response'][:200]}...")
judge_trajectory_url = data.get("trajectory_object_url")
Expand Down
14 changes: 13 additions & 1 deletion src/agent_env/task_step/usage.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,11 @@ def _reported(self, summed: Optional[float]) -> Optional[float]:
return summed


def _unreported() -> Usage:
"""A turn or call whose usage never came back."""
return Usage(provider_details={"unreported": True})


def _unreported_calls(usage: Usage) -> int:
"""The calls a turn's usage says reported none, as the shipped agents put it in ``provider_details``."""
value = usage.provider_details.get("unreported_calls")
Expand Down Expand Up @@ -175,9 +180,16 @@ def cut_off(self, role: ModelRole) -> None:
started, a human peer's, is skipped."""
usage = self._roles.get(role)
if usage is not None:
usage.add(Usage(provider_details={"unreported": True}))
usage.add(_unreported())
self.entries()

def cut_off_call(self, role: ModelRole, *, model: Optional[str], endpoint_host: Optional[str],
reported_by: ReportedBy = ReportedBy.HARNESS) -> None:
"""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)

def entries(self) -> Optional[list[UsageEntry]]:
"""The entries of the roles that ran turns, written to ``metadata["step_usage"]``; None, and nothing written,
when none did."""
Expand Down
11 changes: 11 additions & 0 deletions tst/unit/config/test_model_call.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from __future__ import annotations

import asyncio
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
Expand Down Expand Up @@ -227,3 +228,13 @@ def test_setup_errors_are_the_ones_no_retry_fixes():

assert ConfigError in setup and litellm.AuthenticationError in setup and litellm.BudgetExceededError in setup
assert not issubclass(litellm.Timeout, setup) and not issubclass(litellm.RateLimitError, setup)


def test_a_call_is_cut_off_by_a_cancel_or_a_timeout_even_one_a_retry_gave_up_on():
timeout = litellm.Timeout("timed out", model="gpt-4o-mini", llm_provider="openai")
gave_up = RuntimeError("judge failed after 3 attempts")
gave_up.__cause__ = timeout
refused = litellm.RateLimitError("slow down", model="gpt-4o-mini", llm_provider="openai")

assert all(model_call.cut_off(e) for e in (timeout, gave_up, asyncio.CancelledError()))
assert not any(model_call.cut_off(e) for e in (refused, ValueError("bad answer")))
14 changes: 14 additions & 0 deletions tst/unit/task_step/usage_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,3 +219,17 @@ def test_an_endpoint_that_billed_only_some_calls_has_the_map_price_them_all(monk
[entry] = context.metadata["step_usage"]["grade"]
assert (entry["cost_status"], entry["cost_usd"]) == ("priced", pytest.approx(0.42))


def test_a_judges_call_cut_off_before_any_answered_starts_its_role_as_a_lower_bound(monkeypatch):
monkeypatch.setattr(usage_module, "litellm_prices", lambda: PRICES)
context = TaskStepContext()
usage = StepUsage(context, "grade")
usage.cut_off_call(ModelRole.JUDGE, model="gpt-4o-mini", endpoint_host="proxy:4000", reported_by=ReportedBy.PROVIDER)
[entry] = context.metadata["step_usage"]["grade"]
assert (entry["role"], entry["turns"], entry["input_tokens"], entry["cost_status"]) == ("judge", 1, None, "unpriced")
usage.call(ModelRole.JUDGE, Usage(input_tokens=1_000_000, output_tokens=100_000, input_includes_cache=True),
model="gpt-4o-mini", endpoint_host="proxy:4000")
[entry] = context.metadata["step_usage"]["grade"]
assert (entry["turns"], entry["partial"], entry["cost_status"]) == (2, True, "priced")
assert entry["cost_usd"] == pytest.approx(0.21)

151 changes: 151 additions & 0 deletions tst/unit/task_step/verifiers/test_rubrics_verifier_judge_usage.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,22 @@

from __future__ import annotations

import asyncio
import json
from types import SimpleNamespace

import litellm
import pytest

from agent_env.a2a_agent import A2AAgent, protocol
from agent_env.config import model_call
from agent_env.config.model import ModelRole
from agent_env.config.model_pricing import PriceTable, ReportedBy, price
from agent_env.task_step.context import PromptResponse, TaskStepContext
from agent_env.task_step.task_steps.verifiers import rubrics_verifier
from agent_env.task_step.task_steps.verifiers.rubrics_verifier import RubricsVerifierTaskStep
from agent_env.task_step.usage import StepUsage
from tst.util.config import install_model_config

CRITERIA = [{"id": f"c{i}", "title": f"Criterion {i}"} for i in range(1, 8)]

Expand Down Expand Up @@ -171,3 +176,149 @@ def test_a_call_with_no_usage_is_a_turn_with_no_counts():
[entry] = context.metadata["step_usage"]["verify"]
assert (entry["turns"], entry["input_tokens"], entry["partial"]) == (2, 10, True)
assert entry["role"] == ModelRole.JUDGE.value


@pytest.mark.asyncio
async def test_an_agent_judge_turn_that_runs_out_of_time_is_a_call_of_unknown_usage(monkeypatch):
verifier = _agent_judge(monkeypatch, "completed", "", {})

async def times_out(url, task_id, **kwargs):
raise TimeoutError("the judge ran out of time")

monkeypatch.setattr(protocol, "poll_a2a_task", times_out)
context = TaskStepContext()

with pytest.raises(TimeoutError):
await _judge_once(verifier, context)

[entry] = context.metadata["step_usage"]["verify"]
assert (entry["model"], entry["turns"], entry["input_tokens"], entry["partial"]) == (
"claude-haiku-4-5", 1, None, True)


@pytest.mark.asyncio
async def test_a_cancelled_agent_judge_turn_is_a_call_of_unknown_usage(monkeypatch):
verifier = _agent_judge(monkeypatch, "completed", "", {})
polling = asyncio.Event()

async def waits(url, task_id, **kwargs):
polling.set()
await asyncio.sleep(3600)

async def cancel(url, task_id):
return None

monkeypatch.setattr(protocol, "poll_a2a_task", waits)
monkeypatch.setattr(protocol, "cancel_a2a_task", cancel)
context = TaskStepContext()
judging = asyncio.create_task(_judge_once(verifier, context))
await polling.wait()

judging.cancel()
with pytest.raises(asyncio.CancelledError):
await judging

[entry] = context.metadata["step_usage"]["verify"]
assert (entry["turns"], entry["partial"]) == (1, True)


@pytest.mark.asyncio
async def test_an_agent_judge_cancelled_while_its_message_is_sent_is_a_call_of_unknown_usage(monkeypatch):
verifier = _agent_judge(monkeypatch, "completed", "", {})
sending = asyncio.Event()

async def waits(url, **kwargs):
sending.set()
await asyncio.sleep(3600)

monkeypatch.setattr(protocol, "send_a2a_message", waits)
context = TaskStepContext()
judging = asyncio.create_task(_judge_once(verifier, context))
await sending.wait()

judging.cancel()
with pytest.raises(asyncio.CancelledError):
await judging

[entry] = context.metadata["step_usage"]["verify"]
assert (entry["turns"], entry["partial"]) == (1, True)


_ANSWER = json.dumps({"results": [{"id": "c1", "score": 1.0, "justification": "Checked record c1 with the sheet tool"}]})


def _timeout() -> litellm.Timeout:
return litellm.Timeout("timed out", model="gpt-4o-mini", llm_provider="openai")


def _completes(monkeypatch, outcomes: list) -> None:
"""The direct judge's model calls answered, one by one, by ``outcomes``: an exception raises, a string answers
with 100 prompt and 5 completion tokens."""
install_model_config(monkeypatch, base_url="http://proxy.example:4000", api_key="configured-key")

async def complete(route, messages, **kwargs):
outcome = outcomes.pop(0)
if isinstance(outcome, BaseException):
raise outcome
return model_call.ModelReply(outcome, "gpt-4o-mini", "proxy.example:4000",
{"prompt_tokens": 100, "completion_tokens": 5},
price(None, None, model=None, prices=PriceTable(), reported_by=ReportedBy.PROVIDER))

monkeypatch.setattr(model_call, "complete", complete)


async def _direct_once(verifier: RubricsVerifierTaskStep, context: TaskStepContext) -> None:
await verifier._run_judge_with_output_retries(
eval_prompt="grade it", criteria=CRITERIA[:1], context=context, model="gpt-4o-mini", judge_a2a_url=None,
judge_agent_card={}, judge_agent=None, judge_effort=None, judge_max_thinking_tokens=None,
use_agent_judge=False, usage=StepUsage(context, "verify"))


@pytest.mark.asyncio
async def test_a_direct_judge_that_ran_out_of_time_on_every_attempt_leaves_a_call_of_unknown_usage(monkeypatch):
verifier = _verifier()
_completes(monkeypatch, [_timeout() for _ in range(verifier.DEFAULT_MAX_RETRIES)])
context = TaskStepContext()

with pytest.raises(RuntimeError, match="failed after"):
await _direct_once(verifier, context)

[entry] = context.metadata["step_usage"]["verify"]
assert (entry["turns"], entry["input_tokens"], entry["partial"]) == (1, None, True)


@pytest.mark.asyncio
async def test_a_cancelled_direct_judge_call_is_a_call_of_unknown_usage():
verifier = _verifier()
calling = asyncio.Event()

async def waits(prompt, *, model, context):
calling.set()
await asyncio.sleep(3600)

verifier._prompt_llm_judge = waits
context = TaskStepContext()
judging = asyncio.create_task(_direct_once(verifier, context))
await calling.wait()

judging.cancel()
with pytest.raises(asyncio.CancelledError):
await judging

[entry] = context.metadata["step_usage"]["verify"]
assert (entry["turns"], entry["partial"], entry["cost_status"]) == (1, True, "unpriced")


@pytest.mark.asyncio
async def test_a_judge_refused_on_every_attempt_records_nothing(monkeypatch):
verifier = _verifier()
refused = [litellm.RateLimitError("slow down", model="gpt-4o-mini", llm_provider="openai")
for _ in range(verifier.DEFAULT_MAX_RETRIES)]
_completes(monkeypatch, refused)
context = TaskStepContext()

with pytest.raises(RuntimeError, match="failed after"):
await _direct_once(verifier, context)

assert "verify" not in context.metadata.get("step_usage", {})

Loading