agentcostoptimizer 0.2.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.
- agentcostoptimizer-0.2.0/PKG-INFO +167 -0
- agentcostoptimizer-0.2.0/README.md +150 -0
- agentcostoptimizer-0.2.0/agentcostoptimizer.egg-info/PKG-INFO +167 -0
- agentcostoptimizer-0.2.0/agentcostoptimizer.egg-info/SOURCES.txt +23 -0
- agentcostoptimizer-0.2.0/agentcostoptimizer.egg-info/dependency_links.txt +1 -0
- agentcostoptimizer-0.2.0/agentcostoptimizer.egg-info/entry_points.txt +2 -0
- agentcostoptimizer-0.2.0/agentcostoptimizer.egg-info/requires.txt +15 -0
- agentcostoptimizer-0.2.0/agentcostoptimizer.egg-info/top_level.txt +1 -0
- agentcostoptimizer-0.2.0/agentmeter/__init__.py +13 -0
- agentcostoptimizer-0.2.0/agentmeter/__main__.py +9 -0
- agentcostoptimizer-0.2.0/agentmeter/context.py +68 -0
- agentcostoptimizer-0.2.0/agentmeter/core.py +281 -0
- agentcostoptimizer-0.2.0/agentmeter/integrations/__init__.py +8 -0
- agentcostoptimizer-0.2.0/agentmeter/integrations/claude_agent.py +96 -0
- agentcostoptimizer-0.2.0/agentmeter/integrations/langchain.py +94 -0
- agentcostoptimizer-0.2.0/agentmeter/integrations/litellm.py +76 -0
- agentcostoptimizer-0.2.0/agentmeter/integrations/openai_agents.py +83 -0
- agentcostoptimizer-0.2.0/agentmeter/pricing.py +116 -0
- agentcostoptimizer-0.2.0/agentmeter/report.py +91 -0
- agentcostoptimizer-0.2.0/agentmeter/sinks.py +62 -0
- agentcostoptimizer-0.2.0/agentmeter/wrappers.py +93 -0
- agentcostoptimizer-0.2.0/pyproject.toml +24 -0
- agentcostoptimizer-0.2.0/setup.cfg +4 -0
- agentcostoptimizer-0.2.0/tests/test_agentmeter.py +271 -0
- agentcostoptimizer-0.2.0/tests/test_integrations.py +263 -0
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agentcostoptimizer
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Cost per successful task, budgets and context trimming for existing LLM agents
|
|
5
|
+
Requires-Python: >=3.9
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Provides-Extra: test
|
|
8
|
+
Requires-Dist: pytest; extra == "test"
|
|
9
|
+
Provides-Extra: langchain
|
|
10
|
+
Requires-Dist: langchain-core; extra == "langchain"
|
|
11
|
+
Provides-Extra: litellm
|
|
12
|
+
Requires-Dist: litellm; extra == "litellm"
|
|
13
|
+
Provides-Extra: openai-agents
|
|
14
|
+
Requires-Dist: openai-agents; extra == "openai-agents"
|
|
15
|
+
Provides-Extra: claude-agent
|
|
16
|
+
Requires-Dist: claude-agent-sdk>=0.2.137; extra == "claude-agent"
|
|
17
|
+
|
|
18
|
+
# agentmeter
|
|
19
|
+
|
|
20
|
+
Measure and cut the cost of an **existing** LLM agent. You don't rewrite anything: you wrap the client you already use, mark each task as a success or failure, and get **cost per successful task**.
|
|
21
|
+
|
|
22
|
+
```
|
|
23
|
+
task runs success per run PER SUCCESS steps cache tax
|
|
24
|
+
before 200 50% ₹28.3438 ₹56.6875 11.5 0% 86%
|
|
25
|
+
-> low cache hit rate: put system prompt + tools first and enable prompt caching
|
|
26
|
+
after 200 86% ₹4.6837 ₹5.4781 10.5 86% 89%
|
|
27
|
+
-> 10 run(s) hit the budget: look for loops
|
|
28
|
+
```
|
|
29
|
+
*(output of `examples/demo_offline.py`, simulated data)*
|
|
30
|
+
|
|
31
|
+
📖 **Full documentation:** start at [`docs/index.md`](docs/index.md). It covers getting started, concepts, a guide for each framework, the cost playbook, production setup, the API reference and troubleshooting. To browse it as a website, run `pip install mkdocs-material && mkdocs serve`.
|
|
32
|
+
|
|
33
|
+
## What it does
|
|
34
|
+
|
|
35
|
+
| Problem | agentmeter |
|
|
36
|
+
|---|---|
|
|
37
|
+
| You don't know what a task costs | Records every model call inside a run, priced by model |
|
|
38
|
+
| You pay to re-read history (the "context tax") | Reports `context_tax` and `cache_hit_rate` per run. `auto_cache=True` turns on Anthropic prompt caching |
|
|
39
|
+
| Tool results are huge | `slim(data, keep=[...])` sends only the fields the model needs |
|
|
40
|
+
| History keeps growing | `compact_messages()` swaps old turns for a summary |
|
|
41
|
+
| A stuck loop drains the bill | `Budget(max_steps, max_cost, max_tokens)` stops the run before the next call |
|
|
42
|
+
| Spend says nothing about value | `run.succeed()` / `run.fail()` → **cost per success** report |
|
|
43
|
+
|
|
44
|
+
No dependencies. Works with the **Anthropic** (`messages.create`, `beta.messages.create`) and **OpenAI** (`chat.completions.create`, `responses.create`) Python SDKs, both sync and async.
|
|
45
|
+
|
|
46
|
+
## Install
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
pip install agentcostoptimizer
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Add it to your agent (about 5 lines)
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
from agentmeter import Meter, Price, Budget, JsonlSink, ConsoleSink, slim
|
|
56
|
+
|
|
57
|
+
meter = Meter(
|
|
58
|
+
prices={"claude-sonnet-5-5": Price(input=250, output=1250)}, # your ₹ per 1M tokens
|
|
59
|
+
currency="₹",
|
|
60
|
+
budget=Budget(max_steps=15, max_cost=3.0),
|
|
61
|
+
sinks=[ConsoleSink(), JsonlSink("runs.jsonl")],
|
|
62
|
+
)
|
|
63
|
+
client = meter.wrap(anthropic.Anthropic(), auto_cache=True) # drop-in replacement
|
|
64
|
+
|
|
65
|
+
with meter.run("order_status", user_id="u42") as run:
|
|
66
|
+
... # your existing loop, unchanged, using `client`
|
|
67
|
+
run.succeed() # or run.fail("reason")
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Or use a decorator. A normal return counts as success and an exception as failure, or you can pass `success_check`:
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
meter = Meter(prices=..., success_check=lambda run, out: out.get("eta") is not None)
|
|
74
|
+
|
|
75
|
+
@meter.task("order_status")
|
|
76
|
+
def handle(question): ...
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Then:
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
python -m agentmeter report runs.jsonl # by task
|
|
83
|
+
python -m agentmeter report runs.jsonl --by model
|
|
84
|
+
python -m agentmeter report runs.jsonl --by metadata.user_id --json
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
See `examples/existing_agent.py` for a complete tool-use loop with the changes marked.
|
|
88
|
+
|
|
89
|
+
## Plug into an agent framework
|
|
90
|
+
|
|
91
|
+
Each adapter uses the framework's own hooks, so your agent code stays the same. Always wrap the run in `meter.run(...)` and mark the outcome.
|
|
92
|
+
|
|
93
|
+
| Framework | Hooks into | Budget stop |
|
|
94
|
+
|---|---|---|
|
|
95
|
+
| LangChain / LangGraph | callback handler (`on_chat_model_start` / `on_llm_end`) | **Yes**, raises `BudgetExceeded` |
|
|
96
|
+
| OpenAI Agents SDK | `RunHooks` (`on_llm_start` / `on_llm_end`) | **Yes**, raises `BudgetExceeded` |
|
|
97
|
+
| CrewAI and other LiteLLM-based frameworks | `litellm.callbacks` CustomLogger | Flags only. Use `max_iter` / `max_execution_time` |
|
|
98
|
+
| Claude Agent SDK | final `ResultMessage` (usage, `model_usage`, `num_turns`) | Use the SDK's `max_turns` / `max_budget_usd` |
|
|
99
|
+
|
|
100
|
+
**LangChain / LangGraph**
|
|
101
|
+
```python
|
|
102
|
+
from agentmeter.integrations.langchain import langchain_handler
|
|
103
|
+
handler = langchain_handler(meter)
|
|
104
|
+
|
|
105
|
+
with meter.run("research") as run:
|
|
106
|
+
out = graph.invoke(inputs, config={"callbacks": [handler]})
|
|
107
|
+
run.succeed() if out.get("answer") else run.fail("no answer")
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
**CrewAI (or anything that calls models through LiteLLM)**
|
|
111
|
+
```python
|
|
112
|
+
from agentmeter.integrations.litellm import install
|
|
113
|
+
install(meter) # once at startup
|
|
114
|
+
# install(meter, use_litellm_cost=True, usd_rate=84.0) to use LiteLLM's USD price table, converted to ₹
|
|
115
|
+
|
|
116
|
+
with meter.run("crew:market-research") as run:
|
|
117
|
+
result = crew.kickoff(inputs={"topic": "EV batteries"})
|
|
118
|
+
run.succeed()
|
|
119
|
+
```
|
|
120
|
+
Newer CrewAI versions call some providers natively instead of through LiteLLM. If a run shows `steps: 0`, use `meter.wrap()` on that client, or route through LiteLLM.
|
|
121
|
+
|
|
122
|
+
**OpenAI Agents SDK**
|
|
123
|
+
```python
|
|
124
|
+
from agentmeter.integrations.openai_agents import AgentMeterHooks
|
|
125
|
+
hooks = AgentMeterHooks(meter, inner=my_existing_hooks) # inner is optional
|
|
126
|
+
|
|
127
|
+
async with meter.run("triage") as run:
|
|
128
|
+
result = await Runner.run(agent, "Where is my order?", hooks=hooks, max_turns=10)
|
|
129
|
+
run.succeed()
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
**Claude Agent SDK** (Python SDK v0.2.137 or later)
|
|
133
|
+
```python
|
|
134
|
+
from agentmeter.integrations.claude_agent import metered
|
|
135
|
+
opts = ClaudeAgentOptions(max_turns=15, max_budget_usd=0.50)
|
|
136
|
+
|
|
137
|
+
async with meter.run("fix-bug") as run:
|
|
138
|
+
async for msg in metered(run, query(prompt="...", options=opts)):
|
|
139
|
+
... # your existing handling
|
|
140
|
+
if run.success is None:
|
|
141
|
+
run.succeed()
|
|
142
|
+
```
|
|
143
|
+
Error results mark the run as failed. If the SDK stops a run for hitting `max_turns` or `max_budget_usd`, the run is recorded as `stopped_by_budget`. To use the SDK's own cost estimate instead of your price table, pass `use_sdk_cost=True, usd_rate=84.0`.
|
|
144
|
+
|
|
145
|
+
**Threads:** some frameworks fire callbacks on worker threads. The adapters then fall back to the meter's only open run. If you run several tasks at once in threads, bind each one explicitly with `langchain_handler(meter, run=run)`, `AgentMeterHooks(meter, run=run)` or `make_logger(meter, run=run)`. Calls that can't be matched to a run are counted in `meter.unattributed_calls`.
|
|
146
|
+
|
|
147
|
+
## Reference
|
|
148
|
+
|
|
149
|
+
- **`Price(input, output, cache_read=None, cache_write=None)`**: per 1M tokens. If you leave out the cache prices, cache reads default to 0.1× input and cache writes to 1.25× input. Set them from your provider's price page. Model names match exactly first, then by longest prefix (`"claude-sonnet"` matches `claude-sonnet-5-5`). Models with no price are logged under `unpriced_models` and cost 0.
|
|
150
|
+
- **`Budget`**: checked *before* each call. When it's hit, `BudgetExceeded` is raised and the run is recorded as `stopped_by_budget`. Pass `Meter(swallow_budget_errors=True)` to end the `with` block quietly instead.
|
|
151
|
+
- **Run record fields**: `run_id, task, steps, models, input_tokens` (fresh), `cache_read_tokens, cache_write_tokens, output_tokens, cost, context_tax, cache_hit_rate, success, reason, stopped_by_budget, metadata, duration_s`.
|
|
152
|
+
- **Sinks**: `ConsoleSink`, `JsonlSink(path)`, `MemorySink`, `CallbackSink(fn)`. Use `CallbackSink` to forward to Langfuse, a database or a webhook. A failing sink never breaks the agent.
|
|
153
|
+
- **`context_tax`**: an estimate of the share of input tokens already sent in an earlier step of the same run. If it's high and the cache hit rate is low, you're paying full price to re-read history.
|
|
154
|
+
|
|
155
|
+
## Limits
|
|
156
|
+
|
|
157
|
+
- **Streaming:** calls with `stream=True` aren't recorded automatically. Call `run.record(usage_from_response(final_message), model=...)` yourself.
|
|
158
|
+
- **Frameworks:** LangChain, LlamaIndex, CrewAI and similar are covered when you can pass them the wrapped client. Otherwise, call `run.record(...)` from a callback.
|
|
159
|
+
- **`auto_cache`:** sends Anthropic's top-level `cache_control={"type": "ephemeral"}`. Your SDK version must support it. Set it off and add `cache_control` blocks yourself if not.
|
|
160
|
+
- **`compact_messages`:** expects the task as the first message (keep `system` separate). Compacting rewrites the cached prefix, so run it every N steps, not every step.
|
|
161
|
+
- **Run tracking:** the current run is tracked with `contextvars`, so it follows threads only when the context is copied. Use one `meter.run()` per worker.
|
|
162
|
+
|
|
163
|
+
## Tests
|
|
164
|
+
|
|
165
|
+
```bash
|
|
166
|
+
pytest -q # 33 tests, uses fake clients and stand-in framework modules, no API key needed
|
|
167
|
+
```
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
# agentmeter
|
|
2
|
+
|
|
3
|
+
Measure and cut the cost of an **existing** LLM agent. You don't rewrite anything: you wrap the client you already use, mark each task as a success or failure, and get **cost per successful task**.
|
|
4
|
+
|
|
5
|
+
```
|
|
6
|
+
task runs success per run PER SUCCESS steps cache tax
|
|
7
|
+
before 200 50% ₹28.3438 ₹56.6875 11.5 0% 86%
|
|
8
|
+
-> low cache hit rate: put system prompt + tools first and enable prompt caching
|
|
9
|
+
after 200 86% ₹4.6837 ₹5.4781 10.5 86% 89%
|
|
10
|
+
-> 10 run(s) hit the budget: look for loops
|
|
11
|
+
```
|
|
12
|
+
*(output of `examples/demo_offline.py`, simulated data)*
|
|
13
|
+
|
|
14
|
+
📖 **Full documentation:** start at [`docs/index.md`](docs/index.md). It covers getting started, concepts, a guide for each framework, the cost playbook, production setup, the API reference and troubleshooting. To browse it as a website, run `pip install mkdocs-material && mkdocs serve`.
|
|
15
|
+
|
|
16
|
+
## What it does
|
|
17
|
+
|
|
18
|
+
| Problem | agentmeter |
|
|
19
|
+
|---|---|
|
|
20
|
+
| You don't know what a task costs | Records every model call inside a run, priced by model |
|
|
21
|
+
| You pay to re-read history (the "context tax") | Reports `context_tax` and `cache_hit_rate` per run. `auto_cache=True` turns on Anthropic prompt caching |
|
|
22
|
+
| Tool results are huge | `slim(data, keep=[...])` sends only the fields the model needs |
|
|
23
|
+
| History keeps growing | `compact_messages()` swaps old turns for a summary |
|
|
24
|
+
| A stuck loop drains the bill | `Budget(max_steps, max_cost, max_tokens)` stops the run before the next call |
|
|
25
|
+
| Spend says nothing about value | `run.succeed()` / `run.fail()` → **cost per success** report |
|
|
26
|
+
|
|
27
|
+
No dependencies. Works with the **Anthropic** (`messages.create`, `beta.messages.create`) and **OpenAI** (`chat.completions.create`, `responses.create`) Python SDKs, both sync and async.
|
|
28
|
+
|
|
29
|
+
## Install
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install agentcostoptimizer
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Add it to your agent (about 5 lines)
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
from agentmeter import Meter, Price, Budget, JsonlSink, ConsoleSink, slim
|
|
39
|
+
|
|
40
|
+
meter = Meter(
|
|
41
|
+
prices={"claude-sonnet-5-5": Price(input=250, output=1250)}, # your ₹ per 1M tokens
|
|
42
|
+
currency="₹",
|
|
43
|
+
budget=Budget(max_steps=15, max_cost=3.0),
|
|
44
|
+
sinks=[ConsoleSink(), JsonlSink("runs.jsonl")],
|
|
45
|
+
)
|
|
46
|
+
client = meter.wrap(anthropic.Anthropic(), auto_cache=True) # drop-in replacement
|
|
47
|
+
|
|
48
|
+
with meter.run("order_status", user_id="u42") as run:
|
|
49
|
+
... # your existing loop, unchanged, using `client`
|
|
50
|
+
run.succeed() # or run.fail("reason")
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Or use a decorator. A normal return counts as success and an exception as failure, or you can pass `success_check`:
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
meter = Meter(prices=..., success_check=lambda run, out: out.get("eta") is not None)
|
|
57
|
+
|
|
58
|
+
@meter.task("order_status")
|
|
59
|
+
def handle(question): ...
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Then:
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
python -m agentmeter report runs.jsonl # by task
|
|
66
|
+
python -m agentmeter report runs.jsonl --by model
|
|
67
|
+
python -m agentmeter report runs.jsonl --by metadata.user_id --json
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
See `examples/existing_agent.py` for a complete tool-use loop with the changes marked.
|
|
71
|
+
|
|
72
|
+
## Plug into an agent framework
|
|
73
|
+
|
|
74
|
+
Each adapter uses the framework's own hooks, so your agent code stays the same. Always wrap the run in `meter.run(...)` and mark the outcome.
|
|
75
|
+
|
|
76
|
+
| Framework | Hooks into | Budget stop |
|
|
77
|
+
|---|---|---|
|
|
78
|
+
| LangChain / LangGraph | callback handler (`on_chat_model_start` / `on_llm_end`) | **Yes**, raises `BudgetExceeded` |
|
|
79
|
+
| OpenAI Agents SDK | `RunHooks` (`on_llm_start` / `on_llm_end`) | **Yes**, raises `BudgetExceeded` |
|
|
80
|
+
| CrewAI and other LiteLLM-based frameworks | `litellm.callbacks` CustomLogger | Flags only. Use `max_iter` / `max_execution_time` |
|
|
81
|
+
| Claude Agent SDK | final `ResultMessage` (usage, `model_usage`, `num_turns`) | Use the SDK's `max_turns` / `max_budget_usd` |
|
|
82
|
+
|
|
83
|
+
**LangChain / LangGraph**
|
|
84
|
+
```python
|
|
85
|
+
from agentmeter.integrations.langchain import langchain_handler
|
|
86
|
+
handler = langchain_handler(meter)
|
|
87
|
+
|
|
88
|
+
with meter.run("research") as run:
|
|
89
|
+
out = graph.invoke(inputs, config={"callbacks": [handler]})
|
|
90
|
+
run.succeed() if out.get("answer") else run.fail("no answer")
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
**CrewAI (or anything that calls models through LiteLLM)**
|
|
94
|
+
```python
|
|
95
|
+
from agentmeter.integrations.litellm import install
|
|
96
|
+
install(meter) # once at startup
|
|
97
|
+
# install(meter, use_litellm_cost=True, usd_rate=84.0) to use LiteLLM's USD price table, converted to ₹
|
|
98
|
+
|
|
99
|
+
with meter.run("crew:market-research") as run:
|
|
100
|
+
result = crew.kickoff(inputs={"topic": "EV batteries"})
|
|
101
|
+
run.succeed()
|
|
102
|
+
```
|
|
103
|
+
Newer CrewAI versions call some providers natively instead of through LiteLLM. If a run shows `steps: 0`, use `meter.wrap()` on that client, or route through LiteLLM.
|
|
104
|
+
|
|
105
|
+
**OpenAI Agents SDK**
|
|
106
|
+
```python
|
|
107
|
+
from agentmeter.integrations.openai_agents import AgentMeterHooks
|
|
108
|
+
hooks = AgentMeterHooks(meter, inner=my_existing_hooks) # inner is optional
|
|
109
|
+
|
|
110
|
+
async with meter.run("triage") as run:
|
|
111
|
+
result = await Runner.run(agent, "Where is my order?", hooks=hooks, max_turns=10)
|
|
112
|
+
run.succeed()
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
**Claude Agent SDK** (Python SDK v0.2.137 or later)
|
|
116
|
+
```python
|
|
117
|
+
from agentmeter.integrations.claude_agent import metered
|
|
118
|
+
opts = ClaudeAgentOptions(max_turns=15, max_budget_usd=0.50)
|
|
119
|
+
|
|
120
|
+
async with meter.run("fix-bug") as run:
|
|
121
|
+
async for msg in metered(run, query(prompt="...", options=opts)):
|
|
122
|
+
... # your existing handling
|
|
123
|
+
if run.success is None:
|
|
124
|
+
run.succeed()
|
|
125
|
+
```
|
|
126
|
+
Error results mark the run as failed. If the SDK stops a run for hitting `max_turns` or `max_budget_usd`, the run is recorded as `stopped_by_budget`. To use the SDK's own cost estimate instead of your price table, pass `use_sdk_cost=True, usd_rate=84.0`.
|
|
127
|
+
|
|
128
|
+
**Threads:** some frameworks fire callbacks on worker threads. The adapters then fall back to the meter's only open run. If you run several tasks at once in threads, bind each one explicitly with `langchain_handler(meter, run=run)`, `AgentMeterHooks(meter, run=run)` or `make_logger(meter, run=run)`. Calls that can't be matched to a run are counted in `meter.unattributed_calls`.
|
|
129
|
+
|
|
130
|
+
## Reference
|
|
131
|
+
|
|
132
|
+
- **`Price(input, output, cache_read=None, cache_write=None)`**: per 1M tokens. If you leave out the cache prices, cache reads default to 0.1× input and cache writes to 1.25× input. Set them from your provider's price page. Model names match exactly first, then by longest prefix (`"claude-sonnet"` matches `claude-sonnet-5-5`). Models with no price are logged under `unpriced_models` and cost 0.
|
|
133
|
+
- **`Budget`**: checked *before* each call. When it's hit, `BudgetExceeded` is raised and the run is recorded as `stopped_by_budget`. Pass `Meter(swallow_budget_errors=True)` to end the `with` block quietly instead.
|
|
134
|
+
- **Run record fields**: `run_id, task, steps, models, input_tokens` (fresh), `cache_read_tokens, cache_write_tokens, output_tokens, cost, context_tax, cache_hit_rate, success, reason, stopped_by_budget, metadata, duration_s`.
|
|
135
|
+
- **Sinks**: `ConsoleSink`, `JsonlSink(path)`, `MemorySink`, `CallbackSink(fn)`. Use `CallbackSink` to forward to Langfuse, a database or a webhook. A failing sink never breaks the agent.
|
|
136
|
+
- **`context_tax`**: an estimate of the share of input tokens already sent in an earlier step of the same run. If it's high and the cache hit rate is low, you're paying full price to re-read history.
|
|
137
|
+
|
|
138
|
+
## Limits
|
|
139
|
+
|
|
140
|
+
- **Streaming:** calls with `stream=True` aren't recorded automatically. Call `run.record(usage_from_response(final_message), model=...)` yourself.
|
|
141
|
+
- **Frameworks:** LangChain, LlamaIndex, CrewAI and similar are covered when you can pass them the wrapped client. Otherwise, call `run.record(...)` from a callback.
|
|
142
|
+
- **`auto_cache`:** sends Anthropic's top-level `cache_control={"type": "ephemeral"}`. Your SDK version must support it. Set it off and add `cache_control` blocks yourself if not.
|
|
143
|
+
- **`compact_messages`:** expects the task as the first message (keep `system` separate). Compacting rewrites the cached prefix, so run it every N steps, not every step.
|
|
144
|
+
- **Run tracking:** the current run is tracked with `contextvars`, so it follows threads only when the context is copied. Use one `meter.run()` per worker.
|
|
145
|
+
|
|
146
|
+
## Tests
|
|
147
|
+
|
|
148
|
+
```bash
|
|
149
|
+
pytest -q # 33 tests, uses fake clients and stand-in framework modules, no API key needed
|
|
150
|
+
```
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agentcostoptimizer
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Cost per successful task, budgets and context trimming for existing LLM agents
|
|
5
|
+
Requires-Python: >=3.9
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Provides-Extra: test
|
|
8
|
+
Requires-Dist: pytest; extra == "test"
|
|
9
|
+
Provides-Extra: langchain
|
|
10
|
+
Requires-Dist: langchain-core; extra == "langchain"
|
|
11
|
+
Provides-Extra: litellm
|
|
12
|
+
Requires-Dist: litellm; extra == "litellm"
|
|
13
|
+
Provides-Extra: openai-agents
|
|
14
|
+
Requires-Dist: openai-agents; extra == "openai-agents"
|
|
15
|
+
Provides-Extra: claude-agent
|
|
16
|
+
Requires-Dist: claude-agent-sdk>=0.2.137; extra == "claude-agent"
|
|
17
|
+
|
|
18
|
+
# agentmeter
|
|
19
|
+
|
|
20
|
+
Measure and cut the cost of an **existing** LLM agent. You don't rewrite anything: you wrap the client you already use, mark each task as a success or failure, and get **cost per successful task**.
|
|
21
|
+
|
|
22
|
+
```
|
|
23
|
+
task runs success per run PER SUCCESS steps cache tax
|
|
24
|
+
before 200 50% ₹28.3438 ₹56.6875 11.5 0% 86%
|
|
25
|
+
-> low cache hit rate: put system prompt + tools first and enable prompt caching
|
|
26
|
+
after 200 86% ₹4.6837 ₹5.4781 10.5 86% 89%
|
|
27
|
+
-> 10 run(s) hit the budget: look for loops
|
|
28
|
+
```
|
|
29
|
+
*(output of `examples/demo_offline.py`, simulated data)*
|
|
30
|
+
|
|
31
|
+
📖 **Full documentation:** start at [`docs/index.md`](docs/index.md). It covers getting started, concepts, a guide for each framework, the cost playbook, production setup, the API reference and troubleshooting. To browse it as a website, run `pip install mkdocs-material && mkdocs serve`.
|
|
32
|
+
|
|
33
|
+
## What it does
|
|
34
|
+
|
|
35
|
+
| Problem | agentmeter |
|
|
36
|
+
|---|---|
|
|
37
|
+
| You don't know what a task costs | Records every model call inside a run, priced by model |
|
|
38
|
+
| You pay to re-read history (the "context tax") | Reports `context_tax` and `cache_hit_rate` per run. `auto_cache=True` turns on Anthropic prompt caching |
|
|
39
|
+
| Tool results are huge | `slim(data, keep=[...])` sends only the fields the model needs |
|
|
40
|
+
| History keeps growing | `compact_messages()` swaps old turns for a summary |
|
|
41
|
+
| A stuck loop drains the bill | `Budget(max_steps, max_cost, max_tokens)` stops the run before the next call |
|
|
42
|
+
| Spend says nothing about value | `run.succeed()` / `run.fail()` → **cost per success** report |
|
|
43
|
+
|
|
44
|
+
No dependencies. Works with the **Anthropic** (`messages.create`, `beta.messages.create`) and **OpenAI** (`chat.completions.create`, `responses.create`) Python SDKs, both sync and async.
|
|
45
|
+
|
|
46
|
+
## Install
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
pip install agentcostoptimizer
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Add it to your agent (about 5 lines)
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
from agentmeter import Meter, Price, Budget, JsonlSink, ConsoleSink, slim
|
|
56
|
+
|
|
57
|
+
meter = Meter(
|
|
58
|
+
prices={"claude-sonnet-5-5": Price(input=250, output=1250)}, # your ₹ per 1M tokens
|
|
59
|
+
currency="₹",
|
|
60
|
+
budget=Budget(max_steps=15, max_cost=3.0),
|
|
61
|
+
sinks=[ConsoleSink(), JsonlSink("runs.jsonl")],
|
|
62
|
+
)
|
|
63
|
+
client = meter.wrap(anthropic.Anthropic(), auto_cache=True) # drop-in replacement
|
|
64
|
+
|
|
65
|
+
with meter.run("order_status", user_id="u42") as run:
|
|
66
|
+
... # your existing loop, unchanged, using `client`
|
|
67
|
+
run.succeed() # or run.fail("reason")
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Or use a decorator. A normal return counts as success and an exception as failure, or you can pass `success_check`:
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
meter = Meter(prices=..., success_check=lambda run, out: out.get("eta") is not None)
|
|
74
|
+
|
|
75
|
+
@meter.task("order_status")
|
|
76
|
+
def handle(question): ...
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Then:
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
python -m agentmeter report runs.jsonl # by task
|
|
83
|
+
python -m agentmeter report runs.jsonl --by model
|
|
84
|
+
python -m agentmeter report runs.jsonl --by metadata.user_id --json
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
See `examples/existing_agent.py` for a complete tool-use loop with the changes marked.
|
|
88
|
+
|
|
89
|
+
## Plug into an agent framework
|
|
90
|
+
|
|
91
|
+
Each adapter uses the framework's own hooks, so your agent code stays the same. Always wrap the run in `meter.run(...)` and mark the outcome.
|
|
92
|
+
|
|
93
|
+
| Framework | Hooks into | Budget stop |
|
|
94
|
+
|---|---|---|
|
|
95
|
+
| LangChain / LangGraph | callback handler (`on_chat_model_start` / `on_llm_end`) | **Yes**, raises `BudgetExceeded` |
|
|
96
|
+
| OpenAI Agents SDK | `RunHooks` (`on_llm_start` / `on_llm_end`) | **Yes**, raises `BudgetExceeded` |
|
|
97
|
+
| CrewAI and other LiteLLM-based frameworks | `litellm.callbacks` CustomLogger | Flags only. Use `max_iter` / `max_execution_time` |
|
|
98
|
+
| Claude Agent SDK | final `ResultMessage` (usage, `model_usage`, `num_turns`) | Use the SDK's `max_turns` / `max_budget_usd` |
|
|
99
|
+
|
|
100
|
+
**LangChain / LangGraph**
|
|
101
|
+
```python
|
|
102
|
+
from agentmeter.integrations.langchain import langchain_handler
|
|
103
|
+
handler = langchain_handler(meter)
|
|
104
|
+
|
|
105
|
+
with meter.run("research") as run:
|
|
106
|
+
out = graph.invoke(inputs, config={"callbacks": [handler]})
|
|
107
|
+
run.succeed() if out.get("answer") else run.fail("no answer")
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
**CrewAI (or anything that calls models through LiteLLM)**
|
|
111
|
+
```python
|
|
112
|
+
from agentmeter.integrations.litellm import install
|
|
113
|
+
install(meter) # once at startup
|
|
114
|
+
# install(meter, use_litellm_cost=True, usd_rate=84.0) to use LiteLLM's USD price table, converted to ₹
|
|
115
|
+
|
|
116
|
+
with meter.run("crew:market-research") as run:
|
|
117
|
+
result = crew.kickoff(inputs={"topic": "EV batteries"})
|
|
118
|
+
run.succeed()
|
|
119
|
+
```
|
|
120
|
+
Newer CrewAI versions call some providers natively instead of through LiteLLM. If a run shows `steps: 0`, use `meter.wrap()` on that client, or route through LiteLLM.
|
|
121
|
+
|
|
122
|
+
**OpenAI Agents SDK**
|
|
123
|
+
```python
|
|
124
|
+
from agentmeter.integrations.openai_agents import AgentMeterHooks
|
|
125
|
+
hooks = AgentMeterHooks(meter, inner=my_existing_hooks) # inner is optional
|
|
126
|
+
|
|
127
|
+
async with meter.run("triage") as run:
|
|
128
|
+
result = await Runner.run(agent, "Where is my order?", hooks=hooks, max_turns=10)
|
|
129
|
+
run.succeed()
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
**Claude Agent SDK** (Python SDK v0.2.137 or later)
|
|
133
|
+
```python
|
|
134
|
+
from agentmeter.integrations.claude_agent import metered
|
|
135
|
+
opts = ClaudeAgentOptions(max_turns=15, max_budget_usd=0.50)
|
|
136
|
+
|
|
137
|
+
async with meter.run("fix-bug") as run:
|
|
138
|
+
async for msg in metered(run, query(prompt="...", options=opts)):
|
|
139
|
+
... # your existing handling
|
|
140
|
+
if run.success is None:
|
|
141
|
+
run.succeed()
|
|
142
|
+
```
|
|
143
|
+
Error results mark the run as failed. If the SDK stops a run for hitting `max_turns` or `max_budget_usd`, the run is recorded as `stopped_by_budget`. To use the SDK's own cost estimate instead of your price table, pass `use_sdk_cost=True, usd_rate=84.0`.
|
|
144
|
+
|
|
145
|
+
**Threads:** some frameworks fire callbacks on worker threads. The adapters then fall back to the meter's only open run. If you run several tasks at once in threads, bind each one explicitly with `langchain_handler(meter, run=run)`, `AgentMeterHooks(meter, run=run)` or `make_logger(meter, run=run)`. Calls that can't be matched to a run are counted in `meter.unattributed_calls`.
|
|
146
|
+
|
|
147
|
+
## Reference
|
|
148
|
+
|
|
149
|
+
- **`Price(input, output, cache_read=None, cache_write=None)`**: per 1M tokens. If you leave out the cache prices, cache reads default to 0.1× input and cache writes to 1.25× input. Set them from your provider's price page. Model names match exactly first, then by longest prefix (`"claude-sonnet"` matches `claude-sonnet-5-5`). Models with no price are logged under `unpriced_models` and cost 0.
|
|
150
|
+
- **`Budget`**: checked *before* each call. When it's hit, `BudgetExceeded` is raised and the run is recorded as `stopped_by_budget`. Pass `Meter(swallow_budget_errors=True)` to end the `with` block quietly instead.
|
|
151
|
+
- **Run record fields**: `run_id, task, steps, models, input_tokens` (fresh), `cache_read_tokens, cache_write_tokens, output_tokens, cost, context_tax, cache_hit_rate, success, reason, stopped_by_budget, metadata, duration_s`.
|
|
152
|
+
- **Sinks**: `ConsoleSink`, `JsonlSink(path)`, `MemorySink`, `CallbackSink(fn)`. Use `CallbackSink` to forward to Langfuse, a database or a webhook. A failing sink never breaks the agent.
|
|
153
|
+
- **`context_tax`**: an estimate of the share of input tokens already sent in an earlier step of the same run. If it's high and the cache hit rate is low, you're paying full price to re-read history.
|
|
154
|
+
|
|
155
|
+
## Limits
|
|
156
|
+
|
|
157
|
+
- **Streaming:** calls with `stream=True` aren't recorded automatically. Call `run.record(usage_from_response(final_message), model=...)` yourself.
|
|
158
|
+
- **Frameworks:** LangChain, LlamaIndex, CrewAI and similar are covered when you can pass them the wrapped client. Otherwise, call `run.record(...)` from a callback.
|
|
159
|
+
- **`auto_cache`:** sends Anthropic's top-level `cache_control={"type": "ephemeral"}`. Your SDK version must support it. Set it off and add `cache_control` blocks yourself if not.
|
|
160
|
+
- **`compact_messages`:** expects the task as the first message (keep `system` separate). Compacting rewrites the cached prefix, so run it every N steps, not every step.
|
|
161
|
+
- **Run tracking:** the current run is tracked with `contextvars`, so it follows threads only when the context is copied. Use one `meter.run()` per worker.
|
|
162
|
+
|
|
163
|
+
## Tests
|
|
164
|
+
|
|
165
|
+
```bash
|
|
166
|
+
pytest -q # 33 tests, uses fake clients and stand-in framework modules, no API key needed
|
|
167
|
+
```
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
agentcostoptimizer.egg-info/PKG-INFO
|
|
4
|
+
agentcostoptimizer.egg-info/SOURCES.txt
|
|
5
|
+
agentcostoptimizer.egg-info/dependency_links.txt
|
|
6
|
+
agentcostoptimizer.egg-info/entry_points.txt
|
|
7
|
+
agentcostoptimizer.egg-info/requires.txt
|
|
8
|
+
agentcostoptimizer.egg-info/top_level.txt
|
|
9
|
+
agentmeter/__init__.py
|
|
10
|
+
agentmeter/__main__.py
|
|
11
|
+
agentmeter/context.py
|
|
12
|
+
agentmeter/core.py
|
|
13
|
+
agentmeter/pricing.py
|
|
14
|
+
agentmeter/report.py
|
|
15
|
+
agentmeter/sinks.py
|
|
16
|
+
agentmeter/wrappers.py
|
|
17
|
+
agentmeter/integrations/__init__.py
|
|
18
|
+
agentmeter/integrations/claude_agent.py
|
|
19
|
+
agentmeter/integrations/langchain.py
|
|
20
|
+
agentmeter/integrations/litellm.py
|
|
21
|
+
agentmeter/integrations/openai_agents.py
|
|
22
|
+
tests/test_agentmeter.py
|
|
23
|
+
tests/test_integrations.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
agentmeter
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""agentmeter: cost per successful task for existing LLM agents."""
|
|
2
|
+
from .pricing import Price, PriceBook, Usage, usage_from_response
|
|
3
|
+
from .core import Meter, Run, Budget, BudgetExceeded
|
|
4
|
+
from .sinks import ConsoleSink, JsonlSink, CallbackSink, MemorySink
|
|
5
|
+
from .context import slim, compact_messages
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"Meter", "Run", "Budget", "BudgetExceeded",
|
|
9
|
+
"Price", "PriceBook", "Usage", "usage_from_response",
|
|
10
|
+
"ConsoleSink", "JsonlSink", "CallbackSink", "MemorySink",
|
|
11
|
+
"slim", "compact_messages",
|
|
12
|
+
]
|
|
13
|
+
__version__ = "0.2.0"
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Helpers that shrink what the agent re-sends every step."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
from typing import Any, Callable, Iterable
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def slim(data: Any, keep: Iterable[str], max_chars: int | None = 2000) -> str:
|
|
9
|
+
"""Keep only the fields the model needs from a tool result.
|
|
10
|
+
|
|
11
|
+
slim(order_api_response, keep=["status", "eta", "carrier"])
|
|
12
|
+
-> '{"status": "shipped", "eta": "2026-11-26", "carrier": "BlueDart"}'
|
|
13
|
+
|
|
14
|
+
Dotted paths are supported ("shipment.eta"). Missing fields are skipped.
|
|
15
|
+
"""
|
|
16
|
+
out: dict[str, Any] = {}
|
|
17
|
+
for path in keep:
|
|
18
|
+
cur = data
|
|
19
|
+
for part in path.split("."):
|
|
20
|
+
if isinstance(cur, dict) and part in cur:
|
|
21
|
+
cur = cur[part]
|
|
22
|
+
elif isinstance(cur, list) and part.isdigit() and int(part) < len(cur):
|
|
23
|
+
cur = cur[int(part)]
|
|
24
|
+
else:
|
|
25
|
+
cur = None
|
|
26
|
+
break
|
|
27
|
+
if cur is not None:
|
|
28
|
+
out[path] = cur
|
|
29
|
+
text = json.dumps(out, ensure_ascii=False, default=str)
|
|
30
|
+
if max_chars and len(text) > max_chars:
|
|
31
|
+
text = text[: max_chars - 15] + "...[truncated]"
|
|
32
|
+
return text
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def compact_messages(
|
|
36
|
+
messages: list[dict],
|
|
37
|
+
keep_last: int = 6,
|
|
38
|
+
summarize: Callable[[list[dict]], str] | None = None,
|
|
39
|
+
min_messages: int = 12,
|
|
40
|
+
) -> list[dict]:
|
|
41
|
+
"""Replace older history with one summary message, keeping the first user
|
|
42
|
+
message (the task) and the last `keep_last` messages verbatim.
|
|
43
|
+
|
|
44
|
+
`summarize` gets the dropped messages and returns a short text. Use a cheap
|
|
45
|
+
model for it. Without one, a plain note listing what was dropped is used.
|
|
46
|
+
|
|
47
|
+
The cut is moved so it never separates a tool call from its result.
|
|
48
|
+
Note: compaction changes the cached prefix, so do it every N steps, not every step.
|
|
49
|
+
"""
|
|
50
|
+
if len(messages) < min_messages or len(messages) <= keep_last + 1:
|
|
51
|
+
return messages
|
|
52
|
+
head, rest = messages[0], messages[1:]
|
|
53
|
+
cut = max(len(rest) - keep_last, 0)
|
|
54
|
+
# The kept tail must start on an assistant turn, so it follows the task message
|
|
55
|
+
# correctly and never begins with a tool result whose call was dropped.
|
|
56
|
+
while cut < len(rest) and rest[cut].get("role") != "assistant":
|
|
57
|
+
cut += 1
|
|
58
|
+
dropped, tail = rest[:cut], rest[cut:]
|
|
59
|
+
if not dropped or not tail:
|
|
60
|
+
return messages
|
|
61
|
+
summary = summarize(dropped) if summarize else f"{len(dropped)} earlier messages omitted."
|
|
62
|
+
note = f"[Summary of earlier steps]\n{summary}"
|
|
63
|
+
c = head.get("content")
|
|
64
|
+
if isinstance(c, list):
|
|
65
|
+
new_head = {**head, "content": list(c) + [{"type": "text", "text": note}]}
|
|
66
|
+
else:
|
|
67
|
+
new_head = {**head, "content": f"{c}\n\n{note}"}
|
|
68
|
+
return [new_head] + tail
|