agentcogs 0.2.0__tar.gz → 0.2.2__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 (35) hide show
  1. {agentcogs-0.2.0 → agentcogs-0.2.2}/.gitignore +3 -0
  2. {agentcogs-0.2.0 → agentcogs-0.2.2}/PKG-INFO +10 -6
  3. {agentcogs-0.2.0 → agentcogs-0.2.2}/PYPI.md +9 -5
  4. {agentcogs-0.2.0 → agentcogs-0.2.2}/src/agentcogs/_shekel_compat.py +19 -5
  5. agentcogs-0.2.2/src/agentcogs/_version.py +1 -0
  6. {agentcogs-0.2.0 → agentcogs-0.2.2}/src/agentcogs/budget.py +56 -33
  7. {agentcogs-0.2.0 → agentcogs-0.2.2}/src/agentcogs/config.py +9 -0
  8. {agentcogs-0.2.0 → agentcogs-0.2.2}/src/agentcogs/localstore.py +44 -0
  9. agentcogs-0.2.2/src/agentcogs/provider_watch.py +213 -0
  10. agentcogs-0.2.0/src/agentcogs/_version.py +0 -1
  11. {agentcogs-0.2.0 → agentcogs-0.2.2}/LICENSE +0 -0
  12. {agentcogs-0.2.0 → agentcogs-0.2.2}/pyproject.toml +0 -0
  13. {agentcogs-0.2.0 → agentcogs-0.2.2}/src/agentcogs/__init__.py +0 -0
  14. {agentcogs-0.2.0 → agentcogs-0.2.2}/src/agentcogs/__main__.py +0 -0
  15. {agentcogs-0.2.0 → agentcogs-0.2.2}/src/agentcogs/assistant.py +0 -0
  16. {agentcogs-0.2.0 → agentcogs-0.2.2}/src/agentcogs/cli.py +0 -0
  17. {agentcogs-0.2.0 → agentcogs-0.2.2}/src/agentcogs/client.py +0 -0
  18. {agentcogs-0.2.0 → agentcogs-0.2.2}/src/agentcogs/context.py +0 -0
  19. {agentcogs-0.2.0 → agentcogs-0.2.2}/src/agentcogs/data/price_book_fixture_v1.json +0 -0
  20. {agentcogs-0.2.0 → agentcogs-0.2.2}/src/agentcogs/errors.py +0 -0
  21. {agentcogs-0.2.0 → agentcogs-0.2.2}/src/agentcogs/instrument.py +0 -0
  22. {agentcogs-0.2.0 → agentcogs-0.2.2}/src/agentcogs/integrations/__init__.py +0 -0
  23. {agentcogs-0.2.0 → agentcogs-0.2.2}/src/agentcogs/integrations/fastapi.py +0 -0
  24. {agentcogs-0.2.0 → agentcogs-0.2.2}/src/agentcogs/integrations/langgraph.py +0 -0
  25. {agentcogs-0.2.0 → agentcogs-0.2.2}/src/agentcogs/integrations/litellm_event.py +0 -0
  26. {agentcogs-0.2.0 → agentcogs-0.2.2}/src/agentcogs/kernel/__init__.py +0 -0
  27. {agentcogs-0.2.0 → agentcogs-0.2.2}/src/agentcogs/kernel/attribute.py +0 -0
  28. {agentcogs-0.2.0 → agentcogs-0.2.2}/src/agentcogs/kernel/money.py +0 -0
  29. {agentcogs-0.2.0 → agentcogs-0.2.2}/src/agentcogs/localhttp.py +0 -0
  30. {agentcogs-0.2.0 → agentcogs-0.2.2}/src/agentcogs/outbox.py +0 -0
  31. {agentcogs-0.2.0 → agentcogs-0.2.2}/src/agentcogs/ping.py +0 -0
  32. {agentcogs-0.2.0 → agentcogs-0.2.2}/src/agentcogs/reports.py +0 -0
  33. {agentcogs-0.2.0 → agentcogs-0.2.2}/src/agentcogs/shutdown.py +0 -0
  34. {agentcogs-0.2.0 → agentcogs-0.2.2}/src/agentcogs/star.py +0 -0
  35. {agentcogs-0.2.0 → agentcogs-0.2.2}/src/agentcogs/tokens.py +0 -0
@@ -15,6 +15,9 @@ venv/
15
15
  .mypy_cache/
16
16
  .ruff_cache/
17
17
  *.db
18
+ .agentcogs/
19
+ bench/results/traces/
20
+ bench/results/api.log
18
21
  node_modules/
19
22
  dashboard/dist/
20
23
  backend/.venv/
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: agentcogs
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: Customer-level AI unit economics. Compare each customer's LLM cost with their monthly fee
5
5
  Project-URL: Homepage, https://agentcogs.vercel.app
6
6
  Project-URL: Repository, https://github.com/vaibhav11123/agentcogs
@@ -39,9 +39,13 @@ AgentCOGS is an open-source Python SDK and a self-hosted dashboard for customer-
39
39
 
40
40
  ```bash
41
41
  pip install agentcogs
42
+ agentcogs init
43
+ agentcogs status
42
44
  ```
43
45
 
44
- This package is the SDK. It is on PyPI. The customer list is the dashboard in the [repository](https://github.com/vaibhav11123/agentcogs), and you run that yourself. A hosted API is not serving. The working sample is [agentcogs.vercel.app](https://agentcogs.vercel.app).
46
+ `init` records one sample for `customer_001` at $0.0246 and leaves enforcement off. It does not call a model. With no API key, a later call inside `run(customer_id=...)` is priced from the response and stored in that same file. `instrument()` does not write a row. No prompt or provider key is written.
47
+
48
+ This package is the SDK. The customer list is the dashboard in the [repository](https://github.com/vaibhav11123/agentcogs), and you run that yourself. A hosted API is not serving. The working sample is [agentcogs.vercel.app](https://agentcogs.vercel.app).
45
49
 
46
50
  ## What does the number mean?
47
51
 
@@ -71,17 +75,17 @@ with agentcogs.run(workflow_id="support") as ctx:
71
75
  print(ctx.wait_for_ingest().accepted, ctx.run_id)
72
76
  ```
73
77
 
74
- The SDK does not call a model. Inside the block, shekel reads token usage from the OpenAI or Anthropic call you make. When the block exits, that cost is posted. With no `OPENAI_API_KEY`, the same block posts a zero-cost run so you can see the row. Open that customer and type the monthly fee.
78
+ The SDK does not call a model. Inside the block, an OpenAI or Anthropic call is read from the response. Cached tokens and cache writes are part of the posted total. With no provider call, the same block posts a zero-cost run so you can see the row. Open that customer and type the monthly fee.
75
79
 
76
80
  `python examples/hello_agentcogs.py` in the repository is this path. `python examples/one_run.py` posts one recorded cost of USD 0.84 and does not call a model.
77
81
 
78
82
  ## How attribution works
79
83
 
80
- `set_customer()` names the tenant for this request. `run()` watches the instrumented client calls in the block and posts one event with `total_usd` when the block exits. If no customer is set, `run()` raises before the block. A duplicate `run_id` is accepted as a duplicate and is not stored twice. A failed post sits in a local outbox and is retried. `python -m agentcogs outbox status` shows what has not been delivered.
84
+ `set_customer()` names the tenant for this request. `run()` watches the instrumented client calls in the block and posts one event with `total_usd` when the block exits. If no customer is set, `run()` raises before the block. A duplicate `run_id` is accepted as a duplicate and is not stored twice. On the self-hosted API, that duplicate keeps the customer stored on the first commit. A failed post sits in a local outbox and is retried. `python -m agentcogs outbox status` shows what has not been delivered.
81
85
 
82
86
  ## What the budget check does
83
87
 
84
- If `monthly_budget_usd` is already exceeded, the next `run()` raises `CustomerBudgetExceededError` and does not enter the block. Two calls already in flight can both pass. It is not an atomic reservation. A LiteLLM callback records cost after the provider has already answered, so it cannot stop that call.
88
+ Enforcement stays off until the workspace turns it on. While it is off, an exceeded `monthly_budget_usd` does not stop the next `run()`. When the workspace turns enforcement on, an exceeded budget raises `CustomerBudgetExceededError` and does not enter the block. Two calls already in flight can both pass. It is not an atomic reservation. A LiteLLM callback records cost after the provider has already answered, so it cannot stop that call.
85
89
 
86
90
  LiteLLM does not ship the callback. You copy it from the repository. The FastAPI middleware is a separate extra: `pip install "agentcogs[integrations]"`.
87
91
 
@@ -89,7 +93,7 @@ LiteLLM does not ship the callback. You copy it from the repository. The FastAPI
89
93
 
90
94
  | | |
91
95
  | --- | --- |
92
- | OpenAI and Anthropic | Usage read inside `run()` by shekel, which this package depends on |
96
+ | OpenAI and Anthropic | Usage on the response inside `run()`, including cached tokens and cache writes |
93
97
  | [FastAPI](https://github.com/vaibhav11123/agentcogs/blob/main/docs/integrations/fastapi.md) | Set the tenant from the request. Needs the `integrations` extra |
94
98
  | [LangGraph](https://github.com/vaibhav11123/agentcogs/blob/main/docs/integrations/langgraph.md) | Wrap the graph |
95
99
  | [LiteLLM](https://github.com/vaibhav11123/agentcogs/blob/main/docs/integrations/litellm.md) | A callback you register. It posts after the proxy call |
@@ -8,9 +8,13 @@ AgentCOGS is an open-source Python SDK and a self-hosted dashboard for customer-
8
8
 
9
9
  ```bash
10
10
  pip install agentcogs
11
+ agentcogs init
12
+ agentcogs status
11
13
  ```
12
14
 
13
- This package is the SDK. It is on PyPI. The customer list is the dashboard in the [repository](https://github.com/vaibhav11123/agentcogs), and you run that yourself. A hosted API is not serving. The working sample is [agentcogs.vercel.app](https://agentcogs.vercel.app).
15
+ `init` records one sample for `customer_001` at $0.0246 and leaves enforcement off. It does not call a model. With no API key, a later call inside `run(customer_id=...)` is priced from the response and stored in that same file. `instrument()` does not write a row. No prompt or provider key is written.
16
+
17
+ This package is the SDK. The customer list is the dashboard in the [repository](https://github.com/vaibhav11123/agentcogs), and you run that yourself. A hosted API is not serving. The working sample is [agentcogs.vercel.app](https://agentcogs.vercel.app).
14
18
 
15
19
  ## What does the number mean?
16
20
 
@@ -40,17 +44,17 @@ with agentcogs.run(workflow_id="support") as ctx:
40
44
  print(ctx.wait_for_ingest().accepted, ctx.run_id)
41
45
  ```
42
46
 
43
- The SDK does not call a model. Inside the block, shekel reads token usage from the OpenAI or Anthropic call you make. When the block exits, that cost is posted. With no `OPENAI_API_KEY`, the same block posts a zero-cost run so you can see the row. Open that customer and type the monthly fee.
47
+ The SDK does not call a model. Inside the block, an OpenAI or Anthropic call is read from the response. Cached tokens and cache writes are part of the posted total. With no provider call, the same block posts a zero-cost run so you can see the row. Open that customer and type the monthly fee.
44
48
 
45
49
  `python examples/hello_agentcogs.py` in the repository is this path. `python examples/one_run.py` posts one recorded cost of USD 0.84 and does not call a model.
46
50
 
47
51
  ## How attribution works
48
52
 
49
- `set_customer()` names the tenant for this request. `run()` watches the instrumented client calls in the block and posts one event with `total_usd` when the block exits. If no customer is set, `run()` raises before the block. A duplicate `run_id` is accepted as a duplicate and is not stored twice. A failed post sits in a local outbox and is retried. `python -m agentcogs outbox status` shows what has not been delivered.
53
+ `set_customer()` names the tenant for this request. `run()` watches the instrumented client calls in the block and posts one event with `total_usd` when the block exits. If no customer is set, `run()` raises before the block. A duplicate `run_id` is accepted as a duplicate and is not stored twice. On the self-hosted API, that duplicate keeps the customer stored on the first commit. A failed post sits in a local outbox and is retried. `python -m agentcogs outbox status` shows what has not been delivered.
50
54
 
51
55
  ## What the budget check does
52
56
 
53
- If `monthly_budget_usd` is already exceeded, the next `run()` raises `CustomerBudgetExceededError` and does not enter the block. Two calls already in flight can both pass. It is not an atomic reservation. A LiteLLM callback records cost after the provider has already answered, so it cannot stop that call.
57
+ Enforcement stays off until the workspace turns it on. While it is off, an exceeded `monthly_budget_usd` does not stop the next `run()`. When the workspace turns enforcement on, an exceeded budget raises `CustomerBudgetExceededError` and does not enter the block. Two calls already in flight can both pass. It is not an atomic reservation. A LiteLLM callback records cost after the provider has already answered, so it cannot stop that call.
54
58
 
55
59
  LiteLLM does not ship the callback. You copy it from the repository. The FastAPI middleware is a separate extra: `pip install "agentcogs[integrations]"`.
56
60
 
@@ -58,7 +62,7 @@ LiteLLM does not ship the callback. You copy it from the repository. The FastAPI
58
62
 
59
63
  | | |
60
64
  | --- | --- |
61
- | OpenAI and Anthropic | Usage read inside `run()` by shekel, which this package depends on |
65
+ | OpenAI and Anthropic | Usage on the response inside `run()`, including cached tokens and cache writes |
62
66
  | [FastAPI](https://github.com/vaibhav11123/agentcogs/blob/main/docs/integrations/fastapi.md) | Set the tenant from the request. Needs the `integrations` extra |
63
67
  | [LangGraph](https://github.com/vaibhav11123/agentcogs/blob/main/docs/integrations/langgraph.md) | Wrap the graph |
64
68
  | [LiteLLM](https://github.com/vaibhav11123/agentcogs/blob/main/docs/integrations/litellm.md) | A callback you register. It posts after the proxy call |
@@ -43,19 +43,33 @@ def lanes_from_usage(provider: str, usage: dict) -> dict:
43
43
  """
44
44
  name = (provider or "").lower()
45
45
  if name == "openai":
46
- details = usage.get("input_tokens_details") or {}
46
+ # Chat Completions reports prompt_tokens. The Responses API reports
47
+ # input_tokens. Cached and cache-write tokens are subsets of that total.
48
+ details = usage.get("input_tokens_details") or usage.get("prompt_tokens_details") or {}
47
49
  cache_read = int(details.get("cached_tokens") or 0)
48
50
  write_details = usage.get("cache_write_tokens_details") or {}
49
51
  if "ttl_30m_tokens" in write_details or "ttl_12h_tokens" in write_details:
50
52
  write_30m = int(write_details.get("ttl_30m_tokens") or 0)
51
53
  write_12h = int(write_details.get("ttl_12h_tokens") or 0)
52
- else:
54
+ elif "cache_write_tokens" in usage:
53
55
  write_30m = int(usage.get("cache_write_tokens") or 0)
54
56
  write_12h = 0
55
- uncached = int(usage.get("input_tokens") or 0) - cache_read - write_30m - write_12h
57
+ else:
58
+ write_30m = int(details.get("cache_write_tokens") or 0)
59
+ write_12h = 0
60
+ if "input_tokens" in usage and usage.get("input_tokens") is not None:
61
+ reported = int(usage.get("input_tokens") or 0)
62
+ else:
63
+ reported = int(usage.get("prompt_tokens") or 0)
64
+ uncached = reported - cache_read - write_30m - write_12h
56
65
  if uncached < 0:
57
66
  raise ValueError("LANE_NEGATIVE")
58
- reasoning = usage.get("output_tokens_details") or {}
67
+ if "output_tokens" in usage and usage.get("output_tokens") is not None:
68
+ output = int(usage.get("output_tokens") or 0)
69
+ reasoning = usage.get("output_tokens_details") or {}
70
+ else:
71
+ output = int(usage.get("completion_tokens") or 0)
72
+ reasoning = usage.get("completion_tokens_details") or {}
59
73
  return {
60
74
  "uncached_input": uncached,
61
75
  "cache_read": cache_read,
@@ -63,7 +77,7 @@ def lanes_from_usage(provider: str, usage: dict) -> dict:
63
77
  "cache_write_1h": 0,
64
78
  "cache_write_30m": write_30m,
65
79
  "cache_write_12h": write_12h,
66
- "output": int(usage.get("output_tokens") or 0),
80
+ "output": output,
67
81
  "reasoning": int(reasoning.get("reasoning_tokens") or 0),
68
82
  }
69
83
  if name in {"anthropic", "claude"}:
@@ -0,0 +1 @@
1
+ __version__ = "0.2.2"
@@ -12,6 +12,8 @@ from .client import emit_event, emit_event_sync, fetch_budget
12
12
  from .config import get_config
13
13
  from .context import resolve_customer, resolve_workflow
14
14
  from .errors import ConfigurationError, CustomerBudgetExceededError
15
+ from .localstore import ledger_home, record_calls
16
+ from .provider_watch import pop as pop_watch, priced_calls, push as push_watch, snapshot
15
17
 
16
18
  log = logging.getLogger("agentcogs")
17
19
 
@@ -124,39 +126,60 @@ def run(
124
126
  run_ctx: Optional[RunContext] = None
125
127
 
126
128
  with shekel_budget(**kwargs) as ctx:
129
+ watch = push_watch()
127
130
  try:
128
- run_ctx = RunContext(ctx, run_id, resolved_customer, resolved_workflow)
129
- yield run_ctx
130
- except CustomerBudgetExceededError:
131
- status = "budget_exceeded"
132
- raise
133
- except Exception as e:
134
- status = "error"
135
- error_msg = str(e)[:500]
136
- raise
137
- finally:
138
131
  try:
139
- summary = normalize_summary_data(ctx.summary_data())
140
- event = {
141
- "run_id": run_id,
142
- "customer_id": resolved_customer,
143
- "workflow_id": resolved_workflow,
144
- "ts": int(time.time()),
145
- "status": status,
146
- "total_usd": float(summary.get("total_cost") or 0),
147
- "models": normalize_summary(summary.get("by_model", {})),
148
- "node_costs": getattr(ctx, "node_costs", {}),
149
- "metadata": _cap_metadata(metadata),
150
- "error": error_msg,
151
- }
152
- if run_ctx is not None:
153
- run_ctx._event = event
154
- emit_event(event)
132
+ run_ctx = RunContext(ctx, run_id, resolved_customer, resolved_workflow)
133
+ yield run_ctx
134
+ except CustomerBudgetExceededError:
135
+ status = "budget_exceeded"
136
+ raise
155
137
  except Exception as e:
156
- log.warning("telemetry failed", exc_info=True)
157
- cb = cfg.on_telemetry_error
158
- if cb is not None:
159
- try:
160
- cb(e)
161
- except Exception:
162
- pass
138
+ status = "error"
139
+ error_msg = str(e)[:500]
140
+ raise
141
+ finally:
142
+ try:
143
+ summary = normalize_summary_data(ctx.summary_data())
144
+ event = {
145
+ "run_id": run_id,
146
+ "customer_id": resolved_customer,
147
+ "workflow_id": resolved_workflow,
148
+ "ts": int(time.time()),
149
+ "status": status,
150
+ "total_usd": float(summary.get("total_cost") or 0),
151
+ "models": normalize_summary(summary.get("by_model", {})),
152
+ "node_costs": getattr(ctx, "node_costs", {}),
153
+ "metadata": _cap_metadata(metadata),
154
+ "error": error_msg,
155
+ }
156
+ priced = priced_calls(snapshot())
157
+ if priced is not None:
158
+ event["calls"] = priced["calls"]
159
+ event["book_id"] = priced["book_id"]
160
+ event["total_usd"] = priced["total_usd"]
161
+ event["models"] = priced["models"]
162
+ if run_ctx is not None:
163
+ run_ctx._event = event
164
+ emit_event(event)
165
+ home = ledger_home()
166
+ if cfg.offline and home is not None and status == "completed" and priced is not None:
167
+ record_calls(
168
+ home,
169
+ run_id=run_id,
170
+ customer_id=resolved_customer,
171
+ workflow=resolved_workflow,
172
+ calls=priced["calls"],
173
+ )
174
+ except ValueError:
175
+ raise
176
+ except Exception as e:
177
+ log.warning("telemetry failed", exc_info=True)
178
+ cb = cfg.on_telemetry_error
179
+ if cb is not None:
180
+ try:
181
+ cb(e)
182
+ except Exception:
183
+ pass
184
+ finally:
185
+ pop_watch(watch)
@@ -86,6 +86,15 @@ def init(
86
86
 
87
87
  def get_config() -> _Config:
88
88
  if _config.api_key is None and not _config.offline:
89
+ if os.environ.get("AGENTCOGS_API_KEY"):
90
+ init()
91
+ return _config
92
+ from .localstore import ledger_home
93
+
94
+ if ledger_home() is not None:
95
+ _config.offline = True
96
+ _config.workspace_id = _config.workspace_id or "ws_local"
97
+ return _config
89
98
  init()
90
99
  return _config
91
100
 
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import json
6
+ import os
6
7
  import secrets
7
8
  import shutil
8
9
  import sqlite3
@@ -52,6 +53,15 @@ def fixture_case() -> dict:
52
53
  }
53
54
 
54
55
 
56
+ def ledger_home() -> Path | None:
57
+ """The ledger from `agentcogs init`, if this process can see it."""
58
+ raw = os.environ.get("AGENTCOGS_HOME")
59
+ home = Path(raw) if raw else Path.cwd() / ".agentcogs"
60
+ if (home / "ledger.sqlite").is_file():
61
+ return home
62
+ return None
63
+
64
+
55
65
  def connect(home: Path) -> sqlite3.Connection:
56
66
  home.mkdir(parents=True, exist_ok=True)
57
67
  conn = sqlite3.connect(home / "ledger.sqlite", isolation_level=None)
@@ -236,6 +246,40 @@ def record_event(
236
246
  return {"duplicate": False, "incurred_micro": incurred, "enforce": enforce}
237
247
 
238
248
 
249
+ def record_calls(
250
+ home: Path,
251
+ *,
252
+ run_id: str,
253
+ customer_id: str,
254
+ workflow: str,
255
+ calls: list[dict],
256
+ ) -> list[dict]:
257
+ """Store priced calls from this process. One row per call. No prompt is read."""
258
+ if not calls:
259
+ return []
260
+ conn = connect(home)
261
+ try:
262
+ written: list[dict] = []
263
+ many = len(calls) > 1
264
+ for call in calls:
265
+ model = str(call.get("model") or "")
266
+ call_id = str(call.get("call_id") or "c0")
267
+ provider = "Anthropic" if model.startswith("claude") else "OpenAI"
268
+ result = record_event(
269
+ conn,
270
+ run_id=f"{run_id}:{call_id}" if many else run_id,
271
+ customer_id=customer_id,
272
+ provider=provider,
273
+ workflow=workflow,
274
+ model=model,
275
+ case={"calls": [{"call_id": call_id, "lanes": call.get("lanes") or {}}], "segments": []},
276
+ )
277
+ written.append(result)
278
+ return written
279
+ finally:
280
+ conn.close()
281
+
282
+
239
283
  def verify_fixture(home: Path) -> dict:
240
284
  """Price the documented sample call locally. No provider request."""
241
285
  conn = connect(home)
@@ -0,0 +1,213 @@
1
+ """Record provider usage inside run() and price it with the shipped book.
2
+
3
+ Shekel keeps prompt and completion totals. The chat-completions response also
4
+ carries cache reads and cache writes. Those lanes are what the server prices.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ import threading
11
+ from contextvars import ContextVar
12
+ from decimal import Decimal
13
+ from typing import Any
14
+
15
+ from ._shekel_compat import lanes_from_usage
16
+ from .kernel.attribute import price_call
17
+ from .localstore import price_book
18
+
19
+ log = logging.getLogger("agentcogs")
20
+
21
+ _bucket: ContextVar[list | None] = ContextVar("agentcogs_provider_calls", default=None)
22
+ _lock = threading.Lock()
23
+ _depth = 0
24
+ _saved: dict[str, Any] = {}
25
+
26
+ _INPUT_LANES = (
27
+ "uncached_input",
28
+ "cache_read",
29
+ "cache_write_5m",
30
+ "cache_write_1h",
31
+ "cache_write_30m",
32
+ "cache_write_12h",
33
+ )
34
+
35
+
36
+ def push() -> Any:
37
+ _install()
38
+ box: list = []
39
+ return _bucket.set(box)
40
+
41
+
42
+ def pop(token: Any) -> None:
43
+ _bucket.reset(token)
44
+ _remove()
45
+
46
+
47
+ def snapshot() -> list[dict]:
48
+ box = _bucket.get()
49
+ if not box:
50
+ return []
51
+ return list(box)
52
+
53
+
54
+ def micro_as_usd(micro: int) -> float:
55
+ """Six-decimal dollars. The server parses this back to the same micros."""
56
+ text = format(Decimal(int(micro)) / Decimal(1_000_000), "f")
57
+ return float(text)
58
+
59
+
60
+ def priced_calls(records: list[dict]) -> dict | None:
61
+ """Return ingest fields for these provider responses, or None when empty."""
62
+ if not records:
63
+ return None
64
+ book = price_book()
65
+ calls = []
66
+ by_model: dict[str, dict] = {}
67
+ total = 0
68
+ try:
69
+ for index, record in enumerate(records):
70
+ lanes = lanes_from_usage(record["provider"], record["usage"])
71
+ _priced, micro = price_call(lanes, book)
72
+ model = record.get("model") or "unknown"
73
+ call = {"call_id": f"c{index}", "model": model, "lanes": lanes}
74
+ if record["provider"] == "openai":
75
+ usage = record["usage"]
76
+ if "input_tokens" in usage and usage.get("input_tokens") is not None:
77
+ call["provider_input_tokens"] = int(usage.get("input_tokens") or 0)
78
+ elif "prompt_tokens" in usage:
79
+ call["provider_input_tokens"] = int(usage.get("prompt_tokens") or 0)
80
+ calls.append(call)
81
+ total += micro
82
+ row = by_model.setdefault(
83
+ model, {"input_tokens": 0, "output_tokens": 0, "usd": 0.0, "_micro": 0}
84
+ )
85
+ row["input_tokens"] += sum(int(lanes.get(name, 0)) for name in _INPUT_LANES)
86
+ row["output_tokens"] += int(lanes.get("output", 0))
87
+ row["_micro"] += micro
88
+ except ValueError as exc:
89
+ log.warning("provider usage was not priced (%s)", exc)
90
+ return None
91
+ models = {
92
+ model: {
93
+ "input_tokens": row["input_tokens"],
94
+ "output_tokens": row["output_tokens"],
95
+ "usd": micro_as_usd(row["_micro"]),
96
+ }
97
+ for model, row in by_model.items()
98
+ }
99
+ return {
100
+ "calls": calls,
101
+ "book_id": book["book_id"],
102
+ "total_usd": micro_as_usd(total),
103
+ "models": models,
104
+ "total_micro": total,
105
+ }
106
+
107
+
108
+ def _remember(provider: str, model: str | None, usage: Any) -> None:
109
+ box = _bucket.get()
110
+ if box is None or usage is None:
111
+ return
112
+ if hasattr(usage, "model_dump"):
113
+ payload = usage.model_dump()
114
+ elif isinstance(usage, dict):
115
+ payload = dict(usage)
116
+ else:
117
+ return
118
+ box.append({"provider": provider, "model": model, "usage": payload})
119
+
120
+
121
+ def _install() -> None:
122
+ global _depth
123
+ with _lock:
124
+ _depth += 1
125
+ if _depth == 1:
126
+ _wrap()
127
+
128
+
129
+ def _remove() -> None:
130
+ global _depth
131
+ with _lock:
132
+ _depth -= 1
133
+ if _depth == 0:
134
+ _unwrap()
135
+
136
+
137
+ def _wrap() -> None:
138
+ try:
139
+ import openai.resources.chat.completions as oai
140
+
141
+ _saved["openai"] = oai.Completions.create
142
+ oai.Completions.create = _openai_create # type: ignore[method-assign]
143
+ except ImportError:
144
+ pass
145
+ try:
146
+ import anthropic.resources.messages as ant
147
+
148
+ _saved["anthropic"] = ant.Messages.create
149
+ ant.Messages.create = _anthropic_create # type: ignore[method-assign]
150
+ except ImportError:
151
+ pass
152
+
153
+
154
+ def _unwrap() -> None:
155
+ if "openai" in _saved:
156
+ import openai.resources.chat.completions as oai
157
+
158
+ oai.Completions.create = _saved.pop("openai")
159
+ if "anthropic" in _saved:
160
+ import anthropic.resources.messages as ant
161
+
162
+ ant.Messages.create = _saved.pop("anthropic")
163
+
164
+
165
+ def _openai_create(self: Any, *args: Any, **kwargs: Any) -> Any:
166
+ original = _saved.get("openai")
167
+ response = original(self, *args, **kwargs)
168
+ if kwargs.get("stream") is True:
169
+ return _openai_stream(response)
170
+ _remember("openai", getattr(response, "model", None), getattr(response, "usage", None))
171
+ return response
172
+
173
+
174
+ def _openai_stream(stream: Any):
175
+ last = None
176
+ model = None
177
+ for chunk in stream:
178
+ usage = getattr(chunk, "usage", None)
179
+ if usage is not None:
180
+ last = usage
181
+ model = getattr(chunk, "model", None) or model
182
+ yield chunk
183
+ if last is not None:
184
+ _remember("openai", model, last)
185
+
186
+
187
+ def _anthropic_create(self: Any, *args: Any, **kwargs: Any) -> Any:
188
+ original = _saved.get("anthropic")
189
+ response = original(self, *args, **kwargs)
190
+ if kwargs.get("stream") is True:
191
+ return _anthropic_stream(response)
192
+ _remember("anthropic", getattr(response, "model", None), getattr(response, "usage", None))
193
+ return response
194
+
195
+
196
+ def _anthropic_stream(stream: Any):
197
+ merged: dict = {}
198
+ model = None
199
+ for event in stream:
200
+ kind = getattr(event, "type", None)
201
+ if kind == "message_start":
202
+ message = getattr(event, "message", None)
203
+ model = getattr(message, "model", None) or model
204
+ usage = getattr(message, "usage", None)
205
+ if usage is not None and hasattr(usage, "model_dump"):
206
+ merged.update(usage.model_dump())
207
+ elif kind == "message_delta":
208
+ usage = getattr(event, "usage", None)
209
+ if usage is not None and hasattr(usage, "model_dump"):
210
+ merged.update(usage.model_dump())
211
+ yield event
212
+ if merged:
213
+ _remember("anthropic", model, merged)
@@ -1 +0,0 @@
1
- __version__ = "0.2.0"
File without changes
File without changes