agentcostoptimizer 0.2.0__py3-none-any.whl

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.
@@ -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,18 @@
1
+ agentmeter/__init__.py,sha256=W9_xi9XDoUBtNYR4wUQBTLOtZYieT15R9peGZ8Sr29s,536
2
+ agentmeter/__main__.py,sha256=AvgSj8q8g3op13mXjBUULAEw875RGJtpoRn6DDaZdOc,165
3
+ agentmeter/context.py,sha256=NfYfNOMtsq5BLwLlIw3VsGa0uhDiWFC9USdyKTrsb1Q,2700
4
+ agentmeter/core.py,sha256=b_rG1zKPMOg39I8cU40YuaYM2ksv9sDMNxmScTBFZKY,9893
5
+ agentmeter/pricing.py,sha256=nxjhFNNhoe3D2NcQvFN5hyPp3hoNptr4geIdtrkfOg4,4333
6
+ agentmeter/report.py,sha256=IldshiAkOddnlv8Zx4jnRdv7GGqwL7reZ-SouYHeLl0,3699
7
+ agentmeter/sinks.py,sha256=A9Niack9fsRYqZsVABDfiX1urHmOOy2miUOfiynI834,1763
8
+ agentmeter/wrappers.py,sha256=viBzozASjZdAyqMMe5OnP0yLlhR05F1z0ZzJGXiVTDo,3068
9
+ agentmeter/integrations/__init__.py,sha256=aLaISupJjK9OegaJiMirNv0JGJUiRdy6ai8zyVHYA-s,455
10
+ agentmeter/integrations/claude_agent.py,sha256=4E_uXpiT1SHokdlZGw2X2hlTtnP8T-lIRfumjHUzDOE,4058
11
+ agentmeter/integrations/langchain.py,sha256=qHN9Zg1YyxHaq4fUVRIA3irkwn5tgqWG2Z2MhIvlmMQ,3846
12
+ agentmeter/integrations/litellm.py,sha256=582rTfhX7NJhfSaIc6fvizlEDRrwCibPZK7ZunsYYnU,3279
13
+ agentmeter/integrations/openai_agents.py,sha256=s8rkrG3hqbgkoTIU2CFiZUVOS8YKGqMzBVSUF_tiEb0,2921
14
+ agentcostoptimizer-0.2.0.dist-info/METADATA,sha256=XsHOkHrvoAAq3YgMTCGlGA7mbmOozuiM_bmLSCbEM8E,8903
15
+ agentcostoptimizer-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
16
+ agentcostoptimizer-0.2.0.dist-info/entry_points.txt,sha256=7MW3jaPBud3e4Lo8o1uxHA0K5xjj_E7W5E7Nzz0D2ds,54
17
+ agentcostoptimizer-0.2.0.dist-info/top_level.txt,sha256=F-0V_DCIYy2w0WSlleyuM4xK7QSPGkD3bmUJWoeuFi0,11
18
+ agentcostoptimizer-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ agentmeter = agentmeter.report:main
@@ -0,0 +1 @@
1
+ agentmeter
agentmeter/__init__.py ADDED
@@ -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"
agentmeter/__main__.py ADDED
@@ -0,0 +1,9 @@
1
+ import sys
2
+
3
+ from .report import main
4
+
5
+ if __name__ == "__main__":
6
+ args = sys.argv[1:]
7
+ if args and args[0] == "report":
8
+ args = args[1:]
9
+ main(args)
agentmeter/context.py ADDED
@@ -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
agentmeter/core.py ADDED
@@ -0,0 +1,281 @@
1
+ """Runs, budgets and the Meter."""
2
+ from __future__ import annotations
3
+
4
+ import contextvars
5
+ import functools
6
+ import inspect
7
+ import threading
8
+ import time
9
+ import uuid
10
+ from dataclasses import dataclass, field
11
+ from typing import Any, Callable
12
+
13
+ from .pricing import PriceBook, Price, Usage
14
+ from .sinks import Sink, ConsoleSink
15
+
16
+ _current: contextvars.ContextVar["Run | None"] = contextvars.ContextVar("agentmeter_run", default=None)
17
+
18
+
19
+ class BudgetExceeded(RuntimeError):
20
+ """Raised before a model call when the run has hit its step or cost limit."""
21
+
22
+
23
+ @dataclass
24
+ class Budget:
25
+ max_steps: int | None = None # model calls per run
26
+ max_cost: float | None = None # currency units per run
27
+ max_tokens: int | None = None # total input + output tokens per run
28
+
29
+
30
+ @dataclass
31
+ class Step:
32
+ model: str | None
33
+ usage: Usage
34
+ cost: float
35
+ latency_s: float
36
+
37
+
38
+ @dataclass(eq=False)
39
+ class Run:
40
+ task: str
41
+ meter: "Meter"
42
+ metadata: dict = field(default_factory=dict)
43
+ run_id: str = field(default_factory=lambda: uuid.uuid4().hex)
44
+ steps: list[Step] = field(default_factory=list)
45
+ started: float = field(default_factory=time.time)
46
+ success: bool | None = None
47
+ reason: str | None = None
48
+ stopped_by_budget: bool = False
49
+ unpriced_models: set = field(default_factory=set)
50
+
51
+ # ---- totals -------------------------------------------------------
52
+ @property
53
+ def usage(self) -> Usage:
54
+ total = Usage()
55
+ for s in self.steps:
56
+ total = total + s.usage
57
+ return total
58
+
59
+ @property
60
+ def cost(self) -> float:
61
+ return sum(s.cost for s in self.steps)
62
+
63
+ @property
64
+ def context_tax(self) -> float:
65
+ """Share of input tokens that were already sent in an earlier step of
66
+ this run (estimated as: everything except the growth since the last step)."""
67
+ total_in = sum(s.usage.total_input for s in self.steps)
68
+ if not total_in:
69
+ return 0.0
70
+ new, prev = 0, 0
71
+ for s in self.steps:
72
+ cur = s.usage.total_input
73
+ new += cur if prev == 0 else max(cur - prev, 0)
74
+ prev = cur + s.usage.output_tokens
75
+ return max(0.0, 1 - new / total_in)
76
+
77
+ @property
78
+ def cache_hit_rate(self) -> float:
79
+ u = self.usage
80
+ return u.cache_read_tokens / u.total_input if u.total_input else 0.0
81
+
82
+ # ---- outcome ------------------------------------------------------
83
+ def succeed(self, note: str | None = None):
84
+ self.success, self.reason = True, note
85
+
86
+ def fail(self, reason: str | None = None):
87
+ self.success, self.reason = False, reason
88
+
89
+ # ---- recording ----------------------------------------------------
90
+ def over_budget(self) -> str | None:
91
+ """Return which limit is hit (e.g. 'max_steps=15'), or None."""
92
+ b = self.meter.budget
93
+ if not b:
94
+ return None
95
+ u = self.usage
96
+ if b.max_steps is not None and len(self.steps) >= b.max_steps:
97
+ return f"max_steps={b.max_steps}"
98
+ if b.max_cost is not None and self.cost >= b.max_cost:
99
+ return f"max_cost={b.max_cost}"
100
+ if b.max_tokens is not None and u.total_input + u.output_tokens >= b.max_tokens:
101
+ return f"max_tokens={b.max_tokens}"
102
+ return None
103
+
104
+ def check_budget(self):
105
+ hit = self.over_budget()
106
+ if hit:
107
+ self.stopped_by_budget = True
108
+ raise BudgetExceeded(f"run {self.run_id[:8]} ({self.task}) stopped: {hit}")
109
+
110
+ def record(self, usage: Usage, model: str | None = None, latency_s: float = 0.0,
111
+ cost: float | None = None):
112
+ """Record one model call. Called automatically by wrapped clients and
113
+ framework adapters; call it yourself for streaming or unsupported clients.
114
+ Pass `cost` to use a cost computed elsewhere instead of your price table."""
115
+ if cost is None:
116
+ price: Price | None = self.meter.prices.for_model(model)
117
+ if price is None:
118
+ self.unpriced_models.add(model)
119
+ cost = 0.0
120
+ else:
121
+ cost = price.cost(usage)
122
+ self.steps.append(Step(model, usage, cost, latency_s))
123
+
124
+ def to_dict(self) -> dict:
125
+ u = self.usage
126
+ return {
127
+ "run_id": self.run_id,
128
+ "task": self.task,
129
+ "started": self.started,
130
+ "duration_s": round(time.time() - self.started, 3),
131
+ "steps": len(self.steps),
132
+ "models": sorted({s.model for s in self.steps if s.model}),
133
+ "input_tokens": u.input_tokens,
134
+ "cache_read_tokens": u.cache_read_tokens,
135
+ "cache_write_tokens": u.cache_write_tokens,
136
+ "output_tokens": u.output_tokens,
137
+ "cost": round(self.cost, 6),
138
+ "currency": self.meter.currency,
139
+ "context_tax": round(self.context_tax, 4),
140
+ "cache_hit_rate": round(self.cache_hit_rate, 4),
141
+ "success": self.success,
142
+ "reason": self.reason,
143
+ "stopped_by_budget": self.stopped_by_budget,
144
+ "unpriced_models": sorted(m for m in self.unpriced_models if m),
145
+ "metadata": self.metadata,
146
+ }
147
+
148
+
149
+ class _RunCtx:
150
+ def __init__(self, run: Run):
151
+ self.run, self._token = run, None
152
+
153
+ def _enter(self):
154
+ self._token = _current.set(self.run)
155
+ with self.run.meter._lock:
156
+ self.run.meter._active.append(self.run)
157
+ return self.run
158
+
159
+ def _exit(self, exc):
160
+ r = self.run
161
+ if exc is not None and r.success is None:
162
+ r.fail("budget_exceeded" if isinstance(exc, BudgetExceeded) else f"{type(exc).__name__}: {exc}")
163
+ _current.reset(self._token)
164
+ with r.meter._lock:
165
+ if r in r.meter._active:
166
+ r.meter._active.remove(r)
167
+ r.meter._emit(r)
168
+ if isinstance(exc, BudgetExceeded) and r.meter.swallow_budget_errors:
169
+ return True
170
+ return False
171
+
172
+ def __enter__(self):
173
+ return self._enter()
174
+
175
+ def __exit__(self, et, exc, tb):
176
+ return self._exit(exc)
177
+
178
+ async def __aenter__(self):
179
+ return self._enter()
180
+
181
+ async def __aexit__(self, et, exc, tb):
182
+ return self._exit(exc)
183
+
184
+
185
+ class Meter:
186
+ """Entry point.
187
+
188
+ meter = Meter(prices={"claude-sonnet": Price(250, 1250)}, currency="₹",
189
+ budget=Budget(max_steps=20, max_cost=5), sinks=[JsonlSink("runs.jsonl")])
190
+ client = meter.wrap(anthropic.Anthropic())
191
+ with meter.run("order_status") as run:
192
+ ... # your existing agent loop, unchanged
193
+ run.succeed()
194
+ """
195
+
196
+ def __init__(
197
+ self,
198
+ prices: dict[str, Price] | PriceBook | None = None,
199
+ *,
200
+ default_price: Price | None = None,
201
+ currency: str = "₹",
202
+ budget: Budget | None = None,
203
+ sinks: list[Sink] | None = None,
204
+ success_check: Callable[[Run, Any], bool] | None = None,
205
+ swallow_budget_errors: bool = False,
206
+ ):
207
+ self.prices = prices if isinstance(prices, PriceBook) else PriceBook(prices or {}, default_price)
208
+ self.currency = currency
209
+ self.budget = budget
210
+ self.sinks = sinks if sinks is not None else [ConsoleSink()]
211
+ self.success_check = success_check
212
+ self.swallow_budget_errors = swallow_budget_errors
213
+ self._active: list[Run] = []
214
+ self._lock = threading.Lock()
215
+ self.unattributed_calls = 0
216
+
217
+ # ---- runs ---------------------------------------------------------
218
+ def run(self, task: str, **metadata) -> _RunCtx:
219
+ return _RunCtx(Run(task=task, meter=self, metadata=metadata))
220
+
221
+ @staticmethod
222
+ def current() -> Run | None:
223
+ return _current.get()
224
+
225
+ def active_run(self) -> Run | None:
226
+ """Run for the current context; if a framework fires its callback on
227
+ another thread, fall back to the only run this meter has open.
228
+ With several runs open on other threads the call can't be attributed:
229
+ pass the run to the adapter explicitly in that case."""
230
+ r = _current.get()
231
+ if r is not None and r.meter is self:
232
+ return r
233
+ with self._lock:
234
+ if len(self._active) == 1:
235
+ return self._active[0]
236
+ return None
237
+
238
+ def task(self, name: str | None = None, **metadata):
239
+ """Decorator. If success_check is set it is applied to the return value;
240
+ otherwise a normal return counts as success and an exception as failure."""
241
+ def deco(fn):
242
+ tname = name or fn.__name__
243
+
244
+ if inspect.iscoroutinefunction(fn):
245
+ @functools.wraps(fn)
246
+ async def aw(*a, **k):
247
+ async with self.run(tname, **metadata) as r:
248
+ out = await fn(*a, **k)
249
+ self._judge(r, out)
250
+ return out
251
+ return aw
252
+
253
+ @functools.wraps(fn)
254
+ def w(*a, **k):
255
+ with self.run(tname, **metadata) as r:
256
+ out = fn(*a, **k)
257
+ self._judge(r, out)
258
+ return out
259
+ return w
260
+ return deco
261
+
262
+ def _judge(self, r: Run, out):
263
+ if r.success is not None:
264
+ return
265
+ if self.success_check:
266
+ r.succeed() if self.success_check(r, out) else r.fail("success_check returned False")
267
+ else:
268
+ r.succeed()
269
+
270
+ def _emit(self, r: Run):
271
+ rec = r.to_dict()
272
+ for s in self.sinks:
273
+ try:
274
+ s.write(rec)
275
+ except Exception: # a broken sink must never break the agent
276
+ pass
277
+
278
+ # ---- clients ------------------------------------------------------
279
+ def wrap(self, client, *, auto_cache: bool = False):
280
+ from .wrappers import wrap_client
281
+ return wrap_client(client, self, auto_cache=auto_cache)
@@ -0,0 +1,8 @@
1
+ """Framework adapters. Each one imports its framework lazily, so agentmeter
2
+ itself keeps zero dependencies.
3
+
4
+ LangChain / LangGraph agentmeter.integrations.langchain.langchain_handler(meter)
5
+ LiteLLM / CrewAI agentmeter.integrations.litellm.install(meter)
6
+ OpenAI Agents SDK agentmeter.integrations.openai_agents.AgentMeterHooks(meter)
7
+ Claude Agent SDK agentmeter.integrations.claude_agent.metered_query(meter, ...)
8
+ """
@@ -0,0 +1,96 @@
1
+ """Claude Agent SDK.
2
+
3
+ from claude_agent_sdk import query, ClaudeAgentOptions
4
+ from agentmeter.integrations.claude_agent import metered
5
+
6
+ opts = ClaudeAgentOptions(max_turns=15, max_budget_usd=0.50) # the SDK's own hard stop
7
+ async with meter.run("fix-bug") as run:
8
+ async for msg in metered(run, query(prompt="...", options=opts)):
9
+ ... # your existing message handling, unchanged
10
+ if run.success is None:
11
+ run.succeed()
12
+
13
+ The SDK runs the agent loop itself, so agentmeter reads the final
14
+ ResultMessage: token usage (per model when `model_usage` is present, which also
15
+ counts subagents) and turn count. Error results mark the run failed, and
16
+ budget/turn-limit results set stopped_by_budget. Budgets are enforced by the
17
+ SDK's max_turns / max_budget_usd options, not by agentmeter.
18
+
19
+ The SDK's own estimate is total_cost_usd. Use it instead of your Price table
20
+ with `use_sdk_cost=True, usd_rate=84.0` (₹ per $).
21
+ Needs a Python SDK version that yields ResultMessage (v0.2.137 or later).
22
+ """
23
+ from __future__ import annotations
24
+
25
+ from typing import AsyncIterator
26
+
27
+ from ..core import Run
28
+ from ..pricing import Usage
29
+
30
+ _BUDGET_SUBTYPES = {"error_max_budget_usd", "error_max_turns"}
31
+
32
+
33
+ def _g(d, *names, default=0):
34
+ for n in names:
35
+ v = d.get(n) if isinstance(d, dict) else getattr(d, n, None)
36
+ if v is not None:
37
+ return v
38
+ return default
39
+
40
+
41
+ def _usage(d) -> Usage:
42
+ return Usage(
43
+ input_tokens=int(_g(d, "input_tokens", "inputTokens")),
44
+ output_tokens=int(_g(d, "output_tokens", "outputTokens")),
45
+ cache_read_tokens=int(_g(d, "cache_read_input_tokens", "cacheReadInputTokens")),
46
+ cache_write_tokens=int(_g(d, "cache_creation_input_tokens", "cacheCreationInputTokens")),
47
+ )
48
+
49
+
50
+ def record_result(run: Run, msg, *, use_sdk_cost: bool = False, usd_rate: float = 1.0,
51
+ model: str | None = None):
52
+ """Record a ResultMessage into `run`. Called for you by `metered`."""
53
+ turns = int(_g(msg, "num_turns", default=1)) or 1
54
+ model_usage = _g(msg, "model_usage", default=None)
55
+ sdk_cost = _g(msg, "total_cost_usd", default=None)
56
+
57
+ entries = []
58
+ if model_usage:
59
+ for name, mu in dict(model_usage).items():
60
+ c = _g(mu, "cost_usd", "costUSD", default=None)
61
+ entries.append((name, _usage(mu), c))
62
+ else:
63
+ entries.append((model, _usage(_g(msg, "usage", default={}) or {}), sdk_cost))
64
+
65
+ # Spread over num_turns steps so step counts and averages stay meaningful.
66
+ for name, u, c in entries:
67
+ share = lambda x: x // turns # noqa: E731
68
+ for i in range(turns):
69
+ last = i == turns - 1
70
+ part = Usage(
71
+ u.input_tokens - share(u.input_tokens) * (turns - 1) if last else share(u.input_tokens),
72
+ u.output_tokens - share(u.output_tokens) * (turns - 1) if last else share(u.output_tokens),
73
+ u.cache_read_tokens - share(u.cache_read_tokens) * (turns - 1) if last else share(u.cache_read_tokens),
74
+ u.cache_write_tokens - share(u.cache_write_tokens) * (turns - 1) if last else share(u.cache_write_tokens),
75
+ )
76
+ cost = None
77
+ if use_sdk_cost and c is not None:
78
+ cost = float(c) * usd_rate / turns
79
+ run.record(part, model=name, cost=cost)
80
+ if len(entries) > 1:
81
+ turns = 1 # only spread the first model's usage over turns; others count once
82
+
83
+ subtype = _g(msg, "subtype", default=None)
84
+ if _g(msg, "is_error", default=False) or (subtype and subtype != "success"):
85
+ if subtype in _BUDGET_SUBTYPES:
86
+ run.stopped_by_budget = True
87
+ if run.success is None:
88
+ run.fail(subtype or "error")
89
+
90
+
91
+ async def metered(run: Run, messages: AsyncIterator, **opts) -> AsyncIterator:
92
+ """Pass every message through unchanged; record the ResultMessage."""
93
+ async for m in messages:
94
+ if type(m).__name__ == "ResultMessage":
95
+ record_result(run, m, **opts)
96
+ yield m
@@ -0,0 +1,94 @@
1
+ """LangChain and LangGraph.
2
+
3
+ from agentmeter.integrations.langchain import langchain_handler
4
+
5
+ handler = langchain_handler(meter)
6
+ with meter.run("research") as run:
7
+ out = graph.invoke(inputs, config={"callbacks": [handler]})
8
+ run.succeed() if out.get("answer") else run.fail("no answer")
9
+
10
+ Works for any chat model or LLM that LangChain calls (ChatAnthropic, ChatOpenAI,
11
+ ChatBedrock ...). Budgets are enforced: the handler raises BudgetExceeded
12
+ from on_chat_model_start, which stops the chain or graph.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import time
17
+ from typing import Any
18
+
19
+ from ..core import BudgetExceeded, Meter, Run
20
+ from ..pricing import Usage
21
+
22
+
23
+ def _usage_from_llm_result(response) -> tuple[Usage, str | None]:
24
+ total, model = Usage(), None
25
+ for gen_list in getattr(response, "generations", None) or []:
26
+ for g in gen_list:
27
+ msg = getattr(g, "message", None)
28
+ um = getattr(msg, "usage_metadata", None) if msg is not None else None
29
+ meta = getattr(msg, "response_metadata", None) or {}
30
+ model = model or meta.get("model_name") or meta.get("model")
31
+ if um:
32
+ # LangChain's input_tokens is the full prompt, cache included.
33
+ det = um.get("input_token_details") or {}
34
+ cr, cw = int(det.get("cache_read") or 0), int(det.get("cache_creation") or 0)
35
+ total = total + Usage(max(int(um.get("input_tokens", 0)) - cr - cw, 0),
36
+ int(um.get("output_tokens", 0)), cr, cw)
37
+ if total.total_input == 0 and total.output_tokens == 0:
38
+ # Older / non-chat models report usage in llm_output instead.
39
+ lo = getattr(response, "llm_output", None) or {}
40
+ tu = lo.get("token_usage") or lo.get("usage") or {}
41
+ if tu:
42
+ prompt = int(tu.get("prompt_tokens", tu.get("input_tokens", 0)))
43
+ total = Usage(prompt, int(tu.get("completion_tokens", tu.get("output_tokens", 0))))
44
+ model = model or lo.get("model_name") or lo.get("model")
45
+ return total, model
46
+
47
+
48
+ def langchain_handler(meter: Meter, run: Run | None = None):
49
+ """Return a LangChain callback handler bound to `meter` (and optionally to a
50
+ specific run; otherwise it uses the run that is open when the call starts)."""
51
+ try:
52
+ from langchain_core.callbacks import BaseCallbackHandler
53
+ except ImportError as e: # pragma: no cover
54
+ raise ImportError("pip install langchain-core to use the LangChain adapter") from e
55
+
56
+ class AgentMeterCallback(BaseCallbackHandler):
57
+ raise_error = True # let BudgetExceeded stop the chain/graph
58
+
59
+ def __init__(self):
60
+ super().__init__()
61
+ self._starts: dict[Any, tuple[Run | None, float]] = {}
62
+
63
+ def _run(self) -> Run | None:
64
+ r = run or meter.active_run()
65
+ if r is None:
66
+ meter.unattributed_calls += 1
67
+ return r
68
+
69
+ def _start(self, run_id):
70
+ r = self._run()
71
+ self._starts[run_id] = (r, time.time())
72
+ if r is not None:
73
+ r.check_budget()
74
+
75
+ def on_chat_model_start(self, serialized, messages, *, run_id, **kw):
76
+ self._start(run_id)
77
+
78
+ def on_llm_start(self, serialized, prompts, *, run_id, **kw):
79
+ self._start(run_id)
80
+
81
+ def on_llm_end(self, response, *, run_id, **kw):
82
+ r, t0 = self._starts.pop(run_id, (None, time.time()))
83
+ r = r or self._run()
84
+ if r is not None:
85
+ usage, model = _usage_from_llm_result(response)
86
+ r.record(usage, model=model, latency_s=time.time() - t0)
87
+
88
+ def on_llm_error(self, error, *, run_id, **kw):
89
+ self._starts.pop(run_id, None)
90
+
91
+ return AgentMeterCallback()
92
+
93
+
94
+ __all__ = ["langchain_handler", "BudgetExceeded"]
@@ -0,0 +1,76 @@
1
+ """LiteLLM, and the frameworks that call models through it (CrewAI's LiteLLM
2
+ path, AutoGen's LiteLLM client, smolagents' LiteLLMModel, and others).
3
+
4
+ from agentmeter.integrations.litellm import install
5
+ install(meter) # registers a litellm callback once
6
+
7
+ with meter.run("crew:research") as run:
8
+ result = crew.kickoff(inputs={...})
9
+ run.succeed()
10
+
11
+ LiteLLM runs success callbacks after the response, sometimes on another thread,
12
+ and catches errors raised inside callbacks. So this adapter *records* and flags
13
+ budget overruns (`stopped_by_budget` stays False, `over_budget` goes in metadata)
14
+ but cannot stop a call. Use your framework's own limit for the hard stop:
15
+ CrewAI `Agent(max_iter=..., max_execution_time=...)`, AutoGen `max_turns`, etc.
16
+
17
+ Note: newer CrewAI versions call OpenAI / Anthropic natively for some models
18
+ instead of through LiteLLM. If no steps are recorded, wrap that client instead
19
+ (meter.wrap) or force LiteLLM routing in your LLM config.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ from ..core import Meter, Run
24
+ from ..pricing import usage_from_response
25
+
26
+
27
+ def _record(meter: Meter, run: Run | None, kwargs: dict, response_obj, start_time, end_time,
28
+ use_litellm_cost: bool, usd_rate: float):
29
+ r = run or meter.active_run()
30
+ if r is None:
31
+ meter.unattributed_calls += 1
32
+ return
33
+ try:
34
+ latency = (end_time - start_time).total_seconds()
35
+ except Exception:
36
+ latency = 0.0
37
+ model = getattr(response_obj, "model", None) or kwargs.get("model")
38
+ cost = None
39
+ if use_litellm_cost and kwargs.get("response_cost") is not None:
40
+ cost = float(kwargs["response_cost"]) * usd_rate
41
+ r.record(usage_from_response(response_obj), model=model, latency_s=latency, cost=cost)
42
+ hit = r.over_budget()
43
+ if hit:
44
+ r.metadata["over_budget"] = hit
45
+
46
+
47
+ def make_logger(meter: Meter, run: Run | None = None, *, use_litellm_cost: bool = False,
48
+ usd_rate: float = 1.0):
49
+ """Build the CustomLogger. use_litellm_cost=True uses LiteLLM's own USD price
50
+ table times `usd_rate` (e.g. 84.0 for ₹) instead of your Price entries."""
51
+ try:
52
+ from litellm.integrations.custom_logger import CustomLogger
53
+ except ImportError as e: # pragma: no cover
54
+ raise ImportError("pip install litellm to use the LiteLLM adapter") from e
55
+
56
+ class AgentMeterLogger(CustomLogger):
57
+ def log_success_event(self, kwargs, response_obj, start_time, end_time):
58
+ _record(meter, run, kwargs, response_obj, start_time, end_time, use_litellm_cost, usd_rate)
59
+
60
+ async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
61
+ _record(meter, run, kwargs, response_obj, start_time, end_time, use_litellm_cost, usd_rate)
62
+
63
+ return AgentMeterLogger()
64
+
65
+
66
+ def install(meter: Meter, **opts):
67
+ """Create the logger and append it to litellm.callbacks (idempotent per meter)."""
68
+ import litellm
69
+
70
+ for cb in list(getattr(litellm, "callbacks", None) or []):
71
+ if getattr(cb, "_agentmeter", None) is meter:
72
+ return cb
73
+ logger = make_logger(meter, **opts)
74
+ logger._agentmeter = meter
75
+ litellm.callbacks = list(getattr(litellm, "callbacks", None) or []) + [logger]
76
+ return logger
@@ -0,0 +1,83 @@
1
+ """OpenAI Agents SDK.
2
+
3
+ from agentmeter.integrations.openai_agents import AgentMeterHooks
4
+
5
+ hooks = AgentMeterHooks(meter)
6
+ with meter.run("triage") as run:
7
+ result = await Runner.run(agent, "Where is my order?", hooks=hooks, max_turns=10)
8
+ run.succeed()
9
+
10
+ Records every model response (including handoffs to other agents) and stops
11
+ the run with BudgetExceeded from on_llm_start when a limit is hit.
12
+ Already using RunHooks? Pass yours as `inner=` and it is still called.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import time
17
+ from types import SimpleNamespace
18
+
19
+ from ..core import Meter, Run
20
+ from ..pricing import usage_from_response
21
+
22
+
23
+ def _model_name(agent) -> str | None:
24
+ m = getattr(agent, "model", None)
25
+ if m is None or isinstance(m, str):
26
+ return m
27
+ return getattr(m, "model", None) or getattr(m, "model_name", None)
28
+
29
+
30
+ try:
31
+ from agents import RunHooks as _Base
32
+ except ImportError: # SDK not installed: plain base so the module still imports
33
+ class _Base: # type: ignore[no-redef]
34
+ pass
35
+
36
+
37
+ class AgentMeterHooks(_Base):
38
+ def __init__(self, meter: Meter, run: Run | None = None, inner=None):
39
+ super().__init__()
40
+ self.meter, self.run, self.inner = meter, run, inner
41
+ self._t0: float | None = None
42
+
43
+ def _run(self):
44
+ r = self.run or self.meter.active_run()
45
+ if r is None:
46
+ self.meter.unattributed_calls += 1
47
+ return r
48
+
49
+ async def _inner(self, name, *a):
50
+ fn = getattr(self.inner, name, None)
51
+ if fn:
52
+ await fn(*a)
53
+
54
+ async def on_llm_start(self, context, agent, system_prompt, input_items):
55
+ r = self._run()
56
+ if r is not None:
57
+ r.check_budget()
58
+ self._t0 = time.time()
59
+ await self._inner("on_llm_start", context, agent, system_prompt, input_items)
60
+
61
+ async def on_llm_end(self, context, agent, response):
62
+ r = self._run()
63
+ if r is not None:
64
+ u = getattr(response, "usage", None)
65
+ r.record(usage_from_response(SimpleNamespace(usage=u)), model=_model_name(agent),
66
+ latency_s=time.time() - (self._t0 or time.time()))
67
+ await self._inner("on_llm_end", context, agent, response)
68
+
69
+ # pass-through for the rest so an inner hooks object keeps working
70
+ async def on_agent_start(self, context, agent):
71
+ await self._inner("on_agent_start", context, agent)
72
+
73
+ async def on_agent_end(self, context, agent, output):
74
+ await self._inner("on_agent_end", context, agent, output)
75
+
76
+ async def on_handoff(self, context, from_agent, to_agent):
77
+ await self._inner("on_handoff", context, from_agent, to_agent)
78
+
79
+ async def on_tool_start(self, context, agent, tool):
80
+ await self._inner("on_tool_start", context, agent, tool)
81
+
82
+ async def on_tool_end(self, context, agent, tool, result):
83
+ await self._inner("on_tool_end", context, agent, tool, result)
agentmeter/pricing.py ADDED
@@ -0,0 +1,116 @@
1
+ """Prices and usage normalisation.
2
+
3
+ Prices are per million tokens, in whatever currency you choose (₹, $ ...).
4
+ No real prices are hard-coded: provider prices change, so you pass your own.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass, field
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class Price:
13
+ input: float # per 1M fresh input tokens
14
+ output: float # per 1M output tokens
15
+ cache_read: float | None = None # per 1M cached input tokens (default: 0.1 x input)
16
+ cache_write: float | None = None # per 1M cache-write tokens (default: 1.25 x input)
17
+
18
+ def cost(self, u: "Usage") -> float:
19
+ cr = self.cache_read if self.cache_read is not None else self.input * 0.1
20
+ cw = self.cache_write if self.cache_write is not None else self.input * 1.25
21
+ return (
22
+ u.input_tokens * self.input
23
+ + u.output_tokens * self.output
24
+ + u.cache_read_tokens * cr
25
+ + u.cache_write_tokens * cw
26
+ ) / 1_000_000
27
+
28
+
29
+ @dataclass
30
+ class Usage:
31
+ """Normalised token counts. input_tokens = fresh (uncached) input only."""
32
+ input_tokens: int = 0
33
+ output_tokens: int = 0
34
+ cache_read_tokens: int = 0
35
+ cache_write_tokens: int = 0
36
+
37
+ @property
38
+ def total_input(self) -> int:
39
+ return self.input_tokens + self.cache_read_tokens + self.cache_write_tokens
40
+
41
+ def __add__(self, o: "Usage") -> "Usage":
42
+ return Usage(
43
+ self.input_tokens + o.input_tokens,
44
+ self.output_tokens + o.output_tokens,
45
+ self.cache_read_tokens + o.cache_read_tokens,
46
+ self.cache_write_tokens + o.cache_write_tokens,
47
+ )
48
+
49
+
50
+ def _get(obj, *names, default=0):
51
+ """Read the first present attribute/key among names; supports nested 'a.b'."""
52
+ for name in names:
53
+ cur = obj
54
+ ok = True
55
+ for part in name.split("."):
56
+ if cur is None:
57
+ ok = False
58
+ break
59
+ if isinstance(cur, dict):
60
+ if part not in cur:
61
+ ok = False
62
+ break
63
+ cur = cur[part]
64
+ else:
65
+ if not hasattr(cur, part):
66
+ ok = False
67
+ break
68
+ cur = getattr(cur, part)
69
+ if ok and cur is not None:
70
+ return cur
71
+ return default
72
+
73
+
74
+ def usage_from_response(resp) -> Usage:
75
+ """Extract usage from an Anthropic Messages, OpenAI Chat Completions or
76
+ OpenAI Responses result (objects or dicts)."""
77
+ u = _get(resp, "usage", default=None)
78
+ if u is None:
79
+ return Usage()
80
+
81
+ has = lambda *n: _get(u, *n, default=None) is not None # noqa: E731
82
+
83
+ # Anthropic Messages: input_tokens excludes cached tokens, reported separately.
84
+ if has("input_tokens") and not has("input_tokens_details") and not has("prompt_tokens"):
85
+ return Usage(
86
+ input_tokens=int(_get(u, "input_tokens")),
87
+ output_tokens=int(_get(u, "output_tokens")),
88
+ cache_read_tokens=int(_get(u, "cache_read_input_tokens")),
89
+ cache_write_tokens=int(_get(u, "cache_creation_input_tokens")),
90
+ )
91
+
92
+ # OpenAI chat / responses, LiteLLM: cached (and cache-write) tokens are
93
+ # included in the prompt total, so subtract them to get fresh input.
94
+ prompt = int(_get(u, "prompt_tokens", "input_tokens"))
95
+ cached = int(_get(u, "prompt_tokens_details.cached_tokens", "input_tokens_details.cached_tokens",
96
+ "cache_read_input_tokens"))
97
+ write = int(_get(u, "cache_creation_input_tokens"))
98
+ out = int(_get(u, "completion_tokens", "output_tokens"))
99
+ return Usage(input_tokens=max(prompt - cached - write, 0), output_tokens=out,
100
+ cache_read_tokens=cached, cache_write_tokens=write)
101
+
102
+
103
+ @dataclass
104
+ class PriceBook:
105
+ """Model name -> Price. Matches exact name first, then longest prefix."""
106
+ prices: dict[str, Price] = field(default_factory=dict)
107
+ default: Price | None = None
108
+
109
+ def for_model(self, model: str | None) -> Price | None:
110
+ if model and model in self.prices:
111
+ return self.prices[model]
112
+ if model:
113
+ best = max((k for k in self.prices if model.startswith(k)), key=len, default=None)
114
+ if best:
115
+ return self.prices[best]
116
+ return self.default
agentmeter/report.py ADDED
@@ -0,0 +1,91 @@
1
+ """Cost-per-success report from a JSONL file of run records.
2
+
3
+ python -m agentmeter report runs.jsonl [--by task|model|metadata.KEY] [--json]
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import argparse
8
+ import json
9
+ from collections import defaultdict
10
+
11
+
12
+ def load(path: str) -> list[dict]:
13
+ with open(path, encoding="utf-8") as f:
14
+ return [json.loads(line) for line in f if line.strip()]
15
+
16
+
17
+ def _key(r: dict, by: str) -> str:
18
+ if by == "model":
19
+ return ",".join(r.get("models") or ["?"])
20
+ if by.startswith("metadata."):
21
+ return str((r.get("metadata") or {}).get(by[9:], "?"))
22
+ return str(r.get(by, "?"))
23
+
24
+
25
+ def summarize(records: list[dict], by: str = "task") -> list[dict]:
26
+ groups: dict[str, list[dict]] = defaultdict(list)
27
+ for r in records:
28
+ groups[_key(r, by)].append(r)
29
+ rows = []
30
+ for k, rs in groups.items():
31
+ n = len(rs)
32
+ ok = sum(1 for r in rs if r.get("success") is True)
33
+ unknown = sum(1 for r in rs if r.get("success") is None)
34
+ cost = sum(r.get("cost", 0) for r in rs)
35
+ tin = sum(r.get("input_tokens", 0) + r.get("cache_read_tokens", 0) + r.get("cache_write_tokens", 0) for r in rs)
36
+ rows.append({
37
+ by: k,
38
+ "runs": n,
39
+ "success_rate": ok / n if n else 0,
40
+ "unlabelled": unknown,
41
+ "cost_total": cost,
42
+ "cost_per_run": cost / n if n else 0,
43
+ "cost_per_success": cost / ok if ok else None,
44
+ "avg_steps": sum(r.get("steps", 0) for r in rs) / n,
45
+ "cache_hit_rate": sum(r.get("cache_read_tokens", 0) for r in rs) / tin if tin else 0,
46
+ "avg_context_tax": sum(r.get("context_tax", 0) for r in rs) / n,
47
+ "budget_stops": sum(1 for r in rs if r.get("stopped_by_budget")),
48
+ "currency": rs[0].get("currency", ""),
49
+ })
50
+ return sorted(rows, key=lambda x: -(x["cost_total"]))
51
+
52
+
53
+ def tips(row: dict) -> list[str]:
54
+ t = []
55
+ if row["cache_hit_rate"] < 0.3 and row["avg_steps"] > 2:
56
+ t.append("low cache hit rate: put system prompt + tools first and enable prompt caching")
57
+ if row["avg_context_tax"] > 0.6 and row["cache_hit_rate"] < 0.5:
58
+ t.append("most input is re-read history: slim tool outputs or compact old messages")
59
+ if row["budget_stops"]:
60
+ t.append(f"{row['budget_stops']} run(s) hit the budget: look for loops")
61
+ if row["success_rate"] < 0.7 and row["runs"] >= 5:
62
+ t.append("low success rate is inflating cost per success more than tokens are")
63
+ if row["unlabelled"]:
64
+ t.append(f"{row['unlabelled']} run(s) have no success label: call run.succeed()/run.fail()")
65
+ return t
66
+
67
+
68
+ def main(argv=None):
69
+ p = argparse.ArgumentParser(prog="agentmeter report")
70
+ p.add_argument("path")
71
+ p.add_argument("--by", default="task")
72
+ p.add_argument("--json", action="store_true")
73
+ a = p.parse_args(argv)
74
+ rows = summarize(load(a.path), a.by)
75
+ if a.json:
76
+ print(json.dumps(rows, indent=2, ensure_ascii=False))
77
+ return
78
+ if not rows:
79
+ print("no runs")
80
+ return
81
+ cur = rows[0]["currency"]
82
+ hdr = f"{a.by:<22}{'runs':>6}{'success':>9}{'per run':>12}{'PER SUCCESS':>14}{'steps':>7}{'cache':>7}{'tax':>6}"
83
+ print(hdr)
84
+ print("-" * len(hdr))
85
+ for r in rows:
86
+ cps = f"{cur}{r['cost_per_success']:.4f}" if r["cost_per_success"] is not None else "n/a"
87
+ print(f"{str(r[a.by])[:21]:<22}{r['runs']:>6}{r['success_rate']:>9.0%}"
88
+ f"{cur + format(r['cost_per_run'], '.4f'):>12}{cps:>14}{r['avg_steps']:>7.1f}"
89
+ f"{r['cache_hit_rate']:>7.0%}{r['avg_context_tax']:>6.0%}")
90
+ for t in tips(r):
91
+ print(f"{'':<22} -> {t}")
agentmeter/sinks.py ADDED
@@ -0,0 +1,62 @@
1
+ """Where finished run records go."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import sys
6
+ import threading
7
+ from typing import Callable, Protocol
8
+
9
+
10
+ class Sink(Protocol):
11
+ def write(self, record: dict) -> None: ...
12
+
13
+
14
+ class ConsoleSink:
15
+ def __init__(self, stream=None):
16
+ self.stream = stream or sys.stderr
17
+
18
+ def write(self, r: dict) -> None:
19
+ ok = {True: "OK ", False: "FAIL", None: "?? "}[r["success"]]
20
+ budget = " [budget stop]" if r["stopped_by_budget"] else ""
21
+ print(
22
+ f"[agentmeter] {ok} {r['task']:<20} steps={r['steps']:<3} "
23
+ f"cost={r['currency']}{r['cost']:.4f} cache_hit={r['cache_hit_rate']:.0%} "
24
+ f"context_tax={r['context_tax']:.0%}{budget}",
25
+ file=self.stream,
26
+ )
27
+
28
+
29
+ class JsonlSink:
30
+ """One JSON object per line. Feed the file to `python -m agentmeter report`."""
31
+
32
+ def __init__(self, path: str):
33
+ self.path = path
34
+ self._lock = threading.Lock()
35
+
36
+ def write(self, r: dict) -> None:
37
+ with self._lock, open(self.path, "a", encoding="utf-8") as f:
38
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
39
+
40
+
41
+ class CallbackSink:
42
+ """Send records anywhere: Langfuse, a database, a webhook.
43
+
44
+ CallbackSink(lambda r: langfuse.score(trace_id=r["metadata"]["trace_id"],
45
+ name="success", value=int(r["success"])))
46
+ """
47
+
48
+ def __init__(self, fn: Callable[[dict], None]):
49
+ self.fn = fn
50
+
51
+ def write(self, r: dict) -> None:
52
+ self.fn(r)
53
+
54
+
55
+ class MemorySink:
56
+ """Keeps records in a list. Handy for tests and notebooks."""
57
+
58
+ def __init__(self):
59
+ self.records: list[dict] = []
60
+
61
+ def write(self, r: dict) -> None:
62
+ self.records.append(r)
agentmeter/wrappers.py ADDED
@@ -0,0 +1,93 @@
1
+ """Transparent proxy around an existing LLM client.
2
+
3
+ Intercepts:
4
+ Anthropic: client.messages.create, client.beta.messages.create
5
+ OpenAI: client.chat.completions.create, client.responses.create
6
+ Every other attribute passes straight through, so the wrapped client is a
7
+ drop-in replacement. Works with sync and async clients.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import inspect
12
+ import time
13
+
14
+ from .pricing import usage_from_response
15
+
16
+ TARGETS = {
17
+ ("messages", "create"): "anthropic",
18
+ ("beta", "messages", "create"): "anthropic",
19
+ ("chat", "completions", "create"): "openai",
20
+ ("responses", "create"): "openai",
21
+ }
22
+
23
+
24
+ class _Proxy:
25
+ __slots__ = ("_obj", "_path", "_meter", "_auto_cache")
26
+
27
+ def __init__(self, obj, path, meter, auto_cache):
28
+ object.__setattr__(self, "_obj", obj)
29
+ object.__setattr__(self, "_path", path)
30
+ object.__setattr__(self, "_meter", meter)
31
+ object.__setattr__(self, "_auto_cache", auto_cache)
32
+
33
+ def __getattr__(self, name):
34
+ attr = getattr(self._obj, name)
35
+ path = self._path + (name,)
36
+ kind = TARGETS.get(path)
37
+ if kind and callable(attr):
38
+ return _instrument(attr, kind, self._meter, self._auto_cache)
39
+ if any(t[: len(path)] == path for t in TARGETS):
40
+ return _Proxy(attr, path, self._meter, self._auto_cache)
41
+ return attr
42
+
43
+ def __setattr__(self, name, value):
44
+ setattr(self._obj, name, value)
45
+
46
+ def __repr__(self):
47
+ return f"<agentmeter wrapped {self._obj!r}>"
48
+
49
+
50
+ def _instrument(fn, kind, meter, auto_cache):
51
+ from .core import Meter
52
+
53
+ def before(kwargs):
54
+ run = Meter.current()
55
+ if run is not None:
56
+ run.check_budget()
57
+ if kind == "anthropic" and auto_cache and "cache_control" not in kwargs and not kwargs.get("stream"):
58
+ kwargs["cache_control"] = {"type": "ephemeral"}
59
+ return run
60
+
61
+ def after(run, resp, kwargs, t0):
62
+ if run is None or kwargs.get("stream"):
63
+ return # streaming: call run.record(...) yourself with the final usage
64
+ model = getattr(resp, "model", None) or (resp.get("model") if isinstance(resp, dict) else None) \
65
+ or kwargs.get("model")
66
+ run.record(usage_from_response(resp), model=model, latency_s=time.time() - t0)
67
+
68
+ if inspect.iscoroutinefunction(fn):
69
+ async def acall(*args, **kwargs):
70
+ run = before(kwargs)
71
+ t0 = time.time()
72
+ resp = await fn(*args, **kwargs)
73
+ after(run, resp, kwargs, t0)
74
+ return resp
75
+ return acall
76
+
77
+ def call(*args, **kwargs):
78
+ run = before(kwargs)
79
+ t0 = time.time()
80
+ resp = fn(*args, **kwargs)
81
+ if inspect.isawaitable(resp):
82
+ async def finish():
83
+ r = await resp
84
+ after(run, r, kwargs, t0)
85
+ return r
86
+ return finish()
87
+ after(run, resp, kwargs, t0)
88
+ return resp
89
+ return call
90
+
91
+
92
+ def wrap_client(client, meter, auto_cache=False):
93
+ return _Proxy(client, (), meter, auto_cache)