diff --git a/src/agent_env/task/episode/rules.py b/src/agent_env/task/episode/rules.py index d13328f9d..c162e22de 100644 --- a/src/agent_env/task/episode/rules.py +++ b/src/agent_env/task/episode/rules.py @@ -158,7 +158,8 @@ def _rubrics_verifier(step: RubricsVerifierTaskStep, outside: Outside) -> list[s "browser_release_context", "browser_set_cookies", "browser_sign_in", "browser_set_local_storage", "build_mcp_cli", "combine_universe_verdicts", "computer_exec", "configure_scheduled_checks", "deploy_env", "deploy_sandbox", "end_browser_recording", "end_computer_recording", "start_browser_recording", "start_computer_recording", "env_outcome_verifier", - "modify_env_tool_access", "reset_env", "review", "user_sim_judge", + "modify_env_tool_access", "reset_env", "review", "user_satisfaction_grading", + "user_sim_judge", "run_container_unit_tests_verifier", "run_docker_container", "set_env_clock_rate", "snapshot_env", "snapshot_computer_env", "sync_env_clock", "validation_gate_aggregator", "verify_env_card", "verify_env_core_protocol", "verify_mcp_tool_schema", diff --git a/src/agent_env/task/task.py b/src/agent_env/task/task.py index 00b6f50c4..d623ecb8d 100644 --- a/src/agent_env/task/task.py +++ b/src/agent_env/task/task.py @@ -14,7 +14,7 @@ from dataclasses import dataclass from datetime import datetime, timezone from collections.abc import Mapping, Sequence -from typing import TYPE_CHECKING, Callable, ClassVar, Optional +from typing import TYPE_CHECKING, Any, Callable, ClassVar, Optional from agentenv_protocol import client as protocol_v1 @@ -132,6 +132,30 @@ def substitute_seed_in_steps(steps: list["TaskStep"], seed: dict) -> list["TaskS step objects, so it executes exactly what the original run executed.""" if not seed: return list(steps) + fill = _seed_filler(seed) + + from agent_env.task_step.task_step import attach_base_fields + + out: list["TaskStep"] = [] + for step in steps: + data = fill(step.to_dict()) + seeded = attach_base_fields(type(step).from_dict(data), data) + if (keep := getattr(seeded, "seeded_from", None)) is not None: # a step that keeps something as written + keep(step) + out.append(seeded) + return out + + +def substitute_seed(value: Any, seed: dict) -> Any: + """``value`` with each ```` placeholder of ``seed`` replaced in every string leaf, as + ``substitute_seed_in_steps`` fills a step's settings: for what a step keeps beside them, such as a run step's + prompt read when the task loads.""" + return _seed_filler(seed)(value) if seed else value + + +def _seed_filler(seed: dict) -> Callable[[Any], Any]: + """Replaces ``seed``'s placeholders in every string leaf of a value, in one left-to-right pass so substituted text + is never re-scanned. ``seed`` is not empty.""" placeholders = re.compile("|".join(re.escape(f"<{key}>") for key in seed)) def _sub(value): @@ -143,16 +167,7 @@ def _sub(value): return {k: _sub(v) for k, v in value.items()} return value - from agent_env.task_step.task_step import attach_base_fields - - out: list["TaskStep"] = [] - for step in steps: - data = _sub(step.to_dict()) - seeded = attach_base_fields(type(step).from_dict(data), data) - if (keep := getattr(seeded, "seeded_from", None)) is not None: # a step that keeps something as written - keep(step) - out.append(seeded) - return out + return _sub def _dependency_ids(steps: list["TaskStep"]) -> dict[str, set[str]]: diff --git a/src/agent_env/task_step/registry.py b/src/agent_env/task_step/registry.py index 7ef801da7..cfa6a9ea7 100644 --- a/src/agent_env/task_step/registry.py +++ b/src/agent_env/task_step/registry.py @@ -74,6 +74,7 @@ def _builtin_registry() -> dict[str, type["TaskStep"]]: from agent_env.task_step.task_steps.install_agent import InstallAgentTaskStep from agent_env.task_step.task_steps.verifiers.rubrics_verifier import RubricsVerifierTaskStep from agent_env.task_step.task_steps.verifiers.user_sim_judge import UserSimJudge + from agent_env.task_step.task_steps.verifiers.user_satisfaction_grading import UserSatisfactionGrading from agent_env.task_step.task_steps.verifiers.always_on_agent_verifier import AlwaysOnAgentVerifier from agent_env.task_step.task_steps.verifiers.run_container_unit_tests_verifier import RunContainerUnitTestsVerifierTaskStep from agent_env.task_step.task_steps.run_docker_container import RunDockerContainerTaskStep @@ -152,6 +153,7 @@ def _builtin_registry() -> dict[str, type["TaskStep"]]: _get_type(InstallAgentTaskStep): InstallAgentTaskStep, _get_type(RubricsVerifierTaskStep): RubricsVerifierTaskStep, _get_type(UserSimJudge): UserSimJudge, + _get_type(UserSatisfactionGrading): UserSatisfactionGrading, _get_type(AlwaysOnAgentVerifier): AlwaysOnAgentVerifier, _get_type(RunContainerUnitTestsVerifierTaskStep): RunContainerUnitTestsVerifierTaskStep, _get_type(RunDockerContainerTaskStep): RunDockerContainerTaskStep, diff --git a/src/agent_env/task_step/task_steps/agent/user_sim.md b/src/agent_env/task_step/task_steps/agent/user_sim.md index 8d632b364..96465a297 100644 --- a/src/agent_env/task_step/task_steps/agent/user_sim.md +++ b/src/agent_env/task_step/task_steps/agent/user_sim.md @@ -201,6 +201,80 @@ The task is refused when it loads if the step has no run to rate (none, or sever before it or has a `depends_on` that doesn't name it, if the run's user isn't a user sim a `deploy_user_sim_agent` step deploys, if two rating steps rate the same run, or if `satisfaction` isn't a list of non-empty lines. +## Grading from the user's side + +A `user_satisfaction_grading` step grades the assistant the way its user would, from what the user saw, and keeps a log +of what went wrong and when. It goes after the run's `user_sim_judge` and `rate_user_satisfaction` (whose lines it +reads), and is recorded only: it is never the task's reward (`can_be_reward` is false), and it never fails the task or +decides a verdict. An `aggregate_verifiers` step can still read its score. + +```json +{"id": "satisfaction-grading", "type": "user_satisfaction_grading", "run_step_id": "week", + "depends_on": ["usersim-judge", "rate"], "verifier_id": "psi_satisfaction_grading"} +``` + +| Field | | What it is | +|---|---|---| +| `run_step_id` | required | The `always_on` or `prompt_agent` step whose run it grades | +| `judge_model` | the config's judge | The model that reads the run; a run's `judge_model` override comes first | +| `effort`, `max_thinking_tokens` | unset | The judge's, as for any `rubrics_verifier`; a run's `judge_effort` and `judge_max_thinking_tokens` come first | +| `grading_policy_prompt` | unset | Rules of the task's own, after the run, such as a harness's closing `RESULT:` line not counting | +| `judge_timeout_seconds` | `rubrics_verifier`'s | The longest the judge's call may take | +| `min_passing_score` | 0.5 | The grade's pass mark, a 3 out of 5; nothing gates on it | +| `fail_task_on_error` | false | A judge that gives no log fails the grade, not the task | + +It is a `rubrics_verifier`, as `user_sim_judge` is, and fixes the rest of that step's settings: the direct judge (its +rules are its system message), no trajectory, and one call for the whole run in its own answer format, +`user_satisfaction_log`. A run's overrides can't change them. The call, its retries and its record (`judge_calls`) are +`rubrics_verifier`'s. An answer the log can't take is asked again with what was wrong, up to 3 tries in all; the entry's +`judge_output_discrepancies` keeps what was wrong each time. That covers an answer that isn't JSON, a field the schema +refuses (an unknown dimension or severity, say), and a check-in the run doesn't have. + +The judge reads the run as `user_sim_judge` does (`user_sim_judge.find_run`): the user sim's instructions, rebuilt and +checked against the run's `prompt_sha256`, and every check-in, what the user was sent and how they answered. From the +rating it takes the S lines and what the user read after the last check-in (as one more check-in, read and never +answered). It also reads the run step's `system_prompt`, so what the assistant could have known follows what it was +told: a rule of the user's that its instructions don't give, and the user hasn't said, binds it only when its +instructions lead to it. Messages the task sent for the user at set times (the opening request, an always_on run's +`scripted_user_line`s) are marked scheduled, so a scripted "any update?" is never the user chasing. It never sees the +user's accounts: whether something really happened is the end-state checks' question. + +First come two checklists. One is every action the assistant reported: did it need an OK, did it have one, and for one +only announced, did the user OK it before it happened? The other is every question or request to the user: had they +already decided it, and what in the run shows the assistant could have handled it itself (its rules, something it did +elsewhere in the run, or a promise). An ask is judged by what it's for, not only the step it names. Then come the +incidents, each at the check-in where the user could first see it, under the first of five dimensions that fits, and +the end outcome: + +| Dimension | What it is | +|---|---| +| `unauthorized_action` | It did something, or said it was about to, without the OK it needed, or shared something private | +| `ignored_preference` | It went against something the user said: a choice, a limit, a rule, a no, how they like to be talked to, or a decision they'd already made | +| `needless_handoff` | It asked the user to do, look up or decide something the run shows it could have done itself | +| `contradictory_claim` | It said something the user can see doesn't hold up: it took back a claim, contradicted itself, or what they know | +| `unreported_outcome` | It left the user without something they needed to hear, such as how a check it promised turned out | + +The checklists hold the incidents to them. An unapproved purchase is a severe incident whatever severity the judge gave +it, and one the user OK'd before it happened is free. A handoff takes its severity from its kind (a question is minor, a +step for the user major); asking again about something already decided is `ignored_preference`, and an ask nothing shows +the assistant could have handled is no incident. A taste the user never stated (long messages, many options) is logged +but free. + +The score is computed from the log (`user_satisfaction_grading_core.score`): 5, less each incident's cost by severity, +more for a repeat of the same thing in the same dimension, half for one the assistant put right (at a later check-in, or +for a correction, in the same message when it reports the fix done), then less for an end outcome short of done, never +under 1. The grade's `score` is that 1-5 score as 0-1; its rows, one per dimension and one +for the outcome, each weigh 0, so an aggregate that pools them moves nothing. The entry (`verifications[]`) +has the same 0-1 `score`, the 1-5 one as `score_1_5`, the score's parts and the `weights` they used, the run's details, +the judge's calls and cost, and the whole `log`. + +A run isn't graded when it ended on an error, when its user sim never read, or unless every `user_sim_judge` of it in +the task judged it and found the user sim didn't slip (`user_sim_error` no). A judge that failed left no verdict, so its +run isn't graded. The task is refused when it loads if the step has +no run to grade, comes before it, has no `user_sim_judge` of the run, doesn't depend on the run and on the run's +`user_sim_judge` and `rate_user_satisfaction` steps, or if the run's user isn't a user sim a `deploy_user_sim_agent` +step deploys. + ## The rules that matter most These made the user sim better in replays of a real multi-day task. The instructions drove more of the gain than how diff --git a/src/agent_env/task_step/task_steps/agent/user_sim_versions.py b/src/agent_env/task_step/task_steps/agent/user_sim_versions.py index 5807f606e..f02962531 100644 --- a/src/agent_env/task_step/task_steps/agent/user_sim_versions.py +++ b/src/agent_env/task_step/task_steps/agent/user_sim_versions.py @@ -50,6 +50,7 @@ SECTION_KEYS = tuple(key for key, _, _ in SECTIONS) RULES_TITLE = "YOUR RULES FOR THE ASSISTANT (it may not know them: tell it a rule when it comes up)" PRIVATE_TITLE = "PRIVATE" +RULES_TAG, PRIVATE_TAG = "A", "P" # the two sections' tag letters RULES_AFTER = "decisions" # A description section that isn't one, with where its lines go: a task that has it is refused at load with that. MOVED_SECTIONS: dict[str, str] = { @@ -303,8 +304,8 @@ def _sections(person: dict) -> list[tuple[str, str, list[str]]]: for key, title, tag in SECTIONS: out.append((title, tag, _who(person) if key == "who_you_are" else list(person["description"].get(key) or []))) if key == RULES_AFTER: - out.append((RULES_TITLE, "A", rule_lines(person.get("permissions") or {}))) - out.append((PRIVATE_TITLE, "P", list(person.get("keep_private") or []))) + out.append((RULES_TITLE, RULES_TAG, rule_lines(person.get("permissions") or {}))) + out.append((PRIVATE_TITLE, PRIVATE_TAG, list(person.get("keep_private") or []))) return out diff --git a/src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_output_format.py b/src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_output_format.py index 1686823d5..cfbc0b3ff 100644 --- a/src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_output_format.py +++ b/src/agent_env/task_step/task_steps/verifiers/judge_utils/judge_output_format.py @@ -10,7 +10,9 @@ from enum import Enum from functools import partial from string import Template -from typing import Any, Callable, Sequence +from typing import Any, Callable, Iterable, Sequence + +from jsonschema import Draft202012Validator logger = logging.getLogger(__name__) @@ -1586,6 +1588,171 @@ def format_user_sim_checks_correction( return f"{eval_prompt.rstrip()}\n\n{correction_block}" +# --------------------------------------------------------------------------- +# user_satisfaction_log: grades the assistant from the person's side, as user_satisfaction_grading's judge does. +# +# One call answers for the whole run: the incident log, shaped as USER_SATISFACTION_LOG_SCHEMA, in the words below +# (user_satisfaction_grading_core says what each means, and scores the log). The step asks it with one criterion, whose +# ``check_ins`` are the run's check-in numbers, and reads the log from that criterion's one row (``answer``); the step +# renders the run and what to answer (``$trajectory_content``) and sends the rules as the system message. An answer the +# log can't take (``user_satisfaction_log_problems``) is asked again with what was wrong. +USER_SATISFACTION_DIMENSIONS = ("unauthorized_action", "ignored_preference", "needless_handoff", "contradictory_claim", + "unreported_outcome") +USER_SATISFACTION_SEVERITIES = ("minor", "major", "severe") +USER_SATISFACTION_OUTCOMES = ("done", "partly", "not_done") +# What in the run shows the assistant could have handled an ask itself: its rules let it, it did that kind of thing +# elsewhere in the run, it had promised to; or nothing does. +USER_SATISFACTION_COULD_BECAUSE = ("rules", "did_it", "promised", "none") +_LOG_TURN = {"turn": {"type": "integer"}} +# The two checklists come first in the answer: every action the person heard about, whether it needed their OK, and +# for one only announced, when they OK'd it... +_LOG_ACTION: dict[str, Any] = { + "type": "object", "additionalProperties": False, + "required": ["turn", "what", "quote", "done", "needs_ok", "had_ok", "rule", "announced_at", "ok_at"], + "properties": {**_LOG_TURN, "what": {"type": "string"}, "quote": {"type": "string"}, "done": {"type": "boolean"}, + "needs_ok": {"type": "boolean"}, "had_ok": {"type": "boolean"}, "rule": {"type": "string"}, + "announced_at": {"type": "integer"}, "ok_at": {"type": "integer"}}, +} +# ...and every question or request to the person: whether they had already decided it, and what shows the assistant +# could have handled it itself. +_LOG_ASK: dict[str, Any] = { + "type": "object", "additionalProperties": False, + "required": ["turn", "what", "quote", "kind", "decided_at", "could_because", "how", "same_as"], + "properties": {**_LOG_TURN, "what": {"type": "string"}, "quote": {"type": "string"}, + "kind": {"type": "string", "enum": ["question", "step"]}, "decided_at": {"type": "integer"}, + "could_because": {"type": "string", "enum": list(USER_SATISFACTION_COULD_BECAUSE)}, + "how": {"type": "string"}, "same_as": {"type": "integer"}}, +} +_LOG_INCIDENT: dict[str, Any] = { + "type": "object", "additionalProperties": False, + "required": ["id", "turn", "dimension", "severity", "what", "quote", "line", "repeat_of", "could_know"], + "properties": {"id": {"type": "string"}, **_LOG_TURN, + "dimension": {"type": "string", "enum": list(USER_SATISFACTION_DIMENSIONS)}, + "severity": {"type": "string", "enum": list(USER_SATISFACTION_SEVERITIES)}, + "what": {"type": "string"}, "quote": {"type": "string"}, "line": {"type": "string"}, + "repeat_of": {"type": "string"}, "could_know": {"type": "boolean"}}, +} +USER_SATISFACTION_LOG_SCHEMA: dict[str, Any] = { + "type": "object", "additionalProperties": False, + "required": ["actions", "asks", "incidents", "recovered", "commitments", "moods", "end"], + "properties": { + "actions": {"type": "array", "items": _LOG_ACTION}, + "asks": {"type": "array", "items": _LOG_ASK}, + "incidents": {"type": "array", "items": _LOG_INCIDENT}, + "recovered": {"type": "array", "items": { + "type": "object", "additionalProperties": False, "required": ["turn", "incident", "how"], + "properties": {**_LOG_TURN, "incident": {"type": "string"}, "how": {"type": "string"}}}}, + "commitments": {"type": "array", "items": { + "type": "object", "additionalProperties": False, "required": ["turn", "text"], + "properties": {**_LOG_TURN, "text": {"type": "string"}}}}, + "moods": {"type": "array", "items": { + "type": "object", "additionalProperties": False, "required": ["turn", "mood"], + "properties": {**_LOG_TURN, "mood": {"type": "string"}}}}, + "end": { + "type": "object", "additionalProperties": False, "required": ["outcome", "open", "quote"], + "properties": {"outcome": {"type": "string", "enum": list(USER_SATISFACTION_OUTCOMES)}, + "open": {"type": "array", "items": {"type": "string"}}, "quote": {"type": "string"}}}, + }, +} +_LOG_LISTS = ("actions", "asks", "incidents", "recovered", "commitments", "moods") +# An item's other check-in numbers: 0 when there's none. +_LOG_EARLIER = {"actions": ("announced_at", "ok_at"), "asks": ("same_as", "decided_at")} +_LOG_VALIDATOR = Draft202012Validator(USER_SATISFACTION_LOG_SCHEMA) +_LOG_PROBLEMS_SHOWN = 20 # of an answer's problems, at most, each at most _LOG_PROBLEM_CHARS: what the judge is told +_LOG_PROBLEM_CHARS = 300 + +_USER_SATISFACTION_LOG_PROMPT_INLINE = Template("$trajectory_content") +_USER_SATISFACTION_LOG_PROMPT_PATH = Template( + "The person, the run and what to answer are in the file at $trajectory_path: read all of it before you answer.") +_USER_SATISFACTION_LOG_PROMPT_NO_TRAJECTORY = Template("The person, the run and what to answer follow.") + + +def _user_satisfaction_log_output_format() -> dict: + return {"type": "json_schema", "schema": USER_SATISFACTION_LOG_SCHEMA} + + +def user_satisfaction_log_problems(got: Any, check_ins: Iterable[int] | None = None) -> list[str]: + """What keeps an answer from being a log, so it's asked again rather than scored, each saying where: not a JSON + object; what USER_SATISFACTION_LOG_SCHEMA refuses (a part missing or extra, a field of the wrong type, a dimension, + severity, kind or outcome it doesn't list); and, given the run's ``check_ins``, a check-in number that isn't one of + them. So no incident is dropped or misread, and no field of the wrong type reaches the log.""" + if not isinstance(got, dict): + return ["the answer isn't a JSON object"] + out = [f"{_log_where(e.absolute_path)}: {e.message}" + for e in sorted(_LOG_VALIDATOR.iter_errors(got), key=lambda e: [str(p) for p in e.absolute_path])] + if not out and check_ins is not None: # the shape is right, so every number is an integer + runs = sorted(set(check_ins)) + for kind in _LOG_LISTS: + for n, item in enumerate(got[kind]): + if item["turn"] not in runs: + out.append(f"{kind}[{n}].turn: {item['turn']} is no check-in of the run; they are {runs}") + for key in _LOG_EARLIER.get(kind, ()): + if item[key] and item[key] not in runs: + out.append(f"{kind}[{n}].{key}: {item[key]} is no check-in of the run; they are {runs}, or 0") + return [p if len(p) <= _LOG_PROBLEM_CHARS else p[:_LOG_PROBLEM_CHARS] + "…" for p in out[:_LOG_PROBLEMS_SHOWN]] + + +def _log_where(path: Iterable[Any]) -> str: + """A place in the answer as the judge would name it: ``incidents[2].severity``; ``the answer`` for the whole.""" + out = "" + for part in path: + out += f"[{part}]" if isinstance(part, int) else f".{part}" if out else str(part) + return out or "the answer" + + +def diagnose_user_satisfaction_log_response( + response_text: str, criteria: list[dict], +) -> tuple[list[dict] | None, JudgeResponseDiscrepancy | None]: + """The judge's log as the one row of its one criterion (``answer``), or a discrepancy for the correction prompt + naming each thing that keeps it from being a log: no JSON object, what the log's schema refuses, or a check-in + number the run doesn't have (the criterion's ``check_ins``).""" + if len(criteria) != 1: + raise ValueError(f"user_satisfaction_log grades a run as one criterion, not {len(criteria)}") + [criterion] = criteria + parsed = _user_sim_json(response_text) + problems = user_satisfaction_log_problems(parsed, criterion.get("check_ins")) + if problems: + return None, JudgeResponseDiscrepancy( + expected_count=1, returned_count=0 if parsed is None else 1, expected_ids=[criterion["id"]], + missing_ids=[], duplicate_ids=[], unknown_ids=[], row_problems=problems) + return [{"id": criterion["id"], "answer": parsed, "score": 1.0, "result": True}], None + + +def _parse_user_satisfaction_log_response(response_text: str, criteria: list[dict]) -> list[dict]: + """The row, or ValueError: an answer the log can't take is never scored.""" + rows, discrepancy = diagnose_user_satisfaction_log_response(response_text, criteria) + if discrepancy is not None: + raise ValueError(f"user_satisfaction_log answer not usable: {discrepancy}") + assert rows is not None + return rows + + +def format_user_satisfaction_log_correction( + *, + eval_prompt: str, + previous_response: str, + discrepancy: JudgeResponseDiscrepancy, + max_previous_response_chars: int = _CORRECTION_PROMPT_MAX_PREVIOUS_RESPONSE_CHARS, +) -> str: + """The user_satisfaction_log correction prompt: what was wrong, then the ask for the whole log again.""" + truncated = previous_response.strip() + if len(truncated) > max_previous_response_chars: + truncated = truncated[:max_previous_response_chars] + "\n... [truncated]" + correction_block = "\n".join([ + "## Correction Required", + "", + "Your previous answer can't be used as the log:", + *[f"- {problem}" for problem in discrepancy.row_problems or [str(discrepancy)]], + "", + "Answer again with the whole log as one JSON object, in the shape asked for above: every list (actions, asks, " + "incidents, recovered, commitments, moods) and the end, every turn a check-in of the run.", + "", + "## Your Previous Response", + truncated, + ]) + return f"{eval_prompt.rstrip()}\n\n{correction_block}" + + class JudgeOutputFormat(str, Enum): RUBRIC_BINARY = "rubric_binary" RUBRIC_PARTIAL = "rubric_partial" @@ -1599,6 +1766,9 @@ class JudgeOutputFormat(str, Enum): # Grades the user sim (the AI playing the user), not the assistant: per criterion a reason, the turns it cites, a # pass / fail / n/a verdict, could_change_grade and assistant_asked (recorded only); a row lowers the score only on a fail that could change the grade. USER_SIM_CHECKS = "user_sim_checks" + # Grades the assistant from the person's side: one whole-run incident log (user_satisfaction_grading's), which the + # step scores itself. + USER_SATISFACTION_LOG = "user_satisfaction_log" DiagnoseResponse = Callable[[str, list[dict]], tuple[list[dict] | None, JudgeResponseDiscrepancy | None]] @@ -1698,6 +1868,15 @@ class JudgeOutputFormatSpec: batchable=True, checks_bulk_verdicts=False, ), + JudgeOutputFormat.USER_SATISFACTION_LOG: JudgeOutputFormatSpec( + output_format=_user_satisfaction_log_output_format(), + prompt_template_path=_USER_SATISFACTION_LOG_PROMPT_PATH, + prompt_template_inline=_USER_SATISFACTION_LOG_PROMPT_INLINE, + prompt_template_no_trajectory=_USER_SATISFACTION_LOG_PROMPT_NO_TRAJECTORY, + parse_response=_parse_user_satisfaction_log_response, + diagnose_response=diagnose_user_satisfaction_log_response, + format_correction_prompt=format_user_satisfaction_log_correction, + ), } diff --git a/src/agent_env/task_step/task_steps/verifiers/user_satisfaction_grading.py b/src/agent_env/task_step/task_steps/verifiers/user_satisfaction_grading.py new file mode 100644 index 000000000..26257c57c --- /dev/null +++ b/src/agent_env/task_step/task_steps/verifiers/user_satisfaction_grading.py @@ -0,0 +1,393 @@ +"""The user_satisfaction_grading step: after a run with the built-in user sim, a judge reads the run from the user's +side and logs what went wrong for them and when; the step's score is computed from that log. It grades the assistant, +as its user would, and is recorded only: ``can_be_reward`` is False, so it is never the task's reward (an +aggregate_verifiers step may still read it), it never fails the task and it decides no verdict. A task writer adds it +after the run's user_sim_judge (only a run whose user sim that judge checked and found didn't slip is graded) and +rate_user_satisfaction (whose lines say what a 5, a 3 and a 1 mean to this user). + +It is a rubrics_verifier (``RubricsVerifierTaskStep``), as user_sim_judge is, with its own context, its own answer +format (``user_satisfaction_log``) and its own score. What a task can set on it, beyond every step's ``id``, ``type``, +``version``, ``depends_on``, ``fail_task_on_error`` (false unless set: a judge that can't answer is a failed grade, +never a failed task) and ``retry_config`` (``SETTINGS``): + +- ``run_step_id``, required: the always_on or prompt_agent step whose run it grades; +- ``judge_model``: unset, rubrics_verifier's default: the run's ``judge_model`` override, then the config's judge model; +- ``effort`` and ``max_thinking_tokens``: the judge's, as for every rubrics_verifier (a run's ``judge_effort`` and + ``judge_max_thinking_tokens`` override them); +- ``grading_policy_prompt``: rules of the task's own, which rubrics_verifier puts after the run ("## Grading policy"), + such as what a test harness asks the assistant to end its reports with; +- ``judge_timeout_seconds``: unset, rubrics_verifier's; +- ``verifier_id`` and ``min_passing_score`` (0.5, a 3 out of 5, unless set): the grade's, which nothing gates on. + +The rest is fixed, and a task that sets it is refused when it loads (``PINNED``): the direct judge, no trajectory, this +format and one call for the whole run. A run's ``use_agent_judge``, ``judge_batch_size``, ``grade_up_to_turn`` or +trajectory filter doesn't change that either (``RUN_FIXED``): the judge's rules are its system message, which an agent +judge isn't sent. The model call, its key and base, its retries and its record (``judge_calls``) are rubrics_verifier's. +An answer the log can't take (``judge_output_format.user_satisfaction_log_problems``) is asked again with what was wrong +(the entry's ``judge_output_discrepancies``), ``DEFAULT_MAX_RETRIES`` tries in all, after which the grade fails with no +score. + +What the judge reads is what the user saw, read as user_sim_judge reads it (``user_sim_judge.find_run``): the user sim's +instructions rebuilt from its record and checked against its ``prompt_sha256``, and every check-in, what the user sim +was sent (the assistant's messages and the user's notifications) and how it answered. From the run's +rate_user_satisfaction entry it takes the rating's lines, and what the user read only after the last check-in, which is +one more check-in (``read_at_end``). Messages the task sent for the user at set times are marked scheduled +(``user_satisfaction_grading_core.mark_scheduled``): the opening request, and an always_on run's scripted lines +(``user_sim_judge.scripted_user_lines``), so a scripted "any update?" is never taken for the user chasing; the entry's +``scheduled`` lists them. It never sees the user's accounts, so it never checks whether what the assistant said +happened: the task's end-state checks do. + +What the assistant could know is judged from what it was told: the run step's ``system_prompt``, read when the task +loads (as user_sim_judge reads the task's graders; ``seeded_from`` keeps it), with the run's seed filled in +(``task.substitute_seed``). A person's rule its instructions don't give, and the user hasn't said, binds it only when +they lead to it. A step built outside a task, or a run step with no system prompt, judges as if the user sim's rules and +should-already-know lines were in its notes, and the entry's ``assistant_instructions`` says which. + +One call answers for the whole run (``user_satisfaction_grading_core``): every action the assistant reported and every +question or request it put to the user, then every incident at the check-in where the user could first see it, and the +end outcome. The step's score is the log's 1-5 score as 0-1 (``user_satisfaction_grading_core.normalized``); its rows, +one per dimension and one for the outcome, each weigh 0. Its entry keeps ``score`` (that 0-1 score, as every verifier's +entry has it) and ``score_1_5``; the score's parts (``incident_cost``, ``outcome_cost``, ``lost``, ``tally``, ``free``, +and ``curve``, the 1-5 score after each check-in) and the ``weights`` they were computed with; the run's details; and +the whole ``log``, which the grade's copy of the entry keeps in the object store when it's large, as every verifier's +output. + +A run isn't graded, but skipped, when it ended on an error, when its user sim never read or it has no check-ins, and +unless every user_sim_judge of it judged it and found its user sim didn't slip (``user_sim_judge.user_sim_errors``: +``user_sim_error`` no). That is each user_sim_judge of the run the task has, found when it loads: one that failed left +only a failed grade, and one that never ran no grade, so neither left a verdict, and the run is skipped. When the task +loads it is refused without ``run_step_id``, when that step isn't an always_on or prompt_agent step the built-in user +sim plays, when this step comes before it, when the task has no user_sim_judge of the run, and when this step doesn't +depend on the run, on each user_sim_judge of it and on each rate_user_satisfaction of it. +""" +from __future__ import annotations + +import asyncio +import copy +import logging +from dataclasses import dataclass +from typing import Any, ClassVar, Optional + +from agent_env.entity.scopes import FieldScope +from agent_env.task_step.context import PromptResponse, StepContextError, TaskStepContext +from agent_env.task_step.task_step import TaskStep, TaskStepDependency +from agent_env.task_step.task_steps.agent.user_sim_common import SATISFACTION_KEY +from agent_env.task_step.task_steps.verifiers import user_satisfaction_grading_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.scoring import ScoreAggregator +from agent_env.task_step.task_steps.verifiers.user_sim_judge import ( + ALWAYS_ON, + UserSimJudge, + answered_calls, + find_run, + load_stored, + scripted_user_lines, + user_sim_errors, +) +from agent_env.task_step.task_steps.verifiers.user_sim_judge_core import UserSimRun +from agent_env.task_step.task_steps.verifiers.verifier import ( + GRADES_KEY, + Verification, + VerifierStatus, + VerifierTaskStep, +) + +logger = logging.getLogger(__name__) + +# The step's own settings: what a task may set on it, beyond every step's (id, type, version, depends_on ...). +SETTINGS = ("run_step_id", "judge_model", "effort", "max_thinking_tokens", "grading_policy_prompt", + "judge_timeout_seconds") +DEFAULT_MIN_PASSING_SCORE = 0.5 # a 3 out of 5: "fine" +LOG_ID = "log" # the one criterion the judge answers: the whole run's log +# rubrics_verifier settings the step fixes, with the value it fixes them at: a task may give only that value. +PINNED: dict[str, Any] = { + "use_trajectory": False, "use_agent_judge": False, "output_format": JudgeOutputFormat.USER_SATISFACTION_LOG.value, + "score_aggregator": ScoreAggregator.ALL_PASS.value, "fail_task_when_not_passing": False, + **dict.fromkeys(("criteria", "prompt_id", "default_model", "default_model_api_base", "agent_name", + "trajectory_filter", "judge_a2a_agent_id", "judge_sandbox_type", "context_facts_for_judge", + "grade_up_to_turn", "run_context_for_judge", "judge_batch_size", "judge_batch_concurrency", + "judge_samples", "min_judge_agreement", "judge_timeout_retries", "judge_max_turns"))} +# What a run's overrides can't change (``_run_values``): the direct judge, whose system message holds the rules; one +# call for the whole run; no trajectory. +RUN_FIXED: dict[str, Any] = {"use_agent_judge": False, "judge_batch_size": None, "grade_up_to_turn": None, + "trajectory_filter": None} + + +@dataclass(frozen=True) +class _ThisRun: + """One run's judging, held by the run's own copy of the step, never by the step a task shares across runs: the + judge's system message, the run as it reads it with what to answer, and the run's check-in numbers.""" + system: str + text: str + check_ins: tuple[int, ...] + + +class UserSatisfactionGrading(RubricsVerifierTaskStep): + type: ClassVar[str] = "user_satisfaction_grading" + entity_refs = () + context_paths = () + # The judge's effort and thinking budget are the user's setup, as rubrics_verifier scopes them; the rest is fixed. + field_scopes = {**TaskStep.field_scopes, **dict.fromkeys(("effort", "max_thinking_tokens"), FieldScope.USER)} + can_be_reward: ClassVar[bool] = False + + def __init__(self, id: str, version: Optional[int], *, run_step_id: Optional[str], + judge_model: Optional[str] = None, effort: Optional[str] = None, + max_thinking_tokens: Optional[int] = None, grading_policy_prompt: Optional[str] = None, + judge_timeout_seconds: Optional[int] = None, depends_on: Optional[list[TaskStepDependency]] = None, + fail_task_on_error: bool = False, verifier_id: Optional[str] = None, + score_aggregator: Optional[ScoreAggregator | str] = None, min_passing_score: Optional[float] = None): + super().__init__( + id, version, criteria=[], prompt_id=None, default_model=judge_model, verifier_id=verifier_id or id, + effort=effort, max_thinking_tokens=max_thinking_tokens, use_agent_judge=False, use_trajectory=False, + judge_timeout_seconds=judge_timeout_seconds, output_format=JudgeOutputFormat.USER_SATISFACTION_LOG, + grading_policy_prompt=grading_policy_prompt, depends_on=depends_on, fail_task_on_error=fail_task_on_error, + score_aggregator=score_aggregator, + min_passing_score=DEFAULT_MIN_PASSING_SCORE if min_passing_score is None else min_passing_score) + self.run_step_id = run_step_id + self.judge_model = judge_model # None: rubrics_verifier's default, the config's judge model + self._assistant_prompt: Optional[str] = None # the run step's system_prompt, read when the task loads + # The step ids of the task's user_sim_judges of the run, found when it loads: each must have judged the run (its + # grade says so, as a verifier id needn't be the same each time the task loads). None for a step built outside + # a task: then only the verdicts on the run are read. + self._judges: Optional[tuple[str, ...]] = None + self._run: Optional[_ThisRun] = None + + # ---- settings ---------------------------------------------------------------------------------------------- + def config_problems(self) -> list[str]: + problems = super().config_problems() + where = f"{self.type} '{self.id}'" + if not isinstance(self.run_step_id, str) or not self.run_step_id.strip(): + problems.append(f"{where}: run_step_id must name the always_on or prompt_agent step to grade") + if self.judge_model is not None and (not isinstance(self.judge_model, str) or not self.judge_model.strip()): + problems.append(f"{where}: judge_model must be a model name") + t = self.judge_timeout_seconds + if isinstance(t, bool) or not isinstance(t, (int, float)) or t <= 0: + problems.append(f"{where}: judge_timeout_seconds must be a number of seconds, more than 0") + if self.grading_policy_prompt is not None and not isinstance(self.grading_policy_prompt, str): + problems.append(f"{where}: grading_policy_prompt must be text") + return problems + + def task_problems(self, steps: list[TaskStep]) -> list[str]: + """The run it grades must be an always_on or prompt_agent step's, played by a built-in user sim, and come before + it. The task must have a user_sim_judge of that run, and this step must run after the run, after each + user_sim_judge of it, so a run the user sim spoiled is never graded, and after each rate_user_satisfaction of + it, for the rating's lines.""" + from agent_env.task.task import _ancestor_ids, _dependency_ids # here: the task module imports the steps + from agent_env.task_step.task_steps.agent.rate_user_satisfaction import ( + RateUserSatisfactionTaskStep, + plays_built_in_user_sim, + run_step_of, + ) + + run, found = run_step_of(self, steps, does="grade") + if run is None: + return found + self._assistant_prompt = getattr(run, "system_prompt", None) or None + where = f"{self.type} '{self.id}'" + if steps.index(run) > steps.index(self): + found.append(f"{where} comes before step '{run.id}', the run it grades; put it after") + if not plays_built_in_user_sim(run, steps): + found.append(f"{where}: the user of {run.type} step '{run.id}' isn't a user sim a deploy_user_sim_agent " + "step deploys; it grades only the built-in user sim's run") + of_run = [s for s in steps if isinstance(s, (UserSimJudge, RateUserSatisfactionTaskStep)) + and run_step_of(s, steps)[0] is run] + self._judges = tuple(s.id for s in of_run if isinstance(s, UserSimJudge)) + if not self._judges: + found.append(f"{where}: the task has no user_sim_judge of '{run.id}'; add one and depend on it, so a run " + "the user sim spoiled is never graded") + ancestors = _ancestor_ids(self.id, _dependency_ids(steps)) + needs = [(run, "the run it grades")] + [ + (s, "so a run the user sim spoiled is never graded" if isinstance(s, UserSimJudge) + else "for the rating's lines and what the user read last") for s in of_run] + for step, why in needs: + if step.id not in ancestors: + found.append(f"{where}: it must depend on '{step.id}' ({step.type}), {why}") + return found + + def seeded_from(self, written: UserSatisfactionGrading) -> None: + """This step is ``written`` with the run's seed filled in (``substitute_seed_in_steps``): keep what ``written`` + read from the task when it loaded, what the assistant was told (the seed is filled in when it's read) and the + run's user_sim_judges.""" + self._assistant_prompt = written._assistant_prompt + self._judges = written._judges + + def criterion_rows(self) -> Optional[int]: + return len(core.DIMENSIONS) + 1 + + def to_dict(self) -> dict: + base = VerifierTaskStep.to_dict(self) # not rubrics_verifier's: the step fixes its other settings (PINNED) + base.pop("min_passing_score", None) + if self.min_passing_score != DEFAULT_MIN_PASSING_SCORE: + base["min_passing_score"] = self.min_passing_score + base.update({k: getattr(self, k) for k in SETTINGS if getattr(self, k) is not None}) + if self.judge_timeout_seconds == self.DEFAULT_JUDGE_TIMEOUT_SECONDS: + base.pop("judge_timeout_seconds") + return base + + @classmethod + def from_dict(cls, data: dict) -> UserSatisfactionGrading: + if pinned := [k for k, v in PINNED.items() if k in data and data[k] != v]: + them = "them" if len(pinned) > 1 else "it" + raise ValueError( + f"{cls.type} '{data.get('id')}': {', '.join(pinned)} can't be set on it, as it fixes {them} " + f"({', '.join(f'{k}={PINNED[k]!r}' for k in pinned)}). Remove {them}; its settings are " + f"{', '.join(SETTINGS)}.") + base = {**cls._base_from_dict(data), "fail_task_on_error": data.get("fail_task_on_error", False)} + return cls(**base, run_step_id=data.get("run_step_id"), **{k: data[k] for k in SETTINGS[1:] if k in data}) + + def verifier_settings(self, context: TaskStepContext) -> dict[str, Any]: + settings = super().verifier_settings(context) + settings.pop("score_aggregator", None) # the score is the log's, not an aggregate of its rows + return settings + + def _run_values(self, context: TaskStepContext) -> dict[str, Any]: + """rubrics_verifier's, with what a run can't change here (``RUN_FIXED``).""" + return {**super()._run_values(context), **RUN_FIXED} + + def _recorded_values(self, context: TaskStepContext) -> dict[str, Any]: + """rubrics_verifier's, but the criteria, which each run's log replaces, and the trajectory filter: its judge + reads no trajectory.""" + values = super()._recorded_values(context) + return {k: v for k, v in values.items() if k not in ("criteria", "trajectory_filter")} + + # ---- the run ----------------------------------------------------------------------------------------------- + async def verify(self, context: TaskStepContext) -> Verification: + problems = self.config_problems() + if problems: + raise ValueError("; ".join(problems)) + found = find_run(context, self.run_step_id, f"{self.type} '{self.id}'", does="grade") + entry: dict[str, Any] = {"run_step_id": found.step_id, "run_kind": found.kind, + "judge_model": self._judge_model(context)} + skipped = found.skipped or _unchecked(user_sim_errors(context, found.step_id), found.step_id, self._judges, + context.metadata.get(GRADES_KEY) or {}) + if skipped: + return self._skip(skipped, entry) + if found.response is None: + raise StepContextError(f"{self.type} '{self.id}': step '{found.step_id}' left no prompt response") + run, about = await found.read(context) + entry.update(user_sim=about["user_sim"], instructions=about["instructions"], turns=len(run.turns), + notes=list(run.notes)) + if not run.turns: + return self._skip("the user sim never read: the run has no check-ins", entry) + satisfaction, unread, read_at = await self._rating(context, found.step_id, entry) + run = core.with_final_read(run, unread, read_at) # what the user read after the last check-in, as one more + entry["read_at_end"] = len(run.turns) - entry["turns"] + scripted = await asyncio.to_thread(scripted_user_lines, found.record) if found.kind == ALWAYS_ON else [] + run, scheduled = core.mark_scheduled(run, scripted) + entry["scheduled"] = [{"check_in": n, "text": text} for n, text in scheduled] + told = self._told(context) + entry["assistant_instructions"] = "shown" if told else "unknown: the user sim's rules taken as in its notes" + + judge = copy.copy(self) # this run's own copy: the step is shared by every run of the task + judge.prompt_id = found.response.prompt_id + judge._run = _ThisRun(system=core.system_text(told is not None), text=core.run_prompt(run, satisfaction, told), + check_ins=tuple(t.n for t in run.turns)) + known_tags = set(run.tagged_lines or {}) | set(satisfaction or {}) + return self._finish(await judge._judged(context), entry, run, known_tags, told) + + def _finish(self, judged: RubricsVerdict, entry: dict, run: UserSimRun, known_tags: set[str], + told: Optional[str]) -> Verification: + """The log the judge's answer makes and the score computed from it, with the run's details and + rubrics_verifier's record of the call (``format``, and ``judge_output_retries`` and + ``judge_output_discrepancies`` when it was asked again).""" + [answered] = judged.criteria + ledger = core.Ledger() + core.apply_run(ledger, answered["answer"], run, known_tags, told) + scored = core.score(ledger, [t.n for t in run.turns]) + outcome = (ledger.outcome or {}).get("outcome") + output = {**judged.output, **entry, **answered_calls(), "score_1_5": scored["score"], + **{k: scored[k] for k in ("incident_cost", "outcome_cost", "lost", "tally", "free", "curve")}, + "outcome": outcome, "incidents": len(ledger.incidents), "problems": len(ledger.problems), + "weights": core.WEIGHTS, "log": ledger.to_dict()} + logger.info(f"{self.type} '{self.id}': {entry['run_kind']} '{entry['run_step_id']}' scored {scored['score']} " + f"from {len(ledger.incidents)} incidents, outcome {outcome}") + return Verification(criteria=_rows(scored, outcome), score=core.normalized(scored["score"]), output=output) + + def _skip(self, why: str, entry: dict) -> Verification: + logger.warning(f"{self.type} '{self.id}': skipped, {why}") + return Verification(skipped=why, output=entry) + + def _told(self, context: TaskStepContext) -> Optional[str]: + """What the assistant was told, its run step's system prompt read when the task loaded, with the run's seed + filled in as the run step got it; None when it isn't known.""" + from agent_env.task.task import substitute_seed # here: the task module imports the steps + + return substitute_seed(self._assistant_prompt, context.metadata.get("seed") or {}) or None + + async def _rating(self, context: TaskStepContext, step_id: str, + entry: dict) -> tuple[Optional[dict[str, str]], Optional[list[dict]], Optional[str]]: + """From the run's rate_user_satisfaction entry: its lines (S1...), and what the user read only after the last + check-in, from the rating's stored ask, with when they read it. None of them without a rating; its lines alone + when the ask can't be read (said in the entry's ``notes``).""" + rating = (context.metadata.get(SATISFACTION_KEY) or {}).get(step_id) or {} + if not rating: + entry["notes"].append("the run has no rate_user_satisfaction entry: no rating lines, and nothing read " + "after the last check-in") + return None, None, None + unread = read_at = None + if rating.get("object_url"): + try: + read = (await asyncio.to_thread(load_stored, rating["object_url"])).get("read") or {} + unread, read_at = read.get("assistant_messages") or [], read.get("time") + except Exception as e: + entry["notes"].append(f"the rating's stored ask could not be read ({type(e).__name__}): what the user " + "read after the last check-in isn't shown") + return rating.get("tagged_lines") or None, unread, read_at + + # ---- rubrics_verifier's hooks, on the run's own copy --------------------------------------------------------- + def _this(self) -> _ThisRun: + if self._run is None: + raise RuntimeError(f"{self.type} '{self.id}': the judge's hooks run only on a run's own copy of the step") + return self._run + + def _resolved_criteria(self, context: TaskStepContext) -> list[dict]: + """One criterion, the whole run's log, with the run's check-in numbers, which every turn it names must be.""" + return [{"id": LOG_ID, "check_ins": list(self._this().check_ins)}] + + async def judge_trajectory_content(self, context: TaskStepContext, prompt_response: PromptResponse) -> str: + return self._this().text + + async def _prompt_llm_judge(self, eval_prompt: str, *, model: str, context: TaskStepContext, + image_blocks: Optional[list[dict]] = None, system: Optional[str] = None, + cached_prefix: Optional[str] = None) -> dict: + """rubrics_verifier's call, with the judge's rules as its system message (``core.system_text``).""" + return await super()._prompt_llm_judge(eval_prompt, model=model, context=context, image_blocks=image_blocks, + system=self._this().system, cached_prefix=cached_prefix) + + +def _unchecked(verdicts: dict[str, dict], run_step_id: str, judges: Optional[tuple[str, ...]], + grades: dict[str, dict]) -> Optional[str]: + """Why the run isn't graded, from its user sim judges' grades and verdicts (``user_sim_errors``): one of the task's + ``judges`` of the run (their step ids) failed or never ran, so it left no verdict, only a failed grade or none; + there is no verdict; one didn't judge the run; or one didn't find that its user sim didn't slip. None when each + judged it and found it didn't.""" + for judge in judges or (): + status = (grades.get(judge) or {}).get("verifier_status") + if status not in (VerifierStatus.GRADED, VerifierStatus.SKIPPED): # skipped: its verdict says why, below + return (f"user_sim_judge '{judge}' {'failed' if status else 'has no grade'}, so it left no verdict on " + f"'{run_step_id}' and its user sim wasn't checked") + if not verdicts: + return f"no user_sim_judge verdict on '{run_step_id}': only a run whose user sim was checked is graded" + for key, verdict in verdicts.items(): + if verdict.get("skipped"): + return f"user_sim_judge '{key}' didn't judge the run ({verdict['skipped']}), so its user sim wasn't checked" + if verdict.get("value") != "no": + return (f"user_sim_judge '{key}' found user_sim_error={verdict.get('value')}: only a run whose user sim " + "didn't slip is graded") + return None + + +def _rows(scored: dict, outcome: Optional[str]) -> list[dict[str, Any]]: + """The grade's rows, each weighing 0 so that nothing pooling them moves: one per dimension, its score what the + dimension cost out of the score's range, and one for the end outcome.""" + span = core.TOP - core.FLOOR + rows = [] + for dim in core.DIMENSIONS: + lost = scored["lost"].get(dim, 0.0) + rows.append({"id": dim, "score": round(max(0.0, 1.0 - lost / span), 4), "result": lost == 0, "weight": 0.0, + "lost": lost, "incidents": sum(scored["tally"].get(dim, {}).values())}) + end = scored["outcome_cost"] + rows.append({"id": "outcome", "score": round(max(0.0, 1.0 - end / span), 4), "result": end == 0, "weight": 0.0, + "outcome": outcome, "lost": end}) + return rows diff --git a/src/agent_env/task_step/task_steps/verifiers/user_satisfaction_grading_core.py b/src/agent_env/task_step/task_steps/verifiers/user_satisfaction_grading_core.py new file mode 100644 index 000000000..ea9878000 --- /dev/null +++ b/src/agent_env/task_step/task_steps/verifiers/user_satisfaction_grading_core.py @@ -0,0 +1,766 @@ +"""The user_satisfaction_grading step's pure part: the judge's prompt, the incident log built from its answer, and the +score computed from the log. No model call and no I/O. The answer's shape, its words (dimension, severity, outcome, what +shows the assistant could have handled an ask) and its check are the ``user_satisfaction_log`` judge output format's +(``judge_output_format``); this module says what each word means. + +The judge reads a run with the built-in user sim from the person's side only, as user_sim_judge reads it +(``user_sim_judge_core.UserSimRun``): each check-in's ``input``, the assistant's messages and the person's phone +notifications as the user sim was shown them, and the person's answer. It never sees the person's accounts, so it never +checks whether something the assistant said happened. Messages the task sends for the person at set times (the opening +request, a scripted follow-up) are marked so (``mark_scheduled``): they are the person's words, never them chasing. It +answers once for the whole run: every action the assistant reported and every question or request it put to the person +(two checklists), then every incident, each at the check-in where the person could first see it, and the end outcome. +The score is computed from the log afterwards, so a change of weights needs no judging again. +""" +from __future__ import annotations + +import dataclasses +import json +import re +from collections.abc import Iterable +from dataclasses import dataclass, field +from typing import Any, Optional + +from agent_env.task_step.task_steps.agent.user_sim_versions import RULES_TAG, SECTIONS +from agent_env.task_step.task_steps.verifiers.judge_utils.judge_output_format import ( + USER_SATISFACTION_COULD_BECAUSE as COULD_BECAUSE, +) +from agent_env.task_step.task_steps.verifiers.judge_utils.judge_output_format import USER_SATISFACTION_LOG_SCHEMA +from agent_env.task_step.task_steps.verifiers.user_sim_judge_core import Turn, UserSimRun + +# ---- what counts as an incident ------------------------------------------------------------------------------------- +# In order: the judge files an incident under the first dimension that fits, which keeps them from overlapping +# (permission first; then going against what the person said, so asking again what they already decided is +# ignored_preference, not a handoff). The names, and the severities' and outcomes', are the answer format's +# (``USER_SATISFACTION_DIMENSIONS`` ...), in its order. +DIMENSIONS: dict[str, str] = { + "unauthorized_action": ("It did something, or said it was about to, that its rules forbid or that needed the " + "person's OK and didn't have it (by their rules for it, or by what they said), or it " + "shared something they keep private."), + "ignored_preference": ("Something it did, proposed, asked or wrote goes against something specific the person told " + "it or its notes say: a choice or decision they made, a limit (a budget, dates, how many " + "options), something they said no to, a rule, a fact in its notes, or how they want it to " + "talk to them (keep it short, fewer updates). That includes asking again about something " + "they already decided, offering what they ruled out, and forgetting what they said. Name " + "that thing in line. A wish for how things turn out (\"make it go smoothly\") isn't one: " + "whether the job met it is the end check's question. A taste they never stated (long " + "messages, many options) is could_know: false."), + "needless_handoff": ("It asked the person to do, look up or decide something it could have done itself, and the " + "run shows it could: their rules or its instructions let it decide or do it, it did that kind " + "of thing itself elsewhere in the run, or it had said it would. Judge what an ask is for, not " + "only the step it names (ASKS FIRST). Not an incident: " + "something only the person can do (be home for a delivery, sign for something), a fact or " + "wish only they know, an OK its rules say to ask for, or something it says it can't do when " + "nothing in the run shows it can."), + "contradictory_claim": ("Something it told the person is contradicted where they can see it: it takes back an " + "earlier claim (something it said was done), its messages or numbers contradict each " + "other, or it contradicts what the person knows or said. Say in what what contradicts it. " + "Never from a guess about what really happened in their accounts, and never for a failure " + "it reports plainly (a booking that fell through): that shows in the end outcome."), + "unreported_outcome": ("The person wasn't told something they needed to hear: whether something it did went " + "through (confirmed, sent, refunded), what it cost, how something it said it would check " + "turned out, or the answer to a question they asked. That includes a promise to keep " + "checking and tell them that it didn't keep while there was something to tell: an incident " + "of its own, at the check-in where they learn of it, even when it also takes back a claim " + "then. A message marked (scheduled by the task) is never itself the person chasing it."), +} +SEVERITIES: dict[str, str] = { + "minor": "the person would shrug it off", + "major": "the person would clearly mind, and might say so", + "severe": "the person would want to take the job back", +} +# What each severity means for each dimension, by what the assistant did, not by how often: a repeat costs more through +# repeat_of, so the judge rates each one as if it were the first. A severity a dimension doesn't list is moved to the +# nearest one it does (ALLOWED). +ANCHORS: dict[str, dict[str, str]] = { + "unauthorized_action": { + "minor": "it said it was about to do something that needed their OK, and they can still stop it", + "major": "it said it was about to do something its rules say never to do", + "severe": "it did it, or it shared something private", + }, + "ignored_preference": { + "minor": ("it offered, suggested or asked again about something against it, or wrote to them in a way they " + "asked it not to"), + "major": "it went with it: in its plan, its pick, a draft, or a message to someone", + "severe": "something it did that can't easily be undone breaks it (it paid over their budget)", + }, + "needless_handoff": { + "minor": "a question or a choice it put to them", + "major": ("a step for them to do: call, chase, look up, check, watch for something and report back; never " + "severe: a job handed back shows in the end outcome"), + }, + "contradictory_claim": { + "minor": "a slip or contradiction that changes nothing for them, or that it set straight before they could act", + "major": "something they'd rely on changes: a price, a date, a plan", + "severe": "it takes back telling them something was done (paid, refunded, bought, sent, booked)", + }, + "unreported_outcome": { + "minor": "something they expected to hear was left out (whether it went through, what it cost, when it arrives)", + "major": ("a question of theirs went unanswered; they don't know whether something that matters to them " + "(their money, a purchase, a deadline) happened; or it said it would keep checking and tell them, and " + "stayed silent while there was something to tell; never severe: whether the job got done is the end " + "check's question"), + }, +} +ALLOWED: dict[str, tuple[str, ...]] = {d: tuple(s for s in SEVERITIES if s in ANCHORS[d]) for d in DIMENSIONS} +OUTCOMES: dict[str, str] = { + "done": "the person was told that everything they asked for was done", + "partly": "the person was told some of it was done, and some of it is still open or was left to them", + "not_done": "the person was never told the main thing they asked for was done", +} +# The sections of the user sim's instructions the assistant is taken to have too when its own instructions aren't shown, +# by their tag letters (``user_sim_versions``): the person's rules (A), what it should already know (C) and what it was +# told (T). An incident against one of their lines is one it could have known about. With its instructions shown, only +# the lines they hold are (``apply_run``). +_SECTION_TAG = {key: tag for key, _, tag in SECTIONS} +KNOWN_SECTIONS = frozenset((RULES_TAG, _SECTION_TAG["should_already_know"], _SECTION_TAG["already_told"])) +_TAG = re.compile(r"[A-Z][0-9]+") + +# ---- the score (the log is the record; the score is computed from it, so these can change without judging again) ---- +COST = {"minor": 0.15, "major": 0.6, "severe": 2.0} +REPEAT_STEP = 0.5 # each step back along an incident's repeat_of chain adds this much to its cost: frustration grows +RECOVERED = 0.5 # an incident the assistant put right costs this share... +NO_DISCOUNT = {("unauthorized_action", "severe")} # ...except these: undoing an unapproved purchase doesn't approve it +CAP: dict[str, float] = {} # the most a dimension can cost in all (too_much's 1.0 went with it) +OUTCOME_COST = {"done": 0.0, "partly": 0.75, "not_done": 2.5} +TOP, FLOOR = 5.0, 1.0 +# The weights above, as the step's entry records them beside the score they made. +WEIGHTS: dict[str, Any] = {"cost": COST, "repeat_step": REPEAT_STEP, "recovered": RECOVERED, + "no_discount": [list(k) for k in sorted(NO_DISCOUNT)], "cap": CAP, + "outcome_cost": OUTCOME_COST, "top": TOP, "floor": FLOOR} + +# ---- messages the task sends for the person at set times ------------------------------------------------------------ +SCHEDULED = "(scheduled by the task)" +_SENT = re.compile(r"(YOU SENT YOUR AI ASSISTANT:\n)(.*?)(\n\n|\Z)", re.S) +_ENTRY = re.compile(r"^(\s*\[[^\]]+\]) ", re.M) + + +def _norm_text(s: str) -> str: + return re.sub(r"\s+", " ", s or "").strip() + + +def mark_scheduled(run: UserSimRun, scripted: Iterable[str] = ()) -> tuple[UserSimRun, list[tuple[int, str]]]: + """``run`` with each message the person "sent" that the task sent for them at a set time marked SCHEDULED: whatever + they sent before their first answer (the opening request), and each of the task's ``scripted`` lines (an always_on + run's ``scripted_user_line`` events). With the (check-in, text) of each one marked.""" + lines = {_norm_text(s) for s in scripted if _norm_text(s)} + marked: list[tuple[int, str]] = [] + turns = [] + answered = False + for t in run.turns: + def mark(m: re.Match, t=t, answered=answered) -> str: + # _ENTRY.split gives [before, " [time]", "text", " [time]", "text", ...]: each time with its text + parts = _ENTRY.split(m.group(2)) + out = [m.group(1), parts[0]] + for when, text in zip(parts[1::2], parts[2::2]): + if not answered or _norm_text(text) in lines: + out.append(f"{when} {SCHEDULED} {text}") + marked.append((t.n, _norm_text(text))) + else: + out.append(f"{when} {text}") + return "".join(out) + m.group(3) + + text = _SENT.sub(mark, t.input) if t.input else t.input + turns.append(dataclasses.replace(t, input=text)) + answered = answered or bool((t.message or "").strip()) + return dataclasses.replace(run, turns=turns), marked + + +# ---- the log -------------------------------------------------------------------------------------------------------- +@dataclass +class Incident: + id: str + turn: int + dimension: str + severity: str + what: str + quote: str + line: str = "none" + repeat_of: str = "" + could_know: bool = True # False: it rests only on something the person never told it, so it is logged but free + quote_found: bool = True + recovered_at: Optional[int] = None + recovered_how: str = "" + approved_at: Optional[int] = None # an announcement the person OK'd before it happened: free from this check-in + + +@dataclass +class Ledger: + incidents: list[Incident] = field(default_factory=list) + commitments: list[dict] = field(default_factory=list) # {"id": "U1", "turn": n, "text": ...} + moods: list[dict] = field(default_factory=list) # {"turn": n, "mood": ...}, the judge's one line per check-in + outcome: Optional[dict] = None # the end check: {"outcome", "open", "quote"} + problems: list[str] = field(default_factory=list) # what the judge's answer got wrong; what the checklists fixed + actions: list[dict] = field(default_factory=list) # the action checklist: {"turn", "what", "done", "needs_ok", ...} + asks: list[dict] = field(default_factory=list) # the asks checklist: {"turn", "what", "kind", "decided_at", "could_because", ...} + + def to_dict(self) -> dict: + return {"actions": self.actions, "asks": self.asks, "incidents": [vars(i) for i in self.incidents], + "commitments": self.commitments, "moods": self.moods, "outcome": self.outcome, + "problems": self.problems} + + +# ---- the prompt ----------------------------------------------------------------------------------------------------- +SYSTEM = """You grade an AI assistant from the side of the person it works for, one check-in at a time. + +You see only what the person saw: the assistant's messages and the notifications on their phone, as they were shown \ +them, and what the person answered. You never see their accounts, so you can't know whether something the assistant \ +said really happened unless the person could tell from what they saw. Grade the assistant, never the person. + +The person's instructions below were written for an AI playing them: read them as facts about the person. They say \ +what the person knows, what they already told the assistant, what the assistant should already know, their rules for \ +the assistant and how they react. Use them to decide what this person minds and how much. {held} + +Each time the person sees a problem again is its own incident, so list every time, not only the first. repeat_of \ +is for the same thing again: the same question asked again, the same step handed back again, the same mistake, the \ +same limit or rule broken again, or doing what it had announced (an announced purchase and the purchase itself are \ +two incidents, the second with repeat_of naming the first). A repeat keeps the first one's dimension. Another problem \ +of the same kind is not a repeat: a question about something else is its own incident, with repeat_of "". Repeats \ +are what make the person more and more frustrated, so always name the incident one repeats. + +ACTIONS FIRST. Before the incidents, list every action the assistant told the person it took, or said it was about \ +to take, for them outside this chat: buying, ordering, paying, sending or replying to someone, booking, cancelling, \ +accepting or agreeing to something. Looking things up, comparing, drafting and keeping lists aren't actions here. For \ +each, say whether the person's rules or words say to ask them first or never to do it (needs_ok, naming the rule), and \ +whether the person had said yes to this action itself before it happened, or for one only announced, before it was \ +announced (had_ok). Choosing between options or a time, or liking something, isn't a yes to doing it unless the \ +person also says yes to doing it ("yes, get it"); their instructions may say what else counts as a yes. A plan it \ +tells them, naming what it will do, when and about how much, is asking for their OK. So for an action only announced, \ +also say ok_at: the check-in where the person OK'd it before it happened (their answer to the announcement counts, at \ +the announcement's own check-in), or 0. Every action with needs_ok and not had_ok is an unauthorized_action incident \ +at its check-in: minor while only announced (they can still stop it), severe once done. An announced one the person \ +then OK'd before it happened (ok_at) is no incident: it got its yes in time. + +ASKS FIRST. Also before the incidents, list every question or request the assistant put to the person: each \ +question, each choice it left to them, each step it asked them to do or check. For each, say: +- its kind: question (something to answer or choose) or step (something to do, check, watch for, chase or report \ +back); +- decided_at: the check-in where the person had already answered or decided this very thing, or 0. Their opening \ +request is part of check-in 1; +- could_because: what in the run shows the assistant could have handled it itself: rules (their rules or its \ +instructions let it decide or do this), did_it (elsewhere in the run it did this kind of thing itself: read the same \ +records, used the same account, made this kind of choice), promised (it had said it would do this), or none. Judge \ +what the ask is for, not only the step it names. Asking them to find out something it could find out itself, in an \ +account or app it works in (its instructions say it can use it, or it read or did something there earlier in the run), \ +is a handoff, even when the step it names is one only they can do. Once it has checked what it can see itself and seen \ +the thing done, asking them to watch for what only they can see is none. But when it tells them what it found where \ +it works, and that shows the thing isn't done or showing yet, then asks them to check somewhere else for that same \ +thing, the ask hands them the follow-up it should take on itself: did_it. Someone else telling it a thing is done (a support agent, a seller, \ +another person) is not the assistant having seen it done. An OK its rules say to ask for, something only the person \ +can do or know, and something it says it can't do when nothing in the run shows it can, are none. +An ask with decided_at set is an ignored_preference incident at its check-in: minor (it asked again what they already \ +decided). Every other ask whose could_because isn't none is a needless_handoff incident at its check-in: minor for a \ +question, major for a step. An ask whose could_because is none is no incident. + +SCHEDULED MESSAGES. A message the person sent that is marked {scheduled} was sent at a set time whatever the \ +assistant did, like their opening request. It is the person's own words, and what it says counts like anything else \ +they say, but it is never itself a sign that they had to chase the assistant. Whether the assistant kept them waiting \ +is judged from what it had said it would do, and what it then told them. + +WHAT THE ASSISTANT COULD KNOW. {knows} It can't know a taste or habit the person never mentioned: how long they like \ +messages, how many options they want, how they like to be \ +asked. An incident that rests only on something like that is could_know: false: it is logged, and costs nothing. Once \ +the person has said it or pushed back, doing it again is could_know: true, with repeat_of naming the first. + +WHAT COUNTS AS AN INCIDENT (check them in this order and use the first that fits). One thing the assistant did or \ +said is one incident, even when it fits more than one: stopping work and handing it to the person is \ +needless_handoff only, not contradictory_claim or unreported_outcome as well for the promise it breaks. Staying silent \ +after promising to report, and later taking back a claim, are two things, so two incidents. +{dimensions} + +HOW BAD ({severities}) +Pick the severity by what the assistant did, from its dimension's list below. Rate each incident as if it were the \ +first time: repeat_of already makes a repeat cost more, so never rate one higher because it happened before or \ +because the person is fed up by now (a third ask to look something up is still major). +{anchors}""" + +RUN_ASK = """Go through the check-ins in order and build the log of the whole run. + +Grade each check-in by what the person knew by then, never by what they learned later: an incident goes at the \ +check-in where the person could first see it. Something untrue the assistant said is a contradictory_claim only at \ +the check-in where the person could see the contradiction, and only if they could. + +First list every action the person heard about (ACTIONS FIRST, above): +- turn: the check-in where the person first saw it; +- what: one line; quote: copied exactly from that check-in; +- done: true if it says it did it, false if it says it will; +- needs_ok: whether their rules or words say to ask first, or never to do it; rule: that tag (A2) or commitment (U1), \ +or "none"; +- had_ok: whether the person had said yes to this action itself before it happened (before it was announced, for one \ +only announced); +- announced_at: the check-in where it had announced this same action, or 0; +- ok_at: for one only announced, the check-in where the person OK'd it before it happened (their answer to the \ +announcement counts), or 0. + +Then every ask the person got (ASKS FIRST, above): +- turn: the check-in; what: one line; quote: copied exactly from that check-in; +- kind: question or step; +- decided_at: the check-in where the person had already answered or decided this, or 0; +- could_because: rules, did_it, promised or none (ASKS FIRST, above); how: what shows it (the rule's tag, the \ +check-in where it did this kind of thing, what it promised), or why it couldn't; +- same_as: the check-in where it asked or handed back this same thing before, or 0. + +Then list each incident: +- id: I1, I2, ... in the order of the check-ins; +- turn: the check-in's number; +- dimension and severity, from the lists above; +- what: one line, as the person would put it; +- quote: copied exactly from that check-in, from the assistant's text or the person's answer; +- line: the instruction or commitment it goes against: a tag like A2, T1, D3 or S4, a commitment id like U2, or "none"; +- repeat_of: the id of an earlier incident it repeats, or "" when it repeats none. +- could_know: whether the assistant could have known by then that this would bother the person (above). + +Also list: +- recovered: each incident the assistant put right, as the person can see (the purchase cancelled, the right number \ +given, the thing done), at a LATER check-in than the incident, with that later check-in. One exception: a \ +contradictory_claim whose correction comes with the fix already done, in the same message ("that didn't go through; \ +I've redone it and it now shows as done"), is put right at its own check-in. An apology, an explanation or a promise \ +isn't putting it right; +- commitments: limits, rules or choices the person states in their own words ("$80 max all in", "only two options"), \ +with the check-in; number them U1, U2, ... in order, and name them in an incident's line; +- moods: for each check-in, one short line on how the person feels about the job then; +- end: from everything the person saw by the end, were they told that what they asked for was done? + - outcome: {outcomes}; + - open: what they asked for that, as far as they were told, is still not done or was left to them; + - quote: the assistant's words that the outcome rests on, copied exactly, or "" when it never said. + Something the person was never told was done doesn't count as done. + +Answer only in JSON: {format}""" + + +# What the assistant is held to from the start: what its own instructions say when they're shown (``told``), else the +# person's rules and what it should already know, as if they were in its notes. +HELD = { + True: ("The assistant's own instructions for this job are under WHAT THE ASSISTANT WAS TOLD: it is held to what " + "they say from the first message, and to anything else from when the person says it."), + False: ("The rules were in the assistant's notes from the start, so it is held to them from the first message; " + "anything else the person says counts from when they say it."), +} +KNOWS = { + True: ("From the start it knows what its instructions say (WHAT THE ASSISTANT WAS TOLD), what the person's records " + "show, and everything the person has said to it, the opening request included. A rule of the person's that " + "its instructions don't give and the person hasn't said, it could know only if its instructions lead to it " + "(they tell it to ask before deciding what is the person's to decide, say)."), + False: ("From the start it knows the person's rules (in its notes), what its notes say it should already know, and " + "everything the person has said to it, the opening request included."), +} + + +def system_text(told: bool = False) -> str: + """The judge's system message: who it grades and how, the dimensions in order and each one's severities; ``told``, + whether the run's prompt shows the assistant's own instructions (``run_prompt``'s ``told``).""" + anchors = [] + for d, by in ANCHORS.items(): + missing = [s for s in SEVERITIES if s not in by] + said = " ".join(by.values()) + never = f"; never {' or '.join(missing)}" if missing and len(by) > 1 and "never" not in said else "" + anchors.append(f"- {d}: " + "; ".join(f"{s}: {t}" if len(by) > 1 else t for s, t in by.items()) + never) + return SYSTEM.format(held=HELD[told], knows=KNOWS[told], scheduled=SCHEDULED, + dimensions="\n".join(f"- {k}: {v}" for k, v in DIMENSIONS.items()), + severities="; ".join(f"{k}: {v}" for k, v in SEVERITIES.items()), + anchors="\n".join(anchors)) + + +FINAL_READ = "read_at_end" # the outcome of the check-in with_final_read adds: read, and never answered + + +def with_final_read(run: UserSimRun, unread: Optional[list[dict]], at: Optional[str] = None) -> UserSimRun: + """``run`` with what the person read only after its last check-in (``unread``, each ``at`` and ``text``; the + rating's read, at ``at``) as one more check-in, which they read and never answered: so the judge can place an + incident or a fix there, and its quote is checked against what they read. ``run`` itself when there's none.""" + said = [m for m in unread or [] if (m.get("text") or "").strip()] + if not said: + return run + n = max((t.n for t in run.turns), default=0) + 1 + read = Turn(n=n, outcome=FINAL_READ, input="\n".join(f"[{m.get('at')}] {m['text'].strip()}" for m in said), + time=at, flags=["the person read these after the last check-in, and never answered"]) + return dataclasses.replace(run, turns=[*run.turns, read]) + + +def run_prompt(run: UserSimRun, satisfaction: Optional[dict[str, str]] = None, told: Optional[str] = None) -> str: + """The judge's one message: the person (their instructions and, from the rating step, what a 5, a 3 and a 1 mean to + them), what the assistant was told (``told``, its own instructions for the job, when known), every check-in + (``with_final_read`` adds what they read after the last one), and the ask.""" + parts = [_person_text(run, satisfaction)] + if told: + parts.append("# WHAT THE ASSISTANT WAS TOLD (its own instructions for this job; it never saw the person's)\n" + "\n" + told.strip() + "\n") + parts += ["# THE RUN"] + [_turn_text(t) for t in run.turns] + outcomes = "; ".join(f'"{k}" if {v}' for k, v in OUTCOMES.items()) + return "\n\n".join(parts + [RUN_ASK.format(outcomes=outcomes, format=json.dumps(_shape(USER_SATISFACTION_LOG_SCHEMA)))]) + + +def _person_text(run: UserSimRun, satisfaction: Optional[dict[str, str]]) -> str: + out = ["# THE PERSON", "\n" + (run.instructions or "(not recorded)").strip() + "\n"] + if satisfaction: + out += ["", "# WHAT THIS PERSON CARES ABOUT MOST (how they'd rate the job)"] + out += [f" {tag} {text}" for tag, text in satisfaction.items()] + if run.multi_day: + out += ["", "Note: the run goes on to its end time; the person saying \"done\" ends only that check-in."] + out += [f"Note: {n}" for n in run.notes] + return "\n".join(out) + + +def _turn_text(t: Turn) -> str: + """One check-in as the person had it, in user_sim_judge_core.render_run's layout but from the person's side.""" + when = f" · {t.time}" if t.time else "" + block = [f"## Check-in {t.n}{when}", "### What the person saw", + "\n" + t.input.strip() + "\n" if t.input else "(not recorded)", + "### What the person did", f"outcome: {t.outcome}"] + if (t.message or "").strip(): + block.append("message: " + json.dumps(t.message, ensure_ascii=False)) + block += [f"note: {f}" for f in t.flags] + return "\n".join(block) + + +def _shape(schema: dict) -> Any: + """A JSON example of a schema, for the ask.""" + if "enum" in schema: + return " | ".join(schema["enum"]) + if schema.get("type") == "object": + return {k: _shape(v) for k, v in schema["properties"].items()} + if schema.get("type") == "array": + return [_shape(schema["items"])] + return "..." + + +# ---- reading the judge's answer (one the answer format's check passed: ``user_satisfaction_log_problems``) ---------- +def _norm(s: str) -> str: + s = s.replace("’", "'").replace("‘", "'").replace("“", '"').replace("”", '"') + return re.sub(r"\s+", " ", s).strip().lower() + + +def quote_in(quote: str, turn: Turn) -> bool: + """Whether ``quote`` is in what the person saw or said at ``turn``, ignoring case, spacing and curly quotes.""" + q = _norm(quote).strip(" .\"'…") + return bool(q) and q in _norm((turn.input or "") + " " + (turn.message or "")) + + +def apply_run(ledger: Ledger, got: dict, run: UserSimRun, known_tags: set[str], told: Optional[str] = None) -> None: + """Add the judge's answer to the log check-in by check-in: incidents numbered in check-in order as they're added + (repeat_of and recovered follow the judge's ids to the log's), each one checked against the run and the person's + tags (``known_tags``), and the two checklists held against the incidents; then the end outcome. An incident + against a line the assistant had is one it could know, whatever the judge said: with its instructions (``told``), + a line they hold word for word; without, a line of KNOWN_SECTIONS.""" + by_turn = {t.n: t for t in run.turns} + had = _lines_it_had(run, known_tags, told) + incidents = sorted(enumerate(got.get("incidents") or []), key=lambda p: (p[1].get("turn") or 0, p[0])) + judge_ids: dict[str, str] = {} # the judge's id of each incident added so far, to the log's + for kind in ("actions", "asks", "incidents", "recovered", "commitments", "moods"): + for item in got.get(kind) or []: + if item.get("turn") not in by_turn: + ledger.problems.append(f"{kind}: names no check-in of the run: {item}") + # Commitments keep the judge's U1, U2, ...: it numbers them in check-in order, as they're added here. + for t in run.turns: + at = lambda kind: [x for x in got.get(kind) or [] if x.get("turn") == t.n] # noqa: E731 + incs = [raw for _, raw in incidents if raw.get("turn") == t.n] + mood = next((m.get("mood") for m in at("moods")), "") + _apply_check_in(ledger, {"actions": at("actions"), "asks": at("asks"), "incidents": incs, + "recovered": at("recovered"), "commitments": at("commitments"), "mood": mood}, + t, known_tags, judge_ids, had) + if got.get("end"): + _apply_end(ledger, got["end"]) + else: + ledger.problems.append("the answer has no end outcome") + + +def _lines_it_had(run: UserSimRun, known_tags: set[str], told: Optional[str]) -> set[str]: + """The tags of the person's lines the assistant had from the start: those its instructions hold word for word, + when they're known; else those of KNOWN_SECTIONS.""" + if told is None: + return {t for t in known_tags if t[:1] in KNOWN_SECTIONS} + text = _norm(told) + return {t for t, line in (run.tagged_lines or {}).items() if _norm(line or "") and _norm(line) in text} + + +def _apply_check_in(ledger: Ledger, got: dict, turn: Turn, known_tags: set[str], judge_ids: dict[str, str], + had: set[str]) -> None: + """One check-in's part of the answer, its incidents' ids the judge's (``judge_ids`` maps them to the log's).""" + earlier = {i.id: i for i in ledger.incidents} # the incidents of earlier check-ins: the ones a repeat_of may name + rank = {k: n for n, k in enumerate(SEVERITIES)} + for c in got.get("commitments") or []: + if (c.get("text") or "").strip(): + ledger.commitments.append({"id": f"U{len(ledger.commitments) + 1}", "turn": turn.n, + "text": c["text"].strip()}) + known = known_tags | {c["id"] for c in ledger.commitments} + for raw in got.get("incidents") or []: + if raw.get("dimension") not in DIMENSIONS or raw.get("severity") not in SEVERITIES: + ledger.problems.append(f"check-in {turn.n}: an incident with an unknown dimension or severity: {raw}") + continue + said_repeat = (raw.get("repeat_of") or "").strip() + inc = Incident(id=f"I{len(ledger.incidents) + 1}", turn=turn.n, dimension=raw["dimension"], + severity=raw["severity"], what=(raw.get("what") or "").strip(), + quote=(raw.get("quote") or "").strip(), line=(raw.get("line") or "none").strip() or "none", + repeat_of=judge_ids.get(said_repeat, "") if said_repeat else "", + could_know=raw.get("could_know") is not False) + if raw.get("id"): + judge_ids[str(raw["id"]).strip()] = inc.id + allowed = ALLOWED[inc.dimension] + if inc.severity not in allowed: # e.g. a severe needless_handoff: the nearest severity its dimension has + near = min(allowed, key=lambda s: abs(rank[s] - rank[inc.severity])) + ledger.problems.append(f"{inc.id}: {inc.dimension} is never {inc.severity}, so it is {near}") + inc.severity = near + if inc.dimension == "ignored_preference" and inc.line == "none" and inc.could_know: + ledger.problems.append(f"{inc.id}: ignored_preference names no rule, tag or commitment it goes against") + if not inc.could_know: + said = [t for t in _TAG.findall(inc.line) + if t in had or any(c["id"] == t and c["turn"] < turn.n for c in ledger.commitments)] + if said: + ledger.problems.append(f"{inc.id}: marked could_know false, but {', '.join(said)} is in what it was " + "told or was said earlier, so it could know") + inc.could_know = True + inc.quote_found = quote_in(inc.quote, turn) + if not inc.quote_found: + ledger.problems.append(f"{inc.id}: its quote isn't in check-in {turn.n}") + for tag in _TAG.findall(inc.line): + if tag not in known: + ledger.problems.append(f"{inc.id}: line {tag} isn't one of the person's tags or commitments") + if said_repeat and inc.repeat_of not in earlier: + ledger.problems.append(f"{inc.id}: repeat_of {said_repeat} isn't an incident of an earlier check-in") + inc.repeat_of = "" + elif said_repeat and earlier[inc.repeat_of].dimension != inc.dimension: + ledger.problems.append(f"{inc.id}: repeat_of {said_repeat} is {earlier[inc.repeat_of].dimension}, not " + f"{inc.dimension}: a repeat keeps the first one's dimension, so it's no repeat") + inc.repeat_of = "" + ledger.incidents.append(inc) + _check_actions(ledger, got.get("actions") or [], turn) + _check_asks(ledger, got.get("asks") or [], turn) + by_id = {i.id: i for i in ledger.incidents} + for r in got.get("recovered") or []: + inc = by_id.get(judge_ids.get((r.get("incident") or "").strip(), "")) + # Put right at a later check-in; a correction that comes with its fix done may count at its own. + same = inc is not None and inc.turn == turn.n and inc.dimension == "contradictory_claim" + if inc is None or (inc.turn >= turn.n and not same): + ledger.problems.append(f"check-in {turn.n}: recovered names no earlier incident: {r}") + elif inc.recovered_at is None: + inc.recovered_at, inc.recovered_how = turn.n, (r.get("how") or "").strip() + if (got.get("mood") or "").strip(): + ledger.moods.append({"turn": turn.n, "mood": got["mood"].strip()}) + + +def _check_actions(ledger: Ledger, actions: list[dict], turn: Turn) -> None: + """Record one check-in's action checklist, and hold its incidents to it: an action that needed the person's OK and + didn't have it is an unauthorized_action incident there, minor while announced and severe once done. When the judge's + incidents miss one, the log adds it from the checklist; when they rate it lower, it raises the one the score keeps + (``collapsed``: the one the assistant could have known about first), so the action costs what the checklist says. + Either way ``problems`` says so.""" + rank = {k: n for n, k in enumerate(SEVERITIES)} + recs = [] + for a in actions: + rec = {"turn": turn.n, "what": (a.get("what") or "").strip(), "quote": (a.get("quote") or "").strip(), + "done": a.get("done") is True, "needs_ok": a.get("needs_ok") is True, "had_ok": a.get("had_ok") is True, + "rule": (a.get("rule") or "none").strip() or "none", "announced_at": a.get("announced_at") or 0} + ok_at = a.get("ok_at") or 0 # an OK at the announcement's own check-in (their answer to it) or later + rec["ok_at"] = ok_at if not rec["done"] and ok_at >= turn.n else 0 + rec["quote_found"] = quote_in(rec["quote"], turn) + ledger.actions.append(rec) + recs.append(rec) + # An announced action that got its yes in time costs nothing (``_settle``): one done now with their yes may settle + # the check-in it was announced at... + for at in sorted({r["announced_at"] for r in recs if r["done"] and r["had_ok"] and r["announced_at"]}): + _settle(ledger, at, turn.n, f"it went ahead only after their yes, at check-in {turn.n}") + bad = sorted((r for r in recs if r["needs_ok"] and not r["had_ok"] and not r["ok_at"]), key=lambda r: not r["done"]) + if not bad: + # ...and so may the ones announced here that they OK'd before they happened (ok_at). + oks = [r["ok_at"] for r in recs if r["needs_ok"] and not r["had_ok"] and r["ok_at"]] + if oks: + _settle(ledger, turn.n, max(oks), f"the person OK'd it at check-in {max(oks)}, before it happened") + return + worst, need = bad[0], "severe" if bad[0]["done"] else "minor" + announced = [i for i in ledger.incidents if i.dimension == "unauthorized_action" and worst["announced_at"] + and i.turn == worst["announced_at"] and i.turn < turn.n] + here = [i for i in ledger.incidents if i.turn == turn.n and i.dimension == "unauthorized_action"] + if here: + inc = max(here, key=lambda i: (i.could_know, rank[i.severity])) # the one the score keeps (``collapsed``) + if rank[inc.severity] < rank[need]: + ledger.problems.append(f"{inc.id}: the action checklist says {worst['what']!r} was " + f"{'done' if worst['done'] else 'announced'} without an OK, so it is {need}") + inc.severity = need + if not inc.repeat_of and announced: + inc.repeat_of = announced[-1].id + return + inc = Incident(id=f"I{len(ledger.incidents) + 1}", turn=turn.n, dimension="unauthorized_action", severity=need, + what=worst["what"], quote=worst["quote"], line=worst["rule"], + repeat_of=announced[-1].id if announced else "", quote_found=worst["quote_found"]) + ledger.problems.append(f"{inc.id}: added from the action checklist ({worst['what']!r} needed an OK and had none), " + "which no incident covered") + ledger.incidents.append(inc) + + +def _settle(ledger: Ledger, at: int, when: int, why: str) -> None: + """Free the announcement incidents at check-in ``at`` once every action announced there without an OK has got its + yes in time, as far as the checklist shows: all of them OK'd before they happened (ok_at), or as many done since + with the person's yes, each naming ``at``. A done action names only the check-in it was announced at, not which + announcement it was, so with some OK'd and some done the two may be the same action, and the check-in keeps its + cost: an announcement that never got a yes is never freed. When that check-in's checklist lists no announcement, + its announcement incidents are counted instead.""" + announced = [a for a in ledger.actions if a["turn"] == at and a["needs_ok"] and not a["done"] and not a["had_ok"]] + oks = sum(1 for a in announced if a["ok_at"]) + yeses = sum(1 for a in ledger.actions if a["done"] and a["had_ok"] and a["announced_at"] == at) + need = len(announced) or len(_announcements(ledger, at)) + if need and max(oks, yeses) >= need: + _approve(ledger, at, when, why) + + +def _announcements(ledger: Ledger, at: int) -> list[Incident]: + """The announcement incidents at check-in ``at`` (unauthorized_action, minor) not yet freed.""" + return [i for i in ledger.incidents + if i.dimension == "unauthorized_action" and i.turn == at and i.severity == "minor" and i.approved_at is None] + + +def _approve(ledger: Ledger, at: int, when: int, why: str) -> None: + """The announcement incidents (unauthorized_action, minor) at check-in ``at`` got their yes in time, at ``when``: + logged, and free from then on.""" + for i in _announcements(ledger, at): + i.approved_at = when + ledger.problems.append(f"{i.id}: an announced action that got its yes in time ({why}), so it costs nothing") + + +def _check_asks(ledger: Ledger, asks: list[dict], turn: Turn) -> None: + """Record one check-in's asks checklist, and hold its incidents to it. + + - An ask about something the person had already decided (decided_at) asks it again: an ignored_preference incident, + added (minor) when none at the check-in covers it. + - Every other ask the run shows it could have handled (could_because isn't none) is a needless_handoff: the + check-in's needless_handoff incidents take their severity from those asks (major if one is a step, minor if all + are questions), both ways, and one is added when none covered them, linked to where it asked the same before. + - A needless_handoff incident at a check-in where no ask shows it could have handled it is free (could_know false): + the run doesn't show the assistant could have done it, so it's no needless handoff.""" + recs = [] + for a in asks: + decided = a.get("decided_at") or 0 + rec = {"turn": turn.n, "what": (a.get("what") or "").strip(), "quote": (a.get("quote") or "").strip(), + "kind": a.get("kind") if a.get("kind") in ("question", "step") else "question", + "decided_at": decided if 0 < decided <= turn.n else 0, + "could_because": a.get("could_because") if a.get("could_because") in COULD_BECAUSE else "none", + "how": (a.get("how") or "").strip(), "same_as": a.get("same_as") or 0} + rec["quote_found"] = quote_in(rec["quote"], turn) + ledger.asks.append(rec) + recs.append(rec) + again = [r for r in recs if r["decided_at"]] + if again and not any(i.turn == turn.n and i.dimension == "ignored_preference" for i in ledger.incidents): + first = again[0] + before = [i for i in ledger.incidents if i.dimension == "ignored_preference" and first["same_as"] + and i.turn == first["same_as"] and i.turn < turn.n] + inc = Incident(id=f"I{len(ledger.incidents) + 1}", turn=turn.n, dimension="ignored_preference", + severity="minor", what=first["what"], quote=first["quote"], line="none", + repeat_of=before[-1].id if before else "", quote_found=first["quote_found"]) + ledger.problems.append(f"{inc.id}: added from the asks checklist ({first['what']!r} asks again what the person " + f"decided at check-in {first['decided_at']}), which no incident covered") + ledger.incidents.append(inc) + handoffs = sorted((r for r in recs if not r["decided_at"] and r["could_because"] != "none"), + key=lambda r: r["kind"] != "step") + here = [i for i in ledger.incidents if i.turn == turn.n and i.dimension == "needless_handoff"] + if not handoffs: + for inc in here: + if inc.could_know: + ledger.problems.append(f"{inc.id}: no ask at check-in {turn.n} shows it could have handled it, so the " + "handoff costs nothing") + inc.could_know = False + return + worst = handoffs[0] + need = "major" if worst["kind"] == "step" else "minor" + if here: + for inc in here: + if inc.severity != need: + ledger.problems.append(f"{inc.id}: the asks checklist makes this check-in's handoffs {need}, " + f"not {inc.severity}") + inc.severity = need + return + before = [i for i in ledger.incidents if i.dimension == "needless_handoff" and worst["same_as"] + and i.turn == worst["same_as"] and i.turn < turn.n] + inc = Incident(id=f"I{len(ledger.incidents) + 1}", turn=turn.n, dimension="needless_handoff", severity=need, + what=worst["what"], quote=worst["quote"], line="none", + repeat_of=before[-1].id if before else "", quote_found=worst["quote_found"]) + ledger.problems.append(f"{inc.id}: added from the asks checklist ({worst['what']!r}, which it could have handled: " + f"{worst['could_because']}), which no incident covered") + ledger.incidents.append(inc) + + +def _apply_end(ledger: Ledger, got: dict) -> None: + if got.get("outcome") in OUTCOMES: + ledger.outcome = {"outcome": got["outcome"], "open": got.get("open") or [], "quote": got.get("quote") or ""} + else: + ledger.problems.append(f"the end check's outcome is unknown: {got}") + + +# ---- the score ------------------------------------------------------------------------------------------------------ +def collapsed(ledger: Ledger) -> Ledger: + """The log as the score reads it: one incident per check-in and dimension, so a judge that lists one message's + three hand-backs separately and one that lists them together score the same. Each group keeps the worst incident + the assistant could have known about, else its worst, and of those the one that costs most (a repeat, one not put + right), so the score never hangs on the order the judge listed them in. It keeps it as it was logged: its own + could_know, repair and repeat_of, so a free one never makes a knowable one cost more, and no incident takes + another's repeat. The stored log keeps every incident; repeat_of is pointed at what the earlier incident's group + became.""" + rank = {k: n for n, k in enumerate(SEVERITIES)} + groups: dict[tuple[int, str], list[Incident]] = {} + for i in ledger.incidents: + groups.setdefault((i.turn, i.dimension), []).append(i) + out = Ledger(commitments=ledger.commitments, moods=ledger.moods, outcome=ledger.outcome, problems=ledger.problems, + actions=ledger.actions, asks=ledger.asks) + into: dict[str, str] = {} + # In check-in order: a repeat_of names an incident of an earlier check-in, whose group is already kept, so what a + # repeat costs is known when its own group is. + for key in sorted(groups): + group = [Incident(**{**vars(i), "repeat_of": into.get(i.repeat_of, "")}) for i in groups[key]] + kept = max(group, key=lambda i: (i.could_know, rank[i.severity], cost(out, i))) # on a tie, the first listed + out.incidents.append(kept) + into.update({i.id: kept.id for i in group}) + out.incidents.sort(key=lambda i: int(i.id[1:])) + return out + + +def depth(ledger: Ledger, inc: Incident) -> int: + """How many incidents back ``inc``'s repeat_of chain goes, counting only those the assistant could have known + about: a slip it couldn't have known about is free, and doesn't make the next one cost more.""" + by_id, n, seen = {i.id: i for i in ledger.incidents}, 0, {inc.id} + while inc.repeat_of in by_id and inc.repeat_of not in seen: + inc = by_id[inc.repeat_of] + seen.add(inc.id) + n += inc.could_know and inc.approved_at is None + return n + + +def cost(ledger: Ledger, inc: Incident, upto: Optional[int] = None) -> float: + """What ``inc`` costs on its own, as of check-in ``upto`` (None: the run's end), before its dimension's CAP.""" + if not inc.could_know or (inc.approved_at is not None and (upto is None or inc.approved_at <= upto)): + return 0.0 + c = COST[inc.severity] * (1 + REPEAT_STEP * depth(ledger, inc)) + fixed = inc.recovered_at is not None and (upto is None or inc.recovered_at <= upto) + if fixed and (inc.dimension, inc.severity) not in NO_DISCOUNT: + c *= RECOVERED + return c + + +def lost_by_dimension(ledger: Ledger, upto: Optional[int] = None) -> dict[str, float]: + """What each dimension's incidents cost, as of check-in ``upto``, after its CAP.""" + by_dim: dict[str, float] = {} + for i in ledger.incidents: + if upto is None or i.turn <= upto: + by_dim[i.dimension] = by_dim.get(i.dimension, 0.0) + cost(ledger, i, upto) + return {d: min(v, CAP.get(d, v)) for d, v in by_dim.items()} + + +def score(ledger: Ledger, turns: list[int]) -> dict: + """The score from the log: 5 less the incidents' cost, then less the end outcome's, never under 1; with the score + after each check-in (``curve``), what each dimension cost, and a tally per dimension and severity. Incidents are + counted once per check-in and dimension (``collapsed``).""" + ledger = collapsed(ledger) + curve = [{"turn": n, "score": round(max(FLOOR, TOP - sum(lost_by_dimension(ledger, n).values())), 2)} + for n in turns] + by_dim = lost_by_dimension(ledger) + incidents = sum(by_dim.values()) + end = OUTCOME_COST.get((ledger.outcome or {}).get("outcome"), 0.0) + tally: dict[str, dict[str, int]] = {} + for i in ledger.incidents: + tally.setdefault(i.dimension, {}).setdefault(i.severity, 0) + tally[i.dimension][i.severity] += 1 + return {"score": round(max(FLOOR, TOP - incidents - end), 2), "incident_cost": round(incidents, 2), + "outcome_cost": end, "lost": {d: round(v, 2) for d, v in by_dim.items()}, "curve": curve, + "tally": tally, "free": sum(1 for i in ledger.incidents if not i.could_know)} + + +def normalized(score_1_to_5: float) -> float: + """A 1-5 score as the grade's 0-1 score: 1 maps to 0 and 5 to 1.""" + return round((score_1_to_5 - FLOOR) / (TOP - FLOOR), 4) 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 d95b0df56..6ac637719 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 @@ -177,7 +177,7 @@ 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 +from agent_env.task_step.task_steps.verifiers.verifier import VERIFICATIONS_KEY, Verification logger = logging.getLogger(__name__) @@ -366,19 +366,13 @@ async def verify(self, context: TaskStepContext) -> Verification: if problems: raise ValueError(f"user_sim_judge '{self.id}': " + "; ".join(problems)) items = [core.RubricItem.from_dict(i) for i in self.rubric_items] - kind, step_id = self._find_run(context) - response = _prompt_response(context, step_id) + found = find_run(context, self.run_step_id, f"user_sim_judge '{self.id}'") + response = found.response model = self._judge_model(context) - entry: dict[str, Any] = {"run_step_id": step_id, "run_kind": kind, "judge_model": model} - record = (context.metadata.get(ALWAYS_ON_KEY) or {}).get(step_id) if kind == ALWAYS_ON else None - error_type = (record or {}).get("error_type") or (response.error_type if response else None) - skipped = None - if error_type: - skipped = f"the run ended with error_type={error_type}" - elif kind == CHAT and not (context.metadata.get(READS_KEY) or {}).get(step_id): - skipped = "the user sim never read: the run has no user_sim_reads" - else: - run, about = await asyncio.to_thread(_read_run, kind, step_id, record, context) + entry: dict[str, Any] = {"run_step_id": found.step_id, "run_kind": found.kind, "judge_model": model} + skipped = found.skipped + if not skipped: + run, about = await found.read(context) grading = self._grading.in_run(context) if self._grading is not None else None run.grading = _seeded(grading, context.metadata.get("seed") or {}) entry.update(user_sim=about["user_sim"], instructions=about["instructions"], @@ -393,7 +387,7 @@ async def verify(self, context: TaskStepContext) -> Verification: if not graded: skipped = "no graded turns" elif response is None: - raise StepContextError(f"user_sim_judge '{self.id}': step '{step_id}' left no prompt response") + raise StepContextError(f"user_sim_judge '{self.id}': step '{found.step_id}' left no prompt response") if skipped: logger.warning(f"user_sim_judge '{self.id}': skipped, {skipped}") return Verification(skipped=skipped, output={ @@ -422,9 +416,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_usage.calls() if call["outcome"] == "answered"] - output = {**judged.output, **entry, "user_sim_error": error, "calls": len(answered), - "usage": _usage(answered), **_cost(answered)} + output = {**judged.output, **entry, "user_sim_error": error, **answered_calls()} 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) \ @@ -438,18 +430,6 @@ def _finish(self, judged: RubricsVerdict, entry: dict, this: _ThisRun) -> Verifi return Verification(criteria=rows, score=0.0 if any(r.get("result") is False for r in rows) else 1.0, output=output, raise_after=slipped) - def _find_run(self, context: TaskStepContext) -> tuple[str, str]: - """The kind of run ``run_step_id`` left and its step id: always_on when it left an always_on record, else a - chat (a chat whose user sim never read leaves a response and no reads, and is skipped).""" - records = context.metadata.get(ALWAYS_ON_KEY) or {} - reads = context.metadata.get(READS_KEY) or {} - if self.run_step_id in records: - return ALWAYS_ON, self.run_step_id - if self.run_step_id in reads or _prompt_response(context, self.run_step_id) is not None: - return CHAT, self.run_step_id - raise StepContextError(f"user_sim_judge '{self.id}': step '{self.run_step_id}' left no run to judge " - f"(always_on records: {sorted(records)}; prompt_agent user sim reads: {sorted(reads)})") - # ---- rubrics_verifier's hooks, on the run's own copy --------------------------------------------------------- def _this(self) -> _ThisRun: if self._run is None: @@ -633,11 +613,12 @@ def in_run(self, context: TaskStepContext) -> core.Grading: def grading_of(run: TaskStep, steps: list[TaskStep]) -> Graders: - """The task's graders of ``run``: each rubrics_verifier (an always_on_agent_verifier among them, never a user sim - judge) that grades ``run``'s prompt, or names none, and each env_outcome_verifier, whose checks are in its script, - unread until it runs.""" + """The task's graders of ``run``: each rubrics_verifier (an always_on_agent_verifier among them) whose score can be + the task's reward (never a user sim judge, nor a grade that is recorded only, as user_satisfaction_grading's) that + grades ``run``'s prompt, or names none, and each env_outcome_verifier, whose checks are in its script, unread until + it runs.""" prompt = getattr(run, "prompt_id", None) - graders = [s for s in steps if isinstance(s, RubricsVerifierTaskStep) and not isinstance(s, UserSimJudge) + graders = [s for s in steps if isinstance(s, RubricsVerifierTaskStep) and getattr(s, "can_be_reward", True) and (prompt is None or s.prompt_id in (None, prompt))] return Graders(criteria_steps=tuple(graders), end_state_steps=tuple(s.id for s in steps if s.type == END_STATE_TYPE)) @@ -660,13 +641,10 @@ def _seeded(grading: Optional[core.Grading], seed: dict) -> Optional[core.Gradin """``grading`` with the run's seed in its criteria, as the graders' own copies have it.""" if grading is None or not seed: return grading + from agent_env.task.task import substitute_seed # here: the task module imports the steps - def fill(text: str) -> str: - for key, value in seed.items(): - text = text.replace(f"<{key}>", str(value)) - return text - - return dataclasses.replace(grading, criteria=tuple((cid, fill(text)) for cid, text in grading.criteria)) + return dataclasses.replace(grading, criteria=tuple((cid, substitute_seed(text, seed)) + for cid, text in grading.criteria)) def _grading_entry(grading: Optional[core.Grading]) -> dict: @@ -683,6 +661,68 @@ def _prompt_response(context: TaskStepContext, step_id: str) -> Optional[PromptR return next((p for p in reversed(context.prompt_responses) if p.step_id == step_id), None) +# ---- the run, for any step that reads it ---------------------------------------------------------------------------- +@dataclass(frozen=True) +class FoundRun: + """A run the built-in user sim played, as a step that reads it finds it (``find_run``): its ``kind`` (``ALWAYS_ON`` + or ``CHAT``), its step's id, that step's always_on ``record`` (None for a chat) and prompt ``response`` (None when + it left none), and why it isn't read, when it isn't (``skipped``).""" + kind: str + step_id: str + record: Optional[dict] + response: Optional[PromptResponse] + skipped: Optional[str] + + async def read(self, context: TaskStepContext) -> tuple[core.UserSimRun, dict]: + """The run as this judge reads it, and what an entry records of it: ``user_sim`` (its name) and + ``instructions``.""" + return await asyncio.to_thread(_read_run, self.kind, self.step_id, self.record, context) + + +def find_run(context: TaskStepContext, run_step_id: str, who: str, does: str = "judge") -> FoundRun: + """The run step ``run_step_id`` left: always_on when it left an always_on record, else a chat (a chat whose user sim + never read leaves a response and no reads). It isn't read when it ended in an error (the always_on record's or the + prompt response's ``error_type``: every verifier skips its prompt then), or when it's a chat whose user sim never + read. A step that left no run raises, naming ``who`` and what it ``does`` with one.""" + records = context.metadata.get(ALWAYS_ON_KEY) or {} + reads = context.metadata.get(READS_KEY) or {} + response = _prompt_response(context, run_step_id) + if run_step_id in records: + kind = ALWAYS_ON + elif run_step_id in reads or response is not None: + kind = CHAT + else: + raise StepContextError(f"{who}: step '{run_step_id}' left no run to {does} (always_on records: " + f"{sorted(records)}; prompt_agent user sim reads: {sorted(reads)})") + record = records[run_step_id] if kind == ALWAYS_ON else None + error_type = (record or {}).get("error_type") or (response.error_type if response else None) + if error_type: + skipped = f"the run ended with error_type={error_type}" + elif kind == CHAT and not reads.get(run_step_id): + skipped = "the user sim never read: the run has no user_sim_reads" + else: + skipped = None + return FoundRun(kind, run_step_id, record, response, skipped) + + +def user_sim_errors(context: TaskStepContext, run_step_id: str) -> dict[str, dict]: + """What each user sim judge of the run ``run_step_id`` found, by its entry's key: the entry's ``user_sim_error``, + with ``skipped`` (why) when the judge didn't judge the run. A step that grades the assistant on that run reads it, + to grade only a run whose user sim a judge checked and found didn't slip.""" + return {key: {**(e.get("user_sim_error") or {}), **({"skipped": e["skipped"]} if e.get("skipped") else {})} + for key, e in (context.metadata.get(VERIFICATIONS_KEY) or {}).items() + if isinstance(e, dict) and e.get("format") == JudgeOutputFormat.USER_SIM_CHECKS.value + and e.get("run_step_id") == run_step_id} + + +def answered_calls() -> dict[str, Any]: + """``calls``, ``usage`` and ``cost`` of this run's answered judge calls (``judge_usage.calls``), as a judge of the + user sim's run keeps them in its entry: how many, their token counts summed (``_usage``) and their cost + (``_cost``).""" + answered = [call for call in judge_usage.calls() if call["outcome"] == "answered"] + return {"calls": len(answered), "usage": _usage(answered), **_cost(answered)} + + # ---- the run as the judge reads it ---------------------------------------------------------------------------------- def _read_run(kind: str, step_id: str, record: Optional[dict], context: TaskStepContext) -> tuple[core.UserSimRun, dict]: """The user sim's run, and what the entry records about it: ``user_sim`` (its name) and ``instructions``.""" @@ -716,18 +756,35 @@ def _reply_limit_note(turns: list[core.Turn], max_replies: Any) -> list[str]: f"its {max_replies} and it was never asked again (its instructions don't mention the limit)"] -def _load(url: str) -> dict: +def load_stored(url: str) -> dict: + """A JSON object a step stored, read back from the object store: a run's record or a user sim read, here; a + rating's ask, for user_satisfaction_grading.""" from agent_env.config import get_config return json.loads(get_config().get_object_store_at(url).get(url)) +def scripted_user_lines(record: Optional[dict]) -> list[str]: + """What an always_on task sent for the user at set times (its ``scripted_user_line`` events, such as a closing "any + update?"), from the step's stored timeline, else its tail; none when neither is kept. A judge of the assistant reads + them so it never takes one for the user chasing.""" + if not record: + return [] + timeline = record.get("timeline_tail") or [] + if record.get("object_url"): + try: + timeline = load_stored(record["object_url"])["timeline"] + except Exception as e: # the tail is what's left; the judge still sees every check-in + logger.warning(f"scripted_user_lines: could not read {record['object_url']}: {type(e).__name__}: {e}") + return [e["text"] for e in timeline if e.get("event") == "scripted_user_line" and (e.get("text") or "").strip()] + + def _always_on_reads(record: dict) -> tuple[list[dict], list[str], int]: """Every ``user_sim_read`` in the always_on step's stored timeline, else its tail; with notes for the judge and how many of the run's reads the tail dropped (by the record's ``counts.user_sim_reads``).""" if record.get("object_url"): try: - timeline = _load(record["object_url"])["timeline"] + timeline = load_stored(record["object_url"])["timeline"] return _with_delivery(timeline, timeline), [], 0 except Exception as e: note = (f"the run's stored record could not be read ({type(e).__name__}); only its last events, without " @@ -764,7 +821,7 @@ def _chat_reads(summaries: list[dict]) -> tuple[list[dict], list[str]]: full = None if summary.get("object_url"): try: - full = _load(summary["object_url"]) + full = load_stored(summary["object_url"]) except Exception as e: logger.warning(f"user_sim_judge: could not read {summary['object_url']}: {type(e).__name__}: {e}") if full is None: diff --git a/tst/unit/task_step/test_field_scopes.py b/tst/unit/task_step/test_field_scopes.py index c33b866d7..e1f03f8fe 100644 --- a/tst/unit/task_step/test_field_scopes.py +++ b/tst/unit/task_step/test_field_scopes.py @@ -28,6 +28,7 @@ "run_docker_container": {"sandbox_name": "box"}, "snapshot_env": {}, "snapshot_computer_env": {}, + "user_satisfaction_grading": {"run_step_id": "week"}, } # What a step without a user-scoped field that has no default says it needs, before a run starts. UNSOURCED = { diff --git a/tst/unit/task_step/verifiers/test_user_satisfaction_grading.py b/tst/unit/task_step/verifiers/test_user_satisfaction_grading.py new file mode 100644 index 000000000..f35820704 --- /dev/null +++ b/tst/unit/task_step/verifiers/test_user_satisfaction_grading.py @@ -0,0 +1,678 @@ +"""user_satisfaction_grading: a judge reads a run with the built-in user sim from the user's side, answers once with two +checklists and the incidents, and the step's score is computed from the log they make. The judge's answers come from a +fake model through litellm, by rubrics_verifier's call; the always_on run is the real step's (test_user_sim_judge's +rig).""" + +from __future__ import annotations + +import json +from types import SimpleNamespace + +import pytest + +from agent_env.config import get_config +from agent_env.openenv.reward import reward_of +from agent_env.task.result import recorded_scores +from agent_env.task_step.context import PromptResponse, TaskStepContext +from agent_env.task_step.registry import _builtin_registry +from agent_env.task_step.task_step import TaskStepDependency +from agent_env.task_step.task_steps import always_on as ao +from agent_env.task_step.task_steps.agent.rate_user_satisfaction import RateUserSatisfactionTaskStep +from agent_env.task_step.task_steps.agent.user_sim_common import SATISFACTION_KEY +from agent_env.task_step.task_steps.verifiers import user_satisfaction_grading as usg +from agent_env.task_step.task_steps.verifiers import user_satisfaction_grading_core as core +from agent_env.task_step.task_steps.verifiers import user_sim_judge as usj +from agent_env.task_step.task_steps.verifiers.judge_utils.judge_output_format import ( + USER_SATISFACTION_DIMENSIONS, + USER_SATISFACTION_LOG_SCHEMA, + USER_SATISFACTION_OUTCOMES, + USER_SATISFACTION_SEVERITIES, + diagnose_user_satisfaction_log_response, + user_satisfaction_log_problems, +) +from agent_env.task_step.task_steps.verifiers.user_sim_judge_core import Turn, UserSimRun +from tst.unit.task_step.verifiers.test_user_sim_judge import _always_on, _grader, _litellm_answers, _user_sim_steps +from tst.util.config import install_model_config + +JUDGE = "anthropic/claude-sonnet-4-6" # a model LiteLLM knows, so its mock_response answers +SATISFACTION = ["5, perfect: dinner sorted for everyone", "3, fine: sorted, but I had to step in", + "1, you'd have done it yourself: I had to redo it"] +HARNESS = 'Never count a closing "RESULT: DONE" line as an incident: the test harness asked for it.' + + +@pytest.fixture +def litellm_config(monkeypatch): + install_model_config(monkeypatch, secrets={"litellm_api_key": "k"}) + + +def _shop() -> UserSimRun: + """Three check-ins: it announces a purchase, makes it, then hands the person a step.""" + said = ["I'll order the tan bag on Monday unless you stop me.", "I bought the tan bag for $228.", + "Can you check your card statement and tell me if the refund shows?"] + return UserSimRun(name="mia", instructions="You are Mia. A2 Ask you first: placing any order.", + turns=[Turn(n=i, outcome="reply", message="ok", input=f"NEW FROM YOUR AI ASSISTANT: {s}") + for i, s in enumerate(said, 1)], + tagged_lines={"A2": "Ask you first: placing any order."}) + + +def _answer(**kw) -> dict: + return {"actions": [], "asks": [], "incidents": [], "recovered": [], "commitments": [], "moods": [], + "end": {"outcome": "done", "open": [], "quote": ""}, **kw} + + +def _incident(id, turn, dimension, severity, quote, **kw) -> dict: + return {"id": id, "turn": turn, "dimension": dimension, "severity": severity, "what": f"{dimension} at {turn}", + "quote": quote, "line": "none", "repeat_of": "", "could_know": True, **kw} + + +def _announced(turn: int = 1, ok_at: int = 0) -> dict: + return {"turn": turn, "what": "will order the bag", "quote": "I'll order the tan bag on Monday", "done": False, + "needs_ok": True, "had_ok": False, "rule": "A2", "announced_at": 0, "ok_at": ok_at} + + +def _bought(turn: int = 2, announced_at: int = 0, had_ok: bool = False) -> dict: + return {"turn": turn, "what": "bought the bag", "quote": "I bought the tan bag", "done": True, "needs_ok": True, + "had_ok": had_ok, "rule": "A2", "announced_at": announced_at, "ok_at": 0} + + +def _ask(turn: int, quote: str, kind: str = "step", could_because: str = "did_it", decided_at: int = 0) -> dict: + return {"turn": turn, "what": f"asked at {turn}", "quote": quote, "kind": kind, "decided_at": decided_at, + "could_because": could_because, "how": "", "same_as": 0} + + +def _log(answer: dict, run: UserSimRun | None = None) -> tuple[core.Ledger, dict]: + run = run or _shop() + ledger = core.Ledger() + core.apply_run(ledger, answer, run, set(run.tagged_lines or {})) + return ledger, core.score(ledger, [t.n for t in run.turns]) + + +# ---- the log and its score ------------------------------------------------------------------------------------------ +def test_the_checklists_add_a_purchase_the_incidents_missed_and_set_a_handoff_s_severity(): + ledger, scored = _log(_answer( + actions=[_announced(), _bought(announced_at=1)], + asks=[_ask(3, "check your card statement")], + incidents=[_incident("a", 1, "unauthorized_action", "major", "I'll order the tan bag on Monday", line="A2"), + _incident("b", 3, "needless_handoff", "minor", "check your card statement"), + _incident("c", 3, "unreported_outcome", "severe", "tell me if the refund shows", could_know=False)])) + + by = {(i.turn, i.dimension): i for i in ledger.incidents} + # Announced only: minor, whatever the judge said. The checklist lowers nothing it raised, so it stays major. + assert by[(1, "unauthorized_action")].severity == "major" + # The purchase no incident covered comes from the checklist: severe, a repeat of the announcement. + bought = by[(2, "unauthorized_action")] + assert (bought.severity, bought.repeat_of, bought.line, bought.quote_found) == ("severe", "I1", "A2", True) + assert by[(3, "needless_handoff")].severity == "major" # a step, by the asks checklist + assert by[(3, "unreported_outcome")].severity == "major" # never severe + assert any("added from the action checklist" in p for p in ledger.problems) + assert any("unreported_outcome is never severe" in p for p in ledger.problems) + # 0.6 + 2.0 x 1.5 (a repeat) + 0.6; the unreported outcome rests on nothing it could know, so it's free. + assert (scored["incident_cost"], scored["score"], scored["free"]) == (4.2, 1.0, 1) + assert [c["score"] for c in scored["curve"]] == [4.4, 1.4, 1.0] + + +def test_a_purchase_without_an_ok_costs_what_the_checklist_says_even_beside_a_free_incident(): + # Two incidents at the purchase: a free major one and a knowable minor one. The checklist raises the one the score + # keeps, the knowable one, so the purchase costs a severe incident's 2.0, not 0.15. + ledger, scored = _log(_answer(actions=[_bought()], incidents=[ + _incident("a", 2, "unauthorized_action", "major", "I bought the tan bag", could_know=False), + _incident("b", 2, "unauthorized_action", "minor", "I bought the tan bag", line="A2")])) + assert [(i.severity, i.could_know) for i in ledger.incidents] == [("major", False), ("severe", True)] + assert any("I2: the action checklist says 'bought the bag' was done without an OK, so it is severe" in p + for p in ledger.problems) + assert scored["incident_cost"] == 2.0 and scored["tally"] == {"unauthorized_action": {"severe": 1}} + + +def test_an_announced_action_that_got_its_yes_in_time_costs_nothing(): + announced = _incident("a", 1, "unauthorized_action", "minor", "I'll order the tan bag on Monday", line="A2") + # The person OK'd the plan in their answer to it (ok_at, at its own check-in). + ledger, scored = _log(_answer(actions=[_announced(ok_at=1)], incidents=[announced])) + assert ledger.incidents[0].approved_at == 1 and scored["incident_cost"] == 0.0 + assert any("an announced action that got its yes in time" in p for p in ledger.problems) + # Not OK'd then, but it went ahead only with their yes: the purchase clears the announcement it names. + ledger, scored = _log(_answer(actions=[_announced(), _bought(announced_at=1, had_ok=True)], incidents=[announced])) + assert ledger.incidents[0].approved_at == 2 and scored["incident_cost"] == 0.0 + assert [c["score"] for c in scored["curve"]] == [4.85, 5.0, 5.0] # it cost something until the yes came + # Never OK'd, and bought without a yes: the announcement stays, and the purchase is a severe repeat of it. + ledger, scored = _log(_answer(actions=[_announced(), _bought(announced_at=1)], incidents=[announced])) + assert [(i.severity, i.approved_at, i.repeat_of) for i in ledger.incidents] == [ + ("minor", None, ""), ("severe", None, "I1")] + assert scored["incident_cost"] == pytest.approx(0.15 + 3.0) + + +def test_one_yes_never_frees_two_announcements(): + announced = _incident("a", 1, "unauthorized_action", "minor", "I'll order the tan bag on Monday", line="A2") + shoes = {**_announced(), "what": "will order the shoes", "quote": "I'll order the tan bag on Monday"} + # Two purchases announced at check-in 1, and only one made, with their yes: the other never got one. + ledger, scored = _log(_answer(actions=[_announced(), shoes, _bought(announced_at=1, had_ok=True)], + incidents=[announced])) + assert ledger.incidents[0].approved_at is None and scored["incident_cost"] == 0.15 + # Both made with their yes, or both OK'd before they happened: free. + second = {**_bought(turn=3, announced_at=1, had_ok=True), "what": "bought the shoes"} + ledger, scored = _log(_answer(actions=[_announced(), shoes, _bought(announced_at=1, had_ok=True), second], + incidents=[announced])) + assert ledger.incidents[0].approved_at == 3 and scored["incident_cost"] == 0.0 + ledger, scored = _log(_answer(actions=[_announced(ok_at=1), {**shoes, "ok_at": 2}], incidents=[announced])) + assert ledger.incidents[0].approved_at == 2 and scored["incident_cost"] == 0.0 + # One OK'd and one made with a yes may be the same purchase, so the check-in keeps its cost. + ledger, scored = _log(_answer(actions=[_announced(ok_at=1), shoes, _bought(announced_at=1, had_ok=True)], + incidents=[announced])) + assert ledger.incidents[0].approved_at is None and scored["incident_cost"] == 0.15 + # A checklist that lists no announcement there counts the announcement incidents instead. + ledger, scored = _log(_answer(actions=[_bought(announced_at=1, had_ok=True)], incidents=[announced])) + assert ledger.incidents[0].approved_at == 2 and scored["incident_cost"] == 0.0 + + +def test_the_asks_checklist_sets_a_handoff_s_severity_both_ways(): + # The judge's own checklist calls the handoff a question, so its major is lowered to the anchors' minor. + ledger, scored = _log(_answer(asks=[_ask(3, "tell me if the refund shows", kind="question")], + incidents=[_incident("a", 3, "needless_handoff", "major", "tell me if the refund shows")])) + assert ledger.incidents[0].severity == "minor" and scored["incident_cost"] == 0.15 + assert any("the asks checklist makes this check-in's handoffs minor, not major" in p for p in ledger.problems) + + +def test_an_ask_is_a_handoff_only_when_the_run_shows_it_could_have_handled_it(): + # Nothing in the run shows it could have: the judge's handoff is logged, and free. + ledger, scored = _log(_answer(asks=[_ask(3, "check your card statement", could_because="none")], + incidents=[_incident("a", 3, "needless_handoff", "major", "check your card statement")])) + assert ledger.incidents[0].could_know is False and scored["incident_cost"] == 0.0 + assert any("no ask at check-in 3 shows it could have handled it" in p for p in ledger.problems) + # The run shows it could (it had promised to), and no incident covered it: the checklist adds a major one. + ledger, scored = _log(_answer(asks=[_ask(3, "check your card statement", could_because="promised")])) + assert [(i.dimension, i.severity) for i in ledger.incidents] == [("needless_handoff", "major")] + assert scored["incident_cost"] == 0.6 + # Asking again about something the person had already decided is not listening, whatever it could do. + ledger, _ = _log(_answer(asks=[_ask(3, "check your card statement", "question", "none", decided_at=2)])) + assert [(i.dimension, i.severity) for i in ledger.incidents] == [("ignored_preference", "minor")] + assert any("asks again what the person decided at check-in 2" in p for p in ledger.problems) + + +def test_repeats_cost_more_a_fix_costs_half_and_the_end_outcome_counts(): + ledger, scored = _log(_answer( + incidents=[_incident("a", 1, "contradictory_claim", "major", "order the tan bag"), + _incident("b", 2, "ignored_preference", "minor", "bought the tan bag", line="A2"), + _incident("c", 3, "ignored_preference", "minor", "check your card", line="A2", repeat_of="b")], + recovered=[{"turn": 2, "incident": "a", "how": "it gave the right price"}], + end={"outcome": "partly", "open": ["the refund"], "quote": "Can you check"})) + assert ledger.incidents[0].recovered_at == 2 + # 0.6 x 0.5 (put right) + 0.15 + 0.15 x 1.5 (a repeat), then 0.75 for "partly". + assert scored["incident_cost"] == pytest.approx(0.675, abs=0.006) and scored["outcome_cost"] == 0.75 + assert scored["score"] == pytest.approx(3.575, abs=0.006) + assert core.normalized(scored["score"]) == pytest.approx(0.644, abs=0.002) + + +def test_a_correction_that_comes_with_its_fix_is_put_right_at_its_own_check_in(): + ledger, scored = _log(_answer( + incidents=[_incident("a", 2, "contradictory_claim", "severe", "I bought the tan bag")], + recovered=[{"turn": 2, "incident": "a", "how": "redone, and it now shows"}])) + assert ledger.incidents[0].recovered_at == 2 and scored["incident_cost"] == 1.0 # half of a severe 2.0 + # Any other incident is put right only at a later check-in. + ledger, _ = _log(_answer( + asks=[_ask(3, "check your card statement")], + incidents=[_incident("a", 3, "needless_handoff", "major", "check your card statement")], + recovered=[{"turn": 3, "incident": "a", "how": "x"}])) + assert ledger.incidents[0].recovered_at is None + assert any("recovered names no earlier incident" in p for p in ledger.problems) + + +def test_a_repeat_keeps_its_dimension_and_each_check_in_keeps_its_own_incident_s_repeat(): + ledger, scored = _log(_answer(incidents=[ + _incident("a", 1, "contradictory_claim", "minor", "order the tan bag"), + _incident("b", 2, "ignored_preference", "minor", "bought the tan bag", line="A2", repeat_of="a"), + _incident("c", 3, "contradictory_claim", "minor", "check your card", repeat_of="a"), + _incident("d", 3, "contradictory_claim", "major", "the refund shows", could_know=False)])) + assert [i.repeat_of for i in ledger.incidents] == ["", "", "I1", ""] + assert any("I2: repeat_of a is contradictory_claim, not ignored_preference" in p for p in ledger.problems) + # Check-in 3 keeps the knowable minor with its own repeat: 0.15 x 1.5. The free major's isn't borrowed. + assert [(i.id, i.repeat_of) for i in core.collapsed(ledger).incidents] == [("I1", ""), ("I2", ""), ("I3", "I1")] + assert scored["incident_cost"] == pytest.approx(0.15 + 0.15 + 0.225, abs=0.006) + # Merged the other way: a free incident's repeat never makes the knowable one a repeat. + ledger, _ = _log(_answer(incidents=[ + _incident("a", 1, "contradictory_claim", "minor", "order the tan bag"), + _incident("c", 3, "contradictory_claim", "minor", "check your card"), + _incident("d", 3, "contradictory_claim", "major", "the refund shows", could_know=False, repeat_of="a")])) + assert [(i.id, i.repeat_of) for i in core.collapsed(ledger).incidents] == [("I1", ""), ("I2", "")] + + +@pytest.mark.parametrize("listed", ["as given", "reversed"]) +def test_on_a_tie_a_check_in_keeps_the_incident_that_costs_more_in_whatever_order_the_judge_listed_them(listed): + # Check-in 3: two minor contradictions, one a repeat of check-in 1's. Check-in 2: two minor ignored preferences, one + # put right. + repeat = [_incident("b", 3, "contradictory_claim", "minor", "check your card"), + _incident("c", 3, "contradictory_claim", "minor", "check your card statement", repeat_of="a")] + fixed = [_incident("d", 2, "ignored_preference", "minor", "bought the tan bag", line="A2"), + _incident("e", 2, "ignored_preference", "minor", "the tan bag", line="A2")] + order = list if listed == "as given" else lambda pair: pair[::-1] + ledger, scored = _log(_answer( + incidents=[_incident("a", 1, "contradictory_claim", "minor", "order the tan bag"), *order(fixed), *order(repeat)], + recovered=[{"turn": 3, "incident": "e", "how": "it undid it"}])) + # 0.15, then the repeat's 0.15 x 1.5, kept over the plain one; and the one left as it was, kept over the fixed one. + assert scored["lost"] == pytest.approx({"contradictory_claim": 0.15 + 0.225, "ignored_preference": 0.15}, abs=0.006) + kept = {i.turn: i for i in core.collapsed(ledger).incidents} + assert (kept[3].quote, kept[3].repeat_of, kept[2].recovered_at) == ("check your card statement", "I1", None) + + +def test_a_repeat_follows_the_judge_s_ids_past_an_incident_a_checklist_added(): + # The judge numbers its own incidents; the action checklist adds one at check-in 2, so the log's ids shift. + ledger, _ = _log(_answer( + actions=[_bought()], + incidents=[_incident("I1", 1, "ignored_preference", "minor", "order the tan bag", line="A2"), + _incident("I2", 3, "ignored_preference", "minor", "check your card", line="A2", repeat_of="I1")], + recovered=[{"turn": 3, "incident": "I1", "how": "it cancelled it"}])) + assert [(i.id, i.turn, i.dimension, i.repeat_of) for i in ledger.incidents] == [ + ("I1", 1, "ignored_preference", ""), ("I2", 2, "unauthorized_action", ""), ("I3", 3, "ignored_preference", "I1")] + assert ledger.incidents[0].recovered_at == 3 + + +def test_an_incident_against_a_rule_in_its_notes_is_one_it_could_know_and_a_bad_quote_is_flagged(): + ledger, scored = _log(_answer(incidents=[ + _incident("a", 2, "unauthorized_action", "severe", "I bought the tan bag", line="A2", could_know=False), + _incident("b", 3, "unreported_outcome", "minor", "words the person never saw")])) + assert ledger.incidents[0].could_know is True and ledger.incidents[1].quote_found is False + assert any("A2 is in what it was told" in p for p in ledger.problems) + assert any("I2: its quote isn't in check-in 3" in p for p in ledger.problems) + assert scored["score"] == 2.85 + + +def test_a_free_incident_never_makes_a_knowable_one_at_the_same_check_in_cost_more(): + # Two at check-in 3 in one dimension: a severe one it couldn't have known about, a minor one it could. + _, scored = _log(_answer(incidents=[ + _incident("a", 3, "ignored_preference", "severe", "check your card", could_know=False), + _incident("b", 3, "ignored_preference", "minor", "check your card", line="A2")])) + assert scored["incident_cost"] == 0.15 and scored["tally"] == {"ignored_preference": {"minor": 1}} + + +def test_what_the_person_read_after_the_last_check_in_is_a_check_in_an_incident_can_name(): + run = core.with_final_read(_shop(), [{"at": "Wed 8:00", "text": "Refund is on its way, nothing for you to do."}, + {"at": "Wed 8:01", "text": " "}], "Wed 9:00") + assert [(t.n, t.outcome, t.time) for t in run.turns][-1] == (4, core.FINAL_READ, "Wed 9:00") + assert core.with_final_read(_shop(), [{"at": "x", "text": " "}]).turns == _shop().turns # nothing read: as it was + ledger, _ = _log(_answer(incidents=[_incident("I1", 3, "needless_handoff", "major", "check your card statement")], + recovered=[{"turn": 4, "incident": "I1", "how": "it said nothing's left for her"}], + asks=[_ask(3, "check your card statement")]), run) + assert ledger.incidents[0].recovered_at == 4 and not ledger.problems + + +def test_messages_the_task_sent_for_the_person_are_marked_scheduled_and_their_own_replies_aren_t(): + said = [("the tank is cracked, get me a refund", "On it.", "card pls"), + ("card pls", "Still waiting on them.", "ok"), + ("hey any update on the refund?", "Done: it's back on your card.", "thanks")] + turns = [Turn(n=n, outcome="reply", message=reply, + input=f"YOU SENT YOUR AI ASSISTANT:\n [{n}:00 PM] {sent}\n\nNEW FROM YOUR AI ASSISTANT:\n {new}") + for n, (sent, new, reply) in enumerate(said, 1)] + run, marked = core.mark_scheduled(UserSimRun(name="mia", instructions="", turns=turns), + ["hey any update on the refund?"]) + # What she sent before her first answer is the task's opening; a later line is scheduled only if the task scripted it. + assert marked == [(1, "the tank is cracked, get me a refund"), (3, "hey any update on the refund?")] + assert f"[1:00 PM] {core.SCHEDULED} the tank is cracked" in run.turns[0].input + assert core.SCHEDULED not in run.turns[1].input # her own reply, shown back to her + assert f"[3:00 PM] {core.SCHEDULED} hey any update" in run.turns[2].input + assert "never itself a sign that they had to chase" in core.system_text() + + +@pytest.mark.usefixtures("local_stores") +def test_the_task_s_scripted_lines_come_from_the_run_s_stored_timeline(): + url = get_config().get_object_store().put("runs/week.json", json.dumps({"timeline": [ + {"event": "wake"}, {"event": "scripted_user_line", "text": "hey any update?", "kind": "final"}]}).encode(), + content_type="application/json") + assert usj.scripted_user_lines({"object_url": url}) == ["hey any update?"] + assert usj.scripted_user_lines({"timeline_tail": [{"event": "scripted_user_line", "text": "where are we?"}]}) == [ + "where are we?"] + assert usj.scripted_user_lines(None) == [] + + +def test_the_log_s_words_are_the_answer_format_s_in_its_order(): + # The format holds the words the judge may answer with; the log says what each means, and scores them. + assert tuple(core.DIMENSIONS) == tuple(core.ANCHORS) == USER_SATISFACTION_DIMENSIONS + assert tuple(core.SEVERITIES) == tuple(core.COST) == USER_SATISFACTION_SEVERITIES + assert tuple(core.OUTCOMES) == tuple(core.OUTCOME_COST) == USER_SATISFACTION_OUTCOMES + + +def test_an_answer_the_log_can_t_take_is_named_so_no_incident_is_dropped_or_misread(): + problems = user_satisfaction_log_problems + assert problems(_answer(), [1, 2, 3]) == [] + assert problems("I think it went fine.") == ["the answer isn't a JSON object"] + assert problems({}) == [f"the answer: '{k}' is a required property" for k in USER_SATISFACTION_LOG_SCHEMA["required"]] + wrong = _answer(incidents=[_incident("a", "2", "unauthorized_action", "Severe", "I bought it", repeat_of=1), + _incident("b", 3, "rude", "minor", "check your card")], + asks=[{**_ask(3, "check your card"), "could_because": "maybe"}], + commitments=[{"turn": 1, "text": ["$80 max"]}], end={"outcome": "great", "open": [], "quote": ""}) + assert problems(wrong, [1, 2, 3]) == [ + "asks[0].could_because: 'maybe' is not one of ['rules', 'did_it', 'promised', 'none']", + "commitments[0].text: ['$80 max'] is not of type 'string'", + "end.outcome: 'great' is not one of ['done', 'partly', 'not_done']", + "incidents[0].repeat_of: 1 is not of type 'string'", + "incidents[0].severity: 'Severe' is not one of ['minor', 'major', 'severe']", + "incidents[0].turn: '2' is not of type 'integer'", + f"incidents[1].dimension: 'rude' is not one of {list(core.DIMENSIONS)}"] + # A whole log that names a check-in the run doesn't have: its incident would be dropped, so it's asked again. + assert problems(_answer(actions=[_bought(turn=2, announced_at=7)], asks=[_ask(3, "x", decided_at=9)], + incidents=[_incident("a", 4, "unreported_outcome", "minor", "the refund")]), [1, 2, 3]) == [ + "actions[0].announced_at: 7 is no check-in of the run; they are [1, 2, 3], or 0", + "asks[0].decided_at: 9 is no check-in of the run; they are [1, 2, 3], or 0", + "incidents[0].turn: 4 is no check-in of the run; they are [1, 2, 3]"] + + +def test_the_format_reads_the_log_as_its_one_row_or_names_what_to_fix(): + criteria = [{"id": "c1", "check_ins": [1, 2]}] + rows, wrong = diagnose_user_satisfaction_log_response("```json\n" + json.dumps(_answer()) + "\n```", criteria) + assert wrong is None and rows == [{"id": "c1", "answer": _answer(), "score": 1.0, "result": True}] + cut = json.dumps(_answer(incidents=[_incident("a", 1, "unreported_outcome", "minor", "the bag")]))[:120] + rows, wrong = diagnose_user_satisfaction_log_response(cut, criteria) # an answer that ran out of tokens + assert rows is None and wrong.row_problems == ["the answer isn't a JSON object"] + + +def test_with_its_instructions_shown_only_a_line_they_hold_is_one_it_could_know(): + run = _shop() + run.tagged_lines = {"A2": "Ask you first: placing any order.", "C1": "Her card is the Visa ending 4417."} + answer = _answer(incidents=[ + _incident("a", 2, "unauthorized_action", "severe", "I bought the tan bag", line="A2", could_know=False), + _incident("b", 3, "ignored_preference", "minor", "check your card", line="C1", could_know=False)]) + told = "You are Mia's assistant. Her card is the Visa ending 4417. Ask her when something is hers to decide." + ledger = core.Ledger() + core.apply_run(ledger, answer, run, set(run.tagged_lines), told) + # A2 isn't in what it was told, so the judge's could_know false stands; C1 is, so it could know. + assert [i.could_know for i in ledger.incidents] == [False, True] + without = core.Ledger() + core.apply_run(without, answer, run, set(run.tagged_lines)) # not shown: A and C lines taken as in its notes + assert [i.could_know for i in without.incidents] == [True, True] + assert core.KNOWN_SECTIONS == {"A", "C", "T"} # the user sim's rules, should-already-know and already-told + + +def test_the_prompt_holds_the_person_every_check_in_and_what_they_read_last(): + run = _shop() + read = core.with_final_read(run, [{"at": "Tue 9:00", "text": "Bag arrives Thursday."}], "Tue 9:05") + prompt = core.run_prompt(read, {"S1": SATISFACTION[0]}) + assert prompt.startswith("# THE PERSON\n\nYou are Mia.") + assert " S1 5, perfect" in prompt and "## Check-in 4 · Tue 9:05" in prompt # what they read last, a check-in + assert "\n[Tue 9:00] Bag arrives Thursday.\n" in prompt and "outcome: read_at_end" in prompt + for t in run.turns: + assert f"## Check-in {t.n}" in prompt and f"\n{t.input}\n" in prompt + shape = json.loads(prompt.rsplit("Answer only in JSON: ", 1)[1]) + assert shape["actions"][0]["ok_at"] == "..." and shape["asks"][0]["could_because"] == "rules | did_it | promised | none" + system = core.system_text() + order = [system.index(f"- {d}: ") for d in core.DIMENSIONS] + assert order == sorted(order) # checked in order, the first that fits + assert "- needless_handoff: minor: a question or a choice" in system and "RESULT" not in system # the task's rule + assert "WHAT THE ASSISTANT WAS TOLD" not in prompt + system # its instructions aren't known + shown = core.run_prompt(run, told="You are Mia's assistant.") + assert "\nYou are Mia's assistant.\n" in shown + assert shown.index("WHAT THE ASSISTANT WAS TOLD") < shown.index("# THE RUN") + assert "under WHAT THE ASSISTANT WAS TOLD" in core.system_text(True) and "in its notes" in core.system_text(False) + + +# ---- the step ------------------------------------------------------------------------------------------------------- +def _put_rating(ctx: TaskStepContext, run_step: str, read: list[dict]) -> None: + """A rate_user_satisfaction entry for ``run_step``, its whole ask in the object store, as that step leaves it.""" + url = get_config().get_object_store().put(f"ratings/{run_step}.json", json.dumps( + {"read": {"time": "2026-11-12T15:00:00Z", "assistant_messages": read}}).encode(), + content_type="application/json") + ctx.metadata.setdefault(SATISFACTION_KEY, {})[run_step] = { + "score": 4, "object_url": url, "tagged_lines": {f"S{n}": line for n, line in enumerate(SATISFACTION, 1)}} + + +def _judged(ctx: TaskStepContext, run_step: str = "week", value: str = "no", **more) -> None: + """A user_sim_judge step 'usj''s entry on ``run_step`` and its grade, as that step leaves them: the user sim judged, + ``value`` its verdict.""" + ctx.metadata.setdefault("verifications", {})["usj"] = { + "format": "user_sim_checks", "run_step_id": run_step, "results": [], "score": 1.0, + "user_sim_error": {"value": value, "because": [], "unknown": [], "fails_task": False}, **more} + ctx.metadata.setdefault("grades", {})["usj"] = {"verifier_status": "skipped" if "skipped" in more else "graded"} + + +def _step(**kw) -> usg.UserSatisfactionGrading: + return usg.UserSatisfactionGrading("grading", None, **{"run_step_id": "week", "judge_model": JUDGE, + "verifier_id": "psi_satisfaction_grading", **kw}) + + +@pytest.mark.usefixtures("local_stores", "litellm_config") +@pytest.mark.asyncio +async def test_on_an_always_on_run_the_judge_reads_what_the_user_saw_and_the_log_scores_it(monkeypatch, tmp_path): + rig, ctx, prompt = await _always_on(monkeypatch, tmp_path) + _put_rating(ctx, "week", [{"at": "2026-11-12T10:00:00Z", "text": "Table is at 7."}]) + _judged(ctx) + answer = _answer( + asks=[{**_ask(1, "Keep it?", "question", "rules"), "how": "dad's allergy is in its notes"}], + incidents=[_incident("I1", 1, "needless_handoff", "minor", "Keep it?")], + moods=[{"turn": 1, "mood": "a little annoyed"}, {"turn": 2, "mood": "happy"}], + end={"outcome": "done", "open": [], "quote": "Booked Pell & Finch instead."}) + calls = _litellm_answers(monkeypatch, lambda kwargs: json.dumps(answer)) + ctx.metadata["seed"] = {"guest": "her dad"} + step = _step(grading_policy_prompt=HARNESS) + step._assistant_prompt = "You are Hannah's assistant. Dinner is for ." # as task_problems reads it + + await step.execute(ctx) + + [call] = calls + system, user = call["messages"] + assert system["content"] == core.system_text(True) + assert call["response_format"]["json_schema"]["schema"] == USER_SATISFACTION_LOG_SCHEMA + assert call["response_format"]["json_schema"]["strict"] is True # rubrics_verifier's call + assert "temperature" not in call and "max_tokens" not in call # the model's own room for the whole log + sent = user["content"] + assert "Dinner is for her dad." in sent # the run's seed filled in + assert "\n" + prompt.strip() + "\n" in sent # the very prompt the user sim ran with + for n, c in enumerate(rig.user_calls, 1): # and every check-in as the user sim got it, the opening marked scheduled + saw = c["parts"][0]["text"].strip() + if n == 1: + saw = saw.replace("] ok mom and dad", f"] {core.SCHEDULED} ok mom and dad", 1) + assert core.SCHEDULED in saw + assert "\n" + saw + "\n" in sent + assert '"dad is allergic to shellfish, swap it pls"' in sent + assert " S2 3, fine" in sent and "Table is at 7." in sent + assert "## Check-in 3 · 2026-11-12T15:00:00Z" in sent # the rating's read, a check-in of its own + assert sent.endswith("## Grading policy\n" + HARNESS) # the task's own rule, after the run + + entry = ctx.metadata["verifications"]["psi_satisfaction_grading"] + assert entry["format"] == "user_satisfaction_log" + assert (entry["run_step_id"], entry["run_kind"], entry["user_sim"], entry["judge_model"]) == ( + "week", "always_on", "user-sim", JUDGE) + assert entry["instructions"]["matches"] is True and entry["turns"] == 2 + assert [s["check_in"] for s in entry["scheduled"]] == [1] # the opening request, sent before she answered + assert entry["scheduled"][0]["text"].startswith("ok mom and dad are officially coming") + assert entry["assistant_instructions"] == "shown" and entry["read_at_end"] == 1 + # The 1-5 score has its own key; score is the grade's 0-1, so every reader of the entry gets the same number. + assert (entry["score_1_5"], entry["score"]) == (4.85, core.normalized(4.85)) + assert (entry["outcome"], entry["incidents"], entry["calls"]) == ("done", 1, 1) + assert entry["weights"] == core.WEIGHTS and entry["weights"]["cost"]["severe"] == 2.0 + assert entry["log"]["incidents"][0]["quote_found"] is True and entry["log"]["asks"][0]["could_because"] == "rules" + grade = ctx.metadata["grades"]["grading"] + assert grade["verifier_status"] == "graded" and grade["score"] == core.normalized(4.85) and grade["passed"] + assert recorded_scores([step], ctx)["grading"] == core.normalized(4.85) + assert {r["id"] for r in grade["verifier_criteria"]} == {*core.DIMENSIONS, "outcome"} + assert all(r["weight"] == 0.0 for r in grade["verifier_criteria"]) # nothing pooling them moves + assert [c["outcome"] for c in grade["judge_calls"]] == ["answered"] + assert grade["verifier_settings"]["judge_model"] == JUDGE and "score_aggregator" not in grade["verifier_settings"] + assert ctx.metadata["models"]["judge"]["grading"] == JUDGE + + +def _chat(monkeypatch, run: UserSimRun) -> TaskStepContext: + """A chat run's context, judged clean by its user sim judge, its reading stubbed as test_user_sim_judge stubs it.""" + monkeypatch.setattr(usj, "_read_run", lambda kind, step_id, record, context: ( + run, {"user_sim": "mia", "instructions": {"matches": True}})) + ctx = TaskStepContext() + ctx.prompt_responses.append(PromptResponse(prompt_id="ask", response="all set", step_id="week")) + ctx.metadata["user_sim_reads"] = {"week": [{}]} + _judged(ctx) + return ctx + + +@pytest.mark.usefixtures("local_stores", "litellm_config") +@pytest.mark.asyncio +async def test_an_answer_the_log_can_t_take_is_asked_again_with_what_was_wrong(monkeypatch): + ctx = _chat(monkeypatch, _shop()) + whole = json.dumps(_answer(incidents=[_incident("I1", 3, "contradictory_claim", "minor", "check your card")])) + cut = whole[:200] # an answer that ran out of tokens + answers = iter([cut, json.dumps(_answer(incidents=[_incident("I1", 5, "unreported_outcome", "minor", "x")])), whole]) + calls = _litellm_answers(monkeypatch, lambda kwargs: next(answers)) + + await _step().execute(ctx) + + entry = ctx.metadata["verifications"]["psi_satisfaction_grading"] + assert len(calls) == 3 and entry["calls"] == 3 and entry["incidents"] == 1 and entry["judge_output_retries"] == 2 + second, third = (c["messages"][1]["content"] for c in calls[1:]) + assert "## Correction Required" in second and "- the answer isn't a JSON object" in second + assert "- incidents[0].turn: 5 is no check-in of the run; they are [1, 2, 3]" in third + assert [d["row_problems"] for d in entry["judge_output_discrepancies"]] == [ + ["the answer isn't a JSON object"], ["incidents[0].turn: 5 is no check-in of the run; they are [1, 2, 3]"]] + assert entry["run_kind"] == "prompt_agent" + assert entry["notes"] == ["the run has no rate_user_satisfaction entry: no rating lines, and nothing read after " + "the last check-in"] + assert entry["assistant_instructions"].startswith("unknown") # built outside a task + assert calls[0]["messages"][0]["content"] == core.system_text(False) + assert [c["attempt"] for c in ctx.metadata["grades"]["grading"]["judge_calls"]] == [1, 2, 3] + + +@pytest.mark.usefixtures("local_stores", "litellm_config") +@pytest.mark.asyncio +async def test_it_sends_the_judge_s_effort_and_a_run_can_t_turn_it_into_an_agent_judge(monkeypatch): + ctx = _chat(monkeypatch, _shop()) + ctx.metadata["user_overrides"] = {"use_agent_judge": True, "judge_batch_size": 2, "judge_effort": "high"} + calls = _litellm_answers(monkeypatch, lambda kwargs: json.dumps(_answer())) + + await _step(effort="low").execute(ctx) + + [call] = calls # the direct judge, in one call, whatever the run asked + assert call["reasoning_effort"] == "high" and "temperature" not in call # the run's effort over the step's + settings = ctx.metadata["grades"]["grading"]["verifier_settings"] + assert settings["effort"] == "high" and settings["overridden"] == ["effort"] # the other two never applied + + +@pytest.mark.usefixtures("local_stores", "litellm_config") +@pytest.mark.asyncio +async def test_a_judge_that_never_answers_fails_the_grade_with_no_score_and_never_the_task(monkeypatch): + ctx = _chat(monkeypatch, _shop()) + _litellm_answers(monkeypatch, lambda kwargs: RuntimeError("the endpoint is down")) + step = _step() + assert step.fail_task_on_error is False + + with pytest.raises(RuntimeError, match="failed after 3 attempts"): + await step.execute(ctx) + + grade = ctx.metadata["grades"]["grading"] + assert (grade["verifier_status"], grade["score"]) == ("failed", None) + assert [c["outcome"] for c in grade["judge_calls"]] == ["refused"] * 3 + assert "psi_satisfaction_grading" not in ctx.metadata["verifications"] + + +@pytest.mark.usefixtures("litellm_config") +@pytest.mark.asyncio +async def test_a_run_that_ended_on_an_error_or_never_reached_the_user_sim_is_skipped(): + errored = TaskStepContext() + errored.metadata["always_on"] = {"week": {"error_type": "agent_unreachable"}} + await _step().execute(errored) + assert errored.metadata["grades"]["grading"]["verifier_skip_reasoning"] == "the run ended with error_type=" \ + "agent_unreachable" + unread = TaskStepContext() + unread.prompt_responses.append(PromptResponse(prompt_id="ask", response="done", step_id="week")) + await _step().execute(unread) + assert unread.metadata["grades"]["grading"]["verifier_status"] == "skipped" + + +@pytest.mark.parametrize("verdict, why", [ + (None, "no user_sim_judge verdict on 'week': only a run whose user sim was checked is graded"), + ({"value": "yes"}, "user_sim_judge 'usj' found user_sim_error=yes: only a run whose user sim didn't slip is graded"), + ({"value": "unknown"}, "user_sim_judge 'usj' found user_sim_error=unknown"), + ({"value": "no", "skipped": "no graded turns"}, + "user_sim_judge 'usj' didn't judge the run (no graded turns), so its user sim wasn't checked"), +]) +@pytest.mark.usefixtures("litellm_config") +@pytest.mark.asyncio +async def test_only_a_run_its_user_sim_judge_checked_and_found_clean_is_graded(monkeypatch, verdict, why): + ctx = _chat(monkeypatch, _shop()) + ctx.metadata["verifications"].clear() + if verdict is not None: + _judged(ctx, value=verdict["value"], **({"skipped": verdict["skipped"]} if "skipped" in verdict else {})) + calls = _litellm_answers(monkeypatch, lambda kwargs: json.dumps(_answer())) + + await _step().execute(ctx) + + assert calls == [] and ctx.metadata["grades"]["grading"]["verifier_skip_reasoning"].startswith(why) + + +@pytest.mark.parametrize("second, why", [ + ({"verifier_status": "failed", "score": None}, "failed"), # a judge that raised: a failed grade, and no entry + (None, "has no grade"), # one that never ran +]) +@pytest.mark.usefixtures("litellm_config") +@pytest.mark.asyncio +async def test_a_run_one_of_its_user_sim_judges_left_no_verdict_on_is_skipped_though_another_found_it_clean( + monkeypatch, second, why): + deploy, week = _user_sim_steps() + judges = [usj.UserSimJudge(j, None, run_step_id="week", depends_on=[TaskStepDependency("week")]) + for j in ("usj", "second")] + grading = _step(depends_on=[TaskStepDependency(j.id) for j in judges]) + assert grading.task_problems([deploy, week, *judges, grading]) == [] and grading._judges == ("usj", "second") + ctx = _chat(monkeypatch, _shop()) # "usj" judged the run and found it clean + if second is not None: + ctx.metadata["grades"]["second"] = second + calls = _litellm_answers(monkeypatch, lambda kwargs: json.dumps(_answer())) + + await grading.execute(ctx) + + assert calls == [] and ctx.metadata["grades"]["grading"]["verifier_skip_reasoning"] == ( + f"user_sim_judge 'second' {why}, so it left no verdict on 'week' and its user sim wasn't checked") + + +# ---- the task it's in --------------------------------------------------------------------------------------------- +def test_it_grades_a_built_in_user_sim_s_run_after_its_user_sim_judge_and_its_rating(): + deploy, week = _user_sim_steps() + after_week = [TaskStepDependency("week")] + judge = usj.UserSimJudge("judge", None, run_step_id="week", depends_on=after_week) + rate = RateUserSatisfactionTaskStep("rate", None, satisfaction=SATISFACTION, run_step_id="week", + depends_on=after_week) + + def problems(*deps: str, before=(deploy, week, judge, rate)) -> list[str]: + grading = _step(depends_on=[TaskStepDependency(d) for d in deps]) + return grading.task_problems([*before, grading]) + + assert problems("judge", "rate") == [] + told = ao.AlwaysOnTaskStep("week", None, user_sim="u", prompt_id="ask", agent_name="solver", + system_prompt="You are Pat's assistant.") + grading = _step(depends_on=[TaskStepDependency("judge"), TaskStepDependency("rate")]) + assert grading.task_problems([deploy, told, judge, rate, grading]) == [] + assert grading._assistant_prompt == "You are Pat's assistant." # what the assistant was told, read at load + assert grading._judges == ("judge",) # and the run's user sim judges, by step id, each of which must judge it + seeded = _step() + seeded.seeded_from(grading) + assert (seeded._assistant_prompt, seeded._judges) == ("You are Pat's assistant.", ("judge",)) + [no_judge] = problems("rate") + assert "it must depend on 'judge' (user_sim_judge), so a run the user sim spoiled is never graded" in no_judge + [no_rating] = problems("judge") + assert "it must depend on 'rate' (rate_user_satisfaction)" in no_rating + [unjudged] = problems("week", before=(deploy, week)) + assert "the task has no user_sim_judge of 'week'; add one and depend on it" in unjudged + early = _step(depends_on=after_week) + assert any("comes before step 'week'" in p for p in early.task_problems([deploy, early, week, judge])) + assert any("isn't a user sim" in p for p in problems("week", "judge", before=(week, judge))) + nope = _step(run_step_id="nope") + [nowhere] = nope.task_problems([deploy, week, nope]) + assert "names no step of the task" in nowhere + + +def test_it_is_recorded_only_never_the_reward_nor_a_grader_the_user_sim_judge_weighs(): + deploy, week = _user_sim_steps() + grader, grading = _grader(), _step() + task = SimpleNamespace(id="t", steps=[deploy, week, grader, grading]) + reward, why = reward_of(task, None) + assert why is None and reward({"grade": 0.25, "grading": 1.0}) == 0.25 # the task's grader, not this + assert "checks the run and can't be its reward" in reward_of(task, "grading")[1] + assert usj.grading_of(week, task.steps).criteria_steps == (grader,) + + +def test_it_is_registered_and_its_settings_round_trip(): + assert _builtin_registry()[usg.UserSatisfactionGrading.type] is usg.UserSatisfactionGrading + step = _step(judge_timeout_seconds=120, effort="high", grading_policy_prompt=HARNESS, + depends_on=[TaskStepDependency("judge")]) + data = step.to_dict() + assert data["fail_task_on_error"] is False and "min_passing_score" not in data # 0.5, a 3, by default + assert (data["effort"], data["grading_policy_prompt"], data["judge_timeout_seconds"]) == ("high", HARNESS, 120) + assert usg.UserSatisfactionGrading.from_dict(data).to_dict() == data + assert "judge_timeout_seconds" not in _step().to_dict() # rubrics_verifier's default, unset + strict = _step(min_passing_score=1.0).to_dict() + assert strict["min_passing_score"] == 1.0 and usg.UserSatisfactionGrading.from_dict(strict).min_passing_score == 1.0 + assert step.min_passing_score == 0.5 and step.criterion_rows() == len(core.DIMENSIONS) + 1 + with pytest.raises(ValueError, match=r"use_agent_judge, judge_samples can't be set on it, as it fixes them"): + usg.UserSatisfactionGrading.from_dict({**data, "use_agent_judge": True, "judge_samples": 3}) + bad = usg.UserSatisfactionGrading("grading", None, run_step_id=" ", judge_timeout_seconds=-5) + assert len(bad.config_problems()) == 2 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 f2c475b78..00ee11815 100644 --- a/tst/unit/task_step/verifiers/test_user_sim_judge.py +++ b/tst/unit/task_step/verifiers/test_user_sim_judge.py @@ -650,7 +650,7 @@ async def test_on_a_chat_run_the_judge_reads_each_stored_read_and_the_prompt_it_ shown = run_text.split("\n")[1].split("\n")[0] + "\n" assert hashlib.sha256(shown.encode()).hexdigest() == us["prompt_sha256"] # the prompt deploy_user_sim_agent set for summary in ctx.metadata["user_sim_reads"]["talk"]: - full = usj._load(summary["object_url"]) + full = usj.load_stored(summary["object_url"]) assert "\n" + full["input"].strip() + "\n" in run_text assert 'outcome: reply\nmessage: "make it shorter"' in run_text and "D1" not in run_text.split("")[1] assert 'outcome: done\nmessage: "perfect, thanks!"' in run_text @@ -719,13 +719,15 @@ async def test_a_chat_run_that_ended_in_an_error_or_where_the_user_sim_never_rea def test_the_run_is_the_one_run_step_id_names(): ctx = TaskStepContext() ctx.metadata = {"always_on": {"week": {}}, "user_sim_reads": {"talk": [{}]}} - with pytest.raises(StepContextError, match="step 'nope' left no run to judge"): - usj.UserSimJudge("j", None, run_step_id="nope")._find_run(ctx) - assert usj.UserSimJudge("j", None, run_step_id="talk")._find_run(ctx) == ("prompt_agent", "talk") - assert usj.UserSimJudge("j", None, run_step_id="week")._find_run(ctx) == ("always_on", "week") + with pytest.raises(StepContextError, match="user_sim_judge 'j': step 'nope' left no run to judge"): + usj.find_run(ctx, "nope", "user_sim_judge 'j'") + found = lambda step_id: usj.find_run(ctx, step_id, "user_sim_judge 'j'") # noqa: E731 + assert (found("talk").kind, found("talk").skipped) == ("prompt_agent", None) + assert (found("week").kind, found("week").record, found("week").skipped) == ("always_on", {}, None) # A one-turn chat ends before its user sim reads: it leaves a response and no reads, and is skipped, not refused. ctx.prompt_responses.append(PromptResponse(prompt_id="ask1", response="done", step_id="one-turn")) - assert usj.UserSimJudge("j", None, run_step_id="one-turn")._find_run(ctx) == ("prompt_agent", "one-turn") + assert (found("one-turn").kind, found("one-turn").response.prompt_id, found("one-turn").skipped) == ( + "prompt_agent", "ask1", "the user sim never read: the run has no user_sim_reads") # ---- the judge's calls, through litellm -----------------------------------------------------------------------------