ctxcache 0.3.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.
- ctxcache/__init__.py +109 -0
- ctxcache/adapters/__init__.py +15 -0
- ctxcache/adapters/anthropic.py +34 -0
- ctxcache/adapters/base.py +25 -0
- ctxcache/adapters/bedrock.py +46 -0
- ctxcache/adapters/gemini.py +34 -0
- ctxcache/adapters/openai.py +42 -0
- ctxcache/bedrock_converse.py +67 -0
- ctxcache/bench/__init__.py +1 -0
- ctxcache/bench/runner.py +96 -0
- ctxcache/cli.py +326 -0
- ctxcache/compaction.py +102 -0
- ctxcache/cost.py +171 -0
- ctxcache/data/breaks.yaml +124 -0
- ctxcache/data/providers.toml +199 -0
- ctxcache/exceptions.py +23 -0
- ctxcache/fingerprint.py +68 -0
- ctxcache/guard.py +253 -0
- ctxcache/integrations/__init__.py +17 -0
- ctxcache/integrations/langchain.py +7 -0
- ctxcache/integrations/langgraph.py +144 -0
- ctxcache/integrations/openai_agents.py +42 -0
- ctxcache/integrations/pydantic_ai.py +44 -0
- ctxcache/layout.py +255 -0
- ctxcache/ledger.py +179 -0
- ctxcache/memory/__init__.py +25 -0
- ctxcache/memory/checks.py +53 -0
- ctxcache/memory/recall.py +50 -0
- ctxcache/memory/store.py +315 -0
- ctxcache/offload.py +134 -0
- ctxcache/openai_chat.py +61 -0
- ctxcache/otel.py +60 -0
- ctxcache/planner.py +167 -0
- ctxcache/policies/__init__.py +36 -0
- ctxcache/policies/route.py +179 -0
- ctxcache/replay.py +193 -0
- ctxcache/scenarios.py +250 -0
- ctxcache/segments.py +162 -0
- ctxcache/sim/__init__.py +13 -0
- ctxcache/sim/cache_sim.py +152 -0
- ctxcache/sim/tokens.py +56 -0
- ctxcache/testing.py +250 -0
- ctxcache/tools.py +49 -0
- ctxcache/trace.py +109 -0
- ctxcache/wrapper.py +609 -0
- ctxcache-0.3.0.dist-info/METADATA +218 -0
- ctxcache-0.3.0.dist-info/RECORD +50 -0
- ctxcache-0.3.0.dist-info/WHEEL +4 -0
- ctxcache-0.3.0.dist-info/entry_points.txt +2 -0
- ctxcache-0.3.0.dist-info/licenses/LICENSE +176 -0
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Write checks and safety guards for CtxCache memory (BUILD_HANDBOOK §5.7, M5)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
# Secret pattern detectors
|
|
8
|
+
SECRETS_PATTERNS = [
|
|
9
|
+
re.compile(r"sk-[a-zA-Z0-9_\-]{20,}", re.IGNORECASE), # API keys
|
|
10
|
+
re.compile(r"AIza[0-9A-Za-z\-_]{35}"), # Google API key
|
|
11
|
+
re.compile(r"ghp_[0-9a-zA-Z]{36}"), # GitHub Personal Access Token
|
|
12
|
+
re.compile(r"AKIA[0-9A-Z]{16}"), # AWS Access Key ID
|
|
13
|
+
re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----"), # Private keys
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
# Instruction override / prompt injection patterns
|
|
17
|
+
INJECTION_PATTERNS = [
|
|
18
|
+
re.compile(r"\bignore\s+previous\b", re.IGNORECASE),
|
|
19
|
+
re.compile(r"\bfrom\s+now\s+on\b", re.IGNORECASE),
|
|
20
|
+
re.compile(r"\balways\s+(?:cc|forward|send)\b", re.IGNORECASE),
|
|
21
|
+
re.compile(r"\bdisregard\s+prior\b", re.IGNORECASE),
|
|
22
|
+
re.compile(r"\bsystem\s+override\b", re.IGNORECASE),
|
|
23
|
+
re.compile(r"\byou\s+are\s+now\b", re.IGNORECASE),
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
MAX_FACT_VALUE_LENGTH = 2000
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class MemoryWriteError(ValueError):
|
|
30
|
+
"""Raised when a memory fact fails safety or size write checks."""
|
|
31
|
+
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def validate_fact_write(value: str) -> None:
|
|
36
|
+
"""Validate fact value against size, secrets, and instruction-injection rules (BUILD_HANDBOOK §5.7)."""
|
|
37
|
+
# 1. Size check
|
|
38
|
+
if len(value) > MAX_FACT_VALUE_LENGTH:
|
|
39
|
+
raise MemoryWriteError(
|
|
40
|
+
f"Fact value exceeds maximum length of {MAX_FACT_VALUE_LENGTH} characters (got {len(value)})"
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
# 2. Secret check
|
|
44
|
+
for pat in SECRETS_PATTERNS:
|
|
45
|
+
if pat.search(value):
|
|
46
|
+
raise MemoryWriteError("Fact value rejected: contains sensitive secret or credentials")
|
|
47
|
+
|
|
48
|
+
# 3. Instruction-like text check
|
|
49
|
+
for pat in INJECTION_PATTERNS:
|
|
50
|
+
if pat.search(value):
|
|
51
|
+
raise MemoryWriteError(
|
|
52
|
+
"Fact value rejected: contains prompt injection or override instruction"
|
|
53
|
+
)
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Convenience memory recall and pinning functions (BUILD_HANDBOOK §5.7)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from ctxcache.memory.store import Fact, MemoryStore
|
|
6
|
+
|
|
7
|
+
_GLOBAL_STORE: MemoryStore | None = None
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def get_default_memory_store() -> MemoryStore:
|
|
11
|
+
global _GLOBAL_STORE
|
|
12
|
+
if _GLOBAL_STORE is None:
|
|
13
|
+
_GLOBAL_STORE = MemoryStore()
|
|
14
|
+
return _GLOBAL_STORE
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def set_default_memory_store(store: MemoryStore) -> None:
|
|
18
|
+
global _GLOBAL_STORE
|
|
19
|
+
_GLOBAL_STORE = store
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def remember(
|
|
23
|
+
scope: str,
|
|
24
|
+
subject: str,
|
|
25
|
+
predicate: str,
|
|
26
|
+
value: str,
|
|
27
|
+
source: str = "user",
|
|
28
|
+
source_session: str | None = None,
|
|
29
|
+
tainted: bool = False,
|
|
30
|
+
) -> int:
|
|
31
|
+
"""Store a fact in the default memory store."""
|
|
32
|
+
return get_default_memory_store().remember(
|
|
33
|
+
scope=scope,
|
|
34
|
+
subject=subject,
|
|
35
|
+
predicate=predicate,
|
|
36
|
+
value=value,
|
|
37
|
+
source=source,
|
|
38
|
+
source_session=source_session,
|
|
39
|
+
tainted=tainted,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def recall(scope: str, query: str, k: int = 5) -> list[Fact]:
|
|
44
|
+
"""Recall active facts matching query in scope."""
|
|
45
|
+
return get_default_memory_store().recall(scope=scope, query=query, k=k)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def pin(scope: str, subjects: list[str]) -> list[Fact]:
|
|
49
|
+
"""Retrieve pinned facts for session start."""
|
|
50
|
+
return get_default_memory_store().pin(scope=scope, subjects=subjects)
|
ctxcache/memory/store.py
ADDED
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
"""SQLite facts store and temporal superseding model for CtxCache memory (BUILD_HANDBOOK §5.7, INV-12)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import sqlite3
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from datetime import datetime, timezone
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
import ctxcache
|
|
12
|
+
from ctxcache.memory.checks import validate_fact_write
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass
|
|
16
|
+
class Fact:
|
|
17
|
+
id: int
|
|
18
|
+
scope: str
|
|
19
|
+
subject: str
|
|
20
|
+
predicate: str
|
|
21
|
+
value: str
|
|
22
|
+
valid_from: str
|
|
23
|
+
valid_to: str | None
|
|
24
|
+
superseded_by: int | None
|
|
25
|
+
source: str
|
|
26
|
+
source_session: str | None
|
|
27
|
+
tainted: bool
|
|
28
|
+
created_at: str
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class MemoryStore:
|
|
32
|
+
"""Manages long-term structured facts with temporal validity and superseding (INV-12)."""
|
|
33
|
+
|
|
34
|
+
def __init__(self, db_path: str | Path | None = None):
|
|
35
|
+
if db_path is None:
|
|
36
|
+
ctxcache_dir = os.environ.get("CTXCACHE_HOME", os.path.expanduser("~/.ctxcache"))
|
|
37
|
+
self.db_path = Path(ctxcache_dir) / "memory.sqlite"
|
|
38
|
+
else:
|
|
39
|
+
self.db_path = Path(db_path)
|
|
40
|
+
self.db_path.parent.mkdir(parents=True, exist_ok=True)
|
|
41
|
+
self._init_db()
|
|
42
|
+
# Session pinning snapshot cache to ensure mid-session writes never mutate current SESSION prefix (INV-12)
|
|
43
|
+
self._session_snapshots: dict[str, str] = {}
|
|
44
|
+
|
|
45
|
+
def _get_connection(self) -> sqlite3.Connection:
|
|
46
|
+
conn = sqlite3.connect(str(self.db_path))
|
|
47
|
+
conn.row_factory = sqlite3.Row
|
|
48
|
+
return conn
|
|
49
|
+
|
|
50
|
+
def _init_db(self) -> None:
|
|
51
|
+
with self._get_connection() as conn:
|
|
52
|
+
conn.execute(
|
|
53
|
+
"""
|
|
54
|
+
CREATE TABLE IF NOT EXISTS facts (
|
|
55
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
56
|
+
scope TEXT NOT NULL,
|
|
57
|
+
subject TEXT NOT NULL,
|
|
58
|
+
predicate TEXT NOT NULL,
|
|
59
|
+
value TEXT NOT NULL,
|
|
60
|
+
valid_from TEXT NOT NULL,
|
|
61
|
+
valid_to TEXT,
|
|
62
|
+
superseded_by INTEGER,
|
|
63
|
+
source TEXT NOT NULL,
|
|
64
|
+
source_session TEXT,
|
|
65
|
+
tainted INTEGER NOT NULL DEFAULT 0,
|
|
66
|
+
created_at TEXT NOT NULL
|
|
67
|
+
);
|
|
68
|
+
"""
|
|
69
|
+
)
|
|
70
|
+
conn.execute(
|
|
71
|
+
"CREATE INDEX IF NOT EXISTS idx_facts_scope_subj ON facts(scope, subject, predicate);"
|
|
72
|
+
)
|
|
73
|
+
conn.execute("CREATE INDEX IF NOT EXISTS idx_facts_active ON facts(scope, valid_to);")
|
|
74
|
+
|
|
75
|
+
# Create FTS5 table if supported
|
|
76
|
+
try:
|
|
77
|
+
conn.execute(
|
|
78
|
+
"""
|
|
79
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS facts_fts USING fts5(
|
|
80
|
+
fact_id UNINDEXED,
|
|
81
|
+
scope,
|
|
82
|
+
subject,
|
|
83
|
+
predicate,
|
|
84
|
+
value
|
|
85
|
+
);
|
|
86
|
+
"""
|
|
87
|
+
)
|
|
88
|
+
except sqlite3.OperationalError:
|
|
89
|
+
pass # Fallback to standard SQL query if FTS5 is not compiled in SQLite
|
|
90
|
+
|
|
91
|
+
def remember(
|
|
92
|
+
self,
|
|
93
|
+
scope: str,
|
|
94
|
+
subject: str,
|
|
95
|
+
predicate: str,
|
|
96
|
+
value: str,
|
|
97
|
+
source: str = "user",
|
|
98
|
+
source_session: str | None = None,
|
|
99
|
+
tainted: bool = False,
|
|
100
|
+
) -> int:
|
|
101
|
+
"""Store a new fact, superseding any prior active fact for the same scope, subject, and predicate."""
|
|
102
|
+
validate_fact_write(value)
|
|
103
|
+
|
|
104
|
+
now_iso = datetime.now(timezone.utc).isoformat()
|
|
105
|
+
with self._get_connection() as conn:
|
|
106
|
+
# Check for existing active fact
|
|
107
|
+
cur = conn.execute(
|
|
108
|
+
"""
|
|
109
|
+
SELECT id FROM facts
|
|
110
|
+
WHERE scope = ? AND subject = ? AND predicate = ? AND valid_to IS NULL
|
|
111
|
+
ORDER BY id DESC LIMIT 1
|
|
112
|
+
""",
|
|
113
|
+
(scope, subject, predicate),
|
|
114
|
+
)
|
|
115
|
+
row = cur.fetchone()
|
|
116
|
+
old_fact_id = row["id"] if row else None
|
|
117
|
+
|
|
118
|
+
# Insert new fact
|
|
119
|
+
ins_cur = conn.execute(
|
|
120
|
+
"""
|
|
121
|
+
INSERT INTO facts (
|
|
122
|
+
scope, subject, predicate, value, valid_from, valid_to,
|
|
123
|
+
superseded_by, source, source_session, tainted, created_at
|
|
124
|
+
) VALUES (?, ?, ?, ?, ?, NULL, NULL, ?, ?, ?, ?)
|
|
125
|
+
""",
|
|
126
|
+
(
|
|
127
|
+
scope,
|
|
128
|
+
subject,
|
|
129
|
+
predicate,
|
|
130
|
+
value,
|
|
131
|
+
now_iso,
|
|
132
|
+
source,
|
|
133
|
+
source_session,
|
|
134
|
+
1 if tainted else 0,
|
|
135
|
+
now_iso,
|
|
136
|
+
),
|
|
137
|
+
)
|
|
138
|
+
new_fact_id = int(ins_cur.lastrowid or 0)
|
|
139
|
+
|
|
140
|
+
# Supersede old fact: set valid_to and superseded_by
|
|
141
|
+
if old_fact_id is not None:
|
|
142
|
+
conn.execute(
|
|
143
|
+
"UPDATE facts SET valid_to = ?, superseded_by = ? WHERE id = ?",
|
|
144
|
+
(now_iso, new_fact_id, old_fact_id),
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
# Sync with FTS table
|
|
148
|
+
try:
|
|
149
|
+
conn.execute(
|
|
150
|
+
"INSERT INTO facts_fts (fact_id, scope, subject, predicate, value) VALUES (?, ?, ?, ?, ?)",
|
|
151
|
+
(str(new_fact_id), scope, subject, predicate, value),
|
|
152
|
+
)
|
|
153
|
+
except sqlite3.OperationalError:
|
|
154
|
+
pass
|
|
155
|
+
|
|
156
|
+
# If writing mid-session, attach volatile note to current session so turn tail reflects it
|
|
157
|
+
# without mutating the static SESSION prefix segment
|
|
158
|
+
curr_session = ctxcache.get_current_session()
|
|
159
|
+
if curr_session is not None:
|
|
160
|
+
curr_session.volatile(f"[Memory Updated: {subject} {predicate} {value}]")
|
|
161
|
+
|
|
162
|
+
return new_fact_id
|
|
163
|
+
|
|
164
|
+
def get_fact(self, fact_id: int) -> Fact | None:
|
|
165
|
+
"""Retrieve a fact record by its ID."""
|
|
166
|
+
with self._get_connection() as conn:
|
|
167
|
+
cur = conn.execute("SELECT * FROM facts WHERE id = ?", (fact_id,))
|
|
168
|
+
row = cur.fetchone()
|
|
169
|
+
if not row:
|
|
170
|
+
return None
|
|
171
|
+
return Fact(
|
|
172
|
+
id=row["id"],
|
|
173
|
+
scope=row["scope"],
|
|
174
|
+
subject=row["subject"],
|
|
175
|
+
predicate=row["predicate"],
|
|
176
|
+
value=row["value"],
|
|
177
|
+
valid_from=row["valid_from"],
|
|
178
|
+
valid_to=row["valid_to"],
|
|
179
|
+
superseded_by=row["superseded_by"],
|
|
180
|
+
source=row["source"],
|
|
181
|
+
source_session=row["source_session"],
|
|
182
|
+
tainted=bool(row["tainted"]),
|
|
183
|
+
created_at=row["created_at"],
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
def recall(self, scope: str, query: str, k: int = 5) -> list[Fact]:
|
|
187
|
+
"""Recall active, non-superseded facts matching query keywords in scope."""
|
|
188
|
+
with self._get_connection() as conn:
|
|
189
|
+
# Try FTS5 search
|
|
190
|
+
facts: list[Fact] = []
|
|
191
|
+
try:
|
|
192
|
+
sanitized_query = "".join(c for c in query if c.isalnum() or c.isspace()).strip()
|
|
193
|
+
if sanitized_query:
|
|
194
|
+
match_expr = " OR ".join(sanitized_query.split())
|
|
195
|
+
cur = conn.execute(
|
|
196
|
+
"""
|
|
197
|
+
SELECT f.* FROM facts f
|
|
198
|
+
JOIN facts_fts ON facts_fts.fact_id = f.id
|
|
199
|
+
WHERE f.scope = ? AND f.valid_to IS NULL AND facts_fts MATCH ?
|
|
200
|
+
ORDER BY f.id DESC LIMIT ?
|
|
201
|
+
""",
|
|
202
|
+
(scope, match_expr, k),
|
|
203
|
+
)
|
|
204
|
+
for row in cur.fetchall():
|
|
205
|
+
facts.append(
|
|
206
|
+
Fact(
|
|
207
|
+
id=row["id"],
|
|
208
|
+
scope=row["scope"],
|
|
209
|
+
subject=row["subject"],
|
|
210
|
+
predicate=row["predicate"],
|
|
211
|
+
value=row["value"],
|
|
212
|
+
valid_from=row["valid_from"],
|
|
213
|
+
valid_to=row["valid_to"],
|
|
214
|
+
superseded_by=row["superseded_by"],
|
|
215
|
+
source=row["source"],
|
|
216
|
+
source_session=row["source_session"],
|
|
217
|
+
tainted=bool(row["tainted"]),
|
|
218
|
+
created_at=row["created_at"],
|
|
219
|
+
)
|
|
220
|
+
)
|
|
221
|
+
if facts:
|
|
222
|
+
return facts
|
|
223
|
+
except sqlite3.OperationalError:
|
|
224
|
+
pass
|
|
225
|
+
|
|
226
|
+
# Fallback to standard LIKE filter
|
|
227
|
+
cur = conn.execute(
|
|
228
|
+
"""
|
|
229
|
+
SELECT * FROM facts
|
|
230
|
+
WHERE scope = ? AND valid_to IS NULL
|
|
231
|
+
AND (subject LIKE ? OR predicate LIKE ? OR value LIKE ?)
|
|
232
|
+
ORDER BY id DESC LIMIT ?
|
|
233
|
+
""",
|
|
234
|
+
(scope, f"%{query}%", f"%{query}%", f"%{query}%", k),
|
|
235
|
+
)
|
|
236
|
+
for row in cur.fetchall():
|
|
237
|
+
facts.append(
|
|
238
|
+
Fact(
|
|
239
|
+
id=row["id"],
|
|
240
|
+
scope=row["scope"],
|
|
241
|
+
subject=row["subject"],
|
|
242
|
+
predicate=row["predicate"],
|
|
243
|
+
value=row["value"],
|
|
244
|
+
valid_from=row["valid_from"],
|
|
245
|
+
valid_to=row["valid_to"],
|
|
246
|
+
superseded_by=row["superseded_by"],
|
|
247
|
+
source=row["source"],
|
|
248
|
+
source_session=row["source_session"],
|
|
249
|
+
tainted=bool(row["tainted"]),
|
|
250
|
+
created_at=row["created_at"],
|
|
251
|
+
)
|
|
252
|
+
)
|
|
253
|
+
return facts
|
|
254
|
+
|
|
255
|
+
def pin(self, scope: str, subjects: list[str]) -> list[Fact]:
|
|
256
|
+
"""Retrieve active facts pinned for a session start."""
|
|
257
|
+
if not subjects:
|
|
258
|
+
return []
|
|
259
|
+
placeholders = ",".join("?" for _ in subjects)
|
|
260
|
+
with self._get_connection() as conn:
|
|
261
|
+
cur = conn.execute(
|
|
262
|
+
f"""
|
|
263
|
+
SELECT * FROM facts
|
|
264
|
+
WHERE scope = ? AND valid_to IS NULL AND subject IN ({placeholders})
|
|
265
|
+
ORDER BY subject ASC, id ASC
|
|
266
|
+
""",
|
|
267
|
+
[scope, *subjects],
|
|
268
|
+
)
|
|
269
|
+
facts = []
|
|
270
|
+
for row in cur.fetchall():
|
|
271
|
+
facts.append(
|
|
272
|
+
Fact(
|
|
273
|
+
id=row["id"],
|
|
274
|
+
scope=row["scope"],
|
|
275
|
+
subject=row["subject"],
|
|
276
|
+
predicate=row["predicate"],
|
|
277
|
+
value=row["value"],
|
|
278
|
+
valid_from=row["valid_from"],
|
|
279
|
+
valid_to=row["valid_to"],
|
|
280
|
+
superseded_by=row["superseded_by"],
|
|
281
|
+
source=row["source"],
|
|
282
|
+
source_session=row["source_session"],
|
|
283
|
+
tainted=bool(row["tainted"]),
|
|
284
|
+
created_at=row["created_at"],
|
|
285
|
+
)
|
|
286
|
+
)
|
|
287
|
+
return facts
|
|
288
|
+
|
|
289
|
+
def get_pinned_session_text(
|
|
290
|
+
self, scope: str, subjects: list[str], session_id: str | None = None
|
|
291
|
+
) -> str:
|
|
292
|
+
"""Render pinned session facts.
|
|
293
|
+
|
|
294
|
+
If session_id is provided or an active session is in context, caches the initial render so mid-session writes
|
|
295
|
+
never mutate the SESSION prefix segment during the active session (INV-12).
|
|
296
|
+
"""
|
|
297
|
+
if session_id is None:
|
|
298
|
+
curr = ctxcache.get_current_session()
|
|
299
|
+
if curr is not None:
|
|
300
|
+
session_id = curr.session_id
|
|
301
|
+
|
|
302
|
+
if session_id and session_id in self._session_snapshots:
|
|
303
|
+
return self._session_snapshots[session_id]
|
|
304
|
+
|
|
305
|
+
facts = self.pin(scope=scope, subjects=subjects)
|
|
306
|
+
if not facts:
|
|
307
|
+
rendered = ""
|
|
308
|
+
else:
|
|
309
|
+
lines = [f"- {f.subject} {f.predicate} {f.value}" for f in facts]
|
|
310
|
+
rendered = "Session pinned facts:\n" + "\n".join(lines)
|
|
311
|
+
|
|
312
|
+
if session_id:
|
|
313
|
+
self._session_snapshots[session_id] = rendered
|
|
314
|
+
|
|
315
|
+
return rendered
|
ctxcache/offload.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Context offloading for large tool results in optimize mode (BUILD_HANDBOOK §5.5)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from ctxcache.sim.tokens import count_text_tokens
|
|
10
|
+
|
|
11
|
+
DEFAULT_OFFLOAD_THRESHOLD_TOKENS = 2000
|
|
12
|
+
DEFAULT_PREVIEW_CHARS = 250
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class BlobStore:
|
|
16
|
+
"""Key-value storage for offloaded tool outputs keyed by SHA-256."""
|
|
17
|
+
|
|
18
|
+
def __init__(self, storage_dir: Path | None = None):
|
|
19
|
+
self._memory: dict[str, str] = {}
|
|
20
|
+
self.storage_dir = storage_dir
|
|
21
|
+
if self.storage_dir:
|
|
22
|
+
self.storage_dir.mkdir(parents=True, exist_ok=True)
|
|
23
|
+
|
|
24
|
+
def put(self, content: str) -> str:
|
|
25
|
+
"""Store content and return its SHA-256 hex digest handle."""
|
|
26
|
+
handle = hashlib.sha256(content.encode("utf-8")).hexdigest()
|
|
27
|
+
self._memory[handle] = content
|
|
28
|
+
if self.storage_dir:
|
|
29
|
+
blob_path = self.storage_dir / f"{handle}.txt"
|
|
30
|
+
if not blob_path.exists():
|
|
31
|
+
blob_path.write_text(content, encoding="utf-8")
|
|
32
|
+
return handle
|
|
33
|
+
|
|
34
|
+
def get(self, handle: str) -> str | None:
|
|
35
|
+
"""Retrieve stored content by handle."""
|
|
36
|
+
if handle in self._memory:
|
|
37
|
+
return self._memory[handle]
|
|
38
|
+
if self.storage_dir:
|
|
39
|
+
blob_path = self.storage_dir / f"{handle}.txt"
|
|
40
|
+
if blob_path.exists():
|
|
41
|
+
content = blob_path.read_text(encoding="utf-8")
|
|
42
|
+
self._memory[handle] = content
|
|
43
|
+
return content
|
|
44
|
+
return None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
_GLOBAL_BLOB_STORE: BlobStore | None = None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def get_blob_store() -> BlobStore:
|
|
51
|
+
"""Get the active global BlobStore instance."""
|
|
52
|
+
global _GLOBAL_BLOB_STORE
|
|
53
|
+
if _GLOBAL_BLOB_STORE is None:
|
|
54
|
+
home_blobs = Path.home() / ".ctxcache" / "blobs"
|
|
55
|
+
try:
|
|
56
|
+
_GLOBAL_BLOB_STORE = BlobStore(storage_dir=home_blobs)
|
|
57
|
+
except Exception:
|
|
58
|
+
_GLOBAL_BLOB_STORE = BlobStore(storage_dir=None)
|
|
59
|
+
return _GLOBAL_BLOB_STORE
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def is_read_tool_registered(tools: list[dict[str, Any]] | None) -> bool:
|
|
63
|
+
"""Check if ctxcache.tools.read_offloaded is registered in the client's tools."""
|
|
64
|
+
if not tools:
|
|
65
|
+
return False
|
|
66
|
+
|
|
67
|
+
for t in tools:
|
|
68
|
+
name = ""
|
|
69
|
+
if isinstance(t, dict):
|
|
70
|
+
name = t.get("name") or t.get("function", {}).get("name", "")
|
|
71
|
+
elif hasattr(t, "name"):
|
|
72
|
+
name = t.name
|
|
73
|
+
if name in ("read_offloaded", "ctxcache_read_offloaded"):
|
|
74
|
+
return True
|
|
75
|
+
return False
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def offload_large_tool_outputs(
|
|
79
|
+
messages: list[dict[str, Any]],
|
|
80
|
+
tools: list[dict[str, Any]] | None,
|
|
81
|
+
threshold_tokens: int = DEFAULT_OFFLOAD_THRESHOLD_TOKENS,
|
|
82
|
+
store: BlobStore | None = None,
|
|
83
|
+
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
|
84
|
+
"""Substitute tool results exceeding threshold with deterministic stubs (INV-05).
|
|
85
|
+
|
|
86
|
+
Returns (transformed_messages, changes_recorded).
|
|
87
|
+
If read tool is not registered, offloading is strictly disabled per §5.5.
|
|
88
|
+
"""
|
|
89
|
+
if not is_read_tool_registered(tools):
|
|
90
|
+
return messages, []
|
|
91
|
+
|
|
92
|
+
if store is None:
|
|
93
|
+
store = get_blob_store()
|
|
94
|
+
|
|
95
|
+
new_messages: list[dict[str, Any]] = []
|
|
96
|
+
changes: list[dict[str, Any]] = []
|
|
97
|
+
|
|
98
|
+
for idx, msg in enumerate(messages):
|
|
99
|
+
role = msg.get("role", "")
|
|
100
|
+
content = msg.get("content", "")
|
|
101
|
+
|
|
102
|
+
# Check for tool results (either role == 'tool' or tool_result block)
|
|
103
|
+
is_tool_result = role in ("tool", "tool_result") or "tool_call_id" in msg
|
|
104
|
+
if is_tool_result and isinstance(content, str):
|
|
105
|
+
token_count = count_text_tokens(content)
|
|
106
|
+
if token_count >= threshold_tokens:
|
|
107
|
+
handle = store.put(content)
|
|
108
|
+
size_chars = len(content)
|
|
109
|
+
preview = content[:DEFAULT_PREVIEW_CHARS].replace("\n", " ").strip()
|
|
110
|
+
|
|
111
|
+
stub = (
|
|
112
|
+
f"[OFFLOADED LARGE TOOL RESULT: handle={handle}, {size_chars} chars, ~{token_count} tokens. "
|
|
113
|
+
f"To inspect sections, call read_offloaded(handle='{handle}', start=..., end=...). "
|
|
114
|
+
f"Preview: {preview}...]"
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
new_msg = dict(msg)
|
|
118
|
+
new_msg["content"] = stub
|
|
119
|
+
new_messages.append(new_msg)
|
|
120
|
+
|
|
121
|
+
changes.append(
|
|
122
|
+
{
|
|
123
|
+
"kind": "output_offloaded",
|
|
124
|
+
"message_index": idx,
|
|
125
|
+
"handle": handle,
|
|
126
|
+
"tokens_saved": token_count,
|
|
127
|
+
"chars_saved": size_chars,
|
|
128
|
+
}
|
|
129
|
+
)
|
|
130
|
+
continue
|
|
131
|
+
|
|
132
|
+
new_messages.append(msg)
|
|
133
|
+
|
|
134
|
+
return new_messages, changes
|
ctxcache/openai_chat.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Stdlib client for an OpenAI-compatible Chat Completions endpoint.
|
|
2
|
+
|
|
3
|
+
Bedrock's working path is ``/openai/v1/chat/completions``. The shorter
|
|
4
|
+
``/v1/chat/completions`` path on ``bedrock-runtime`` is not that operation.
|
|
5
|
+
The API key is sent as a bearer token and is never written to the ledger.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import urllib.error
|
|
12
|
+
import urllib.request
|
|
13
|
+
from types import SimpleNamespace
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
_ALLOWED = {"model", "messages", "max_tokens", "temperature", "tools", "tool_choice"}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ChatCompletions:
|
|
20
|
+
"""Object whose ``create`` method ctxcache.wrap can intercept."""
|
|
21
|
+
|
|
22
|
+
def __init__(self, endpoint: str, api_key: str) -> None:
|
|
23
|
+
self._endpoint = endpoint
|
|
24
|
+
self._api_key = api_key
|
|
25
|
+
self.last_payload: dict[str, Any] | None = None
|
|
26
|
+
|
|
27
|
+
def create(self, **kwargs: Any) -> SimpleNamespace:
|
|
28
|
+
payload = {key: value for key, value in kwargs.items() if key in _ALLOWED}
|
|
29
|
+
self.last_payload = payload
|
|
30
|
+
request = urllib.request.Request(
|
|
31
|
+
self._endpoint,
|
|
32
|
+
data=json.dumps(payload).encode(),
|
|
33
|
+
headers={
|
|
34
|
+
"Authorization": f"Bearer {self._api_key}",
|
|
35
|
+
"Content-Type": "application/json",
|
|
36
|
+
},
|
|
37
|
+
method="POST",
|
|
38
|
+
)
|
|
39
|
+
try:
|
|
40
|
+
with urllib.request.urlopen(request, timeout=120) as response:
|
|
41
|
+
raw = response.read().decode()
|
|
42
|
+
except urllib.error.HTTPError as exc:
|
|
43
|
+
detail = exc.read().decode(errors="replace")[:500]
|
|
44
|
+
raise RuntimeError(f"chat completions HTTP {exc.code}: {detail}") from exc
|
|
45
|
+
data = json.loads(raw)
|
|
46
|
+
if "error" in data:
|
|
47
|
+
raise RuntimeError(f"chat completions error: {data['error']}")
|
|
48
|
+
usage = data.get("usage") or {}
|
|
49
|
+
return SimpleNamespace(usage=usage, raw=data)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class _Chat:
|
|
53
|
+
def __init__(self, completions: ChatCompletions) -> None:
|
|
54
|
+
self.completions = completions
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class OpenAIChatClient:
|
|
58
|
+
"""Minimal chat client. Pass the full completions URL as ``endpoint``."""
|
|
59
|
+
|
|
60
|
+
def __init__(self, endpoint: str, api_key: str) -> None:
|
|
61
|
+
self.chat = _Chat(ChatCompletions(endpoint, api_key))
|
ctxcache/otel.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""OpenTelemetry instrumentation for prompt caching spans (BUILD_HANDBOOK §4.1, D-10)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
# Optional OTel imports via importlib to avoid hard dependencies in core
|
|
9
|
+
_trace_mod = None
|
|
10
|
+
_tracer = None
|
|
11
|
+
|
|
12
|
+
try:
|
|
13
|
+
_trace_mod = importlib.import_module("opentelemetry.trace")
|
|
14
|
+
_tracer = _trace_mod.get_tracer("ctxcache", "0.1.0a1")
|
|
15
|
+
except Exception:
|
|
16
|
+
pass
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def is_otel_available() -> bool:
|
|
20
|
+
return _tracer is not None
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def record_span(
|
|
24
|
+
*,
|
|
25
|
+
session_id: str,
|
|
26
|
+
call_index: int,
|
|
27
|
+
provider: str,
|
|
28
|
+
model: str,
|
|
29
|
+
mode: str,
|
|
30
|
+
read_tokens: int,
|
|
31
|
+
write_tokens: int,
|
|
32
|
+
uncached_tokens: int,
|
|
33
|
+
output_tokens: int,
|
|
34
|
+
cost_usd: str,
|
|
35
|
+
breaks_count: int,
|
|
36
|
+
) -> Any:
|
|
37
|
+
"""Create an OTel span with semantic GenAI cache attributes if OTel is installed."""
|
|
38
|
+
if _tracer is None:
|
|
39
|
+
return None
|
|
40
|
+
|
|
41
|
+
span = _tracer.start_span(f"ctxcache.call.{call_index}")
|
|
42
|
+
total_input = read_tokens + write_tokens + uncached_tokens
|
|
43
|
+
|
|
44
|
+
# GenAI semantic conventions (D-10)
|
|
45
|
+
span.set_attribute("gen_ai.system", provider)
|
|
46
|
+
span.set_attribute("gen_ai.request.model", model)
|
|
47
|
+
span.set_attribute("gen_ai.usage.input_tokens", total_input)
|
|
48
|
+
span.set_attribute("gen_ai.usage.output_tokens", output_tokens)
|
|
49
|
+
span.set_attribute("gen_ai.usage.cache_read.input_tokens", read_tokens)
|
|
50
|
+
span.set_attribute("gen_ai.usage.cache_write.input_tokens", write_tokens)
|
|
51
|
+
|
|
52
|
+
# CtxCache specific dimensions
|
|
53
|
+
span.set_attribute("ctxcache.session_id", session_id)
|
|
54
|
+
span.set_attribute("ctxcache.call_index", call_index)
|
|
55
|
+
span.set_attribute("ctxcache.mode", mode)
|
|
56
|
+
span.set_attribute("ctxcache.cost_usd", cost_usd)
|
|
57
|
+
span.set_attribute("ctxcache.breaks_count", breaks_count)
|
|
58
|
+
|
|
59
|
+
span.end()
|
|
60
|
+
return span
|