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.
agent_jit/core.py ADDED
@@ -0,0 +1,390 @@
1
+ """The ``AgentJIT`` facade: wrap an agent, record its runs, compile repeated ones, route to them."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import uuid
6
+ from collections.abc import Callable, Iterable, Sequence
7
+ from dataclasses import dataclass, replace
8
+ from pathlib import Path
9
+ from typing import Literal
10
+
11
+ from agent_jit.compiler import CompiledSkill, compile_branched, compile_skill, skill_is_current
12
+ from agent_jit.ir import OutcomeUnknown, Refusal, Trace, TraceStep
13
+ from agent_jit.journal import Journal, JournaledTools
14
+ from agent_jit.roi import DEFAULT_ROUTER_TOKENS, worth_compiling
15
+ from agent_jit.router import Route, route
16
+ from agent_jit.runtime import execute, synthetic_history
17
+ from agent_jit.slicer import slice_trace
18
+ from agent_jit.stats import CircuitBreaker, RunStats, StatsBook
19
+ from agent_jit.store import TraceStore
20
+ from agent_jit.tools import Agent, LLMClient, ToolCaller, ToolSpec, schema_hash
21
+ from agent_jit.tracer import RecordingLLM, RecordingTools
22
+
23
+ SuccessCheck = Callable[[Trace], bool]
24
+ GroupKey = tuple[str, ...]
25
+ SkillKey = tuple[GroupKey, ...]
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class RunResult:
30
+ answer: str
31
+ path: Literal["plain", "compiled", "fallback"]
32
+ inner_llm_calls: int
33
+ router_tokens: int
34
+ inner_tokens: int
35
+ phrasing_tokens: int
36
+
37
+
38
+ class AgentJIT:
39
+ """Shared configuration: one SQLite file for traces and the write journal."""
40
+
41
+ def __init__(
42
+ self,
43
+ db_path: str | Path,
44
+ min_support: int = 2,
45
+ skills_dir: str | Path = ".agent_jit/skills",
46
+ router_token_estimate: int | None = None,
47
+ breaker: CircuitBreaker | None = None,
48
+ ) -> None:
49
+ self._store = TraceStore(db_path)
50
+ self._journal = Journal(db_path)
51
+ self._min_support = min_support
52
+ self._skills_dir = Path(skills_dir)
53
+ self._router_token_estimate = router_token_estimate
54
+ self._breaker = breaker
55
+
56
+ def wrap(
57
+ self,
58
+ agent: Agent,
59
+ llm: LLMClient,
60
+ tools: ToolCaller,
61
+ success_check: SuccessCheck | None = None,
62
+ ) -> Wrapped:
63
+ return Wrapped(
64
+ agent,
65
+ llm,
66
+ tools,
67
+ success_check,
68
+ self._store,
69
+ self._journal,
70
+ self._min_support,
71
+ self._skills_dir,
72
+ self._router_token_estimate,
73
+ self._breaker if self._breaker is not None else CircuitBreaker(),
74
+ )
75
+
76
+
77
+ class Wrapped:
78
+ """An agent whose repeated runs get compiled. Skills live as long as this object."""
79
+
80
+ def __init__(
81
+ self,
82
+ agent: Agent,
83
+ llm: LLMClient,
84
+ tools: ToolCaller,
85
+ success_check: SuccessCheck | None,
86
+ store: TraceStore,
87
+ journal: Journal,
88
+ min_support: int,
89
+ skills_dir: Path,
90
+ router_token_estimate: int | None = None,
91
+ breaker: CircuitBreaker | None = None,
92
+ ) -> None:
93
+ self._agent = agent
94
+ self._llm = llm
95
+ self._tools = tools
96
+ self._success_check = success_check
97
+ self._store = store
98
+ self._journal = journal
99
+ self._min_support = min_support
100
+ self._skills_dir = skills_dir
101
+ self._estimate = router_token_estimate
102
+ self._breaker = breaker if breaker is not None else CircuitBreaker()
103
+ self._skills: dict[SkillKey, CompiledSkill] = {}
104
+ self._groups: dict[GroupKey, list[Trace]] = {}
105
+ self._loaded = False
106
+ self._ns = uuid.uuid4().hex[:8] # keeps a shared breaker's keys apart per wrapped agent
107
+ self._attempted: dict[str, object] = {}
108
+ self._made = 0
109
+ self._router_spent = 0
110
+ self._router_calls = 0
111
+ self._stats = StatsBook()
112
+ self._refusals: list[str] = []
113
+ self._problems: list[str] = []
114
+ self._skipped: dict[SkillKey, str] = {}
115
+ self._disabled: dict[str, str] = {}
116
+
117
+ @property
118
+ def refusals(self) -> tuple[str, ...]:
119
+ """Why a repeated pattern was not compiled."""
120
+ return tuple(self._refusals)
121
+
122
+ @property
123
+ def problems(self) -> tuple[str, ...]:
124
+ """Bookkeeping that failed after a run had already finished (never raised: the run's
125
+ writes have happened, so the caller must still get its result)."""
126
+ return tuple(self._problems)
127
+
128
+ @property
129
+ def stats(self) -> RunStats:
130
+ return self._stats.snapshot()
131
+
132
+ @property
133
+ def disabled(self) -> tuple[str, ...]:
134
+ """Skills switched off, with the reason: a tool schema changed or the breaker tripped."""
135
+ return tuple(f"{name}: {why}" for name, why in self._disabled.items())
136
+
137
+ @property
138
+ def skipped(self) -> tuple[str, ...]:
139
+ """Groups the ROI gate declined to compile."""
140
+ return tuple(self._skipped.values())
141
+
142
+ async def run(self, request: str) -> RunResult:
143
+ offered = self._offered()
144
+ routed, router_tokens = await route(self._llm, request, offered)
145
+ if offered:
146
+ self._router_spent += router_tokens
147
+ self._router_calls += 1
148
+ run_id = uuid.uuid4().hex
149
+ tools = JournaledTools(self._tools, self._journal, run_id)
150
+ if routed is None:
151
+ result = await self._run_plain(request, run_id, tools, router_tokens)
152
+ else:
153
+ result = await self._run_compiled(routed, request, run_id, tools, router_tokens)
154
+ self._breaker.record(self._breaker_key(routed.skill), result.path == "fallback")
155
+ self._stats.add(result)
156
+ return result
157
+
158
+ def _breaker_key(self, skill: CompiledSkill) -> str:
159
+ return f"{self._ns}:{skill.name}"
160
+
161
+ def _specs_for(self, tools: Iterable[str]) -> list[ToolSpec]:
162
+ """Specs of the named tools, found by ``spec`` as the runtime does (not by ``specs``)."""
163
+ found = []
164
+ for name in dict.fromkeys(tools):
165
+ try:
166
+ found.append(self._tools.spec(name))
167
+ except KeyError:
168
+ continue
169
+ return found
170
+
171
+ def _next_name(self) -> str:
172
+ n = self._made + 1
173
+ while (self._skills_dir / f"skill_{n}.py").exists(): # another agent's file
174
+ n += 1
175
+ return f"skill_{n}"
176
+
177
+ def _offered(self) -> tuple[CompiledSkill, ...]:
178
+ """Skills the router may pick: current schemas and a breaker that has not tripped."""
179
+ offered = []
180
+ for skill in self._skills.values():
181
+ if not skill_is_current(skill, self._specs_for(skill.tools)):
182
+ self._disabled[skill.name] = "a tool schema changed since it was compiled"
183
+ elif self._breaker.tripped(self._breaker_key(skill)):
184
+ self._disabled[skill.name] = "it fell back too often (circuit breaker)"
185
+ else:
186
+ self._disabled.pop(skill.name, None)
187
+ offered.append(skill)
188
+ return tuple(offered)
189
+
190
+ async def _run_plain(
191
+ self, request: str, run_id: str, tools: JournaledTools, router_tokens: int
192
+ ) -> RunResult:
193
+ llm, recorder = RecordingLLM(self._llm), RecordingTools(tools)
194
+ try:
195
+ answer = await self._agent(request, llm, recorder, ())
196
+ except OutcomeUnknown:
197
+ self._save(Trace(run_id, request, recorder.steps, "", llm.tokens, None))
198
+ raise
199
+ schemas = {t: schema_hash(self._tools.spec(t)) for t in {s.tool for s in recorder.steps}}
200
+ trace = Trace(run_id, request, recorder.steps, answer, llm.tokens, None, schemas)
201
+ success = self._success_check(trace) if self._success_check is not None else None
202
+ trace = replace(trace, success=success)
203
+ if self._save(trace) and success:
204
+ self._compile_quietly(trace)
205
+ return RunResult(answer, "plain", llm.calls, router_tokens, llm.tokens, 0)
206
+
207
+ async def _run_compiled(
208
+ self, routed: Route, request: str, run_id: str, tools: JournaledTools, router_tokens: int
209
+ ) -> RunResult:
210
+ outcome = await execute(routed.skill, routed.params, tools)
211
+ phrasing = 0
212
+ if outcome.failure is None:
213
+ if outcome.answer is not None:
214
+ return RunResult(outcome.answer, "compiled", 0, router_tokens, 0, 0)
215
+ reply = await self._llm.complete(synthetic_history(request, outcome.steps), [])
216
+ if not reply.tool_calls:
217
+ return RunResult(reply.content, "compiled", 0, router_tokens, 0, reply.tokens)
218
+ phrasing = reply.tokens # the model needs more tools than the skill ran: hand over
219
+ tools.start_replay()
220
+ llm, recorder = RecordingLLM(self._llm), RecordingTools(tools)
221
+ history = synthetic_history(request, outcome.steps)
222
+ try:
223
+ answer = await self._agent(request, llm, recorder, history)
224
+ except OutcomeUnknown:
225
+ steps = _renumbered(outcome.steps, recorder.steps)
226
+ self._save(Trace(run_id, request, steps, "", llm.tokens, None))
227
+ raise
228
+ steps = _renumbered(outcome.steps, recorder.steps)
229
+ # Saved so nothing is lost, but success stays None: fallback runs are never compiled.
230
+ self._save(Trace(run_id, request, steps, answer, llm.tokens, None))
231
+ return RunResult(answer, "fallback", llm.calls, router_tokens, llm.tokens, phrasing)
232
+
233
+ def _save(self, trace: Trace) -> bool:
234
+ try:
235
+ self._store.save(trace)
236
+ except TypeError as exc:
237
+ self._problems.append(f"run {trace.run_id}: trace not saved: {exc}")
238
+ return False
239
+ return True
240
+
241
+ # ------------------------------------------------------------------ compilation
242
+
243
+ def _compile_quietly(self, trace: Trace) -> None:
244
+ """Compile, but never let that break a run whose tools already ran."""
245
+ try:
246
+ self._maybe_compile(trace)
247
+ except Exception as exc:
248
+ self._problems.append(f"run {trace.run_id}: compile step failed: {exc!r}")
249
+
250
+ def _router_estimate(self) -> int:
251
+ if self._estimate is not None:
252
+ return self._estimate
253
+ if self._router_calls:
254
+ return round(self._router_spent / self._router_calls)
255
+ return DEFAULT_ROUTER_TOKENS
256
+
257
+ def _add_to_groups(self, trace: Trace) -> GroupKey:
258
+ """Keep successful traces grouped in memory; the store is read once, not every run."""
259
+ key = _group_key(trace)
260
+ if not self._loaded:
261
+ self._loaded = True
262
+ for old in self._store.successful():
263
+ if old.run_id != trace.run_id:
264
+ self._groups.setdefault(_group_key(old), []).append(old)
265
+ self._groups.setdefault(key, []).append(trace)
266
+ return key
267
+
268
+ def _maybe_compile(self, trace: Trace) -> None:
269
+ key = self._add_to_groups(trace)
270
+ if not key:
271
+ return
272
+ seen = {tool for g in self._groups.values() for t in g for tool in t.schemas}
273
+ hashes = {s.name: schema_hash(s) for s in self._specs_for(seen)}
274
+ family: dict[GroupKey, list[Trace]] = {}
275
+ for k, group in self._groups.items():
276
+ fresh = [t for t in group if _is_fresh(t, hashes)]
277
+ if k and k[0] == key[0] and len(fresh) >= self._min_support:
278
+ family[k] = fresh
279
+ if not family:
280
+ return
281
+ covered = self._covered(key[0])
282
+ signature = (
283
+ tuple(sorted(hashes.items())),
284
+ tuple(sorted((k, len(v)) for k, v in family.items())),
285
+ )
286
+ if set(family) <= covered or self._attempted.get(key[0]) == signature:
287
+ return
288
+ self._attempted[key[0]] = signature
289
+ if len(family) >= 2 and self._compile_family(family):
290
+ return
291
+ for k, traces in family.items():
292
+ if k in covered:
293
+ continue
294
+ if any(other != k and other[: len(k)] == k for other in family):
295
+ self._refusals.append(f"{' -> '.join(k)}: ambiguous, a strict prefix of another")
296
+ continue
297
+ self._compile_group(k, traces)
298
+
299
+ def _covered(self, first_tool: str) -> set[GroupKey]:
300
+ """Groups an up-to-date skill already handles, tripped or not."""
301
+ covered: set[GroupKey] = set()
302
+ for skill_key, skill in self._skills.items():
303
+ # A tripped skill still counts: recompiling the same traces would only re-trip it.
304
+ if skill_key[0][0] == first_tool and skill_is_current(
305
+ skill, self._specs_for(skill.tools)
306
+ ):
307
+ covered.update(skill_key)
308
+ return covered
309
+
310
+ def _worth_it(self, keys: SkillKey, traces: Sequence[Trace]) -> bool:
311
+ estimate = self._router_estimate()
312
+ if worth_compiling(traces, estimate):
313
+ self._skipped.pop(keys, None)
314
+ return True
315
+ label = " | ".join(" -> ".join(k) for k in keys)
316
+ self._skipped[keys] = f"{label}: inner-loop tokens do not exceed the router estimate"
317
+ return False
318
+
319
+ def _compile_family(self, family: dict[GroupKey, list[Trace]]) -> bool:
320
+ keys = tuple(family)
321
+ groups = list(family.values())
322
+ if not self._worth_it(keys, [t for g in groups for t in g]):
323
+ return True # declined on cost: do not also compile the members one by one
324
+ name = self._next_name()
325
+ try:
326
+ skill = compile_branched(
327
+ groups, name, self._min_support, self._specs_for(_tools_of(groups))
328
+ )
329
+ except Refusal as exc:
330
+ self._refusals.append(f"{' | '.join(' -> '.join(k) for k in keys)}: {exc}")
331
+ return False
332
+ except Exception as exc:
333
+ self._refusals.append(
334
+ f"{' | '.join(' -> '.join(k) for k in keys)}: unexpected: {exc!r}"
335
+ )
336
+ return False
337
+ self._install(keys, skill)
338
+ return True
339
+
340
+ def _compile_group(self, key: GroupKey, traces: list[Trace]) -> None:
341
+ if not self._worth_it((key,), traces):
342
+ return
343
+ name = self._next_name()
344
+ try:
345
+ skill = compile_skill(
346
+ traces, name, self._min_support, self._specs_for(_tools_of([traces]))
347
+ )
348
+ except Refusal as exc:
349
+ self._refusals.append(f"{' -> '.join(key)}: {exc}")
350
+ return
351
+ except Exception as exc:
352
+ self._refusals.append(f"{' -> '.join(key)}: unexpected error while compiling: {exc!r}")
353
+ return
354
+ self._install((key,), skill)
355
+
356
+ def _install(self, keys: SkillKey, skill: CompiledSkill) -> None:
357
+ self._made += 1
358
+ first = keys[0][0]
359
+ for old_keys in [k for k in self._skills if k[0][0] == first and set(k) & set(keys)]:
360
+ old = self._skills.pop(old_keys)
361
+ self._disabled.pop(old.name, None)
362
+ (self._skills_dir / f"{old.name}.py").unlink(missing_ok=True)
363
+ self._skills[keys] = skill
364
+ try:
365
+ self._skills_dir.mkdir(parents=True, exist_ok=True)
366
+ (self._skills_dir / f"{skill.name}.py").write_text(skill.source, encoding="utf-8")
367
+ except OSError as exc:
368
+ self._problems.append(f"skill {skill.name} kept in memory but not written: {exc}")
369
+
370
+
371
+ def _tools_of(groups: Sequence[Sequence[Trace]]) -> list[str]:
372
+ return [tool for g in groups for t in g for tool in t.schemas]
373
+
374
+
375
+ def _group_key(trace: Trace) -> GroupKey:
376
+ return tuple(step.tool for step in slice_trace(trace).steps)
377
+
378
+
379
+ def _is_fresh(trace: Trace, hashes: dict[str, str]) -> bool:
380
+ """True when every tool the run used still has the schema it had then."""
381
+ return all(
382
+ step.tool in trace.schemas and trace.schemas[step.tool] == hashes.get(step.tool)
383
+ for step in trace.steps
384
+ )
385
+
386
+
387
+ def _renumbered(
388
+ first: tuple[TraceStep, ...], later: tuple[TraceStep, ...]
389
+ ) -> tuple[TraceStep, ...]:
390
+ return first + tuple(replace(s, index=len(first) + i) for i, s in enumerate(later))
agent_jit/demo.py ADDED
@@ -0,0 +1,238 @@
1
+ """A toy refund agent run five times, with a mock LLM and no API key.
2
+
3
+ python -m agent_jit.demo
4
+
5
+ Runs 1 and 2 are recorded, then compiled. Run 3 uses zero inner LLM calls. In run 4 a guard fails
6
+ *after* the refund ran and the agent asks to refund again; the journal answers without running
7
+ it. In run 5 a guard fails before any write. Nothing here measures anything: the "LLM" is a
8
+ deterministic script, so token counts are fixed numbers, not results.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import json
15
+ import re
16
+ import tempfile
17
+ from collections import Counter
18
+ from collections.abc import Mapping, Sequence
19
+ from dataclasses import dataclass
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ from agent_jit.core import AgentJIT, RunResult
24
+ from agent_jit.ir import Message, Reply, ToolCallReq, ToolRejected, Trace
25
+ from agent_jit.stats import RunStats
26
+ from agent_jit.tools import LLMClient, ToolCaller, ToolRegistry, ToolSpec
27
+
28
+ ORDERS: dict[str, tuple[str, int, str]] = {
29
+ "8821": ("delivered", 125, "CUS-101"),
30
+ "7730": ("delivered", 340, "CUS-102"),
31
+ "9001": ("delivered", 275, "CUS-103"),
32
+ "9002": ("delivered", 410, "CUS-104"),
33
+ "9003": ("cancelled", 90, "CUS-105"),
34
+ }
35
+ CUSTOMERS: dict[str, tuple[str, str]] = {
36
+ "CUS-101": ("Ada", "ada@example.com"),
37
+ "CUS-102": ("Grace", "grace@example.com"),
38
+ "CUS-103": ("Alan", "alan@example.com"),
39
+ "CUS-104": ("Edsger", "edsger@example.com"),
40
+ "CUS-105": ("Barbara", "barbara@example.com"),
41
+ }
42
+ ORDER_OF_EMAIL = {
43
+ email: next(o for o, v in ORDERS.items() if CUSTOMERS[v[2]][1] == email)
44
+ for _, email in CUSTOMERS.values()
45
+ }
46
+ RUNS = ("8821", "7730", "9001", "9002", "9003")
47
+ ROUTER_TOKENS = 20
48
+ AGENT_TOKENS = 50
49
+
50
+
51
+ class Shop:
52
+ """Five tools over a tiny in-memory shop. Counters record what really executed."""
53
+
54
+ def __init__(self) -> None:
55
+ self.refunds: Counter[str] = Counter()
56
+ self.emails: Counter[str] = Counter()
57
+ self.registry = ToolRegistry()
58
+ schema: dict[str, Any] = {"type": "object"}
59
+
60
+ async def get_order(order_id: str) -> dict[str, Any]:
61
+ if order_id not in ORDERS:
62
+ raise ToolRejected(f"unknown order {order_id}")
63
+ status, amount, customer = ORDERS[order_id]
64
+ return {"status": status, "amount": amount, "customer_id": customer}
65
+
66
+ async def get_customer(customer_id: str) -> dict[str, str]:
67
+ name, email = CUSTOMERS[customer_id]
68
+ return {"name": name, "email": email}
69
+
70
+ async def search_orders(customer_id: str) -> dict[str, list[str]]:
71
+ # other open orders of the customer; nobody in the demo has any
72
+ return {"open_orders": []}
73
+
74
+ async def refund_order(order_id: str, amount: int) -> dict[str, str]:
75
+ self.refunds[order_id] += 1
76
+ return {"status": "pending_review" if order_id == "9002" else "refunded"}
77
+
78
+ async def send_email(to: str, subject: str) -> dict[str, bool]:
79
+ self.emails[ORDER_OF_EMAIL[to]] += 1
80
+ return {"queued": True}
81
+
82
+ self.registry.register("get_order", get_order, schema, effect="read")
83
+ self.registry.register("get_customer", get_customer, schema, effect="read")
84
+ self.registry.register("search_orders", search_orders, schema, effect="read")
85
+ self.registry.register("refund_order", refund_order, schema, effect="write")
86
+ self.registry.register("send_email", send_email, schema, effect="write")
87
+
88
+ def writes(self) -> int:
89
+ return sum(self.refunds.values()) + sum(self.emails.values())
90
+
91
+
92
+ class MockLLM:
93
+ """A deterministic policy over the message history: routes, plans, answers. No network."""
94
+
95
+ def __init__(self) -> None:
96
+ self.repeat_refund_requests = 0
97
+
98
+ async def complete(self, messages: Sequence[Message], tools: Sequence[ToolSpec]) -> Reply:
99
+ if messages[0].content.startswith("You route"):
100
+ return self._route(messages[0].content)
101
+ return self._agent(messages)
102
+
103
+ @staticmethod
104
+ def _route(prompt: str) -> Reply:
105
+ request = prompt.rsplit("Request: ", 1)[1]
106
+ match = re.search(r"Refund order (\d{4})", request)
107
+ body: dict[str, Any] = {"skill": None, "params": {}}
108
+ if match and "skill_1" in prompt:
109
+ body = {"skill": "skill_1", "params": {"order_id": match.group(1)}}
110
+ return Reply(json.dumps(body), tokens=ROUTER_TOKENS)
111
+
112
+ def _agent(self, messages: Sequence[Message]) -> Reply:
113
+ found = re.search(r"(\d{4})", messages[0].content)
114
+ assert found is not None, "the demo requests always name a four digit order"
115
+ order_id = found.group(1)
116
+ done = _calls_so_far(messages)
117
+ names = [name for name, _ in done]
118
+ results = dict(done) # the latest result per tool
119
+ if "get_order" not in names:
120
+ return self._call(messages, "get_order", {"order_id": order_id})
121
+ order = results["get_order"]
122
+ if order["status"] != "delivered":
123
+ return self._final(f"Order {order_id} cannot be refunded ({order['status']}).")
124
+ if "get_customer" not in names:
125
+ return self._call(messages, "get_customer", {"customer_id": order["customer_id"]})
126
+ if "refund_order" not in names:
127
+ args = {"order_id": order_id, "amount": order["amount"]}
128
+ return self._call(messages, "refund_order", args)
129
+ if results["refund_order"]["status"] == "pending_review":
130
+ if names.count("refund_order") == 1:
131
+ self.repeat_refund_requests += 1
132
+ args = {"order_id": order_id, "amount": order["amount"]}
133
+ return self._call(messages, "refund_order", args)
134
+ return self._final(f"Refund for order {order_id} is pending review.")
135
+ email = results["get_customer"]["email"]
136
+ if "send_email" not in names:
137
+ return self._call(messages, "send_email", {"to": email, "subject": "Your refund"})
138
+ if "search_orders" not in names:
139
+ return self._call(messages, "search_orders", {"customer_id": order["customer_id"]})
140
+ return self._final(f"Refunded {order['amount']} for order {order_id} and emailed {email}.")
141
+
142
+ @staticmethod
143
+ def _call(messages: Sequence[Message], name: str, args: dict[str, Any]) -> Reply:
144
+ call = ToolCallReq(f"call_{len(messages)}", name, args)
145
+ return Reply("", tool_calls=(call,), tokens=AGENT_TOKENS)
146
+
147
+ @staticmethod
148
+ def _final(text: str) -> Reply:
149
+ return Reply(text, tokens=AGENT_TOKENS)
150
+
151
+
152
+ def _calls_so_far(messages: Sequence[Message]) -> list[tuple[str, dict[str, Any]]]:
153
+ """(tool name, parsed result) for every tool call already answered, in order."""
154
+ names = {c.id: c.name for m in messages for c in m.tool_calls}
155
+ return [
156
+ (names[m.tool_call_id or ""], json.loads(m.content)) for m in messages if m.role == "tool"
157
+ ]
158
+
159
+
160
+ async def shop_agent(
161
+ request: str, llm: LLMClient, tools: ToolCaller, history: Sequence[Message]
162
+ ) -> str:
163
+ """A plain tool-calling loop. With a non-empty ``history`` it continues that conversation."""
164
+ messages = list(history) or [Message("user", request)]
165
+ for _ in range(12):
166
+ reply = await llm.complete(messages, tools.specs())
167
+ if not reply.tool_calls:
168
+ return reply.content
169
+ messages.append(Message("assistant", reply.content, tool_calls=reply.tool_calls))
170
+ for call in reply.tool_calls:
171
+ try:
172
+ result: Any = await tools.call(call.name, call.args)
173
+ except ToolRejected as exc:
174
+ result = {"error": str(exc)}
175
+ messages.append(Message("tool", json.dumps(result), tool_call_id=call.id))
176
+ raise RuntimeError("the agent did not finish within 12 steps")
177
+
178
+
179
+ @dataclass(frozen=True)
180
+ class DemoReport:
181
+ results: tuple[RunResult, ...]
182
+ refunds: Mapping[str, int]
183
+ emails: Mapping[str, int]
184
+ writes_per_run: tuple[int, ...] = ()
185
+ repeat_refund_requests: int = 0
186
+ stats: RunStats | None = None
187
+
188
+
189
+ def _refunded(trace: Trace) -> bool:
190
+ return trace.answer.startswith("Refunded")
191
+
192
+
193
+ async def run_demo(workdir: Path) -> DemoReport:
194
+ shop, llm = Shop(), MockLLM()
195
+ jit = AgentJIT(workdir / "demo.sqlite", min_support=2, skills_dir=workdir / "skills")
196
+ wrapped = jit.wrap(shop_agent, llm, shop.registry, success_check=_refunded)
197
+ results: list[RunResult] = []
198
+ writes: list[int] = []
199
+ for order_id in RUNS:
200
+ before = shop.writes()
201
+ results.append(await wrapped.run(f"Refund order {order_id}"))
202
+ writes.append(shop.writes() - before)
203
+ return DemoReport(
204
+ tuple(results),
205
+ dict(shop.refunds),
206
+ dict(shop.emails),
207
+ tuple(writes),
208
+ llm.repeat_refund_requests,
209
+ wrapped.stats,
210
+ )
211
+
212
+
213
+ def main() -> None:
214
+ with tempfile.TemporaryDirectory() as tmp:
215
+ workdir = Path(tmp)
216
+ report = asyncio.run(run_demo(workdir))
217
+ source = (workdir / "skills" / "skill_1.py").read_text()
218
+ print("agent-jit toy demo: mock LLM, no API key, nothing measured\n")
219
+ for n, (order_id, result, writes) in enumerate(
220
+ zip(RUNS, report.results, report.writes_per_run, strict=True), start=1
221
+ ):
222
+ print(
223
+ f"run {n} {result.path:<9} inner_llm_calls={result.inner_llm_calls} "
224
+ f"router_tokens={result.router_tokens} writes_performed={writes} "
225
+ f"Refund order {order_id} -> {result.answer}"
226
+ )
227
+ print(f"\nrefunds executed per order: {dict(report.refunds)}")
228
+ print(f"emails sent per order: {dict(report.emails)}")
229
+ print(
230
+ f"the agent asked to refund 9002 again {report.repeat_refund_requests} time(s); "
231
+ "the journal answered it without executing"
232
+ )
233
+ print("\ngenerated skill_1.py:\n")
234
+ print(source)
235
+
236
+
237
+ if __name__ == "__main__":
238
+ main()
@@ -0,0 +1 @@
1
+ """Evaluation helpers: episode metrics, cache baselines and the episode harness."""