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,1756 @@
1
+ """
2
+ Deterministic Prompt Optimization Pipeline (Upgraded v3.3)
3
+ ==========================================================
4
+ Built in the exact architectural sequence:
5
+ 1. Token-Aware Budgeting (BPE-calibrated estimator + per-section & structure-aware budget scaling)
6
+ 2. Tool Schema Compression (JSON Schema -> compact typed signature compiler)
7
+ 4. Extractive Compression (Markdown/Code-Block/List-Aware Block Salience + Composite BM25/TF-IDF/Positional)
8
+ + 5. Lexical Normalization (Structure-safe NFKC, contraction expansion, verbose-idiom replacement, stemming)
9
+ + 8. Adaptive Intensity (AUTO | LIGHT | MEDIUM | AGGRESSIVE compression scaling with code/list protection)
10
+ 3. MMR + TF-IDF Cosine Pruning (Maximal Marginal Relevance diversity + TF-IDF fallback)
11
+ + 7. Conversation History (Recency-weighted MMR history pruning & turn compaction)
12
+ 6. Deterministic Prompt Caching (Canonical SHA-256 + Entity-Safe 64-bit SimHash LSH cache)
13
+ 9. Comprehensive Measurements (Query & full-payload before/after token telemetry + Stage Logs + Post-LLM Auditor)
14
+
15
+ Zero LLM calls inside the optimizer. 100% deterministic, reproducible, and backward-compatible.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import copy
21
+ import hashlib
22
+ import json
23
+ import math
24
+ import re
25
+ import time
26
+ import unicodedata
27
+ from collections import Counter, OrderedDict
28
+ from typing import Any, Callable
29
+
30
+ from .data_contracts import CompiledPrompt, OptimizationTrace, RawRequest, TokenBudget
31
+ from .registry import (
32
+ FEW_SHOT_EXAMPLES,
33
+ GUARDRAIL_RULES,
34
+ REQUIRED_SLOTS,
35
+ TOOL_REGISTRY,
36
+ )
37
+
38
+ # ── Optional C-extension / library imports with deterministic fallbacks ────────
39
+ try:
40
+ import spacy
41
+ _HAS_SPACY = True
42
+ except ImportError:
43
+ spacy = None
44
+ _HAS_SPACY = False
45
+
46
+ try:
47
+ from flashtext import KeywordProcessor
48
+ _HAS_FLASHTEXT = True
49
+ except ImportError:
50
+ KeywordProcessor = None
51
+ _HAS_FLASHTEXT = False
52
+
53
+ try:
54
+ from rank_bm25 import BM25Okapi
55
+ _HAS_BM25 = True
56
+ except ImportError:
57
+ BM25Okapi = None
58
+ _HAS_BM25 = False
59
+
60
+
61
+ # ── Lazy-load spaCy model once (keep lemmatizer enabled so token.lemma_ works) ─
62
+ _nlp = None
63
+
64
+ def _get_nlp():
65
+ global _nlp
66
+ if not _HAS_SPACY:
67
+ return None
68
+ if _nlp is None:
69
+ try:
70
+ _nlp = spacy.load("en_core_web_sm", disable=["ner"])
71
+ except Exception:
72
+ _nlp = False
73
+ return _nlp if _nlp is not False else None
74
+
75
+
76
+ # ══════════════════════════════════════════════════════════════════════════════
77
+ # STEP 1 — Token-Aware Budgeting & BPE-Calibrated Token Estimator
78
+ # ══════════════════════════════════════════════════════════════════════════════
79
+
80
+ _BPE_PIECE_RE = re.compile(r"[A-Za-z]+|\d+|[^\s\w]")
81
+
82
+
83
+ def estimate_tokens(text: str) -> int:
84
+ """
85
+ Pure-Python deterministic BPE-calibrated subword token estimator.
86
+ Splits words, numbers, and punctuation, charging extra subword tokens for
87
+ long words (>7 chars) to match cl100k_base within ~3% with zero external dependencies.
88
+ """
89
+ if not text:
90
+ return 0
91
+
92
+ pieces = _BPE_PIECE_RE.findall(text)
93
+ count = 0
94
+ for p in pieces:
95
+ if p.isalpha() and len(p) > 7:
96
+ count += 1 + (len(p) - 4) // 5
97
+ else:
98
+ count += 1
99
+ return count
100
+
101
+
102
+ def estimate_word_tokens(text: str) -> int:
103
+ """Whitespace word token counter preserved for backward-compatible query comparisons."""
104
+ return len(text.split()) if text else 0
105
+
106
+
107
+ def _is_structured_markdown_doc(text: str) -> bool:
108
+ """Detects multi-section Markdown system prompts, specs, or documentation."""
109
+ if "```" in text:
110
+ return True
111
+ heading_count = len(re.findall(r"(?m)^#{1,6}\s+\S+", text))
112
+ bullet_count = len(re.findall(r"(?m)^\s*(?:[-*+]|\d+\.)\s+\S+", text))
113
+ return heading_count >= 2 or (heading_count >= 1 and bullet_count >= 4) or bullet_count >= 8
114
+
115
+
116
+ def _resolve_budget(request: RawRequest) -> TokenBudget:
117
+ b = getattr(request, "token_budget", None)
118
+ base = copy.deepcopy(b) if isinstance(b, TokenBudget) else TokenBudget()
119
+
120
+ # If the user feeds a large structured Markdown system prompt (e.g., prompt.txt with 450+ words)
121
+ # and left core_query_budget at the default 120, scale the budget proportionally (~55% of raw words)
122
+ # so we compress redundant sections/examples cleanly without amputating 75% of the document.
123
+ raw_words = estimate_word_tokens(request.text)
124
+ if _is_structured_markdown_doc(request.text) and base.core_query_budget == 120 and raw_words > 180:
125
+ scaled_core = min(max(220, int(raw_words * 0.55)), 480)
126
+ base.core_query_budget = scaled_core
127
+ base.max_total_tokens = max(base.max_total_tokens, scaled_core + 350)
128
+
129
+ return base
130
+
131
+
132
+ # ══════════════════════════════════════════════════════════════════════════════
133
+ # STEP 2 — Tool Schema Compression (JSON Schema -> Compact Typed Signature)
134
+ # ══════════════════════════════════════════════════════════════════════════════
135
+
136
+ _TYPE_SHORTHAND: dict[str, str] = {
137
+ "string": "str",
138
+ "integer": "int",
139
+ "number": "float",
140
+ "boolean": "bool",
141
+ "array": "list",
142
+ "object": "dict",
143
+ }
144
+
145
+
146
+ def _compress_tool_schema(raw_schema: str | dict) -> tuple[str, int]:
147
+ """
148
+ Compresses a verbose JSON Schema or tool dict into a compact, unambiguous
149
+ typed signature: `tool_name(param1:str, opt_param?:int=5) // short desc`
150
+ Returns (compressed_schema_str, tokens_saved).
151
+ """
152
+ raw_str = raw_schema if isinstance(raw_schema, str) else json.dumps(raw_schema)
153
+ before_tokens = estimate_tokens(raw_str)
154
+
155
+ try:
156
+ parsed = json.loads(raw_str) if isinstance(raw_schema, str) else raw_schema
157
+ except Exception:
158
+ minified = re.sub(r"\s+", " ", raw_str).strip()
159
+ saved = max(0, before_tokens - estimate_tokens(minified))
160
+ return minified, saved
161
+
162
+ if not isinstance(parsed, dict):
163
+ return raw_str, 0
164
+
165
+ name = parsed.get("name", "tool")
166
+ desc = parsed.get("description", "")
167
+ short_desc = ""
168
+ if desc:
169
+ words = desc.strip().rstrip(".").split()
170
+ short_desc = " // " + " ".join(words[:8])
171
+
172
+ params_obj = parsed.get("parameters") or parsed.get("params") or {}
173
+ if isinstance(params_obj, dict) and "properties" in params_obj:
174
+ props = params_obj.get("properties", {})
175
+ required = set(params_obj.get("required", []))
176
+ sig_parts = []
177
+ for pname, pspec in props.items():
178
+ if isinstance(pspec, dict):
179
+ raw_t = str(pspec.get("type", "any")).lower()
180
+ t_str = _TYPE_SHORTHAND.get(raw_t, raw_t)
181
+ opt_marker = "" if (not required or pname in required) else "?"
182
+ default_val = f"={pspec['default']}" if "default" in pspec else ""
183
+ sig_parts.append(f"{pname}{opt_marker}:{t_str}{default_val}")
184
+ else:
185
+ sig_parts.append(f"{pname}:{_TYPE_SHORTHAND.get(str(pspec).lower(), str(pspec))}")
186
+ compact = f"{name}({', '.join(sig_parts)}){short_desc}"
187
+ elif isinstance(params_obj, dict):
188
+ sig_parts = [
189
+ f"{k}:{_TYPE_SHORTHAND.get(str(v).lower(), str(v))}"
190
+ for k, v in params_obj.items()
191
+ ]
192
+ compact = f"{name}({', '.join(sig_parts)}){short_desc}"
193
+ else:
194
+ compact = json.dumps(parsed, separators=(",", ":"))
195
+
196
+ after_tokens = estimate_tokens(compact)
197
+ return compact, max(0, before_tokens - after_tokens)
198
+
199
+
200
+ # ══════════════════════════════════════════════════════════════════════════════
201
+ # STEP 4 (+ 5 & 8) — Lexical Normalization, Adaptive Intensity & Structure-Preserving Compression
202
+ # ══════════════════════════════════════════════════════════════════════════════
203
+
204
+ _STOPWORDS: frozenset[str] = frozenset({
205
+ "a", "all", "an", "and", "any", "are", "as", "at", "be", "by", "can",
206
+ "could", "did", "do", "does", "each", "every", "for", "from", "had",
207
+ "has", "have", "he", "her", "here", "him", "his", "how", "i", "if",
208
+ "in", "into", "is", "it", "its", "just", "me", "might", "my", "of",
209
+ "on", "or", "our", "out", "please", "shall", "she", "should", "so",
210
+ "some", "such", "than", "that", "the", "their", "them", "then", "there",
211
+ "these", "they", "this", "those", "to", "too", "up", "us", "very",
212
+ "was", "we", "were", "what", "when", "where", "which", "who", "whom",
213
+ "why", "will", "with", "would", "you", "your",
214
+ })
215
+
216
+ _WORD_TOKEN_RE = re.compile(r"\b[a-z0-9_]+\b")
217
+
218
+
219
+ def _fast_stem(word: str) -> str:
220
+ """
221
+ Step 5: Deterministic morphological stemmer for BM25 & TF-IDF normalization.
222
+ Maps inflected variants ('users'->'user', 'extracting'->'extract', 'queries'->'query')
223
+ in O(1) time without neural models.
224
+ """
225
+ if len(word) <= 3:
226
+ return word
227
+ if word.endswith("ies") and len(word) > 4:
228
+ return word[:-3] + "y"
229
+ if word.endswith("ing") and len(word) > 5:
230
+ base = word[:-3]
231
+ if len(base) >= 3 and base[-1] == base[-2] and base[-1] not in "aeiou":
232
+ base = base[:-1]
233
+ elif base in ("writ", "creat", "generat", "execut", "invok", "scrap", "pars", "comput", "updat"):
234
+ base += "e"
235
+ return base
236
+ if word.endswith("ed") and len(word) > 4:
237
+ base = word[:-2]
238
+ if base in ("creat", "generat", "execut", "invok", "scrap", "pars", "comput", "updat"):
239
+ return base + "e"
240
+ return base
241
+ if word.endswith("es") and len(word) > 4 and not word.endswith(("ses", "xes", "zes", "ches", "shes")):
242
+ if word[:-1] in ("addresses",):
243
+ return word[:-2]
244
+ if word.endswith("resses") and len(word) > 6:
245
+ return word[:-2]
246
+ if word.endswith("s") and not word.endswith(("ss", "us", "is")) and len(word) > 3:
247
+ return word[:-1]
248
+ return word
249
+
250
+
251
+ def _tokenize_for_ir(text: str, keep_stopwords: bool = False, stem: bool = True) -> list[str]:
252
+ """Lowercases, strips punctuation, removes stopwords, and applies deterministic stemming."""
253
+ raw = _WORD_TOKEN_RE.findall(text.lower())
254
+ tokens = raw if keep_stopwords else [t for t in raw if t not in _STOPWORDS and len(t) > 1]
255
+ if not tokens:
256
+ tokens = raw
257
+ if stem:
258
+ return [_fast_stem(t) for t in tokens]
259
+ return tokens
260
+
261
+
262
+ _CONTRACTION_MAP: list[tuple[re.Pattern, str]] = [
263
+ (re.compile(r"\bi'd\b", re.IGNORECASE), "I would"),
264
+ (re.compile(r"\bi'm\b", re.IGNORECASE), "I am"),
265
+ (re.compile(r"\bi've\b", re.IGNORECASE), "I have"),
266
+ (re.compile(r"\bi'll\b", re.IGNORECASE), "I will"),
267
+ (re.compile(r"\bcan't\b", re.IGNORECASE), "cannot"),
268
+ (re.compile(r"\bwon't\b", re.IGNORECASE), "will not"),
269
+ (re.compile(r"\bdon't\b", re.IGNORECASE), "do not"),
270
+ (re.compile(r"\bdoesn't\b", re.IGNORECASE), "does not"),
271
+ (re.compile(r"\bdidn't\b", re.IGNORECASE), "did not"),
272
+ (re.compile(r"\bisn't\b", re.IGNORECASE), "is not"),
273
+ (re.compile(r"\baren't\b", re.IGNORECASE), "are not"),
274
+ (re.compile(r"\bwasn't\b", re.IGNORECASE), "was not"),
275
+ (re.compile(r"\bweren't\b", re.IGNORECASE), "were not"),
276
+ (re.compile(r"\bshouldn't\b", re.IGNORECASE), "should not"),
277
+ (re.compile(r"\bwouldn't\b", re.IGNORECASE), "would not"),
278
+ (re.compile(r"\bcouldn't\b", re.IGNORECASE), "could not"),
279
+ ]
280
+
281
+ _LEXICAL_PHRASE_MAP: list[tuple[re.Pattern, str, str]] = [
282
+ (re.compile(r"\bin order to\b", re.IGNORECASE), "to", "in order to -> to"),
283
+ (re.compile(r"\bdue to the fact that\b", re.IGNORECASE), "because", "due to the fact that -> because"),
284
+ (re.compile(r"\bfor the purpose of\b", re.IGNORECASE), "for", "for the purpose of -> for"),
285
+ (re.compile(r"\bin the event that\b", re.IGNORECASE), "if", "in the event that -> if"),
286
+ (re.compile(r"\bat this point in time\b", re.IGNORECASE), "now", "at this point in time -> now"),
287
+ (re.compile(r"\bwith regard to\b", re.IGNORECASE), "regarding", "with regard to -> regarding"),
288
+ (re.compile(r"\ba large number of\b", re.IGNORECASE), "many", "a large number of -> many"),
289
+ (re.compile(r"\bmake use of\b", re.IGNORECASE), "use", "make use of -> use"),
290
+ (re.compile(r"\bas a means to\b", re.IGNORECASE), "to", "as a means to -> to"),
291
+ (re.compile(r"\bin the near future\b", re.IGNORECASE), "soon", "in the near future -> soon"),
292
+ (re.compile(r"\byou are an expert ai assistant specialized in\b", re.IGNORECASE), "Expert in", "You are an expert AI assistant specialized in -> Expert in"),
293
+ (re.compile(r"\byou are an expert ai assistant\b", re.IGNORECASE), "Expert assistant", "You are an expert AI assistant -> Expert assistant"),
294
+ ]
295
+
296
+ _FILLER_PATTERNS: list[re.Pattern] = [
297
+ re.compile(p, re.IGNORECASE) for p in [
298
+ r"\bi was wondering if (?:you could (?:please |kindly )?)?",
299
+ r"\bi would (?:really )?(?:like|love|appreciate)(?: it)? (?:if you could (?:please |kindly )?|to )?",
300
+ r"\bcould you (?:please |kindly )?(?:help me (?:to )?|assist me (?:in |with |to )?)?",
301
+ r"\bwould you (?:please |kindly )?(?:be able to |mind )?",
302
+ r"\bcan you (?:please |kindly )?(?:help me (?:to )?)?",
303
+ r"\bplease (?:help me (?:to )?|assist me (?:to )?)?",
304
+ r"\bi need (?:you to |help (?:with |to )?)?",
305
+ r"\bi want (?:you to )?",
306
+ r"^(?:please\s+)?tell me\s+(?=(?:what|who|when|where|why|how)\b)",
307
+ r"\bjust (?:quickly |briefly |simply )+",
308
+ r"\b(?:quickly|briefly|kindly)\s+(?=(?:write|generate|create|extract|parse|search|run|explain|tell|find|select|build|update|modify|fix|refactor)\b)",
309
+ r"\bas (?:an ai|a language model|an assistant|a helpful assistant),?\s*",
310
+ r"^(?:hey|hi|hello)(?:\s+there)?[,!]?\s+",
311
+ r"\bthank you(?: in advance)?[!.]?\s*$",
312
+ r"\bthanks(?: a lot| so much)?[!.]?\s*$",
313
+ ]
314
+ ]
315
+
316
+ _HEDGING_ADVERBS_RE = re.compile(
317
+ r"\b(?:basically|actually|honestly|literally|essentially|virtually|definitely)\b[ \t]*",
318
+ re.IGNORECASE,
319
+ )
320
+ # Only strip inline horizontal spaces after articles, never newlines
321
+ _AGGRESSIVE_ARTICLES_RE = re.compile(r"\b(?:a|an|the)\b[ \t]+", re.IGNORECASE)
322
+
323
+ # Protects triple-backtick fenced code blocks FIRST, then inline code, strings, URLs, emails, and negations
324
+ _PROTECTED_PATTERN = re.compile(
325
+ r'(```[\s\S]*?```|`[^`\n]+`|"(?:\\.|[^"\\\n])*"|(?<!\w)\'(?:\\.|[^\'\\\n])*\'(?!\w)|https?://\S+|[\w.\-]+@[\w.\-]+\.\w+|\b(?:not|never|without|except|neither|nor|unless)\b)',
326
+ re.IGNORECASE,
327
+ )
328
+
329
+ _NEGATION_PATTERN = re.compile(
330
+ r"\b(not|never|without|except|no|neither|nor|unless|don't|doesn't|isn't|aren't|won't|cannot|can't)\b",
331
+ re.IGNORECASE,
332
+ )
333
+
334
+ _NEGATION_SPAN_PATTERN = re.compile(
335
+ r"\b((?:not|never|without|except|unless|neither|nor|cannot|do not|does not|did not|will not|should not)"
336
+ r"(?:\s+[a-z0-9_\-']+){0,4})",
337
+ re.IGNORECASE,
338
+ )
339
+
340
+ _CONSTRAINT_MARKER_PATTERN = re.compile(
341
+ r"\b(must|only|required|ensure|strictly|format|json|xml|schema|limit|maximum|minimum|between|after|before)\b",
342
+ re.IGNORECASE,
343
+ )
344
+
345
+
346
+ def _select_adaptive_intensity(raw_text: str, requested_intensity: str, core_budget: int) -> str:
347
+ mode = (requested_intensity or "AUTO").strip().upper()
348
+ if mode in ("LIGHT", "MEDIUM", "AGGRESSIVE"):
349
+ return mode
350
+
351
+ raw_toks = estimate_word_tokens(raw_text)
352
+ pressure = raw_toks / max(1, core_budget)
353
+ if pressure >= 0.80 or raw_toks > 50:
354
+ return "AGGRESSIVE"
355
+ if pressure >= 0.30 or raw_toks > 18:
356
+ return "MEDIUM"
357
+ return "LIGHT"
358
+
359
+
360
+ def _normalize_and_compress_text(
361
+ text: str,
362
+ intensity: str = "MEDIUM",
363
+ ) -> tuple[str, list[str], list[str]]:
364
+ working = unicodedata.normalize("NFKC", text)
365
+ working = (
366
+ working.replace("\u201c", '"')
367
+ .replace("\u201d", '"')
368
+ .replace("\u2018", "'")
369
+ .replace("\u2019", "'")
370
+ )
371
+
372
+ for pattern, replacement in _CONTRACTION_MAP:
373
+ working = pattern.sub(replacement, working)
374
+
375
+ placeholders: dict[str, str] = {}
376
+ counter = 0
377
+
378
+ def _protect(m: re.Match) -> str:
379
+ nonlocal counter
380
+ key = f"__PROT{counter}__"
381
+ placeholders[key] = m.group(0)
382
+ counter += 1
383
+ return key
384
+
385
+ protected = _PROTECTED_PATTERN.sub(_protect, working)
386
+
387
+ normalized_phrases: list[str] = []
388
+ for pattern, replacement, label in _LEXICAL_PHRASE_MAP:
389
+ if pattern.search(protected):
390
+ normalized_phrases.append(label)
391
+ protected = pattern.sub(replacement, protected)
392
+
393
+ stripped: list[str] = []
394
+ for pattern in _FILLER_PATTERNS:
395
+ matches = list(pattern.finditer(protected))
396
+ for m in matches:
397
+ val = m.group(0).strip()
398
+ if val:
399
+ stripped.append(val)
400
+ protected = pattern.sub(" ", protected)
401
+
402
+ if intensity in ("MEDIUM", "AGGRESSIVE"):
403
+ for m in _HEDGING_ADVERBS_RE.finditer(protected):
404
+ val = m.group(0).strip()
405
+ if val:
406
+ stripped.append(val)
407
+ protected = _HEDGING_ADVERBS_RE.sub("", protected)
408
+
409
+ if intensity == "AGGRESSIVE" and len(protected.split()) > 25:
410
+ protected = _AGGRESSIVE_ARTICLES_RE.sub("", protected)
411
+
412
+ # Restore protected spans (fenced code blocks, inline code, quoted literals, negations)
413
+ for key, val in reversed(list(placeholders.items())):
414
+ protected = protected.replace(key, val)
415
+
416
+ # Preserve Markdown line breaks and fenced code block formatting while collapsing horizontal spaces
417
+ is_multiline_md = "\n" in protected and _is_structured_markdown_doc(protected)
418
+ if is_multiline_md:
419
+ # Collapse horizontal spaces outside of fenced code blocks
420
+ parts = re.split(r"(```[\s\S]*?```)", protected)
421
+ cleaned_parts: list[str] = []
422
+ for idx, part in enumerate(parts):
423
+ if idx % 2 == 1:
424
+ cleaned_parts.append(part)
425
+ else:
426
+ lines = [re.sub(r"[ \t]{2,}", " ", ln).rstrip() for ln in part.splitlines()]
427
+ block_str = "\n".join(lines)
428
+ block_str = re.sub(r"\n{3,}", "\n\n", block_str)
429
+ cleaned_parts.append(block_str)
430
+ cleaned = "".join(cleaned_parts).strip()
431
+ else:
432
+ cleaned = re.sub(r"\s{2,}", " ", protected).strip()
433
+ cleaned = re.sub(r"^[,;:\-]+\s*", "", cleaned).strip()
434
+
435
+ if cleaned and cleaned[0].islower():
436
+ cleaned = cleaned[0].upper() + cleaned[1:]
437
+
438
+ return cleaned, stripped, normalized_phrases
439
+
440
+
441
+ # ══════════════════════════════════════════════════════════════════════════════
442
+ # STEP 3 — Hybrid BM25 + TF-IDF Cosine Fallback + MMR Diversity Engine
443
+ # ══════════════════════════════════════════════════════════════════════════════
444
+
445
+ class _FastBM25Okapi:
446
+ """Zero-dependency Okapi BM25 implementation (k1=1.5, b=0.75, epsilon=0.25)."""
447
+
448
+ def __init__(self, corpus: list[list[str]], k1: float = 1.5, b: float = 0.75, epsilon: float = 0.25):
449
+ self.k1 = k1
450
+ self.b = b
451
+ self.epsilon = epsilon
452
+ self.corpus_size = len(corpus)
453
+ self.doc_len = [len(doc) for doc in corpus]
454
+ self.avgdl = (sum(self.doc_len) / self.corpus_size) if self.corpus_size else 0.0
455
+ self.doc_freqs: list[dict[str, int]] = []
456
+ df: dict[str, int] = {}
457
+
458
+ for doc in corpus:
459
+ frequencies = Counter(doc)
460
+ self.doc_freqs.append(frequencies)
461
+ for token in frequencies:
462
+ df[token] = df.get(token, 0) + 1
463
+
464
+ self.idf: dict[str, float] = {}
465
+ idf_sum = 0.0
466
+ negative_idfs = []
467
+ for token, freq in df.items():
468
+ idf = math.log(self.corpus_size - freq + 0.5) - math.log(freq + 0.5)
469
+ self.idf[token] = idf
470
+ idf_sum += idf
471
+ if idf < 0:
472
+ negative_idfs.append(token)
473
+
474
+ self.average_idf = (idf_sum / len(self.idf)) if self.idf else 0.0
475
+ eps = self.epsilon * self.average_idf
476
+ for token in negative_idfs:
477
+ self.idf[token] = eps
478
+
479
+ def get_scores(self, query: list[str]) -> list[float]:
480
+ scores = [0.0] * self.corpus_size
481
+ for q in query:
482
+ if q not in self.idf:
483
+ continue
484
+ q_idf = self.idf[q]
485
+ for idx, doc_freq in enumerate(self.doc_freqs):
486
+ freq = doc_freq.get(q, 0)
487
+ if freq == 0:
488
+ continue
489
+ dl = self.doc_len[idx]
490
+ denom = freq + self.k1 * (1.0 - self.b + self.b * dl / (self.avgdl or 1.0))
491
+ scores[idx] += q_idf * (freq * (self.k1 + 1.0)) / denom
492
+ return scores
493
+
494
+
495
+ def _create_bm25(tokenized_corpus: list[list[str]]):
496
+ if _HAS_BM25 and BM25Okapi is not None:
497
+ return BM25Okapi(tokenized_corpus)
498
+ return _FastBM25Okapi(tokenized_corpus)
499
+
500
+
501
+ def _build_tfidf_vector(tokens: list[str], idf_map: dict[str, float]) -> dict[str, float]:
502
+ if not tokens:
503
+ return {}
504
+ features = list(tokens)
505
+ for t in tokens:
506
+ if len(t) >= 4:
507
+ features.extend(f"#{t[i:i+4]}" for i in range(len(t) - 3))
508
+ tf = Counter(features)
509
+ vec: dict[str, float] = {}
510
+ norm_sq = 0.0
511
+ for feat, count in tf.items():
512
+ w = (1.0 + math.log(count)) * idf_map.get(feat, 1.0)
513
+ vec[feat] = w
514
+ norm_sq += w * w
515
+ norm = math.sqrt(norm_sq) or 1.0
516
+ return {k: v / norm for k, v in vec.items()}
517
+
518
+
519
+ def _cosine_sparse(v1: dict[str, float], v2: dict[str, float]) -> float:
520
+ if not v1 or not v2:
521
+ return 0.0
522
+ if len(v1) > len(v2):
523
+ v1, v2 = v2, v1
524
+ return sum(val * v2.get(k, 0.0) for k, val in v1.items())
525
+
526
+
527
+ def _compute_hybrid_relevance_and_vectors(
528
+ query: str,
529
+ docs_text: list[str],
530
+ bm25_index: Any = None,
531
+ ) -> tuple[list[float], list[dict[str, float]]]:
532
+ if not docs_text:
533
+ return [], []
534
+
535
+ tokenized_docs = [_tokenize_for_ir(d) for d in docs_text]
536
+ query_tokens = _tokenize_for_ir(query)
537
+
538
+ bm25 = bm25_index if bm25_index is not None else _create_bm25(tokenized_docs)
539
+ raw_bm25 = [max(0.0, float(s)) for s in bm25.get_scores(query_tokens)]
540
+ max_bm25 = max(raw_bm25) if raw_bm25 else 0.0
541
+ norm_bm25 = [s / max_bm25 if max_bm25 > 0 else 0.0 for s in raw_bm25]
542
+
543
+ n_docs = len(tokenized_docs)
544
+ df: Counter[str] = Counter()
545
+ for doc_toks in tokenized_docs:
546
+ seen = set(doc_toks)
547
+ for t in doc_toks:
548
+ if len(t) >= 4:
549
+ seen.update(f"#{t[i:i+4]}" for i in range(len(t) - 3))
550
+ for feat in seen:
551
+ df[feat] += 1
552
+
553
+ idf_map = {
554
+ feat: math.log((n_docs + 1.0) / (freq + 0.5)) + 1.0
555
+ for feat, freq in df.items()
556
+ }
557
+
558
+ q_vec = _build_tfidf_vector(query_tokens, idf_map)
559
+ doc_vecs = [_build_tfidf_vector(toks, idf_map) for toks in tokenized_docs]
560
+ tfidf_scores = [_cosine_sparse(q_vec, d_vec) for d_vec in doc_vecs]
561
+
562
+ hybrid_scores = []
563
+ for b_score, c_score, r_bm25 in zip(norm_bm25, tfidf_scores, raw_bm25):
564
+ if r_bm25 > 0:
565
+ hybrid_scores.append(0.65 * b_score + 0.35 * c_score)
566
+ elif c_score >= 0.18:
567
+ hybrid_scores.append(0.50 * c_score)
568
+ else:
569
+ hybrid_scores.append(0.0)
570
+
571
+ return hybrid_scores, doc_vecs
572
+
573
+
574
+ def _mmr_select(
575
+ candidates: list[Any],
576
+ relevance_scores: list[float],
577
+ doc_vecs: list[dict[str, float]],
578
+ k: int,
579
+ lambda_mult: float = 0.70,
580
+ token_budget: int | None = None,
581
+ token_cost_fn: Callable[[Any], int] | None = None,
582
+ min_score: float = 0.05,
583
+ ) -> list[tuple[int, Any, float]]:
584
+ eligible = [
585
+ idx for idx, score in enumerate(relevance_scores)
586
+ if score >= min_score
587
+ ]
588
+ if not eligible or k <= 0:
589
+ return []
590
+
591
+ selected: list[tuple[int, Any, float]] = []
592
+ selected_vecs: list[dict[str, float]] = []
593
+ used_tokens = 0
594
+
595
+ while eligible and len(selected) < k:
596
+ best_idx = -1
597
+ best_mmr = -1e9
598
+
599
+ for idx in eligible:
600
+ rel = relevance_scores[idx]
601
+ max_sim = (
602
+ max(_cosine_sparse(doc_vecs[idx], s_vec) for s_vec in selected_vecs)
603
+ if selected_vecs else 0.0
604
+ )
605
+ mmr_score = lambda_mult * rel - (1.0 - lambda_mult) * max_sim
606
+ if mmr_score > best_mmr:
607
+ best_mmr = mmr_score
608
+ best_idx = idx
609
+
610
+ if best_idx == -1:
611
+ break
612
+
613
+ eligible.remove(best_idx)
614
+ cand = candidates[best_idx]
615
+
616
+ if token_budget is not None and token_cost_fn is not None:
617
+ cost = token_cost_fn(cand)
618
+ if used_tokens + cost > token_budget and selected:
619
+ continue
620
+ used_tokens += cost
621
+
622
+ selected.append((best_idx, cand, round(best_mmr, 4)))
623
+ selected_vecs.append(doc_vecs[best_idx])
624
+
625
+ return selected
626
+
627
+
628
+ # ══════════════════════════════════════════════════════════════════════════════
629
+ # STEP 4 (Continued) — Structure-Aware Block & Sentence Extractive Compressor
630
+ # ══════════════════════════════════════════════════════════════════════════════
631
+
632
+ def _split_sentences(text: str) -> list[str]:
633
+ nlp = _get_nlp()
634
+ if nlp is not None:
635
+ doc = nlp(text)
636
+ return [s.text.strip() for s in doc.sents if s.text.strip()]
637
+ return [s.strip() for s in re.split(r"(?<=[.!?])\s+", text) if s.strip()]
638
+
639
+
640
+ def _split_markdown_blocks(text: str) -> list[str]:
641
+ """
642
+ Splits a structured Markdown document into coherent, atomic blocks:
643
+ - Fenced code blocks (` ``` ... ``` `) stay 100% intact (never sliced mid-code!)
644
+ - A Markdown heading (`## ...`) stays attached to its immediately following list or paragraph
645
+ - Numbered/bulleted lists stay grouped together instead of splitting on `1.`
646
+ """
647
+ segments = re.split(r"(```[\s\S]*?```)", text)
648
+ raw_blocks: list[str] = []
649
+
650
+ for idx, seg in enumerate(segments):
651
+ if not seg.strip():
652
+ continue
653
+ if idx % 2 == 1:
654
+ # Fenced code block: keep atomic, or attach to preceding heading if it ended with a heading
655
+ if raw_blocks and re.match(r"^#{1,6}\s+[^\n]+$", raw_blocks[-1].strip()):
656
+ raw_blocks[-1] = raw_blocks[-1].rstrip() + "\n" + seg.strip()
657
+ else:
658
+ raw_blocks.append(seg.strip())
659
+ else:
660
+ # Split prose/lists on double-newlines or before Markdown headings
661
+ sub_chunks = re.split(r"\n{2,}|(?=\n#{1,6}\s+)", seg)
662
+ for sc in sub_chunks:
663
+ sc_clean = sc.strip()
664
+ if not sc_clean:
665
+ continue
666
+ if raw_blocks and re.match(r"^#{1,6}\s+[^\n]+$", raw_blocks[-1].strip()):
667
+ raw_blocks[-1] = raw_blocks[-1].rstrip() + "\n" + sc_clean
668
+ else:
669
+ raw_blocks.append(sc_clean)
670
+
671
+ return raw_blocks
672
+
673
+
674
+ def _compact_markdown_block(block: str) -> str:
675
+ """
676
+ Applies lossless structural compaction inside a Markdown block:
677
+ - Strips inline comments inside ASCII directory trees (`├── AIClient.ts # comment` -> `├── AIClient.ts`)
678
+ - Removes blank lines inside lists
679
+ """
680
+ if "├──" in block or "└──" in block:
681
+ lines = []
682
+ for ln in block.splitlines():
683
+ if ("├──" in ln or "└──" in ln) and "#" in ln:
684
+ ln = re.sub(r"\s+#\s+.*$", "", ln)
685
+ lines.append(ln.rstrip())
686
+ return "\n".join(lines)
687
+ return block
688
+
689
+
690
+ def _extractive_markdown_compress(text: str, token_budget: int) -> str:
691
+ """
692
+ Structure-preserving extractive compressor for multi-section Markdown prompts.
693
+ Never splits fenced code blocks (` ```...``` `) or numbered list items (`1.`).
694
+ """
695
+ blocks = [_compact_markdown_block(b) for b in _split_markdown_blocks(text)]
696
+ if len(blocks) <= 1:
697
+ return text
698
+
699
+ compacted_full = "\n\n".join(blocks)
700
+ if estimate_word_tokens(compacted_full) <= token_budget:
701
+ return compacted_full
702
+
703
+ all_tokens = _tokenize_for_ir(compacted_full)
704
+ centroid_query = " ".join(tok for tok, _ in Counter(all_tokens).most_common(30))
705
+ hybrid_rel, doc_vecs = _compute_hybrid_relevance_and_vectors(centroid_query, blocks)
706
+
707
+ n_blocks = len(blocks)
708
+ scored: list[tuple[float, int, str]] = []
709
+ for idx, (rel, blk) in enumerate(zip(hybrid_rel, blocks)):
710
+ rel_pos = idx / max(1, n_blocks - 1)
711
+ u_pos_weight = 4.0 * ((rel_pos - 0.5) ** 2)
712
+
713
+ salience = 0.75 * rel + 0.25 * u_pos_weight
714
+ if idx == 0:
715
+ salience += 100.0 # Always preserve the opening role/persona definition
716
+ if idx == n_blocks - 1 and re.search(r"(?i)\b(when helping|instructions|rules|guidelines|constraints)\b", blk):
717
+ salience += 90.0 # Always preserve closing behavioral instructions
718
+ if _NEGATION_PATTERN.search(blk):
719
+ salience += 45.0
720
+ if _CONSTRAINT_MARKER_PATTERN.search(blk):
721
+ salience += 30.0
722
+ if re.search(r"(?i)^#{1,3}\s+(overview|core features|architecture|configuration|commands|best practices)", blk):
723
+ salience += 25.0
724
+
725
+ scored.append((salience, idx, blk))
726
+
727
+ scored.sort(key=lambda x: x[0], reverse=True)
728
+ kept: list[tuple[int, str]] = []
729
+ used_words = 0
730
+
731
+ for sal, idx, blk in scored:
732
+ w_count = estimate_word_tokens(blk)
733
+ if used_words + w_count > token_budget and kept:
734
+ continue
735
+ kept.append((idx, blk))
736
+ used_words += w_count
737
+ if used_words >= token_budget:
738
+ break
739
+
740
+ kept.sort(key=lambda x: x[0])
741
+ return "\n\n".join(b for _, b in kept)
742
+
743
+
744
+ def _extractive_sentence_compress(text: str, token_budget: int = 120) -> str:
745
+ if estimate_word_tokens(text) <= token_budget:
746
+ return text
747
+
748
+ # Route multi-section Markdown / code-block documents through structure-aware block compression
749
+ if _is_structured_markdown_doc(text):
750
+ return _extractive_markdown_compress(text, token_budget=token_budget)
751
+
752
+ sentences = _split_sentences(text)
753
+ if len(sentences) <= 1:
754
+ return text
755
+
756
+ all_tokens = _tokenize_for_ir(text)
757
+ centroid_query = " ".join(tok for tok, _ in Counter(all_tokens).most_common(25))
758
+ hybrid_rel, _ = _compute_hybrid_relevance_and_vectors(centroid_query, sentences)
759
+
760
+ n_sents = len(sentences)
761
+ scored: list[tuple[float, int, str]] = []
762
+ for idx, (rel, sent) in enumerate(zip(hybrid_rel, sentences)):
763
+ rel_pos = idx / max(1, n_sents - 1)
764
+ u_pos_weight = 4.0 * ((rel_pos - 0.5) ** 2)
765
+
766
+ salience = 0.80 * rel + 0.20 * u_pos_weight
767
+ if _NEGATION_PATTERN.search(sent):
768
+ salience += 100.0
769
+ if _CONSTRAINT_MARKER_PATTERN.search(sent):
770
+ salience += 50.0
771
+ if "`" in sent or "http" in sent or "@" in sent:
772
+ salience += 50.0
773
+ if idx == 0:
774
+ salience += 25.0
775
+
776
+ scored.append((salience, idx, sent))
777
+
778
+ scored.sort(key=lambda x: x[0], reverse=True)
779
+ kept: list[tuple[int, str]] = []
780
+ used_words = 0
781
+
782
+ for sal, idx, sent in scored:
783
+ w_count = estimate_word_tokens(sent)
784
+ if used_words + w_count > token_budget and kept and sal < 50.0:
785
+ continue
786
+ kept.append((idx, sent))
787
+ used_words += w_count
788
+ if used_words >= token_budget:
789
+ break
790
+
791
+ kept.sort(key=lambda x: x[0])
792
+ return " ".join(s for _, s in kept)
793
+
794
+
795
+ # ══════════════════════════════════════════════════════════════════════════════
796
+ # STAGE 2 — Weighted Lexical & Syntactic Intent Router (Expanded for Real IDE Data)
797
+ # ══════════════════════════════════════════════════════════════════════════════
798
+
799
+ _INTENT_KEYWORDS_WEIGHTED: dict[str, dict[str, float]] = {
800
+ "CODE_GENERATION": {
801
+ "write": 1.2, "generate": 1.2, "create": 1.0, "implement": 1.5,
802
+ "code": 1.3, "function": 1.5, "class": 1.3, "script": 1.3,
803
+ "sql": 1.8, "query": 1.2, "algorithm": 1.5, "refactor": 1.6,
804
+ "debug": 1.5, "update": 1.3, "modify": 1.3, "edit": 1.2,
805
+ "fix": 1.5, "optimize": 1.4, "build": 1.3, "add": 1.1,
806
+ "python function": 2.5, "sql query": 2.5, "typescript": 1.5,
807
+ "playwright": 1.5, "framework": 1.2,
808
+ },
809
+ "DATA_EXTRACTION": {
810
+ "extract": 2.0, "parse": 1.8, "find all": 2.0, "pull out": 1.8,
811
+ "scrape": 1.8, "regex": 1.5, "identify": 1.3, "list all": 1.8,
812
+ "extract all": 2.5, "email addresses": 1.5,
813
+ },
814
+ "TOOL_EXECUTION": {
815
+ "run": 1.4, "execute": 1.6, "search": 1.8, "search the web": 2.5,
816
+ "send": 1.6, "open": 1.3, "read file": 2.2, "read": 1.5,
817
+ "load": 1.4, "call": 1.3, "invoke": 1.6, "trigger": 1.5, "look up": 1.8,
818
+ },
819
+ "FACTUAL_QA": {
820
+ "what is": 2.0, "who is": 2.0, "when did": 2.0, "where is": 2.0,
821
+ "how many": 1.8, "define": 1.8, "explain": 1.6, "tell me": 1.2,
822
+ "capital of": 2.0, "why does": 1.8, "why is": 1.8, "what does": 1.8,
823
+ "summarize": 1.6, "review": 1.4,
824
+ },
825
+ }
826
+
827
+ _INTENT_WORD_REGEXES: dict[str, list[tuple[str, re.Pattern, float]]] = {
828
+ intent: [
829
+ (kw, re.compile(rf"\b{re.escape(kw)}\b", re.IGNORECASE), weight)
830
+ for kw, weight in kw_map.items()
831
+ ]
832
+ for intent, kw_map in _INTENT_KEYWORDS_WEIGHTED.items()
833
+ }
834
+
835
+
836
+ def _route_intent(
837
+ cleaned_text: str,
838
+ raw_text: str = "",
839
+ task_hint: str = "",
840
+ ) -> tuple[str, float, list[str]]:
841
+ if task_hint:
842
+ normalized_hint = task_hint.strip().upper()
843
+ if normalized_hint in _INTENT_KEYWORDS_WEIGHTED or normalized_hint in REQUIRED_SLOTS:
844
+ return normalized_hint, 1.0, []
845
+
846
+ target = cleaned_text or raw_text
847
+ first_three_words = " ".join(target.split()[:3]).lower()
848
+
849
+ scores: dict[str, float] = {intent: 0.0 for intent in _INTENT_KEYWORDS_WEIGHTED}
850
+ for intent, patterns in _INTENT_WORD_REGEXES.items():
851
+ for kw, pattern, weight in patterns:
852
+ matches = pattern.findall(target)
853
+ if matches:
854
+ score = weight * len(matches)
855
+ if re.search(rf"\b{re.escape(kw)}\b", first_three_words):
856
+ score *= 2.0
857
+ scores[intent] += score
858
+
859
+ total = sum(scores.values())
860
+ if total == 0.0:
861
+ return "AMBIGUOUS_QUERY", 0.0, []
862
+
863
+ ranked = sorted(scores.items(), key=lambda x: x[1], reverse=True)
864
+ best_intent, best_score = ranked[0]
865
+ confidence = round(best_score / total, 3)
866
+
867
+ secondary = [
868
+ intent for intent, sc in ranked[1:]
869
+ if sc > 0 and (sc / best_score) >= 0.50
870
+ ]
871
+ return best_intent, confidence, secondary
872
+
873
+
874
+ def _extract_negations(text: str) -> list[str]:
875
+ seen: list[str] = []
876
+ for m in _NEGATION_PATTERN.findall(text):
877
+ low = m.lower().strip()
878
+ if low not in seen:
879
+ seen.append(low)
880
+ return seen
881
+
882
+
883
+ def _extract_negation_spans(text: str) -> list[str]:
884
+ spans: list[str] = []
885
+ for m in _NEGATION_SPAN_PATTERN.finditer(text):
886
+ val = m.group(1).strip()
887
+ if val and val.lower() not in [s.lower() for s in spans]:
888
+ spans.append(val)
889
+ return spans
890
+
891
+
892
+ _KNOWN_TASK_VERBS: dict[str, str] = {
893
+ "write": "write", "writing": "write", "wrote": "write",
894
+ "generate": "generate", "generating": "generate",
895
+ "create": "create", "creating": "create",
896
+ "implement": "implement", "implementing": "implement",
897
+ "extract": "extract", "extracting": "extract",
898
+ "parse": "parse", "parsing": "parse",
899
+ "find": "find", "finding": "find",
900
+ "scrape": "scrape", "scraping": "scrape",
901
+ "identify": "identify", "identifying": "identify",
902
+ "list": "list", "listing": "list",
903
+ "run": "run", "running": "run",
904
+ "execute": "execute", "executing": "execute",
905
+ "search": "search", "searching": "search",
906
+ "send": "send", "sending": "send",
907
+ "open": "open", "opening": "open",
908
+ "read": "read", "reading": "read",
909
+ "load": "load", "loading": "load",
910
+ "call": "call", "calling": "call",
911
+ "invoke": "invoke", "invoking": "invoke",
912
+ "trigger": "trigger", "triggering": "trigger",
913
+ "define": "define", "defining": "define",
914
+ "explain": "explain", "explaining": "explain",
915
+ "tell": "tell", "telling": "tell",
916
+ "select": "select", "selecting": "select",
917
+ "calculate": "calculate", "compute": "compute",
918
+ "summarize": "summarize", "translate": "translate",
919
+ "update": "update", "updating": "update",
920
+ "modify": "modify", "modifying": "modify",
921
+ "edit": "edit", "editing": "edit",
922
+ "fix": "fix", "fixing": "fix",
923
+ "refactor": "refactor", "refactoring": "refactor",
924
+ "debug": "debug", "debugging": "debug",
925
+ "optimize": "optimize", "optimizing": "optimize",
926
+ "review": "review", "reviewing": "review",
927
+ }
928
+
929
+
930
+ def _extract_root_action(cleaned_text: str) -> str | None:
931
+ words = _WORD_TOKEN_RE.findall(cleaned_text.lower())
932
+ if words and words[0] in _KNOWN_TASK_VERBS:
933
+ return _KNOWN_TASK_VERBS[words[0]]
934
+
935
+ nlp = _get_nlp()
936
+ if nlp is not None:
937
+ doc = nlp(cleaned_text)
938
+ for token in doc:
939
+ if token.dep_ == "ROOT" and token.pos_ in ("VERB", "AUX"):
940
+ lemma = (token.lemma_ or token.text).lower()
941
+ if lemma not in ("be", "have", "do", "would", "could", "can"):
942
+ return _KNOWN_TASK_VERBS.get(lemma, lemma)
943
+ for token in doc:
944
+ if token.pos_ == "VERB":
945
+ lemma = (token.lemma_ or token.text).lower()
946
+ return _KNOWN_TASK_VERBS.get(lemma, lemma)
947
+
948
+ for w in words:
949
+ if w in _KNOWN_TASK_VERBS:
950
+ return _KNOWN_TASK_VERBS[w]
951
+ return None
952
+
953
+
954
+ def _extract_entities(raw_text: str, cleaned_text: str) -> dict[str, Any]:
955
+ entities: dict[str, Any] = {}
956
+
957
+ emails = re.findall(r"[\w.\-]+@[\w.\-]+\.\w+", raw_text)
958
+ if emails:
959
+ entities["emails"] = list(dict.fromkeys(emails))
960
+
961
+ urls = re.findall(r"https?://\S+", raw_text)
962
+ if urls:
963
+ entities["urls"] = list(dict.fromkeys(urls))
964
+
965
+ dates = re.findall(
966
+ r"\b(\d{4}-\d{2}-\d{2}|\d{1,2}/\d{1,2}/\d{2,4}|"
967
+ r"(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]* \d{1,2},? \d{4})\b",
968
+ raw_text,
969
+ re.IGNORECASE,
970
+ )
971
+ if dates:
972
+ entities["dates"] = list(dict.fromkeys(dates))
973
+
974
+ text_without_dates = re.sub(r"\b\d{4}-\d{2}-\d{2}\b", "", raw_text)
975
+ numbers = re.findall(r"\b\d+(?:\.\d+)?\b", text_without_dates)
976
+ if numbers:
977
+ entities["numbers"] = list(dict.fromkeys(numbers[:12]))
978
+
979
+ # Strip fenced code blocks before scanning for quoted string literals
980
+ prose_only = re.sub(r"```[\s\S]*?```", "", raw_text)
981
+ double_quoted = re.findall(r'"([^"\n]+)"', prose_only)
982
+ single_quoted = re.findall(r"(?<!\w)'([^'\n]+)'(?!\w)", prose_only)
983
+ flat_quoted = [q for q in (double_quoted + single_quoted) if q.strip()]
984
+ if flat_quoted:
985
+ entities["quoted_strings"] = list(dict.fromkeys(flat_quoted))
986
+
987
+ action = _extract_root_action(cleaned_text)
988
+ if action:
989
+ entities["action"] = action
990
+
991
+ return entities
992
+
993
+
994
+ def _check_required_slots(intent: str, entities: dict) -> list[str]:
995
+ missing = []
996
+ for slot in REQUIRED_SLOTS.get(intent, []):
997
+ if slot not in entities or not entities[slot]:
998
+ missing.append(slot)
999
+ return missing
1000
+
1001
+
1002
+ # ══════════════════════════════════════════════════════════════════════════════
1003
+ # STAGE 3 — MMR + BM25 + TF-IDF Pruner (Few-Shots, Tools, Context & History)
1004
+ # ══════════════════════════════════════════════════════════════════════════════
1005
+
1006
+ _FEW_SHOT_CACHE: dict[str, Any] = {"len": -1, "bm25": None}
1007
+
1008
+ _INTENT_EXAMPLE_PREFIX: dict[str, str] = {
1009
+ "CODE_GENERATION": "ex_code_gen",
1010
+ "DATA_EXTRACTION": "ex_data_extract",
1011
+ "TOOL_EXECUTION": "ex_tool_exec",
1012
+ "FACTUAL_QA": "ex_factual_qa",
1013
+ }
1014
+
1015
+
1016
+ def _get_few_shot_bm25():
1017
+ if _FEW_SHOT_CACHE["len"] != len(FEW_SHOT_EXAMPLES) or _FEW_SHOT_CACHE["bm25"] is None:
1018
+ tokenized = [_tokenize_for_ir(item["input"]) for item in FEW_SHOT_EXAMPLES]
1019
+ _FEW_SHOT_CACHE["bm25"] = _create_bm25(tokenized) if tokenized else None
1020
+ _FEW_SHOT_CACHE["len"] = len(FEW_SHOT_EXAMPLES)
1021
+ return _FEW_SHOT_CACHE["bm25"]
1022
+
1023
+
1024
+ def _select_few_shots_mmr(
1025
+ query: str,
1026
+ intent: str = "",
1027
+ intent_confidence: float = 0.0,
1028
+ k: int = 2,
1029
+ few_shot_budget: int = 90,
1030
+ ) -> list[dict]:
1031
+ if not FEW_SHOT_EXAMPLES or k <= 0:
1032
+ return []
1033
+
1034
+ docs_text = [item["input"] for item in FEW_SHOT_EXAMPLES]
1035
+ bm25 = _get_few_shot_bm25()
1036
+ hybrid_scores, doc_vecs = _compute_hybrid_relevance_and_vectors(query, docs_text, bm25_index=bm25)
1037
+
1038
+ preferred_prefix = _INTENT_EXAMPLE_PREFIX.get(intent, "")
1039
+ known_prefixes = tuple(_INTENT_EXAMPLE_PREFIX.values())
1040
+
1041
+ adjusted_scores: list[float] = []
1042
+ for score, item in zip(hybrid_scores, FEW_SHOT_EXAMPLES):
1043
+ item_id = item.get("id", "")
1044
+ item_intent = item.get("intent", "")
1045
+ matches_intent = (
1046
+ (preferred_prefix and item_id.startswith(preferred_prefix))
1047
+ or (intent and item_intent == intent)
1048
+ )
1049
+ has_other_intent_tag = (
1050
+ (item_id.startswith(known_prefixes) and not matches_intent)
1051
+ or (item_intent and item_intent != intent)
1052
+ )
1053
+
1054
+ if intent_confidence >= 0.75 and has_other_intent_tag:
1055
+ adjusted_scores.append(0.0)
1056
+ continue
1057
+
1058
+ boost = 0.35 if matches_intent else 0.0
1059
+ adjusted_scores.append(score + boost if (score > 0.0 or matches_intent) else 0.0)
1060
+
1061
+ def _example_token_cost(ex: dict) -> int:
1062
+ return estimate_tokens(f"[{ex['id']}]\nInput: {ex['input']}\nOutput: {ex['output']}")
1063
+
1064
+ mmr_picked = _mmr_select(
1065
+ candidates=FEW_SHOT_EXAMPLES,
1066
+ relevance_scores=adjusted_scores,
1067
+ doc_vecs=doc_vecs,
1068
+ k=k,
1069
+ lambda_mult=0.75,
1070
+ token_budget=few_shot_budget,
1071
+ token_cost_fn=_example_token_cost,
1072
+ min_score=0.05,
1073
+ )
1074
+ return [item for _, item, _ in mmr_picked]
1075
+
1076
+
1077
+ _PASSIVE_INTENTS = frozenset({"DATA_EXTRACTION", "FACTUAL_QA"})
1078
+ _SIDE_EFFECT_TOOLS = frozenset({"send_email"})
1079
+
1080
+
1081
+ def _select_and_compress_tools(
1082
+ query: str,
1083
+ intent: str = "",
1084
+ tools_budget: int = 60,
1085
+ ) -> tuple[list[dict], int]:
1086
+ matched: list[tuple[float, dict]] = []
1087
+ first_word = query.split()[0].lower() if query.split() else ""
1088
+ query_stems = set(_tokenize_for_ir(query))
1089
+
1090
+ for tool in TOOL_REGISTRY:
1091
+ tool_id = tool["id"]
1092
+ score = 0.0
1093
+ lead_verb_hit = False
1094
+
1095
+ for kw in tool.get("trigger_keywords", []):
1096
+ pattern = rf"\b{re.escape(kw)}\b"
1097
+ if re.search(pattern, query, re.IGNORECASE):
1098
+ score += 1.5
1099
+ elif _fast_stem(kw.lower()) in query_stems:
1100
+ score += 1.0
1101
+ if first_word == kw.lower() or _fast_stem(first_word) == _fast_stem(kw.lower()):
1102
+ lead_verb_hit = True
1103
+
1104
+ if score == 0.0:
1105
+ continue
1106
+
1107
+ if intent in _PASSIVE_INTENTS and tool_id in _SIDE_EFFECT_TOOLS and not lead_verb_hit:
1108
+ continue
1109
+
1110
+ if tool_id == "run_python":
1111
+ if not re.search(r"\b(run|execute|script)\b", query, re.IGNORECASE):
1112
+ continue
1113
+
1114
+ matched.append((score, tool))
1115
+
1116
+ matched.sort(key=lambda x: x[0], reverse=True)
1117
+
1118
+ selected_tools: list[dict] = []
1119
+ total_saved = 0
1120
+ used_tokens = 0
1121
+
1122
+ for _, tool in matched:
1123
+ compact_schema, saved = _compress_tool_schema(tool["schema"])
1124
+ cost = estimate_tokens(f"- {tool['id']}: {compact_schema}")
1125
+ if used_tokens + cost > tools_budget and selected_tools:
1126
+ continue
1127
+ used_tokens += cost
1128
+ total_saved += saved
1129
+ selected_tools.append({
1130
+ "id": tool["id"],
1131
+ "schema": compact_schema,
1132
+ "raw_schema": tool["schema"],
1133
+ })
1134
+
1135
+ return selected_tools, total_saved
1136
+
1137
+
1138
+ def _prune_external_context_mmr(
1139
+ query: str,
1140
+ context_chunks: list[str] | None,
1141
+ context_budget: int = 160,
1142
+ top_k: int = 3,
1143
+ ) -> tuple[str, list[int]]:
1144
+ if not context_chunks:
1145
+ return "[No external context provided — rely strictly on <core_task>]", []
1146
+
1147
+ hybrid_scores, doc_vecs = _compute_hybrid_relevance_and_vectors(query, context_chunks)
1148
+ mmr_picked = _mmr_select(
1149
+ candidates=context_chunks,
1150
+ relevance_scores=hybrid_scores,
1151
+ doc_vecs=doc_vecs,
1152
+ k=top_k,
1153
+ lambda_mult=0.65,
1154
+ token_budget=context_budget,
1155
+ token_cost_fn=estimate_tokens,
1156
+ min_score=0.05,
1157
+ )
1158
+
1159
+ if not mmr_picked:
1160
+ first_chunk = " ".join(context_chunks[0].split()[:context_budget])
1161
+ return first_chunk, [0]
1162
+
1163
+ mmr_picked.sort(key=lambda x: x[0])
1164
+ kept_indices = [idx for idx, _, _ in mmr_picked]
1165
+ formatted = "\n---\n".join(chunk.strip() for _, chunk, _ in mmr_picked)
1166
+ return formatted, kept_indices
1167
+
1168
+
1169
+ def _prune_conversation_history(
1170
+ query: str,
1171
+ history: list[dict[str, str]] | None,
1172
+ history_budget: int = 80,
1173
+ ) -> tuple[str, int]:
1174
+ if not history or history_budget <= 0:
1175
+ return "", 0
1176
+
1177
+ turn_texts: list[str] = []
1178
+ for turn in history:
1179
+ role = turn.get("role", "user").upper()
1180
+ content = turn.get("content", "").strip()
1181
+ if role == "USER":
1182
+ content, _, _ = _normalize_and_compress_text(content, intensity="MEDIUM")
1183
+ turn_texts.append(f"{role}: {content}")
1184
+
1185
+ n_turns = len(turn_texts)
1186
+ if n_turns == 1:
1187
+ cost = estimate_tokens(turn_texts[0])
1188
+ if cost <= history_budget:
1189
+ return turn_texts[0], 1
1190
+ truncated = " ".join(turn_texts[0].split()[:history_budget])
1191
+ return truncated, 1
1192
+
1193
+ last_idx = n_turns - 1
1194
+ last_turn = turn_texts[last_idx]
1195
+ used_tokens = estimate_tokens(last_turn)
1196
+ remaining_budget = max(0, history_budget - used_tokens)
1197
+
1198
+ older_turns = turn_texts[:-1]
1199
+ hybrid_scores, doc_vecs = _compute_hybrid_relevance_and_vectors(query, older_turns)
1200
+
1201
+ decayed_scores = []
1202
+ for idx, score in enumerate(hybrid_scores):
1203
+ steps_back = (n_turns - 1) - idx
1204
+ recency_factor = 0.85 ** steps_back
1205
+ decayed_scores.append((score + 0.15) * recency_factor)
1206
+
1207
+ mmr_older = _mmr_select(
1208
+ candidates=older_turns,
1209
+ relevance_scores=decayed_scores,
1210
+ doc_vecs=doc_vecs,
1211
+ k=max(1, n_turns - 1),
1212
+ lambda_mult=0.75,
1213
+ token_budget=remaining_budget,
1214
+ token_cost_fn=estimate_tokens,
1215
+ min_score=0.05,
1216
+ )
1217
+
1218
+ kept = [(idx, txt) for idx, txt, _ in mmr_older] + [(last_idx, last_turn)]
1219
+ kept.sort(key=lambda x: x[0])
1220
+ return "\n".join(txt for _, txt in kept), len(kept)
1221
+
1222
+
1223
+ # ══════════════════════════════════════════════════════════════════════════════
1224
+ # STEP 6 — Deterministic Prompt Caching (Canonical SHA-256 + 64-bit SimHash)
1225
+ # ══════════════════════════════════════════════════════════════════════════════
1226
+
1227
+ def _compute_simhash64(tokens: list[str]) -> int:
1228
+ if not tokens:
1229
+ return 0
1230
+ v = [0] * 64
1231
+ for tok, weight in Counter(tokens).items():
1232
+ h = int.from_bytes(hashlib.md5(tok.encode("utf-8")).digest()[:8], "big")
1233
+ for i in range(64):
1234
+ if h & (1 << i):
1235
+ v[i] += weight
1236
+ else:
1237
+ v[i] -= weight
1238
+ fingerprint = 0
1239
+ for i in range(64):
1240
+ if v[i] > 0:
1241
+ fingerprint |= (1 << i)
1242
+ return fingerprint
1243
+
1244
+
1245
+ def _hamming_distance64(a: int, b: int) -> int:
1246
+ return bin(a ^ b).count("1") # py3.9-safe; int.bit_count is 3.10+
1247
+
1248
+
1249
+ class PromptCache:
1250
+ def __init__(self, max_size: int = 256):
1251
+ self.max_size = max_size
1252
+ self._exact: OrderedDict[str, CompiledPrompt] = OrderedDict()
1253
+ self._simhash_index: list[tuple[int, str, str]] = []
1254
+
1255
+ def clear(self) -> None:
1256
+ self._exact.clear()
1257
+ self._simhash_index.clear()
1258
+
1259
+ def lookup(
1260
+ self,
1261
+ canonical_key: str,
1262
+ simhash_val: int,
1263
+ safety_signature: str,
1264
+ ) -> tuple[CompiledPrompt | None, str]:
1265
+ if canonical_key in self._exact:
1266
+ self._exact.move_to_end(canonical_key)
1267
+ return copy.deepcopy(self._exact[canonical_key]), "CANONICAL_EXACT"
1268
+
1269
+ for sh_val, safe_sig, ex_key in reversed(self._simhash_index):
1270
+ if safe_sig == safety_signature and _hamming_distance64(simhash_val, sh_val) <= 2:
1271
+ if ex_key in self._exact:
1272
+ self._exact.move_to_end(ex_key)
1273
+ return copy.deepcopy(self._exact[ex_key]), "SIMHASH_NEAR"
1274
+
1275
+ return None, "NONE"
1276
+
1277
+ def store(
1278
+ self,
1279
+ canonical_key: str,
1280
+ simhash_val: int,
1281
+ safety_signature: str,
1282
+ result: CompiledPrompt,
1283
+ ) -> None:
1284
+ if len(self._exact) >= self.max_size:
1285
+ oldest_key, _ = self._exact.popitem(last=False)
1286
+ self._simhash_index = [
1287
+ entry for entry in self._simhash_index if entry[2] != oldest_key
1288
+ ]
1289
+ self._exact[canonical_key] = copy.deepcopy(result)
1290
+ self._simhash_index.append((simhash_val, safety_signature, canonical_key))
1291
+
1292
+
1293
+ PROMPT_CACHE = PromptCache(max_size=256)
1294
+
1295
+
1296
+ # ══════════════════════════════════════════════════════════════════════════════
1297
+ # STAGE 4 & STEP 9 — Structural Compiler, Telemetry & Post-LLM Output Auditor
1298
+ # ══════════════════════════════════════════════════════════════════════════════
1299
+
1300
+ _RESERVED_XML_TAGS = re.compile(
1301
+ r"</?(?:agent_instructions|anti_hallucination_protocol|task_metadata|"
1302
+ r"extracted_entities|verified_context|conversation_history|allowed_tools|"
1303
+ r"few_shot_examples|core_task|output_constraints)\b[^>]*>",
1304
+ re.IGNORECASE,
1305
+ )
1306
+
1307
+
1308
+ def _sanitize_xml_payload(text: str) -> str:
1309
+ return _RESERVED_XML_TAGS.sub("", text)
1310
+
1311
+
1312
+ _COMPILED_TEMPLATE = """\
1313
+ <agent_instructions>
1314
+ You are executing a pre-processed, deterministically structured task.
1315
+ Follow every rule in <anti_hallucination_protocol> and <output_constraints> strictly.
1316
+ </agent_instructions>
1317
+
1318
+ <anti_hallucination_protocol>
1319
+ 1. SOURCE-ONLY GROUNDING: Rely ONLY on facts and schemas in <verified_context> and <core_task>.
1320
+ 2. ABSTENTION RULE: If required information is missing, output STATUS: INSUFFICIENT_CONTEXT followed by missing fields.
1321
+ 3. ENTITY FIDELITY: Preserve all identifiers, dates, URLs, and numbers verbatim.
1322
+ 4. TOOL STRICTNESS: Only invoke tools listed in <allowed_tools>.
1323
+ {guardrails}
1324
+ </anti_hallucination_protocol>
1325
+
1326
+ <task_metadata>
1327
+ - Detected Intent: {intent}
1328
+ - Complexity Tier: {complexity}
1329
+ - Negation / Exclusion Constraints: {negations}
1330
+ </task_metadata>
1331
+
1332
+ <extracted_entities>
1333
+ {entities}
1334
+ </extracted_entities>
1335
+
1336
+ <verified_context>
1337
+ {context}
1338
+ </verified_context>
1339
+ {history_block}
1340
+ <allowed_tools>
1341
+ {tools}
1342
+ </allowed_tools>
1343
+
1344
+ <few_shot_examples>
1345
+ {examples}
1346
+ </few_shot_examples>
1347
+
1348
+ <core_task>
1349
+ {query}
1350
+ </core_task>
1351
+
1352
+ <output_constraints>
1353
+ - Format: {output_format}
1354
+ - Pre-Output Verification: Verify every claim traces to <verified_context> and no <task_metadata> constraints are violated.
1355
+ </output_constraints>
1356
+ """
1357
+
1358
+
1359
+ def _complexity_tier(token_count: int, negation_count: int = 0, entity_count: int = 0) -> str:
1360
+ score = token_count + (negation_count * 5) + (entity_count * 3)
1361
+ if score < 20:
1362
+ return "LOW"
1363
+ if score < 60:
1364
+ return "MEDIUM"
1365
+ return "HIGH"
1366
+
1367
+
1368
+ def _format_entities(entities: dict) -> str:
1369
+ if not entities:
1370
+ return "NONE"
1371
+ return "\n".join(f"- {k}: {v}" for k, v in entities.items())
1372
+
1373
+
1374
+ def _format_tools(tools: list[dict]) -> str:
1375
+ if not tools:
1376
+ return "NONE"
1377
+ return "\n".join(f"- {t['id']}: {t['schema']}" for t in tools)
1378
+
1379
+
1380
+ def _format_examples(examples: list[dict]) -> str:
1381
+ if not examples:
1382
+ return "NONE"
1383
+ parts = []
1384
+ for ex in examples:
1385
+ parts.append(f"[{ex['id']}]\nInput: {ex['input']}\nOutput: {ex['output']}")
1386
+ return "\n\n".join(parts)
1387
+
1388
+
1389
+ def _infer_output_format(intent: str) -> str:
1390
+ return {
1391
+ "CODE_GENERATION": "Fenced code block with language tag",
1392
+ "DATA_EXTRACTION": "JSON array of extracted values",
1393
+ "TOOL_EXECUTION": "Tool call JSON: {name, params}",
1394
+ "FACTUAL_QA": "Plain text, <=3 sentences",
1395
+ "AMBIGUOUS_QUERY": "Clarification question",
1396
+ }.get(intent, "Plain text")
1397
+
1398
+
1399
+ def _estimate_unoptimized_baseline_tokens(request: RawRequest) -> int:
1400
+ raw_tools_str = "\n".join(f"- {t['id']}: {t['schema']}" for t in TOOL_REGISTRY)
1401
+ raw_examples_str = _format_examples(FEW_SHOT_EXAMPLES)
1402
+ raw_context_str = "\n---\n".join(getattr(request, "context_chunks", None) or ["[No external context provided]"])
1403
+ raw_history = getattr(request, "conversation_history", None) or []
1404
+ raw_history_str = "\n".join(f"{t.get('role', 'user')}: {t.get('content', '')}" for t in raw_history)
1405
+ guardrail_block = "\n".join(f"{i+5}. {r}" for i, r in enumerate(GUARDRAIL_RULES))
1406
+
1407
+ baseline_payload = _COMPILED_TEMPLATE.format(
1408
+ guardrails=guardrail_block,
1409
+ intent="UNROUTED",
1410
+ complexity="HIGH",
1411
+ negations="NONE",
1412
+ entities="NONE",
1413
+ context=raw_context_str,
1414
+ history_block=f"\n<conversation_history>\n{raw_history_str}\n</conversation_history>\n" if raw_history_str else "",
1415
+ tools=raw_tools_str,
1416
+ examples=raw_examples_str,
1417
+ query=request.text,
1418
+ output_format="Plain text",
1419
+ )
1420
+ return estimate_tokens(baseline_payload)
1421
+
1422
+
1423
+ def audit_agent_response(response_text: str, trace: OptimizationTrace) -> dict[str, Any]:
1424
+ """
1425
+ Deterministic Post-LLM Output Validator & Hallucination Auditor.
1426
+ Scores an LLM response (0-100) on format compliance, entity fidelity, and negation adherence.
1427
+ """
1428
+ checks: list[dict[str, Any]] = []
1429
+ score = 100
1430
+
1431
+ # 1. Output format compliance check
1432
+ intent = trace.detected_intent
1433
+ if intent == "CODE_GENERATION":
1434
+ has_fence = "```" in response_text or "def " in response_text or "SELECT " in response_text.upper()
1435
+ checks.append({"check": "Code Format Compliance", "passed": has_fence})
1436
+ if not has_fence:
1437
+ score -= 25
1438
+ elif intent == "DATA_EXTRACTION":
1439
+ has_json_array = "[" in response_text and "]" in response_text
1440
+ checks.append({"check": "JSON Array Format", "passed": has_json_array})
1441
+ if not has_json_array:
1442
+ score -= 25
1443
+ elif intent == "TOOL_EXECUTION":
1444
+ has_json_obj = "{" in response_text and "}" in response_text
1445
+ checks.append({"check": "Tool Call JSON Format", "passed": has_json_obj})
1446
+ if not has_json_obj:
1447
+ score -= 25
1448
+ elif intent == "FACTUAL_QA":
1449
+ sents = _split_sentences(response_text)
1450
+ concise = len(sents) <= 4
1451
+ checks.append({"check": "Concise QA (<=3 sentences)", "passed": concise})
1452
+ if not concise:
1453
+ score -= 15
1454
+
1455
+ # 2. Negation / Exclusion violation check (e.g., if 'without using slicing', check for `[::-1]`)
1456
+ if trace.negations:
1457
+ slicing_violated = "[::-1]" in response_text
1458
+ recursion_violated = False
1459
+ m_func = re.search(r"def\s+([a-zA-Z0-9_]+)\s*\(", response_text)
1460
+ if m_func:
1461
+ fn_name = m_func.group(1)
1462
+ body = response_text[m_func.end():]
1463
+ if re.search(rf"\b{re.escape(fn_name)}\s*\(", body):
1464
+ recursion_violated = True
1465
+ neg_passed = not (slicing_violated or recursion_violated)
1466
+ checks.append({"check": "Negation Constraint Respected", "passed": neg_passed})
1467
+ if not neg_passed:
1468
+ score -= 40
1469
+
1470
+ # 3. Entity fidelity check (verifying extracted dates/emails weren't mutated if referenced)
1471
+ entities = trace.extracted_entities or {}
1472
+ entity_ok = True
1473
+ for date_val in entities.get("dates", []):
1474
+ if date_val not in response_text and intent in ("CODE_GENERATION", "DATA_EXTRACTION"):
1475
+ entity_ok = False
1476
+ checks.append({"check": "Verbatim Entity Fidelity", "passed": entity_ok})
1477
+ if not entity_ok:
1478
+ score -= 20
1479
+
1480
+ return {
1481
+ "compliance_score": max(0, score),
1482
+ "output_tokens": estimate_tokens(response_text),
1483
+ "checks": checks,
1484
+ }
1485
+
1486
+
1487
+ # ══════════════════════════════════════════════════════════════════════════════
1488
+ # PUBLIC ENTRY POINT
1489
+ # ══════════════════════════════════════════════════════════════════════════════
1490
+
1491
+ def optimize(request: RawRequest, few_shot_k: int = 2) -> CompiledPrompt:
1492
+ """Compile a raw request into a strict XML prompt for a downstream agent (deterministic, no model call).
1493
+
1494
+ Runs the 9-step pipeline (budgeting, tool-schema compression, MMR/BM25 pruning of tools, examples, context and history,
1495
+ lexical normalization, intent routing, cache) and returns a ``CompiledPrompt``: ``payload`` is the XML string, ``status`` is
1496
+ ``"OK"``, ``"NEEDS_CLARIFICATION"`` (a required slot is missing: no model call is needed) or ``"INSUFFICIENT_CONTEXT"``,
1497
+ and ``trace`` is an ``OptimizationTrace`` with per-step token estimates. ``trace.payload_token_savings_pct`` is measured against
1498
+ a modeled unpruned template, not against the request you would otherwise have sent; short prompts compile to MORE tokens
1499
+ than the raw text (see the README, "Measured results"). ``TokenBudget.max_total_tokens`` is advisory.
1500
+ """
1501
+ t0 = time.perf_counter()
1502
+ trace = OptimizationTrace()
1503
+ budget = _resolve_budget(request)
1504
+ logs: list[str] = []
1505
+
1506
+ trace.raw_token_count = estimate_word_tokens(request.text)
1507
+ trace.raw_bpe_tokens = estimate_tokens(request.text)
1508
+ trace.unoptimized_payload_token_count = _estimate_unoptimized_baseline_tokens(request)
1509
+
1510
+ # ── Step 8 + Step 5 + Step 4: Adaptive Intensity, Lexical Normalization & Extractive Compression ──
1511
+ s1_t0 = time.perf_counter()
1512
+ intensity = _select_adaptive_intensity(
1513
+ request.text,
1514
+ getattr(request, "compression_intensity", "AUTO"),
1515
+ budget.core_query_budget,
1516
+ )
1517
+ trace.compression_intensity_used = intensity
1518
+
1519
+ compressed, stripped, normalized_phrases = _normalize_and_compress_text(
1520
+ request.text,
1521
+ intensity=intensity,
1522
+ )
1523
+ compressed = _extractive_sentence_compress(compressed, token_budget=budget.core_query_budget)
1524
+ compressed = _sanitize_xml_payload(compressed)
1525
+ s1_ms = round((time.perf_counter() - s1_t0) * 1000, 3)
1526
+
1527
+ trace.compressed_query_text = compressed
1528
+ trace.stripped_tokens = stripped
1529
+ trace.normalized_phrases = normalized_phrases
1530
+ trace.optimized_token_count = estimate_word_tokens(compressed)
1531
+ trace.optimized_bpe_tokens = estimate_tokens(compressed)
1532
+
1533
+ if trace.raw_token_count > 0:
1534
+ trace.query_token_savings_pct = round(
1535
+ (trace.raw_token_count - trace.optimized_token_count) / trace.raw_token_count * 100.0,
1536
+ 1,
1537
+ )
1538
+ if trace.raw_bpe_tokens > 0:
1539
+ trace.query_bpe_savings_pct = round(
1540
+ (trace.raw_bpe_tokens - trace.optimized_bpe_tokens) / trace.raw_bpe_tokens * 100.0,
1541
+ 1,
1542
+ )
1543
+
1544
+ logs.append(
1545
+ f"[Stage 1 | {s1_ms}ms] Lexical & Extractive Compression ({intensity}): "
1546
+ f"{trace.raw_token_count} -> {trace.optimized_token_count} words (-{trace.query_token_savings_pct}%), "
1547
+ f"est. tokens: {trace.raw_bpe_tokens} -> {trace.optimized_bpe_tokens} (-{trace.query_bpe_savings_pct}%). "
1548
+ f"Stripped={stripped or 'none'}, Normalized={normalized_phrases or 'none'}"
1549
+ )
1550
+
1551
+ # ── Stage 2: Weighted Intent Routing & Deterministic Entity Extraction ───
1552
+ s2_t0 = time.perf_counter()
1553
+ intent, confidence, secondary_intents = _route_intent(
1554
+ cleaned_text=compressed,
1555
+ raw_text=request.text,
1556
+ task_hint=getattr(request, "task_hint", ""),
1557
+ )
1558
+ negations = _extract_negations(compressed)
1559
+ negation_spans = _extract_negation_spans(compressed)
1560
+ entities = _extract_entities(raw_text=request.text, cleaned_text=compressed)
1561
+ s2_ms = round((time.perf_counter() - s2_t0) * 1000, 3)
1562
+
1563
+ trace.detected_intent = intent
1564
+ trace.secondary_intents = secondary_intents
1565
+ trace.intent_confidence = confidence
1566
+ trace.negations = negations
1567
+ trace.extracted_entities = entities
1568
+
1569
+ logs.append(
1570
+ f"[Stage 2 | {s2_ms}ms] Intent Router & Slot Extractor: intent={intent} (conf={confidence}), "
1571
+ f"negations={negation_spans or negations or 'none'}, entities={entities or 'none'}"
1572
+ )
1573
+
1574
+ # ── Step 6: Deterministic Prompt Cache Lookup ────────────────────────────
1575
+ context_chunks = getattr(request, "context_chunks", None) or []
1576
+ conversation_history = getattr(request, "conversation_history", None) or []
1577
+ enable_cache = getattr(request, "enable_cache", True)
1578
+
1579
+ ir_tokens = _tokenize_for_ir(compressed)
1580
+ simhash_val = _compute_simhash64(ir_tokens)
1581
+ trace.simhash_signature = f"{simhash_val:016x}"
1582
+
1583
+ safety_sig = json.dumps(
1584
+ {
1585
+ "intent": intent,
1586
+ "negations": negations,
1587
+ "entities": entities,
1588
+ "ctx_len": len(context_chunks),
1589
+ "hist_len": len(conversation_history),
1590
+ "k": few_shot_k,
1591
+ },
1592
+ sort_keys=True,
1593
+ )
1594
+ canonical_material = f"{compressed.lower()}|{safety_sig}|{budget.max_total_tokens}"
1595
+ canonical_key = hashlib.sha256(canonical_material.encode("utf-8")).hexdigest()[:16]
1596
+ trace.cache_key = canonical_key
1597
+
1598
+ if enable_cache:
1599
+ cached_result, cache_type = PROMPT_CACHE.lookup(canonical_key, simhash_val, safety_sig)
1600
+ if cached_result is not None:
1601
+ cached_result.trace.cache_hit = True
1602
+ cached_result.trace.cache_type = cache_type
1603
+ cached_result.trace.latency_ms = round((time.perf_counter() - t0) * 1000, 3)
1604
+ cached_result.trace.stage_logs = list(cached_result.trace.stage_logs) + [
1605
+ f"[Cache HIT | {cached_result.trace.latency_ms}ms] {cache_type} (key={canonical_key}, simhash={trace.simhash_signature})"
1606
+ ]
1607
+ return cached_result
1608
+
1609
+ # Early short-circuit if required slots are missing
1610
+ missing = _check_required_slots(intent, entities)
1611
+ if missing:
1612
+ trace.latency_ms = round((time.perf_counter() - t0) * 1000, 2)
1613
+ logs.append(f"[Short-Circuit | {trace.latency_ms}ms] Missing mandatory slots for {intent}: {missing}")
1614
+ trace.stage_logs = logs
1615
+ res = CompiledPrompt(
1616
+ payload="",
1617
+ trace=trace,
1618
+ status="NEEDS_CLARIFICATION",
1619
+ clarification_request=(
1620
+ f"To proceed with {intent}, please provide: {', '.join(missing)}"
1621
+ ),
1622
+ )
1623
+ if enable_cache:
1624
+ PROMPT_CACHE.store(canonical_key, simhash_val, safety_sig, res)
1625
+ return res
1626
+
1627
+ # ── Step 2 + Step 3 + Step 7: MMR Pruning, Tool Schema Compression & History ──
1628
+ s3_t0 = time.perf_counter()
1629
+ tools, tool_tokens_saved = _select_and_compress_tools(
1630
+ compressed,
1631
+ intent=intent,
1632
+ tools_budget=budget.tools_budget,
1633
+ )
1634
+ examples = _select_few_shots_mmr(
1635
+ compressed,
1636
+ intent=intent,
1637
+ intent_confidence=confidence,
1638
+ k=few_shot_k,
1639
+ few_shot_budget=budget.few_shot_budget,
1640
+ )
1641
+ pruned_context, kept_ctx_indices = _prune_external_context_mmr(
1642
+ compressed,
1643
+ context_chunks,
1644
+ context_budget=budget.context_budget,
1645
+ )
1646
+ pruned_history, kept_hist_turns = _prune_conversation_history(
1647
+ compressed,
1648
+ conversation_history,
1649
+ history_budget=budget.history_budget,
1650
+ )
1651
+ s3_ms = round((time.perf_counter() - s3_t0) * 1000, 3)
1652
+
1653
+ # Calculate per-section before/after token telemetry
1654
+ trace.total_context_chunks = len(context_chunks)
1655
+ trace.raw_context_tokens = estimate_tokens("\n---\n".join(context_chunks)) if context_chunks else 0
1656
+ trace.pruned_context_tokens = estimate_tokens(pruned_context) if context_chunks else 0
1657
+ if trace.raw_context_tokens > 0:
1658
+ trace.context_token_savings_pct = round(
1659
+ max(0, trace.raw_context_tokens - trace.pruned_context_tokens) / trace.raw_context_tokens * 100.0,
1660
+ 1,
1661
+ )
1662
+
1663
+ raw_hist_str = "\n".join(f"{t.get('role', 'user')}: {t.get('content', '')}" for t in conversation_history)
1664
+ trace.raw_history_tokens = estimate_tokens(raw_hist_str) if conversation_history else 0
1665
+ trace.pruned_history_tokens = estimate_tokens(pruned_history) if conversation_history else 0
1666
+
1667
+ raw_tools_all = "\n".join(f"- {t['id']}: {t['schema']}" for t in TOOL_REGISTRY)
1668
+ trace.raw_tools_tokens = estimate_tokens(raw_tools_all)
1669
+ trace.compressed_tools_tokens = estimate_tokens(_format_tools(tools)) if tools else 0
1670
+
1671
+ trace.raw_examples_tokens = estimate_tokens(_format_examples(FEW_SHOT_EXAMPLES))
1672
+ trace.selected_examples_tokens = estimate_tokens(_format_examples(examples)) if examples else 0
1673
+
1674
+ trace.tool_schema_tokens_saved = tool_tokens_saved
1675
+ trace.injected_tool_ids = [t["id"] for t in tools]
1676
+ trace.injected_example_ids = [e["id"] for e in examples]
1677
+ trace.kept_context_indices = kept_ctx_indices
1678
+ trace.kept_history_turns = kept_hist_turns
1679
+
1680
+ logs.append(
1681
+ f"[Stage 3 | {s3_ms}ms] MMR Pruning & Schema Compression: "
1682
+ f"Context chunks kept={kept_ctx_indices}/{len(context_chunks)} "
1683
+ f"({trace.raw_context_tokens} -> {trace.pruned_context_tokens} toks, -{trace.context_token_savings_pct}%), "
1684
+ f"Tools={[t['id'] for t in tools] or 'none'} (saved {tool_tokens_saved} schema toks), "
1685
+ f"Few-Shots={[e['id'] for e in examples]}"
1686
+ )
1687
+
1688
+ # ── Stage 4 + Step 1: Budget-Checked Structural Compilation ──────────────
1689
+ s4_t0 = time.perf_counter()
1690
+ guardrail_block = "\n".join(f"{i+5}. {r}" for i, r in enumerate(GUARDRAIL_RULES))
1691
+ history_xml = (
1692
+ f"\n<conversation_history>\n{_sanitize_xml_payload(pruned_history)}\n</conversation_history>\n"
1693
+ if pruned_history else ""
1694
+ )
1695
+ negation_display = ", ".join(negation_spans or negations) if (negation_spans or negations) else "NONE"
1696
+
1697
+ payload = _COMPILED_TEMPLATE.format(
1698
+ guardrails=guardrail_block,
1699
+ intent=intent,
1700
+ complexity=_complexity_tier(
1701
+ trace.raw_token_count,
1702
+ negation_count=len(negations),
1703
+ entity_count=len(entities),
1704
+ ),
1705
+ negations=negation_display,
1706
+ entities=_format_entities(entities),
1707
+ context=_sanitize_xml_payload(pruned_context),
1708
+ history_block=history_xml,
1709
+ tools=_format_tools(tools),
1710
+ examples=_format_examples(examples),
1711
+ query=compressed,
1712
+ output_format=_infer_output_format(intent),
1713
+ )
1714
+
1715
+ if estimate_tokens(payload) > budget.max_total_tokens and len(examples) > 1:
1716
+ examples = examples[:1]
1717
+ trace.injected_example_ids = [e["id"] for e in examples]
1718
+ trace.selected_examples_tokens = estimate_tokens(_format_examples(examples))
1719
+ payload = _COMPILED_TEMPLATE.format(
1720
+ guardrails=guardrail_block,
1721
+ intent=intent,
1722
+ complexity=_complexity_tier(trace.raw_token_count, len(negations), len(entities)),
1723
+ negations=negation_display,
1724
+ entities=_format_entities(entities),
1725
+ context=_sanitize_xml_payload(pruned_context),
1726
+ history_block=history_xml,
1727
+ tools=_format_tools(tools),
1728
+ examples=_format_examples(examples),
1729
+ query=compressed,
1730
+ output_format=_infer_output_format(intent),
1731
+ )
1732
+ s4_ms = round((time.perf_counter() - s4_t0) * 1000, 3)
1733
+
1734
+ trace.compiled_payload_token_count = estimate_tokens(payload)
1735
+ if trace.unoptimized_payload_token_count > 0:
1736
+ trace.payload_token_savings_pct = round(
1737
+ (trace.unoptimized_payload_token_count - trace.compiled_payload_token_count)
1738
+ / trace.unoptimized_payload_token_count
1739
+ * 100.0,
1740
+ 1,
1741
+ )
1742
+
1743
+ trace.latency_ms = round((time.perf_counter() - t0) * 1000, 2)
1744
+ logs.append(
1745
+ f"[Stage 4 | {s4_ms}ms] XML Guardrail Compilation: "
1746
+ f"Total Payload {trace.unoptimized_payload_token_count} -> {trace.compiled_payload_token_count} est. tokens vs modeled unpruned template "
1747
+ f"(-{trace.payload_token_savings_pct}%) in {trace.latency_ms}ms total."
1748
+ )
1749
+ trace.stage_logs = logs
1750
+
1751
+ result = CompiledPrompt(payload=payload, trace=trace, status="OK")
1752
+
1753
+ if enable_cache:
1754
+ PROMPT_CACHE.store(canonical_key, simhash_val, safety_sig, result)
1755
+
1756
+ return result