agent-jit-runtime 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,94 @@
1
+ """Baselines the JIT is compared against.
2
+
3
+ Each baseline runs a request and returns ``(answer, llm_tokens, path)``. They cannot tell a
4
+ correct run from a wrong one; the harness scores every episode with the environment's own check,
5
+ so a cache hit that skips a task's writes fails that check.
6
+
7
+ * ``PlainBaseline``: the agent with no caching.
8
+ * ``ExactMatchCache``: answers an identical request from the stored answer, running no tools.
9
+ * ``SemanticCache``: same, for near-duplicate requests. The similarity is lexical (Jaccard over
10
+ lowercase words), a stand-in for an embedding model, not a measurement of one.
11
+ * ``LoopReplay``: for a similar request, replays the first run's tool calls verbatim, with the
12
+ old arguments and no LLM call (a one-shot replay in the spirit of LOOP, not a reimplementation).
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import re
18
+ from collections.abc import Mapping
19
+ from typing import Any, Protocol
20
+
21
+ from agent_jit.tools import Agent, LLMClient, ToolCaller
22
+ from agent_jit.tracer import RecordingLLM, RecordingTools
23
+
24
+
25
+ class Baseline(Protocol):
26
+ async def run(self, request: str, tools: ToolCaller) -> tuple[str, int, str]: ...
27
+
28
+
29
+ def _words(text: str) -> frozenset[str]:
30
+ return frozenset(re.findall(r"\w+", text.lower()))
31
+
32
+
33
+ def _jaccard(a: frozenset[str], b: frozenset[str]) -> float:
34
+ return len(a & b) / len(a | b) if a | b else 1.0
35
+
36
+
37
+ class PlainBaseline:
38
+ def __init__(self, agent: Agent, llm: LLMClient) -> None:
39
+ self._agent = agent
40
+ self._llm = RecordingLLM(llm)
41
+
42
+ async def run(self, request: str, tools: ToolCaller) -> tuple[str, int, str]:
43
+ before = self._llm.tokens
44
+ answer = await self._agent(request, self._llm, tools, ())
45
+ return answer, self._llm.tokens - before, "agent"
46
+
47
+
48
+ class ExactMatchCache:
49
+ def __init__(self, inner: Baseline) -> None:
50
+ self._inner = inner
51
+ self._answers: dict[str, str] = {}
52
+
53
+ async def run(self, request: str, tools: ToolCaller) -> tuple[str, int, str]:
54
+ if request in self._answers:
55
+ return self._answers[request], 0, "cache"
56
+ answer, tokens, path = await self._inner.run(request, tools)
57
+ self._answers[request] = answer
58
+ return answer, tokens, path
59
+
60
+
61
+ class SemanticCache:
62
+ def __init__(self, inner: Baseline, threshold: float = 0.8) -> None:
63
+ self._inner = inner
64
+ self._threshold = threshold
65
+ self._entries: list[tuple[frozenset[str], str]] = []
66
+
67
+ async def run(self, request: str, tools: ToolCaller) -> tuple[str, int, str]:
68
+ words = _words(request)
69
+ best = max(self._entries, key=lambda e: _jaccard(words, e[0]), default=None)
70
+ if best is not None and _jaccard(words, best[0]) >= self._threshold:
71
+ return best[1], 0, "cache"
72
+ answer, tokens, path = await self._inner.run(request, tools)
73
+ self._entries.append((words, answer))
74
+ return answer, tokens, path
75
+
76
+
77
+ class LoopReplay:
78
+ def __init__(self, inner: Baseline, threshold: float = 0.8) -> None:
79
+ self._inner = inner
80
+ self._threshold = threshold
81
+ self._runs: list[tuple[frozenset[str], list[tuple[str, Mapping[str, Any]]], str]] = []
82
+
83
+ async def run(self, request: str, tools: ToolCaller) -> tuple[str, int, str]:
84
+ words = _words(request)
85
+ best = max(self._runs, key=lambda r: _jaccard(words, r[0]), default=None)
86
+ if best is not None and _jaccard(words, best[0]) >= self._threshold:
87
+ for name, args in best[1]:
88
+ await tools.call(name, args)
89
+ return best[2], 0, "replay"
90
+ recording = RecordingTools(tools)
91
+ answer, tokens, path = await self._inner.run(request, recording)
92
+ calls = [(s.tool, s.args) for s in recording.steps if s.ok]
93
+ self._runs.append((words, calls, answer))
94
+ return answer, tokens, path
@@ -0,0 +1,124 @@
1
+ """Run a sequence of episodes through a runner and score each one with the environment's check."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from collections.abc import Awaitable, Callable, Iterable, Mapping
7
+ from dataclasses import dataclass
8
+ from typing import Any
9
+
10
+ from agent_jit.core import Wrapped
11
+ from agent_jit.eval.baselines import Baseline
12
+ from agent_jit.eval.metrics import EpisodeResult
13
+ from agent_jit.ir import Trace
14
+ from agent_jit.tools import ToolCaller, ToolSpec
15
+
16
+ Runner = Callable[["Episode"], Awaitable[tuple[str, int, str]]]
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class Episode:
21
+ request: str
22
+ tools: ToolCaller
23
+ # Scores the finished episode from the environment's own state and the final answer; the
24
+ # runner cannot influence it.
25
+ check: Callable[[str], bool]
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class Outcome:
30
+ results: list[EpisodeResult]
31
+ stopped: str | None # why the run ended early (a fatal exception), or None
32
+
33
+
34
+ class SwappableTools:
35
+ """A ToolCaller whose target changes per episode, so one wrapped agent sees fresh worlds."""
36
+
37
+ def __init__(self) -> None:
38
+ self._tools: ToolCaller | None = None
39
+ self._check: Callable[[str], bool] = lambda _: False
40
+
41
+ def swap(self, tools: ToolCaller, check: Callable[[str], bool]) -> None:
42
+ self._tools, self._check = tools, check
43
+
44
+ def _current(self) -> ToolCaller:
45
+ if self._tools is None:
46
+ raise RuntimeError("no episode is active")
47
+ return self._tools
48
+
49
+ def specs(self) -> tuple[ToolSpec, ...]:
50
+ return self._tools.specs() if self._tools is not None else ()
51
+
52
+ def spec(self, name: str) -> ToolSpec:
53
+ return self._current().spec(name)
54
+
55
+ async def call(self, name: str, args: Mapping[str, Any]) -> Any:
56
+ return await self._current().call(name, args)
57
+
58
+ def success(self, trace: Trace) -> bool:
59
+ """The ``success_check`` for a wrapped agent: the active episode's own check."""
60
+ return self._check(trace.answer)
61
+
62
+
63
+ def baseline_runner(baseline: Baseline) -> Runner:
64
+ async def run(episode: Episode) -> tuple[str, int, str]:
65
+ return await baseline.run(episode.request, episode.tools)
66
+
67
+ return run
68
+
69
+
70
+ class JitRunner:
71
+ def __init__(self, wrapped: Wrapped, swappable: SwappableTools) -> None:
72
+ self._wrapped = wrapped
73
+ self._swappable = swappable
74
+
75
+ async def run(self, episode: Episode) -> tuple[str, int, str]:
76
+ self._swappable.swap(episode.tools, episode.check)
77
+ result = await self._wrapped.run(episode.request)
78
+ tokens = result.router_tokens + result.inner_tokens + result.phrasing_tokens
79
+ return result.answer, tokens, "agent" if result.path == "plain" else result.path
80
+
81
+
82
+ async def run_episodes(
83
+ episodes: Iterable[Episode],
84
+ run: Runner,
85
+ compile_tokens: Callable[[], int] = lambda: 0,
86
+ fatal: tuple[type[Exception], ...] = (),
87
+ clock: Callable[[], float] = time.perf_counter,
88
+ llm_tokens: Callable[[], int] | None = None,
89
+ ) -> Outcome:
90
+ """Run each episode, score it with its own check, and attribute tokens and compile cost.
91
+
92
+ ``llm_tokens`` reads the model client's running total; when given, an episode's tokens are the
93
+ change in that total, so a crashed or interrupted episode still carries what it spent. Latency
94
+ stops before the check runs. A ``fatal`` exception ends the run but keeps the interrupted
95
+ episode (path ``"stopped"``) in the results.
96
+ """
97
+ results: list[EpisodeResult] = []
98
+ spent = compile_tokens()
99
+ for episode in episodes:
100
+ llm_before = llm_tokens() if llm_tokens is not None else 0
101
+ started = clock()
102
+ seconds: float | None = None
103
+ stopped: str | None = None
104
+ try:
105
+ answer, tokens, path = await run(episode)
106
+ seconds = clock() - started
107
+ success = bool(episode.check(answer))
108
+ except fatal as exc:
109
+ stopped = f"{type(exc).__name__}: {exc}"
110
+ answer, tokens, path, success = stopped, 0, "stopped", False
111
+ except Exception as exc: # recorded as a failed episode, never hidden
112
+ answer, tokens, path, success = f"{type(exc).__name__}: {exc}", 0, "error", False
113
+ if seconds is None:
114
+ seconds = clock() - started
115
+ if llm_tokens is not None:
116
+ tokens = llm_tokens() - llm_before
117
+ total = compile_tokens()
118
+ results.append(
119
+ EpisodeResult(episode.request, answer, tokens, total - spent, seconds, path, success)
120
+ )
121
+ spent = total
122
+ if stopped is not None:
123
+ return Outcome(results, stopped)
124
+ return Outcome(results, None)
@@ -0,0 +1,49 @@
1
+ """Episode results and the metrics the evaluation reports (net cost includes compile cost)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from collections.abc import Sequence
7
+ from dataclasses import dataclass
8
+
9
+ HIT_PATHS = frozenset({"cache", "compiled", "replay"})
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class EpisodeResult:
14
+ request: str
15
+ answer: str
16
+ tokens: int
17
+ compile_tokens: int
18
+ seconds: float
19
+ path: str
20
+ success: bool
21
+
22
+
23
+ def cumulative_net_tokens(results: Sequence[EpisodeResult]) -> list[int]:
24
+ total, curve = 0, []
25
+ for result in results:
26
+ total += result.tokens + result.compile_tokens
27
+ curve.append(total)
28
+ return curve
29
+
30
+
31
+ def _percentile(sorted_values: Sequence[float], q: float) -> float:
32
+ if not sorted_values:
33
+ return 0.0
34
+ rank = math.ceil(q * len(sorted_values)) # nearest-rank method
35
+ return sorted_values[max(rank, 1) - 1]
36
+
37
+
38
+ def summarize(results: Sequence[EpisodeResult]) -> dict[str, float]:
39
+ n = len(results)
40
+ seconds = sorted(r.seconds for r in results)
41
+ return {
42
+ "episodes": n,
43
+ "success_rate": sum(r.success for r in results) / n if n else 0.0,
44
+ "hit_rate": sum(r.path in HIT_PATHS for r in results) / n if n else 0.0,
45
+ "fallback_rate": sum(r.path == "fallback" for r in results) / n if n else 0.0,
46
+ "net_tokens": sum(r.tokens + r.compile_tokens for r in results),
47
+ "p50_seconds": _percentile(seconds, 0.50),
48
+ "p95_seconds": _percentile(seconds, 0.95),
49
+ }