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
agent_jit/router.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""Pick a compiled skill for a request with one LLM call, and distrust the answer.
|
|
2
|
+
|
|
3
|
+
The model may only choose a skill and copy parameter values out of the request. Anything else,
|
|
4
|
+
including a value that does not literally appear in the request, means "no route" and the plain
|
|
5
|
+
agent runs.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import math
|
|
12
|
+
import re
|
|
13
|
+
from collections.abc import Mapping, Sequence
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from agent_jit.compiler import CompiledSkill
|
|
18
|
+
from agent_jit.ir import Message
|
|
19
|
+
from agent_jit.provenance import Param, find_in_request, literal_fits, request_shape
|
|
20
|
+
from agent_jit.tools import LLMClient
|
|
21
|
+
|
|
22
|
+
_INTEGER = re.compile(r"-?[0-9]+")
|
|
23
|
+
_DECIMAL = re.compile(r"-?[0-9]+(\.[0-9]+)?")
|
|
24
|
+
_CASE_CHANGING = frozenset({"lower", "upper"})
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class Route:
|
|
29
|
+
skill: CompiledSkill
|
|
30
|
+
params: Mapping[str, Any]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _prompt(request: str, skills: Sequence[CompiledSkill]) -> str:
|
|
34
|
+
lines = [
|
|
35
|
+
"You route a user request to a saved skill, or to none.",
|
|
36
|
+
'Reply with JSON only: {"skill": "<name>" or null, "params": {"<name>": <value>}}.',
|
|
37
|
+
"Use null when no skill clearly fits. Copy parameter values exactly from the request.",
|
|
38
|
+
"Skills:",
|
|
39
|
+
]
|
|
40
|
+
for skill in skills:
|
|
41
|
+
params = ", ".join(f"{p.name} ({p.kind})" for p in skill.params) or "none"
|
|
42
|
+
lines.append(f"- {skill.name}: e.g. {skill.example_request!r}; parameters: {params}")
|
|
43
|
+
lines.append(f"Request: {request}")
|
|
44
|
+
return "\n".join(lines)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _number_text(value: Any, kind: str) -> tuple[Any, str] | None:
|
|
48
|
+
"""Normalize an int or float parameter; returns (value, text it should appear as)."""
|
|
49
|
+
if isinstance(value, bool):
|
|
50
|
+
return None
|
|
51
|
+
if kind == "int":
|
|
52
|
+
if isinstance(value, int):
|
|
53
|
+
return value, str(value)
|
|
54
|
+
if isinstance(value, str) and _INTEGER.fullmatch(value):
|
|
55
|
+
return int(value), value
|
|
56
|
+
return None
|
|
57
|
+
if isinstance(value, int | float):
|
|
58
|
+
number = float(value)
|
|
59
|
+
return (number, repr(value)) if math.isfinite(number) else None
|
|
60
|
+
if isinstance(value, str) and _DECIMAL.fullmatch(value):
|
|
61
|
+
return float(value), value
|
|
62
|
+
return None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _validate(param: Param, value: Any, request: str) -> tuple[bool, Any, str]:
|
|
66
|
+
"""(valid, normalized value, the exact text of the request it was found in)."""
|
|
67
|
+
if param.kind == "str":
|
|
68
|
+
if not isinstance(value, str):
|
|
69
|
+
return False, None, ""
|
|
70
|
+
normalized, text = value, value
|
|
71
|
+
if param.transform.startswith("removeprefix:") and not value.startswith(
|
|
72
|
+
param.transform[len("removeprefix:") :]
|
|
73
|
+
):
|
|
74
|
+
return False, None, ""
|
|
75
|
+
else:
|
|
76
|
+
parsed = _number_text(value, param.kind)
|
|
77
|
+
if parsed is None:
|
|
78
|
+
return False, None, ""
|
|
79
|
+
normalized, text = parsed
|
|
80
|
+
found = find_in_request(request, text, param.transform in _CASE_CHANGING)
|
|
81
|
+
return (found is not None), normalized, found or ""
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _parse(content: str) -> tuple[str, dict[str, Any]] | None:
|
|
85
|
+
try:
|
|
86
|
+
reply = json.loads(content)
|
|
87
|
+
except json.JSONDecodeError:
|
|
88
|
+
return None
|
|
89
|
+
if not isinstance(reply, dict):
|
|
90
|
+
return None
|
|
91
|
+
name, params = reply.get("skill"), reply.get("params")
|
|
92
|
+
if not isinstance(name, str) or not isinstance(params, dict):
|
|
93
|
+
return None
|
|
94
|
+
return name, params
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _fits_shape(skill: CompiledSkill, request: str, literals: list[tuple[str, str]]) -> bool:
|
|
98
|
+
"""A parameter cannot stretch over more words than it had when learned, and the rest of the
|
|
99
|
+
request must equal a learned request shape."""
|
|
100
|
+
by_name = {p.name: p for p in skill.params}
|
|
101
|
+
if not all(literal_fits(by_name[name].texts, literal) for name, literal in literals):
|
|
102
|
+
return False
|
|
103
|
+
try:
|
|
104
|
+
return request_shape(request, literals) in skill.request_shapes
|
|
105
|
+
except ValueError:
|
|
106
|
+
return False
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
async def route(
|
|
110
|
+
llm: LLMClient, request: str, skills: Sequence[CompiledSkill]
|
|
111
|
+
) -> tuple[Route | None, int]:
|
|
112
|
+
"""Ask the model for a skill; returns the validated route (or None) and the tokens spent."""
|
|
113
|
+
if not skills:
|
|
114
|
+
return None, 0
|
|
115
|
+
reply = await llm.complete([Message("user", _prompt(request, skills))], [])
|
|
116
|
+
parsed = _parse(reply.content)
|
|
117
|
+
if parsed is None:
|
|
118
|
+
return None, reply.tokens
|
|
119
|
+
name, given = parsed
|
|
120
|
+
skill = next((s for s in skills if s.name == name), None)
|
|
121
|
+
if skill is None or set(given) != {p.name for p in skill.params}:
|
|
122
|
+
return None, reply.tokens
|
|
123
|
+
checked: dict[str, Any] = {}
|
|
124
|
+
literals: list[tuple[str, str]] = []
|
|
125
|
+
for param in skill.params:
|
|
126
|
+
ok, normalized, literal = _validate(param, given[param.name], request)
|
|
127
|
+
if not ok:
|
|
128
|
+
return None, reply.tokens
|
|
129
|
+
checked[param.name] = normalized
|
|
130
|
+
literals.append((param.name, literal))
|
|
131
|
+
# The model picks the skill, so nothing it says may make a skill run for a request unlike the
|
|
132
|
+
# ones it was learned from: a writing skill could act on the wrong intent, and a read-only one
|
|
133
|
+
# would answer "Cancel order 9" without cancelling. The check is plain text, not an opinion.
|
|
134
|
+
if not _fits_shape(skill, request, literals):
|
|
135
|
+
return None, reply.tokens
|
|
136
|
+
return Route(skill, checked), reply.tokens
|
agent_jit/runtime.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""Execute compiled skills and build the synthetic history that lets an agent finish the job."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import copy
|
|
6
|
+
import json
|
|
7
|
+
from collections.abc import Mapping, Sequence
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import Any, NoReturn
|
|
10
|
+
|
|
11
|
+
from agent_jit.compiler import CompiledSkill, load_skill
|
|
12
|
+
from agent_jit.guards import Guard, check
|
|
13
|
+
from agent_jit.ir import Message, OutcomeUnknown, ToolCallReq, ToolRejected, TraceStep
|
|
14
|
+
from agent_jit.provenance import extract, get_transform
|
|
15
|
+
from agent_jit.tools import ToolCaller
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class GuardViolation(Exception):
|
|
19
|
+
"""A guard failed after its step ran; compiled code runs no further tool."""
|
|
20
|
+
|
|
21
|
+
def __init__(self, guard: Guard) -> None:
|
|
22
|
+
super().__init__(f"guard {guard.kind} at {guard.path!r} failed at step {guard.step}")
|
|
23
|
+
self.guard = guard
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ExecFailure(Exception):
|
|
27
|
+
"""A value the compiled code needed was missing or could not be transformed."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class ExecResult:
|
|
32
|
+
answer: str | None
|
|
33
|
+
steps: tuple[TraceStep, ...]
|
|
34
|
+
failure: str | None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Context:
|
|
38
|
+
"""What compiled skills call into: runs tools, checks guards, reads values."""
|
|
39
|
+
|
|
40
|
+
def __init__(self, tools: ToolCaller) -> None:
|
|
41
|
+
self._tools = tools
|
|
42
|
+
self._done: list[TraceStep] = []
|
|
43
|
+
self._rechecked: set[int] = set()
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def done(self) -> tuple[TraceStep, ...]:
|
|
47
|
+
return tuple(self._done)
|
|
48
|
+
|
|
49
|
+
async def call(
|
|
50
|
+
self, index: int, tool: str, args: Mapping[str, Any], guards: Sequence[Guard]
|
|
51
|
+
) -> Any:
|
|
52
|
+
self._recheck_earlier(index, guards)
|
|
53
|
+
effect = self._tools.spec(tool).effect
|
|
54
|
+
frozen = copy.deepcopy(dict(args))
|
|
55
|
+
try:
|
|
56
|
+
result = await self._tools.call(tool, args)
|
|
57
|
+
except ToolRejected as exc:
|
|
58
|
+
self._done.append(TraceStep(index, tool, frozen, {"error": str(exc)}, effect, False))
|
|
59
|
+
raise
|
|
60
|
+
except OutcomeUnknown:
|
|
61
|
+
raise
|
|
62
|
+
except Exception as exc:
|
|
63
|
+
if effect != "read":
|
|
64
|
+
raise
|
|
65
|
+
# A failed read changed nothing, so the agent can safely take over from here.
|
|
66
|
+
reason = f"{type(exc).__name__}: {exc}"
|
|
67
|
+
self._done.append(TraceStep(index, tool, frozen, {"error": reason}, effect, False))
|
|
68
|
+
raise ExecFailure(f"{tool} failed: {reason}") from exc
|
|
69
|
+
self._done.append(TraceStep(index, tool, frozen, copy.deepcopy(result), effect, True))
|
|
70
|
+
for guard in guards:
|
|
71
|
+
if guard.step == index and not check(guard, result):
|
|
72
|
+
raise GuardViolation(guard)
|
|
73
|
+
return result
|
|
74
|
+
|
|
75
|
+
def _recheck_earlier(self, index: int, guards: Sequence[Guard]) -> None:
|
|
76
|
+
"""Before a step runs, check its guards that concern steps already done.
|
|
77
|
+
|
|
78
|
+
A branch's own invariants on the shared steps must hold before any branch tool runs.
|
|
79
|
+
"""
|
|
80
|
+
for guard in guards:
|
|
81
|
+
if guard.step < index and id(guard) not in self._rechecked:
|
|
82
|
+
self._rechecked.add(id(guard))
|
|
83
|
+
if not check(guard, self._done[guard.step].result):
|
|
84
|
+
raise GuardViolation(guard)
|
|
85
|
+
|
|
86
|
+
def fail(self, message: str) -> NoReturn:
|
|
87
|
+
raise ExecFailure(message)
|
|
88
|
+
|
|
89
|
+
def get(self, result: Any, path: tuple[str | int, ...], transform: str) -> Any:
|
|
90
|
+
fn = get_transform(transform)
|
|
91
|
+
try:
|
|
92
|
+
return fn(extract(result, path))
|
|
93
|
+
except (LookupError, TypeError, ValueError) as exc:
|
|
94
|
+
raise ExecFailure(f"cannot read {path!r} with {transform}: {exc}") from exc
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
async def execute(skill: CompiledSkill, params: Mapping[str, Any], tools: ToolCaller) -> ExecResult:
|
|
98
|
+
"""Run ``skill``. ``failure`` is set when a guard, value or rejected tool stopped it.
|
|
99
|
+
|
|
100
|
+
``OutcomeUnknown`` and unexpected errors propagate: there is no safe fallback after them.
|
|
101
|
+
"""
|
|
102
|
+
expected = sorted(p.name for p in skill.params)
|
|
103
|
+
if sorted(params) != expected:
|
|
104
|
+
raise ValueError(f"parameters {sorted(params)} do not match the skill's {expected}")
|
|
105
|
+
ctx = Context(tools)
|
|
106
|
+
run = load_skill(skill)
|
|
107
|
+
answer: str | None = None
|
|
108
|
+
failure: str | None = None
|
|
109
|
+
try:
|
|
110
|
+
answer = await run(ctx, **params)
|
|
111
|
+
except GuardViolation as exc:
|
|
112
|
+
failure = str(exc)
|
|
113
|
+
except ExecFailure as exc:
|
|
114
|
+
failure = str(exc)
|
|
115
|
+
except ToolRejected as exc:
|
|
116
|
+
last = ctx.done[-1].tool if ctx.done else "tool"
|
|
117
|
+
failure = f"{last} was rejected: {exc}"
|
|
118
|
+
return ExecResult(answer, ctx.done, failure)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def synthetic_history(request: str, steps: Sequence[TraceStep]) -> tuple[Message, ...]:
|
|
122
|
+
"""The conversation an agent would have had if it had made ``steps`` itself.
|
|
123
|
+
|
|
124
|
+
Every call is paired with its result, so the agent sees the work as already done.
|
|
125
|
+
"""
|
|
126
|
+
messages: list[Message] = [Message("user", request)]
|
|
127
|
+
for step in steps:
|
|
128
|
+
call_id = f"jit_{step.index}"
|
|
129
|
+
messages.append(
|
|
130
|
+
Message("assistant", "", tool_calls=(ToolCallReq(call_id, step.tool, step.args),))
|
|
131
|
+
)
|
|
132
|
+
# The text is for the LLM to read, so a result that is not JSON is shown by repr
|
|
133
|
+
# rather than losing the history of a write that already happened.
|
|
134
|
+
messages.append(
|
|
135
|
+
Message("tool", json.dumps(step.result, default=repr), tool_call_id=call_id)
|
|
136
|
+
)
|
|
137
|
+
return tuple(messages)
|
agent_jit/slicer.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Backward slicing: drop reads that nothing depends on, never the checks that guard a write."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import replace
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from agent_jit.ir import Trace, TraceStep
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _leaves(value: Any) -> list[str]:
|
|
12
|
+
"""String forms of every scalar inside ``value`` (None excluded)."""
|
|
13
|
+
if isinstance(value, dict):
|
|
14
|
+
return [s for v in value.values() for s in _leaves(v)]
|
|
15
|
+
if isinstance(value, list):
|
|
16
|
+
return [s for v in value for s in _leaves(v)]
|
|
17
|
+
if value is None:
|
|
18
|
+
return []
|
|
19
|
+
return [str(value)]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _occurs(text: str, needle: str) -> bool:
|
|
23
|
+
"""``needle`` appears in ``text`` bounded by non-alphanumerics (any length)."""
|
|
24
|
+
if not needle:
|
|
25
|
+
return False
|
|
26
|
+
start = text.find(needle)
|
|
27
|
+
while start != -1:
|
|
28
|
+
end = start + len(needle)
|
|
29
|
+
if (start == 0 or not text[start - 1].isalnum()) and (
|
|
30
|
+
end == len(text) or not text[end].isalnum()
|
|
31
|
+
):
|
|
32
|
+
return True
|
|
33
|
+
start = text.find(needle, start + 1)
|
|
34
|
+
return False
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _is_mutating(step: TraceStep) -> bool:
|
|
38
|
+
return step.effect != "read"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def slice_trace(trace: Trace) -> Trace:
|
|
42
|
+
"""Return a copy of ``trace`` without dead reads, steps re-indexed from 0.
|
|
43
|
+
|
|
44
|
+
Kept: every mutating step (even a failed one) and every read that comes before the last
|
|
45
|
+
mutating step, because it may be the check that made the write safe. Removed: failed reads,
|
|
46
|
+
and reads after the last mutating step whose values reach neither the answer nor the
|
|
47
|
+
arguments of a later kept step.
|
|
48
|
+
"""
|
|
49
|
+
last_mutation = max((s.index for s in trace.steps if _is_mutating(s)), default=-1)
|
|
50
|
+
needed: set[str] = set()
|
|
51
|
+
kept: list[TraceStep] = []
|
|
52
|
+
for step in reversed(trace.steps):
|
|
53
|
+
if _is_mutating(step):
|
|
54
|
+
keep = True
|
|
55
|
+
elif not step.ok:
|
|
56
|
+
keep = False
|
|
57
|
+
elif step.index < last_mutation:
|
|
58
|
+
keep = True
|
|
59
|
+
else:
|
|
60
|
+
produced = _leaves(step.result)
|
|
61
|
+
keep = any(p in needed or _occurs(trace.answer, p) for p in produced)
|
|
62
|
+
if keep:
|
|
63
|
+
kept.append(step)
|
|
64
|
+
needed.update(_leaves(dict(step.args)))
|
|
65
|
+
ordered = reversed(kept)
|
|
66
|
+
return replace(trace, steps=tuple(replace(s, index=i) for i, s in enumerate(ordered)))
|
agent_jit/stats.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Run statistics and the circuit breaker that switches off a skill that keeps falling back."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import deque
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import TYPE_CHECKING
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from agent_jit.core import RunResult
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class CircuitBreaker:
|
|
14
|
+
"""Trips a skill once more than ``max_fallback_rate`` of its last ``window`` runs fell back.
|
|
15
|
+
|
|
16
|
+
It needs at least ``min_runs`` recorded runs first, and a tripped skill stays tripped.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def __init__(self, window: int = 10, min_runs: int = 5, max_fallback_rate: float = 0.5) -> None:
|
|
20
|
+
if window < 1 or min_runs < 1:
|
|
21
|
+
raise ValueError("window and min_runs must be at least 1")
|
|
22
|
+
if min_runs > window:
|
|
23
|
+
raise ValueError("min_runs larger than window could never trip")
|
|
24
|
+
if not 0.0 <= max_fallback_rate <= 1.0:
|
|
25
|
+
raise ValueError("max_fallback_rate must be between 0 and 1")
|
|
26
|
+
self._window = window
|
|
27
|
+
self._min_runs = min_runs
|
|
28
|
+
self._max_rate = max_fallback_rate
|
|
29
|
+
self._runs: dict[str, deque[bool]] = {}
|
|
30
|
+
self._tripped: set[str] = set()
|
|
31
|
+
|
|
32
|
+
def record(self, skill: str, fell_back: bool) -> None:
|
|
33
|
+
runs = self._runs.setdefault(skill, deque(maxlen=self._window))
|
|
34
|
+
runs.append(fell_back)
|
|
35
|
+
if len(runs) >= self._min_runs and sum(runs) / len(runs) > self._max_rate:
|
|
36
|
+
self._tripped.add(skill)
|
|
37
|
+
|
|
38
|
+
def tripped(self, skill: str) -> bool:
|
|
39
|
+
return skill in self._tripped
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class RunStats:
|
|
44
|
+
plain: int
|
|
45
|
+
compiled: int
|
|
46
|
+
fallback: int
|
|
47
|
+
router_tokens: int
|
|
48
|
+
inner_tokens: int
|
|
49
|
+
phrasing_tokens: int
|
|
50
|
+
compile_tokens: int # always 0: the compiler calls no LLM
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class StatsBook:
|
|
54
|
+
def __init__(self) -> None:
|
|
55
|
+
self._counts = {"plain": 0, "compiled": 0, "fallback": 0}
|
|
56
|
+
self._router = 0
|
|
57
|
+
self._inner = 0
|
|
58
|
+
self._phrasing = 0
|
|
59
|
+
|
|
60
|
+
def add(self, result: RunResult) -> None:
|
|
61
|
+
self._counts[result.path] += 1
|
|
62
|
+
self._router += result.router_tokens
|
|
63
|
+
self._inner += result.inner_tokens
|
|
64
|
+
self._phrasing += result.phrasing_tokens
|
|
65
|
+
|
|
66
|
+
def snapshot(self) -> RunStats:
|
|
67
|
+
return RunStats(
|
|
68
|
+
plain=self._counts["plain"],
|
|
69
|
+
compiled=self._counts["compiled"],
|
|
70
|
+
fallback=self._counts["fallback"],
|
|
71
|
+
router_tokens=self._router,
|
|
72
|
+
inner_tokens=self._inner,
|
|
73
|
+
phrasing_tokens=self._phrasing,
|
|
74
|
+
compile_tokens=0,
|
|
75
|
+
)
|
agent_jit/store.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""SQLite persistence for traces. Anything that is not plain JSON is refused loudly."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import sqlite3
|
|
7
|
+
from collections.abc import Iterator
|
|
8
|
+
from contextlib import contextmanager
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from agent_jit.ir import Trace, TraceStep
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _check_json(value: Any, where: str) -> None:
|
|
16
|
+
if value is None or isinstance(value, bool | int | float | str):
|
|
17
|
+
return
|
|
18
|
+
if isinstance(value, list):
|
|
19
|
+
for i, item in enumerate(value):
|
|
20
|
+
_check_json(item, f"{where}[{i}]")
|
|
21
|
+
return
|
|
22
|
+
if isinstance(value, dict):
|
|
23
|
+
for key, item in value.items():
|
|
24
|
+
if not isinstance(key, str):
|
|
25
|
+
raise TypeError(f"non-string key {key!r} at {where}")
|
|
26
|
+
_check_json(item, f"{where}.{key}")
|
|
27
|
+
return
|
|
28
|
+
raise TypeError(f"value of type {type(value).__name__} at {where} is not JSON")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _to_json(trace: Trace) -> str:
|
|
32
|
+
steps = []
|
|
33
|
+
for s in trace.steps:
|
|
34
|
+
_check_json(dict(s.args), f"step {s.index} args")
|
|
35
|
+
_check_json(s.result, f"step {s.index} result")
|
|
36
|
+
steps.append(
|
|
37
|
+
{
|
|
38
|
+
"index": s.index,
|
|
39
|
+
"tool": s.tool,
|
|
40
|
+
"args": dict(s.args),
|
|
41
|
+
"result": s.result,
|
|
42
|
+
"effect": s.effect,
|
|
43
|
+
"ok": s.ok,
|
|
44
|
+
}
|
|
45
|
+
)
|
|
46
|
+
return json.dumps(
|
|
47
|
+
{
|
|
48
|
+
"run_id": trace.run_id,
|
|
49
|
+
"request": trace.request,
|
|
50
|
+
"steps": steps,
|
|
51
|
+
"answer": trace.answer,
|
|
52
|
+
"tokens": trace.tokens,
|
|
53
|
+
"success": trace.success,
|
|
54
|
+
"schemas": dict(trace.schemas),
|
|
55
|
+
}
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _from_json(body: str) -> Trace:
|
|
60
|
+
d = json.loads(body)
|
|
61
|
+
steps = tuple(
|
|
62
|
+
TraceStep(s["index"], s["tool"], s["args"], s["result"], s["effect"], s["ok"])
|
|
63
|
+
for s in d["steps"]
|
|
64
|
+
)
|
|
65
|
+
return Trace(
|
|
66
|
+
d["run_id"],
|
|
67
|
+
d["request"],
|
|
68
|
+
steps,
|
|
69
|
+
d["answer"],
|
|
70
|
+
d["tokens"],
|
|
71
|
+
d["success"],
|
|
72
|
+
d.get("schemas", {}),
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class TraceStore:
|
|
77
|
+
def __init__(self, path: str | Path) -> None:
|
|
78
|
+
self._path = str(path)
|
|
79
|
+
with self._connect() as con:
|
|
80
|
+
con.execute(
|
|
81
|
+
"CREATE TABLE IF NOT EXISTS traces ("
|
|
82
|
+
"run_id TEXT PRIMARY KEY, success INTEGER, body TEXT NOT NULL)"
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
@contextmanager
|
|
86
|
+
def _connect(self) -> Iterator[sqlite3.Connection]:
|
|
87
|
+
con = sqlite3.connect(self._path)
|
|
88
|
+
try:
|
|
89
|
+
with con:
|
|
90
|
+
yield con
|
|
91
|
+
finally:
|
|
92
|
+
con.close()
|
|
93
|
+
|
|
94
|
+
def save(self, trace: Trace) -> None:
|
|
95
|
+
body = _to_json(trace)
|
|
96
|
+
success = None if trace.success is None else int(trace.success)
|
|
97
|
+
with self._connect() as con:
|
|
98
|
+
con.execute(
|
|
99
|
+
"INSERT INTO traces (run_id, success, body) VALUES (?, ?, ?)",
|
|
100
|
+
(trace.run_id, success, body),
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
def successful(self) -> tuple[Trace, ...]:
|
|
104
|
+
with self._connect() as con:
|
|
105
|
+
rows = con.execute(
|
|
106
|
+
"SELECT body FROM traces WHERE success = 1 ORDER BY rowid"
|
|
107
|
+
).fetchall()
|
|
108
|
+
return tuple(_from_json(r[0]) for r in rows)
|
|
109
|
+
|
|
110
|
+
def all_traces(self) -> tuple[Trace, ...]:
|
|
111
|
+
"""Every saved trace, including failed and unconfirmed ones, oldest first."""
|
|
112
|
+
with self._connect() as con:
|
|
113
|
+
rows = con.execute("SELECT body FROM traces ORDER BY rowid").fetchall()
|
|
114
|
+
return tuple(_from_json(r[0]) for r in rows)
|
agent_jit/tools.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Tool registry and the protocols the rest of the package depends on."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import Any, Protocol
|
|
10
|
+
|
|
11
|
+
from agent_jit.ir import Effect, Message, Reply
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class ToolSpec:
|
|
16
|
+
name: str
|
|
17
|
+
schema: Mapping[str, Any]
|
|
18
|
+
effect: Effect = "write"
|
|
19
|
+
idempotency_param: str | None = None
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def schema_hash(spec: ToolSpec) -> str:
|
|
23
|
+
"""A short fingerprint of everything about a tool that a compiled skill depends on."""
|
|
24
|
+
body = json.dumps(
|
|
25
|
+
{
|
|
26
|
+
"name": spec.name,
|
|
27
|
+
"schema": spec.schema,
|
|
28
|
+
"effect": spec.effect,
|
|
29
|
+
"idempotency_param": spec.idempotency_param,
|
|
30
|
+
},
|
|
31
|
+
sort_keys=True,
|
|
32
|
+
separators=(",", ":"),
|
|
33
|
+
)
|
|
34
|
+
return hashlib.sha256(body.encode("utf-8")).hexdigest()[:16]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class ToolCaller(Protocol):
|
|
38
|
+
def specs(self) -> tuple[ToolSpec, ...]: ...
|
|
39
|
+
|
|
40
|
+
def spec(self, name: str) -> ToolSpec: ...
|
|
41
|
+
|
|
42
|
+
async def call(self, name: str, args: Mapping[str, Any]) -> Any: ...
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class LLMClient(Protocol):
|
|
46
|
+
async def complete(self, messages: Sequence[Message], tools: Sequence[ToolSpec]) -> Reply: ...
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
Agent = Callable[[str, LLMClient, ToolCaller, Sequence[Message]], Awaitable[str]]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class ToolRegistry:
|
|
53
|
+
def __init__(self) -> None:
|
|
54
|
+
self._specs: dict[str, ToolSpec] = {}
|
|
55
|
+
self._fns: dict[str, Callable[..., Awaitable[Any]]] = {}
|
|
56
|
+
|
|
57
|
+
def register(
|
|
58
|
+
self,
|
|
59
|
+
name: str,
|
|
60
|
+
fn: Callable[..., Awaitable[Any]],
|
|
61
|
+
schema: Mapping[str, Any],
|
|
62
|
+
effect: Effect = "write",
|
|
63
|
+
idempotency_param: str | None = None,
|
|
64
|
+
) -> None:
|
|
65
|
+
if name in self._specs:
|
|
66
|
+
raise ValueError(f"tool already registered: {name}")
|
|
67
|
+
self._specs[name] = ToolSpec(name, schema, effect, idempotency_param)
|
|
68
|
+
self._fns[name] = fn
|
|
69
|
+
|
|
70
|
+
def specs(self) -> tuple[ToolSpec, ...]:
|
|
71
|
+
return tuple(self._specs.values())
|
|
72
|
+
|
|
73
|
+
def spec(self, name: str) -> ToolSpec:
|
|
74
|
+
try:
|
|
75
|
+
return self._specs[name]
|
|
76
|
+
except KeyError:
|
|
77
|
+
raise KeyError(f"unknown tool: {name}") from None
|
|
78
|
+
|
|
79
|
+
async def call(self, name: str, args: Mapping[str, Any]) -> Any:
|
|
80
|
+
self.spec(name)
|
|
81
|
+
return await self._fns[name](**args)
|
agent_jit/tracer.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Recording wrappers around an LLM client and a tool caller."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import copy
|
|
6
|
+
from collections.abc import Mapping, Sequence
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from agent_jit.ir import Message, Reply, ToolRejected, TraceStep
|
|
10
|
+
from agent_jit.tools import LLMClient, ToolCaller, ToolSpec
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class RecordingLLM:
|
|
14
|
+
def __init__(self, inner: LLMClient) -> None:
|
|
15
|
+
self._inner = inner
|
|
16
|
+
self.tokens = 0
|
|
17
|
+
self.calls = 0
|
|
18
|
+
|
|
19
|
+
async def complete(self, messages: Sequence[Message], tools: Sequence[ToolSpec]) -> Reply:
|
|
20
|
+
reply = await self._inner.complete(messages, tools)
|
|
21
|
+
self.calls += 1
|
|
22
|
+
self.tokens += reply.tokens
|
|
23
|
+
return reply
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class RecordingTools:
|
|
27
|
+
def __init__(self, inner: ToolCaller) -> None:
|
|
28
|
+
self._inner = inner
|
|
29
|
+
self._steps: list[TraceStep] = []
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def steps(self) -> tuple[TraceStep, ...]:
|
|
33
|
+
return tuple(self._steps)
|
|
34
|
+
|
|
35
|
+
def specs(self) -> tuple[ToolSpec, ...]:
|
|
36
|
+
return self._inner.specs()
|
|
37
|
+
|
|
38
|
+
def spec(self, name: str) -> ToolSpec:
|
|
39
|
+
return self._inner.spec(name)
|
|
40
|
+
|
|
41
|
+
async def call(self, name: str, args: Mapping[str, Any]) -> Any:
|
|
42
|
+
effect = self._inner.spec(name).effect
|
|
43
|
+
index = len(self._steps)
|
|
44
|
+
frozen_args = copy.deepcopy(dict(args))
|
|
45
|
+
try:
|
|
46
|
+
result = await self._inner.call(name, args)
|
|
47
|
+
except ToolRejected as exc:
|
|
48
|
+
failed = TraceStep(index, name, frozen_args, {"error": str(exc)}, effect, False)
|
|
49
|
+
self._steps.append(failed)
|
|
50
|
+
raise
|
|
51
|
+
except BaseException as exc:
|
|
52
|
+
self._steps.append(
|
|
53
|
+
TraceStep(index, name, frozen_args, {"error": type(exc).__name__}, effect, False)
|
|
54
|
+
)
|
|
55
|
+
raise
|
|
56
|
+
self._steps.append(TraceStep(index, name, frozen_args, copy.deepcopy(result), effect, True))
|
|
57
|
+
return result
|