diff --git a/src/agent_env/config/model_call.py b/src/agent_env/config/model_call.py index 10c0776be..2cc68a1f8 100644 --- a/src/agent_env/config/model_call.py +++ b/src/agent_env/config/model_call.py @@ -4,6 +4,7 @@ from __future__ import annotations +import asyncio import contextlib import io import math @@ -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), 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 c3840c256..79e9c919c 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 @@ -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, @@ -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) # 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( @@ -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 @@ -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") diff --git a/src/agent_env/task_step/usage.py b/src/agent_env/task_step/usage.py index 2e4845694..0710d0b92 100644 --- a/src/agent_env/task_step/usage.py +++ b/src/agent_env/task_step/usage.py @@ -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") @@ -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.""" diff --git a/tst/unit/config/test_model_call.py b/tst/unit/config/test_model_call.py index 4168233c9..3ce789879 100644 --- a/tst/unit/config/test_model_call.py +++ b/tst/unit/config/test_model_call.py @@ -4,6 +4,7 @@ from __future__ import annotations +import asyncio import json import threading from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer @@ -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"))) diff --git a/tst/unit/task_step/usage_test.py b/tst/unit/task_step/usage_test.py index c454c7233..bd6203244 100644 --- a/tst/unit/task_step/usage_test.py +++ b/tst/unit/task_step/usage_test.py @@ -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) + diff --git a/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_usage.py b/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_usage.py index 417a19c43..f4301e119 100644 --- a/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_usage.py +++ b/tst/unit/task_step/verifiers/test_rubrics_verifier_judge_usage.py @@ -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)] @@ -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", {}) +