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
ctxcache/scenarios.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
"""Four offline scenarios that show different cache outcomes.
|
|
2
|
+
|
|
3
|
+
These runs use the simulator and FakeProvider. They are not provider bills.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import html
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from decimal import Decimal
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from ctxcache.replay import replay_trace_events
|
|
14
|
+
|
|
15
|
+
_STABLE = "You are a careful coding agent.\n" + ("Follow the repository rules. " * 800)
|
|
16
|
+
_TOOLS = [
|
|
17
|
+
{"name": "read_file", "description": "Read a file"},
|
|
18
|
+
{"name": "grep_search", "description": "Search the repo"},
|
|
19
|
+
{"name": "run_tests", "description": "Run the test suite"},
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True)
|
|
24
|
+
class ModeRow:
|
|
25
|
+
mode: str
|
|
26
|
+
read_pct: float
|
|
27
|
+
cost_ratio: Decimal
|
|
28
|
+
user_caused_breaks: int
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class Scenario:
|
|
33
|
+
slug: str
|
|
34
|
+
title: str
|
|
35
|
+
story: str
|
|
36
|
+
rows: tuple[ModeRow, ...]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _call(
|
|
40
|
+
ts: float,
|
|
41
|
+
system: str,
|
|
42
|
+
messages: list[dict[str, Any]],
|
|
43
|
+
tools: list[dict[str, str]] | None = None,
|
|
44
|
+
) -> dict[str, Any]:
|
|
45
|
+
return {
|
|
46
|
+
"v": 1,
|
|
47
|
+
"ts": ts,
|
|
48
|
+
"request": {
|
|
49
|
+
"kwargs": {
|
|
50
|
+
"system": system,
|
|
51
|
+
"messages": messages,
|
|
52
|
+
"tools": tools if tools is not None else [],
|
|
53
|
+
}
|
|
54
|
+
},
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def clock_in_system() -> list[dict[str, Any]]:
|
|
59
|
+
"""A timestamp at the top of the system prompt, three turns."""
|
|
60
|
+
calls = []
|
|
61
|
+
messages: list[dict[str, Any]] = []
|
|
62
|
+
for index, stamp in enumerate(
|
|
63
|
+
("2026-11-02T08:00:00", "2026-11-02T08:00:10", "2026-11-02T08:00:20")
|
|
64
|
+
):
|
|
65
|
+
messages = [*messages, {"role": "user", "content": f"Turn {index + 1}"}]
|
|
66
|
+
if index:
|
|
67
|
+
messages = [
|
|
68
|
+
*messages[:-1],
|
|
69
|
+
{"role": "assistant", "content": "Noted."},
|
|
70
|
+
messages[-1],
|
|
71
|
+
]
|
|
72
|
+
calls.append(
|
|
73
|
+
_call(
|
|
74
|
+
ts=100.0 + index * 10,
|
|
75
|
+
system=f"Current time: {stamp}\n{_STABLE}",
|
|
76
|
+
messages=messages,
|
|
77
|
+
tools=list(_TOOLS),
|
|
78
|
+
)
|
|
79
|
+
)
|
|
80
|
+
return calls
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def tools_shuffled() -> list[dict[str, Any]]:
|
|
84
|
+
"""The same tools come back in a different order on the second turn."""
|
|
85
|
+
forward = list(_TOOLS)
|
|
86
|
+
backward = list(reversed(_TOOLS))
|
|
87
|
+
first = [{"role": "user", "content": "Find the bug."}]
|
|
88
|
+
second = [
|
|
89
|
+
{"role": "user", "content": "Find the bug."},
|
|
90
|
+
{"role": "assistant", "content": "Looking."},
|
|
91
|
+
{"role": "user", "content": "And fix the test."},
|
|
92
|
+
]
|
|
93
|
+
return [
|
|
94
|
+
_call(100.0, _STABLE, first, forward),
|
|
95
|
+
_call(110.0, _STABLE, second, backward),
|
|
96
|
+
]
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def too_short_to_cache() -> list[dict[str, Any]]:
|
|
100
|
+
"""One short question. The provider minimum is not met."""
|
|
101
|
+
question = _call(100.0, "Be brief.", [{"role": "user", "content": "What is 2+2?"}])
|
|
102
|
+
again = _call(110.0, "Be brief.", [{"role": "user", "content": "What is 2+2?"}])
|
|
103
|
+
return [question, again]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def history_rewritten() -> list[dict[str, Any]]:
|
|
107
|
+
"""The first user message is edited on the next call."""
|
|
108
|
+
return [
|
|
109
|
+
_call(100.0, _STABLE, [{"role": "user", "content": "Original question."}], list(_TOOLS)),
|
|
110
|
+
_call(
|
|
111
|
+
110.0,
|
|
112
|
+
_STABLE,
|
|
113
|
+
[
|
|
114
|
+
{"role": "user", "content": "A different question, rewritten in place."},
|
|
115
|
+
{"role": "assistant", "content": "Noted."},
|
|
116
|
+
{"role": "user", "content": "Continue."},
|
|
117
|
+
],
|
|
118
|
+
list(_TOOLS),
|
|
119
|
+
),
|
|
120
|
+
]
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _rows(calls: list[dict[str, Any]]) -> tuple[ModeRow, ...]:
|
|
124
|
+
rows: list[ModeRow] = []
|
|
125
|
+
for mode in ("observe", "safe", "optimize"):
|
|
126
|
+
summary = replay_trace_events(calls, mode=mode, provider="gemini", model="gemini-2.5-flash")
|
|
127
|
+
rows.append(
|
|
128
|
+
ModeRow(
|
|
129
|
+
mode=mode,
|
|
130
|
+
read_pct=summary.read_pct,
|
|
131
|
+
cost_ratio=summary.cost_ratio,
|
|
132
|
+
user_caused_breaks=summary.user_caused_breaks,
|
|
133
|
+
)
|
|
134
|
+
)
|
|
135
|
+
return tuple(rows)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def run_scenarios() -> tuple[Scenario, ...]:
|
|
139
|
+
"""Replay the four scenarios. Prices come from the simulator."""
|
|
140
|
+
return (
|
|
141
|
+
Scenario(
|
|
142
|
+
slug="clock",
|
|
143
|
+
title="A clock at the top of the instructions",
|
|
144
|
+
story=(
|
|
145
|
+
"The system text is the same every turn except the time. "
|
|
146
|
+
"Observe and safe send that changing line first, so nothing is read from cache "
|
|
147
|
+
"and the guard blames the app. "
|
|
148
|
+
"Optimize takes the time out of the instructions. "
|
|
149
|
+
"On the next turn it writes the same time again onto the message it already sent, "
|
|
150
|
+
"and puts the new time only on the new turn. "
|
|
151
|
+
"The guard records no app-caused break. "
|
|
152
|
+
"The input cost falls because the stable instructions are read from cache. "
|
|
153
|
+
"The clock is a few tokens, so once those instructions are stable the read share barely moves."
|
|
154
|
+
),
|
|
155
|
+
rows=_rows(clock_in_system()),
|
|
156
|
+
),
|
|
157
|
+
Scenario(
|
|
158
|
+
slug="tools",
|
|
159
|
+
title="The same tools, in a new order",
|
|
160
|
+
story=(
|
|
161
|
+
"The second call sends the same three tools shuffled. "
|
|
162
|
+
"Safe puts them back in the first-seen order before the simulator prices the call."
|
|
163
|
+
),
|
|
164
|
+
rows=_rows(tools_shuffled()),
|
|
165
|
+
),
|
|
166
|
+
Scenario(
|
|
167
|
+
slug="short",
|
|
168
|
+
title="Too short to cache",
|
|
169
|
+
story=(
|
|
170
|
+
"The prompt is one short question. "
|
|
171
|
+
"A miss here is the provider minimum, and it is not counted as the application's fault."
|
|
172
|
+
),
|
|
173
|
+
rows=_rows(too_short_to_cache()),
|
|
174
|
+
),
|
|
175
|
+
Scenario(
|
|
176
|
+
slug="rewrite",
|
|
177
|
+
title="An earlier message was edited",
|
|
178
|
+
story=(
|
|
179
|
+
"The first user message changes on the next call. "
|
|
180
|
+
"CtxCache names that break. It does not quietly rewrite history to hide it."
|
|
181
|
+
),
|
|
182
|
+
rows=_rows(history_rewritten()),
|
|
183
|
+
),
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def render_html(scenarios: tuple[Scenario, ...]) -> str:
|
|
188
|
+
"""A single page of the measured rows. No network, no invented numbers."""
|
|
189
|
+
cards: list[str] = []
|
|
190
|
+
for scenario in scenarios:
|
|
191
|
+
body = []
|
|
192
|
+
for row in scenario.rows:
|
|
193
|
+
body.append(
|
|
194
|
+
"<tr>"
|
|
195
|
+
f"<td>{html.escape(row.mode)}</td>"
|
|
196
|
+
f"<td>{row.read_pct:.1f}%</td>"
|
|
197
|
+
f"<td>{row.cost_ratio:.2f}×</td>"
|
|
198
|
+
f"<td>{row.user_caused_breaks}</td>"
|
|
199
|
+
"</tr>"
|
|
200
|
+
)
|
|
201
|
+
cards.append(
|
|
202
|
+
"<section>"
|
|
203
|
+
f"<h2>{html.escape(scenario.title)}</h2>"
|
|
204
|
+
f"<p>{html.escape(scenario.story)}</p>"
|
|
205
|
+
"<table><thead><tr><th>Mode</th><th>Read share</th>"
|
|
206
|
+
"<th>Input cost vs no cache</th><th>Breaks blamed on the app</th></tr></thead>"
|
|
207
|
+
f"<tbody>{''.join(body)}</tbody></table>"
|
|
208
|
+
"</section>"
|
|
209
|
+
)
|
|
210
|
+
return f"""<!DOCTYPE html>
|
|
211
|
+
<html lang="en">
|
|
212
|
+
<head>
|
|
213
|
+
<meta charset="utf-8">
|
|
214
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
215
|
+
<title>CtxCache scenarios</title>
|
|
216
|
+
<style>
|
|
217
|
+
body {{ margin: 0; background: #f7f4ee; color: #1c1917;
|
|
218
|
+
font-family: Palatino, Georgia, serif; font-size: 18px; line-height: 1.5; }}
|
|
219
|
+
main {{ max-width: 760px; margin: 0 auto; padding: 40px 20px 72px; }}
|
|
220
|
+
h1 {{ font-weight: 500; font-size: 36px; letter-spacing: -0.02em; margin: 0 0 8px; }}
|
|
221
|
+
h2 {{ font-weight: 500; font-size: 24px; margin: 36px 0 8px; }}
|
|
222
|
+
.kicker {{ font-family: "Avenir Next", "Segoe UI", sans-serif; font-size: 12px;
|
|
223
|
+
letter-spacing: 0.12em; text-transform: uppercase; color: #9a3412; }}
|
|
224
|
+
.note {{ background: #f8f1dc; border-left: 3px solid #854d0e; padding: 12px 14px; }}
|
|
225
|
+
table {{ width: 100%; border-collapse: collapse; font-size: 16px; }}
|
|
226
|
+
th, td {{ text-align: left; padding: 8px 8px 8px 0; border-bottom: 1px solid #e4ddd2; }}
|
|
227
|
+
th {{ font-family: "Avenir Next", "Segoe UI", sans-serif; font-size: 12px;
|
|
228
|
+
letter-spacing: 0.06em; text-transform: uppercase; color: #57534e; }}
|
|
229
|
+
</style>
|
|
230
|
+
</head>
|
|
231
|
+
<body>
|
|
232
|
+
<main>
|
|
233
|
+
<p class="kicker">CtxCache · four scenarios · simulator</p>
|
|
234
|
+
<h1>The same library, four different outcomes</h1>
|
|
235
|
+
<p class="note">These prices are the offline simulator for Gemini 2.5 Flash.
|
|
236
|
+
They are not a provider bill. Regenerate this page with
|
|
237
|
+
<code>ctxcache scenarios --html ctxcache-scenarios.html</code>.</p>
|
|
238
|
+
{"".join(cards)}
|
|
239
|
+
</main>
|
|
240
|
+
</body>
|
|
241
|
+
</html>
|
|
242
|
+
"""
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def write_html(path: str) -> tuple[Scenario, ...]:
|
|
246
|
+
scenarios = run_scenarios()
|
|
247
|
+
from pathlib import Path
|
|
248
|
+
|
|
249
|
+
Path(path).write_text(render_html(scenarios), encoding="utf-8")
|
|
250
|
+
return scenarios
|
ctxcache/segments.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""Five stability classes and request segmentation (BUILD_HANDBOOK §2.4)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from enum import Enum
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class StabilityClass(str, Enum):
|
|
11
|
+
STATIC = "STATIC"
|
|
12
|
+
SESSION = "SESSION"
|
|
13
|
+
APPEND = "APPEND"
|
|
14
|
+
VOLATILE = "VOLATILE"
|
|
15
|
+
TURN = "TURN"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class Segment:
|
|
20
|
+
"""A classified section of the prompt context."""
|
|
21
|
+
|
|
22
|
+
stability: StabilityClass
|
|
23
|
+
kind: str # "tools", "system", "message", "volatile"
|
|
24
|
+
index: int
|
|
25
|
+
data: Any
|
|
26
|
+
fingerprint: str = ""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def classify_message(
|
|
30
|
+
msg_index: int,
|
|
31
|
+
total_messages: int,
|
|
32
|
+
role: str,
|
|
33
|
+
content: Any,
|
|
34
|
+
) -> StabilityClass:
|
|
35
|
+
"""Classify a message into its stability class.
|
|
36
|
+
|
|
37
|
+
The last user or tool message is TURN. Prior messages are APPEND.
|
|
38
|
+
"""
|
|
39
|
+
if msg_index == total_messages - 1:
|
|
40
|
+
return StabilityClass.TURN
|
|
41
|
+
return StabilityClass.APPEND
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _part_text(part: Any) -> str:
|
|
45
|
+
if isinstance(part, str):
|
|
46
|
+
return part
|
|
47
|
+
if isinstance(part, dict):
|
|
48
|
+
if "text" in part:
|
|
49
|
+
return str(part.get("text") or "")
|
|
50
|
+
return str(part)
|
|
51
|
+
text = getattr(part, "text", None)
|
|
52
|
+
if isinstance(text, str):
|
|
53
|
+
return text
|
|
54
|
+
return str(part)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def contents_as_messages(contents: Any) -> list[dict[str, Any]]:
|
|
58
|
+
"""Turn Gemini ``contents`` into messages for the guard.
|
|
59
|
+
|
|
60
|
+
The provider still receives the original ``contents``. This view is only
|
|
61
|
+
used to count tokens and detect a changed prompt.
|
|
62
|
+
"""
|
|
63
|
+
if contents is None:
|
|
64
|
+
return []
|
|
65
|
+
if isinstance(contents, str):
|
|
66
|
+
return [{"role": "user", "content": contents}]
|
|
67
|
+
if not isinstance(contents, list):
|
|
68
|
+
return [{"role": "user", "content": _part_text(contents)}]
|
|
69
|
+
|
|
70
|
+
messages: list[dict[str, Any]] = []
|
|
71
|
+
for item in contents:
|
|
72
|
+
if isinstance(item, str):
|
|
73
|
+
messages.append({"role": "user", "content": item})
|
|
74
|
+
continue
|
|
75
|
+
if isinstance(item, dict):
|
|
76
|
+
role = str(item.get("role", "user"))
|
|
77
|
+
if "parts" in item:
|
|
78
|
+
parts = item.get("parts")
|
|
79
|
+
text = (
|
|
80
|
+
"\n".join(_part_text(part) for part in parts) if isinstance(parts, list) else ""
|
|
81
|
+
)
|
|
82
|
+
messages.append({"role": role, "content": text})
|
|
83
|
+
elif "content" in item:
|
|
84
|
+
messages.append({"role": role, "content": item.get("content")})
|
|
85
|
+
else:
|
|
86
|
+
messages.append({"role": role, "content": str(item)})
|
|
87
|
+
continue
|
|
88
|
+
role = str(getattr(item, "role", "user"))
|
|
89
|
+
parts = getattr(item, "parts", None)
|
|
90
|
+
if isinstance(parts, list):
|
|
91
|
+
messages.append(
|
|
92
|
+
{"role": role, "content": "\n".join(_part_text(part) for part in parts)}
|
|
93
|
+
)
|
|
94
|
+
else:
|
|
95
|
+
messages.append({"role": role, "content": _part_text(item)})
|
|
96
|
+
return messages
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def segment_request(
|
|
100
|
+
system: Any = None,
|
|
101
|
+
tools: list[dict[str, Any]] | None = None,
|
|
102
|
+
messages: list[dict[str, Any]] | None = None,
|
|
103
|
+
volatile_notes: list[str] | None = None,
|
|
104
|
+
) -> list[Segment]:
|
|
105
|
+
"""Segment a model request into stability classes in canonical provider order:
|
|
106
|
+
|
|
107
|
+
tools (STATIC) -> system (STATIC/SESSION) -> messages (APPEND -> TURN) -> volatile tail.
|
|
108
|
+
"""
|
|
109
|
+
segments: list[Segment] = []
|
|
110
|
+
|
|
111
|
+
# 1. Tools are STATIC
|
|
112
|
+
if tools:
|
|
113
|
+
for idx, tool in enumerate(tools):
|
|
114
|
+
segments.append(
|
|
115
|
+
Segment(
|
|
116
|
+
stability=StabilityClass.STATIC,
|
|
117
|
+
kind="tools",
|
|
118
|
+
index=idx,
|
|
119
|
+
data=tool,
|
|
120
|
+
)
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
# 2. Top-level system prompt is STATIC
|
|
124
|
+
if system is not None:
|
|
125
|
+
segments.append(
|
|
126
|
+
Segment(
|
|
127
|
+
stability=StabilityClass.STATIC,
|
|
128
|
+
kind="system",
|
|
129
|
+
index=0,
|
|
130
|
+
data=system,
|
|
131
|
+
)
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
# 3. Conversation messages (APPEND and final TURN)
|
|
135
|
+
if messages:
|
|
136
|
+
n_msgs = len(messages)
|
|
137
|
+
for idx, msg in enumerate(messages):
|
|
138
|
+
role = str(msg.get("role", "user"))
|
|
139
|
+
content = msg.get("content", "")
|
|
140
|
+
stability = classify_message(idx, n_msgs, role, content)
|
|
141
|
+
segments.append(
|
|
142
|
+
Segment(
|
|
143
|
+
stability=stability,
|
|
144
|
+
kind="message",
|
|
145
|
+
index=idx,
|
|
146
|
+
data=msg,
|
|
147
|
+
)
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
# 4. Volatile tail notes
|
|
151
|
+
if volatile_notes:
|
|
152
|
+
for idx, note in enumerate(volatile_notes):
|
|
153
|
+
segments.append(
|
|
154
|
+
Segment(
|
|
155
|
+
stability=StabilityClass.VOLATILE,
|
|
156
|
+
kind="volatile",
|
|
157
|
+
index=idx,
|
|
158
|
+
data=note,
|
|
159
|
+
)
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
return segments
|
ctxcache/sim/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Simulator package for offline token and prompt cache estimation."""
|
|
2
|
+
|
|
3
|
+
from ctxcache.sim.cache_sim import CacheSimulator, SimulatedCallResult, compute_calibration_mae
|
|
4
|
+
from ctxcache.sim.tokens import count_message_tokens, count_text_tokens, count_tool_tokens
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"CacheSimulator",
|
|
8
|
+
"SimulatedCallResult",
|
|
9
|
+
"compute_calibration_mae",
|
|
10
|
+
"count_text_tokens",
|
|
11
|
+
"count_message_tokens",
|
|
12
|
+
"count_tool_tokens",
|
|
13
|
+
]
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""Cache simulator modeling provider prompt caching rules and calibration."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from ctxcache.cost import load_providers_toml
|
|
10
|
+
from ctxcache.sim.tokens import count_message_tokens, count_text_tokens, count_tool_tokens
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class SimulatedCallResult:
|
|
15
|
+
call_index: int
|
|
16
|
+
predicted_read: int
|
|
17
|
+
predicted_write: int
|
|
18
|
+
predicted_uncached: int
|
|
19
|
+
predicted_read_share: float
|
|
20
|
+
total_input: int
|
|
21
|
+
cause: str | None = None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class CacheSimulator:
|
|
25
|
+
"""Simulates provider prompt cache behavior from recorded traces."""
|
|
26
|
+
|
|
27
|
+
def __init__(self, provider: str = "gemini", model: str = "gemini-2.5-flash"):
|
|
28
|
+
self.provider = provider
|
|
29
|
+
self.model = model
|
|
30
|
+
providers_data = load_providers_toml()
|
|
31
|
+
p_info = providers_data.get("providers", {}).get(provider, {})
|
|
32
|
+
m_info = p_info.get("models", {}).get(model, {})
|
|
33
|
+
|
|
34
|
+
self.min_prefix = int(
|
|
35
|
+
m_info.get("min_prefix_tokens", p_info.get("min_prefix_tokens", 2048))
|
|
36
|
+
)
|
|
37
|
+
self.ttl_seconds = float(p_info.get("default_ttl_seconds", 3600.0))
|
|
38
|
+
|
|
39
|
+
# Session cache state
|
|
40
|
+
self.cached_prefix_tokens: list[int] = []
|
|
41
|
+
self.cached_prefix_hashes: list[str] = []
|
|
42
|
+
self.last_call_ts: float | None = None
|
|
43
|
+
|
|
44
|
+
def reset(self) -> None:
|
|
45
|
+
self.cached_prefix_tokens.clear()
|
|
46
|
+
self.cached_prefix_hashes.clear()
|
|
47
|
+
self.last_call_ts = None
|
|
48
|
+
|
|
49
|
+
def simulate_call(
|
|
50
|
+
self,
|
|
51
|
+
call_index: int,
|
|
52
|
+
messages: list[dict[str, Any]],
|
|
53
|
+
tools: list[dict[str, Any]] | None = None,
|
|
54
|
+
system: str | None = None,
|
|
55
|
+
ts: float = 0.0,
|
|
56
|
+
) -> SimulatedCallResult:
|
|
57
|
+
"""Simulate a single call against provider caching rules."""
|
|
58
|
+
# Check TTL
|
|
59
|
+
ttl_expired = False
|
|
60
|
+
if self.last_call_ts is not None and (ts - self.last_call_ts) > self.ttl_seconds:
|
|
61
|
+
ttl_expired = True
|
|
62
|
+
self.cached_prefix_tokens.clear()
|
|
63
|
+
self.cached_prefix_hashes.clear()
|
|
64
|
+
|
|
65
|
+
# Build token blocks and hashes in provider prefix order: tools -> system -> messages
|
|
66
|
+
token_blocks: list[int] = []
|
|
67
|
+
hash_blocks: list[str] = []
|
|
68
|
+
|
|
69
|
+
if tools:
|
|
70
|
+
for t in tools:
|
|
71
|
+
tok = count_tool_tokens(t, self.model)
|
|
72
|
+
token_blocks.append(tok)
|
|
73
|
+
hash_blocks.append(f"tool:{t.get('name', '')}:{json.dumps(t, sort_keys=True)}")
|
|
74
|
+
|
|
75
|
+
if system:
|
|
76
|
+
tok = count_text_tokens(system, self.model)
|
|
77
|
+
token_blocks.append(tok)
|
|
78
|
+
hash_blocks.append(f"system:{system}")
|
|
79
|
+
|
|
80
|
+
for m in messages:
|
|
81
|
+
tok = count_message_tokens(m, self.model)
|
|
82
|
+
token_blocks.append(tok)
|
|
83
|
+
content_str = str(m.get("content", ""))
|
|
84
|
+
hash_blocks.append(f"msg:{m.get('role', '')}:{content_str}")
|
|
85
|
+
|
|
86
|
+
total_input = sum(token_blocks)
|
|
87
|
+
|
|
88
|
+
# Match prefix against previous cached prefix
|
|
89
|
+
matching_tokens = 0
|
|
90
|
+
matching_blocks = 0
|
|
91
|
+
for i in range(min(len(hash_blocks), len(self.cached_prefix_hashes))):
|
|
92
|
+
if hash_blocks[i] == self.cached_prefix_hashes[i]:
|
|
93
|
+
matching_tokens += token_blocks[i]
|
|
94
|
+
matching_blocks += 1
|
|
95
|
+
else:
|
|
96
|
+
break
|
|
97
|
+
|
|
98
|
+
cause = None
|
|
99
|
+
predicted_read = 0
|
|
100
|
+
predicted_write = 0
|
|
101
|
+
predicted_uncached = total_input
|
|
102
|
+
|
|
103
|
+
# Cache reading logic
|
|
104
|
+
if matching_tokens >= self.min_prefix and not ttl_expired:
|
|
105
|
+
predicted_read = matching_tokens
|
|
106
|
+
else:
|
|
107
|
+
if total_input < self.min_prefix:
|
|
108
|
+
cause = "below_minimum"
|
|
109
|
+
elif ttl_expired:
|
|
110
|
+
cause = "ttl_expired"
|
|
111
|
+
elif matching_tokens < self.min_prefix and self.cached_prefix_hashes:
|
|
112
|
+
cause = "volatile_in_prefix"
|
|
113
|
+
|
|
114
|
+
# Update cached prefix state and token accounting (INV-06: read + write + uncached == total_input)
|
|
115
|
+
if total_input >= self.min_prefix:
|
|
116
|
+
predicted_write = total_input - predicted_read
|
|
117
|
+
predicted_uncached = 0
|
|
118
|
+
self.cached_prefix_tokens = list(token_blocks)
|
|
119
|
+
self.cached_prefix_hashes = list(hash_blocks)
|
|
120
|
+
else:
|
|
121
|
+
predicted_write = 0
|
|
122
|
+
predicted_uncached = total_input
|
|
123
|
+
self.cached_prefix_tokens = []
|
|
124
|
+
self.cached_prefix_hashes = []
|
|
125
|
+
|
|
126
|
+
self.last_call_ts = ts
|
|
127
|
+
read_share = float(predicted_read) / total_input if total_input > 0 else 0.0
|
|
128
|
+
|
|
129
|
+
return SimulatedCallResult(
|
|
130
|
+
call_index=call_index,
|
|
131
|
+
predicted_read=predicted_read,
|
|
132
|
+
predicted_write=predicted_write,
|
|
133
|
+
predicted_uncached=predicted_uncached,
|
|
134
|
+
predicted_read_share=read_share,
|
|
135
|
+
total_input=total_input,
|
|
136
|
+
cause=cause,
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def compute_calibration_mae(
|
|
141
|
+
actual_read_shares: list[float],
|
|
142
|
+
predicted_read_shares: list[float],
|
|
143
|
+
) -> float:
|
|
144
|
+
"""Compute Mean Absolute Error (MAE) in read share percentage points.
|
|
145
|
+
|
|
146
|
+
Returns value in points (0 to 100).
|
|
147
|
+
"""
|
|
148
|
+
if not actual_read_shares or not predicted_read_shares:
|
|
149
|
+
return 0.0
|
|
150
|
+
n = min(len(actual_read_shares), len(predicted_read_shares))
|
|
151
|
+
errors = [abs(actual_read_shares[i] - predicted_read_shares[i]) * 100.0 for i in range(n)]
|
|
152
|
+
return sum(errors) / n
|
ctxcache/sim/tokens.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Offline token counting and estimation helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib
|
|
6
|
+
import json
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
# Optional tiktoken support
|
|
10
|
+
_tiktoken_encoding = None
|
|
11
|
+
try:
|
|
12
|
+
_tiktoken_mod = importlib.import_module("tiktoken")
|
|
13
|
+
_tiktoken_encoding = _tiktoken_mod.get_encoding("cl100k_base")
|
|
14
|
+
except Exception:
|
|
15
|
+
pass
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def count_text_tokens(text: str, model: str = "gemini-2.5-flash") -> int:
|
|
19
|
+
"""Offline token estimation for text.
|
|
20
|
+
|
|
21
|
+
Uses tiktoken if available for GPT models, or calibrated character-per-token ratio
|
|
22
|
+
(approx 3.85 chars/token for code & technical text) with minimum 1 token for non-empty text.
|
|
23
|
+
"""
|
|
24
|
+
if not text:
|
|
25
|
+
return 0
|
|
26
|
+
|
|
27
|
+
if _tiktoken_encoding is not None and ("gpt" in model.lower() or "openai" in model.lower()):
|
|
28
|
+
return len(_tiktoken_encoding.encode(text))
|
|
29
|
+
|
|
30
|
+
# Calibrated character-per-token estimate across code and prose
|
|
31
|
+
# 3.85 characters/token matches Gemini tokenization benchmarks closely
|
|
32
|
+
char_len = len(text)
|
|
33
|
+
estimated = max(1, int(round(char_len / 3.85)))
|
|
34
|
+
return estimated
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def count_message_tokens(message: dict[str, Any], model: str = "gemini-2.5-flash") -> int:
|
|
38
|
+
"""Estimate token count for a single message including role metadata framing."""
|
|
39
|
+
tokens = 4 # Per-message overhead (role, formatting tokens)
|
|
40
|
+
content = message.get("content", "")
|
|
41
|
+
if isinstance(content, str):
|
|
42
|
+
tokens += count_text_tokens(content, model=model)
|
|
43
|
+
elif isinstance(content, list):
|
|
44
|
+
for block in content:
|
|
45
|
+
if isinstance(block, str):
|
|
46
|
+
tokens += count_text_tokens(block, model=model)
|
|
47
|
+
elif isinstance(block, dict):
|
|
48
|
+
text = block.get("text") or json.dumps(block)
|
|
49
|
+
tokens += count_text_tokens(text, model=model)
|
|
50
|
+
return tokens
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def count_tool_tokens(tool: dict[str, Any], model: str = "gemini-2.5-flash") -> int:
|
|
54
|
+
"""Estimate tokens for a tool schema definition."""
|
|
55
|
+
serialized = json.dumps(tool, sort_keys=True)
|
|
56
|
+
return count_text_tokens(serialized, model=model) + 8 # Schema framing overhead
|