tokensafe 2.4.3 → 2.5.1

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.
@@ -1,8 +1,8 @@
1
1
  """
2
2
  TokenSafe Prompt Cache Prefix Normalizer.
3
- Normalizes system instructions, architectural banners, and invariant tool definitions
4
- into deterministic prefixes to guarantee up to 90% prompt cache hit rates on
5
- Anthropic (Claude 3.5), DeepSeek-V3, and OpenAI.
3
+ Normalizes system instructions, tool schemas, architectural banners, and stable
4
+ history checkpoints into deterministic prefixes with multi-breakpoint cache_control
5
+ to maximize prompt cache hit rates on Anthropic, DeepSeek, OpenAI, and Gemini.
6
6
  """
7
7
 
8
8
  import re
@@ -11,8 +11,68 @@ import hashlib
11
11
  from typing import Dict, List, Any, Tuple, Optional
12
12
  from src.tokenizer import count_tokens
13
13
 
14
+
15
+ def _canonicalize_json(obj: Any) -> Any:
16
+ """Recursively sorts dictionary keys so serialized tool schemas are byte-deterministic."""
17
+ if isinstance(obj, dict):
18
+ return {k: _canonicalize_json(v) for k, v in sorted(obj.items())}
19
+ if isinstance(obj, list):
20
+ return [_canonicalize_json(item) for item in obj]
21
+ return obj
22
+
23
+
24
+ def _tool_name(tool: Dict[str, Any]) -> str:
25
+ if not isinstance(tool, dict):
26
+ return ""
27
+ if tool.get("name"):
28
+ return str(tool["name"])
29
+ fn = tool.get("function")
30
+ if isinstance(fn, dict) and fn.get("name"):
31
+ return str(fn["name"])
32
+ return ""
33
+
34
+
35
+ def _inject_cache_control_on_msg(msg: Dict[str, Any]) -> bool:
36
+ """Attaches Anthropic cache_control to the last non-empty block of a message."""
37
+ content_val = msg.get("content")
38
+ if isinstance(content_val, str):
39
+ if not content_val.strip():
40
+ return False
41
+ msg["content"] = [
42
+ {
43
+ "type": "text",
44
+ "text": content_val,
45
+ "cache_control": {"type": "ephemeral"},
46
+ }
47
+ ]
48
+ return True
49
+ if isinstance(content_val, list) and content_val:
50
+ copied = [dict(b) if isinstance(b, dict) else b for b in content_val]
51
+ for block in reversed(copied):
52
+ if isinstance(block, dict):
53
+ if block.get("type") == "text" and not str(block.get("text", "")).strip():
54
+ continue
55
+ block["cache_control"] = {"type": "ephemeral"}
56
+ msg["content"] = copied
57
+ return True
58
+ return False
59
+
60
+
61
+ def _message_text(msg: Dict[str, Any]) -> str:
62
+ content = msg.get("content", "")
63
+ if isinstance(content, str):
64
+ return content
65
+ if isinstance(content, list):
66
+ return "\n".join(
67
+ str(b.get("text", ""))
68
+ for b in content
69
+ if isinstance(b, dict) and isinstance(b.get("text"), str)
70
+ )
71
+ return ""
72
+
73
+
14
74
  class PromptCacheNormalizer:
15
- """Normalizes prompt message streams into cache-friendly deterministic prefixes."""
75
+ """Normalizes prompt message streams and tool definitions into cache-friendly prefixes."""
16
76
 
17
77
  VOLATILE_PATTERNS = [
18
78
  re.compile(r"The current local time is:.*?(?=\n|$)", re.IGNORECASE),
@@ -20,11 +80,16 @@ class PromptCacheNormalizer:
20
80
  re.compile(r"request_id=['\"][a-zA-Z0-9_-]+['\"]", re.IGNORECASE),
21
81
  re.compile(r"uuid=['\"][a-f0-9-]{36}['\"]", re.IGNORECASE),
22
82
  re.compile(r"turn_count=\d+", re.IGNORECASE),
83
+ re.compile(r"\(Dedup Hit #\d+, Saved ~?\d[\d,]* tokens\)", re.IGNORECASE),
84
+ re.compile(r"Saved \*?\*?\d[\d,]* tokens\*?\*?", re.IGNORECASE),
85
+ re.compile(r"Conversation ID:\s*[a-f0-9-]{8,36}", re.IGNORECASE),
86
+ re.compile(r"invocationNum[\"']?\s*[:=]\s*\d+", re.IGNORECASE),
87
+ re.compile(r"Generated locally at \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}", re.IGNORECASE),
23
88
  ]
24
89
 
25
90
  @classmethod
26
91
  def strip_volatile_elements(cls, text: str) -> str:
27
- """Removes volatile timestamps and ephemeral request IDs from static prefix."""
92
+ """Removes volatile timestamps, hit counters, and ephemeral IDs from static prefix."""
28
93
  for pattern in cls.VOLATILE_PATTERNS:
29
94
  text = pattern.sub("", text)
30
95
  return text
@@ -35,71 +100,125 @@ class PromptCacheNormalizer:
35
100
  cleaned = re.sub(r"\s+", " ", prefix_text).strip()
36
101
  return hashlib.sha256(cleaned.encode("utf-8")).hexdigest()
37
102
 
103
+ @classmethod
104
+ def normalize_tools(
105
+ cls,
106
+ tools: Optional[List[Dict[str, Any]]],
107
+ provider: str = "generic",
108
+ inject_cache_control: bool = True,
109
+ ) -> Optional[List[Dict[str, Any]]]:
110
+ """Sorts tools by name and canonicalizes JSON key order for byte-identical prefixes."""
111
+ if not tools or not isinstance(tools, list):
112
+ return tools
113
+ canon = [_canonicalize_json(dict(t)) if isinstance(t, dict) else t for t in tools]
114
+ canon.sort(key=_tool_name)
115
+ if inject_cache_control and provider == "anthropic" and canon and isinstance(canon[-1], dict):
116
+ canon[-1]["cache_control"] = {"type": "ephemeral"}
117
+ return canon
118
+
38
119
  @classmethod
39
120
  def normalize_messages(
40
121
  cls,
41
122
  messages: List[Dict[str, Any]],
42
123
  provider: str = "generic",
43
- inject_cache_control: bool = True
124
+ inject_cache_control: bool = True,
125
+ tools: Optional[List[Dict[str, Any]]] = None,
44
126
  ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
45
127
  """
46
- Normalizes message list:
47
- 1. Separates static system/prefix instructions from dynamic turns
48
- 2. Sanitizes non-deterministic markers in the static prefix
49
- 3. For Anthropic: Injects 'cache_control: {"type": "ephemeral"}' if tokens >= 1024
50
- 4. Calculates prefix hash and estimated cache savings
128
+ Normalizes message list and optional tool schemas:
129
+ 1. Separates static system/developer prefix from dynamic turns
130
+ 2. Strips volatile timestamps, counters, and ephemeral request IDs
131
+ 3. For Anthropic/generic: injects multi-breakpoint 'cache_control: {"type": "ephemeral"}'
132
+ (tools[-1], last static system message, and rolling penultimate turn messages[-2])
133
+ 4. For OpenAI: emits deterministic prompt_cache_key without mutating message shape
51
134
  """
135
+ norm_tools = cls.normalize_tools(tools, provider=provider, inject_cache_control=False) if tools is not None else None
52
136
  if not messages:
53
- return messages, {"prefix_tokens": 0, "cache_hit_eligible": False}
137
+ return messages, {
138
+ "prefix_tokens": 0,
139
+ "cache_hit_eligible": False,
140
+ "cache_eligible": False,
141
+ "cache_control_injected": False,
142
+ "breakpoints_injected": 0,
143
+ "provider": provider,
144
+ "normalized_tools": norm_tools,
145
+ }
54
146
 
55
- normalized = []
56
- static_prefix_parts = []
147
+ normalized: List[Dict[str, Any]] = []
148
+ static_prefix_parts: List[str] = []
57
149
  last_static_idx = -1
150
+ seen_non_static = False
58
151
 
59
152
  for idx, msg in enumerate(messages):
60
153
  msg_copy = dict(msg)
61
154
  role = msg_copy.get("role", "")
62
155
  content = msg_copy.get("content", "")
63
156
 
64
- # Static prefix includes system messages and developer instructions before first user turn
65
- if role in ("system", "developer") and isinstance(content, str):
66
- cleaned_content = cls.strip_volatile_elements(content)
67
- msg_copy["content"] = cleaned_content
68
- static_prefix_parts.append(cleaned_content)
69
- last_static_idx = idx
157
+ if role in ("system", "developer") and not seen_non_static:
158
+ if isinstance(content, str):
159
+ cleaned_content = cls.strip_volatile_elements(content)
160
+ msg_copy["content"] = cleaned_content
161
+ static_prefix_parts.append(cleaned_content)
162
+ last_static_idx = idx
163
+ elif isinstance(content, list):
164
+ cleaned_blocks = []
165
+ for blk in content:
166
+ if isinstance(blk, dict) and isinstance(blk.get("text"), str):
167
+ blk_copy = dict(blk)
168
+ blk_copy["text"] = cls.strip_volatile_elements(blk_copy["text"])
169
+ cleaned_blocks.append(blk_copy)
170
+ static_prefix_parts.append(blk_copy["text"])
171
+ else:
172
+ cleaned_blocks.append(blk)
173
+ msg_copy["content"] = cleaned_blocks
174
+ last_static_idx = idx
175
+ else:
176
+ seen_non_static = True
70
177
  normalized.append(msg_copy)
71
178
 
72
- prefix_str = "\n".join(static_prefix_parts)
179
+ tools_str = json.dumps(norm_tools, sort_keys=True, ensure_ascii=False) if norm_tools else ""
180
+ prefix_str = "\n".join(p for p in (tools_str, *static_prefix_parts) if p)
73
181
  prefix_tokens = count_tokens(prefix_str) if prefix_str else 0
74
182
  prefix_hash = cls.compute_prefix_hash(prefix_str) if prefix_str else ""
75
183
 
76
- # Anthropic caching requires >= 1024 tokens for Claude 3.5 Sonnet / Haiku
77
- # DeepSeek caches 64-token chunks
78
184
  cache_eligible = prefix_tokens >= 64
79
- cache_control_injected = False
80
-
81
- if inject_cache_control and last_static_idx >= 0 and prefix_tokens >= 1024:
82
- target_msg = normalized[last_static_idx]
83
- content_val = target_msg.get("content")
84
- if isinstance(content_val, str):
85
- # Anthropic structured content format with cache_control block
86
- target_msg["content"] = [
87
- {
88
- "type": "text",
89
- "text": content_val,
90
- "cache_control": {"type": "ephemeral"}
91
- }
92
- ]
93
- cache_control_injected = True
94
- elif isinstance(content_val, list) and len(content_val) > 0:
95
- if isinstance(content_val[-1], dict):
96
- content_val[-1]["cache_control"] = {"type": "ephemeral"}
97
- cache_control_injected = True
98
-
99
- return normalized, {
185
+ breakpoints_injected = 0
186
+ supports_cc = provider in ("generic", "anthropic")
187
+
188
+ if inject_cache_control and supports_cc:
189
+ # Breakpoint #1: Tools schema tail (for Anthropic when tools are supplied)
190
+ if provider == "anthropic" and norm_tools and len(norm_tools) > 0 and isinstance(norm_tools[-1], dict):
191
+ if prefix_tokens >= 1024:
192
+ norm_tools[-1]["cache_control"] = {"type": "ephemeral"}
193
+ breakpoints_injected += 1
194
+
195
+ # Breakpoint #2: Static system/developer prefix tail
196
+ if last_static_idx >= 0 and prefix_tokens >= 1024:
197
+ if _inject_cache_control_on_msg(normalized[last_static_idx]):
198
+ breakpoints_injected += 1
199
+
200
+ # Breakpoint #3: Rolling history checkpoint (penultimate turn before new user input)
201
+ if provider == "anthropic" and len(normalized) >= 3 and breakpoints_injected < 4:
202
+ penultimate_idx = len(normalized) - 2
203
+ if penultimate_idx > last_static_idx:
204
+ upto_tokens = prefix_tokens + sum(
205
+ count_tokens(_message_text(m))
206
+ for m in normalized[last_static_idx + 1 : penultimate_idx + 1]
207
+ )
208
+ if upto_tokens >= 1024 and _inject_cache_control_on_msg(normalized[penultimate_idx]):
209
+ breakpoints_injected += 1
210
+
211
+ meta: Dict[str, Any] = {
100
212
  "prefix_tokens": prefix_tokens,
101
213
  "prefix_hash": prefix_hash,
102
214
  "cache_eligible": cache_eligible,
103
- "cache_control_injected": cache_control_injected,
104
- "provider": provider
215
+ "cache_control_injected": breakpoints_injected > 0,
216
+ "breakpoints_injected": breakpoints_injected,
217
+ "provider": provider,
105
218
  }
219
+ if prefix_hash:
220
+ meta["prompt_cache_key"] = prefix_hash[:32]
221
+ if norm_tools is not None:
222
+ meta["normalized_tools"] = norm_tools
223
+
224
+ return normalized, meta
package/src/cli.py CHANGED
@@ -385,8 +385,12 @@ def main():
385
385
  else:
386
386
  print(f" Expires: Never (Lifetime)")
387
387
  else:
388
- print(" Status: Free Tier (up to 500,000 tokens/mo)")
389
- print(" Upgrade: https://tokensafe.dev ($9/mo Solo with 7-Day Free Trial)\n")
388
+ quota = LicenseManager.check_quota()
389
+ q_saved = int(quota.get("monthly_saved", 0))
390
+ q_limit = int(quota.get("monthly_limit") or 500_000)
391
+ q_state = "\033[31mQUOTA REACHED (Pro optimizations paused)\033[0m" if quota.get("is_quota_exceeded") else "\033[32mActive\033[0m"
392
+ print(f" Status: Free Tier ({q_saved:,} / {q_limit:,} measured tokens this month · {q_state})")
393
+ print(" Upgrade: https://tokensafe.dev/#pricing ($9/mo Solo with 7-Day Free Trial)\n")
390
394
  print()
391
395
 
392
396
  elif command in ("providers", "models", "keys"):
package/src/dashboard.py CHANGED
@@ -81,10 +81,10 @@ class Dashboard:
81
81
  limit = 500_000
82
82
  q_pct = min(100.0, (monthly_saved / limit * 100.0))
83
83
  if monthly_saved >= limit:
84
- out.append(f" {BOLD}Subscription Tier:{RESET} {YELLOW}COMMUNITY (Free){RESET} • {RED}{BOLD}500k Monthly Quota Reached{RESET}")
85
- out.append(f" {BOLD}Quota Usage:{RESET} {RED}{render_bar(q_pct)}{RESET} (Upgrade to Solo for Unlimited: {CYAN}https://tokensafe.dev/#pricing{RESET})")
84
+ out.append(f" {BOLD}Subscription Tier:{RESET} {YELLOW}COMMUNITY (Free){RESET} • {RED}{BOLD}500k Monthly Measured Quota Reached ({monthly_saved:,}/{limit:,}){RESET}")
85
+ out.append(f" {BOLD}Quota Usage:{RESET} {RED}{render_bar(q_pct)}{RESET} (Pro optimizations paused · Upgrade: tokensafe activate <key> | {CYAN}https://tokensafe.dev/#pricing{RESET})")
86
86
  else:
87
- out.append(f" {BOLD}Subscription Tier:{RESET} {YELLOW}COMMUNITY (Free){RESET} • {monthly_saved:,} / {limit:,} tokens this month")
87
+ out.append(f" {BOLD}Subscription Tier:{RESET} {YELLOW}COMMUNITY (Free){RESET} • {monthly_saved:,} / {limit:,} measured tokens this month")
88
88
  out.append(f" {BOLD}Quota Usage:{RESET} {YELLOW}{render_bar(q_pct)}{RESET} (Upgrade to Solo for Unlimited)")
89
89
  else:
90
90
  email_info = f" ({payload.get('email', '')})" if payload.get('email') else ""
@@ -161,6 +161,12 @@ class Dashboard:
161
161
 
162
162
  md = []
163
163
  md.append("# ⚡ TokenSafe Context & Token Optimizer Report\n")
164
+ quota = LicenseManager.check_quota(self.tracker)
165
+ if quota.get("tier") == "free":
166
+ m_saved = int(quota.get("monthly_saved", 0))
167
+ m_limit = int(quota.get("monthly_limit") or 500_000)
168
+ status_tag = "QUOTA REACHED — Pro optimizers paused" if quota.get("is_quota_exceeded") else "Active"
169
+ md.append(f"> **Plan:** Community (`{m_saved:,} / {m_limit:,}` measured tokens/mo · **{status_tag}**)\n")
164
170
  md.append(f"> **Cumulative Resource Efficiency:** **{pct:.1f}% Reduction** across {summary['total_events']} events.\n")
165
171
  md.append("| Metric | Value |")
166
172
  md.append("| :--- | :--- |")
@@ -242,7 +248,7 @@ class Dashboard:
242
248
  banner_html = f"""
243
249
  <div style="background: rgba(234, 179, 8, 0.1); border: 1px solid rgba(234, 179, 8, 0.3); border-radius: 12px; padding: 14px 18px; margin-bottom: 24px; display: flex; justify-content: space-between; align-items: center; font-size: 13px;">
244
250
  <div>
245
- <strong style="color: #eab308;">⚡ Community Edition:</strong> {monthly_saved:,} / {limit:,} free tokens saved this month ({q_pct}%).
251
+ <strong style="color: #eab308;">⚡ Community Edition:</strong> {monthly_saved:,} / {limit:,} free measured tokens saved this month ({q_pct}%).
246
252
  </div>
247
253
  <a href="https://tokensafe.dev/#pricing" target="_blank" style="background: #10b981; color: #090a0f; font-weight: 700; padding: 6px 14px; border-radius: 8px; text-decoration: none; font-size: 12px;">Upgrade to Solo (Unlimited)</a>
248
254
  </div>
@@ -5,20 +5,31 @@ Zero external runtime dependencies.
5
5
  """
6
6
 
7
7
  import os
8
+ import re
8
9
  import hashlib
9
10
  import sqlite3
10
11
  import threading
11
12
  from collections import OrderedDict
12
13
  from datetime import datetime
13
- from typing import Optional, Dict, Any
14
-
14
+ from typing import Optional, Dict, Any, Tuple
15
15
  from src.paths import resolve_data_dir
16
16
 
17
+
18
+ _COMBINED_SLOT_RE = re.compile(
19
+ r"(?P<file>(?<![A-Za-z0-9_])(?:[A-Za-z0-9_.-]+[/\\])*[A-Za-z0-9_-]+\."
20
+ r"(?:py|ts|tsx|js|jsx|mjs|cjs|go|rs|java|cs|cpp|c|h|hpp|rb|php|kt|swift|css|scss|json|yaml|yml|toml|md|sql|sh)\b)"
21
+ r"|`(?P<bt_sym>[A-Za-z_][A-Za-z0-9_]*)`"
22
+ r"|\b(?P<sym>[a-zA-Z][a-zA-Z0-9]*_[a-zA-Z0-9_]+|[a-z]+[A-Z][a-zA-Z0-9]*|[A-Z][a-z]+[A-Z][a-zA-Z0-9]*)\b"
23
+ )
24
+ _UNRESOLVED_SLOT_RE = re.compile(r"<(?:FILE|SYM)_\d+>")
25
+
26
+
17
27
  class DistillationCache:
18
- """Thread-safe two-tier cache (In-Memory LRU + Persistent SQLite)."""
28
+ """Thread-safe two-tier cache (In-Memory LRU + Persistent SQLite) with parametric slot templates."""
19
29
 
20
30
  _lock = threading.Lock()
21
31
  _memory_cache: OrderedDict = OrderedDict()
32
+ _template_memory_cache: OrderedDict = OrderedDict()
22
33
  _MAX_MEMORY_ENTRIES = 1000
23
34
  _db_path: Optional[str] = None
24
35
  _initialized_dbs: set = set()
@@ -36,6 +47,67 @@ class DistillationCache:
36
47
  norm = cls._normalize_prompt(prompt_text)
37
48
  return hashlib.sha256(norm.encode("utf-8")).hexdigest()
38
49
 
50
+ @classmethod
51
+ def _extract_template(cls, prompt_text: str) -> Tuple[str, Dict[str, str]]:
52
+ """Extracts file paths and code identifiers in one pass for template reuse."""
53
+ norm = cls._normalize_prompt(prompt_text)
54
+ slots: Dict[str, str] = {}
55
+ val_to_slot: Dict[str, str] = {}
56
+ file_idx = 0
57
+ sym_idx = 0
58
+
59
+ def repl_any(m: re.Match) -> str:
60
+ nonlocal file_idx, sym_idx
61
+ file_val = m.group("file")
62
+ if file_val:
63
+ if file_val not in val_to_slot:
64
+ slot = f"<FILE_{file_idx}>"
65
+ file_idx += 1
66
+ val_to_slot[file_val] = slot
67
+ slots[slot] = file_val
68
+ return val_to_slot[file_val]
69
+ sym_val = m.group("bt_sym") or m.group("sym")
70
+ if sym_val:
71
+ if sym_val not in val_to_slot:
72
+ slot = f"<SYM_{sym_idx}>"
73
+ sym_idx += 1
74
+ val_to_slot[sym_val] = slot
75
+ slots[slot] = sym_val
76
+ return val_to_slot[sym_val]
77
+ return m.group(0)
78
+
79
+ templated = _COMBINED_SLOT_RE.sub(repl_any, norm)
80
+ # Lowercase surrounding natural language while keeping uppercase slot tokens intact
81
+ parts = re.split(r"(<(?:FILE|SYM)_\d+>)", templated)
82
+ normalized_tmpl = "".join(p if _UNRESOLVED_SLOT_RE.fullmatch(p) else p.lower() for p in parts)
83
+ return normalized_tmpl, slots
84
+
85
+ @classmethod
86
+ def _to_template_sexpr(cls, distilled_text: str, slots: Dict[str, str]) -> Optional[str]:
87
+ """Replaces extracted slot values in distilled S-Expression with placeholders."""
88
+ if not slots:
89
+ return None
90
+ tmpl = distilled_text.strip()
91
+ # Sort longest values first to avoid partial substring clashes
92
+ replaced_any = False
93
+ for slot, val in sorted(slots.items(), key=lambda kv: len(kv[1]), reverse=True):
94
+ if val in tmpl:
95
+ tmpl = tmpl.replace(val, slot)
96
+ replaced_any = True
97
+ return tmpl if replaced_any else None
98
+
99
+ @classmethod
100
+ def _instantiate_template(cls, template_sexpr: str, slots: Dict[str, str]) -> Optional[str]:
101
+ """Substitutes current prompt's slots back into a cached template S-Expression."""
102
+ if not template_sexpr:
103
+ return None
104
+ out = template_sexpr
105
+ for slot, val in slots.items():
106
+ out = out.replace(slot, val)
107
+ if _UNRESOLVED_SLOT_RE.search(out):
108
+ return None
109
+ return out
110
+
39
111
  @classmethod
40
112
  def _get_db_path(cls) -> str:
41
113
  if cls._db_path:
@@ -62,26 +134,36 @@ class DistillationCache:
62
134
  );
63
135
  """)
64
136
  conn.execute("CREATE INDEX IF NOT EXISTS idx_distill_hash ON distillation_cache(prompt_hash);")
137
+ conn.execute("""
138
+ CREATE TABLE IF NOT EXISTS distillation_templates (
139
+ template_hash TEXT PRIMARY KEY,
140
+ template_prompt TEXT,
141
+ template_sexpr TEXT NOT NULL,
142
+ provider TEXT NOT NULL,
143
+ created_at TEXT NOT NULL,
144
+ hit_count INTEGER DEFAULT 0
145
+ );
146
+ """)
65
147
  conn.commit()
66
148
  cls._initialized_dbs.add(db_path)
67
149
 
68
150
  @classmethod
69
151
  def get(cls, prompt_text: str) -> Optional[str]:
70
- """Retrieves cached distillation S-Expression if present."""
152
+ """Retrieves cached distillation S-Expression via exact or parametric template lookup."""
71
153
  if not prompt_text or not prompt_text.strip():
72
154
  return None
73
155
 
74
156
  h = cls._hash_prompt(prompt_text)
75
157
 
76
158
  with cls._lock:
77
- # 1. Check in-memory LRU
159
+ # 1. Check exact in-memory LRU
78
160
  if h in cls._memory_cache:
79
161
  cls._hits += 1
80
162
  distilled = cls._memory_cache.pop(h)
81
- cls._memory_cache[h] = distilled # Move to end (most recently used)
163
+ cls._memory_cache[h] = distilled
82
164
  return distilled
83
165
 
84
- # 2. Check SQLite persistent cache
166
+ # 2. Check SQLite persistent exact cache
85
167
  db_path = cls._get_db_path()
86
168
  conn = None
87
169
  try:
@@ -105,7 +187,7 @@ class DistillationCache:
105
187
  cls._hits += 1
106
188
  cls._memory_cache[h] = distilled_text
107
189
  if len(cls._memory_cache) > cls._MAX_MEMORY_ENTRIES:
108
- cls._memory_cache.popitem(last=False) # Evict oldest
190
+ cls._memory_cache.popitem(last=False)
109
191
 
110
192
  return distilled_text
111
193
  except Exception:
@@ -117,7 +199,60 @@ class DistillationCache:
117
199
  except Exception:
118
200
  pass
119
201
 
120
- # 3. Check L3 Shared Team Cache (TokenSafe Team tier)
202
+ # 3. Check parametric template cache (L1 memory + L2 SQLite)
203
+ tmpl_prompt, slots = cls._extract_template(prompt_text)
204
+ tmpl_hash = hashlib.sha256(tmpl_prompt.encode("utf-8")).hexdigest() if slots else ""
205
+
206
+ if tmpl_hash:
207
+ with cls._lock:
208
+ tmpl_sexpr = cls._template_memory_cache.get(tmpl_hash)
209
+ if tmpl_sexpr is not None:
210
+ cls._template_memory_cache.move_to_end(tmpl_hash)
211
+ if tmpl_sexpr:
212
+ instantiated = cls._instantiate_template(tmpl_sexpr, slots)
213
+ if instantiated:
214
+ cls.set(prompt_text, instantiated, provider="template_cache", sync_remote=False)
215
+ with cls._lock:
216
+ cls._hits += 1
217
+ return instantiated
218
+
219
+ conn = None
220
+ try:
221
+ conn = sqlite3.connect(db_path, timeout=5.0)
222
+ cls._init_db(conn)
223
+ cursor = conn.cursor()
224
+ cursor.execute(
225
+ "SELECT template_sexpr, hit_count FROM distillation_templates WHERE template_hash = ?",
226
+ (tmpl_hash,)
227
+ )
228
+ row = cursor.fetchone()
229
+ if row:
230
+ tmpl_sexpr_db, hit_count = row[0], row[1]
231
+ instantiated = cls._instantiate_template(tmpl_sexpr_db, slots)
232
+ if instantiated:
233
+ cursor.execute(
234
+ "UPDATE distillation_templates SET hit_count = ? WHERE template_hash = ?",
235
+ (hit_count + 1, tmpl_hash)
236
+ )
237
+ conn.commit()
238
+ with cls._lock:
239
+ cls._template_memory_cache[tmpl_hash] = tmpl_sexpr_db
240
+ if len(cls._template_memory_cache) > cls._MAX_MEMORY_ENTRIES:
241
+ cls._template_memory_cache.popitem(last=False)
242
+ cls.set(prompt_text, instantiated, provider="template_cache", sync_remote=False)
243
+ with cls._lock:
244
+ cls._hits += 1
245
+ return instantiated
246
+ except Exception:
247
+ pass
248
+ finally:
249
+ if conn:
250
+ try:
251
+ conn.close()
252
+ except Exception:
253
+ pass
254
+
255
+ # 4. Check L3 Shared Team Cache (exact, then parametric template)
121
256
  try:
122
257
  from src.team_cache import TeamCache
123
258
  team_val = TeamCache.get("PROMPT", prompt_text)
@@ -126,6 +261,14 @@ class DistillationCache:
126
261
  with cls._lock:
127
262
  cls._hits += 1
128
263
  return team_val
264
+ if tmpl_hash:
265
+ team_tmpl = TeamCache.get("PROMPT_TMPL", tmpl_prompt)
266
+ instantiated = cls._instantiate_template(team_tmpl, slots) if team_tmpl else None
267
+ if instantiated:
268
+ cls.set(prompt_text, instantiated, provider="team_template_cache", sync_remote=False)
269
+ with cls._lock:
270
+ cls._hits += 1
271
+ return instantiated
129
272
  except Exception:
130
273
  pass
131
274
 
@@ -135,18 +278,27 @@ class DistillationCache:
135
278
 
136
279
  @classmethod
137
280
  def set(cls, prompt_text: str, distilled_text: str, provider: str = "deepseek", sync_remote: bool = True) -> None:
138
- """Stores a distillation result into memory LRU, SQLite cache, and Team Cache if applicable."""
281
+ """Stores a distillation result and parametric template into memory, SQLite, and Team Cache."""
139
282
  if not prompt_text or not distilled_text or not distilled_text.strip():
140
283
  return
141
284
 
142
285
  h = cls._hash_prompt(prompt_text)
143
286
  norm_prompt = cls._normalize_prompt(prompt_text)
287
+ clean_distilled = distilled_text.strip()
144
288
  now_iso = datetime.now().isoformat()
145
289
 
290
+ tmpl_prompt, slots = cls._extract_template(prompt_text)
291
+ tmpl_sexpr = cls._to_template_sexpr(clean_distilled, slots) if slots else None
292
+ tmpl_hash = hashlib.sha256(tmpl_prompt.encode("utf-8")).hexdigest() if tmpl_sexpr else ""
293
+
146
294
  with cls._lock:
147
- cls._memory_cache[h] = distilled_text.strip()
295
+ cls._memory_cache[h] = clean_distilled
148
296
  if len(cls._memory_cache) > cls._MAX_MEMORY_ENTRIES:
149
297
  cls._memory_cache.popitem(last=False)
298
+ if tmpl_hash and tmpl_sexpr:
299
+ cls._template_memory_cache[tmpl_hash] = tmpl_sexpr
300
+ if len(cls._template_memory_cache) > cls._MAX_MEMORY_ENTRIES:
301
+ cls._template_memory_cache.popitem(last=False)
150
302
 
151
303
  db_path = cls._get_db_path()
152
304
  conn = None
@@ -160,7 +312,15 @@ class DistillationCache:
160
312
  ON CONFLICT(prompt_hash) DO UPDATE SET
161
313
  distilled_text = excluded.distilled_text,
162
314
  provider = excluded.provider
163
- """, (h, norm_prompt[:500], distilled_text.strip(), provider, now_iso))
315
+ """, (h, norm_prompt[:500], clean_distilled, provider, now_iso))
316
+ if tmpl_hash and tmpl_sexpr:
317
+ cursor.execute("""
318
+ INSERT INTO distillation_templates (template_hash, template_prompt, template_sexpr, provider, created_at, hit_count)
319
+ VALUES (?, ?, ?, ?, ?, 0)
320
+ ON CONFLICT(template_hash) DO UPDATE SET
321
+ template_sexpr = excluded.template_sexpr,
322
+ provider = excluded.provider
323
+ """, (tmpl_hash, tmpl_prompt[:500], tmpl_sexpr, provider, now_iso))
164
324
  conn.commit()
165
325
  except Exception:
166
326
  pass
@@ -175,7 +335,9 @@ class DistillationCache:
175
335
  if sync_remote:
176
336
  try:
177
337
  from src.team_cache import TeamCache
178
- TeamCache.put("PROMPT", prompt_text, distilled_text.strip(), tokens_saved=45)
338
+ TeamCache.put("PROMPT", prompt_text, clean_distilled, tokens_saved=45)
339
+ if tmpl_hash and tmpl_sexpr:
340
+ TeamCache.put("PROMPT_TMPL", tmpl_prompt, tmpl_sexpr, tokens_saved=45)
179
341
  except Exception:
180
342
  pass
181
343
 
@@ -184,6 +346,7 @@ class DistillationCache:
184
346
  """Clears both in-memory and persistent SQLite cache."""
185
347
  with cls._lock:
186
348
  cls._memory_cache.clear()
349
+ cls._template_memory_cache.clear()
187
350
  cls._hits = 0
188
351
  cls._misses = 0
189
352
 
@@ -193,6 +356,7 @@ class DistillationCache:
193
356
  conn = sqlite3.connect(db_path, timeout=5.0)
194
357
  cls._init_db(conn)
195
358
  conn.execute("DELETE FROM distillation_cache;")
359
+ conn.execute("DELETE FROM distillation_templates;")
196
360
  conn.commit()
197
361
  except Exception:
198
362
  pass