railtracks-toolevo 0.1.0__tar.gz
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.
- railtracks_toolevo-0.1.0/LICENSE +21 -0
- railtracks_toolevo-0.1.0/PKG-INFO +158 -0
- railtracks_toolevo-0.1.0/README.md +134 -0
- railtracks_toolevo-0.1.0/pyproject.toml +66 -0
- railtracks_toolevo-0.1.0/pyproject.toml.orig +54 -0
- railtracks_toolevo-0.1.0/src/railtracks_toolevo/__init__.py +4 -0
- railtracks_toolevo-0.1.0/src/railtracks_toolevo/evo.py +276 -0
- railtracks_toolevo-0.1.0/src/railtracks_toolevo/heal.py +199 -0
- railtracks_toolevo-0.1.0/src/railtracks_toolevo/py.typed +0 -0
- railtracks_toolevo-0.1.0/src/railtracks_toolevo/store.py +98 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Guan Zheng Huang
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: railtracks-toolevo
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Tool descriptions that evolve from an agent's own failed calls: a drop-in middleware for Railtracks
|
|
5
|
+
Keywords: railtracks,ai-agents,llm,tool-calling,function-calling,self-improving,prompt-optimization,middleware,mcp
|
|
6
|
+
Author: Guan Zheng Huang
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
16
|
+
Classifier: Typing :: Typed
|
|
17
|
+
Requires-Dist: railtracks>=1.8.1
|
|
18
|
+
Requires-Python: >=3.11
|
|
19
|
+
Project-URL: Homepage, https://github.com/CoronRing/railtracks-toolevo
|
|
20
|
+
Project-URL: Documentation, https://github.com/CoronRing/railtracks-toolevo/blob/main/docs/design.md
|
|
21
|
+
Project-URL: Issues, https://github.com/CoronRing/railtracks-toolevo/issues
|
|
22
|
+
Project-URL: Railtracks, https://github.com/RailtownAI/railtracks
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# railtracks-toolevo: self-healing tool descriptions for AI agents
|
|
26
|
+
|
|
27
|
+
[](https://pypi.org/project/railtracks-toolevo/)
|
|
28
|
+
[](https://www.python.org/)
|
|
29
|
+
[](https://github.com/RailtownAI/railtracks)
|
|
30
|
+
[](https://github.com/CoronRing/railtracks-toolevo/blob/main/LICENSE)
|
|
31
|
+
|
|
32
|
+
**Your agent's tools teach themselves.** `railtracks-toolevo` is a drop-in middleware for [Railtracks](https://github.com/RailtownAI/railtracks) agents. It watches tool calls fail and recover, rewrites the tool's description so the next call gets it right the first time, and keeps a change only if replaying the model's own decisions proves it helps. No tool is ever run twice.
|
|
33
|
+
|
|
34
|
+
> **Tool descriptions are the interface between an LLM and your code.** When a description leaves out a rule the tool enforces (a value format, an allowed list, the order of calls), the agent guesses, fails, reads the error and tries again. Nothing crashes, so nobody fixes it, and you pay for the extra calls on every request. ToolEvo closes that loop automatically.
|
|
35
|
+
|
|
36
|
+
<p align="center">
|
|
37
|
+
<img src="https://raw.githubusercontent.com/CoronRing/railtracks-toolevo/main/docs/images/stool.png" width="30%" alt="Low-poly wooden stool built in Blender by a Railtracks agent">
|
|
38
|
+
<img src="https://raw.githubusercontent.com/CoronRing/railtracks-toolevo/main/docs/images/lamp.png" width="30%" alt="Low-poly desk lamp built in Blender by a Railtracks agent">
|
|
39
|
+
<img src="https://raw.githubusercontent.com/CoronRing/railtracks-toolevo/main/docs/images/mailbox.png" width="30%" alt="Low-poly red mailbox built in Blender by a Railtracks agent">
|
|
40
|
+
</p>
|
|
41
|
+
<p align="center"><sub>Three models built by the <a href="https://github.com/CoronRing/railtracks-toolevo/blob/main/examples/blender_asset/build.py">Blender demo</a>. The first took 9 tool calls with 4 failures; after ToolEvo healed three tool descriptions, the next two took 4 calls with none.</sub></p>
|
|
42
|
+
|
|
43
|
+
## Why ToolEvo
|
|
44
|
+
|
|
45
|
+
- **Drop-in.** One line on your agent: `model_middleware=[evo.middleware]`. No change to your tools.
|
|
46
|
+
- **You choose what can change.** List the tools allowed to evolve; every other tool stays frozen.
|
|
47
|
+
- **Off the hot path.** Healing runs after the answer is returned, on a background thread, so users never wait for it.
|
|
48
|
+
- **Safe by design.** A new description is checked by replaying the model's earlier decisions with it. Only the model is called, so tools that send emails, charge cards or write to databases are never re-executed.
|
|
49
|
+
- **Versioned and reversible.** Every version is saved with a one-line lesson, survives restarts, and can be reverted.
|
|
50
|
+
- **Only text changes.** Tool names, parameter names, types and required fields always come from your code.
|
|
51
|
+
|
|
52
|
+
## Quick start
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
pip install railtracks-toolevo
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
import railtracks as rt
|
|
60
|
+
from railtracks_toolevo import ToolEvo
|
|
61
|
+
|
|
62
|
+
def get_weather(city: str) -> str:
|
|
63
|
+
"""Get the weather.
|
|
64
|
+
|
|
65
|
+
Args:
|
|
66
|
+
city: The city.
|
|
67
|
+
"""
|
|
68
|
+
name, _, country = city.partition(", ")
|
|
69
|
+
if len(country) != 2:
|
|
70
|
+
raise ValueError("Use 'City, CC' with a two-letter country code, e.g. 'Paris, FR'.")
|
|
71
|
+
return f"{name}: 18C, light rain"
|
|
72
|
+
|
|
73
|
+
llm = rt.llm.OpenAILLM("gpt-6-luna")
|
|
74
|
+
evo = ToolEvo(llm, evolve=[get_weather]) # tools not listed stay frozen
|
|
75
|
+
agent = rt.agent_node("Weather", tool_nodes=[rt.function_node(get_weather)], llm=llm, model_middleware=[evo.middleware])
|
|
76
|
+
flow = rt.Flow("weather", entry_point=agent)
|
|
77
|
+
|
|
78
|
+
flow.invoke("Weather in Paris?") # calls "Paris", fails, retries "Paris, FR"; healing runs after the answer
|
|
79
|
+
evo.wait()
|
|
80
|
+
flow.invoke("Weather in Tokyo?") # calls "Tokyo, JP" first time
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
What changed in the description the agent reads:
|
|
84
|
+
|
|
85
|
+
```diff
|
|
86
|
+
get_weather(city)
|
|
87
|
+
- city: The city.
|
|
88
|
+
+ city: The city, formatted as 'City, CC' with a two-letter country code.
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## How it works
|
|
92
|
+
|
|
93
|
+
```mermaid
|
|
94
|
+
flowchart TD
|
|
95
|
+
A[Agent calls a tool] --> B{Failed?}
|
|
96
|
+
B -- no --> Z[Answer returned]
|
|
97
|
+
B -- yes --> C[Agent reads the error and retries] --> Z
|
|
98
|
+
Z -. after the answer .-> D[Healer writes a new description from the failure and the retry that worked]
|
|
99
|
+
D --> E[Replay the model's earlier decisions with the new text]
|
|
100
|
+
E -- now makes the call that worked, breaks nothing --> F[Commit a new version]
|
|
101
|
+
E -- otherwise --> G[Reject]
|
|
102
|
+
F --> H[Next request reads the new description]
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
1. **Serve.** Before every model call, ToolEvo hands the model the live version of each evolvable tool's description and records which calls it makes. Each tool result comes back in the next call's history, so every call is matched to its outcome and to the exact context the model had.
|
|
106
|
+
2. **Propose.** After the answer, a healer model sees each failed call, the error it got, and the call that worked afterwards, and rewrites the description with the missing rule.
|
|
107
|
+
3. **Gate.** The model's earlier decisions are replayed with the new text. A failure counts as fixed when the model now makes the call that later worked. A call that already worked must stay the same (decisions that vary on their own are detected with a control replay and skipped).
|
|
108
|
+
4. **Commit.** Accepted text becomes a new version in `toolevo.json`. `evo.store.revert(tool, version)` undoes it.
|
|
109
|
+
|
|
110
|
+
The method is a practical version of DATE (Dynamic Agentic Tool Evolution): replay the decision, never the execution. The full design and its limits are in [docs/design.md](https://github.com/CoronRing/railtracks-toolevo/blob/main/docs/design.md).
|
|
111
|
+
|
|
112
|
+
## Demos
|
|
113
|
+
|
|
114
|
+
| Demo | What it shows | Result (gpt-6-luna) |
|
|
115
|
+
|---|---|---|
|
|
116
|
+
| [`examples/weather.py`](https://github.com/CoronRing/railtracks-toolevo/blob/main/examples/weather.py) | A weather tool that wants "City, CC" but only says "The city." | 2 calls before healing, 1 after. Healing cost $0.0001. |
|
|
117
|
+
| [`examples/blender_asset/build.py`](https://github.com/CoronRing/railtracks-toolevo/blob/main/examples/blender_asset/build.py) | An agent that builds 3D models in headless Blender. Three asset tools start from one-line descriptions that hide six rules; `run_blender` stays frozen. | Stool: 9 calls, 4 failed. Lamp and mailbox: 4 calls, 0 failed. Total spend under one cent. |
|
|
118
|
+
|
|
119
|
+
```bash
|
|
120
|
+
git clone https://github.com/CoronRing/railtracks-toolevo && cd railtracks-toolevo
|
|
121
|
+
uv run --group demo examples/weather.py
|
|
122
|
+
uv run --group demo examples/blender_asset/build.py # needs Blender on PATH or in $BLENDER
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Set `OPENAI_API_KEY` in your environment or a `.env` file. Models are not deterministic, so your numbers will differ a little.
|
|
126
|
+
|
|
127
|
+
## Options
|
|
128
|
+
|
|
129
|
+
| Argument | Default | Meaning |
|
|
130
|
+
|---|---|---|
|
|
131
|
+
| `evolve` | required | Tools allowed to change: functions, `function_node` results, node classes or names. Every other tool is frozen. |
|
|
132
|
+
| `path` | `toolevo.json` | Where versions are kept. |
|
|
133
|
+
| `healer` | `model` | A different (often stronger) model to write new descriptions. |
|
|
134
|
+
| `failed` | the tool raised | `(tool, result) -> bool`, for tools that fail quietly, such as a search that returns "no matches". |
|
|
135
|
+
| `background` | `True` | Heal on a worker thread after each answer. `False` heals before the answer is returned. |
|
|
136
|
+
| `min_failures` | 1 | New failed calls of a tool needed before a heal is tried. |
|
|
137
|
+
| `max_replays` | 3 | Decisions replayed per check. |
|
|
138
|
+
| `max_chars` | 1200 | Longest description the healer may write. |
|
|
139
|
+
|
|
140
|
+
## FAQ
|
|
141
|
+
|
|
142
|
+
**Why does my agent keep calling a tool wrong?** Usually because the description leaves out a rule the tool enforces. The model can't follow a rule it was never told, so it learns it from the error message on every request. ToolEvo writes that rule into the description once.
|
|
143
|
+
|
|
144
|
+
**Does it work with MCP tools and agents used as tools?** It is designed to: ToolEvo works on the description the model reads, matched by tool name, not on the tool's code, so any tool a Railtracks agent can call can be listed in `evolve` by name. The demos so far use function tools.
|
|
145
|
+
|
|
146
|
+
**Does it re-run my tools to test a fix?** No. It only replays the model's decision (which call it would make) and compares that with calls whose outcomes are already known.
|
|
147
|
+
|
|
148
|
+
**What does it cost?** One healer call per heal, plus a few replayed model calls. In the demos that was a fraction of a cent.
|
|
149
|
+
|
|
150
|
+
**Which providers does it support?** It uses Railtracks' own model interface, so any model Railtracks supports (OpenAI, Anthropic, Gemini, Ollama, OpenAI-compatible endpoints) should work. The healer needs structured output. The demos use OpenAI.
|
|
151
|
+
|
|
152
|
+
## Status
|
|
153
|
+
|
|
154
|
+
Version 0.1, an add-on outside the core Railtracks framework. Known limits: the check is designed for small samples (DATE's full statistical test needs more traffic), and evidence is kept in memory, so it does not carry across restarts. Committed descriptions do. Issues and pull requests are welcome.
|
|
155
|
+
|
|
156
|
+
## License
|
|
157
|
+
|
|
158
|
+
[MIT](https://github.com/CoronRing/railtracks-toolevo/blob/main/LICENSE)
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
# railtracks-toolevo: self-healing tool descriptions for AI agents
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/railtracks-toolevo/)
|
|
4
|
+
[](https://www.python.org/)
|
|
5
|
+
[](https://github.com/RailtownAI/railtracks)
|
|
6
|
+
[](https://github.com/CoronRing/railtracks-toolevo/blob/main/LICENSE)
|
|
7
|
+
|
|
8
|
+
**Your agent's tools teach themselves.** `railtracks-toolevo` is a drop-in middleware for [Railtracks](https://github.com/RailtownAI/railtracks) agents. It watches tool calls fail and recover, rewrites the tool's description so the next call gets it right the first time, and keeps a change only if replaying the model's own decisions proves it helps. No tool is ever run twice.
|
|
9
|
+
|
|
10
|
+
> **Tool descriptions are the interface between an LLM and your code.** When a description leaves out a rule the tool enforces (a value format, an allowed list, the order of calls), the agent guesses, fails, reads the error and tries again. Nothing crashes, so nobody fixes it, and you pay for the extra calls on every request. ToolEvo closes that loop automatically.
|
|
11
|
+
|
|
12
|
+
<p align="center">
|
|
13
|
+
<img src="https://raw.githubusercontent.com/CoronRing/railtracks-toolevo/main/docs/images/stool.png" width="30%" alt="Low-poly wooden stool built in Blender by a Railtracks agent">
|
|
14
|
+
<img src="https://raw.githubusercontent.com/CoronRing/railtracks-toolevo/main/docs/images/lamp.png" width="30%" alt="Low-poly desk lamp built in Blender by a Railtracks agent">
|
|
15
|
+
<img src="https://raw.githubusercontent.com/CoronRing/railtracks-toolevo/main/docs/images/mailbox.png" width="30%" alt="Low-poly red mailbox built in Blender by a Railtracks agent">
|
|
16
|
+
</p>
|
|
17
|
+
<p align="center"><sub>Three models built by the <a href="https://github.com/CoronRing/railtracks-toolevo/blob/main/examples/blender_asset/build.py">Blender demo</a>. The first took 9 tool calls with 4 failures; after ToolEvo healed three tool descriptions, the next two took 4 calls with none.</sub></p>
|
|
18
|
+
|
|
19
|
+
## Why ToolEvo
|
|
20
|
+
|
|
21
|
+
- **Drop-in.** One line on your agent: `model_middleware=[evo.middleware]`. No change to your tools.
|
|
22
|
+
- **You choose what can change.** List the tools allowed to evolve; every other tool stays frozen.
|
|
23
|
+
- **Off the hot path.** Healing runs after the answer is returned, on a background thread, so users never wait for it.
|
|
24
|
+
- **Safe by design.** A new description is checked by replaying the model's earlier decisions with it. Only the model is called, so tools that send emails, charge cards or write to databases are never re-executed.
|
|
25
|
+
- **Versioned and reversible.** Every version is saved with a one-line lesson, survives restarts, and can be reverted.
|
|
26
|
+
- **Only text changes.** Tool names, parameter names, types and required fields always come from your code.
|
|
27
|
+
|
|
28
|
+
## Quick start
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install railtracks-toolevo
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
import railtracks as rt
|
|
36
|
+
from railtracks_toolevo import ToolEvo
|
|
37
|
+
|
|
38
|
+
def get_weather(city: str) -> str:
|
|
39
|
+
"""Get the weather.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
city: The city.
|
|
43
|
+
"""
|
|
44
|
+
name, _, country = city.partition(", ")
|
|
45
|
+
if len(country) != 2:
|
|
46
|
+
raise ValueError("Use 'City, CC' with a two-letter country code, e.g. 'Paris, FR'.")
|
|
47
|
+
return f"{name}: 18C, light rain"
|
|
48
|
+
|
|
49
|
+
llm = rt.llm.OpenAILLM("gpt-6-luna")
|
|
50
|
+
evo = ToolEvo(llm, evolve=[get_weather]) # tools not listed stay frozen
|
|
51
|
+
agent = rt.agent_node("Weather", tool_nodes=[rt.function_node(get_weather)], llm=llm, model_middleware=[evo.middleware])
|
|
52
|
+
flow = rt.Flow("weather", entry_point=agent)
|
|
53
|
+
|
|
54
|
+
flow.invoke("Weather in Paris?") # calls "Paris", fails, retries "Paris, FR"; healing runs after the answer
|
|
55
|
+
evo.wait()
|
|
56
|
+
flow.invoke("Weather in Tokyo?") # calls "Tokyo, JP" first time
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
What changed in the description the agent reads:
|
|
60
|
+
|
|
61
|
+
```diff
|
|
62
|
+
get_weather(city)
|
|
63
|
+
- city: The city.
|
|
64
|
+
+ city: The city, formatted as 'City, CC' with a two-letter country code.
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## How it works
|
|
68
|
+
|
|
69
|
+
```mermaid
|
|
70
|
+
flowchart TD
|
|
71
|
+
A[Agent calls a tool] --> B{Failed?}
|
|
72
|
+
B -- no --> Z[Answer returned]
|
|
73
|
+
B -- yes --> C[Agent reads the error and retries] --> Z
|
|
74
|
+
Z -. after the answer .-> D[Healer writes a new description from the failure and the retry that worked]
|
|
75
|
+
D --> E[Replay the model's earlier decisions with the new text]
|
|
76
|
+
E -- now makes the call that worked, breaks nothing --> F[Commit a new version]
|
|
77
|
+
E -- otherwise --> G[Reject]
|
|
78
|
+
F --> H[Next request reads the new description]
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
1. **Serve.** Before every model call, ToolEvo hands the model the live version of each evolvable tool's description and records which calls it makes. Each tool result comes back in the next call's history, so every call is matched to its outcome and to the exact context the model had.
|
|
82
|
+
2. **Propose.** After the answer, a healer model sees each failed call, the error it got, and the call that worked afterwards, and rewrites the description with the missing rule.
|
|
83
|
+
3. **Gate.** The model's earlier decisions are replayed with the new text. A failure counts as fixed when the model now makes the call that later worked. A call that already worked must stay the same (decisions that vary on their own are detected with a control replay and skipped).
|
|
84
|
+
4. **Commit.** Accepted text becomes a new version in `toolevo.json`. `evo.store.revert(tool, version)` undoes it.
|
|
85
|
+
|
|
86
|
+
The method is a practical version of DATE (Dynamic Agentic Tool Evolution): replay the decision, never the execution. The full design and its limits are in [docs/design.md](https://github.com/CoronRing/railtracks-toolevo/blob/main/docs/design.md).
|
|
87
|
+
|
|
88
|
+
## Demos
|
|
89
|
+
|
|
90
|
+
| Demo | What it shows | Result (gpt-6-luna) |
|
|
91
|
+
|---|---|---|
|
|
92
|
+
| [`examples/weather.py`](https://github.com/CoronRing/railtracks-toolevo/blob/main/examples/weather.py) | A weather tool that wants "City, CC" but only says "The city." | 2 calls before healing, 1 after. Healing cost $0.0001. |
|
|
93
|
+
| [`examples/blender_asset/build.py`](https://github.com/CoronRing/railtracks-toolevo/blob/main/examples/blender_asset/build.py) | An agent that builds 3D models in headless Blender. Three asset tools start from one-line descriptions that hide six rules; `run_blender` stays frozen. | Stool: 9 calls, 4 failed. Lamp and mailbox: 4 calls, 0 failed. Total spend under one cent. |
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
git clone https://github.com/CoronRing/railtracks-toolevo && cd railtracks-toolevo
|
|
97
|
+
uv run --group demo examples/weather.py
|
|
98
|
+
uv run --group demo examples/blender_asset/build.py # needs Blender on PATH or in $BLENDER
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Set `OPENAI_API_KEY` in your environment or a `.env` file. Models are not deterministic, so your numbers will differ a little.
|
|
102
|
+
|
|
103
|
+
## Options
|
|
104
|
+
|
|
105
|
+
| Argument | Default | Meaning |
|
|
106
|
+
|---|---|---|
|
|
107
|
+
| `evolve` | required | Tools allowed to change: functions, `function_node` results, node classes or names. Every other tool is frozen. |
|
|
108
|
+
| `path` | `toolevo.json` | Where versions are kept. |
|
|
109
|
+
| `healer` | `model` | A different (often stronger) model to write new descriptions. |
|
|
110
|
+
| `failed` | the tool raised | `(tool, result) -> bool`, for tools that fail quietly, such as a search that returns "no matches". |
|
|
111
|
+
| `background` | `True` | Heal on a worker thread after each answer. `False` heals before the answer is returned. |
|
|
112
|
+
| `min_failures` | 1 | New failed calls of a tool needed before a heal is tried. |
|
|
113
|
+
| `max_replays` | 3 | Decisions replayed per check. |
|
|
114
|
+
| `max_chars` | 1200 | Longest description the healer may write. |
|
|
115
|
+
|
|
116
|
+
## FAQ
|
|
117
|
+
|
|
118
|
+
**Why does my agent keep calling a tool wrong?** Usually because the description leaves out a rule the tool enforces. The model can't follow a rule it was never told, so it learns it from the error message on every request. ToolEvo writes that rule into the description once.
|
|
119
|
+
|
|
120
|
+
**Does it work with MCP tools and agents used as tools?** It is designed to: ToolEvo works on the description the model reads, matched by tool name, not on the tool's code, so any tool a Railtracks agent can call can be listed in `evolve` by name. The demos so far use function tools.
|
|
121
|
+
|
|
122
|
+
**Does it re-run my tools to test a fix?** No. It only replays the model's decision (which call it would make) and compares that with calls whose outcomes are already known.
|
|
123
|
+
|
|
124
|
+
**What does it cost?** One healer call per heal, plus a few replayed model calls. In the demos that was a fraction of a cent.
|
|
125
|
+
|
|
126
|
+
**Which providers does it support?** It uses Railtracks' own model interface, so any model Railtracks supports (OpenAI, Anthropic, Gemini, Ollama, OpenAI-compatible endpoints) should work. The healer needs structured output. The demos use OpenAI.
|
|
127
|
+
|
|
128
|
+
## Status
|
|
129
|
+
|
|
130
|
+
Version 0.1, an add-on outside the core Railtracks framework. Known limits: the check is designed for small samples (DATE's full statistical test needs more traffic), and evidence is kept in memory, so it does not carry across restarts. Committed descriptions do. Issues and pull requests are welcome.
|
|
131
|
+
|
|
132
|
+
## License
|
|
133
|
+
|
|
134
|
+
[MIT](https://github.com/CoronRing/railtracks-toolevo/blob/main/LICENSE)
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "railtracks-toolevo"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Tool descriptions that evolve from an agent's own failed calls: a drop-in middleware for Railtracks"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
requires-python = ">=3.11"
|
|
9
|
+
keywords = [
|
|
10
|
+
"railtracks",
|
|
11
|
+
"ai-agents",
|
|
12
|
+
"llm",
|
|
13
|
+
"tool-calling",
|
|
14
|
+
"function-calling",
|
|
15
|
+
"self-improving",
|
|
16
|
+
"prompt-optimization",
|
|
17
|
+
"middleware",
|
|
18
|
+
"mcp",
|
|
19
|
+
]
|
|
20
|
+
classifiers = [
|
|
21
|
+
"Development Status :: 3 - Alpha",
|
|
22
|
+
"Intended Audience :: Developers",
|
|
23
|
+
"Programming Language :: Python :: 3",
|
|
24
|
+
"Programming Language :: Python :: 3.11",
|
|
25
|
+
"Programming Language :: Python :: 3.12",
|
|
26
|
+
"Programming Language :: Python :: 3.13",
|
|
27
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
28
|
+
"Typing :: Typed",
|
|
29
|
+
]
|
|
30
|
+
dependencies = ["railtracks>=1.8.1"]
|
|
31
|
+
|
|
32
|
+
[[project.authors]]
|
|
33
|
+
name = "Guan Zheng Huang"
|
|
34
|
+
|
|
35
|
+
[project.urls]
|
|
36
|
+
Homepage = "https://github.com/CoronRing/railtracks-toolevo"
|
|
37
|
+
Documentation = "https://github.com/CoronRing/railtracks-toolevo/blob/main/docs/design.md"
|
|
38
|
+
Issues = "https://github.com/CoronRing/railtracks-toolevo/issues"
|
|
39
|
+
Railtracks = "https://github.com/RailtownAI/railtracks"
|
|
40
|
+
|
|
41
|
+
[build-system]
|
|
42
|
+
requires = ["uv_build>=0.13.5,<0.14.0"]
|
|
43
|
+
build-backend = "uv_build"
|
|
44
|
+
|
|
45
|
+
[dependency-groups]
|
|
46
|
+
demo = ["python-dotenv>=1.2.4"]
|
|
47
|
+
dev = [
|
|
48
|
+
"pytest>=9.2.0",
|
|
49
|
+
"pytest-asyncio>=1.5.0",
|
|
50
|
+
"ruff>=0.17.6",
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
[tool.ruff]
|
|
54
|
+
line-length = 120
|
|
55
|
+
extend-exclude = ["README.md"]
|
|
56
|
+
|
|
57
|
+
[tool.ruff.lint]
|
|
58
|
+
extend-select = [
|
|
59
|
+
"I",
|
|
60
|
+
"UP",
|
|
61
|
+
"B",
|
|
62
|
+
]
|
|
63
|
+
|
|
64
|
+
[tool.pytest.ini_options]
|
|
65
|
+
asyncio_mode = "auto"
|
|
66
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "railtracks-toolevo"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Tool descriptions that evolve from an agent's own failed calls: a drop-in middleware for Railtracks"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
authors = [{ name = "Guan Zheng Huang" }]
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
requires-python = ">=3.11"
|
|
10
|
+
keywords = ["railtracks", "ai-agents", "llm", "tool-calling", "function-calling", "self-improving", "prompt-optimization", "middleware", "mcp"]
|
|
11
|
+
classifiers = [
|
|
12
|
+
"Development Status :: 3 - Alpha",
|
|
13
|
+
"Intended Audience :: Developers",
|
|
14
|
+
"Programming Language :: Python :: 3",
|
|
15
|
+
"Programming Language :: Python :: 3.11",
|
|
16
|
+
"Programming Language :: Python :: 3.12",
|
|
17
|
+
"Programming Language :: Python :: 3.13",
|
|
18
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
19
|
+
"Typing :: Typed",
|
|
20
|
+
]
|
|
21
|
+
dependencies = [
|
|
22
|
+
"railtracks>=1.8.1",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
[project.urls]
|
|
26
|
+
Homepage = "https://github.com/CoronRing/railtracks-toolevo"
|
|
27
|
+
Documentation = "https://github.com/CoronRing/railtracks-toolevo/blob/main/docs/design.md"
|
|
28
|
+
Issues = "https://github.com/CoronRing/railtracks-toolevo/issues"
|
|
29
|
+
Railtracks = "https://github.com/RailtownAI/railtracks"
|
|
30
|
+
|
|
31
|
+
[build-system]
|
|
32
|
+
requires = ["uv_build>=0.13.5,<0.14.0"]
|
|
33
|
+
build-backend = "uv_build"
|
|
34
|
+
|
|
35
|
+
[dependency-groups]
|
|
36
|
+
demo = [
|
|
37
|
+
"python-dotenv>=1.2.4",
|
|
38
|
+
]
|
|
39
|
+
dev = [
|
|
40
|
+
"pytest>=9.2.0",
|
|
41
|
+
"pytest-asyncio>=1.5.0",
|
|
42
|
+
"ruff>=0.17.6",
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
[tool.ruff]
|
|
46
|
+
line-length = 120
|
|
47
|
+
extend-exclude = ["README.md"]
|
|
48
|
+
|
|
49
|
+
[tool.ruff.lint]
|
|
50
|
+
extend-select = ["I", "UP", "B"]
|
|
51
|
+
|
|
52
|
+
[tool.pytest.ini_options]
|
|
53
|
+
asyncio_mode = "auto"
|
|
54
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
"""`ToolEvo`: a model middleware that serves evolved tool texts, logs each tool call's outcome, and heals afterwards.
|
|
2
|
+
|
|
3
|
+
It sits on the agent's model call rather than on each tool, because that is the only place that both decides what
|
|
4
|
+
the model reads and sees every call with its outcome: each tool result comes back in the next call's history, keyed
|
|
5
|
+
by the call's id. See docs/design.md.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import atexit
|
|
12
|
+
import logging
|
|
13
|
+
import threading
|
|
14
|
+
from collections.abc import Awaitable, Callable, Iterable
|
|
15
|
+
from concurrent.futures import Future, ThreadPoolExecutor
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from pydantic import BaseModel
|
|
20
|
+
from railtracks import wrap_llm
|
|
21
|
+
from railtracks.llm import MessageHistory, ModelBase, Tool, ToolMessage
|
|
22
|
+
from railtracks.llm.middleware import ModelMiddleware
|
|
23
|
+
from railtracks.llm.response import Response
|
|
24
|
+
|
|
25
|
+
from . import heal
|
|
26
|
+
from .heal import Call, Decision
|
|
27
|
+
from .store import SpecStore
|
|
28
|
+
|
|
29
|
+
logger = logging.getLogger("railtracks_toolevo")
|
|
30
|
+
|
|
31
|
+
ERROR_PREFIX = "There was an error during tool execution"
|
|
32
|
+
KEEP_DECISIONS = 500
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def raised(tool: str, result: str) -> bool:
|
|
36
|
+
"""The default failure test: the tool raised an exception."""
|
|
37
|
+
return result.startswith(ERROR_PREFIX)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class HealEvent:
|
|
42
|
+
"""One healing attempt for one tool."""
|
|
43
|
+
|
|
44
|
+
tool: str
|
|
45
|
+
lesson: str
|
|
46
|
+
verdict: heal.Verdict
|
|
47
|
+
version: int | None
|
|
48
|
+
cost_usd: float
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class ToolEvo:
|
|
52
|
+
"""Evolves the descriptions of chosen tools from the agent's own failed calls.
|
|
53
|
+
|
|
54
|
+
Attach `middleware` to an agent with `model_middleware=[evo.middleware]`. Tools not listed in `evolve` are frozen:
|
|
55
|
+
their text is never changed, though the agent still sees them during replays.
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
model: The model the agent uses; replays must use the same one.
|
|
59
|
+
evolve: The tools allowed to change, as functions, `function_node` results, node classes or names.
|
|
60
|
+
path: The JSON file that keeps each tool's versions; evolved texts survive restarts.
|
|
61
|
+
healer: The model that writes new texts; defaults to `model`.
|
|
62
|
+
failed: Decides from a tool's name and result text whether a call failed; defaults to "the tool raised".
|
|
63
|
+
background: Heal on a worker thread after each answer, so the answer is never delayed; False heals
|
|
64
|
+
before the answer is returned.
|
|
65
|
+
min_failures: New failed calls of a tool needed before a heal is tried.
|
|
66
|
+
max_replays: Decisions replayed per pool (failed, worked) when gating a candidate.
|
|
67
|
+
max_chars: Longest description the healer may write.
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
def __init__(
|
|
71
|
+
self,
|
|
72
|
+
model: ModelBase,
|
|
73
|
+
evolve: Iterable[object],
|
|
74
|
+
path: Path | str = "toolevo.json",
|
|
75
|
+
*,
|
|
76
|
+
healer: ModelBase | None = None,
|
|
77
|
+
failed: Callable[[str, str], bool] = raised,
|
|
78
|
+
background: bool = True,
|
|
79
|
+
min_failures: int = 1,
|
|
80
|
+
max_replays: int = 3,
|
|
81
|
+
max_chars: int = 1200,
|
|
82
|
+
) -> None:
|
|
83
|
+
self.store = SpecStore(path)
|
|
84
|
+
self.events: list[HealEvent] = []
|
|
85
|
+
self.calls: list[Call] = []
|
|
86
|
+
self._model = model
|
|
87
|
+
self._healer = healer or model
|
|
88
|
+
self._evolve = {_tool_name(t) for t in evolve}
|
|
89
|
+
self._failed = failed
|
|
90
|
+
self._background = background
|
|
91
|
+
self._min_failures = min_failures
|
|
92
|
+
self._max_replays = max_replays
|
|
93
|
+
self._max_chars = max_chars
|
|
94
|
+
self._lock = threading.Lock()
|
|
95
|
+
self._open: dict[str, Call] = {}
|
|
96
|
+
self._decisions: list[Decision] = []
|
|
97
|
+
self._used: set[str] = set()
|
|
98
|
+
self._seeded: set[str] = set()
|
|
99
|
+
self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="toolevo")
|
|
100
|
+
self._futures: list[Future[None]] = []
|
|
101
|
+
self.middleware: ModelMiddleware = wrap_llm(self._wrap, name="ToolEvo")
|
|
102
|
+
atexit.register(self.wait)
|
|
103
|
+
|
|
104
|
+
@property
|
|
105
|
+
def spend_usd(self) -> float:
|
|
106
|
+
"""Model spend on healing so far (proposals and replays)."""
|
|
107
|
+
return sum(e.cost_usd for e in self.events)
|
|
108
|
+
|
|
109
|
+
def wait(self) -> None:
|
|
110
|
+
"""Block until every scheduled heal has finished."""
|
|
111
|
+
while self._futures:
|
|
112
|
+
self._futures.pop(0).result()
|
|
113
|
+
|
|
114
|
+
async def _wrap(
|
|
115
|
+
self,
|
|
116
|
+
llm_call: Callable[
|
|
117
|
+
[MessageHistory, type[BaseModel] | None, list[Tool] | None],
|
|
118
|
+
Awaitable[Response],
|
|
119
|
+
],
|
|
120
|
+
history: MessageHistory,
|
|
121
|
+
schema: type[BaseModel] | None,
|
|
122
|
+
tools: list[Tool] | None,
|
|
123
|
+
) -> Response:
|
|
124
|
+
earlier = self._settle(history)
|
|
125
|
+
served = [self._serve(t) for t in tools] if tools else tools
|
|
126
|
+
response = await llm_call(history, schema, served)
|
|
127
|
+
emitted = response.message.tool_calls
|
|
128
|
+
if emitted and served:
|
|
129
|
+
calls = [Call(c.identifier, c.name, dict(c.arguments)) for c in emitted]
|
|
130
|
+
with self._lock:
|
|
131
|
+
self._open.update((c.id, c) for c in calls)
|
|
132
|
+
self._decisions.append(Decision(MessageHistory(list(history)), list(served), calls, earlier))
|
|
133
|
+
del self._decisions[:-KEEP_DECISIONS]
|
|
134
|
+
elif tools:
|
|
135
|
+
await self._schedule()
|
|
136
|
+
return response
|
|
137
|
+
|
|
138
|
+
def _settle(self, history: MessageHistory) -> set[str]:
|
|
139
|
+
"""Fill in the outcome of every logged call answered in `history`; return the ids of calls it contains."""
|
|
140
|
+
seen: set[str] = set()
|
|
141
|
+
for message in history:
|
|
142
|
+
if not isinstance(message, ToolMessage):
|
|
143
|
+
continue
|
|
144
|
+
answer = message.content
|
|
145
|
+
seen.add(answer.identifier)
|
|
146
|
+
with self._lock:
|
|
147
|
+
call = self._open.pop(answer.identifier, None)
|
|
148
|
+
if call is None:
|
|
149
|
+
continue
|
|
150
|
+
call.result = str(answer.result)
|
|
151
|
+
call.failed = self._failed(call.tool, call.result)
|
|
152
|
+
self.calls.append(call)
|
|
153
|
+
return seen
|
|
154
|
+
|
|
155
|
+
def _serve(self, tool: Tool) -> Tool:
|
|
156
|
+
if tool.name not in self._evolve:
|
|
157
|
+
return tool
|
|
158
|
+
if tool.name not in self._seeded:
|
|
159
|
+
if self.store.seed(tool.name, heal.text_of(tool)):
|
|
160
|
+
logger.warning(
|
|
161
|
+
"%s: the text in code changed, so its evolved versions were dropped",
|
|
162
|
+
tool.name,
|
|
163
|
+
)
|
|
164
|
+
self._seeded.add(tool.name)
|
|
165
|
+
text = self.store.current(tool.name)
|
|
166
|
+
return heal.with_text(tool, text) if text else tool
|
|
167
|
+
|
|
168
|
+
async def _schedule(self) -> None:
|
|
169
|
+
if self._background:
|
|
170
|
+
self._futures = [f for f in self._futures if not f.done()]
|
|
171
|
+
self._futures.append(self._executor.submit(self._heal_all))
|
|
172
|
+
else:
|
|
173
|
+
await asyncio.to_thread(self._heal_all)
|
|
174
|
+
|
|
175
|
+
def _heal_all(self) -> None:
|
|
176
|
+
for tool in sorted(self._evolve):
|
|
177
|
+
try:
|
|
178
|
+
self._heal(tool)
|
|
179
|
+
except Exception:
|
|
180
|
+
logger.exception("%s: healing failed", tool)
|
|
181
|
+
|
|
182
|
+
def _heal(self, tool: str) -> None:
|
|
183
|
+
with self._lock:
|
|
184
|
+
decisions = [d for d in self._decisions if all(c.failed is not None for c in d.calls)]
|
|
185
|
+
_link_recoveries(decisions)
|
|
186
|
+
failed = [(d, c) for d in decisions for c in d.calls if c.tool == tool and c.failed and c.id not in self._used]
|
|
187
|
+
if len(failed) < self._min_failures:
|
|
188
|
+
return
|
|
189
|
+
good = [
|
|
190
|
+
(d, c)
|
|
191
|
+
for d in decisions
|
|
192
|
+
for c in d.calls
|
|
193
|
+
if c.tool == tool and not c.failed and not any(f.id in d.earlier for _, f in failed)
|
|
194
|
+
][-self._max_replays :]
|
|
195
|
+
served = next((t for d in reversed(decisions) for t in d.tools if t.name == tool), None)
|
|
196
|
+
text = self.store.current(tool)
|
|
197
|
+
if served is None or text is None:
|
|
198
|
+
return
|
|
199
|
+
live = heal.with_text(served, text)
|
|
200
|
+
shown, held = _split([x for x in failed if x[1].recovery], self._max_replays)
|
|
201
|
+
if not held:
|
|
202
|
+
return
|
|
203
|
+
shown += [x for x in failed if not x[1].recovery]
|
|
204
|
+
self._used.update(c.id for _, c in failed)
|
|
205
|
+
proposal = heal.propose(
|
|
206
|
+
self._healer,
|
|
207
|
+
live,
|
|
208
|
+
[c for _, c in shown],
|
|
209
|
+
[c for _, c in good],
|
|
210
|
+
self._max_chars,
|
|
211
|
+
)
|
|
212
|
+
if proposal is None:
|
|
213
|
+
logger.info("%s: the healer proposed no usable change", tool)
|
|
214
|
+
return
|
|
215
|
+
candidate, lesson, cost = proposal
|
|
216
|
+
verdict = heal.gate(self._model, tool, candidate, held, good)
|
|
217
|
+
version = self.store.commit(tool, candidate, lesson)["version"] if verdict.accepted else None
|
|
218
|
+
self.events.append(HealEvent(tool, lesson, verdict, version, cost + verdict.cost_usd))
|
|
219
|
+
logger.info(
|
|
220
|
+
"%s: %s v%s, fixed %g/%d, broke %d/%d (%d unstable): %s",
|
|
221
|
+
tool,
|
|
222
|
+
"committed" if version is not None else "rejected",
|
|
223
|
+
version if version is not None else "-",
|
|
224
|
+
verdict.fixes,
|
|
225
|
+
verdict.tried_fixes,
|
|
226
|
+
verdict.breaks,
|
|
227
|
+
verdict.tried_breaks,
|
|
228
|
+
verdict.unstable,
|
|
229
|
+
lesson,
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _link_recoveries(decisions: list[Decision]) -> None:
|
|
234
|
+
"""Point each failed call at the first later call of the same tool, in the same conversation, that worked."""
|
|
235
|
+
for i, decision in enumerate(decisions):
|
|
236
|
+
for call in decision.calls:
|
|
237
|
+
if not call.failed or call.recovery:
|
|
238
|
+
continue
|
|
239
|
+
call.recovery = next(
|
|
240
|
+
(
|
|
241
|
+
c
|
|
242
|
+
for later in decisions[i + 1 :]
|
|
243
|
+
if call.id in later.earlier
|
|
244
|
+
for c in later.calls
|
|
245
|
+
if c.tool == call.tool and c.failed is False
|
|
246
|
+
),
|
|
247
|
+
None,
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _split(
|
|
252
|
+
recovered: list[tuple[Decision, Call]], max_replays: int
|
|
253
|
+
) -> tuple[list[tuple[Decision, Call]], list[tuple[Decision, Call]]]:
|
|
254
|
+
"""Failures shown to the healer and failures held out for the gate.
|
|
255
|
+
|
|
256
|
+
With four or more, the newer half is held out so a text is never scored on the calls it was written from; with
|
|
257
|
+
fewer, the same calls serve both (see docs/design.md, Known limits).
|
|
258
|
+
"""
|
|
259
|
+
if len(recovered) >= 4:
|
|
260
|
+
half = len(recovered) // 2
|
|
261
|
+
return recovered[:half], recovered[half:][:max_replays]
|
|
262
|
+
return list(recovered), recovered[-max_replays:]
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _tool_name(tool: object) -> str:
|
|
266
|
+
if isinstance(tool, str):
|
|
267
|
+
return tool
|
|
268
|
+
info = getattr(tool, "tool_info", None) or getattr(getattr(tool, "node_type", None), "tool_info", None)
|
|
269
|
+
if callable(info):
|
|
270
|
+
result = info()
|
|
271
|
+
if isinstance(result, Tool):
|
|
272
|
+
return result.name
|
|
273
|
+
name = getattr(tool, "__name__", None)
|
|
274
|
+
if not isinstance(name, str):
|
|
275
|
+
raise TypeError(f"cannot tell the tool name of {tool!r}")
|
|
276
|
+
return name
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""Proposing a new tool text from logged calls, and gating it by replaying the model's decisions.
|
|
2
|
+
|
|
3
|
+
The gate follows DATE: a text change can only change which call the model emits, so only the decision is replayed
|
|
4
|
+
and no tool runs. Each replayed failure scores like a DATE flip: 1 when the decision now emits the call that later
|
|
5
|
+
worked in the same conversation, 0.5 when it no longer emits the failed call but its new call is unverified, 0 when
|
|
6
|
+
it repeats the failure. A call that worked first time is broken when the replayed decision no longer emits it; a
|
|
7
|
+
decision that already varies when replayed with the live text is unstable and is not counted.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import copy
|
|
13
|
+
import json
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
|
|
16
|
+
from pydantic import BaseModel
|
|
17
|
+
from railtracks.llm import MessageHistory, ModelBase, SystemMessage, Tool, UserMessage
|
|
18
|
+
|
|
19
|
+
from .store import ToolText
|
|
20
|
+
|
|
21
|
+
INSTRUCTIONS = """You maintain the description of one tool that an AI agent reads before calling it. The agent's calls to this tool failed, and you see the evidence: each failed call with the error it got, the call that worked afterwards when there was one, and some calls that worked first time.
|
|
22
|
+
|
|
23
|
+
Rewrite the description so a fresh agent reading it would make the working call on its first try.
|
|
24
|
+
|
|
25
|
+
Rules:
|
|
26
|
+
- Keep what the description already says unless the evidence shows it is wrong. Add the missing convention concisely, as short imperative lines.
|
|
27
|
+
- State only facts the evidence supports: formats, units, allowed values, required order of calls. Never guess.
|
|
28
|
+
- Stay general: no mention of the specific request (no city, object or user named in the evidence), no copied results.
|
|
29
|
+
- Rewrite a parameter's description only when its value convention caused the failure. Return every parameter in `params`.
|
|
30
|
+
- `lesson` is one plain line, at most 12 words, saying what was learned.
|
|
31
|
+
- The description must stay under {max_chars} characters."""
|
|
32
|
+
|
|
33
|
+
RESULT_CHARS = 400
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class ParamText(BaseModel):
|
|
37
|
+
"""A parameter description in the healer's answer."""
|
|
38
|
+
|
|
39
|
+
name: str
|
|
40
|
+
description: str
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Patch(BaseModel):
|
|
44
|
+
"""The healer's answer."""
|
|
45
|
+
|
|
46
|
+
description: str
|
|
47
|
+
params: list[ParamText]
|
|
48
|
+
lesson: str
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class Call:
|
|
53
|
+
"""One tool call the model emitted, and its outcome once the tool answered."""
|
|
54
|
+
|
|
55
|
+
id: str
|
|
56
|
+
tool: str
|
|
57
|
+
arguments: dict[str, object]
|
|
58
|
+
result: str | None = None
|
|
59
|
+
failed: bool | None = None
|
|
60
|
+
recovery: Call | None = None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass
|
|
64
|
+
class Decision:
|
|
65
|
+
"""One model call that emitted tool calls: what the model saw, and what it called."""
|
|
66
|
+
|
|
67
|
+
history: MessageHistory
|
|
68
|
+
tools: list[Tool]
|
|
69
|
+
calls: list[Call]
|
|
70
|
+
earlier: set[str] = field(default_factory=set)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass
|
|
74
|
+
class Verdict:
|
|
75
|
+
"""Replay counts for one candidate text."""
|
|
76
|
+
|
|
77
|
+
fixes: float = 0.0
|
|
78
|
+
tried_fixes: int = 0
|
|
79
|
+
breaks: int = 0
|
|
80
|
+
tried_breaks: int = 0
|
|
81
|
+
unstable: int = 0
|
|
82
|
+
cost_usd: float = 0.0
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def accepted(self) -> bool:
|
|
86
|
+
"""Replayed failures score at least 0.5 on average, and no stable call that worked is broken."""
|
|
87
|
+
return self.tried_fixes > 0 and 2 * self.fixes >= self.tried_fixes and self.breaks == 0
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def text_of(tool: Tool) -> ToolText:
|
|
91
|
+
"""The text a tool carries."""
|
|
92
|
+
return {
|
|
93
|
+
"description": tool.detail,
|
|
94
|
+
"params": {p.name: p.description for p in tool.parameters or []},
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def with_text(tool: Tool, text: ToolText) -> Tool:
|
|
99
|
+
"""A copy of `tool` that reads `text`; name and parameter schema are unchanged."""
|
|
100
|
+
params = []
|
|
101
|
+
for param in tool.parameters or []:
|
|
102
|
+
clone = copy.copy(param)
|
|
103
|
+
clone.description = text["params"].get(param.name, param.description)
|
|
104
|
+
params.append(clone)
|
|
105
|
+
return Tool(tool.name, text["description"], params)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def propose(
|
|
109
|
+
model: ModelBase,
|
|
110
|
+
tool: Tool,
|
|
111
|
+
failures: list[Call],
|
|
112
|
+
successes: list[Call],
|
|
113
|
+
max_chars: int,
|
|
114
|
+
) -> tuple[ToolText, str, float] | None:
|
|
115
|
+
"""One candidate text, its lesson and the call's cost; None when the answer changes nothing or is too long."""
|
|
116
|
+
payload = {
|
|
117
|
+
"tool": {"name": tool.name, **text_of(tool)},
|
|
118
|
+
"failed_calls": [
|
|
119
|
+
{
|
|
120
|
+
"arguments": c.arguments,
|
|
121
|
+
"error": _clip(c.result),
|
|
122
|
+
"worked_afterwards": c.recovery.arguments if c.recovery else None,
|
|
123
|
+
}
|
|
124
|
+
for c in failures
|
|
125
|
+
],
|
|
126
|
+
"calls_that_worked_first_time": [{"arguments": c.arguments, "result": _clip(c.result)} for c in successes],
|
|
127
|
+
}
|
|
128
|
+
messages = MessageHistory(
|
|
129
|
+
[
|
|
130
|
+
SystemMessage(INSTRUCTIONS.replace("{max_chars}", str(max_chars))),
|
|
131
|
+
UserMessage(json.dumps(payload, indent=1, default=str)),
|
|
132
|
+
]
|
|
133
|
+
)
|
|
134
|
+
response = model.structured(messages, Patch)
|
|
135
|
+
patch = response.message.content
|
|
136
|
+
cost = response.message_info.total_cost or 0.0
|
|
137
|
+
if not isinstance(patch, Patch):
|
|
138
|
+
return None
|
|
139
|
+
old = text_of(tool)
|
|
140
|
+
params = {p.name: p.description.strip() for p in patch.params if p.name in old["params"] and p.description.strip()}
|
|
141
|
+
text: ToolText = {
|
|
142
|
+
"description": patch.description.strip(),
|
|
143
|
+
"params": {**old["params"], **params},
|
|
144
|
+
}
|
|
145
|
+
if not text["description"] or len(text["description"]) > max_chars or text == old:
|
|
146
|
+
return None
|
|
147
|
+
return text, patch.lesson.strip(), cost
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def gate(
|
|
151
|
+
model: ModelBase,
|
|
152
|
+
tool: str,
|
|
153
|
+
text: ToolText,
|
|
154
|
+
failed: list[tuple[Decision, Call]],
|
|
155
|
+
good: list[tuple[Decision, Call]],
|
|
156
|
+
) -> Verdict:
|
|
157
|
+
"""Replay each decision with `text` in place of the tool's live text and score fixes and breaks."""
|
|
158
|
+
verdict = Verdict()
|
|
159
|
+
for decision, call in failed:
|
|
160
|
+
assert call.recovery is not None
|
|
161
|
+
emitted = _replay(model, decision, tool, text, verdict)
|
|
162
|
+
verdict.tried_fixes += 1
|
|
163
|
+
if _same(call.recovery.arguments, emitted):
|
|
164
|
+
verdict.fixes += 1.0
|
|
165
|
+
elif not _same(call.arguments, emitted):
|
|
166
|
+
verdict.fixes += 0.5
|
|
167
|
+
for decision, call in good:
|
|
168
|
+
if not _same(call.arguments, _replay(model, decision, tool, None, verdict)):
|
|
169
|
+
verdict.unstable += 1
|
|
170
|
+
continue
|
|
171
|
+
verdict.tried_breaks += 1
|
|
172
|
+
verdict.breaks += not _same(call.arguments, _replay(model, decision, tool, text, verdict))
|
|
173
|
+
return verdict
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _replay(
|
|
177
|
+
model: ModelBase, decision: Decision, tool: str, text: ToolText | None, verdict: Verdict
|
|
178
|
+
) -> list[dict[str, object]]:
|
|
179
|
+
"""The arguments of each call to `tool` the decision emits now; `text` None replays the text it was made with."""
|
|
180
|
+
tools = [with_text(t, text) if t.name == tool and text else t for t in decision.tools]
|
|
181
|
+
response = model.chat_with_tools(decision.history, tools)
|
|
182
|
+
verdict.cost_usd += response.message_info.total_cost or 0.0
|
|
183
|
+
return [c.arguments for c in response.message.tool_calls if c.name == tool]
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _same(arguments: dict[str, object], emitted: list[dict[str, object]]) -> bool:
|
|
187
|
+
return any(_norm(arguments) == _norm(e) for e in emitted)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _norm(arguments: dict[str, object]) -> str:
|
|
191
|
+
return json.dumps(
|
|
192
|
+
{k: v.strip().casefold() if isinstance(v, str) else v for k, v in arguments.items()},
|
|
193
|
+
sort_keys=True,
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _clip(text: str | None) -> str:
|
|
198
|
+
text = text or ""
|
|
199
|
+
return text if len(text) <= RESULT_CHARS else text[:RESULT_CHARS] + "..."
|
|
File without changes
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Versioned tool texts on disk: what the agent reads for each evolvable tool, and every earlier version.
|
|
2
|
+
|
|
3
|
+
Only text is stored. A tool's name, parameter names, types and required set come from code and never change here.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import threading
|
|
11
|
+
from datetime import UTC, datetime
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import TypedDict
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ToolText(TypedDict):
|
|
17
|
+
"""The parts of a tool the agent reads and the healer may rewrite."""
|
|
18
|
+
|
|
19
|
+
description: str
|
|
20
|
+
params: dict[str, str]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Version(ToolText):
|
|
24
|
+
"""One stored version of a tool's text."""
|
|
25
|
+
|
|
26
|
+
version: int
|
|
27
|
+
lesson: str
|
|
28
|
+
created: str
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class SpecStore:
|
|
32
|
+
"""Tool texts in a JSON file, one list of versions per tool; the last version is the live one.
|
|
33
|
+
|
|
34
|
+
Version 0 is the text written in code. When that text changes, the tool's history starts over, since the
|
|
35
|
+
evolved versions were built on the old one.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
def __init__(self, path: Path | str) -> None:
|
|
39
|
+
self.path = Path(path)
|
|
40
|
+
self._lock = threading.Lock()
|
|
41
|
+
self._tools: dict[str, list[Version]] = (
|
|
42
|
+
json.loads(self.path.read_text(encoding="utf-8")) if self.path.exists() else {}
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
def seed(self, tool: str, text: ToolText) -> bool:
|
|
46
|
+
"""Record the code's text as version 0 unless it is already there; True when the history started over."""
|
|
47
|
+
with self._lock:
|
|
48
|
+
versions = self._tools.get(tool)
|
|
49
|
+
if versions and _text(versions[0]) == text:
|
|
50
|
+
return False
|
|
51
|
+
self._tools[tool] = [_version(0, text, "written in code")]
|
|
52
|
+
self._save()
|
|
53
|
+
return versions is not None
|
|
54
|
+
|
|
55
|
+
def current(self, tool: str) -> ToolText | None:
|
|
56
|
+
"""The live text of a tool, or None for a tool never seen."""
|
|
57
|
+
with self._lock:
|
|
58
|
+
versions = self._tools.get(tool)
|
|
59
|
+
return _text(versions[-1]) if versions else None
|
|
60
|
+
|
|
61
|
+
def versions(self, tool: str) -> list[Version]:
|
|
62
|
+
"""Every version of a tool, oldest first."""
|
|
63
|
+
with self._lock:
|
|
64
|
+
return list(self._tools.get(tool, []))
|
|
65
|
+
|
|
66
|
+
def commit(self, tool: str, text: ToolText, lesson: str) -> Version:
|
|
67
|
+
"""Make `text` the live version of a seeded tool."""
|
|
68
|
+
with self._lock:
|
|
69
|
+
versions = self._tools[tool]
|
|
70
|
+
version = _version(versions[-1]["version"] + 1, text, lesson)
|
|
71
|
+
versions.append(version)
|
|
72
|
+
self._save()
|
|
73
|
+
return version
|
|
74
|
+
|
|
75
|
+
def revert(self, tool: str, version: int) -> Version:
|
|
76
|
+
"""Make an earlier version live again, as a new version, so the history keeps the change."""
|
|
77
|
+
old = next(v for v in self.versions(tool) if v["version"] == version)
|
|
78
|
+
return self.commit(tool, _text(old), f"reverted to v{version}")
|
|
79
|
+
|
|
80
|
+
def _save(self) -> None:
|
|
81
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
82
|
+
tmp = self.path.with_suffix(self.path.suffix + ".tmp")
|
|
83
|
+
tmp.write_text(json.dumps(self._tools, indent=2, ensure_ascii=False), encoding="utf-8")
|
|
84
|
+
os.replace(tmp, self.path)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _text(version: Version) -> ToolText:
|
|
88
|
+
return {"description": version["description"], "params": dict(version["params"])}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _version(number: int, text: ToolText, lesson: str) -> Version:
|
|
92
|
+
return {
|
|
93
|
+
"version": number,
|
|
94
|
+
"description": text["description"],
|
|
95
|
+
"params": dict(text["params"]),
|
|
96
|
+
"lesson": lesson,
|
|
97
|
+
"created": datetime.now(UTC).isoformat(timespec="seconds"),
|
|
98
|
+
}
|