agentfork-cli 0.2.0__tar.gz → 0.3.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.
- {agentfork_cli-0.2.0 → agentfork_cli-0.3.0}/PKG-INFO +60 -21
- {agentfork_cli-0.2.0 → agentfork_cli-0.3.0}/README.md +55 -18
- agentfork_cli-0.3.0/examples/langgraph_refund_agent.py +33 -0
- {agentfork_cli-0.2.0 → agentfork_cli-0.3.0}/pyproject.toml +3 -3
- agentfork_cli-0.3.0/src/agentfork/__init__.py +3 -0
- {agentfork_cli-0.2.0 → agentfork_cli-0.3.0}/src/agentfork/cli.py +42 -17
- agentfork_cli-0.3.0/src/agentfork/pricing.py +70 -0
- {agentfork_cli-0.2.0 → agentfork_cli-0.3.0}/src/agentfork/recorder.py +40 -8
- agentfork_cli-0.3.0/src/agentfork/replay.py +155 -0
- {agentfork_cli-0.2.0 → agentfork_cli-0.3.0}/src/agentfork/server.py +21 -6
- {agentfork_cli-0.2.0 → agentfork_cli-0.3.0}/src/agentfork/store.py +8 -1
- {agentfork_cli-0.2.0 → agentfork_cli-0.3.0}/src/agentfork/ui.html +26 -12
- agentfork_cli-0.3.0/tests/test_cost.py +64 -0
- agentfork_cli-0.3.0/tests/test_langgraph.py +65 -0
- agentfork_cli-0.3.0/tests/test_sweep.py +73 -0
- {agentfork_cli-0.2.0 → agentfork_cli-0.3.0}/tests/test_ui.py +5 -1
- agentfork_cli-0.2.0/src/agentfork/__init__.py +0 -3
- agentfork_cli-0.2.0/src/agentfork/replay.py +0 -109
- agentfork_cli-0.2.0/tests/test_sweep.py +0 -37
- {agentfork_cli-0.2.0 → agentfork_cli-0.3.0}/.gitignore +0 -0
- {agentfork_cli-0.2.0 → agentfork_cli-0.3.0}/LICENSE +0 -0
- {agentfork_cli-0.2.0 → agentfork_cli-0.3.0}/examples/demo_agent.py +0 -0
- {agentfork_cli-0.2.0 → agentfork_cli-0.3.0}/examples/demo_agent_claude.py +0 -0
- {agentfork_cli-0.2.0 → agentfork_cli-0.3.0}/examples/refund_agent.py +0 -0
- {agentfork_cli-0.2.0 → agentfork_cli-0.3.0}/examples/refund_agent_cents.py +0 -0
- {agentfork_cli-0.2.0 → agentfork_cli-0.3.0}/tests/test_anthropic.py +0 -0
- {agentfork_cli-0.2.0 → agentfork_cli-0.3.0}/tests/test_cli.py +0 -0
- {agentfork_cli-0.2.0 → agentfork_cli-0.3.0}/tests/test_fork.py +0 -0
- {agentfork_cli-0.2.0 → agentfork_cli-0.3.0}/tests/test_recorder.py +0 -0
- {agentfork_cli-0.2.0 → agentfork_cli-0.3.0}/tests/test_save_test.py +0 -0
- {agentfork_cli-0.2.0 → agentfork_cli-0.3.0}/tests/test_smoke.py +0 -0
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
2
|
Name: agentfork-cli
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Fork your LLM agent at any step and sweep prompts, models or tool results to find what fixes it.
|
|
5
5
|
Project-URL: Homepage, https://github.com/bimal1023/agentfork
|
|
6
6
|
Project-URL: Issues, https://github.com/bimal1023/agentfork/issues
|
|
7
7
|
Author: Bimal Kumal
|
|
8
8
|
License-Expression: MIT
|
|
9
9
|
License-File: LICENSE
|
|
10
|
-
Keywords: agents,anthropic,debugging,llm,openai,replay,testing
|
|
10
|
+
Keywords: agents,anthropic,debugging,langgraph,llm,openai,replay,testing
|
|
11
11
|
Classifier: Development Status :: 3 - Alpha
|
|
12
12
|
Classifier: Intended Audience :: Developers
|
|
13
13
|
Classifier: Programming Language :: Python :: 3
|
|
@@ -22,6 +22,8 @@ Provides-Extra: dev
|
|
|
22
22
|
Requires-Dist: anthropic; extra == 'dev'
|
|
23
23
|
Requires-Dist: fastapi; extra == 'dev'
|
|
24
24
|
Requires-Dist: httpx; extra == 'dev'
|
|
25
|
+
Requires-Dist: langchain-openai; extra == 'dev'
|
|
26
|
+
Requires-Dist: langgraph; extra == 'dev'
|
|
25
27
|
Requires-Dist: openai; extra == 'dev'
|
|
26
28
|
Requires-Dist: pytest; extra == 'dev'
|
|
27
29
|
Requires-Dist: uvicorn; extra == 'dev'
|
|
@@ -49,28 +51,30 @@ Everything runs locally. No account, no server, no data leaves your machine.
|
|
|
49
51
|
A refund agent reads `"amount": 4999, "currency": "USD"` from an order API. The amount is in cents, and the agent refunds **$4,999** for a $49.99 laptop ([examples/refund_agent_cents.py](examples/refund_agent_cents.py)). Is the fix a better model or a better prompt?
|
|
50
52
|
|
|
51
53
|
```text
|
|
52
|
-
$ agentfork sweep
|
|
54
|
+
$ agentfork sweep 543da612 --step 3 --repeat 3 --expect "49.99" --model gpt-4o-mini,gpt-4o
|
|
55
|
+
Estimated cost: about $0.0050
|
|
53
56
|
|
|
54
|
-
variant
|
|
55
|
-
original 1
|
|
56
|
-
model=gpt-4o-mini 3
|
|
57
|
-
model=gpt-4o 3
|
|
57
|
+
variant ok pass tokens time cost sample output
|
|
58
|
+
original 1/1 0/1 446 1.7s $0.0001 I have processed a refund of $4,999.00...
|
|
59
|
+
model=gpt-4o-mini 3/3 0/3 446 1.4s $0.0001 I have processed a refund of $4,999.00...
|
|
60
|
+
model=gpt-4o 3/3 0/3 394 1.2s $0.0015 The full amount of $4,999.00 for order A123...
|
|
58
61
|
```
|
|
59
62
|
|
|
60
|
-
A bigger model doesn't fix it. One sentence in the prompt does:
|
|
63
|
+
A bigger model costs 15x more per run and doesn't fix it. One sentence in the prompt does:
|
|
61
64
|
|
|
62
65
|
```text
|
|
63
|
-
$ agentfork sweep
|
|
66
|
+
$ agentfork sweep 543da612 --step 3 --repeat 3 --expect "49.99" \
|
|
64
67
|
--system "You are a support agent. Look up the order, then refund the full order amount in USD." \
|
|
65
68
|
--system "... Order amounts from the API are in cents; divide by 100 before refunding."
|
|
69
|
+
Estimated cost: about $0.0006
|
|
66
70
|
|
|
67
|
-
variant
|
|
68
|
-
original
|
|
69
|
-
system #1
|
|
70
|
-
system #2
|
|
71
|
+
variant ok pass tokens time cost sample output
|
|
72
|
+
original 1/1 0/1 446 1.7s $0.0001 I have processed a refund of $4,999.00...
|
|
73
|
+
system #1 3/3 0/3 445 1.2s $0.0001 I've successfully refunded you $4,999.00...
|
|
74
|
+
system #2 3/3 3/3 457 1.2s $0.0001 I have processed a refund of $49.99...
|
|
71
75
|
```
|
|
72
76
|
|
|
73
|
-
Steps 1 and 2 replayed from cache in every run, so only the step that mattered was paid for.
|
|
77
|
+
Steps 1 and 2 replayed from cache in every run, so only the step that mattered was paid for, and the runs went 4 at a time.
|
|
74
78
|
|
|
75
79
|
## Quickstart
|
|
76
80
|
|
|
@@ -95,6 +99,33 @@ def run_agent(question): ...
|
|
|
95
99
|
|
|
96
100
|
Run your agent as usual. Each run is saved to `.agentfork/traces.db`.
|
|
97
101
|
|
|
102
|
+
### LangGraph
|
|
103
|
+
|
|
104
|
+
Wrap the chat model and put `@agentfork.tool` under LangChain's `@tool`. Forks and sweeps then work on the graph like on any other agent ([examples/langgraph_refund_agent.py](examples/langgraph_refund_agent.py)):
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
import agentfork
|
|
108
|
+
from langchain_core.tools import tool
|
|
109
|
+
from langchain_openai import ChatOpenAI
|
|
110
|
+
from langgraph.prebuilt import create_react_agent
|
|
111
|
+
|
|
112
|
+
llm = agentfork.wrap_langchain(ChatOpenAI(model="gpt-4o-mini")) # or ChatAnthropic
|
|
113
|
+
|
|
114
|
+
@tool
|
|
115
|
+
@agentfork.tool
|
|
116
|
+
def lookup_order(order_id: str) -> str:
|
|
117
|
+
"""Look up an order by id."""
|
|
118
|
+
...
|
|
119
|
+
|
|
120
|
+
graph = create_react_agent(llm, [lookup_order])
|
|
121
|
+
|
|
122
|
+
@agentfork.trace
|
|
123
|
+
def run_agent(question):
|
|
124
|
+
return graph.invoke({"messages": [("user", question)]})["messages"][-1].content
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
Streaming models (`streaming=True`) and the OpenAI Responses API aren't recorded yet.
|
|
128
|
+
|
|
98
129
|
## Commands
|
|
99
130
|
|
|
100
131
|
| Command | What it does |
|
|
@@ -102,7 +133,7 @@ Run your agent as usual. Each run is saved to `.agentfork/traces.db`.
|
|
|
102
133
|
| `agentfork list` | Recent runs with steps, tokens, duration and fork lineage |
|
|
103
134
|
| `agentfork show <id> [--full]` | A run as a step tree, with optional full JSON |
|
|
104
135
|
| `agentfork fork <id> --step N --output/--model/--system ...` | Re-run from step N with one change; earlier steps come from cache |
|
|
105
|
-
| `agentfork sweep <id> --step N --model a,b --system ... --repeat K --expect TEXT` | Try many variants of step N, K times each, and compare pass rate, tokens and
|
|
136
|
+
| `agentfork sweep <id> --step N --model a,b --system ... --repeat K --expect TEXT [--parallel P]` | Try many variants of step N, K times each, P at a time (default 4), and compare pass rate, tokens, time and cost |
|
|
106
137
|
| `agentfork diff <a> <b>` | Compare two runs step by step |
|
|
107
138
|
| `agentfork save-test <id>` | Save a run as a pytest test that replays from cache in CI with no API key |
|
|
108
139
|
| `agentfork ui [--port N]` | Open the local web UI to browse, fork, sweep and compare runs |
|
|
@@ -133,11 +164,19 @@ Start it from the folder you ran your agent in, since runs are saved to `.agentf
|
|
|
133
164
|
|
|
134
165
|
## How it works
|
|
135
166
|
|
|
136
|
-
1. **Record.** `@trace`, `@tool` and `wrap_openai`/`wrap_anthropic` capture each step's inputs, outputs, tokens and latency, plus a hash of its inputs.
|
|
167
|
+
1. **Record.** `@trace`, `@tool` and `wrap_openai`/`wrap_anthropic`/`wrap_langchain` capture each step's inputs, outputs, tokens and latency, plus a hash of its inputs.
|
|
137
168
|
2. **Fork.** agentfork re-imports your agent and re-runs it. Steps before N are served from the cache, step N gets your change, and everything after runs live. A model change applies to every LLM call from step N on.
|
|
138
|
-
3. **Sweep.** Runs fork for each variant `--repeat` times and checks each final output for your `--expect` text.
|
|
169
|
+
3. **Sweep.** Runs fork for each variant `--repeat` times, `--parallel` at a time, and checks each final output for your `--expect` text. Before it starts, it estimates the cost from the tokens the original run used from step N on, priced per model.
|
|
139
170
|
4. **Test.** `save-test` writes a JSON snapshot plus a pytest file. The test replays every step from cache and fails with a diff if any step's inputs, the step count, or the final output changes.
|
|
140
171
|
|
|
172
|
+
## Costs
|
|
173
|
+
|
|
174
|
+
Costs use list prices per model for OpenAI and Anthropic, built into [pricing.py](src/agentfork/pricing.py). Prices change, and a model without a price shows `-`. To add or correct one, put USD per 1M input and output tokens in `.agentfork/prices.json`:
|
|
175
|
+
|
|
176
|
+
```json
|
|
177
|
+
{"gpt-4o-mini": [0.15, 0.60], "my-finetune": [3.0, 12.0]}
|
|
178
|
+
```
|
|
179
|
+
|
|
141
180
|
## Related work
|
|
142
181
|
|
|
143
182
|
agentfork overlaps with record/replay tools like [agent-rewind](https://pypi.org/project/agent-rewind/), which supports many more providers, and [agentstep](https://pypi.org/project/agentstep/), a LangGraph time-travel debugger with a web UI. agentfork's focus is the step after replay: sweeping many variants of one step, with repeats and pass rates, to choose a fix with evidence.
|
|
@@ -148,9 +187,9 @@ agentfork overlaps with record/replay tools like [agent-rewind](https://pypi.org
|
|
|
148
187
|
- [x] OpenAI and Anthropic support
|
|
149
188
|
- [x] Sweep with repeats and pass rates
|
|
150
189
|
- [x] Local web UI
|
|
151
|
-
- [
|
|
152
|
-
- [
|
|
153
|
-
- [
|
|
190
|
+
- [x] Cost estimates per variant
|
|
191
|
+
- [x] Parallel sweeps
|
|
192
|
+
- [x] LangGraph integration
|
|
154
193
|
|
|
155
194
|
## License
|
|
156
195
|
|
|
@@ -15,28 +15,30 @@ Everything runs locally. No account, no server, no data leaves your machine.
|
|
|
15
15
|
A refund agent reads `"amount": 4999, "currency": "USD"` from an order API. The amount is in cents, and the agent refunds **$4,999** for a $49.99 laptop ([examples/refund_agent_cents.py](examples/refund_agent_cents.py)). Is the fix a better model or a better prompt?
|
|
16
16
|
|
|
17
17
|
```text
|
|
18
|
-
$ agentfork sweep
|
|
18
|
+
$ agentfork sweep 543da612 --step 3 --repeat 3 --expect "49.99" --model gpt-4o-mini,gpt-4o
|
|
19
|
+
Estimated cost: about $0.0050
|
|
19
20
|
|
|
20
|
-
variant
|
|
21
|
-
original 1
|
|
22
|
-
model=gpt-4o-mini 3
|
|
23
|
-
model=gpt-4o 3
|
|
21
|
+
variant ok pass tokens time cost sample output
|
|
22
|
+
original 1/1 0/1 446 1.7s $0.0001 I have processed a refund of $4,999.00...
|
|
23
|
+
model=gpt-4o-mini 3/3 0/3 446 1.4s $0.0001 I have processed a refund of $4,999.00...
|
|
24
|
+
model=gpt-4o 3/3 0/3 394 1.2s $0.0015 The full amount of $4,999.00 for order A123...
|
|
24
25
|
```
|
|
25
26
|
|
|
26
|
-
A bigger model doesn't fix it. One sentence in the prompt does:
|
|
27
|
+
A bigger model costs 15x more per run and doesn't fix it. One sentence in the prompt does:
|
|
27
28
|
|
|
28
29
|
```text
|
|
29
|
-
$ agentfork sweep
|
|
30
|
+
$ agentfork sweep 543da612 --step 3 --repeat 3 --expect "49.99" \
|
|
30
31
|
--system "You are a support agent. Look up the order, then refund the full order amount in USD." \
|
|
31
32
|
--system "... Order amounts from the API are in cents; divide by 100 before refunding."
|
|
33
|
+
Estimated cost: about $0.0006
|
|
32
34
|
|
|
33
|
-
variant
|
|
34
|
-
original
|
|
35
|
-
system #1
|
|
36
|
-
system #2
|
|
35
|
+
variant ok pass tokens time cost sample output
|
|
36
|
+
original 1/1 0/1 446 1.7s $0.0001 I have processed a refund of $4,999.00...
|
|
37
|
+
system #1 3/3 0/3 445 1.2s $0.0001 I've successfully refunded you $4,999.00...
|
|
38
|
+
system #2 3/3 3/3 457 1.2s $0.0001 I have processed a refund of $49.99...
|
|
37
39
|
```
|
|
38
40
|
|
|
39
|
-
Steps 1 and 2 replayed from cache in every run, so only the step that mattered was paid for.
|
|
41
|
+
Steps 1 and 2 replayed from cache in every run, so only the step that mattered was paid for, and the runs went 4 at a time.
|
|
40
42
|
|
|
41
43
|
## Quickstart
|
|
42
44
|
|
|
@@ -61,6 +63,33 @@ def run_agent(question): ...
|
|
|
61
63
|
|
|
62
64
|
Run your agent as usual. Each run is saved to `.agentfork/traces.db`.
|
|
63
65
|
|
|
66
|
+
### LangGraph
|
|
67
|
+
|
|
68
|
+
Wrap the chat model and put `@agentfork.tool` under LangChain's `@tool`. Forks and sweeps then work on the graph like on any other agent ([examples/langgraph_refund_agent.py](examples/langgraph_refund_agent.py)):
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
import agentfork
|
|
72
|
+
from langchain_core.tools import tool
|
|
73
|
+
from langchain_openai import ChatOpenAI
|
|
74
|
+
from langgraph.prebuilt import create_react_agent
|
|
75
|
+
|
|
76
|
+
llm = agentfork.wrap_langchain(ChatOpenAI(model="gpt-4o-mini")) # or ChatAnthropic
|
|
77
|
+
|
|
78
|
+
@tool
|
|
79
|
+
@agentfork.tool
|
|
80
|
+
def lookup_order(order_id: str) -> str:
|
|
81
|
+
"""Look up an order by id."""
|
|
82
|
+
...
|
|
83
|
+
|
|
84
|
+
graph = create_react_agent(llm, [lookup_order])
|
|
85
|
+
|
|
86
|
+
@agentfork.trace
|
|
87
|
+
def run_agent(question):
|
|
88
|
+
return graph.invoke({"messages": [("user", question)]})["messages"][-1].content
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Streaming models (`streaming=True`) and the OpenAI Responses API aren't recorded yet.
|
|
92
|
+
|
|
64
93
|
## Commands
|
|
65
94
|
|
|
66
95
|
| Command | What it does |
|
|
@@ -68,7 +97,7 @@ Run your agent as usual. Each run is saved to `.agentfork/traces.db`.
|
|
|
68
97
|
| `agentfork list` | Recent runs with steps, tokens, duration and fork lineage |
|
|
69
98
|
| `agentfork show <id> [--full]` | A run as a step tree, with optional full JSON |
|
|
70
99
|
| `agentfork fork <id> --step N --output/--model/--system ...` | Re-run from step N with one change; earlier steps come from cache |
|
|
71
|
-
| `agentfork sweep <id> --step N --model a,b --system ... --repeat K --expect TEXT` | Try many variants of step N, K times each, and compare pass rate, tokens and
|
|
100
|
+
| `agentfork sweep <id> --step N --model a,b --system ... --repeat K --expect TEXT [--parallel P]` | Try many variants of step N, K times each, P at a time (default 4), and compare pass rate, tokens, time and cost |
|
|
72
101
|
| `agentfork diff <a> <b>` | Compare two runs step by step |
|
|
73
102
|
| `agentfork save-test <id>` | Save a run as a pytest test that replays from cache in CI with no API key |
|
|
74
103
|
| `agentfork ui [--port N]` | Open the local web UI to browse, fork, sweep and compare runs |
|
|
@@ -99,11 +128,19 @@ Start it from the folder you ran your agent in, since runs are saved to `.agentf
|
|
|
99
128
|
|
|
100
129
|
## How it works
|
|
101
130
|
|
|
102
|
-
1. **Record.** `@trace`, `@tool` and `wrap_openai`/`wrap_anthropic` capture each step's inputs, outputs, tokens and latency, plus a hash of its inputs.
|
|
131
|
+
1. **Record.** `@trace`, `@tool` and `wrap_openai`/`wrap_anthropic`/`wrap_langchain` capture each step's inputs, outputs, tokens and latency, plus a hash of its inputs.
|
|
103
132
|
2. **Fork.** agentfork re-imports your agent and re-runs it. Steps before N are served from the cache, step N gets your change, and everything after runs live. A model change applies to every LLM call from step N on.
|
|
104
|
-
3. **Sweep.** Runs fork for each variant `--repeat` times and checks each final output for your `--expect` text.
|
|
133
|
+
3. **Sweep.** Runs fork for each variant `--repeat` times, `--parallel` at a time, and checks each final output for your `--expect` text. Before it starts, it estimates the cost from the tokens the original run used from step N on, priced per model.
|
|
105
134
|
4. **Test.** `save-test` writes a JSON snapshot plus a pytest file. The test replays every step from cache and fails with a diff if any step's inputs, the step count, or the final output changes.
|
|
106
135
|
|
|
136
|
+
## Costs
|
|
137
|
+
|
|
138
|
+
Costs use list prices per model for OpenAI and Anthropic, built into [pricing.py](src/agentfork/pricing.py). Prices change, and a model without a price shows `-`. To add or correct one, put USD per 1M input and output tokens in `.agentfork/prices.json`:
|
|
139
|
+
|
|
140
|
+
```json
|
|
141
|
+
{"gpt-4o-mini": [0.15, 0.60], "my-finetune": [3.0, 12.0]}
|
|
142
|
+
```
|
|
143
|
+
|
|
107
144
|
## Related work
|
|
108
145
|
|
|
109
146
|
agentfork overlaps with record/replay tools like [agent-rewind](https://pypi.org/project/agent-rewind/), which supports many more providers, and [agentstep](https://pypi.org/project/agentstep/), a LangGraph time-travel debugger with a web UI. agentfork's focus is the step after replay: sweeping many variants of one step, with repeats and pass rates, to choose a fix with evidence.
|
|
@@ -114,9 +151,9 @@ agentfork overlaps with record/replay tools like [agent-rewind](https://pypi.org
|
|
|
114
151
|
- [x] OpenAI and Anthropic support
|
|
115
152
|
- [x] Sweep with repeats and pass rates
|
|
116
153
|
- [x] Local web UI
|
|
117
|
-
- [
|
|
118
|
-
- [
|
|
119
|
-
- [
|
|
154
|
+
- [x] Cost estimates per variant
|
|
155
|
+
- [x] Parallel sweeps
|
|
156
|
+
- [x] LangGraph integration
|
|
120
157
|
|
|
121
158
|
## License
|
|
122
159
|
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from langchain_core.tools import tool
|
|
3
|
+
from langchain_openai import ChatOpenAI
|
|
4
|
+
from langgraph.prebuilt import create_react_agent
|
|
5
|
+
import agentfork
|
|
6
|
+
|
|
7
|
+
# The refund agent from refund_agent_cents.py, built with LangGraph.
|
|
8
|
+
# wrap_langchain records the model's calls; @agentfork.tool (under @tool) records the tools.
|
|
9
|
+
llm = agentfork.wrap_langchain(ChatOpenAI(model="gpt-4o-mini"))
|
|
10
|
+
|
|
11
|
+
SYSTEM = "You are a support agent. Look up the order, then refund the full order amount in USD."
|
|
12
|
+
ORDERS = {"A123": {"order_id": "A123", "item": "laptop", "amount": 4999, "currency": "USD", "status": "delivered"}}
|
|
13
|
+
|
|
14
|
+
@tool
|
|
15
|
+
@agentfork.tool
|
|
16
|
+
def lookup_order(order_id: str) -> str:
|
|
17
|
+
"""Look up an order by id."""
|
|
18
|
+
return json.dumps(ORDERS.get(order_id, {"error": "not found"}))
|
|
19
|
+
|
|
20
|
+
@tool
|
|
21
|
+
@agentfork.tool
|
|
22
|
+
def issue_refund(order_id: str, amount_usd: float) -> str:
|
|
23
|
+
"""Refund an order. amount_usd is in US dollars."""
|
|
24
|
+
return f"Refunded ${amount_usd:,.2f} for order {order_id}"
|
|
25
|
+
|
|
26
|
+
graph = create_react_agent(llm, [lookup_order, issue_refund], prompt=SYSTEM)
|
|
27
|
+
|
|
28
|
+
@agentfork.trace
|
|
29
|
+
def run_agent(question):
|
|
30
|
+
return graph.invoke({"messages": [("user", question)]})["messages"][-1].content
|
|
31
|
+
|
|
32
|
+
if __name__ == "__main__":
|
|
33
|
+
print(run_agent("My headphones from order A123 arrived broken. Please refund me."))
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "agentfork-cli"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.3.0"
|
|
4
4
|
description = "Fork your LLM agent at any step and sweep prompts, models or tool results to find what fixes it."
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
requires-python = ">=3.9"
|
|
7
7
|
license = "MIT"
|
|
8
8
|
authors = [{ name = "Bimal Kumal" }]
|
|
9
|
-
keywords = ["llm", "agents", "debugging", "replay", "testing", "openai", "anthropic"]
|
|
9
|
+
keywords = ["llm", "agents", "debugging", "replay", "testing", "openai", "anthropic", "langgraph"]
|
|
10
10
|
classifiers = [
|
|
11
11
|
"Development Status :: 3 - Alpha",
|
|
12
12
|
"Intended Audience :: Developers",
|
|
@@ -20,7 +20,7 @@ dependencies = ["typer", "rich"]
|
|
|
20
20
|
openai = ["openai"]
|
|
21
21
|
anthropic = ["anthropic"]
|
|
22
22
|
ui = ["fastapi", "uvicorn"]
|
|
23
|
-
dev = ["pytest", "openai", "anthropic", "fastapi", "uvicorn", "httpx"]
|
|
23
|
+
dev = ["pytest", "openai", "anthropic", "fastapi", "uvicorn", "httpx", "langgraph", "langchain-openai"]
|
|
24
24
|
|
|
25
25
|
[project.urls]
|
|
26
26
|
Homepage = "https://github.com/bimal1023/agentfork"
|
|
@@ -3,12 +3,13 @@ from datetime import datetime
|
|
|
3
3
|
from typing import List, Optional
|
|
4
4
|
|
|
5
5
|
import typer
|
|
6
|
+
from rich import box
|
|
6
7
|
from rich.console import Console
|
|
7
8
|
from rich.syntax import Syntax
|
|
8
9
|
from rich.table import Table
|
|
9
10
|
from rich.tree import Tree
|
|
10
11
|
|
|
11
|
-
from . import replay, store
|
|
12
|
+
from . import pricing, replay, store
|
|
12
13
|
|
|
13
14
|
app = typer.Typer(help="agentfork: record, inspect and replay LLM agent runs.")
|
|
14
15
|
console = Console()
|
|
@@ -84,10 +85,13 @@ def show(run_id: str = typer.Argument(..., help="Run id or its first few charact
|
|
|
84
85
|
color = STATUS_COLOR.get(run["status"], "white")
|
|
85
86
|
fork = (f" [dim]fork of {run['parent_run_id'][:8]} at step {run['fork_step']}[/dim]"
|
|
86
87
|
if run.get("parent_run_id") else "")
|
|
88
|
+
steps = store.get_steps(run["id"])
|
|
89
|
+
cost = pricing.steps_cost([s for s in steps if not s["cached"]])
|
|
90
|
+
cost = f" [dim]{pricing.fmt(cost)}[/dim]" if cost is not None else ""
|
|
87
91
|
root = Tree(f"[bold]{run['name']}[/bold] {run['id'][:8]} "
|
|
88
|
-
f"[{color}]{run['status']}[/{color}] {_duration(run)}{fork}")
|
|
92
|
+
f"[{color}]{run['status']}[/{color}] {_duration(run)}{cost}{fork}")
|
|
89
93
|
nodes = {}
|
|
90
|
-
for s in
|
|
94
|
+
for s in steps:
|
|
91
95
|
node = nodes.get(s["parent_id"], root).add(_label(s))
|
|
92
96
|
if full:
|
|
93
97
|
node.add(Syntax(json.dumps(_load(s["input_json"]), indent=2), "json", word_wrap=True))
|
|
@@ -195,6 +199,13 @@ def _make_labels(variants):
|
|
|
195
199
|
labels[id(v)] = f"{key} #{counts[key]}"
|
|
196
200
|
return labels
|
|
197
201
|
|
|
202
|
+
def _clip(text, n):
|
|
203
|
+
return text if len(text) <= n else text[:n - 1] + "…"
|
|
204
|
+
|
|
205
|
+
def _avg_cost(rows):
|
|
206
|
+
costs = [r["cost"] for r in rows]
|
|
207
|
+
return "-" if None in costs else pricing.fmt(sum(costs) / len(costs))
|
|
208
|
+
|
|
198
209
|
@app.command()
|
|
199
210
|
def sweep(run_id: str = typer.Argument(..., help="Run to sweep."),
|
|
200
211
|
step: int = typer.Option(..., "--step", help="Step to vary (see `show`)."),
|
|
@@ -202,7 +213,8 @@ def sweep(run_id: str = typer.Argument(..., help="Run to sweep."),
|
|
|
202
213
|
system: Optional[List[str]] = typer.Option(None, "--system", help="System prompt to try; repeat for more."),
|
|
203
214
|
output: Optional[List[str]] = typer.Option(None, "--output", help="Tool result to try; repeat for more."),
|
|
204
215
|
repeat: int = typer.Option(1, "--repeat", help="Runs per variant (LLMs vary run to run)."),
|
|
205
|
-
expect: Optional[str] = typer.Option(None, "--expect", help="Text a good final output contains.")
|
|
216
|
+
expect: Optional[str] = typer.Option(None, "--expect", help="Text a good final output contains."),
|
|
217
|
+
parallel: int = typer.Option(4, "--parallel", help="How many runs to make at the same time.")):
|
|
206
218
|
"""Fork one step across several models, prompts or tool results and compare outcomes."""
|
|
207
219
|
variants = [{"model": m.strip()} for m in (model or "").split(",") if m.strip()]
|
|
208
220
|
variants += [{"system": s} for s in (system or [])]
|
|
@@ -213,7 +225,17 @@ def sweep(run_id: str = typer.Argument(..., help="Run to sweep."),
|
|
|
213
225
|
run = _resolve(run_id)
|
|
214
226
|
labels = _make_labels(variants)
|
|
215
227
|
console.print(f"[bold]Sweeping step {step} of {run['id'][:8]}: "
|
|
216
|
-
f"{len(variants)} variants x {repeat} = {len(variants) * repeat} runs
|
|
228
|
+
f"{len(variants)} variants x {repeat} = {len(variants) * repeat} runs, "
|
|
229
|
+
f"{min(parallel, len(variants) * repeat)} at a time[/bold]")
|
|
230
|
+
try:
|
|
231
|
+
est = replay.estimate(run, step, variants, repeat)
|
|
232
|
+
except ValueError:
|
|
233
|
+
est = None
|
|
234
|
+
if est and est["total"] is not None:
|
|
235
|
+
console.print(f"[dim]Estimated cost: about {pricing.fmt(est['total'])}[/dim]")
|
|
236
|
+
elif est and est["unpriced"]:
|
|
237
|
+
console.print(f"[dim]Estimated cost unknown: no price for {', '.join(est['unpriced'])} "
|
|
238
|
+
f"(add it to .agentfork/prices.json)[/dim]")
|
|
217
239
|
|
|
218
240
|
def progress(r):
|
|
219
241
|
mark = "[green]ok[/green]" if r["status"] == "ok" else "[red]error[/red]"
|
|
@@ -221,7 +243,8 @@ def sweep(run_id: str = typer.Argument(..., help="Run to sweep."),
|
|
|
221
243
|
console.print(f" {mark}{verdict} {labels[id(r['variant'])]} [dim]{r['tokens']} tok[/dim]")
|
|
222
244
|
|
|
223
245
|
try:
|
|
224
|
-
results = replay.sweep(run, step, variants, repeat=repeat, expect=expect,
|
|
246
|
+
results = replay.sweep(run, step, variants, repeat=repeat, expect=expect,
|
|
247
|
+
on_result=progress, parallel=parallel)
|
|
225
248
|
except ValueError as e:
|
|
226
249
|
console.print(f"[red]{e}[/red]")
|
|
227
250
|
raise typer.Exit(1)
|
|
@@ -229,28 +252,30 @@ def sweep(run_id: str = typer.Argument(..., help="Run to sweep."),
|
|
|
229
252
|
groups = {"original": [replay.baseline(run, step, expect)]}
|
|
230
253
|
for r in results:
|
|
231
254
|
groups.setdefault(labels[id(r["variant"])], []).append(r)
|
|
232
|
-
table = Table(title=f"Sweep of step {step} ({run['id'][:8]})",
|
|
255
|
+
table = Table(title=f"Sweep of step {step} ({run['id'][:8]})", box=box.SIMPLE_HEAD,
|
|
256
|
+
caption="tokens, time and cost are averages per run", caption_justify="left")
|
|
233
257
|
table.add_column("variant", no_wrap=True)
|
|
234
|
-
table.add_column("
|
|
235
|
-
table.add_column("ok", no_wrap=True, min_width=3)
|
|
258
|
+
table.add_column("ok", no_wrap=True)
|
|
236
259
|
if expect:
|
|
237
|
-
table.add_column("pass", no_wrap=True
|
|
238
|
-
table.add_column("
|
|
239
|
-
table.add_column("
|
|
240
|
-
table.add_column("
|
|
241
|
-
table.add_column("
|
|
260
|
+
table.add_column("pass", no_wrap=True)
|
|
261
|
+
table.add_column("tokens", no_wrap=True, justify="right")
|
|
262
|
+
table.add_column("time", no_wrap=True, justify="right")
|
|
263
|
+
table.add_column("cost", no_wrap=True, justify="right")
|
|
264
|
+
table.add_column("sample output", max_width=40)
|
|
265
|
+
table.add_column("runs", no_wrap=True)
|
|
242
266
|
for label, rs in groups.items():
|
|
243
267
|
n = len(rs)
|
|
244
268
|
ids = [(r["run_id"] or "-")[:8] for r in rs]
|
|
245
|
-
row = [label,
|
|
269
|
+
row = [label, f"{sum(r['status'] == 'ok' for r in rs)}/{n}"]
|
|
246
270
|
if expect:
|
|
247
271
|
passed = sum(bool(r["passed"]) for r in rs)
|
|
248
272
|
color = "green" if passed == n else ("yellow" if passed else "red")
|
|
249
273
|
row.append(f"[{color}]{passed}/{n}[/{color}]")
|
|
250
274
|
row += [f"{sum(r['tokens'] for r in rs) / n:.0f}",
|
|
251
275
|
f"{sum(r['latency_ms'] for r in rs) / n / 1000:.1f}s",
|
|
252
|
-
|
|
253
|
-
|
|
276
|
+
_avg_cost(rs),
|
|
277
|
+
_clip(str(rs[0]["result"]), 60 if console.width >= 100 else 30),
|
|
278
|
+
ids[0] + (f" +{n - 1}" if n > 1 else "")]
|
|
254
279
|
table.add_row(*row)
|
|
255
280
|
console.print(table)
|
|
256
281
|
for v in variants:
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Model prices for cost estimates, in USD per 1M tokens: (input, output).
|
|
2
|
+
|
|
3
|
+
Standard-tier list prices, checked October 2026. Prices change, so add or
|
|
4
|
+
override models in .agentfork/prices.json, for example:
|
|
5
|
+
|
|
6
|
+
{"gpt-4o-mini": [0.15, 0.60], "my-finetune": [3.0, 12.0]}
|
|
7
|
+
"""
|
|
8
|
+
import json, re, warnings
|
|
9
|
+
from . import store
|
|
10
|
+
|
|
11
|
+
PRICES = {
|
|
12
|
+
# OpenAI
|
|
13
|
+
"gpt-5": (1.25, 10.00), "gpt-5-mini": (0.25, 2.00), "gpt-5-nano": (0.05, 0.40),
|
|
14
|
+
"gpt-4.1": (2.00, 8.00), "gpt-4.1-mini": (0.40, 1.60), "gpt-4.1-nano": (0.10, 0.40),
|
|
15
|
+
"gpt-4o": (2.50, 10.00), "gpt-4o-mini": (0.15, 0.60),
|
|
16
|
+
"o3": (2.00, 8.00), "o3-mini": (1.10, 4.40), "o4-mini": (1.10, 4.40),
|
|
17
|
+
# Anthropic
|
|
18
|
+
"claude-fable-5-1": (10.00, 50.00), "claude-fable-5": (10.00, 50.00),
|
|
19
|
+
"claude-opus-5-5": (4.00, 20.00), "claude-opus-5": (5.00, 25.00),
|
|
20
|
+
"claude-opus-4-8": (5.00, 25.00), "claude-opus-4-7": (5.00, 25.00),
|
|
21
|
+
"claude-opus-4-6": (5.00, 25.00), "claude-opus-4-5": (5.00, 25.00),
|
|
22
|
+
"claude-opus-4-1": (15.00, 75.00), "claude-opus-4": (15.00, 75.00),
|
|
23
|
+
"claude-sonnet-5-5": (2.00, 10.00), "claude-sonnet-5": (2.00, 10.00),
|
|
24
|
+
"claude-sonnet-4-6": (3.00, 15.00), "claude-sonnet-4-5": (3.00, 15.00),
|
|
25
|
+
"claude-sonnet-4": (3.00, 15.00), "claude-3-7-sonnet": (3.00, 15.00),
|
|
26
|
+
"claude-haiku-5-5": (0.10, 0.50), "claude-haiku-4-5": (1.00, 5.00),
|
|
27
|
+
"claude-3-5-haiku": (0.80, 4.00),
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
# Dated snapshots and aliases cost the same as the base model: gpt-4o-mini-2024-07-18, claude-3-5-haiku-latest.
|
|
31
|
+
_SUFFIX = re.compile(r"-(\d{8}|\d{4}-\d{2}-\d{2}|latest)$")
|
|
32
|
+
|
|
33
|
+
def _user_prices():
|
|
34
|
+
path = store.db_path().parent / "prices.json"
|
|
35
|
+
try:
|
|
36
|
+
return {k.lower(): tuple(v) for k, v in json.loads(path.read_text()).items()}
|
|
37
|
+
except FileNotFoundError:
|
|
38
|
+
return {}
|
|
39
|
+
except (ValueError, TypeError, AttributeError) as e:
|
|
40
|
+
warnings.warn(f"agentfork: ignoring {path}: {e}")
|
|
41
|
+
return {}
|
|
42
|
+
|
|
43
|
+
def price(model):
|
|
44
|
+
"""(input, output) USD per 1M tokens, or None if the model is unknown."""
|
|
45
|
+
if not model:
|
|
46
|
+
return None
|
|
47
|
+
table = {**PRICES, **_user_prices()}
|
|
48
|
+
name = model.lower()
|
|
49
|
+
return table.get(name) or table.get(_SUFFIX.sub("", name))
|
|
50
|
+
|
|
51
|
+
def steps_cost(steps, model=None):
|
|
52
|
+
"""Total USD for the LLM steps, priced at `model` if given. None if a model or token count is unknown."""
|
|
53
|
+
total = 0.0
|
|
54
|
+
for s in steps:
|
|
55
|
+
if s["type"] != "llm":
|
|
56
|
+
continue
|
|
57
|
+
p = price(model or s["name"])
|
|
58
|
+
if p is None or s["tokens_in"] is None:
|
|
59
|
+
return None
|
|
60
|
+
total += (s["tokens_in"] * p[0] + (s["tokens_out"] or 0) * p[1]) / 1e6
|
|
61
|
+
return total
|
|
62
|
+
|
|
63
|
+
def unpriced(steps, model=None):
|
|
64
|
+
"""Models among the LLM steps that have no price."""
|
|
65
|
+
return sorted({model or s["name"] for s in steps if s["type"] == "llm" and price(model or s["name"]) is None})
|
|
66
|
+
|
|
67
|
+
def fmt(cost):
|
|
68
|
+
if cost is None:
|
|
69
|
+
return "-"
|
|
70
|
+
return f"${cost:.4f}" if cost < 0.01 else f"${cost:.2f}"
|
|
@@ -162,6 +162,8 @@ def trace(fn=None, *, name=None):
|
|
|
162
162
|
"parent_run_id": parent_run, "fork_step": replay.get("fork_step") if parent_run else None,
|
|
163
163
|
})
|
|
164
164
|
last_run_id = run_id
|
|
165
|
+
if replay:
|
|
166
|
+
replay["run_id"] = run_id
|
|
165
167
|
t_run, t_seq, t_parent = _run_id.set(run_id), _seq.set([0]), _parent_step.set(None)
|
|
166
168
|
status, output = "error", None
|
|
167
169
|
try:
|
|
@@ -170,6 +172,8 @@ def trace(fn=None, *, name=None):
|
|
|
170
172
|
return output
|
|
171
173
|
finally:
|
|
172
174
|
last_run_seq = _seq.get()[0]
|
|
175
|
+
if replay:
|
|
176
|
+
replay["seq"] = last_run_seq
|
|
173
177
|
_run_id.reset(t_run); _seq.reset(t_seq); _parent_step.reset(t_parent)
|
|
174
178
|
store.update_run(run_id, ended_at=time.time(), status=status, output_json=dumps(output))
|
|
175
179
|
print(f"[agentfork] saved run {run_id[:8]} ({status})")
|
|
@@ -182,20 +186,48 @@ def tool(fn):
|
|
|
182
186
|
return record_step("tool", fn.__name__, fn, args, kwargs)
|
|
183
187
|
return wrapper
|
|
184
188
|
|
|
189
|
+
class _RawResponse:
|
|
190
|
+
"""Minimal stand-in for the SDKs' raw responses, for callers that use .with_raw_response (LangChain)."""
|
|
191
|
+
def __init__(self, parsed):
|
|
192
|
+
self._parsed, self.headers = parsed, {}
|
|
193
|
+
def parse(self):
|
|
194
|
+
return self._parsed
|
|
195
|
+
|
|
196
|
+
class _WithRawResponse:
|
|
197
|
+
def __init__(self, create):
|
|
198
|
+
self.create = lambda *args, **kwargs: _RawResponse(create(*args, **kwargs))
|
|
199
|
+
|
|
200
|
+
def _patch(resource, provider):
|
|
201
|
+
original = resource.create
|
|
202
|
+
def create(*args, **kwargs):
|
|
203
|
+
return record_step("llm", kwargs.get("model", "llm"), original, args, kwargs, provider=provider)
|
|
204
|
+
resource.create = create
|
|
205
|
+
resource.with_raw_response = _WithRawResponse(create)
|
|
206
|
+
|
|
185
207
|
def wrap_openai(client):
|
|
186
208
|
from openai.types.chat import ChatCompletion
|
|
187
209
|
_LLM_DECODERS["openai"] = ChatCompletion.model_validate
|
|
188
|
-
|
|
189
|
-
def create(*args, **kwargs):
|
|
190
|
-
return record_step("llm", kwargs.get("model", "llm"), original, args, kwargs, provider="openai")
|
|
191
|
-
client.chat.completions.create = create
|
|
210
|
+
_patch(client.chat.completions, "openai")
|
|
192
211
|
return client
|
|
193
212
|
|
|
194
213
|
def wrap_anthropic(client):
|
|
195
214
|
from anthropic.types import Message
|
|
196
215
|
_LLM_DECODERS["anthropic"] = Message.model_validate
|
|
197
|
-
|
|
198
|
-
def create(*args, **kwargs):
|
|
199
|
-
return record_step("llm", kwargs.get("model", "llm"), original, args, kwargs, provider="anthropic")
|
|
200
|
-
client.messages.create = create
|
|
216
|
+
_patch(client.messages, "anthropic")
|
|
201
217
|
return client
|
|
218
|
+
|
|
219
|
+
def wrap_langchain(llm):
|
|
220
|
+
"""Record the calls a LangChain chat model makes, e.g. inside a LangGraph agent.
|
|
221
|
+
|
|
222
|
+
Works with ChatOpenAI and ChatAnthropic (non-streaming). Wrap the model before
|
|
223
|
+
passing it to the graph; models returned by bind_tools are handled too.
|
|
224
|
+
"""
|
|
225
|
+
model = getattr(llm, "bound", llm)
|
|
226
|
+
if getattr(model, "root_client", None) is not None:
|
|
227
|
+
wrap_openai(model.root_client)
|
|
228
|
+
return llm
|
|
229
|
+
client = getattr(model, "_client", None)
|
|
230
|
+
if client is not None and hasattr(client, "messages"):
|
|
231
|
+
wrap_anthropic(client)
|
|
232
|
+
return llm
|
|
233
|
+
raise TypeError(f"agentfork can't record {type(model).__name__}; use ChatOpenAI or ChatAnthropic")
|