agentfork-cli 0.1.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.
Files changed (33) hide show
  1. agentfork_cli-0.3.0/PKG-INFO +196 -0
  2. agentfork_cli-0.3.0/README.md +160 -0
  3. agentfork_cli-0.3.0/examples/langgraph_refund_agent.py +33 -0
  4. {agentfork_cli-0.1.0 → agentfork_cli-0.3.0}/pyproject.toml +7 -3
  5. agentfork_cli-0.3.0/src/agentfork/__init__.py +3 -0
  6. {agentfork_cli-0.1.0 → agentfork_cli-0.3.0}/src/agentfork/cli.py +59 -17
  7. agentfork_cli-0.3.0/src/agentfork/pricing.py +70 -0
  8. {agentfork_cli-0.1.0 → agentfork_cli-0.3.0}/src/agentfork/recorder.py +40 -8
  9. agentfork_cli-0.3.0/src/agentfork/replay.py +155 -0
  10. agentfork_cli-0.3.0/src/agentfork/server.py +156 -0
  11. {agentfork_cli-0.1.0 → agentfork_cli-0.3.0}/src/agentfork/store.py +8 -1
  12. agentfork_cli-0.3.0/src/agentfork/ui.html +752 -0
  13. agentfork_cli-0.3.0/tests/test_cost.py +64 -0
  14. agentfork_cli-0.3.0/tests/test_langgraph.py +65 -0
  15. agentfork_cli-0.3.0/tests/test_sweep.py +73 -0
  16. agentfork_cli-0.3.0/tests/test_ui.py +42 -0
  17. agentfork_cli-0.1.0/PKG-INFO +0 -125
  18. agentfork_cli-0.1.0/README.md +0 -97
  19. agentfork_cli-0.1.0/src/agentfork/__init__.py +0 -3
  20. agentfork_cli-0.1.0/src/agentfork/replay.py +0 -109
  21. agentfork_cli-0.1.0/tests/test_sweep.py +0 -37
  22. {agentfork_cli-0.1.0 → agentfork_cli-0.3.0}/.gitignore +0 -0
  23. {agentfork_cli-0.1.0 → agentfork_cli-0.3.0}/LICENSE +0 -0
  24. {agentfork_cli-0.1.0 → agentfork_cli-0.3.0}/examples/demo_agent.py +0 -0
  25. {agentfork_cli-0.1.0 → agentfork_cli-0.3.0}/examples/demo_agent_claude.py +0 -0
  26. {agentfork_cli-0.1.0 → agentfork_cli-0.3.0}/examples/refund_agent.py +0 -0
  27. {agentfork_cli-0.1.0 → agentfork_cli-0.3.0}/examples/refund_agent_cents.py +0 -0
  28. {agentfork_cli-0.1.0 → agentfork_cli-0.3.0}/tests/test_anthropic.py +0 -0
  29. {agentfork_cli-0.1.0 → agentfork_cli-0.3.0}/tests/test_cli.py +0 -0
  30. {agentfork_cli-0.1.0 → agentfork_cli-0.3.0}/tests/test_fork.py +0 -0
  31. {agentfork_cli-0.1.0 → agentfork_cli-0.3.0}/tests/test_recorder.py +0 -0
  32. {agentfork_cli-0.1.0 → agentfork_cli-0.3.0}/tests/test_save_test.py +0 -0
  33. {agentfork_cli-0.1.0 → agentfork_cli-0.3.0}/tests/test_smoke.py +0 -0
@@ -0,0 +1,196 @@
1
+ Metadata-Version: 2.5
2
+ Name: agentfork-cli
3
+ Version: 0.3.0
4
+ Summary: Fork your LLM agent at any step and sweep prompts, models or tool results to find what fixes it.
5
+ Project-URL: Homepage, https://github.com/bimal1023/agentfork
6
+ Project-URL: Issues, https://github.com/bimal1023/agentfork/issues
7
+ Author: Bimal Kumal
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: agents,anthropic,debugging,langgraph,llm,openai,replay,testing
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Software Development :: Debuggers
15
+ Classifier: Topic :: Software Development :: Testing
16
+ Requires-Python: >=3.9
17
+ Requires-Dist: rich
18
+ Requires-Dist: typer
19
+ Provides-Extra: anthropic
20
+ Requires-Dist: anthropic; extra == 'anthropic'
21
+ Provides-Extra: dev
22
+ Requires-Dist: anthropic; extra == 'dev'
23
+ Requires-Dist: fastapi; extra == 'dev'
24
+ Requires-Dist: httpx; extra == 'dev'
25
+ Requires-Dist: langchain-openai; extra == 'dev'
26
+ Requires-Dist: langgraph; extra == 'dev'
27
+ Requires-Dist: openai; extra == 'dev'
28
+ Requires-Dist: pytest; extra == 'dev'
29
+ Requires-Dist: uvicorn; extra == 'dev'
30
+ Provides-Extra: openai
31
+ Requires-Dist: openai; extra == 'openai'
32
+ Provides-Extra: ui
33
+ Requires-Dist: fastapi; extra == 'ui'
34
+ Requires-Dist: uvicorn; extra == 'ui'
35
+ Description-Content-Type: text/markdown
36
+
37
+ # agentfork
38
+
39
+ [![tests](https://github.com/bimal1023/agentfork/actions/workflows/tests.yml/badge.svg)](https://github.com/bimal1023/agentfork/actions/workflows/tests.yml)
40
+
41
+ **Fork your LLM agent at any step, then sweep prompts, models or tool results to find what actually fixes it.**
42
+
43
+ ![agentfork demo](https://raw.githubusercontent.com/bimal1023/agentfork/main/docs/demo.gif)
44
+
45
+ When an agent misbehaves at step 3, the usual loop is: tweak the prompt, re-run everything, eyeball one output, repeat. That is slow, costs tokens on steps that didn't change, and one lucky run proves nothing. agentfork records every LLM and tool call, replays earlier steps from cache, and runs **many variants of one step, several times each**, so you get pass rates instead of anecdotes.
46
+
47
+ Everything runs locally. No account, no server, no data leaves your machine.
48
+
49
+ ## The headline example
50
+
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?
52
+
53
+ ```text
54
+ $ agentfork sweep 543da612 --step 3 --repeat 3 --expect "49.99" --model gpt-4o-mini,gpt-4o
55
+ Estimated cost: about $0.0050
56
+
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...
61
+ ```
62
+
63
+ A bigger model costs 15x more per run and doesn't fix it. One sentence in the prompt does:
64
+
65
+ ```text
66
+ $ agentfork sweep 543da612 --step 3 --repeat 3 --expect "49.99" \
67
+ --system "You are a support agent. Look up the order, then refund the full order amount in USD." \
68
+ --system "... Order amounts from the API are in cents; divide by 100 before refunding."
69
+ Estimated cost: about $0.0006
70
+
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...
75
+ ```
76
+
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.
78
+
79
+ ## Quickstart
80
+
81
+ ```bash
82
+ pip install "agentfork-cli[openai]" # or agentfork-cli[anthropic]
83
+ ```
84
+
85
+ Add three things to your agent:
86
+
87
+ ```python
88
+ from openai import OpenAI
89
+ from agentfork import trace, tool, wrap_openai
90
+
91
+ client = wrap_openai(OpenAI()) # records every LLM call (wrap_anthropic for Claude)
92
+
93
+ @tool # records every tool call
94
+ def lookup_order(order_id): ...
95
+
96
+ @trace # one run = one call of your agent
97
+ def run_agent(question): ...
98
+ ```
99
+
100
+ Run your agent as usual. Each run is saved to `.agentfork/traces.db`.
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
+
129
+ ## Commands
130
+
131
+ | Command | What it does |
132
+ | --- | --- |
133
+ | `agentfork list` | Recent runs with steps, tokens, duration and fork lineage |
134
+ | `agentfork show <id> [--full]` | A run as a step tree, with optional full JSON |
135
+ | `agentfork fork <id> --step N --output/--model/--system ...` | Re-run from step N with one change; earlier steps come from cache |
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 |
137
+ | `agentfork diff <a> <b>` | Compare two runs step by step |
138
+ | `agentfork save-test <id>` | Save a run as a pytest test that replays from cache in CI with no API key |
139
+ | `agentfork ui [--port N]` | Open the local web UI to browse, fork, sweep and compare runs |
140
+
141
+ ## Web UI
142
+
143
+ Prefer clicking to typing? The same fork, sweep and diff are available in a local web UI.
144
+
145
+ ```bash
146
+ pip install "agentfork-cli[openai,ui]"
147
+ agentfork ui # opens http://127.0.0.1:8000
148
+ ```
149
+
150
+ Start it from the folder you ran your agent in, since runs are saved to `.agentfork/` there. The server only listens on your own machine.
151
+
152
+ 1. **Find the step that went wrong.** Pick a run on the left. Its timeline shows each LLM and tool call in plain words, such as `Decided to call issue_refund(amount_usd=4999)`. Click a step to see its full input and output.
153
+ 2. **Try a change.** On that step, use another model, edit the system prompt, or fake a tool's result. Earlier steps replay from cache, and the new run appears under the original.
154
+ 3. **Test several.** Enter a few changes, how many times to run each, and text the final output must contain. You get a pass rate per change, with the original run as the baseline:
155
+
156
+ ```text
157
+ Change Passed Example output
158
+ Original ○ 0/1 I have processed a refund of $4,999.00...
159
+ Change 1 ●●● 3/3 I have processed a refund of $49.99...
160
+ Change 2 ○○○ 0/3 I have processed a refund of $4,999.00...
161
+ ```
162
+
163
+ 4. **Compare.** Tick two runs to see them side by side, with the first step where they differ highlighted.
164
+
165
+ ## How it works
166
+
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.
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.
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.
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.
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
+
180
+ ## Related work
181
+
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.
183
+
184
+ ## Roadmap
185
+
186
+ - [x] Recorder, CLI viewer, fork, diff, snapshot tests
187
+ - [x] OpenAI and Anthropic support
188
+ - [x] Sweep with repeats and pass rates
189
+ - [x] Local web UI
190
+ - [x] Cost estimates per variant
191
+ - [x] Parallel sweeps
192
+ - [x] LangGraph integration
193
+
194
+ ## License
195
+
196
+ MIT
@@ -0,0 +1,160 @@
1
+ # agentfork
2
+
3
+ [![tests](https://github.com/bimal1023/agentfork/actions/workflows/tests.yml/badge.svg)](https://github.com/bimal1023/agentfork/actions/workflows/tests.yml)
4
+
5
+ **Fork your LLM agent at any step, then sweep prompts, models or tool results to find what actually fixes it.**
6
+
7
+ ![agentfork demo](https://raw.githubusercontent.com/bimal1023/agentfork/main/docs/demo.gif)
8
+
9
+ When an agent misbehaves at step 3, the usual loop is: tweak the prompt, re-run everything, eyeball one output, repeat. That is slow, costs tokens on steps that didn't change, and one lucky run proves nothing. agentfork records every LLM and tool call, replays earlier steps from cache, and runs **many variants of one step, several times each**, so you get pass rates instead of anecdotes.
10
+
11
+ Everything runs locally. No account, no server, no data leaves your machine.
12
+
13
+ ## The headline example
14
+
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
+
17
+ ```text
18
+ $ agentfork sweep 543da612 --step 3 --repeat 3 --expect "49.99" --model gpt-4o-mini,gpt-4o
19
+ Estimated cost: about $0.0050
20
+
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...
25
+ ```
26
+
27
+ A bigger model costs 15x more per run and doesn't fix it. One sentence in the prompt does:
28
+
29
+ ```text
30
+ $ agentfork sweep 543da612 --step 3 --repeat 3 --expect "49.99" \
31
+ --system "You are a support agent. Look up the order, then refund the full order amount in USD." \
32
+ --system "... Order amounts from the API are in cents; divide by 100 before refunding."
33
+ Estimated cost: about $0.0006
34
+
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...
39
+ ```
40
+
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.
42
+
43
+ ## Quickstart
44
+
45
+ ```bash
46
+ pip install "agentfork-cli[openai]" # or agentfork-cli[anthropic]
47
+ ```
48
+
49
+ Add three things to your agent:
50
+
51
+ ```python
52
+ from openai import OpenAI
53
+ from agentfork import trace, tool, wrap_openai
54
+
55
+ client = wrap_openai(OpenAI()) # records every LLM call (wrap_anthropic for Claude)
56
+
57
+ @tool # records every tool call
58
+ def lookup_order(order_id): ...
59
+
60
+ @trace # one run = one call of your agent
61
+ def run_agent(question): ...
62
+ ```
63
+
64
+ Run your agent as usual. Each run is saved to `.agentfork/traces.db`.
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
+
93
+ ## Commands
94
+
95
+ | Command | What it does |
96
+ | --- | --- |
97
+ | `agentfork list` | Recent runs with steps, tokens, duration and fork lineage |
98
+ | `agentfork show <id> [--full]` | A run as a step tree, with optional full JSON |
99
+ | `agentfork fork <id> --step N --output/--model/--system ...` | Re-run from step N with one change; earlier steps come from cache |
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 |
101
+ | `agentfork diff <a> <b>` | Compare two runs step by step |
102
+ | `agentfork save-test <id>` | Save a run as a pytest test that replays from cache in CI with no API key |
103
+ | `agentfork ui [--port N]` | Open the local web UI to browse, fork, sweep and compare runs |
104
+
105
+ ## Web UI
106
+
107
+ Prefer clicking to typing? The same fork, sweep and diff are available in a local web UI.
108
+
109
+ ```bash
110
+ pip install "agentfork-cli[openai,ui]"
111
+ agentfork ui # opens http://127.0.0.1:8000
112
+ ```
113
+
114
+ Start it from the folder you ran your agent in, since runs are saved to `.agentfork/` there. The server only listens on your own machine.
115
+
116
+ 1. **Find the step that went wrong.** Pick a run on the left. Its timeline shows each LLM and tool call in plain words, such as `Decided to call issue_refund(amount_usd=4999)`. Click a step to see its full input and output.
117
+ 2. **Try a change.** On that step, use another model, edit the system prompt, or fake a tool's result. Earlier steps replay from cache, and the new run appears under the original.
118
+ 3. **Test several.** Enter a few changes, how many times to run each, and text the final output must contain. You get a pass rate per change, with the original run as the baseline:
119
+
120
+ ```text
121
+ Change Passed Example output
122
+ Original ○ 0/1 I have processed a refund of $4,999.00...
123
+ Change 1 ●●● 3/3 I have processed a refund of $49.99...
124
+ Change 2 ○○○ 0/3 I have processed a refund of $4,999.00...
125
+ ```
126
+
127
+ 4. **Compare.** Tick two runs to see them side by side, with the first step where they differ highlighted.
128
+
129
+ ## How it works
130
+
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.
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.
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.
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.
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
+
144
+ ## Related work
145
+
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.
147
+
148
+ ## Roadmap
149
+
150
+ - [x] Recorder, CLI viewer, fork, diff, snapshot tests
151
+ - [x] OpenAI and Anthropic support
152
+ - [x] Sweep with repeats and pass rates
153
+ - [x] Local web UI
154
+ - [x] Cost estimates per variant
155
+ - [x] Parallel sweeps
156
+ - [x] LangGraph integration
157
+
158
+ ## License
159
+
160
+ MIT
@@ -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.1.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",
@@ -19,7 +19,8 @@ dependencies = ["typer", "rich"]
19
19
  [project.optional-dependencies]
20
20
  openai = ["openai"]
21
21
  anthropic = ["anthropic"]
22
- dev = ["pytest", "openai", "anthropic"]
22
+ ui = ["fastapi", "uvicorn"]
23
+ dev = ["pytest", "openai", "anthropic", "fastapi", "uvicorn", "httpx", "langgraph", "langchain-openai"]
23
24
 
24
25
  [project.urls]
25
26
  Homepage = "https://github.com/bimal1023/agentfork"
@@ -34,3 +35,6 @@ build-backend = "hatchling.build"
34
35
 
35
36
  [tool.hatch.build.targets.sdist]
36
37
  exclude = ["docs/", ".github/", "tests/agentfork/"]
38
+
39
+ [tool.hatch.build.targets.wheel]
40
+ packages = ["src/agentfork"]
@@ -0,0 +1,3 @@
1
+ from .recorder import trace, tool, wrap_anthropic, wrap_langchain, wrap_openai
2
+
3
+ __all__ = ["trace", "tool", "wrap_openai", "wrap_anthropic", "wrap_langchain"]
@@ -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 store.get_steps(run["id"]):
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[/bold]")
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, on_result=progress)
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,31 +252,50 @@ 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]})", show_lines=True)
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("runs", no_wrap=True, min_width=4)
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, min_width=4)
238
- table.add_column("avg tokens", no_wrap=True, min_width=6)
239
- table.add_column("avg time", no_wrap=True, min_width=6)
240
- table.add_column("sample output", max_width=36, overflow="ellipsis", no_wrap=True)
241
- table.add_column("run ids", no_wrap=True)
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, str(n), f"{sum(r['status'] == 'ok' for r in rs)}/{n}"]
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
- str(rs[0]["result"]),
253
- ", ".join(ids[:2]) + (f" +{len(ids) - 2}" if len(ids) > 2 else "")]
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:
257
282
  key, value = next(iter(v.items()))
258
283
  if key != "model":
259
284
  console.print(f"[bold]{labels[id(v)]}[/bold]: {value}")
285
+
286
+ @app.command()
287
+ def ui(port: int = typer.Option(8000, "--port", help="Port for the local web UI."),
288
+ no_browser: bool = typer.Option(False, "--no-browser", help="Don't open a browser.")):
289
+ """Open the local web UI: runs, timelines, fork, sweep and compare."""
290
+ try:
291
+ import uvicorn
292
+ from .server import app as web_app
293
+ except ImportError:
294
+ console.print('[red]The UI needs extra packages: pip install "agentfork-cli[ui]"[/red]')
295
+ raise typer.Exit(1)
296
+ url = f"http://127.0.0.1:{port}"
297
+ console.print(f"[green]agentfork UI running at {url}[/green] (Ctrl+C to stop)")
298
+ if not no_browser:
299
+ import threading, webbrowser
300
+ threading.Timer(1.0, lambda: webbrowser.open(url)).start()
301
+ uvicorn.run(web_app, host="127.0.0.1", port=port, log_level="warning")
@@ -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}"