tokaudit 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.
- tokaudit/__init__.py +3 -0
- tokaudit/adapters.py +350 -0
- tokaudit/benchmark.py +251 -0
- tokaudit/cli.py +220 -0
- tokaudit/config.py +92 -0
- tokaudit/dedup.py +216 -0
- tokaudit/integrity.py +459 -0
- tokaudit/jsoninput.py +15 -0
- tokaudit/logs.py +262 -0
- tokaudit/prefix.py +341 -0
- tokaudit/prices.py +107 -0
- tokaudit/providers.json +124 -0
- tokaudit/report.py +382 -0
- tokaudit/rules.py +265 -0
- tokaudit/tokenizers.py +227 -0
- tokaudit/whatif.py +326 -0
- tokaudit-0.2.0.dist-info/METADATA +773 -0
- tokaudit-0.2.0.dist-info/RECORD +22 -0
- tokaudit-0.2.0.dist-info/WHEEL +5 -0
- tokaudit-0.2.0.dist-info/entry_points.txt +2 -0
- tokaudit-0.2.0.dist-info/licenses/LICENSE +21 -0
- tokaudit-0.2.0.dist-info/top_level.txt +1 -0
tokaudit/__init__.py
ADDED
tokaudit/adapters.py
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
"""Adapters for known LLM gateway/observability export shapes.
|
|
2
|
+
|
|
3
|
+
Each adapter normalizes one exported record into the plain dict shape that
|
|
4
|
+
``logs.parse_record`` understands. Detection is by field signature and is
|
|
5
|
+
deliberately strict: an unrecognized shape raises a clear error rather
|
|
6
|
+
than silently mis-parsing.
|
|
7
|
+
|
|
8
|
+
Grounding status (re-checked dates inline):
|
|
9
|
+
- LiteLLM SpendLogs row: fields verified against litellm/proxy/
|
|
10
|
+
schema.prisma (model LiteLLM_SpendLogs) on 2026-10-28, re-verified same
|
|
11
|
+
day against BerriAI/litellm main schema.prisma (request_id, startTime,
|
|
12
|
+
messages, model, custom_llm_provider, session_id, prompt_tokens Int,
|
|
13
|
+
completion_tokens Int, cache_hit String all present). cache_hit is
|
|
14
|
+
LiteLLM's application-level cache flag, not provider prompt-cache
|
|
15
|
+
usage, and is deliberately not mapped to actual_usage cache fields.
|
|
16
|
+
Response shapes verified 2026-10-31 against BerriAI/litellm main
|
|
17
|
+
(litellm/proxy/spend_tracking/spend_management_endpoints.py): the
|
|
18
|
+
legacy GET /spend/logs returns full Prisma rows WITH messages; the
|
|
19
|
+
paginated GET /spend/logs/v2 wraps rows in a data/total/page envelope
|
|
20
|
+
and its list SQL (_SPEND_LOG_LIST_COLUMNS) deliberately omits
|
|
21
|
+
messages/response/proxy_server_request, keeping them for the detail
|
|
22
|
+
route /spend/logs/ui/{request_id}. Both v2 shapes are detected and
|
|
23
|
+
rejected with re-export guidance instead of a generic "no messages"
|
|
24
|
+
parse error. messages is typed str | list | dict | None on
|
|
25
|
+
SpendLogsPayload (litellm/proxy/_types.py); dict/None payloads raise
|
|
26
|
+
loudly below.
|
|
27
|
+
- Langfuse observation (Observations API v2, GET /api/public/v2/observations):
|
|
28
|
+
usageDetails key families pinned by Langfuse's provider-usage-key matrix
|
|
29
|
+
(github.com/langfuse/langfuse .agents/skills/add-model-price/references/
|
|
30
|
+
provider-usage-key-matrix.md, fetched 2026-10-28).
|
|
31
|
+
validated 2026-10-28 against the authoritative Fern schema
|
|
32
|
+
(github.com/langfuse/langfuse, fern/apis/server/definition/commons.yml,
|
|
33
|
+
type ObservationV2; re-verified same day: core id/traceId/startTime/
|
|
34
|
+
projectId/type, sessionId in basic, input/output in io, model in model
|
|
35
|
+
group, all still current). Facts that shape this adapter:
|
|
36
|
+
* core fields id/traceId/startTime/endTime/projectId/parentObservationId/type
|
|
37
|
+
are always present; everything else is an optional field group;
|
|
38
|
+
* `input`/`output` belong to the optional `io` group and are returned as
|
|
39
|
+
raw strings (JSON-serialized when structured);
|
|
40
|
+
* `type` distinguishes GENERATION (an LLM call) from SPAN/EVENT/etc.
|
|
41
|
+
Loud errors on mismatch.
|
|
42
|
+
- Helicone request row (POST /v1/request/query): validated 2026-10-28
|
|
43
|
+
against the authoritative HeliconeRequest type
|
|
44
|
+
(github.com/Helicone/helicone, packages/llm-mapper/types.ts;
|
|
45
|
+
re-verified same day, fields unchanged). Rows are
|
|
46
|
+
FLAT: request_id, request_created_at, request_body (raw request JSON),
|
|
47
|
+
response_body, provider, request_model/response_model. There is no nested
|
|
48
|
+
request/response wrapper. request_body may arrive as a JSON string.
|
|
49
|
+
Loud errors on mismatch.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
from __future__ import annotations
|
|
53
|
+
|
|
54
|
+
import json
|
|
55
|
+
|
|
56
|
+
import math
|
|
57
|
+
from typing import Any, Dict
|
|
58
|
+
|
|
59
|
+
from .jsoninput import unique_object
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _is_litellm_spendlog(obj: Dict[str, Any]) -> bool:
|
|
63
|
+
return "request_id" in obj and "startTime" in obj and "messages" in obj
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
# Langfuse usageDetails key families, verbatim from the Langfuse provider
|
|
67
|
+
# usage-key matrix (github.com/langfuse/langfuse,
|
|
68
|
+
# .agents/skills/add-model-price/references/provider-usage-key-matrix.md,
|
|
69
|
+
# fetched 2026-10-28; excerpt in rules/EVIDENCE.md).
|
|
70
|
+
_LF_CACHE_READ_KEYS = ("input_cache_read", "cache_read_input_tokens",
|
|
71
|
+
"input_cached_tokens")
|
|
72
|
+
_LF_CACHE_WRITE_KEYS = ("input_cache_creation", "cache_write_tokens",
|
|
73
|
+
"input_cache_write_tokens",
|
|
74
|
+
"cache_creation_input_tokens")
|
|
75
|
+
_LF_CACHE_TTL_KEYS = ("input_cache_creation_5m", "input_cache_creation_1h")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _max_present(details: Dict[str, Any], keys) -> Optional[int]:
|
|
79
|
+
vals = []
|
|
80
|
+
for k in keys:
|
|
81
|
+
v = details.get(k)
|
|
82
|
+
if isinstance(v, bool):
|
|
83
|
+
continue
|
|
84
|
+
if isinstance(v, int) and v >= 0:
|
|
85
|
+
vals.append(v)
|
|
86
|
+
return max(vals) if vals else None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _langfuse_usage(details: Dict[str, Any]) -> Dict[str, int]:
|
|
91
|
+
"""Recover inclusive text-input usage from Langfuse's exclusive buckets.
|
|
92
|
+
|
|
93
|
+
Aliases within one family retain the existing max policy. Duration-specific
|
|
94
|
+
writes are separate buckets: normalized generic writes are a remainder,
|
|
95
|
+
not a total. Never invent missing ordinary input or unknown input types.
|
|
96
|
+
"""
|
|
97
|
+
read = _max_present(details, _LF_CACHE_READ_KEYS)
|
|
98
|
+
writes = _max_present(details, _LF_CACHE_WRITE_KEYS)
|
|
99
|
+
ttl_present = [key for key in _LF_CACHE_TTL_KEYS if key in details]
|
|
100
|
+
write_present = [key for key in _LF_CACHE_WRITE_KEYS + _LF_CACHE_TTL_KEYS
|
|
101
|
+
if key in details]
|
|
102
|
+
writes_valid = all(type(details[key]) is int and details[key] >= 0
|
|
103
|
+
for key in write_present)
|
|
104
|
+
if ttl_present:
|
|
105
|
+
writes = (sum(details[key] for key in ttl_present) + (writes or 0)
|
|
106
|
+
if writes_valid else None)
|
|
107
|
+
elif not writes_valid:
|
|
108
|
+
writes = None
|
|
109
|
+
usage = {}
|
|
110
|
+
if read is not None:
|
|
111
|
+
usage["cache_read_tokens"] = read
|
|
112
|
+
if writes is not None:
|
|
113
|
+
usage["cache_write_tokens"] = writes
|
|
114
|
+
input_keys = ("input", "input_tokens")
|
|
115
|
+
known = set(input_keys + _LF_CACHE_READ_KEYS + _LF_CACHE_WRITE_KEYS
|
|
116
|
+
+ _LF_CACHE_TTL_KEYS)
|
|
117
|
+
present = [key for key in known if key in details]
|
|
118
|
+
valid = all(type(details[key]) is int and details[key] >= 0
|
|
119
|
+
for key in present)
|
|
120
|
+
unsupported = any(key.startswith("input_") and key not in known
|
|
121
|
+
for key in details)
|
|
122
|
+
ordinary = _max_present(details, input_keys)
|
|
123
|
+
if ordinary is not None and valid and not unsupported:
|
|
124
|
+
usage["prompt_tokens"] = ordinary + (read or 0) + (writes or 0)
|
|
125
|
+
return usage
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _is_langfuse_observation(obj: Dict[str, Any]) -> bool:
|
|
129
|
+
# Core ObservationV2 fields; `input` is NOT required for detection because
|
|
130
|
+
# it sits in the optional `io` field group of the v2 export.
|
|
131
|
+
return (
|
|
132
|
+
"id" in obj
|
|
133
|
+
and ("startTime" in obj or "start_time" in obj)
|
|
134
|
+
and ("traceId" in obj or "projectId" in obj or "type" in obj)
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _is_helicone_row(obj: Dict[str, Any]) -> bool:
|
|
139
|
+
# Flat HeliconeRequest row; `request_id` alone collides with LiteLLM
|
|
140
|
+
# spend logs, which are matched first, so require the body field too.
|
|
141
|
+
return "request_id" in obj and "request_body" in obj
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _is_litellm_spendlog_v2_envelope(obj: Dict[str, Any]) -> bool:
|
|
145
|
+
# GET /spend/logs/v2 wraps its page in an envelope:
|
|
146
|
+
# {"data": [...rows], "total", "page", "page_size", "total_pages"}.
|
|
147
|
+
return (
|
|
148
|
+
isinstance(obj.get("data"), list)
|
|
149
|
+
and "total" in obj
|
|
150
|
+
and "page" in obj
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _is_litellm_spendlog_v2_list_row(obj: Dict[str, Any]) -> bool:
|
|
155
|
+
# A row from the /spend/logs/v2 LIST (and /spend/logs/ui list): the
|
|
156
|
+
# handler selects _SPEND_LOG_LIST_COLUMNS, which deliberately omits the
|
|
157
|
+
# heavy columns messages/response/proxy_server_request
|
|
158
|
+
# (litellm/proxy/spend_tracking/spend_management_endpoints.py; verified
|
|
159
|
+
# 2026-10-31). The legacy /spend/logs route returns full Prisma rows
|
|
160
|
+
# WITH messages, and the detail route /spend/logs/ui/{request_id} does
|
|
161
|
+
# too; only the list shape lacks them.
|
|
162
|
+
return (
|
|
163
|
+
"request_id" in obj
|
|
164
|
+
and "startTime" in obj
|
|
165
|
+
and "spend" in obj
|
|
166
|
+
and "total_tokens" in obj
|
|
167
|
+
and "messages" not in obj
|
|
168
|
+
and "request_body" not in obj # not Helicone
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
_V2_LIST_GUIDANCE = (
|
|
173
|
+
"LiteLLM /spend/logs/v2 list rows do not include messages/response: the "
|
|
174
|
+
"endpoint fetches only _SPEND_LOG_LIST_COLUMNS and keeps the heavy "
|
|
175
|
+
"payload columns for the detail route. Tokaudit audits token counts "
|
|
176
|
+
"from request content, so it cannot use these rows. Re-export with "
|
|
177
|
+
"message payloads: use the legacy GET /spend/logs (returns full rows "
|
|
178
|
+
"with messages) or the detail route GET /spend/logs/ui/{request_id} "
|
|
179
|
+
"per request."
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
_REQUEST_CONTENT_FIELDS = ("tools", "functions", "tool_choice", "function_call")
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _retain_content_fields(source: Dict[str, Any], target: Dict[str, Any]) -> None:
|
|
187
|
+
# The parser must see unrepresented request content before it can reject
|
|
188
|
+
# it. Dropping these fields here would bypass text-only coverage checks.
|
|
189
|
+
for key in _REQUEST_CONTENT_FIELDS:
|
|
190
|
+
if key in source:
|
|
191
|
+
target[key] = source[key]
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _retain_cache_identity(source: Dict[str, Any], target: Dict[str, Any]) -> None:
|
|
195
|
+
# These are represented request-body values, not inferred export metadata.
|
|
196
|
+
# Preserve both so parse_record applies the same precedence as plain logs.
|
|
197
|
+
for key in ("prompt_cache_key", "cache_key"):
|
|
198
|
+
if key in source:
|
|
199
|
+
target[key] = source[key]
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def adapt(obj: Dict[str, Any]) -> Dict[str, Any]:
|
|
203
|
+
"""Normalize a known export record to parse_record's input shape.
|
|
204
|
+
|
|
205
|
+
Returns the object unchanged when no adapter matches.
|
|
206
|
+
"""
|
|
207
|
+
if _is_litellm_spendlog_v2_envelope(obj):
|
|
208
|
+
raise ValueError(
|
|
209
|
+
"this looks like a LiteLLM /spend/logs/v2 paginated envelope "
|
|
210
|
+
"(data/total/page keys). " + _V2_LIST_GUIDANCE
|
|
211
|
+
)
|
|
212
|
+
if _is_litellm_spendlog_v2_list_row(obj):
|
|
213
|
+
raise ValueError(
|
|
214
|
+
f"litellm record {obj.get('request_id')}: " + _V2_LIST_GUIDANCE
|
|
215
|
+
)
|
|
216
|
+
if _is_litellm_spendlog(obj):
|
|
217
|
+
out: Dict[str, Any] = {
|
|
218
|
+
"id": obj.get("request_id"),
|
|
219
|
+
"model": obj.get("model"),
|
|
220
|
+
"ts": obj.get("startTime"),
|
|
221
|
+
"provider": obj.get("custom_llm_provider") or None,
|
|
222
|
+
}
|
|
223
|
+
_retain_content_fields(obj, out)
|
|
224
|
+
messages = obj.get("messages")
|
|
225
|
+
if isinstance(messages, str):
|
|
226
|
+
out["prompt"] = messages
|
|
227
|
+
elif isinstance(messages, list):
|
|
228
|
+
out["messages"] = messages
|
|
229
|
+
else:
|
|
230
|
+
raise ValueError(
|
|
231
|
+
f"litellm record {out['id']}: messages has unexpected type "
|
|
232
|
+
f"{type(messages).__name__}"
|
|
233
|
+
)
|
|
234
|
+
if obj.get("session_id"):
|
|
235
|
+
out["session_id"] = obj["session_id"]
|
|
236
|
+
# Provider-reported prompt tokens (typed Int field on SpendLogs).
|
|
237
|
+
# cache_hit is NOT mapped: it marks LiteLLM's own application-level
|
|
238
|
+
# cache (exact/semantic match against prior responses), not the
|
|
239
|
+
# provider's prompt cache, and SpendLogs has no cache-read token
|
|
240
|
+
# field, so cache comparison fails closed for this adapter.
|
|
241
|
+
pt = obj.get("prompt_tokens")
|
|
242
|
+
if isinstance(pt, int) and not isinstance(pt, bool) and pt >= 0:
|
|
243
|
+
out["actual_usage"] = {"prompt_tokens": pt}
|
|
244
|
+
return {k: v for k, v in out.items() if v is not None}
|
|
245
|
+
|
|
246
|
+
if _is_langfuse_observation(obj):
|
|
247
|
+
obs_type = obj.get("type")
|
|
248
|
+
if isinstance(obs_type, str) and obs_type != "GENERATION":
|
|
249
|
+
raise ValueError(
|
|
250
|
+
f"langfuse observation {obj.get('id')}: type {obs_type} is not an "
|
|
251
|
+
"LLM generation; filter the export to GENERATION observations"
|
|
252
|
+
)
|
|
253
|
+
if "input" not in obj:
|
|
254
|
+
raise ValueError(
|
|
255
|
+
f"langfuse observation {obj.get('id')}: no input field; re-export "
|
|
256
|
+
"with the `io` field group so the observation input is included"
|
|
257
|
+
)
|
|
258
|
+
inp = obj["input"]
|
|
259
|
+
out = {
|
|
260
|
+
"id": obj.get("id"),
|
|
261
|
+
"model": obj.get("model"),
|
|
262
|
+
"ts": obj.get("startTime", obj.get("start_time")),
|
|
263
|
+
"session_id": obj.get("sessionId", obj.get("session_id")),
|
|
264
|
+
}
|
|
265
|
+
# The v2 API returns input as a raw string; structured inputs arrive
|
|
266
|
+
# JSON-serialized, so try to recover messages from a string first.
|
|
267
|
+
if isinstance(inp, str):
|
|
268
|
+
try:
|
|
269
|
+
inp = json.loads(inp, object_pairs_hook=unique_object)
|
|
270
|
+
except (json.JSONDecodeError, TypeError):
|
|
271
|
+
pass # Plain text still needs the common usage normalization.
|
|
272
|
+
if isinstance(inp, list):
|
|
273
|
+
out["messages"] = inp
|
|
274
|
+
elif isinstance(inp, dict) and isinstance(inp.get("messages"), list):
|
|
275
|
+
_retain_content_fields(inp, out)
|
|
276
|
+
_retain_cache_identity(inp, out)
|
|
277
|
+
out["messages"] = inp["messages"]
|
|
278
|
+
if inp.get("system") is not None:
|
|
279
|
+
out["system"] = inp["system"]
|
|
280
|
+
elif isinstance(inp, str):
|
|
281
|
+
out["prompt"] = inp
|
|
282
|
+
else:
|
|
283
|
+
raise ValueError(
|
|
284
|
+
f"langfuse observation {out['id']}: input has unexpected shape "
|
|
285
|
+
f"({type(inp).__name__}); export the observation's messages"
|
|
286
|
+
)
|
|
287
|
+
# Provider-reported usage from usageDetails. Key families pinned by
|
|
288
|
+
# Langfuse's own provider-usage-key matrix (see module docstring).
|
|
289
|
+
# Aliases use max; distinct exclusive buckets sum (see EVIDENCE.md).
|
|
290
|
+
details = obj.get("usageDetails") or obj.get("usage_details")
|
|
291
|
+
if isinstance(details, dict):
|
|
292
|
+
usage = _langfuse_usage(details)
|
|
293
|
+
if usage:
|
|
294
|
+
out["actual_usage"] = usage
|
|
295
|
+
return {k: v for k, v in out.items() if v is not None}
|
|
296
|
+
|
|
297
|
+
if _is_helicone_row(obj):
|
|
298
|
+
body = obj.get("request_body")
|
|
299
|
+
if isinstance(body, str):
|
|
300
|
+
try:
|
|
301
|
+
body = json.loads(body, object_pairs_hook=unique_object)
|
|
302
|
+
except json.JSONDecodeError:
|
|
303
|
+
body = None
|
|
304
|
+
out = {
|
|
305
|
+
"id": obj.get("request_id"),
|
|
306
|
+
"model": obj.get("request_model") or obj.get("model"),
|
|
307
|
+
"ts": obj.get("request_created_at", obj.get("created_at")),
|
|
308
|
+
"provider": obj.get("provider"),
|
|
309
|
+
}
|
|
310
|
+
if isinstance(body, dict):
|
|
311
|
+
_retain_content_fields(body, out)
|
|
312
|
+
_retain_cache_identity(body, out)
|
|
313
|
+
if isinstance(body, dict) and isinstance(body.get("messages"), list):
|
|
314
|
+
out["messages"] = body["messages"]
|
|
315
|
+
if body.get("system") is not None:
|
|
316
|
+
out["system"] = body["system"]
|
|
317
|
+
elif isinstance(body, dict) and isinstance(body.get("prompt"), str):
|
|
318
|
+
out["prompt"] = body["prompt"]
|
|
319
|
+
else:
|
|
320
|
+
raise ValueError(
|
|
321
|
+
f"helicone row {out['id']}: request_body has no messages/prompt "
|
|
322
|
+
f"(got {type(obj.get('request_body')).__name__})"
|
|
323
|
+
)
|
|
324
|
+
# Provider-reported usage (typed fields on HeliconeRequest, verified
|
|
325
|
+
# 2026-10-28): carried through for the report's simulated-vs-reported
|
|
326
|
+
# comparison; never fed back into the simulation.
|
|
327
|
+
usage = {}
|
|
328
|
+
for src_key, dst_key in (
|
|
329
|
+
("prompt_tokens", "prompt_tokens"),
|
|
330
|
+
("prompt_cache_read_tokens", "cache_read_tokens"),
|
|
331
|
+
("prompt_cache_write_tokens", "cache_write_tokens"),
|
|
332
|
+
):
|
|
333
|
+
v = obj.get(src_key)
|
|
334
|
+
# Skip malformed values (bools, negative/fractional/non-finite counts) the same
|
|
335
|
+
# way the LiteLLM/Langfuse adapters skip theirs: reported
|
|
336
|
+
# usage only feeds the simulated-vs-reported comparison, so
|
|
337
|
+
# "no reported value" is the conservative outcome.
|
|
338
|
+
if (
|
|
339
|
+
isinstance(v, (int, float))
|
|
340
|
+
and not isinstance(v, bool)
|
|
341
|
+
and math.isfinite(v)
|
|
342
|
+
and v >= 0
|
|
343
|
+
and int(v) == v
|
|
344
|
+
):
|
|
345
|
+
usage[dst_key] = int(v)
|
|
346
|
+
if usage:
|
|
347
|
+
out["actual_usage"] = usage
|
|
348
|
+
return {k: v for k, v in out.items() if v is not None}
|
|
349
|
+
|
|
350
|
+
return obj
|
tokaudit/benchmark.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
"""Deterministic synthetic benchmark for the estimator backend.
|
|
2
|
+
|
|
3
|
+
Measures EstimatorBackend against tiktoken o200k_base on a seeded,
|
|
4
|
+
fully synthetic corpus (prose, code, JSON). The corpus is generated
|
|
5
|
+
from templates; it contains no real user or provider data. Results
|
|
6
|
+
describe estimator behaviour on THIS synthetic corpus only - they are
|
|
7
|
+
not accuracy claims about real workloads.
|
|
8
|
+
|
|
9
|
+
Run: python -m tokaudit.benchmark [--samples N] [--seed S] [--json]
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
import json
|
|
16
|
+
import math
|
|
17
|
+
import os
|
|
18
|
+
import random
|
|
19
|
+
import statistics
|
|
20
|
+
import sys
|
|
21
|
+
from dataclasses import dataclass, asdict
|
|
22
|
+
from typing import Dict, List, Optional
|
|
23
|
+
|
|
24
|
+
from .tokenizers import EstimatorBackend, TiktokenBackend
|
|
25
|
+
|
|
26
|
+
CATEGORIES = ("prose", "code", "json")
|
|
27
|
+
|
|
28
|
+
_SUBJECTS = ["the cache", "a retry loop", "the scheduler", "our metrics pipeline",
|
|
29
|
+
"the queue depth", "this dashboard", "the batch window", "a cold start"]
|
|
30
|
+
_VERBS = ["reduces", "increases", "obscures", "reveals", "delays", "smooths", "amplifies"]
|
|
31
|
+
_OBJECTS = ["tail latency", "token usage", "memory pressure", "error rates",
|
|
32
|
+
"cache hits", "queue drain time", "allocator churn"]
|
|
33
|
+
_ADVERBS = ["markedly", "slightly", "consistently", "occasionally", "sharply", "gradually"]
|
|
34
|
+
|
|
35
|
+
_CODE_TEMPLATES = [
|
|
36
|
+
"def {name}({args}):\n total = 0\n for item in {iterable}:\n total += item * {factor}\n return total\n",
|
|
37
|
+
"function {name}({args}) {{\n let acc = 0;\n for (const x of {iterable}) {{\n acc += x - {factor};\n }}\n return acc;\n}}\n",
|
|
38
|
+
"func {name}({args} []int) int {{\n acc := 0\n for _, v := range {iterable} {{\n acc += v + {factor}\n }}\n return acc\n}}\n",
|
|
39
|
+
"class {Name}:\n def __init__(self, limit={factor}):\n self.limit = limit\n self.items = []\n\n def push(self, value):\n if len(self.items) >= self.limit:\n raise OverflowError('limit exceeded')\n self.items.append(value)\n",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
_JSON_KEY_BANK = ["id", "name", "status", "latency_ms", "retries", "payload", "meta",
|
|
43
|
+
"created_at", "tokens_in", "tokens_out", "model", "region", "tags"]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _prose_sample(rng: random.Random) -> str:
|
|
47
|
+
n = rng.randint(3, 8)
|
|
48
|
+
sentences = []
|
|
49
|
+
for _ in range(n):
|
|
50
|
+
s = f"{rng.choice(_SUBJECTS).capitalize()} {rng.choice(_ADVERBS)} {rng.choice(_VERBS)} {rng.choice(_OBJECTS)}"
|
|
51
|
+
if rng.random() < 0.4:
|
|
52
|
+
s += f" when {rng.choice(_SUBJECTS)} {rng.choice(_VERBS)} {rng.choice(_OBJECTS)}"
|
|
53
|
+
sentences.append(s + ".")
|
|
54
|
+
return " ".join(sentences)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _code_sample(rng: random.Random) -> str:
|
|
58
|
+
tmpl = rng.choice(_CODE_TEMPLATES)
|
|
59
|
+
name = rng.choice(["accumulate", "summarize", "fold_values", "tally", "aggregate"])
|
|
60
|
+
return tmpl.format(
|
|
61
|
+
name=name + str(rng.randint(0, 99)),
|
|
62
|
+
Name=name.capitalize() + str(rng.randint(0, 99)),
|
|
63
|
+
args=", ".join(f"v{i}" for i in range(rng.randint(1, 3))),
|
|
64
|
+
iterable=rng.choice(["values", "batch", "rows", "chunks"]),
|
|
65
|
+
factor=rng.randint(2, 17),
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _json_value(rng: random.Random, depth: int):
|
|
70
|
+
if depth >= 4:
|
|
71
|
+
return rng.choice([None, True, rng.randint(0, 9999), "leaf"])
|
|
72
|
+
r = rng.random()
|
|
73
|
+
if r < 0.35:
|
|
74
|
+
return {rng.choice(_JSON_KEY_BANK) + str(rng.randint(0, 9)): _json_value(rng, depth + 1)
|
|
75
|
+
for _ in range(rng.randint(1, 5))}
|
|
76
|
+
if r < 0.6:
|
|
77
|
+
return [_json_value(rng, depth + 1) for _ in range(rng.randint(1, 6))]
|
|
78
|
+
return rng.choice([None, True, False, rng.randint(0, 99999), rng.uniform(0, 100),
|
|
79
|
+
"tok-" + str(rng.randint(100, 999))])
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _json_sample(rng: random.Random) -> str:
|
|
83
|
+
obj = {rng.choice(_JSON_KEY_BANK) + str(i): _json_value(rng, 1)
|
|
84
|
+
for i in range(rng.randint(2, 6))}
|
|
85
|
+
return json.dumps(obj, indent=rng.choice([None, 2, 2, 4]))
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def synthetic_corpus(samples_per_category: int = 30, seed: int = 20261029) -> Dict[str, List[str]]:
|
|
89
|
+
"""Deterministic synthetic corpus. Raises ValueError on bad inputs."""
|
|
90
|
+
if samples_per_category < 1:
|
|
91
|
+
raise ValueError("samples_per_category must be >= 1")
|
|
92
|
+
corpus: Dict[str, List[str]] = {}
|
|
93
|
+
for category in CATEGORIES:
|
|
94
|
+
rng = random.Random(f"{seed}:{category}") # str seed: stable across
|
|
95
|
+
# Python versions and processes (a tuple seed hashed per-process
|
|
96
|
+
# before 3.11 and raises TypeError on 3.11+)
|
|
97
|
+
if category == "prose":
|
|
98
|
+
gen = _prose_sample
|
|
99
|
+
elif category == "code":
|
|
100
|
+
gen = _code_sample
|
|
101
|
+
else:
|
|
102
|
+
gen = _json_sample
|
|
103
|
+
samples = [gen(rng) for _ in range(samples_per_category)]
|
|
104
|
+
if any(not s for s in samples):
|
|
105
|
+
raise ValueError(f"generator produced an empty {category} sample")
|
|
106
|
+
corpus[category] = samples
|
|
107
|
+
return corpus
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@dataclass
|
|
111
|
+
class BenchmarkRow:
|
|
112
|
+
category: str
|
|
113
|
+
samples: int
|
|
114
|
+
exact_mean: float
|
|
115
|
+
mean_abs_pct: float
|
|
116
|
+
median_abs_pct: float
|
|
117
|
+
p90_abs_pct: float
|
|
118
|
+
max_abs_pct: float
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _pct_rank(values: List[float], pct: float) -> float:
|
|
122
|
+
ordered = sorted(values)
|
|
123
|
+
rank = max(1, math.ceil(pct / 100.0 * len(ordered)))
|
|
124
|
+
return ordered[rank - 1]
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def run_benchmark(corpus: Dict[str, List[str]],
|
|
128
|
+
estimator: Optional[EstimatorBackend] = None,
|
|
129
|
+
exact: Optional[TiktokenBackend] = None) -> List[BenchmarkRow]:
|
|
130
|
+
"""Measure estimator error per category. Fails closed on empty inputs."""
|
|
131
|
+
estimator = estimator or EstimatorBackend()
|
|
132
|
+
exact = exact or TiktokenBackend()
|
|
133
|
+
rows: List[BenchmarkRow] = []
|
|
134
|
+
for category in CATEGORIES:
|
|
135
|
+
samples = corpus.get(category)
|
|
136
|
+
if not samples:
|
|
137
|
+
raise ValueError(f"benchmark corpus is missing category: {category}")
|
|
138
|
+
errors: List[float] = []
|
|
139
|
+
exact_counts: List[int] = []
|
|
140
|
+
for text in samples:
|
|
141
|
+
if not text:
|
|
142
|
+
raise ValueError(f"empty sample in category: {category}")
|
|
143
|
+
exact_n = exact.count(text)
|
|
144
|
+
if exact_n <= 0:
|
|
145
|
+
raise ValueError(f"exact backend returned no tokens for a {category} sample")
|
|
146
|
+
est_n = estimator.count(text)
|
|
147
|
+
errors.append(abs(est_n - exact_n) / exact_n * 100.0)
|
|
148
|
+
exact_counts.append(exact_n)
|
|
149
|
+
rows.append(BenchmarkRow(
|
|
150
|
+
category=category,
|
|
151
|
+
samples=len(samples),
|
|
152
|
+
exact_mean=statistics.fmean(exact_counts),
|
|
153
|
+
mean_abs_pct=statistics.fmean(errors),
|
|
154
|
+
median_abs_pct=statistics.median(errors),
|
|
155
|
+
p90_abs_pct=_pct_rank(errors, 90),
|
|
156
|
+
max_abs_pct=max(errors),
|
|
157
|
+
))
|
|
158
|
+
return rows
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def to_markdown(rows: List[BenchmarkRow]) -> str:
|
|
162
|
+
lines = [
|
|
163
|
+
"| Category | Samples | Mean exact tokens | Mean abs err | Median abs err | p90 abs err | Max abs err |",
|
|
164
|
+
"| --- | --- | --- | --- | --- | --- | --- |",
|
|
165
|
+
]
|
|
166
|
+
for r in rows:
|
|
167
|
+
lines.append(
|
|
168
|
+
f"| {r.category} | {r.samples} | {r.exact_mean:.0f} | "
|
|
169
|
+
f"{r.mean_abs_pct:.1f}% | {r.median_abs_pct:.1f}% | "
|
|
170
|
+
f"{r.p90_abs_pct:.1f}% | {r.max_abs_pct:.1f}% |"
|
|
171
|
+
)
|
|
172
|
+
return "\n".join(lines)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _chunks(text: str, sizes: List[int]) -> List[str]:
|
|
176
|
+
out: List[str] = []
|
|
177
|
+
for size in sizes:
|
|
178
|
+
if size < 1:
|
|
179
|
+
raise ValueError("chunk sizes must be >= 1")
|
|
180
|
+
for i in range(0, max(len(text) - size, 0), size):
|
|
181
|
+
out.append(text[i : i + size])
|
|
182
|
+
return [c for c in out if c.strip()]
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def run_file_benchmark(path: str, sizes: List[int],
|
|
186
|
+
estimator: Optional[EstimatorBackend] = None,
|
|
187
|
+
exact: Optional[TiktokenBackend] = None) -> BenchmarkRow:
|
|
188
|
+
"""Measure estimator error on a user-supplied text file, chunked.
|
|
189
|
+
|
|
190
|
+
Fails closed: missing, unreadable, or whitespace-only files raise
|
|
191
|
+
ValueError; a file that yields no chunks raises ValueError.
|
|
192
|
+
"""
|
|
193
|
+
try:
|
|
194
|
+
with open(path, encoding="utf-8") as fh:
|
|
195
|
+
text = fh.read()
|
|
196
|
+
except OSError as exc:
|
|
197
|
+
raise ValueError(f"cannot read benchmark file {path!r}: {exc}") from exc
|
|
198
|
+
except UnicodeDecodeError as exc:
|
|
199
|
+
raise ValueError(f"benchmark file {path!r} is not valid UTF-8: {exc}") from exc
|
|
200
|
+
if not text.strip():
|
|
201
|
+
raise ValueError(f"benchmark file {path!r} is empty")
|
|
202
|
+
chunks = _chunks(text, sizes)
|
|
203
|
+
if not chunks:
|
|
204
|
+
raise ValueError(
|
|
205
|
+
f"benchmark file {path!r} is shorter than the smallest chunk size; "
|
|
206
|
+
"add --chunk-sizes with a smaller value"
|
|
207
|
+
)
|
|
208
|
+
estimator = estimator or EstimatorBackend()
|
|
209
|
+
exact = exact or TiktokenBackend()
|
|
210
|
+
errors: List[float] = []
|
|
211
|
+
exact_counts: List[int] = []
|
|
212
|
+
for chunk in chunks:
|
|
213
|
+
exact_n = exact.count(chunk)
|
|
214
|
+
if exact_n <= 0:
|
|
215
|
+
raise ValueError(f"exact backend returned no tokens for a chunk of {path!r}")
|
|
216
|
+
errors.append(abs(estimator.count(chunk) - exact_n) / exact_n * 100.0)
|
|
217
|
+
exact_counts.append(exact_n)
|
|
218
|
+
return BenchmarkRow(
|
|
219
|
+
category=os.path.basename(path),
|
|
220
|
+
samples=len(chunks),
|
|
221
|
+
exact_mean=statistics.fmean(exact_counts),
|
|
222
|
+
mean_abs_pct=statistics.fmean(errors),
|
|
223
|
+
median_abs_pct=statistics.median(errors),
|
|
224
|
+
p90_abs_pct=_pct_rank(errors, 90),
|
|
225
|
+
max_abs_pct=max(errors),
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
230
|
+
parser = argparse.ArgumentParser(description="Benchmark the estimator.")
|
|
231
|
+
parser.add_argument("--file", help="measure on this UTF-8 text file instead of the synthetic corpus")
|
|
232
|
+
parser.add_argument("--chunk-sizes", default="200,800,3000",
|
|
233
|
+
help="comma-separated chunk sizes for --file (default 200,800,3000)")
|
|
234
|
+
parser.add_argument("--samples", type=int, default=30, help="samples per category (synthetic corpus)")
|
|
235
|
+
parser.add_argument("--seed", type=int, default=20261029)
|
|
236
|
+
parser.add_argument("--json", action="store_true", help="emit JSON instead of markdown")
|
|
237
|
+
args = parser.parse_args(argv)
|
|
238
|
+
if args.file:
|
|
239
|
+
sizes = [int(s) for s in args.chunk_sizes.split(",")]
|
|
240
|
+
rows = [run_file_benchmark(args.file, sizes)]
|
|
241
|
+
else:
|
|
242
|
+
rows = run_benchmark(synthetic_corpus(samples_per_category=args.samples, seed=args.seed))
|
|
243
|
+
if args.json:
|
|
244
|
+
print(json.dumps([asdict(r) for r in rows], indent=2))
|
|
245
|
+
else:
|
|
246
|
+
print(to_markdown(rows))
|
|
247
|
+
return 0
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
if __name__ == "__main__":
|
|
251
|
+
sys.exit(main())
|