contextgate-core 0.6.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,430 @@
1
+ """
2
+ Deterministic request gate (the core engine behind the proxy, `smarty bench` and the ledger).
3
+
4
+ Design rules (each is enforced by tests, not by convention):
5
+ 1. PROTECTED SPANS ARE NEVER TOUCHED. Text is split into protected spans (fenced/inline code, URLs, emails, paths,
6
+ identifiers, quoted strings, JSON, negation clauses) and prose; only prose is compressed. A verification pass then
7
+ checks every protected span (and every digit-bearing token) still appears verbatim, and falls back to the original
8
+ text if anything is missing. The guarantee does not depend on compression intensity.
9
+ 2. PREFIX STABILITY. Providers cache by exact prefix, so every transform is deterministic and CAUSAL: the transformed
10
+ message i depends only on messages 0..i, never on later ones. transform(msgs[:k]) == transform(msgs)[:k].
11
+ 3. VALID STRUCTURE. Tool schemas keep their exact JSON structure (types, enum, required, ...): only `description`
12
+ strings are shortened. System/assistant/tool messages are untouched by the strict profile.
13
+ 4. FAIL OPEN. Any internal error returns the request unchanged.
14
+ No network, no LLM; only the deterministic rule tables of pipeline.py.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import copy
20
+ import hashlib
21
+ import json
22
+ import re
23
+ import time
24
+ from collections import Counter
25
+ from dataclasses import dataclass, field
26
+ from typing import Any
27
+
28
+ from . import pipeline as _p # deterministic rule tables + estimate_tokens (pure Python, no heavy dependencies)
29
+
30
+ estimate_tokens = _p.estimate_tokens
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class Profile:
35
+ name: str
36
+ prose_level: int # 1 filler + lexical phrases | 2 + hedging adverbs | 3 + articles in long prose
37
+ dedupe: bool # causal exact-duplicate collapse of long messages
38
+ schemas: bool = True # shorten tool-schema descriptions
39
+
40
+
41
+ PROFILES = {
42
+ "strict": Profile("strict", 1, False),
43
+ "balanced": Profile("balanced", 2, True),
44
+ "aggressive": Profile("aggressive", 3, True),
45
+ }
46
+ DEDUPE_MIN_TOKENS = 200
47
+
48
+
49
+ # ── protected spans ───────────────────────────────────────────────────────────
50
+ _PROT_RES = [re.compile(p) for p in (
51
+ r"(?:```|~~~)[\s\S]*?(?:```|~~~|\Z)", # fenced code (also unterminated)
52
+ r"`[^`\n]+`", # inline code
53
+ r"https?://[^\s<>\"')\]]+", # URLs
54
+ r"[\w.+\-]+@[\w\-]+\.[\w.\-]+", # emails
55
+ r"(?:\.{0,2}/)?(?:[\w.\-]+/)+[\w.\-]*", # paths with a slash
56
+ r"\b[\w\-]+\.(?:py|ts|tsx|js|jsx|json|md|ya?ml|toml|txt|sh|go|rs|java|rb|cc?|cpp|hpp?|css|html|sql)\b", # file names
57
+ r"\b[a-z][a-z0-9]*(?:_[a-z0-9]+)+\b", # snake_case
58
+ r"\b[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+\b", # CONSTANT_CASE
59
+ r"\b[A-Z][a-z0-9]+(?:[A-Z][a-z0-9]*)+\b", # CamelCase
60
+ r"\b[a-z]+(?:[A-Z][a-z0-9]*)+\b", # lowerCamel
61
+ r"\b[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)+\b", # dotted names (os.path.join)
62
+ r"\"(?:\\.|[^\"\\\n]){2,}\"", # double-quoted literals
63
+ )]
64
+ _NEG_SPAN = re.compile(_p._NEGATION_SPAN_PATTERN.pattern, re.IGNORECASE) # "never modify the input" (word + up to 4)
65
+ _DIGIT_TOKEN = re.compile(r"\d[\w.\-:/,%]*")
66
+
67
+
68
+ class WorkBudgetExceeded(Exception):
69
+ """Adversarial/pathological input: the gate skips compression and forwards the original."""
70
+
71
+
72
+ _JSON_DECODER = json.JSONDecoder()
73
+ _JSON_MAX_ATTEMPTS = 4000 # candidate '{'/'[' starts that were tried
74
+ _JSON_MAX_SCAN = 4_000_000 # chars handed to the decoder in total
75
+
76
+
77
+ def _json_ranges(text: str) -> list[tuple[int, int]]:
78
+ """Regions that parse as JSON objects/arrays are protected verbatim.
79
+
80
+ Uses the C decoder (fails at the first bad token) and a hard work budget, so input like
81
+ '{' * 100000 cannot burn CPU; over budget raises WorkBudgetExceeded (caller forwards the original).
82
+ """
83
+ out: list[tuple[int, int]] = []
84
+ i, n, attempts, scanned = 0, len(text), 0, 0
85
+ while i < n:
86
+ c = text[i]
87
+ if c in "{[":
88
+ nxt = text[i + 1:i + 2].lstrip() or text[i + 1:i + 40].lstrip()[:1]
89
+ # cheap pre-filter: an object must open with a quote or '}', a list with a value start
90
+ if (c == "{" and nxt in ('"', "}")) or (c == "[" and nxt and (nxt in '"{[]-0123456789tfn')):
91
+ attempts += 1
92
+ if attempts > _JSON_MAX_ATTEMPTS:
93
+ raise WorkBudgetExceeded("json scan budget")
94
+ try:
95
+ _, end = _JSON_DECODER.raw_decode(text[i:i + 200_000])
96
+ scanned += end
97
+ if scanned > _JSON_MAX_SCAN:
98
+ raise WorkBudgetExceeded("json scan budget")
99
+ out.append((i, i + end))
100
+ i += end
101
+ continue
102
+ except json.JSONDecodeError as exc:
103
+ scanned += exc.pos + 1 # real decoder work: failing late (unterminated list) is expensive
104
+ except RecursionError:
105
+ scanned += 200_000 # deep nesting is the expensive failure (the C decoder recurses until its limit, which is
106
+ # much deeper on newer Pythons): charge it like a full-size scan
107
+ except ValueError:
108
+ scanned += 1000
109
+ if scanned > _JSON_MAX_SCAN:
110
+ raise WorkBudgetExceeded("json scan budget")
111
+ i += 1
112
+ return out
113
+
114
+
115
+ def protected_ranges(text: str) -> list[tuple[int, int]]:
116
+ spans = [m.span() for rx in _PROT_RES for m in rx.finditer(text)]
117
+ spans += [m.span() for m in _NEG_SPAN.finditer(text)]
118
+ spans += _json_ranges(text)
119
+ spans.sort()
120
+ merged: list[list[int]] = []
121
+ for s, e in spans:
122
+ if merged and s <= merged[-1][1]:
123
+ merged[-1][1] = max(merged[-1][1], e)
124
+ else:
125
+ merged.append([s, e])
126
+ return [(s, e) for s, e in merged]
127
+
128
+
129
+ # ── prose compression ─────────────────────────────────────────────────────────
130
+ def _compress_prose(seg: str, level: int) -> str:
131
+ out = seg
132
+ for pat, rep, _label in _p._LEXICAL_PHRASE_MAP:
133
+ out = pat.sub(rep, out)
134
+ for pat in _p._FILLER_PATTERNS:
135
+ out = pat.sub(" ", out)
136
+ if level >= 2:
137
+ out = _p._HEDGING_ADVERBS_RE.sub("", out)
138
+ if level >= 3 and len(out.split()) > 25:
139
+ out = _p._AGGRESSIVE_ARTICLES_RE.sub("", out)
140
+ out = re.sub(r"(?<=\S)[ \t]{2,}(?=\S)", " ", out) # collapse inner runs only: never indentation
141
+ out = re.sub(r"[ \t]+([,;.!?])", r"\1", out) # " ," left behind by a removed filler
142
+ lead, trail = seg[:len(seg) - len(seg.lstrip(" \t"))], seg[len(seg.rstrip(" \t")):]
143
+ core = out.strip(" \t")
144
+ if not core:
145
+ return lead + trail if (lead or trail) else ""
146
+ return lead + core + trail
147
+
148
+
149
+ def _compress_segments(text: str, level: int) -> str:
150
+ parts: list[str] = []
151
+ pos = 0
152
+ for s, e in protected_ranges(text):
153
+ if s > pos:
154
+ parts.append(_compress_prose(text[pos:s], level))
155
+ parts.append(text[s:e])
156
+ pos = e
157
+ if pos < len(text):
158
+ parts.append(_compress_prose(text[pos:], level))
159
+ out = "".join(parts)
160
+ if text[:1].isupper() and out[:1].islower(): # a removed opener must not lowercase the sentence
161
+ out = out[:1].upper() + out[1:]
162
+ return out
163
+
164
+
165
+ def verify(original: str, compressed: str) -> list[str]:
166
+ """Protected spans and digit-bearing tokens that did not survive verbatim (empty = safe)."""
167
+ missing: list[str] = []
168
+ for span, n in Counter(original[s:e] for s, e in protected_ranges(original)).items():
169
+ if compressed.count(span) < n:
170
+ missing.append(span)
171
+ for tok, n in Counter(_DIGIT_TOKEN.findall(original)).items():
172
+ if compressed.count(tok) < n:
173
+ missing.append(tok)
174
+ return missing
175
+
176
+
177
+ def gate_text(text: str, level: int | str = 1) -> tuple[str, bool]:
178
+ """Compress prose deterministically while keeping everything load-bearing verbatim.
179
+
180
+ ``level`` is the prose level 1-3 or a profile name (``"strict"`` = 1, ``"balanced"`` = 2, ``"aggressive"`` = 3).
181
+ Protected spans (code, URLs, emails, paths, identifiers, quoted strings, JSON, digit tokens, negation clauses) are never
182
+ altered and are re-verified afterwards.
183
+
184
+ Returns ``(text, ok)``. ``ok`` is False when verification failed or the input was pathological (work budget exceeded):
185
+ in that case ``text`` is the ORIGINAL, unchanged. The function never makes the text longer and never raises on odd input;
186
+ it raises ``ValueError`` only for an unknown ``level``.
187
+
188
+ >>> gate_text("Could you please basically fix `get_user()`, do not use recursion.", "balanced")
189
+ ('Fix `get_user()`, do not use recursion.', True)
190
+ """
191
+ if isinstance(level, str):
192
+ if level not in PROFILES:
193
+ raise ValueError(f"unknown profile {level!r}; choose from {', '.join(PROFILES)} or a level 1-3")
194
+ level = PROFILES[level].prose_level
195
+ if not isinstance(level, int) or isinstance(level, bool) or level not in (1, 2, 3):
196
+ raise ValueError(f"level must be 1, 2 or 3 (or a profile name), got {level!r}")
197
+ if not text or not text.strip():
198
+ return text, True
199
+ try:
200
+ out = _compress_segments(text, level)
201
+ except WorkBudgetExceeded:
202
+ return text, False
203
+ if out != text and verify(text, out):
204
+ return text, False
205
+ return out, True
206
+
207
+
208
+ # ── structured requests ───────────────────────────────────────────────────────
209
+ @dataclass
210
+ class GateResult:
211
+ body: dict
212
+ raw_tokens: int
213
+ fwd_tokens: int
214
+ by_category: dict[str, tuple[int, int]] = field(default_factory=dict)
215
+ fallbacks: int = 0
216
+ protected_ok: bool = True
217
+ ms: float = 0.0
218
+ applied: bool = False
219
+ error: str = ""
220
+
221
+ @property
222
+ def saved(self) -> int:
223
+ return self.raw_tokens - self.fwd_tokens
224
+
225
+
226
+ def _tok(obj: Any) -> int:
227
+ return estimate_tokens(obj if isinstance(obj, str) else json.dumps(obj, separators=(",", ":"), ensure_ascii=False))
228
+
229
+
230
+ def _walk_descriptions(node: Any, level: int, state: dict) -> Any:
231
+ if isinstance(node, dict):
232
+ out = {}
233
+ for k, v in node.items():
234
+ if k == "description" and isinstance(v, str):
235
+ new, ok = gate_text(v, level)
236
+ state["fallbacks"] += 0 if ok else 1
237
+ out[k] = new
238
+ else:
239
+ out[k] = _walk_descriptions(v, level, state)
240
+ return out
241
+ if isinstance(node, list):
242
+ return [_walk_descriptions(x, level, state) for x in node]
243
+ return node
244
+
245
+
246
+ def _text_parts(content: Any):
247
+ """Yield (container, key) pairs for every text string of an OpenAI-style message content."""
248
+ if isinstance(content, str):
249
+ return
250
+ if isinstance(content, list):
251
+ for part in content:
252
+ if isinstance(part, dict) and part.get("type") == "text" and isinstance(part.get("text"), str):
253
+ yield part, "text"
254
+
255
+
256
+ def gate_openai_request(body: dict, profile: Profile | str = "strict") -> GateResult:
257
+ """Transform an OpenAI-compatible chat request. Never raises: on any error the original body is returned."""
258
+ prof = PROFILES[profile] if isinstance(profile, str) else profile
259
+ t0 = time.perf_counter()
260
+ try:
261
+ out = copy.deepcopy(body)
262
+ state = {"fallbacks": 0}
263
+ cats = {"user_text": [0, 0], "tool_schemas": [0, 0], "duplicates": [0, 0]}
264
+ seen: dict[str, int] = {}
265
+ for i, msg in enumerate(out.get("messages") or []):
266
+ if not isinstance(msg, dict):
267
+ continue
268
+ role, content = msg.get("role"), msg.get("content")
269
+ if role == "user":
270
+ if isinstance(content, str):
271
+ new, ok = gate_text(content, prof.prose_level)
272
+ cats["user_text"][0] += _tok(content)
273
+ cats["user_text"][1] += _tok(new)
274
+ state["fallbacks"] += 0 if ok else 1
275
+ msg["content"] = new
276
+ else:
277
+ for part, key in _text_parts(content):
278
+ new, ok = gate_text(part[key], prof.prose_level)
279
+ cats["user_text"][0] += _tok(part[key])
280
+ cats["user_text"][1] += _tok(new)
281
+ state["fallbacks"] += 0 if ok else 1
282
+ part[key] = new
283
+ if prof.dedupe and isinstance(msg.get("content"), str): # causal: depends only on messages 0..i
284
+ text = msg["content"]
285
+ tk = _tok(text)
286
+ if tk >= DEDUPE_MIN_TOKENS:
287
+ h = hashlib.sha1(text.encode("utf-8", "replace")).hexdigest()
288
+ if h in seen:
289
+ ref = f"[identical to message #{seen[h]}]"
290
+ cats["duplicates"][0] += tk
291
+ cats["duplicates"][1] += _tok(ref)
292
+ msg["content"] = ref
293
+ else:
294
+ seen[h] = i
295
+ if prof.schemas and isinstance(out.get("tools"), list):
296
+ before = _tok(out["tools"])
297
+ out["tools"] = _walk_descriptions(out["tools"], prof.prose_level, state)
298
+ cats["tool_schemas"] = [before, _tok(out["tools"])]
299
+ raw_t, fwd_t = _tok({"messages": body.get("messages"), "tools": body.get("tools")}), \
300
+ _tok({"messages": out.get("messages"), "tools": out.get("tools")})
301
+ if fwd_t >= raw_t: # never forward something larger than what we received
302
+ return GateResult(body, raw_t, raw_t, {k: (a, a) for k, (a, _) in cats.items()}, state["fallbacks"],
303
+ state["fallbacks"] == 0, (time.perf_counter() - t0) * 1000, False)
304
+ return GateResult(out, raw_t, fwd_t, {k: (a, b) for k, (a, b) in cats.items()}, state["fallbacks"],
305
+ state["fallbacks"] == 0, (time.perf_counter() - t0) * 1000, True)
306
+ except Exception as exc: # fail open
307
+ t = _tok({"messages": body.get("messages"), "tools": body.get("tools")}) if isinstance(body, dict) else 0
308
+ return GateResult(body, t, t, {}, 0, True, (time.perf_counter() - t0) * 1000, False, error=f"{type(exc).__name__}: {exc}")
309
+
310
+
311
+ # ── Anthropic /v1/messages ────────────────────────────────────────────────────
312
+ # Real Claude Code requests (checked against recorded request blobs): user text blocks are mostly <system-reminder>
313
+ # wrappers (instruction text: never rewritten), assistant `thinking` blocks carry signatures (changing one character
314
+ # invalidates them), `tool_use` blocks hold exact commands. So only the user's own plain-text blocks and tool-schema
315
+ # descriptions are ever touched; system, thinking, tool_use and (in strict) tool_result are forwarded verbatim.
316
+ _NEVER_TOUCH = ("thinking", "redacted_thinking", "tool_use", "server_tool_use", "image", "document")
317
+
318
+
319
+ def _is_prose(text: str) -> bool:
320
+ s = text.lstrip()
321
+ return bool(s) and not s.startswith("<") and "<system-reminder>" not in text
322
+
323
+
324
+ def _maybe_backref(text: str, idx: int, seen: dict[str, int], cat: list[int]) -> str | None:
325
+ tk = _tok(text)
326
+ if tk < DEDUPE_MIN_TOKENS:
327
+ return None
328
+ h = hashlib.sha1(text.encode("utf-8", "replace")).hexdigest()
329
+ if h in seen:
330
+ ref = f"[identical to message #{seen[h]}]"
331
+ cat[0] += tk
332
+ cat[1] += _tok(ref)
333
+ return ref
334
+ seen[h] = idx
335
+ return None
336
+
337
+
338
+ def _anthropic_payload(b: dict) -> dict:
339
+ return {"system": b.get("system"), "messages": b.get("messages"), "tools": b.get("tools")}
340
+
341
+
342
+ def gate_anthropic_request(body: dict, profile: Profile | str = "strict") -> GateResult:
343
+ """Transform an Anthropic Messages request. Never raises: on any error the original body is returned."""
344
+ prof = PROFILES[profile] if isinstance(profile, str) else profile
345
+ t0 = time.perf_counter()
346
+ try:
347
+ out = copy.deepcopy(body)
348
+ state = {"fallbacks": 0}
349
+ cats = {"user_text": [0, 0], "tool_schemas": [0, 0], "duplicates": [0, 0]}
350
+ seen: dict[str, int] = {}
351
+ for i, msg in enumerate(out.get("messages") or []):
352
+ if not isinstance(msg, dict):
353
+ continue
354
+ content = msg.get("content")
355
+ if msg.get("role") == "user":
356
+ if isinstance(content, str):
357
+ if _is_prose(content):
358
+ new, ok = gate_text(content, prof.prose_level)
359
+ cats["user_text"][0] += _tok(content)
360
+ cats["user_text"][1] += _tok(new)
361
+ state["fallbacks"] += 0 if ok else 1
362
+ msg["content"] = new
363
+ elif isinstance(content, list):
364
+ for block in content:
365
+ if isinstance(block, dict) and block.get("type") == "text" and isinstance(block.get("text"), str) \
366
+ and _is_prose(block["text"]):
367
+ new, ok = gate_text(block["text"], prof.prose_level)
368
+ cats["user_text"][0] += _tok(block["text"])
369
+ cats["user_text"][1] += _tok(new)
370
+ state["fallbacks"] += 0 if ok else 1
371
+ block["text"] = new
372
+ if prof.dedupe: # causal exact-duplicate collapse; same rules as the OpenAI path
373
+ content = msg.get("content")
374
+ if isinstance(content, str):
375
+ ref = _maybe_backref(content, i, seen, cats["duplicates"])
376
+ if ref:
377
+ msg["content"] = ref
378
+ elif isinstance(content, list):
379
+ for block in content:
380
+ if not (isinstance(block, dict) and block.get("type") == "tool_result") or block.get("type") in _NEVER_TOUCH:
381
+ continue
382
+ inner = block.get("content")
383
+ text = inner if isinstance(inner, str) else (
384
+ "\n".join(x["text"] for x in inner) if isinstance(inner, list) and inner and all(
385
+ isinstance(x, dict) and x.get("type") == "text" and isinstance(x.get("text"), str) for x in inner) else None)
386
+ if text:
387
+ ref = _maybe_backref(text, i, seen, cats["duplicates"])
388
+ if ref:
389
+ block["content"] = ref
390
+ if prof.schemas and isinstance(out.get("tools"), list):
391
+ before = _tok(out["tools"])
392
+ out["tools"] = _walk_descriptions(out["tools"], prof.prose_level, state) # also reaches input_schema descriptions
393
+ cats["tool_schemas"] = [before, _tok(out["tools"])]
394
+ raw_t, fwd_t = _tok(_anthropic_payload(body)), _tok(_anthropic_payload(out))
395
+ if fwd_t >= raw_t:
396
+ return GateResult(body, raw_t, raw_t, {k: (a, a) for k, (a, _) in cats.items()}, state["fallbacks"],
397
+ state["fallbacks"] == 0, (time.perf_counter() - t0) * 1000, False)
398
+ return GateResult(out, raw_t, fwd_t, {k: (a, b) for k, (a, b) in cats.items()}, state["fallbacks"],
399
+ state["fallbacks"] == 0, (time.perf_counter() - t0) * 1000, True)
400
+ except Exception as exc: # fail open
401
+ t = _tok(_anthropic_payload(body)) if isinstance(body, dict) else 0
402
+ return GateResult(body, t, t, {}, 0, True, (time.perf_counter() - t0) * 1000, False, error=f"{type(exc).__name__}: {exc}")
403
+
404
+
405
+ def detect_api(body: Any) -> str:
406
+ """'anthropic' or 'openai', from the request shape (used by offline replay; the proxy knows the route)."""
407
+ if not isinstance(body, dict):
408
+ return "openai"
409
+ msgs = body.get("messages") if isinstance(body.get("messages"), list) else []
410
+ if "system" in body and not any(isinstance(m, dict) and m.get("role") == "system" for m in msgs):
411
+ return "anthropic"
412
+ tools = body.get("tools")
413
+ if isinstance(tools, list) and tools and isinstance(tools[0], dict) and "input_schema" in tools[0]:
414
+ return "anthropic"
415
+ for m in msgs:
416
+ c = m.get("content") if isinstance(m, dict) else None
417
+ if isinstance(c, list) and any(isinstance(b, dict) and b.get("type") in ("tool_use", "tool_result", "thinking") for b in c):
418
+ return "anthropic"
419
+ return "openai"
420
+
421
+
422
+ def gate_request(body: dict, profile: Profile | str = "strict", api: str | None = None) -> GateResult:
423
+ """Gate a chat request body (OpenAI-compatible or Anthropic Messages; auto-detected unless ``api`` is ``"openai"``/``"anthropic"``).
424
+
425
+ Only user plain-text and tool-schema ``description`` strings are rewritten; everything else (system prompts, signed ``thinking``,
426
+ ``tool_use``/``tool_result``, ``cache_control``) is forwarded verbatim. Never raises: on any error ``result.body`` is the original
427
+ request and ``result.error`` names the failure. ``result.body`` is never larger than the input (``result.saved >= 0``).
428
+ ``result.applied`` says whether anything changed; token counts are estimates (``estimate_tokens``), not provider counts.
429
+ """
430
+ return (gate_anthropic_request if (api or detect_api(body)) == "anthropic" else gate_openai_request)(body, profile)
@@ -0,0 +1,148 @@
1
+ """
2
+ Offline replay: run recorded (or synthetic) OpenAI-format requests through the gate and report MEASURED savings, per
3
+ profile and per transform category, with the safety counters. No network. This is how ROI gets proven on YOUR traffic:
4
+
5
+ python gateway.py --upstream ... --record traffic.jsonl # capture originals (contains your prompts: keep private)
6
+ python gate_bench.py traffic.jsonl # replay offline
7
+
8
+ Input: JSONL where each line is a request body or {"ts":..., "body": {...}} (the --record format), or a JSON array.
9
+ `--from-docs DIR` builds SYNTHETIC RAG-style requests from real text files in DIR (clearly labelled as synthetic).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import json
16
+ import os
17
+ import random
18
+ import re
19
+ import statistics
20
+ import sys
21
+ from typing import Any
22
+
23
+ from . import gate
24
+
25
+ CATEGORIES = ("user_text", "tool_schemas", "duplicates")
26
+
27
+
28
+ def load_requests(path: str) -> list[dict]:
29
+ raw = open(path, encoding="utf-8").read().strip()
30
+ if not raw:
31
+ return []
32
+ if raw[0] == "[":
33
+ items = json.loads(raw)
34
+ else:
35
+ items = [json.loads(line) for line in raw.splitlines() if line.strip()]
36
+ return [i["body"] if isinstance(i, dict) and isinstance(i.get("body"), dict) else i for i in items if isinstance(i, dict)]
37
+
38
+
39
+ def synthetic_from_docs(root: str, n: int = 30, chunks: int = 6, seed: int = 7, api: str = "openai") -> list[dict]:
40
+ """RAG-style requests: real paragraphs from real files as context, a polite filler-laden question, a tool schema."""
41
+ paras: list[str] = []
42
+ for dp, dns, fns in os.walk(root):
43
+ dns[:] = [d for d in dns if d not in {"node_modules", ".git", ".venv", "NLP-start", "__pycache__", ".smarty", "dist", "out"}]
44
+ for fn in fns:
45
+ if fn.lower().endswith((".md", ".txt", ".rst")):
46
+ try:
47
+ text = open(os.path.join(dp, fn), encoding="utf-8", errors="replace").read()
48
+ except OSError:
49
+ continue
50
+ paras += [p.strip() for p in re.split(r"\n\s*\n", text) if len(p.split()) >= 40]
51
+ if not paras:
52
+ return []
53
+ rng = random.Random(seed)
54
+ qs = ["Could you please explain how this works? I was wondering if you could basically summarise the key points.",
55
+ "I would really appreciate it if you could help me understand the setup, in order to configure it properly.",
56
+ "Can you please tell me what to change, and do not suggest anything outside of these documents?"]
57
+ tools = [{"type": "function", "function": {"name": "search_docs", "description": "Could you please use this tool in order to search the "
58
+ "documentation for the information that the user is asking about.", "parameters": {"type": "object",
59
+ "properties": {"query": {"type": "string", "description": "I would like you to provide the search query to run."}},
60
+ "required": ["query"]}}}]
61
+ out = []
62
+ for _ in range(n):
63
+ ctx = "\n\n".join(f"[doc {i + 1}]\n{rng.choice(paras)}" for i in range(chunks))
64
+ if api == "anthropic":
65
+ a_tools = [{"name": t["function"]["name"], "description": t["function"]["description"],
66
+ "input_schema": t["function"]["parameters"]} for t in tools]
67
+ out.append({"model": "synthetic", "max_tokens": 512, "system": [{"type": "text", "text": "You answer using only the provided documents."}],
68
+ "messages": [{"role": "user", "content": [{"type": "text", "text": f"{ctx}\n\n{rng.choice(qs)}"}]}], "tools": a_tools})
69
+ continue
70
+ out.append({"model": "synthetic", "messages": [{"role": "system", "content": "You answer using only the provided documents."},
71
+ {"role": "user", "content": f"{ctx}\n\n{rng.choice(qs)}"}], "tools": tools})
72
+ return out
73
+
74
+
75
+ def run(requests: list[dict], profile: str) -> dict[str, Any]:
76
+ raw = fwd = fallbacks = errors = applied = 0
77
+ apis: dict[str, int] = {}
78
+ cats = {c: [0, 0] for c in CATEGORIES}
79
+ per, ms = [], []
80
+ for body in requests:
81
+ api = gate.detect_api(body)
82
+ apis[api] = apis.get(api, 0) + 1
83
+ r = gate.gate_request(body, profile, api)
84
+ raw += r.raw_tokens
85
+ fwd += r.fwd_tokens
86
+ fallbacks += r.fallbacks
87
+ errors += 1 if r.error else 0
88
+ applied += 1 if r.applied else 0
89
+ ms.append(r.ms)
90
+ per.append(100 * r.saved / r.raw_tokens if r.raw_tokens else 0.0)
91
+ for c, (a, b) in r.by_category.items():
92
+ cats[c][0] += a
93
+ cats[c][1] += b
94
+ ms.sort()
95
+ return {"profile": profile, "requests": len(requests), "apis": apis, "applied": applied, "raw_tokens": raw, "fwd_tokens": fwd,
96
+ "saved_tokens": raw - fwd, "saved_pct": round(100 * (raw - fwd) / raw, 2) if raw else 0.0,
97
+ "per_request_saved_pct": {"min": round(min(per), 2), "median": round(statistics.median(per), 2), "max": round(max(per), 2)} if per else {},
98
+ "categories": {c: {"before": a, "after": b, "saved": a - b} for c, (a, b) in cats.items()},
99
+ "verification_fallbacks": fallbacks, "errors": errors,
100
+ "gate_ms_p50": round(statistics.median(ms), 2) if ms else 0.0, "gate_ms_p95": round(ms[int(0.95 * (len(ms) - 1))], 2) if ms else 0.0}
101
+
102
+
103
+ def format_report(results: list[dict], label: str) -> str:
104
+ mix = ", ".join(f"{n} {k}" for k, n in sorted(results[0].get("apis", {}).items()))
105
+ L = [f"{label}: {results[0]['requests']} requests ({mix}), {results[0]['raw_tokens']} estimated input tokens before gating", ""]
106
+ L.append(f"{'profile':12}{'saved':>9}{'%':>8}{'median/req':>12}{'max/req':>9} {'user text':>10}{'schemas':>9}{'dupes':>8}{'fallbacks':>10}{'p95 ms':>8}")
107
+ for r in results:
108
+ c = r["categories"]
109
+ L.append(f"{r['profile']:12}{r['saved_tokens']:>9}{r['saved_pct']:>7.2f}%{r['per_request_saved_pct'].get('median', 0):>11.2f}%"
110
+ f"{r['per_request_saved_pct'].get('max', 0):>8.2f}% {c['user_text']['saved']:>10}{c['tool_schemas']['saved']:>9}"
111
+ f"{c['duplicates']['saved']:>8}{r['verification_fallbacks']:>10}{r['gate_ms_p95']:>8}")
112
+ L.append("\nunits: estimated tokens (pipeline.estimate_tokens). Savings are for whatever workload you replayed: "
113
+ "re-run on your own recorded traffic before quoting a number.")
114
+ return "\n".join(L)
115
+
116
+
117
+ def main(argv: list[str] | None = None) -> int:
118
+ ap = argparse.ArgumentParser(prog="bench", description=__doc__.split("\n")[1])
119
+ ap.add_argument("file", nargs="?", help="JSONL/JSON of recorded requests")
120
+ ap.add_argument("--from-docs", metavar="DIR", help="build SYNTHETIC RAG requests from real text files in DIR")
121
+ ap.add_argument("--n", type=int, default=30)
122
+ ap.add_argument("--api", choices=("openai", "anthropic"), default="openai", help="shape of the --from-docs synthetic requests")
123
+ ap.add_argument("--profiles", nargs="+", default=list(gate.PROFILES), choices=sorted(gate.PROFILES))
124
+ ap.add_argument("--json", dest="json_out")
125
+ a = ap.parse_args(argv)
126
+ try:
127
+ if a.from_docs:
128
+ reqs, label = synthetic_from_docs(a.from_docs, a.n, api=a.api), f"SYNTHETIC {a.api} requests built from real documents in {a.from_docs}"
129
+ elif a.file:
130
+ reqs, label = load_requests(a.file), f"recorded requests from {a.file}"
131
+ else:
132
+ print("error: give a recorded-requests file or --from-docs DIR", file=sys.stderr)
133
+ return 2
134
+ except (OSError, ValueError) as exc:
135
+ print(f"error: {exc}", file=sys.stderr)
136
+ return 2
137
+ if not reqs:
138
+ print("error: no requests found", file=sys.stderr)
139
+ return 2
140
+ results = [run(reqs, p) for p in a.profiles]
141
+ print(format_report(results, label))
142
+ if a.json_out:
143
+ json.dump(results, open(a.json_out, "w"), indent=2)
144
+ return 0
145
+
146
+
147
+ if __name__ == "__main__":
148
+ sys.exit(main())