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/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Adapters between agent-jit's interfaces and concrete tools, models and benchmarks."""
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""An ``LLMClient`` over the Anthropic Messages API, restricted to Haiku and capped by a budget.
|
|
2
|
+
|
|
3
|
+
The SDK client is injected (an ``anthropic.AsyncAnthropic`` or anything with an async
|
|
4
|
+
``messages.create``), so this module imports nothing third-party and tests never touch the network.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
from collections.abc import Sequence
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from agent_jit.ir import Message, Reply, ToolCallReq
|
|
14
|
+
from agent_jit.tools import ToolSpec
|
|
15
|
+
|
|
16
|
+
ALLOWED_MODELS = frozenset({"claude-haiku-5-5"})
|
|
17
|
+
|
|
18
|
+
# Estimated list prices in USD per million tokens for claude-haiku-5-5, prompts up to 100k tokens
|
|
19
|
+
# (platform.claude.com/docs/en/about-claude/pricing, read 2026-11-29). An estimate: an account's
|
|
20
|
+
# real rates may differ, and prompts over 100k tokens are priced higher.
|
|
21
|
+
PRICE_PER_MTOK = {"input": 0.10, "output": 0.50, "cache_write": 0.125, "cache_read": 0.01}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def cost_usd(usage: dict[str, int]) -> float:
|
|
25
|
+
return sum(usage.get(kind, 0) * price for kind, price in PRICE_PER_MTOK.items()) / 1_000_000
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class BudgetExceeded(Exception):
|
|
29
|
+
"""The token budget is used up; no further call was made."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _tool_json(spec: ToolSpec) -> dict[str, Any]:
|
|
33
|
+
schema = dict(spec.schema)
|
|
34
|
+
description = str(schema.pop("description", ""))
|
|
35
|
+
return {"name": spec.name, "description": description, "input_schema": schema}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _messages_json(messages: Sequence[Message]) -> list[dict[str, Any]]:
|
|
39
|
+
out: list[dict[str, Any]] = []
|
|
40
|
+
for message in messages:
|
|
41
|
+
if message.role == "tool":
|
|
42
|
+
block = {
|
|
43
|
+
"type": "tool_result",
|
|
44
|
+
"tool_use_id": message.tool_call_id,
|
|
45
|
+
"content": message.content,
|
|
46
|
+
}
|
|
47
|
+
last = out[-1] if out else None
|
|
48
|
+
if last and last["role"] == "user" and isinstance(last["content"], list):
|
|
49
|
+
last["content"].append(block) # parallel results share one user message
|
|
50
|
+
else:
|
|
51
|
+
out.append({"role": "user", "content": [block]})
|
|
52
|
+
elif message.role == "assistant" and message.tool_calls:
|
|
53
|
+
blocks: list[dict[str, Any]] = []
|
|
54
|
+
if message.content:
|
|
55
|
+
blocks.append({"type": "text", "text": message.content})
|
|
56
|
+
blocks.extend(
|
|
57
|
+
{"type": "tool_use", "id": c.id, "name": c.name, "input": dict(c.args)}
|
|
58
|
+
for c in message.tool_calls
|
|
59
|
+
)
|
|
60
|
+
out.append({"role": "assistant", "content": blocks})
|
|
61
|
+
else:
|
|
62
|
+
out.append({"role": message.role, "content": message.content})
|
|
63
|
+
return out
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
_USAGE_FIELDS = {
|
|
67
|
+
"input": "input_tokens",
|
|
68
|
+
"output": "output_tokens",
|
|
69
|
+
"cache_write": "cache_creation_input_tokens",
|
|
70
|
+
"cache_read": "cache_read_input_tokens",
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _tokens(usage: Any) -> int:
|
|
75
|
+
return sum(int(getattr(usage, field, 0) or 0) for field in _USAGE_FIELDS.values())
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _declared_tools(messages: Sequence[Message]) -> list[dict[str, Any]]:
|
|
79
|
+
"""Bare definitions for tools named in the history, for requests that pass no tool list."""
|
|
80
|
+
names = dict.fromkeys(c.name for m in messages for c in m.tool_calls)
|
|
81
|
+
return [{"name": n, "description": "", "input_schema": {"type": "object"}} for n in names]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class AnthropicLLM:
|
|
85
|
+
def __init__(
|
|
86
|
+
self,
|
|
87
|
+
client: Any,
|
|
88
|
+
model: str,
|
|
89
|
+
budget_tokens: int,
|
|
90
|
+
max_output_tokens: int = 1024,
|
|
91
|
+
budget_usd: float | None = None,
|
|
92
|
+
) -> None:
|
|
93
|
+
if model not in ALLOWED_MODELS:
|
|
94
|
+
raise ValueError(f"model not allowed: {model!r}; allowed: {sorted(ALLOWED_MODELS)}")
|
|
95
|
+
self._client = client
|
|
96
|
+
self._model = model
|
|
97
|
+
self._budget = budget_tokens
|
|
98
|
+
self._max_output = max_output_tokens
|
|
99
|
+
self._budget_usd = budget_usd
|
|
100
|
+
self._usage = {"input": 0, "output": 0, "cache_write": 0, "cache_read": 0}
|
|
101
|
+
self._calls = 0
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def usage(self) -> dict[str, int]:
|
|
105
|
+
"""Tokens by kind, since each kind is priced differently."""
|
|
106
|
+
return dict(self._usage)
|
|
107
|
+
|
|
108
|
+
@property
|
|
109
|
+
def tokens_used(self) -> int:
|
|
110
|
+
return sum(self._usage.values())
|
|
111
|
+
|
|
112
|
+
@property
|
|
113
|
+
def spent_usd(self) -> float:
|
|
114
|
+
return cost_usd(self._usage)
|
|
115
|
+
|
|
116
|
+
@property
|
|
117
|
+
def calls(self) -> int:
|
|
118
|
+
return self._calls
|
|
119
|
+
|
|
120
|
+
async def complete(self, messages: Sequence[Message], tools: Sequence[ToolSpec]) -> Reply:
|
|
121
|
+
tool_json = [_tool_json(spec) for spec in tools] or _declared_tools(messages)
|
|
122
|
+
if tools:
|
|
123
|
+
tool_json[-1]["cache_control"] = {"type": "ephemeral"} # cache the whole tool list
|
|
124
|
+
kwargs: dict[str, Any] = {
|
|
125
|
+
"model": self._model,
|
|
126
|
+
"max_tokens": self._max_output,
|
|
127
|
+
"messages": _messages_json(messages),
|
|
128
|
+
}
|
|
129
|
+
if tool_json:
|
|
130
|
+
kwargs["tools"] = tool_json
|
|
131
|
+
# A rough size (3 characters per token) plus the largest possible reply: refuse a call
|
|
132
|
+
# that could take the spend past the budget, instead of noticing afterwards.
|
|
133
|
+
prompt_estimate = len(json.dumps(kwargs)) // 3
|
|
134
|
+
estimate = prompt_estimate + self._max_output
|
|
135
|
+
if self.tokens_used + estimate > self._budget:
|
|
136
|
+
raise BudgetExceeded(
|
|
137
|
+
f"used {self.tokens_used} of {self._budget} tokens; next call could use {estimate}"
|
|
138
|
+
)
|
|
139
|
+
if self._budget_usd is not None: # priced as if nothing were cached: the safe side
|
|
140
|
+
worst = (
|
|
141
|
+
prompt_estimate * PRICE_PER_MTOK["cache_write"]
|
|
142
|
+
+ self._max_output * PRICE_PER_MTOK["output"]
|
|
143
|
+
) / 1_000_000
|
|
144
|
+
if self.spent_usd + worst > self._budget_usd:
|
|
145
|
+
raise BudgetExceeded(
|
|
146
|
+
f"spent {self.spent_usd:.4f} of {self._budget_usd} USD; "
|
|
147
|
+
f"next call could cost {worst:.4f}"
|
|
148
|
+
)
|
|
149
|
+
response = await self._client.messages.create(**kwargs)
|
|
150
|
+
self._calls += 1
|
|
151
|
+
usage = response.usage
|
|
152
|
+
for kind, field in _USAGE_FIELDS.items():
|
|
153
|
+
self._usage[kind] += int(getattr(usage, field, 0) or 0)
|
|
154
|
+
text = "".join(b.text for b in response.content if b.type == "text")
|
|
155
|
+
calls = tuple(
|
|
156
|
+
ToolCallReq(b.id, b.name, dict(b.input))
|
|
157
|
+
for b in response.content
|
|
158
|
+
if b.type == "tool_use"
|
|
159
|
+
)
|
|
160
|
+
return Reply(text, calls, _tokens(usage))
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Expose AppWorld's APIs as discrete tools.
|
|
2
|
+
|
|
3
|
+
AppWorld agents normally write Python against ``apis.<app>.<api>``. This adapter instead turns
|
|
4
|
+
each documented API (the function-calling docs) into a tool, runs it through ``world.execute`` and
|
|
5
|
+
returns the parsed response, so a tool-calling agent, and agent-jit, can work with it.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import ast
|
|
11
|
+
import json
|
|
12
|
+
from collections.abc import Mapping, Sequence
|
|
13
|
+
from typing import Any, Protocol
|
|
14
|
+
|
|
15
|
+
from agent_jit.ir import Effect, ToolRejected
|
|
16
|
+
from agent_jit.tools import ToolSpec
|
|
17
|
+
|
|
18
|
+
_READ_PREFIXES = ("show_", "search_")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class WorldLike(Protocol):
|
|
22
|
+
def execute(self, code: str) -> str: ...
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def classify_effect(tool_name: str) -> Effect:
|
|
26
|
+
"""``read`` for lookups and login, ``write`` for everything else, including unknown names."""
|
|
27
|
+
api = tool_name.rpartition("__")[2]
|
|
28
|
+
if api == "login" or api.startswith(_READ_PREFIXES):
|
|
29
|
+
return "read"
|
|
30
|
+
return "write"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def specs_from_docs(docs: Sequence[Mapping[str, Any]]) -> tuple[ToolSpec, ...]:
|
|
34
|
+
specs = []
|
|
35
|
+
for doc in docs:
|
|
36
|
+
fn = doc["function"]
|
|
37
|
+
schema = {**fn.get("parameters", {}), "description": fn.get("description", "")}
|
|
38
|
+
specs.append(ToolSpec(fn["name"], schema, classify_effect(fn["name"])))
|
|
39
|
+
return tuple(specs)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
_JSON_SCALARS = (str, bool, int, float, type(None))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _is_json(value: Any, depth: int = 0) -> bool:
|
|
46
|
+
"""True for plain JSON values only: their ``repr`` is a safe literal to embed in code."""
|
|
47
|
+
if depth > 50:
|
|
48
|
+
return False
|
|
49
|
+
if type(value) in _JSON_SCALARS:
|
|
50
|
+
return True
|
|
51
|
+
if type(value) in (list, tuple):
|
|
52
|
+
return all(_is_json(v, depth + 1) for v in value)
|
|
53
|
+
if type(value) is dict:
|
|
54
|
+
return all(type(k) is str and _is_json(v, depth + 1) for k, v in value.items())
|
|
55
|
+
return False
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _parse(output: str) -> Any:
|
|
59
|
+
text = output.strip()
|
|
60
|
+
for parser in (json.loads, ast.literal_eval):
|
|
61
|
+
try:
|
|
62
|
+
parsed = parser(text)
|
|
63
|
+
except (ValueError, SyntaxError, RecursionError, MemoryError):
|
|
64
|
+
continue
|
|
65
|
+
# Plain, shallow JSON only: how deep a parser goes before it gives up depends on the Python
|
|
66
|
+
# version, and a hostile nesting must not reach the trace store as a structure.
|
|
67
|
+
return parsed if _is_json(parsed) else text
|
|
68
|
+
return text
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class AppWorldTools:
|
|
72
|
+
def __init__(self, world: WorldLike, docs: Sequence[Mapping[str, Any]]) -> None:
|
|
73
|
+
self._world = world
|
|
74
|
+
self._specs = {spec.name: spec for spec in specs_from_docs(docs)}
|
|
75
|
+
|
|
76
|
+
def specs(self) -> tuple[ToolSpec, ...]:
|
|
77
|
+
return tuple(self._specs.values())
|
|
78
|
+
|
|
79
|
+
def spec(self, name: str) -> ToolSpec:
|
|
80
|
+
try:
|
|
81
|
+
return self._specs[name]
|
|
82
|
+
except KeyError:
|
|
83
|
+
raise KeyError(f"unknown tool: {name}") from None
|
|
84
|
+
|
|
85
|
+
async def call(self, name: str, args: Mapping[str, Any]) -> Any:
|
|
86
|
+
self.spec(name) # unknown names never reach world.execute
|
|
87
|
+
if not _is_json(dict(args)):
|
|
88
|
+
raise ToolRejected("arguments must be plain JSON values")
|
|
89
|
+
app, _, api = name.partition("__")
|
|
90
|
+
output = self._world.execute(f"print(apis.{app}.{api}(**{dict(args)!r}))")
|
|
91
|
+
if output.startswith("Execution failed"):
|
|
92
|
+
raise ToolRejected(output.strip().splitlines()[-1])
|
|
93
|
+
return _parse(output)
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""A plain tool-calling loop: ask the model, run its tool calls, repeat until it answers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from collections.abc import Sequence
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from agent_jit.ir import Message, ToolRejected
|
|
10
|
+
from agent_jit.tools import LLMClient, ToolCaller
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
async def tool_loop_agent(
|
|
14
|
+
request: str,
|
|
15
|
+
llm: LLMClient,
|
|
16
|
+
tools: ToolCaller,
|
|
17
|
+
history: Sequence[Message],
|
|
18
|
+
max_turns: int = 12,
|
|
19
|
+
) -> str:
|
|
20
|
+
messages = list(history) or [Message("user", request)]
|
|
21
|
+
for _ in range(max_turns):
|
|
22
|
+
reply = await llm.complete(messages, tools.specs())
|
|
23
|
+
if not reply.tool_calls:
|
|
24
|
+
return reply.content
|
|
25
|
+
messages.append(Message("assistant", reply.content, tool_calls=reply.tool_calls))
|
|
26
|
+
for call in reply.tool_calls:
|
|
27
|
+
result: Any
|
|
28
|
+
try:
|
|
29
|
+
result = await tools.call(call.name, call.args)
|
|
30
|
+
except ToolRejected as exc:
|
|
31
|
+
result = {"error": str(exc)}
|
|
32
|
+
except KeyError as exc: # a tool the model invented: tell it, do not abort
|
|
33
|
+
result = {"error": str(exc.args[0]) if exc.args else "unknown tool"}
|
|
34
|
+
messages.append(Message("tool", json.dumps(result, default=str), tool_call_id=call.id))
|
|
35
|
+
raise RuntimeError("agent did not finish")
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""An ``LLMClient`` over a local Ollama server (``/api/chat``), with the server's own token counts.
|
|
2
|
+
|
|
3
|
+
``prompt_eval_count`` counts the prompt tokens Ollama actually evaluated; when it can reuse an
|
|
4
|
+
earlier identical prefix from its cache it reports fewer, so these counts can understate the size of
|
|
5
|
+
a prompt. That affects every system compared the same way.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import json
|
|
12
|
+
import urllib.error
|
|
13
|
+
import urllib.request
|
|
14
|
+
from collections.abc import Callable, Sequence
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from agent_jit.ir import Message, Reply, ToolCallReq
|
|
18
|
+
from agent_jit.tools import ToolSpec
|
|
19
|
+
|
|
20
|
+
HOST = "http://localhost:11434"
|
|
21
|
+
MAX_NEW_TOKENS = 768
|
|
22
|
+
Post = Callable[[dict[str, Any]], dict[str, Any]]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _tool_json(spec: ToolSpec) -> dict[str, Any]:
|
|
26
|
+
schema = dict(spec.schema)
|
|
27
|
+
description = str(schema.pop("description", ""))
|
|
28
|
+
parameters = {"type": "object", "properties": {}, **schema}
|
|
29
|
+
return {
|
|
30
|
+
"type": "function",
|
|
31
|
+
"function": {"name": spec.name, "description": description, "parameters": parameters},
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _messages_json(messages: Sequence[Message]) -> list[dict[str, Any]]:
|
|
36
|
+
names: dict[str, str] = {}
|
|
37
|
+
out: list[dict[str, Any]] = []
|
|
38
|
+
for message in messages:
|
|
39
|
+
if message.role == "tool":
|
|
40
|
+
name = names.get(message.tool_call_id or "", "")
|
|
41
|
+
out.append({"role": "tool", "tool_name": name, "content": message.content})
|
|
42
|
+
elif message.role == "assistant" and message.tool_calls:
|
|
43
|
+
for call in message.tool_calls:
|
|
44
|
+
names[call.id] = call.name
|
|
45
|
+
calls = [
|
|
46
|
+
{"function": {"name": c.name, "arguments": dict(c.args)}}
|
|
47
|
+
for c in message.tool_calls
|
|
48
|
+
]
|
|
49
|
+
out.append({"role": "assistant", "content": message.content, "tool_calls": calls})
|
|
50
|
+
else:
|
|
51
|
+
out.append({"role": message.role, "content": message.content})
|
|
52
|
+
return out
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _default_post(body: dict[str, Any], timeout: float = 600) -> dict[str, Any]:
|
|
56
|
+
def send(payload: dict[str, Any]) -> dict[str, Any]:
|
|
57
|
+
request = urllib.request.Request(
|
|
58
|
+
HOST + "/api/chat", json.dumps(payload).encode(), {"Content-Type": "application/json"}
|
|
59
|
+
)
|
|
60
|
+
with urllib.request.urlopen(request, timeout=timeout) as response: # noqa: S310
|
|
61
|
+
parsed: dict[str, Any] = json.loads(response.read())
|
|
62
|
+
return parsed
|
|
63
|
+
|
|
64
|
+
try:
|
|
65
|
+
return send(body)
|
|
66
|
+
except urllib.error.HTTPError as exc:
|
|
67
|
+
if exc.code != 400 or "think" not in body:
|
|
68
|
+
raise
|
|
69
|
+
return send({k: v for k, v in body.items() if k != "think"}) # no thinking switch
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class OllamaLLM:
|
|
73
|
+
def __init__(
|
|
74
|
+
self,
|
|
75
|
+
model: str,
|
|
76
|
+
num_ctx: int = 8192,
|
|
77
|
+
post: Post | None = None,
|
|
78
|
+
max_new: int = MAX_NEW_TOKENS,
|
|
79
|
+
) -> None:
|
|
80
|
+
self._model = model
|
|
81
|
+
self._num_ctx = num_ctx
|
|
82
|
+
self._max_new = max_new
|
|
83
|
+
self._post: Post = post or _default_post
|
|
84
|
+
self.tokens_used = 0
|
|
85
|
+
self.calls = 0
|
|
86
|
+
|
|
87
|
+
async def complete(self, messages: Sequence[Message], tools: Sequence[ToolSpec]) -> Reply:
|
|
88
|
+
body: dict[str, Any] = {
|
|
89
|
+
"model": self._model,
|
|
90
|
+
"messages": _messages_json(messages),
|
|
91
|
+
"stream": False,
|
|
92
|
+
"think": False,
|
|
93
|
+
"options": {
|
|
94
|
+
"temperature": 0,
|
|
95
|
+
"num_ctx": self._num_ctx,
|
|
96
|
+
"num_predict": self._max_new,
|
|
97
|
+
},
|
|
98
|
+
}
|
|
99
|
+
if tools:
|
|
100
|
+
body["tools"] = [_tool_json(spec) for spec in tools]
|
|
101
|
+
raw = await asyncio.to_thread(self._post, body)
|
|
102
|
+
self.calls += 1
|
|
103
|
+
used = int(raw.get("prompt_eval_count", 0)) + int(raw.get("eval_count", 0))
|
|
104
|
+
self.tokens_used += used
|
|
105
|
+
message = raw["message"]
|
|
106
|
+
calls = []
|
|
107
|
+
for i, call in enumerate(message.get("tool_calls") or []):
|
|
108
|
+
fn = call["function"]
|
|
109
|
+
args = fn.get("arguments") or {}
|
|
110
|
+
if isinstance(args, str):
|
|
111
|
+
args = json.loads(args)
|
|
112
|
+
calls.append(ToolCallReq(f"call_{self.calls}_{i}", fn["name"], dict(args)))
|
|
113
|
+
return Reply(message.get("content", "") or "", tuple(calls), used)
|
agent_jit/branches.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Find the value that tells two families of runs apart, so one skill can branch on it."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping, Sequence
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from agent_jit.guards import MAX_EQUALS_LENGTH, nodes
|
|
10
|
+
from agent_jit.ir import Trace
|
|
11
|
+
from agent_jit.provenance import extract, strict_eq
|
|
12
|
+
|
|
13
|
+
Path = tuple[str | int, ...]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class Discriminator:
|
|
18
|
+
"""``values`` maps a group's tool sequence to the value at ``step``/``path`` selecting it."""
|
|
19
|
+
|
|
20
|
+
step: int
|
|
21
|
+
path: Path
|
|
22
|
+
values: Mapping[tuple[str, ...], str | bool]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _eligible(value: Any) -> bool:
|
|
26
|
+
"""The same kind of value an equality guard can hold: a bool or a short word without digits."""
|
|
27
|
+
if isinstance(value, bool):
|
|
28
|
+
return True
|
|
29
|
+
return (
|
|
30
|
+
isinstance(value, str)
|
|
31
|
+
and 0 < len(value) <= MAX_EQUALS_LENGTH
|
|
32
|
+
and not any(c.isdigit() for c in value)
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def split_index(keys: Sequence[tuple[str, ...]]) -> int | None:
|
|
37
|
+
"""First index where the sequences differ, or None if one is a prefix of another."""
|
|
38
|
+
for i in range(min(len(k) for k in keys)):
|
|
39
|
+
if len({k[i] for k in keys}) > 1:
|
|
40
|
+
return i
|
|
41
|
+
return None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _group_value(group: Sequence[Trace], step: int, path: Path) -> Any:
|
|
45
|
+
"""The one value every trace of ``group`` has at ``path``; raises LookupError if none."""
|
|
46
|
+
values = [extract(t.steps[step].result, path) for t in group]
|
|
47
|
+
if not _eligible(values[0]) or not all(strict_eq(values[0], v) for v in values[1:]):
|
|
48
|
+
raise LookupError("not constant or not eligible")
|
|
49
|
+
return values[0]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def find_discriminator(groups: Sequence[Sequence[Trace]]) -> Discriminator | None:
|
|
53
|
+
"""A prefix-step value that is constant inside each group and different between groups."""
|
|
54
|
+
if len(groups) < 2 or any(not g for g in groups):
|
|
55
|
+
return None
|
|
56
|
+
keys = [tuple(s.tool for s in g[0].steps) for g in groups]
|
|
57
|
+
if len(set(keys)) != len(keys):
|
|
58
|
+
return None
|
|
59
|
+
split = split_index(keys)
|
|
60
|
+
if split is None:
|
|
61
|
+
return None
|
|
62
|
+
found_all: list[Discriminator] = []
|
|
63
|
+
for step in range(split):
|
|
64
|
+
if not all(t.steps[step].ok for g in groups for t in g):
|
|
65
|
+
continue
|
|
66
|
+
for path in nodes(groups[0][0].steps[step].result):
|
|
67
|
+
try:
|
|
68
|
+
found = [_group_value(g, step, path) for g in groups]
|
|
69
|
+
except LookupError:
|
|
70
|
+
continue
|
|
71
|
+
if len({(type(v), v) for v in found}) == len(found):
|
|
72
|
+
found_all.append(Discriminator(step, path, dict(zip(keys, found, strict=True))))
|
|
73
|
+
# Two different values that both separate the groups may be a coincidence: refuse.
|
|
74
|
+
return found_all[0] if len(found_all) == 1 else None
|