Metadata-Version: 2.4
Name: railtracks-toolevo
Version: 0.1.0
Summary: Tool descriptions that evolve from an agent's own failed calls: a drop-in middleware for Railtracks
Keywords: railtracks,ai-agents,llm,tool-calling,function-calling,self-improving,prompt-optimization,middleware,mcp
Author: Guan Zheng Huang
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Typing :: Typed
Requires-Dist: railtracks>=1.8.1
Requires-Python: >=3.11
Project-URL: Homepage, https://github.com/CoronRing/railtracks-toolevo
Project-URL: Documentation, https://github.com/CoronRing/railtracks-toolevo/blob/main/docs/design.md
Project-URL: Issues, https://github.com/CoronRing/railtracks-toolevo/issues
Project-URL: Railtracks, https://github.com/RailtownAI/railtracks
Description-Content-Type: text/markdown

# railtracks-toolevo: self-healing tool descriptions for AI agents

[![PyPI](https://img.shields.io/pypi/v/railtracks-toolevo)](https://pypi.org/project/railtracks-toolevo/)
[![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue)](https://www.python.org/)
[![Railtracks](https://img.shields.io/badge/built%20for-Railtracks-6f42c1)](https://github.com/RailtownAI/railtracks)
[![License: MIT](https://img.shields.io/badge/license-MIT-green)](https://github.com/CoronRing/railtracks-toolevo/blob/main/LICENSE)

**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.

> **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.

<p align="center">
  <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">
  <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">
  <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">
</p>
<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>

## Why ToolEvo

- **Drop-in.** One line on your agent: `model_middleware=[evo.middleware]`. No change to your tools.
- **You choose what can change.** List the tools allowed to evolve; every other tool stays frozen.
- **Off the hot path.** Healing runs after the answer is returned, on a background thread, so users never wait for it.
- **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.
- **Versioned and reversible.** Every version is saved with a one-line lesson, survives restarts, and can be reverted.
- **Only text changes.** Tool names, parameter names, types and required fields always come from your code.

## Quick start

```bash
pip install railtracks-toolevo
```

```python
import railtracks as rt
from railtracks_toolevo import ToolEvo

def get_weather(city: str) -> str:
    """Get the weather.

    Args:
        city: The city.
    """
    name, _, country = city.partition(", ")
    if len(country) != 2:
        raise ValueError("Use 'City, CC' with a two-letter country code, e.g. 'Paris, FR'.")
    return f"{name}: 18C, light rain"

llm = rt.llm.OpenAILLM("gpt-6-luna")
evo = ToolEvo(llm, evolve=[get_weather])  # tools not listed stay frozen
agent = rt.agent_node("Weather", tool_nodes=[rt.function_node(get_weather)], llm=llm, model_middleware=[evo.middleware])
flow = rt.Flow("weather", entry_point=agent)

flow.invoke("Weather in Paris?")  # calls "Paris", fails, retries "Paris, FR"; healing runs after the answer
evo.wait()
flow.invoke("Weather in Tokyo?")  # calls "Tokyo, JP" first time
```

What changed in the description the agent reads:

```diff
  get_weather(city)
-   city: The city.
+   city: The city, formatted as 'City, CC' with a two-letter country code.
```

## How it works

```mermaid
flowchart TD
    A[Agent calls a tool] --> B{Failed?}
    B -- no --> Z[Answer returned]
    B -- yes --> C[Agent reads the error and retries] --> Z
    Z -. after the answer .-> D[Healer writes a new description from the failure and the retry that worked]
    D --> E[Replay the model's earlier decisions with the new text]
    E -- now makes the call that worked, breaks nothing --> F[Commit a new version]
    E -- otherwise --> G[Reject]
    F --> H[Next request reads the new description]
```

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.
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.
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).
4. **Commit.** Accepted text becomes a new version in `toolevo.json`. `evo.store.revert(tool, version)` undoes it.

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).

## Demos

| Demo | What it shows | Result (gpt-6-luna) |
|---|---|---|
| [`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. |
| [`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. |

```bash
git clone https://github.com/CoronRing/railtracks-toolevo && cd railtracks-toolevo
uv run --group demo examples/weather.py
uv run --group demo examples/blender_asset/build.py   # needs Blender on PATH or in $BLENDER
```

Set `OPENAI_API_KEY` in your environment or a `.env` file. Models are not deterministic, so your numbers will differ a little.

## Options

| Argument | Default | Meaning |
|---|---|---|
| `evolve` | required | Tools allowed to change: functions, `function_node` results, node classes or names. Every other tool is frozen. |
| `path` | `toolevo.json` | Where versions are kept. |
| `healer` | `model` | A different (often stronger) model to write new descriptions. |
| `failed` | the tool raised | `(tool, result) -> bool`, for tools that fail quietly, such as a search that returns "no matches". |
| `background` | `True` | Heal on a worker thread after each answer. `False` heals before the answer is returned. |
| `min_failures` | 1 | New failed calls of a tool needed before a heal is tried. |
| `max_replays` | 3 | Decisions replayed per check. |
| `max_chars` | 1200 | Longest description the healer may write. |

## FAQ

**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.

**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.

**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.

**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.

**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.

## Status

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.

## License

[MIT](https://github.com/CoronRing/railtracks-toolevo/blob/main/LICENSE)
