Publish tiny_computer_agent/ from marimo
Browse files- tiny_computer_agent/__init__.py +31 -6
- tiny_computer_agent/__main__.py +15 -0
- tiny_computer_agent/trace.py +539 -0
tiny_computer_agent/__init__.py
CHANGED
|
@@ -14,6 +14,15 @@ call at run time, and the core imports nothing outside the standard library.
|
|
| 14 |
loop = AgentLoop(screen=screen, brain=brain) # dry run by default
|
| 15 |
episode = loop.run("save the document")
|
| 16 |
print(episode.render())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
"""
|
| 18 |
|
| 19 |
from tiny_computer_agent.act import (
|
|
@@ -74,8 +83,22 @@ from tiny_computer_agent.perception import (
|
|
| 74 |
make_detector,
|
| 75 |
)
|
| 76 |
from tiny_computer_agent.safety import Policy, PolicyViolation
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
-
__version__ = "0.
|
| 79 |
|
| 80 |
__all__ = [
|
| 81 |
"ACTION_KINDS", "ACTION_MENU", "Action", "ActionError", "ActionResult",
|
|
@@ -84,9 +107,11 @@ __all__ = [
|
|
| 84 |
"Episode", "Executor", "FakeScreen", "GoalUnreachable", "GrabScreen",
|
| 85 |
"IndexedScreen", "InputUnavailable", "MODEL_BRAINS", "MenuItem", "MockBrain",
|
| 86 |
"ModelBrain", "Observation", "OcrDetector", "PlannerBrain", "Policy",
|
| 87 |
-
"PolicyViolation", "PyAutoGuiExecutor", "
|
| 88 |
-
"Step", "TextPlannerBrain", "
|
| 89 |
-
"
|
| 90 |
-
"
|
| 91 |
-
"
|
|
|
|
|
|
|
| 92 |
]
|
|
|
|
| 14 |
loop = AgentLoop(screen=screen, brain=brain) # dry run by default
|
| 15 |
episode = loop.run("save the document")
|
| 16 |
print(episode.render())
|
| 17 |
+
|
| 18 |
+
An episode can be saved as a portable *trace*, replayed offline, and scored, so
|
| 19 |
+
"the model looked plausible on that screenshot" becomes a number:
|
| 20 |
+
|
| 21 |
+
from tiny_computer_agent import Trace, benchmark, run_scenario
|
| 22 |
+
|
| 23 |
+
trace = run_scenario(Scenario("click 'Save'", frames=[...], expected="Save"), brain)
|
| 24 |
+
trace.save("traces/save.json") # diffable, no pixels
|
| 25 |
+
print(benchmark(scenarios, {"planner": lambda s: PlannerBrain()}).render())
|
| 26 |
"""
|
| 27 |
|
| 28 |
from tiny_computer_agent.act import (
|
|
|
|
| 83 |
make_detector,
|
| 84 |
)
|
| 85 |
from tiny_computer_agent.safety import Policy, PolicyViolation
|
| 86 |
+
from tiny_computer_agent.trace import (
|
| 87 |
+
Scenario,
|
| 88 |
+
Scoreboard,
|
| 89 |
+
Trace,
|
| 90 |
+
TraceStep,
|
| 91 |
+
Verdict,
|
| 92 |
+
benchmark,
|
| 93 |
+
benchmark_traces,
|
| 94 |
+
load_traces,
|
| 95 |
+
run_scenario,
|
| 96 |
+
score,
|
| 97 |
+
score_replay,
|
| 98 |
+
score_trace,
|
| 99 |
+
)
|
| 100 |
|
| 101 |
+
__version__ = "0.3.0"
|
| 102 |
|
| 103 |
__all__ = [
|
| 104 |
"ACTION_KINDS", "ACTION_MENU", "Action", "ActionError", "ActionResult",
|
|
|
|
| 107 |
"Episode", "Executor", "FakeScreen", "GoalUnreachable", "GrabScreen",
|
| 108 |
"IndexedScreen", "InputUnavailable", "MODEL_BRAINS", "MenuItem", "MockBrain",
|
| 109 |
"ModelBrain", "Observation", "OcrDetector", "PlannerBrain", "Policy",
|
| 110 |
+
"PolicyViolation", "PyAutoGuiExecutor", "Scenario", "Scoreboard", "ScreenSource",
|
| 111 |
+
"ScreenUnavailable", "Step", "TextPlannerBrain", "Trace", "TraceStep", "VLMBrain",
|
| 112 |
+
"Verdict", "benchmark", "benchmark_traces", "detector_available",
|
| 113 |
+
"extract_json_object", "extract_json_objects", "load_traces", "make_detector",
|
| 114 |
+
"make_model_brain", "model_cached", "model_dependencies", "normalise_label",
|
| 115 |
+
"parse_action", "parse_decision", "resolve_device", "resolve_point",
|
| 116 |
+
"run_scenario", "score", "score_replay", "score_trace", "__version__",
|
| 117 |
]
|
tiny_computer_agent/__main__.py
CHANGED
|
@@ -32,6 +32,7 @@ from tiny_computer_agent.observe import (
|
|
| 32 |
)
|
| 33 |
from tiny_computer_agent.perception import IndexedScreen, detector_available, make_detector
|
| 34 |
from tiny_computer_agent.safety import Policy
|
|
|
|
| 35 |
|
| 36 |
ALLOW_REAL_INPUT_ENV = "TINY_COMPUTER_AGENT_ALLOW_REAL_INPUT"
|
| 37 |
EXAMPLE_IMAGE = "example"
|
|
@@ -88,6 +89,12 @@ def build_parser() -> argparse.ArgumentParser:
|
|
| 88 |
help="permit clicks on numbered grid cells with --real-input")
|
| 89 |
parser.add_argument("--kill-switch", default=DEFAULT_KILL_SWITCH,
|
| 90 |
help="create this file to abort the run before the next action")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
return parser
|
| 92 |
|
| 93 |
|
|
@@ -247,6 +254,14 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 247 |
|
| 248 |
print()
|
| 249 |
print(episode.render())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
return 0 if episode.success else 1
|
| 251 |
|
| 252 |
|
|
|
|
| 32 |
)
|
| 33 |
from tiny_computer_agent.perception import IndexedScreen, detector_available, make_detector
|
| 34 |
from tiny_computer_agent.safety import Policy
|
| 35 |
+
from tiny_computer_agent.trace import Trace, score_trace
|
| 36 |
|
| 37 |
ALLOW_REAL_INPUT_ENV = "TINY_COMPUTER_AGENT_ALLOW_REAL_INPUT"
|
| 38 |
EXAMPLE_IMAGE = "example"
|
|
|
|
| 89 |
help="permit clicks on numbered grid cells with --real-input")
|
| 90 |
parser.add_argument("--kill-switch", default=DEFAULT_KILL_SWITCH,
|
| 91 |
help="create this file to abort the run before the next action")
|
| 92 |
+
parser.add_argument("--trace", default=None, metavar="PATH",
|
| 93 |
+
help="write a portable trace of the run (frames, no pixels) so it "
|
| 94 |
+
"can be replayed and scored offline")
|
| 95 |
+
parser.add_argument("--expected", default=None, metavar="LABEL",
|
| 96 |
+
help="the element label that is the right answer for this goal; "
|
| 97 |
+
"recorded in the trace so the run can be scored")
|
| 98 |
return parser
|
| 99 |
|
| 100 |
|
|
|
|
| 254 |
|
| 255 |
print()
|
| 256 |
print(episode.render())
|
| 257 |
+
|
| 258 |
+
if args.trace:
|
| 259 |
+
trace = Trace.record(episode, expected=args.expected, brain=args.brain,
|
| 260 |
+
scenario=args.goal)
|
| 261 |
+
print(f"trace: wrote {trace.save(args.trace)} ({trace.frames} frames)")
|
| 262 |
+
if args.expected:
|
| 263 |
+
print("score: " + score_trace(trace).line().strip())
|
| 264 |
+
print(f" replay it later: Trace.load({str(args.trace)!r}).render()")
|
| 265 |
return 0 if episode.success else 1
|
| 266 |
|
| 267 |
|
tiny_computer_agent/trace.py
ADDED
|
@@ -0,0 +1,539 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Traces: an episode you can save, replay and score.
|
| 2 |
+
|
| 3 |
+
An :class:`~tiny_computer_agent.loop.Episode` is the record of one run; a **trace**
|
| 4 |
+
is that record made portable. A trace keeps each frame's *element index* - the
|
| 5 |
+
labels and their geometry - but never the pixels, so it replays on a machine with
|
| 6 |
+
no display, no OCR engine and no model weights: hand the recorded frames back to a
|
| 7 |
+
brain and count how often it picks the element the trace says was right.
|
| 8 |
+
|
| 9 |
+
That count is the whole point of this module. It is what turns "the model looked
|
| 10 |
+
plausible on that one screenshot" into an **accuracy** you can compare between
|
| 11 |
+
brains, put in a table, and regression-test in CI - the harness's own answer to the
|
| 12 |
+
question the results table keeps asking: *which brain is actually right, and how
|
| 13 |
+
often?*
|
| 14 |
+
|
| 15 |
+
Two judgements are kept apart on purpose. The score is about the brain's
|
| 16 |
+
**decision** - what it chose when it had to commit. Whether the harness *allowed*
|
| 17 |
+
that decision to run is a separate axis, reported by :attr:`Verdict.blocked`, so a
|
| 18 |
+
policy refusal can never masquerade as a clean success (the harness owns success)
|
| 19 |
+
nor hide a brain that chose correctly.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
from __future__ import annotations
|
| 23 |
+
|
| 24 |
+
import json
|
| 25 |
+
from dataclasses import dataclass, field, replace
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
from typing import Any, Callable, Mapping, Sequence
|
| 28 |
+
|
| 29 |
+
from tiny_computer_agent.actions import Action, parse_action
|
| 30 |
+
from tiny_computer_agent.brain import Brain
|
| 31 |
+
from tiny_computer_agent.loop import AgentLoop, Episode
|
| 32 |
+
from tiny_computer_agent.observe import (
|
| 33 |
+
Element,
|
| 34 |
+
FakeScreen,
|
| 35 |
+
Observation,
|
| 36 |
+
normalise_label,
|
| 37 |
+
)
|
| 38 |
+
from tiny_computer_agent.safety import Policy
|
| 39 |
+
|
| 40 |
+
TRACE_VERSION = 1
|
| 41 |
+
DONE = "done"
|
| 42 |
+
NOTHING = "nothing"
|
| 43 |
+
|
| 44 |
+
# The fields of Element, in one place, so serialisation and Element stay in step.
|
| 45 |
+
_ELEMENT_FIELDS = ("label", "kind", "x", "y", "width", "height")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _element_to_dict(element: Element) -> dict[str, Any]:
|
| 49 |
+
return {name: getattr(element, name) for name in _ELEMENT_FIELDS}
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _element_from_dict(data: Mapping[str, Any]) -> Element:
|
| 53 |
+
return Element(**{name: data[name] for name in _ELEMENT_FIELDS if name in data})
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@dataclass(frozen=True)
|
| 57 |
+
class TraceStep:
|
| 58 |
+
"""One recorded frame: what was on screen, and what the brain did about it."""
|
| 59 |
+
|
| 60 |
+
index: int
|
| 61 |
+
elements: tuple[Element, ...] = ()
|
| 62 |
+
text: str = ""
|
| 63 |
+
action: Action | None = None
|
| 64 |
+
error: str | None = None
|
| 65 |
+
outcome: str = ""
|
| 66 |
+
|
| 67 |
+
def observation(self) -> Observation:
|
| 68 |
+
"""The frame as the brain saw it - pixels deliberately omitted."""
|
| 69 |
+
return Observation(index=self.index, elements=self.elements, text=self.text)
|
| 70 |
+
|
| 71 |
+
def to_dict(self) -> dict[str, Any]:
|
| 72 |
+
return {
|
| 73 |
+
"index": self.index,
|
| 74 |
+
"elements": [_element_to_dict(e) for e in self.elements],
|
| 75 |
+
"text": self.text,
|
| 76 |
+
"action": self.action.to_dict() if self.action is not None else None,
|
| 77 |
+
"error": self.error,
|
| 78 |
+
"outcome": self.outcome,
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
@classmethod
|
| 82 |
+
def from_dict(cls, data: Mapping[str, Any]) -> TraceStep:
|
| 83 |
+
raw_action = data.get("action")
|
| 84 |
+
return cls(
|
| 85 |
+
index=int(data.get("index", 0)),
|
| 86 |
+
elements=tuple(_element_from_dict(e) for e in data.get("elements", ())),
|
| 87 |
+
text=data.get("text", ""),
|
| 88 |
+
action=parse_action(raw_action) if raw_action else None,
|
| 89 |
+
error=data.get("error"),
|
| 90 |
+
outcome=data.get("outcome", ""),
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
@dataclass
|
| 95 |
+
class Trace:
|
| 96 |
+
"""A saved run: the frames, the decisions, and the answer that was right.
|
| 97 |
+
|
| 98 |
+
``expected`` is the ground truth a scorer compares against. It lives on the
|
| 99 |
+
trace rather than on a step because a task has one correct *choice*, not one
|
| 100 |
+
correct action per turn - the waits and retries on the way there are not
|
| 101 |
+
decisions about what to do.
|
| 102 |
+
"""
|
| 103 |
+
|
| 104 |
+
goal: str
|
| 105 |
+
expected: str | None = None
|
| 106 |
+
brain: str = ""
|
| 107 |
+
scenario: str = ""
|
| 108 |
+
steps: list[TraceStep] = field(default_factory=list)
|
| 109 |
+
success: bool = False
|
| 110 |
+
stop_reason: str = ""
|
| 111 |
+
|
| 112 |
+
# -- recording ---------------------------------------------------------
|
| 113 |
+
|
| 114 |
+
@classmethod
|
| 115 |
+
def record(
|
| 116 |
+
cls,
|
| 117 |
+
episode: Episode,
|
| 118 |
+
*,
|
| 119 |
+
expected: str | None = None,
|
| 120 |
+
brain: str = "",
|
| 121 |
+
scenario: str = "",
|
| 122 |
+
) -> Trace:
|
| 123 |
+
"""Copy an episode into a portable trace (no pixels, no live objects)."""
|
| 124 |
+
return cls(
|
| 125 |
+
goal=episode.goal,
|
| 126 |
+
expected=expected,
|
| 127 |
+
brain=brain,
|
| 128 |
+
scenario=scenario,
|
| 129 |
+
steps=[
|
| 130 |
+
TraceStep(
|
| 131 |
+
index=step.index,
|
| 132 |
+
elements=tuple(step.observation.elements),
|
| 133 |
+
text=step.observation.text,
|
| 134 |
+
action=step.action,
|
| 135 |
+
error=step.error,
|
| 136 |
+
outcome=step.result.summary() if step.result is not None else "",
|
| 137 |
+
)
|
| 138 |
+
for step in episode.steps
|
| 139 |
+
],
|
| 140 |
+
success=episode.success,
|
| 141 |
+
stop_reason=episode.stop_reason,
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
# -- reading -----------------------------------------------------------
|
| 145 |
+
|
| 146 |
+
@property
|
| 147 |
+
def name(self) -> str:
|
| 148 |
+
return self.scenario or self.goal
|
| 149 |
+
|
| 150 |
+
@property
|
| 151 |
+
def frames(self) -> int:
|
| 152 |
+
return len(self.steps)
|
| 153 |
+
|
| 154 |
+
def decision_step(self) -> TraceStep | None:
|
| 155 |
+
"""The step where the brain committed: first labelled click, else first ``done``.
|
| 156 |
+
|
| 157 |
+
Waits are skipped - waiting is patience, not a choice about what to do.
|
| 158 |
+
"""
|
| 159 |
+
for step in self.steps:
|
| 160 |
+
action = step.action
|
| 161 |
+
if action is None:
|
| 162 |
+
continue
|
| 163 |
+
if action.kind == "click" and action.label:
|
| 164 |
+
return step
|
| 165 |
+
if action.kind == "done":
|
| 166 |
+
return step
|
| 167 |
+
return None
|
| 168 |
+
|
| 169 |
+
@property
|
| 170 |
+
def choice(self) -> str | None:
|
| 171 |
+
"""The label the brain chose, or None when it committed to no element."""
|
| 172 |
+
step = self.decision_step()
|
| 173 |
+
if step is not None and step.action is not None and step.action.kind == "click":
|
| 174 |
+
return step.action.label
|
| 175 |
+
return None
|
| 176 |
+
|
| 177 |
+
@property
|
| 178 |
+
def decided(self) -> str:
|
| 179 |
+
"""What the brain committed to: a label, the bare word ``done``, or nothing.
|
| 180 |
+
|
| 181 |
+
Kept deliberately blunt so a mis-scored run shows up in the table: a brain
|
| 182 |
+
that answered "done" before ever looking has not chosen the right element.
|
| 183 |
+
"""
|
| 184 |
+
step = self.decision_step()
|
| 185 |
+
if step is None or step.action is None:
|
| 186 |
+
return NOTHING
|
| 187 |
+
return step.action.label if step.action.kind == "click" else DONE
|
| 188 |
+
|
| 189 |
+
@property
|
| 190 |
+
def blocked(self) -> bool:
|
| 191 |
+
"""True when the harness stopped the deciding action (e.g. a policy refusal)."""
|
| 192 |
+
step = self.decision_step()
|
| 193 |
+
return step is not None and step.error is not None
|
| 194 |
+
|
| 195 |
+
def observations(self) -> list[Observation]:
|
| 196 |
+
return [step.observation() for step in self.steps]
|
| 197 |
+
|
| 198 |
+
def render(self) -> str:
|
| 199 |
+
"""A compact, replayable summary - the trace's own version of Episode.render()."""
|
| 200 |
+
header = f"trace: {self.name}"
|
| 201 |
+
if self.brain:
|
| 202 |
+
header += f" (brain: {self.brain})"
|
| 203 |
+
lines = [
|
| 204 |
+
header,
|
| 205 |
+
f"goal: {self.goal}",
|
| 206 |
+
f"expected: {self.expected!r} chose: {self.decided!r}"
|
| 207 |
+
+ (" (the harness refused it)" if self.blocked else ""),
|
| 208 |
+
f"result: {'success' if self.success else 'failure'} - {self.stop_reason}",
|
| 209 |
+
]
|
| 210 |
+
for step in self.steps:
|
| 211 |
+
if step.action is not None:
|
| 212 |
+
body = step.action.describe()
|
| 213 |
+
else:
|
| 214 |
+
body = step.error or "no action"
|
| 215 |
+
lines.append(f" {step.index} | {body}")
|
| 216 |
+
return "\n".join(lines)
|
| 217 |
+
|
| 218 |
+
# -- replay ------------------------------------------------------------
|
| 219 |
+
|
| 220 |
+
def replay(self, brain: Brain) -> Trace:
|
| 221 |
+
"""Answer the recorded frames again with a (usually different) brain.
|
| 222 |
+
|
| 223 |
+
Nothing is captured and nothing is clicked: this is the offline half of
|
| 224 |
+
"replay a trace", and it is why a trace can be scored on any machine.
|
| 225 |
+
"""
|
| 226 |
+
steps: list[TraceStep] = []
|
| 227 |
+
for step in self.steps:
|
| 228 |
+
try:
|
| 229 |
+
action = brain.decide(self.goal, step.observation())
|
| 230 |
+
steps.append(replace(step, action=action, error=None, outcome="replayed"))
|
| 231 |
+
except Exception as exc: # a brain that fails is a scored outcome, not a crash
|
| 232 |
+
steps.append(
|
| 233 |
+
replace(step, action=None, error=f"{type(exc).__name__}: {exc}", outcome="")
|
| 234 |
+
)
|
| 235 |
+
return Trace(
|
| 236 |
+
goal=self.goal,
|
| 237 |
+
expected=self.expected,
|
| 238 |
+
brain=getattr(brain, "name", type(brain).__name__),
|
| 239 |
+
scenario=self.scenario,
|
| 240 |
+
steps=steps,
|
| 241 |
+
success=False,
|
| 242 |
+
stop_reason="replayed",
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
# -- persistence -------------------------------------------------------
|
| 246 |
+
|
| 247 |
+
def to_dict(self) -> dict[str, Any]:
|
| 248 |
+
return {
|
| 249 |
+
"trace_version": TRACE_VERSION,
|
| 250 |
+
"goal": self.goal,
|
| 251 |
+
"expected": self.expected,
|
| 252 |
+
"brain": self.brain,
|
| 253 |
+
"scenario": self.scenario,
|
| 254 |
+
"success": self.success,
|
| 255 |
+
"stop_reason": self.stop_reason,
|
| 256 |
+
"steps": [step.to_dict() for step in self.steps],
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
@classmethod
|
| 260 |
+
def from_dict(cls, data: Mapping[str, Any]) -> Trace:
|
| 261 |
+
version = int(data.get("trace_version", TRACE_VERSION))
|
| 262 |
+
if version > TRACE_VERSION:
|
| 263 |
+
raise ValueError(
|
| 264 |
+
f"trace_version {version} is newer than this build understands "
|
| 265 |
+
f"({TRACE_VERSION}); upgrade tiny-computer-agent to read it"
|
| 266 |
+
)
|
| 267 |
+
return cls(
|
| 268 |
+
goal=data.get("goal", ""),
|
| 269 |
+
expected=data.get("expected"),
|
| 270 |
+
brain=data.get("brain", ""),
|
| 271 |
+
scenario=data.get("scenario", ""),
|
| 272 |
+
steps=[TraceStep.from_dict(step) for step in data.get("steps", ())],
|
| 273 |
+
success=bool(data.get("success", False)),
|
| 274 |
+
stop_reason=data.get("stop_reason", ""),
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
def to_json(self, *, indent: int = 2) -> str:
|
| 278 |
+
return json.dumps(self.to_dict(), indent=indent, ensure_ascii=False)
|
| 279 |
+
|
| 280 |
+
@classmethod
|
| 281 |
+
def from_json(cls, text: str) -> Trace:
|
| 282 |
+
return cls.from_dict(json.loads(text))
|
| 283 |
+
|
| 284 |
+
def save(self, path: str | Path) -> Path:
|
| 285 |
+
target = Path(path)
|
| 286 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 287 |
+
target.write_text(self.to_json() + "\n", encoding="utf-8")
|
| 288 |
+
return target
|
| 289 |
+
|
| 290 |
+
@classmethod
|
| 291 |
+
def load(cls, path: str | Path) -> Trace:
|
| 292 |
+
return cls.from_json(Path(path).read_text(encoding="utf-8"))
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def load_traces(path: str | Path) -> list[Trace]:
|
| 296 |
+
"""Every trace in a file or a directory of ``*.json`` traces, in name order."""
|
| 297 |
+
target = Path(path)
|
| 298 |
+
files = sorted(target.glob("*.json")) if target.is_dir() else [target]
|
| 299 |
+
return [Trace.load(file) for file in files]
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
# -- scoring ---------------------------------------------------------------
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
@dataclass(frozen=True)
|
| 306 |
+
class Verdict:
|
| 307 |
+
"""One trace, judged: did the brain choose what the trace says was right?"""
|
| 308 |
+
|
| 309 |
+
scenario: str
|
| 310 |
+
expected: str | None
|
| 311 |
+
chosen: str
|
| 312 |
+
correct: bool
|
| 313 |
+
brain: str = ""
|
| 314 |
+
blocked: bool = False
|
| 315 |
+
detail: str = ""
|
| 316 |
+
|
| 317 |
+
def line(self) -> str:
|
| 318 |
+
mark = "correct " if self.correct else "incorrect"
|
| 319 |
+
line = f" {mark} {self.scenario}: expected {self.expected!r}, chose {self.chosen!r}"
|
| 320 |
+
if self.blocked:
|
| 321 |
+
line += " (harness refused it)"
|
| 322 |
+
elif self.detail:
|
| 323 |
+
line += f" ({self.detail})"
|
| 324 |
+
return line
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def score_trace(trace: Trace) -> Verdict:
|
| 328 |
+
"""Judge one recorded choice against the trace's ground truth.
|
| 329 |
+
|
| 330 |
+
Comparison is on :func:`~tiny_computer_agent.observe.normalise_label`, so a
|
| 331 |
+
choice the OCR rendered as ``"Save ."`` is still credited for ``"Save"`` - the
|
| 332 |
+
same forgiveness the element index uses everywhere else. A decision the policy
|
| 333 |
+
refused is still scored on the *choice* (that is what the benchmark measures),
|
| 334 |
+
and flagged by :attr:`Verdict.blocked` rather than counted as a clean success.
|
| 335 |
+
"""
|
| 336 |
+
chosen = trace.decided
|
| 337 |
+
expected = trace.expected
|
| 338 |
+
if expected is None:
|
| 339 |
+
return Verdict(
|
| 340 |
+
scenario=trace.name, expected=None, chosen=chosen, correct=False,
|
| 341 |
+
brain=trace.brain, blocked=trace.blocked,
|
| 342 |
+
detail="trace records no expected answer to score against",
|
| 343 |
+
)
|
| 344 |
+
correct = normalise_label(chosen) == normalise_label(expected)
|
| 345 |
+
detail = "" if correct else (
|
| 346 |
+
f"chose {chosen!r}, not {expected!r}" if chosen != NOTHING
|
| 347 |
+
else "never committed to a choice"
|
| 348 |
+
)
|
| 349 |
+
return Verdict(
|
| 350 |
+
scenario=trace.name, expected=expected, chosen=chosen, correct=correct,
|
| 351 |
+
brain=trace.brain, blocked=trace.blocked, detail=detail,
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def score_replay(trace: Trace, brain: Brain) -> Verdict:
|
| 356 |
+
""""Replay a trace, count how often the choice was right", for a single trace."""
|
| 357 |
+
return score_trace(trace.replay(brain))
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
@dataclass
|
| 361 |
+
class Scoreboard:
|
| 362 |
+
"""Verdicts collected into an accuracy - the number this whole module exists for."""
|
| 363 |
+
|
| 364 |
+
verdicts: list[Verdict] = field(default_factory=list)
|
| 365 |
+
|
| 366 |
+
def __len__(self) -> int:
|
| 367 |
+
return len(self.verdicts)
|
| 368 |
+
|
| 369 |
+
def __iter__(self):
|
| 370 |
+
return iter(self.verdicts)
|
| 371 |
+
|
| 372 |
+
def add(self, verdict: Verdict) -> Scoreboard:
|
| 373 |
+
self.verdicts.append(verdict)
|
| 374 |
+
return self
|
| 375 |
+
|
| 376 |
+
@property
|
| 377 |
+
def total(self) -> int:
|
| 378 |
+
return len(self.verdicts)
|
| 379 |
+
|
| 380 |
+
@property
|
| 381 |
+
def earned(self) -> int:
|
| 382 |
+
return sum(1 for verdict in self.verdicts if verdict.correct)
|
| 383 |
+
|
| 384 |
+
@property
|
| 385 |
+
def accuracy(self) -> float:
|
| 386 |
+
"""Share of decisions that matched the right answer, 0.0 when empty."""
|
| 387 |
+
return self.earned / self.total if self.total else 0.0
|
| 388 |
+
|
| 389 |
+
@property
|
| 390 |
+
def blocked(self) -> int:
|
| 391 |
+
"""Decisions the harness stopped, whatever the score - a separate axis."""
|
| 392 |
+
return sum(1 for verdict in self.verdicts if verdict.blocked)
|
| 393 |
+
|
| 394 |
+
def brains(self) -> list[str]:
|
| 395 |
+
"""Every brain that appears, in first-seen order, so tables stay stable."""
|
| 396 |
+
seen: list[str] = []
|
| 397 |
+
for verdict in self.verdicts:
|
| 398 |
+
if verdict.brain not in seen:
|
| 399 |
+
seen.append(verdict.brain)
|
| 400 |
+
return seen
|
| 401 |
+
|
| 402 |
+
def accuracy_for(self, brain: str) -> float:
|
| 403 |
+
rows = [v for v in self.verdicts if v.brain == brain]
|
| 404 |
+
return sum(1 for v in rows if v.correct) / len(rows) if rows else 0.0
|
| 405 |
+
|
| 406 |
+
def by_brain(self) -> dict[str, float]:
|
| 407 |
+
return {brain: self.accuracy_for(brain) for brain in self.brains()}
|
| 408 |
+
|
| 409 |
+
def to_rows(self) -> list[dict[str, Any]]:
|
| 410 |
+
"""Rows for a dataframe / notebook table. ``correct`` is a plain bool."""
|
| 411 |
+
return [
|
| 412 |
+
{
|
| 413 |
+
"brain": verdict.brain or "-",
|
| 414 |
+
"scenario": verdict.scenario,
|
| 415 |
+
"expected": verdict.expected,
|
| 416 |
+
"chose": verdict.chosen,
|
| 417 |
+
"correct": verdict.correct,
|
| 418 |
+
}
|
| 419 |
+
for verdict in self.verdicts
|
| 420 |
+
]
|
| 421 |
+
|
| 422 |
+
def confusion(self) -> dict[tuple[str, str], int]:
|
| 423 |
+
"""(expected, chose) -> count, for the cases a scalar accuracy hides."""
|
| 424 |
+
counts: dict[tuple[str, str], int] = {}
|
| 425 |
+
for verdict in self.verdicts:
|
| 426 |
+
key = (verdict.expected or "-", verdict.chosen)
|
| 427 |
+
counts[key] = counts.get(key, 0) + 1
|
| 428 |
+
return counts
|
| 429 |
+
|
| 430 |
+
def render(self) -> str:
|
| 431 |
+
lines = [f"scoreboard: {self.earned}/{self.total} correct ({self.accuracy:.0%})"]
|
| 432 |
+
lines += [f" {brain or '-'}: {self.accuracy_for(brain):.0%}" for brain in self.brains()]
|
| 433 |
+
lines += [verdict.line() for verdict in self.verdicts]
|
| 434 |
+
if self.blocked:
|
| 435 |
+
lines.append(f" ({self.blocked} decision(s) stopped by the harness)")
|
| 436 |
+
return "\n".join(lines)
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
# -- a suite of tasks, for benchmarking -----------------------------------
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
@dataclass(frozen=True)
|
| 443 |
+
class Scenario:
|
| 444 |
+
"""A task with one element that is the right answer, and the frames to show."""
|
| 445 |
+
|
| 446 |
+
goal: str
|
| 447 |
+
frames: tuple[tuple[Element, ...], ...]
|
| 448 |
+
expected: str
|
| 449 |
+
text: str = ""
|
| 450 |
+
name: str = ""
|
| 451 |
+
|
| 452 |
+
def __post_init__(self) -> None:
|
| 453 |
+
if not self.frames:
|
| 454 |
+
raise ValueError("a scenario needs at least one frame")
|
| 455 |
+
# freeze the frames so a scenario can be replayed and compared safely
|
| 456 |
+
object.__setattr__(self, "frames", tuple(tuple(frame) for frame in self.frames))
|
| 457 |
+
|
| 458 |
+
@property
|
| 459 |
+
def label(self) -> str:
|
| 460 |
+
return self.name or self.goal
|
| 461 |
+
|
| 462 |
+
def screen(self) -> FakeScreen:
|
| 463 |
+
"""A fresh screen each time, so one scenario can be run against many brains."""
|
| 464 |
+
return FakeScreen(list(self.frames), text=self.text)
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
def run_scenario(
|
| 468 |
+
scenario: Scenario, brain: Brain, *, brain_name: str = "", max_steps: int = 6
|
| 469 |
+
) -> Trace:
|
| 470 |
+
"""Run one scenario and return its trace, ground truth included."""
|
| 471 |
+
episode = AgentLoop(
|
| 472 |
+
screen=scenario.screen(),
|
| 473 |
+
brain=brain,
|
| 474 |
+
policy=Policy(step_budget=max_steps),
|
| 475 |
+
).run(scenario.goal)
|
| 476 |
+
return Trace.record(
|
| 477 |
+
episode,
|
| 478 |
+
expected=scenario.expected,
|
| 479 |
+
brain=brain_name or getattr(brain, "name", type(brain).__name__),
|
| 480 |
+
scenario=scenario.label,
|
| 481 |
+
)
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
def score(scenario: Scenario, brain: Brain, *, brain_name: str = "", max_steps: int = 6) -> Verdict:
|
| 485 |
+
return score_trace(run_scenario(scenario, brain, brain_name=brain_name, max_steps=max_steps))
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
def benchmark(
|
| 489 |
+
scenarios: Sequence[Scenario],
|
| 490 |
+
brains: Mapping[str, Callable[[Scenario], Brain]],
|
| 491 |
+
*,
|
| 492 |
+
max_steps: int = 6,
|
| 493 |
+
) -> Scoreboard:
|
| 494 |
+
"""Run every scenario through every brain, scoring the choice each one made.
|
| 495 |
+
|
| 496 |
+
``brains`` maps a display name to a *factory* taking the scenario, because some
|
| 497 |
+
brains (a scripted :class:`~tiny_computer_agent.brain.MockBrain`, say) need to see
|
| 498 |
+
the task before they can answer it, and because a fresh brain per task keeps state
|
| 499 |
+
like "already clicked this" from leaking between scenarios.
|
| 500 |
+
"""
|
| 501 |
+
board = Scoreboard()
|
| 502 |
+
for scenario in scenarios:
|
| 503 |
+
for name, factory in brains.items():
|
| 504 |
+
board.add(score(scenario, factory(scenario), brain_name=name, max_steps=max_steps))
|
| 505 |
+
return board
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
def benchmark_traces(traces: Sequence[Trace], brain: Brain, *, name: str = "") -> Scoreboard:
|
| 509 |
+
"""Replay recorded traces against one brain and count how often it was right.
|
| 510 |
+
|
| 511 |
+
The literal roadmap step: the frames are already recorded, nothing new is
|
| 512 |
+
captured, and the only variable is the brain under test.
|
| 513 |
+
"""
|
| 514 |
+
label = name or getattr(brain, "name", type(brain).__name__)
|
| 515 |
+
board = Scoreboard()
|
| 516 |
+
for trace in traces:
|
| 517 |
+
replayed = trace.replay(brain)
|
| 518 |
+
replayed.brain = label
|
| 519 |
+
board.add(score_trace(replayed))
|
| 520 |
+
return board
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
__all__ = [
|
| 524 |
+
"DONE",
|
| 525 |
+
"NOTHING",
|
| 526 |
+
"TRACE_VERSION",
|
| 527 |
+
"Scenario",
|
| 528 |
+
"Scoreboard",
|
| 529 |
+
"Trace",
|
| 530 |
+
"TraceStep",
|
| 531 |
+
"Verdict",
|
| 532 |
+
"benchmark",
|
| 533 |
+
"benchmark_traces",
|
| 534 |
+
"load_traces",
|
| 535 |
+
"run_scenario",
|
| 536 |
+
"score",
|
| 537 |
+
"score_replay",
|
| 538 |
+
"score_trace",
|
| 539 |
+
]
|