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/__init__.py +5 -0
- agent_jit/adapters/__init__.py +1 -0
- agent_jit/adapters/anthropic.py +160 -0
- agent_jit/adapters/appworld.py +93 -0
- agent_jit/adapters/loop_agent.py +35 -0
- agent_jit/adapters/ollama.py +113 -0
- agent_jit/branches.py +74 -0
- agent_jit/compiler.py +659 -0
- agent_jit/core.py +390 -0
- agent_jit/demo.py +238 -0
- agent_jit/eval/__init__.py +1 -0
- agent_jit/eval/baselines.py +94 -0
- agent_jit/eval/harness.py +124 -0
- agent_jit/eval/metrics.py +49 -0
- agent_jit/eval/supportdesk.py +446 -0
- agent_jit/guards.py +185 -0
- agent_jit/ir.py +64 -0
- agent_jit/journal.py +219 -0
- agent_jit/provenance.py +460 -0
- agent_jit/py.typed +0 -0
- agent_jit/roi.py +20 -0
- agent_jit/router.py +136 -0
- agent_jit/runtime.py +137 -0
- agent_jit/slicer.py +66 -0
- agent_jit/stats.py +75 -0
- agent_jit/store.py +114 -0
- agent_jit/tools.py +81 -0
- agent_jit/tracer.py +57 -0
- agent_jit_runtime-0.1.0.dist-info/METADATA +223 -0
- agent_jit_runtime-0.1.0.dist-info/RECORD +32 -0
- agent_jit_runtime-0.1.0.dist-info/WHEEL +4 -0
- agent_jit_runtime-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
"""A repetitive support-desk workload on a sample database, for measuring the JIT.
|
|
2
|
+
|
|
3
|
+
The tools are structured (the SQL lives inside them), so an agent only chooses and chains calls.
|
|
4
|
+
Six request types recur with different parameters; five are lookups and writes whose arguments
|
|
5
|
+
flow from earlier outputs, and one ("how many orders has NAME placed") ends in a count the model
|
|
6
|
+
computes. Every episode gets a fresh in-memory database, and success is a check of that database or
|
|
7
|
+
of the answer text, never of what the agent claims. ``ScriptedDeskLLM`` is a mock policy for tests
|
|
8
|
+
and for an upper-bound run; it is not a model.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import ast
|
|
14
|
+
import json
|
|
15
|
+
import random
|
|
16
|
+
import re
|
|
17
|
+
import sqlite3
|
|
18
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from agent_jit.ir import Message, Reply, ToolCallReq, ToolRejected
|
|
23
|
+
from agent_jit.tools import ToolRegistry, ToolSpec
|
|
24
|
+
|
|
25
|
+
NAMES = ("Ada", "Ben", "Cleo", "Dara", "Eli", "Fay", "Gus", "Hana", "Ivan", "Jade", "Kofi", "Lena")
|
|
26
|
+
STATUSES = ("delivered", "shipped", "processing")
|
|
27
|
+
ORDERS_PER_STATUS = 12
|
|
28
|
+
ROUTE_TOKENS = 40
|
|
29
|
+
AGENT_TOKENS = 60
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _schema(description: str, **props: str) -> dict[str, Any]:
|
|
33
|
+
return {
|
|
34
|
+
"type": "object",
|
|
35
|
+
"properties": {name: {"type": kind} for name, kind in props.items()},
|
|
36
|
+
"required": list(props),
|
|
37
|
+
"description": description,
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class Desk:
|
|
42
|
+
"""One episode's database and tools; also a ``ToolCaller``."""
|
|
43
|
+
|
|
44
|
+
def __init__(self, seed: int = 7, permissive: bool = False) -> None:
|
|
45
|
+
self.permissive = permissive # True: write tools trust the caller and skip state checks
|
|
46
|
+
self.db = sqlite3.connect(":memory:")
|
|
47
|
+
self.db.executescript(
|
|
48
|
+
"create table customers (id text primary key, name text, email text, tier text);"
|
|
49
|
+
"create table orders (id text primary key, customer_id text, status text,"
|
|
50
|
+
" amount integer, refunded integer default 0);"
|
|
51
|
+
"create table outbox (customer_id text, order_id text);"
|
|
52
|
+
)
|
|
53
|
+
rng = random.Random(seed)
|
|
54
|
+
for i, name in enumerate(NAMES):
|
|
55
|
+
tier = rng.choice(["standard", "gold"])
|
|
56
|
+
self.db.execute(
|
|
57
|
+
"insert into customers values (?, ?, ?, ?)",
|
|
58
|
+
(f"C{100 + i}", name, f"{name.lower()}@example.com", tier),
|
|
59
|
+
)
|
|
60
|
+
ids = rng.sample(range(1000, 10000), ORDERS_PER_STATUS * len(STATUSES))
|
|
61
|
+
statuses = [s for s in STATUSES for _ in range(ORDERS_PER_STATUS)]
|
|
62
|
+
rng.shuffle(statuses)
|
|
63
|
+
for order_id, status in zip(ids, statuses, strict=True):
|
|
64
|
+
owner = f"C{100 + rng.randrange(len(NAMES))}"
|
|
65
|
+
self.db.execute(
|
|
66
|
+
"insert into orders values (?, ?, ?, ?, 0)",
|
|
67
|
+
(str(order_id), owner, status, rng.randint(20, 500)),
|
|
68
|
+
)
|
|
69
|
+
self.registry = ToolRegistry()
|
|
70
|
+
self._register()
|
|
71
|
+
|
|
72
|
+
# -- ToolCaller ---------------------------------------------------------------------------
|
|
73
|
+
def specs(self) -> tuple[ToolSpec, ...]:
|
|
74
|
+
return self.registry.specs()
|
|
75
|
+
|
|
76
|
+
def spec(self, name: str) -> ToolSpec:
|
|
77
|
+
return self.registry.spec(name)
|
|
78
|
+
|
|
79
|
+
async def call(self, name: str, args: Mapping[str, Any]) -> Any:
|
|
80
|
+
return await self.registry.call(name, args)
|
|
81
|
+
|
|
82
|
+
# -- state the checks read ----------------------------------------------------------------
|
|
83
|
+
def status(self, order_id: str) -> str:
|
|
84
|
+
row = self.db.execute("select status from orders where id=?", (order_id,)).fetchone()
|
|
85
|
+
return str(row[0])
|
|
86
|
+
|
|
87
|
+
def refunded(self, order_id: str) -> int:
|
|
88
|
+
row = self.db.execute("select refunded from orders where id=?", (order_id,)).fetchone()
|
|
89
|
+
return int(row[0])
|
|
90
|
+
|
|
91
|
+
def notified(self, customer_id: str, order_id: str) -> bool:
|
|
92
|
+
row = self.db.execute(
|
|
93
|
+
"select 1 from outbox where customer_id=? and order_id=?", (customer_id, order_id)
|
|
94
|
+
).fetchone()
|
|
95
|
+
return row is not None
|
|
96
|
+
|
|
97
|
+
# -- tools --------------------------------------------------------------------------------
|
|
98
|
+
def _order(self, order_id: str) -> tuple[Any, ...]:
|
|
99
|
+
row = self.db.execute(
|
|
100
|
+
"select id, customer_id, status, amount, refunded from orders where id=?", (order_id,)
|
|
101
|
+
).fetchone()
|
|
102
|
+
if row is None:
|
|
103
|
+
raise ToolRejected(f"no order {order_id}")
|
|
104
|
+
return tuple(row)
|
|
105
|
+
|
|
106
|
+
def _register(self) -> None:
|
|
107
|
+
async def find_customer(name: str) -> dict[str, Any]:
|
|
108
|
+
row = self.db.execute(
|
|
109
|
+
"select id, name, email, tier from customers where lower(name)=lower(?)", (name,)
|
|
110
|
+
).fetchone()
|
|
111
|
+
if row is None:
|
|
112
|
+
raise ToolRejected(f"no customer named {name}")
|
|
113
|
+
return {"customer_id": row[0], "name": row[1], "email": row[2], "tier": row[3]}
|
|
114
|
+
|
|
115
|
+
async def get_order(order_id: str) -> dict[str, Any]:
|
|
116
|
+
row = self._order(order_id)
|
|
117
|
+
return {
|
|
118
|
+
"order_id": row[0],
|
|
119
|
+
"customer_id": row[1],
|
|
120
|
+
"status": row[2],
|
|
121
|
+
"amount": row[3],
|
|
122
|
+
"refunded": row[4],
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async def list_orders(customer_id: str) -> dict[str, Any]:
|
|
126
|
+
rows = self.db.execute(
|
|
127
|
+
"select id, status, amount from orders where customer_id=? order by id",
|
|
128
|
+
(customer_id,),
|
|
129
|
+
).fetchall()
|
|
130
|
+
return {"orders": [{"order_id": r[0], "status": r[1], "amount": r[2]} for r in rows]}
|
|
131
|
+
|
|
132
|
+
async def refund_order(order_id: str, amount: int) -> dict[str, Any]:
|
|
133
|
+
row = self._order(order_id)
|
|
134
|
+
if not self.permissive and (row[2] != "delivered" or row[4] != 0):
|
|
135
|
+
raise ToolRejected(f"order {order_id} cannot be refunded ({row[2]})")
|
|
136
|
+
if not 0 < amount <= row[3]:
|
|
137
|
+
raise ToolRejected(f"refund amount must be between 1 and {row[3]}")
|
|
138
|
+
self.db.execute("update orders set refunded=? where id=?", (amount, order_id))
|
|
139
|
+
return {"status": "refunded", "amount": amount}
|
|
140
|
+
|
|
141
|
+
async def cancel_order(order_id: str) -> dict[str, Any]:
|
|
142
|
+
row = self._order(order_id)
|
|
143
|
+
if not self.permissive and row[2] != "processing":
|
|
144
|
+
raise ToolRejected(f"order {order_id} cannot be cancelled ({row[2]})")
|
|
145
|
+
self.db.execute("update orders set status='cancelled' where id=?", (order_id,))
|
|
146
|
+
return {"status": "cancelled"}
|
|
147
|
+
|
|
148
|
+
async def notify_shipped(customer_id: str, order_id: str) -> dict[str, Any]:
|
|
149
|
+
row = self._order(order_id)
|
|
150
|
+
if row[1] != customer_id or row[2] != "shipped":
|
|
151
|
+
raise ToolRejected(f"order {order_id} is not a shipped order of {customer_id}")
|
|
152
|
+
self.db.execute("insert into outbox values (?, ?)", (customer_id, order_id))
|
|
153
|
+
return {"sent": True}
|
|
154
|
+
|
|
155
|
+
reg = self.registry
|
|
156
|
+
reg.register(
|
|
157
|
+
"find_customer",
|
|
158
|
+
find_customer,
|
|
159
|
+
_schema("Look up a customer by first name.", name="string"),
|
|
160
|
+
"read",
|
|
161
|
+
)
|
|
162
|
+
reg.register(
|
|
163
|
+
"get_order",
|
|
164
|
+
get_order,
|
|
165
|
+
_schema("Show an order: status, amount, refunded.", order_id="string"),
|
|
166
|
+
"read",
|
|
167
|
+
)
|
|
168
|
+
reg.register(
|
|
169
|
+
"list_orders",
|
|
170
|
+
list_orders,
|
|
171
|
+
_schema("List a customer's orders.", customer_id="string"),
|
|
172
|
+
"read",
|
|
173
|
+
)
|
|
174
|
+
reg.register(
|
|
175
|
+
"refund_order",
|
|
176
|
+
refund_order,
|
|
177
|
+
_schema(
|
|
178
|
+
"Refund a delivered order, up to its amount.", order_id="string", amount="integer"
|
|
179
|
+
),
|
|
180
|
+
"write",
|
|
181
|
+
)
|
|
182
|
+
reg.register(
|
|
183
|
+
"cancel_order",
|
|
184
|
+
cancel_order,
|
|
185
|
+
_schema("Cancel an order that is still processing.", order_id="string"),
|
|
186
|
+
"write",
|
|
187
|
+
)
|
|
188
|
+
reg.register(
|
|
189
|
+
"notify_shipped",
|
|
190
|
+
notify_shipped,
|
|
191
|
+
_schema(
|
|
192
|
+
"Email the customer that their shipped order is on its way.",
|
|
193
|
+
customer_id="string",
|
|
194
|
+
order_id="string",
|
|
195
|
+
),
|
|
196
|
+
"write",
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
# ----------------------------------------------------------------------------- the requests
|
|
201
|
+
|
|
202
|
+
Check = Callable[[Desk, str], bool]
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
@dataclass(frozen=True)
|
|
206
|
+
class DeskRequest:
|
|
207
|
+
kind: str
|
|
208
|
+
text: str
|
|
209
|
+
check: Check
|
|
210
|
+
permissive: bool = False
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
_PATTERNS = {
|
|
214
|
+
"refund": re.compile(r"^Refund order (\d{4})\.$"),
|
|
215
|
+
"status": re.compile(r"^What is the status of order (\d{4})\?$"),
|
|
216
|
+
"cancel": re.compile(r"^Cancel order (\d{4})\.$"),
|
|
217
|
+
"notify": re.compile(r"^Tell (\w+) that order (\d{4}) has shipped\.$"),
|
|
218
|
+
"email": re.compile(r"^What is the email address of (\w+)\?$"),
|
|
219
|
+
"count": re.compile(r"^How many orders has (\w+) placed\?$"),
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def classify(text: str) -> tuple[str, tuple[str, ...]] | None:
|
|
224
|
+
for kind, pattern in _PATTERNS.items():
|
|
225
|
+
match = pattern.match(text)
|
|
226
|
+
if match:
|
|
227
|
+
return kind, match.groups()
|
|
228
|
+
return None
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _word(text: str, word: str) -> bool:
|
|
232
|
+
return re.search(rf"\b{re.escape(word)}\b", text, re.IGNORECASE) is not None
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _refunded(order_id: str, amount: int) -> Check:
|
|
236
|
+
return lambda desk, answer: desk.refunded(order_id) == amount
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _cancelled(order_id: str) -> Check:
|
|
240
|
+
return lambda desk, answer: desk.status(order_id) == "cancelled"
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _notified(customer_id: str, order_id: str) -> Check:
|
|
244
|
+
return lambda desk, answer: desk.notified(customer_id, order_id)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _mentions(word: str) -> Check:
|
|
248
|
+
return lambda desk, answer: _word(answer, word)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def make_requests(per_type: int, seed: int) -> list[DeskRequest]:
|
|
252
|
+
if not 1 <= per_type <= ORDERS_PER_STATUS:
|
|
253
|
+
raise ValueError(f"per_type must be between 1 and {ORDERS_PER_STATUS}")
|
|
254
|
+
rng = random.Random(seed)
|
|
255
|
+
ref = Desk()
|
|
256
|
+
|
|
257
|
+
def orders(status: str) -> list[tuple[str, str, str, int]]:
|
|
258
|
+
rows = ref.db.execute(
|
|
259
|
+
"select o.id, c.name, c.id, o.amount from orders o"
|
|
260
|
+
" join customers c on c.id=o.customer_id where o.status=? order by o.id",
|
|
261
|
+
(status,),
|
|
262
|
+
).fetchall()
|
|
263
|
+
return [(str(r[0]), str(r[1]), str(r[2]), int(r[3])) for r in rows]
|
|
264
|
+
|
|
265
|
+
def count_of(name: str) -> int:
|
|
266
|
+
row = ref.db.execute(
|
|
267
|
+
"select count(*) from orders o join customers c on c.id=o.customer_id where c.name=?",
|
|
268
|
+
(name,),
|
|
269
|
+
).fetchone()
|
|
270
|
+
return int(row[0])
|
|
271
|
+
|
|
272
|
+
requests: list[DeskRequest] = []
|
|
273
|
+
for oid, _, _, amount in rng.sample(orders("delivered"), per_type):
|
|
274
|
+
requests.append(DeskRequest("refund", f"Refund order {oid}.", _refunded(oid, amount)))
|
|
275
|
+
every = [o for s in STATUSES for o in orders(s)]
|
|
276
|
+
for oid, _, _, _ in rng.sample(every, per_type):
|
|
277
|
+
text = f"What is the status of order {oid}?"
|
|
278
|
+
requests.append(DeskRequest("status", text, _mentions(ref.status(oid))))
|
|
279
|
+
for oid, _, _, _ in rng.sample(orders("processing"), per_type):
|
|
280
|
+
requests.append(DeskRequest("cancel", f"Cancel order {oid}.", _cancelled(oid)))
|
|
281
|
+
for oid, name, cid, _ in rng.sample(orders("shipped"), per_type):
|
|
282
|
+
text = f"Tell {name} that order {oid} has shipped."
|
|
283
|
+
requests.append(DeskRequest("notify", text, _notified(cid, oid)))
|
|
284
|
+
for name in rng.sample(NAMES, per_type):
|
|
285
|
+
text = f"What is the email address of {name}?"
|
|
286
|
+
requests.append(DeskRequest("email", text, _mentions(f"{name.lower()}@example.com")))
|
|
287
|
+
for name in rng.sample(NAMES, per_type):
|
|
288
|
+
text = f"How many orders has {name} placed?"
|
|
289
|
+
requests.append(DeskRequest("count", text, _mentions(str(count_of(name)))))
|
|
290
|
+
rng.shuffle(requests)
|
|
291
|
+
return requests
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def make_drift_requests(per_type: int, seed: int) -> list[DeskRequest]:
|
|
295
|
+
"""Refunds and cancels where the *data* later stops matching what was learned.
|
|
296
|
+
|
|
297
|
+
A warm-up of valid requests comes first (delivered orders to refund, processing ones to
|
|
298
|
+
cancel); then valid and invalid ones are mixed. An invalid request names an order whose status
|
|
299
|
+
forbids the action. The desk's tools do not check (``permissive``), so only the agent's own
|
|
300
|
+
check, or a guard compiled from the warm-up, stands between the request and a wrong write.
|
|
301
|
+
"""
|
|
302
|
+
if not 1 <= per_type <= ORDERS_PER_STATUS // 2:
|
|
303
|
+
raise ValueError(f"per_type must be between 1 and {ORDERS_PER_STATUS // 2}")
|
|
304
|
+
rng = random.Random(seed)
|
|
305
|
+
ref = Desk()
|
|
306
|
+
|
|
307
|
+
def ids(*statuses: str) -> list[str]:
|
|
308
|
+
marks = ",".join("?" * len(statuses))
|
|
309
|
+
rows = ref.db.execute(
|
|
310
|
+
f"select id from orders where status in ({marks}) order by id", statuses
|
|
311
|
+
).fetchall()
|
|
312
|
+
return [str(r[0]) for r in rows]
|
|
313
|
+
|
|
314
|
+
def amount(oid: str) -> int:
|
|
315
|
+
return int(ref.db.execute("select amount from orders where id=?", (oid,)).fetchone()[0])
|
|
316
|
+
|
|
317
|
+
def refund_ok(oid: str) -> DeskRequest:
|
|
318
|
+
return DeskRequest("refund", f"Refund order {oid}.", _refunded(oid, amount(oid)), True)
|
|
319
|
+
|
|
320
|
+
def cancel_ok(oid: str) -> DeskRequest:
|
|
321
|
+
return DeskRequest("cancel", f"Cancel order {oid}.", _cancelled(oid), True)
|
|
322
|
+
|
|
323
|
+
def refund_bad(oid: str) -> DeskRequest:
|
|
324
|
+
def check(desk: Desk, answer: str) -> bool:
|
|
325
|
+
return desk.refunded(oid) == 0 and _word(answer, "cannot")
|
|
326
|
+
|
|
327
|
+
return DeskRequest("refund-invalid", f"Refund order {oid}.", check, True)
|
|
328
|
+
|
|
329
|
+
def cancel_bad(oid: str) -> DeskRequest:
|
|
330
|
+
def check(desk: Desk, answer: str) -> bool:
|
|
331
|
+
return desk.status(oid) == ref.status(oid) and _word(answer, "cannot")
|
|
332
|
+
|
|
333
|
+
return DeskRequest("cancel-invalid", f"Cancel order {oid}.", check, True)
|
|
334
|
+
|
|
335
|
+
delivered = rng.sample(ids("delivered"), 2 * per_type)
|
|
336
|
+
processing = rng.sample(ids("processing"), 2 * per_type)
|
|
337
|
+
warm = [refund_ok(o) for o in delivered[:per_type]] + [
|
|
338
|
+
cancel_ok(o) for o in processing[:per_type]
|
|
339
|
+
]
|
|
340
|
+
test = (
|
|
341
|
+
[refund_ok(o) for o in delivered[per_type:]]
|
|
342
|
+
+ [cancel_ok(o) for o in processing[per_type:]]
|
|
343
|
+
+ [refund_bad(o) for o in rng.sample(ids("shipped", "processing"), per_type)]
|
|
344
|
+
+ [cancel_bad(o) for o in rng.sample(ids("shipped", "delivered"), per_type)]
|
|
345
|
+
)
|
|
346
|
+
rng.shuffle(warm)
|
|
347
|
+
rng.shuffle(test)
|
|
348
|
+
return warm + test
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
# ------------------------------------------------------------------------------ mock policy
|
|
352
|
+
|
|
353
|
+
_PLANS = {
|
|
354
|
+
"refund": ["get_order", "refund_order"],
|
|
355
|
+
"status": ["get_order"],
|
|
356
|
+
"cancel": ["get_order", "cancel_order"],
|
|
357
|
+
"notify": ["find_customer", "notify_shipped"],
|
|
358
|
+
"email": ["find_customer"],
|
|
359
|
+
"count": ["find_customer", "list_orders"],
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
_ALLOWED = {"refund": ("refunded", "delivered"), "cancel": ("cancelled", "processing")}
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def _param_values(kind: str, groups: tuple[str, ...]) -> dict[str, str]:
|
|
367
|
+
if kind in {"refund", "status", "cancel"}:
|
|
368
|
+
return {"order_id": groups[0]}
|
|
369
|
+
if kind == "notify":
|
|
370
|
+
return {"name": groups[0], "order_id": groups[1]}
|
|
371
|
+
return {"name": groups[0]}
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
class ScriptedDeskLLM:
|
|
375
|
+
"""Plays a competent agent for the six request types, and routes to saved skills. A mock.
|
|
376
|
+
|
|
377
|
+
``careful`` makes it check an order's status before a refund or cancel and decline when the
|
|
378
|
+
state does not allow it (for a desk whose tools do not check; see ``make_drift_requests``).
|
|
379
|
+
"""
|
|
380
|
+
|
|
381
|
+
def __init__(self, careful: bool = False) -> None:
|
|
382
|
+
self.careful = careful
|
|
383
|
+
|
|
384
|
+
async def complete(self, messages: Sequence[Message], tools: Sequence[ToolSpec]) -> Reply:
|
|
385
|
+
if messages[0].content.startswith("You route"):
|
|
386
|
+
return self._route(messages[0].content)
|
|
387
|
+
return self._agent(messages)
|
|
388
|
+
|
|
389
|
+
def _route(self, prompt: str) -> Reply:
|
|
390
|
+
request = prompt.rsplit("Request: ", 1)[1]
|
|
391
|
+
wanted = classify(request)
|
|
392
|
+
body: dict[str, Any] = {"skill": None, "params": {}}
|
|
393
|
+
if wanted is not None:
|
|
394
|
+
kind, groups = wanted
|
|
395
|
+
values = _param_values(kind, groups)
|
|
396
|
+
for match in re.finditer(r"- (\S+): e\.g\. (.+?); parameters: (.*)", prompt):
|
|
397
|
+
example = classify(ast.literal_eval(match.group(2)))
|
|
398
|
+
if example is None or example[0] != kind:
|
|
399
|
+
continue
|
|
400
|
+
names = [p.split(" ")[0] for p in match.group(3).split(", ") if p != "none"]
|
|
401
|
+
if all(n in values for n in names):
|
|
402
|
+
body = {"skill": match.group(1), "params": {n: values[n] for n in names}}
|
|
403
|
+
break
|
|
404
|
+
return Reply(json.dumps(body), tokens=ROUTE_TOKENS)
|
|
405
|
+
|
|
406
|
+
def _agent(self, messages: Sequence[Message]) -> Reply:
|
|
407
|
+
kind, groups = classify(messages[0].content) or ("", ())
|
|
408
|
+
names: dict[str, str] = {}
|
|
409
|
+
results: list[tuple[str, Any]] = []
|
|
410
|
+
for m in messages:
|
|
411
|
+
for c in m.tool_calls:
|
|
412
|
+
names[c.id] = c.name
|
|
413
|
+
if m.role == "tool":
|
|
414
|
+
results.append((names.get(m.tool_call_id or "", ""), json.loads(m.content)))
|
|
415
|
+
if results and "error" in results[-1][1]:
|
|
416
|
+
return Reply(f"Could not complete: {results[-1][1]['error']}", tokens=AGENT_TOKENS)
|
|
417
|
+
values = _param_values(kind, groups)
|
|
418
|
+
oid, name = values.get("order_id", ""), values.get("name", "")
|
|
419
|
+
plan = _PLANS[kind]
|
|
420
|
+
first = results[0][1] if results else {}
|
|
421
|
+
if self.careful and kind in _ALLOWED and len(results) == 1:
|
|
422
|
+
verb, allowed = _ALLOWED[kind]
|
|
423
|
+
if first["status"] != allowed:
|
|
424
|
+
text = f"Order {oid} cannot be {verb} ({first['status']})."
|
|
425
|
+
return Reply(text, tokens=AGENT_TOKENS)
|
|
426
|
+
if len(results) < len(plan):
|
|
427
|
+
tool = plan[len(results)]
|
|
428
|
+
args: dict[str, dict[str, Any]] = {
|
|
429
|
+
"get_order": {"order_id": oid},
|
|
430
|
+
"find_customer": {"name": name},
|
|
431
|
+
"refund_order": {"order_id": oid, "amount": first.get("amount")},
|
|
432
|
+
"cancel_order": {"order_id": oid},
|
|
433
|
+
"notify_shipped": {"customer_id": first.get("customer_id"), "order_id": oid},
|
|
434
|
+
"list_orders": {"customer_id": first.get("customer_id")},
|
|
435
|
+
}
|
|
436
|
+
call = ToolCallReq(f"call_{len(messages)}", tool, args[tool])
|
|
437
|
+
return Reply("", (call,), tokens=AGENT_TOKENS)
|
|
438
|
+
text = {
|
|
439
|
+
"refund": lambda: f"Refunded {first['amount']} for order {oid}.",
|
|
440
|
+
"status": lambda: f"Order {oid} is {first['status']}.",
|
|
441
|
+
"cancel": lambda: f"Cancelled order {oid}.",
|
|
442
|
+
"notify": lambda: f"Notified {name} about order {oid}.",
|
|
443
|
+
"email": lambda: f"{name}'s email is {first['email']}.",
|
|
444
|
+
"count": lambda: f"{name} has placed {len(results[1][1]['orders'])} orders.",
|
|
445
|
+
}[kind]()
|
|
446
|
+
return Reply(text, tokens=AGENT_TOKENS)
|
agent_jit/guards.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""Daikon-style guards: conservative invariants that held in every successful trace.
|
|
2
|
+
|
|
3
|
+
A missing guard can let a wrong action fire; an extra guard only causes a fallback. So the
|
|
4
|
+
synthesizer leans towards more guards, but ``equals`` and ``length`` are limited to values that
|
|
5
|
+
are plausibly decisions (booleans, short word-like strings, list sizes) so ordinary data does not
|
|
6
|
+
trip them.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import datetime
|
|
12
|
+
import re
|
|
13
|
+
from collections.abc import Collection, Iterator, Mapping, Sequence
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from typing import Any, Literal
|
|
16
|
+
|
|
17
|
+
from agent_jit.ir import Refusal, Trace
|
|
18
|
+
from agent_jit.provenance import extract, strict_eq
|
|
19
|
+
|
|
20
|
+
Kind = Literal["type", "non_null", "non_empty", "equals", "length", "sign", "format"]
|
|
21
|
+
Path = tuple[str | int, ...]
|
|
22
|
+
|
|
23
|
+
MAX_EQUALS_LENGTH = 32
|
|
24
|
+
_FORMATS: dict[str, re.Pattern[str]] = {
|
|
25
|
+
"uuid": re.compile(
|
|
26
|
+
r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"
|
|
27
|
+
),
|
|
28
|
+
"email": re.compile(r"[^@\s]+@[^@\s]+\.[^@\s]+"),
|
|
29
|
+
"iso_date": re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}"),
|
|
30
|
+
"digits": re.compile(r"[0-9]+"),
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True)
|
|
35
|
+
class Guard:
|
|
36
|
+
step: int
|
|
37
|
+
path: Path
|
|
38
|
+
kind: Kind
|
|
39
|
+
expected: Any
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _is_number(v: Any) -> bool:
|
|
43
|
+
return isinstance(v, int | float) and not isinstance(v, bool)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _sign(v: int | float) -> int:
|
|
47
|
+
return (v > 0) - (v < 0)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _matches_format(value: Any, fmt: str) -> bool:
|
|
51
|
+
if not isinstance(value, str) or fmt not in _FORMATS:
|
|
52
|
+
return False
|
|
53
|
+
if not _FORMATS[fmt].fullmatch(value):
|
|
54
|
+
return False
|
|
55
|
+
if fmt == "iso_date":
|
|
56
|
+
try:
|
|
57
|
+
datetime.date.fromisoformat(value)
|
|
58
|
+
except ValueError:
|
|
59
|
+
return False
|
|
60
|
+
return True
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def check(guard: Guard, result: Any) -> bool:
|
|
64
|
+
"""True when ``result`` satisfies ``guard``. A missing path is False."""
|
|
65
|
+
try:
|
|
66
|
+
value = extract(result, guard.path)
|
|
67
|
+
except LookupError:
|
|
68
|
+
return False
|
|
69
|
+
kind = guard.kind
|
|
70
|
+
if kind == "type":
|
|
71
|
+
return bool(type(value).__name__ == guard.expected)
|
|
72
|
+
if kind == "non_null":
|
|
73
|
+
return value is not None
|
|
74
|
+
if kind == "non_empty":
|
|
75
|
+
return isinstance(value, str | list | dict) and len(value) > 0
|
|
76
|
+
if kind == "equals":
|
|
77
|
+
return strict_eq(value, guard.expected)
|
|
78
|
+
if kind == "length":
|
|
79
|
+
return isinstance(value, list) and bool(len(value) == guard.expected)
|
|
80
|
+
if kind == "sign":
|
|
81
|
+
return _is_number(value) and bool(_sign(value) == guard.expected)
|
|
82
|
+
if kind == "format":
|
|
83
|
+
return _matches_format(value, guard.expected)
|
|
84
|
+
raise ValueError(f"unknown guard kind: {kind!r}")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def nodes(value: Any, path: Path = ()) -> Iterator[Path]:
|
|
88
|
+
"""Every path worth guarding: dict keys, and list index 0 only."""
|
|
89
|
+
yield path
|
|
90
|
+
if isinstance(value, dict):
|
|
91
|
+
for k, v in value.items():
|
|
92
|
+
yield from nodes(v, (*path, k))
|
|
93
|
+
elif isinstance(value, list) and value:
|
|
94
|
+
yield from nodes(value[0], (*path, 0))
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _node_guards(step: int, path: Path, values: list[Any], decisions: bool) -> list[Guard]:
|
|
98
|
+
type_names = {type(v).__name__ for v in values}
|
|
99
|
+
if len(type_names) != 1:
|
|
100
|
+
return []
|
|
101
|
+
(type_name,) = type_names
|
|
102
|
+
first = values[0]
|
|
103
|
+
guards = [Guard(step, path, "type", type_name)]
|
|
104
|
+
if first is None:
|
|
105
|
+
return guards
|
|
106
|
+
guards.append(Guard(step, path, "non_null", True))
|
|
107
|
+
if isinstance(first, str | list | dict) and all(len(v) > 0 for v in values):
|
|
108
|
+
guards.append(Guard(step, path, "non_empty", True))
|
|
109
|
+
if _is_number(first):
|
|
110
|
+
signs = {_sign(v) for v in values}
|
|
111
|
+
if len(signs) == 1:
|
|
112
|
+
guards.append(Guard(step, path, "sign", signs.pop()))
|
|
113
|
+
if isinstance(first, str):
|
|
114
|
+
for fmt in _FORMATS:
|
|
115
|
+
if all(_matches_format(v, fmt) for v in values):
|
|
116
|
+
guards.append(Guard(step, path, "format", fmt))
|
|
117
|
+
break
|
|
118
|
+
if decisions and _is_decision_value(values):
|
|
119
|
+
guards.append(Guard(step, path, "equals", first))
|
|
120
|
+
if decisions and isinstance(first, list) and len({len(v) for v in values}) == 1:
|
|
121
|
+
guards.append(Guard(step, path, "length", len(first)))
|
|
122
|
+
return guards
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _is_decision_value(values: list[Any]) -> bool:
|
|
126
|
+
first = values[0]
|
|
127
|
+
if not all(strict_eq(first, v) for v in values[1:]):
|
|
128
|
+
return False
|
|
129
|
+
if isinstance(first, bool):
|
|
130
|
+
return True
|
|
131
|
+
return (
|
|
132
|
+
isinstance(first, str)
|
|
133
|
+
and len(first) <= MAX_EQUALS_LENGTH
|
|
134
|
+
and not any(c.isdigit() for c in first)
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _read_paths(extra: Collection[Path], result: Any) -> list[Path]:
|
|
139
|
+
"""Paths past list index 0 that a binding reads, with their ancestors and, for the list item
|
|
140
|
+
reached, all of the item's own fields, so a reordered list fails a guard instead of binding
|
|
141
|
+
the wrong item."""
|
|
142
|
+
paths: list[Path] = []
|
|
143
|
+
for path in extra:
|
|
144
|
+
cut = max((i for i, k in enumerate(path) if isinstance(k, int) and k != 0), default=None)
|
|
145
|
+
if cut is None:
|
|
146
|
+
continue # already covered by nodes()
|
|
147
|
+
paths.extend(path[: n + 1] for n in range(len(path)))
|
|
148
|
+
item = path[: cut + 1]
|
|
149
|
+
try:
|
|
150
|
+
paths.extend((*item, *rel) for rel in nodes(extract(result, item)))
|
|
151
|
+
except LookupError:
|
|
152
|
+
continue
|
|
153
|
+
return paths
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def synthesize(
|
|
157
|
+
traces: Sequence[Trace], reads: Mapping[int, Collection[Path]] | None = None
|
|
158
|
+
) -> tuple[Guard, ...]:
|
|
159
|
+
"""Guards that held in every trace. Steps that failed in any trace get none.
|
|
160
|
+
|
|
161
|
+
``reads`` maps a step to the output paths the compiled code reads; those past list index 0 get
|
|
162
|
+
guards too, which ``nodes`` alone would not produce."""
|
|
163
|
+
if not traces:
|
|
164
|
+
raise Refusal("no traces to synthesize guards from")
|
|
165
|
+
first = traces[0]
|
|
166
|
+
sequence = tuple(s.tool for s in first.steps)
|
|
167
|
+
for t in traces[1:]:
|
|
168
|
+
if tuple(s.tool for s in t.steps) != sequence:
|
|
169
|
+
raise Refusal(f"tool sequence differs in run {t.run_id}")
|
|
170
|
+
last_mutation = max((s.index for s in first.steps if s.effect != "read"), default=-1)
|
|
171
|
+
guards: list[Guard] = []
|
|
172
|
+
for i, step in enumerate(first.steps):
|
|
173
|
+
if not all(t.steps[i].ok for t in traces):
|
|
174
|
+
continue
|
|
175
|
+
forced = set(_read_paths((reads or {}).get(i, ()), step.result))
|
|
176
|
+
for path in dict.fromkeys([*nodes(step.result), *forced]):
|
|
177
|
+
try:
|
|
178
|
+
values = [extract(t.steps[i].result, path) for t in traces]
|
|
179
|
+
except LookupError:
|
|
180
|
+
continue
|
|
181
|
+
# A list item that was picked by position is only trusted if it is still the same item,
|
|
182
|
+
# so its fields get the identity (equals) guards even when no write follows.
|
|
183
|
+
decisions = i <= last_mutation or path in forced
|
|
184
|
+
guards.extend(_node_guards(i, path, values, decisions=decisions))
|
|
185
|
+
return tuple(guards)
|
agent_jit/ir.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Frozen types and exceptions shared by every module."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Any, Literal
|
|
8
|
+
|
|
9
|
+
Effect = Literal["read", "write", "irreversible"]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ToolRejected(Exception):
|
|
13
|
+
"""A tool refused the call; nothing happened, so the call may be retried."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class OutcomeUnknown(Exception):
|
|
17
|
+
"""A mutating call may or may not have happened; a human must check."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Refusal(Exception):
|
|
21
|
+
"""The compiler declined to compile; the message says why."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class ToolCallReq:
|
|
26
|
+
id: str
|
|
27
|
+
name: str
|
|
28
|
+
args: Mapping[str, Any]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class Message:
|
|
33
|
+
role: Literal["user", "assistant", "tool"]
|
|
34
|
+
content: str
|
|
35
|
+
tool_calls: tuple[ToolCallReq, ...] = ()
|
|
36
|
+
tool_call_id: str | None = None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True)
|
|
40
|
+
class Reply:
|
|
41
|
+
content: str
|
|
42
|
+
tool_calls: tuple[ToolCallReq, ...] = ()
|
|
43
|
+
tokens: int = 0
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class TraceStep:
|
|
48
|
+
index: int
|
|
49
|
+
tool: str
|
|
50
|
+
args: Mapping[str, Any]
|
|
51
|
+
result: Any
|
|
52
|
+
effect: Effect
|
|
53
|
+
ok: bool
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class Trace:
|
|
58
|
+
run_id: str
|
|
59
|
+
request: str
|
|
60
|
+
steps: tuple[TraceStep, ...]
|
|
61
|
+
answer: str
|
|
62
|
+
tokens: int
|
|
63
|
+
success: bool | None
|
|
64
|
+
schemas: Mapping[str, str] = field(default_factory=dict)
|