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/testing.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
"""FakeProvider and test mock harness for CtxCache prompt caching (BUILD_HANDBOOK §5.9, §11)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from ctxcache.sim.cache_sim import CacheSimulator
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class TextBlock:
|
|
14
|
+
text: str
|
|
15
|
+
type: str = "text"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class AnthropicUsage:
|
|
20
|
+
input_tokens: int
|
|
21
|
+
output_tokens: int
|
|
22
|
+
cache_read_input_tokens: int = 0
|
|
23
|
+
cache_creation_input_tokens: int = 0
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class AnthropicResponse:
|
|
28
|
+
id: str
|
|
29
|
+
content: list[TextBlock]
|
|
30
|
+
usage: AnthropicUsage
|
|
31
|
+
type: str = "message"
|
|
32
|
+
role: str = "assistant"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class OpenAIMessage:
|
|
37
|
+
content: str
|
|
38
|
+
role: str = "assistant"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass
|
|
42
|
+
class OpenAIChoice:
|
|
43
|
+
message: OpenAIMessage
|
|
44
|
+
index: int = 0
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass
|
|
48
|
+
class OpenAIUsage:
|
|
49
|
+
prompt_tokens: int
|
|
50
|
+
completion_tokens: int
|
|
51
|
+
total_tokens: int
|
|
52
|
+
prompt_tokens_details: dict[str, int]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass
|
|
56
|
+
class OpenAIResponse:
|
|
57
|
+
id: str
|
|
58
|
+
choices: list[OpenAIChoice]
|
|
59
|
+
usage: OpenAIUsage
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass
|
|
63
|
+
class GeminiPart:
|
|
64
|
+
text: str
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass
|
|
68
|
+
class GeminiContent:
|
|
69
|
+
parts: list[GeminiPart]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass
|
|
73
|
+
class GeminiCandidate:
|
|
74
|
+
content: GeminiContent
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@dataclass
|
|
78
|
+
class GeminiUsageMetadata:
|
|
79
|
+
prompt_token_count: int
|
|
80
|
+
candidates_token_count: int
|
|
81
|
+
cached_content_token_count: int
|
|
82
|
+
total_token_count: int
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass
|
|
86
|
+
class GeminiResponse:
|
|
87
|
+
text: str
|
|
88
|
+
candidates: list[GeminiCandidate]
|
|
89
|
+
usage_metadata: GeminiUsageMetadata
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class FakeMessagesEndpoint:
|
|
93
|
+
"""Mock for Anthropic client.messages endpoint."""
|
|
94
|
+
|
|
95
|
+
def __init__(self, provider_parent: FakeProvider):
|
|
96
|
+
self._parent = provider_parent
|
|
97
|
+
|
|
98
|
+
def create(self, **kwargs: Any) -> AnthropicResponse:
|
|
99
|
+
messages = kwargs.get("messages", [])
|
|
100
|
+
system = kwargs.get("system", "")
|
|
101
|
+
tools = kwargs.get("tools")
|
|
102
|
+
ts = kwargs.get("ts", time.time())
|
|
103
|
+
|
|
104
|
+
self._parent.call_count += 1
|
|
105
|
+
sim_res = self._parent.simulator.simulate_call(
|
|
106
|
+
call_index=self._parent.call_count,
|
|
107
|
+
messages=messages,
|
|
108
|
+
tools=tools,
|
|
109
|
+
system=str(system) if system else None,
|
|
110
|
+
ts=ts,
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
out_tokens = 50
|
|
114
|
+
usage = AnthropicUsage(
|
|
115
|
+
input_tokens=sim_res.total_input,
|
|
116
|
+
output_tokens=out_tokens,
|
|
117
|
+
cache_read_input_tokens=sim_res.predicted_read,
|
|
118
|
+
cache_creation_input_tokens=sim_res.predicted_write,
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
return AnthropicResponse(
|
|
122
|
+
id=f"fake-anthropic-msg-{self._parent.call_count}",
|
|
123
|
+
content=[TextBlock(text="Fake simulated response from Anthropic model.")],
|
|
124
|
+
usage=usage,
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class FakeCompletionsEndpoint:
|
|
129
|
+
"""Mock for OpenAI client.chat.completions endpoint."""
|
|
130
|
+
|
|
131
|
+
def __init__(self, provider_parent: FakeProvider):
|
|
132
|
+
self._parent = provider_parent
|
|
133
|
+
|
|
134
|
+
def create(self, **kwargs: Any) -> OpenAIResponse:
|
|
135
|
+
messages = kwargs.get("messages", [])
|
|
136
|
+
tools = kwargs.get("tools")
|
|
137
|
+
ts = kwargs.get("ts", time.time())
|
|
138
|
+
|
|
139
|
+
self._parent.call_count += 1
|
|
140
|
+
sim_res = self._parent.simulator.simulate_call(
|
|
141
|
+
call_index=self._parent.call_count,
|
|
142
|
+
messages=messages,
|
|
143
|
+
tools=tools,
|
|
144
|
+
system=None,
|
|
145
|
+
ts=ts,
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
out_tokens = 45
|
|
149
|
+
usage = OpenAIUsage(
|
|
150
|
+
prompt_tokens=sim_res.total_input,
|
|
151
|
+
completion_tokens=out_tokens,
|
|
152
|
+
total_tokens=sim_res.total_input + out_tokens,
|
|
153
|
+
prompt_tokens_details={"cached_tokens": sim_res.predicted_read},
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
return OpenAIResponse(
|
|
157
|
+
id=f"fake-openai-chatcmpl-{self._parent.call_count}",
|
|
158
|
+
choices=[
|
|
159
|
+
OpenAIChoice(
|
|
160
|
+
message=OpenAIMessage(content="Fake simulated response from OpenAI model.")
|
|
161
|
+
)
|
|
162
|
+
],
|
|
163
|
+
usage=usage,
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
class FakeChatEndpoint:
|
|
168
|
+
def __init__(self, provider_parent: FakeProvider):
|
|
169
|
+
self.completions = FakeCompletionsEndpoint(provider_parent)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class FakeModelsEndpoint:
|
|
173
|
+
"""Mock for Google GenAI client.models endpoint."""
|
|
174
|
+
|
|
175
|
+
def __init__(self, provider_parent: FakeProvider):
|
|
176
|
+
self._parent = provider_parent
|
|
177
|
+
|
|
178
|
+
def generate_content(self, **kwargs: Any) -> GeminiResponse:
|
|
179
|
+
contents = kwargs.get("contents", [])
|
|
180
|
+
config = kwargs.get("config", {})
|
|
181
|
+
system_instruction = config.get("system_instruction", "")
|
|
182
|
+
tools = config.get("tools")
|
|
183
|
+
ts = kwargs.get("ts", time.time())
|
|
184
|
+
|
|
185
|
+
# Standardize contents into message list
|
|
186
|
+
messages: list[dict[str, Any]] = []
|
|
187
|
+
if isinstance(contents, list):
|
|
188
|
+
for c in contents:
|
|
189
|
+
if isinstance(c, dict):
|
|
190
|
+
messages.append(c)
|
|
191
|
+
else:
|
|
192
|
+
messages.append({"role": "user", "content": str(c)})
|
|
193
|
+
else:
|
|
194
|
+
messages.append({"role": "user", "content": str(contents)})
|
|
195
|
+
|
|
196
|
+
self._parent.call_count += 1
|
|
197
|
+
sim_res = self._parent.simulator.simulate_call(
|
|
198
|
+
call_index=self._parent.call_count,
|
|
199
|
+
messages=messages,
|
|
200
|
+
tools=tools,
|
|
201
|
+
system=str(system_instruction) if system_instruction else None,
|
|
202
|
+
ts=ts,
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
out_tokens = 60
|
|
206
|
+
usage = GeminiUsageMetadata(
|
|
207
|
+
prompt_token_count=sim_res.total_input,
|
|
208
|
+
candidates_token_count=out_tokens,
|
|
209
|
+
cached_content_token_count=sim_res.predicted_read,
|
|
210
|
+
total_token_count=sim_res.total_input + out_tokens,
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
resp_text = "Fake simulated response from Gemini model."
|
|
214
|
+
return GeminiResponse(
|
|
215
|
+
text=resp_text,
|
|
216
|
+
candidates=[GeminiCandidate(content=GeminiContent(parts=[GeminiPart(text=resp_text)]))],
|
|
217
|
+
usage_metadata=usage,
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
class FakeProvider:
|
|
222
|
+
"""Mock provider executing calls through the cache simulator without network requests (BUILD_HANDBOOK §5.9).
|
|
223
|
+
|
|
224
|
+
Supports:
|
|
225
|
+
- Anthropic: client.messages.create()
|
|
226
|
+
- OpenAI: client.chat.completions.create()
|
|
227
|
+
- Google Gemini: client.models.generate_content()
|
|
228
|
+
"""
|
|
229
|
+
|
|
230
|
+
def __init__(self, provider: str = "gemini", model: str | None = None):
|
|
231
|
+
self.provider = provider
|
|
232
|
+
if model is None:
|
|
233
|
+
if provider == "gemini":
|
|
234
|
+
model = "gemini-2.5-flash"
|
|
235
|
+
elif provider == "openai":
|
|
236
|
+
model = "gpt-4o"
|
|
237
|
+
else:
|
|
238
|
+
model = "claude-3-5-sonnet"
|
|
239
|
+
self.model = model
|
|
240
|
+
self.simulator = CacheSimulator(provider=provider, model=model)
|
|
241
|
+
self.call_count = 0
|
|
242
|
+
|
|
243
|
+
# Endpoints
|
|
244
|
+
self.messages = FakeMessagesEndpoint(self)
|
|
245
|
+
self.chat = FakeChatEndpoint(self)
|
|
246
|
+
self.models = FakeModelsEndpoint(self)
|
|
247
|
+
|
|
248
|
+
def reset(self) -> None:
|
|
249
|
+
self.call_count = 0
|
|
250
|
+
self.simulator.reset()
|
ctxcache/tools.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""CtxCache built-in tools for context offloading (BUILD_HANDBOOK §5.5)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from ctxcache.offload import get_blob_store
|
|
8
|
+
|
|
9
|
+
READ_OFFLOADED_TOOL_DEF: dict[str, Any] = {
|
|
10
|
+
"type": "function",
|
|
11
|
+
"function": {
|
|
12
|
+
"name": "read_offloaded",
|
|
13
|
+
"description": (
|
|
14
|
+
"Read characters from an offloaded large tool result by handle. "
|
|
15
|
+
"Use this when you need detailed sections of a previously offloaded tool output."
|
|
16
|
+
),
|
|
17
|
+
"parameters": {
|
|
18
|
+
"type": "object",
|
|
19
|
+
"properties": {
|
|
20
|
+
"handle": {
|
|
21
|
+
"type": "string",
|
|
22
|
+
"description": "The unique SHA-256 blob handle of the offloaded result.",
|
|
23
|
+
},
|
|
24
|
+
"start": {
|
|
25
|
+
"type": "integer",
|
|
26
|
+
"description": "Start character offset (0-indexed, default 0).",
|
|
27
|
+
"default": 0,
|
|
28
|
+
},
|
|
29
|
+
"end": {
|
|
30
|
+
"type": "integer",
|
|
31
|
+
"description": "End character offset (optional; reads to end if omitted).",
|
|
32
|
+
},
|
|
33
|
+
},
|
|
34
|
+
"required": ["handle"],
|
|
35
|
+
},
|
|
36
|
+
},
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def read_offloaded(handle: str, start: int = 0, end: int | None = None) -> str:
|
|
41
|
+
"""Read a slice of offloaded content from the local blob store."""
|
|
42
|
+
store = get_blob_store()
|
|
43
|
+
content = store.get(handle)
|
|
44
|
+
if content is None:
|
|
45
|
+
return f"Error: Offloaded handle '{handle}' not found in local blob store."
|
|
46
|
+
|
|
47
|
+
if end is not None:
|
|
48
|
+
return content[start:end]
|
|
49
|
+
return content[start:]
|
ctxcache/trace.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Trace writer and ledger record structures."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class TraceRecorder:
|
|
12
|
+
"""Writes JSONL traces for CtxCache sessions."""
|
|
13
|
+
|
|
14
|
+
def __init__(self, trace_dir: str | Path | None = None):
|
|
15
|
+
if trace_dir is None:
|
|
16
|
+
env_trace_dir = os.environ.get("CTXCACHE_TRACE_DIR")
|
|
17
|
+
if env_trace_dir:
|
|
18
|
+
self.trace_dir = Path(env_trace_dir)
|
|
19
|
+
else:
|
|
20
|
+
ctxcache_dir = os.environ.get("CTXCACHE_HOME", os.path.expanduser("~/.ctxcache"))
|
|
21
|
+
self.trace_dir = Path(ctxcache_dir) / "traces"
|
|
22
|
+
else:
|
|
23
|
+
self.trace_dir = Path(trace_dir)
|
|
24
|
+
self.trace_dir.mkdir(parents=True, exist_ok=True)
|
|
25
|
+
|
|
26
|
+
def record_call(
|
|
27
|
+
self,
|
|
28
|
+
*,
|
|
29
|
+
session_id: str,
|
|
30
|
+
call_index: int,
|
|
31
|
+
ts_start: float,
|
|
32
|
+
ts_end: float,
|
|
33
|
+
ts_first_token: float | None = None,
|
|
34
|
+
provider: str,
|
|
35
|
+
api: str,
|
|
36
|
+
model: str,
|
|
37
|
+
mode: str,
|
|
38
|
+
params: dict[str, Any] | None = None,
|
|
39
|
+
fingerprints: dict[str, list[str]] | None = None,
|
|
40
|
+
usage: dict[str, Any] | None = None,
|
|
41
|
+
breaks: list[dict[str, Any]] | None = None,
|
|
42
|
+
changes: list[dict[str, Any]] | None = None,
|
|
43
|
+
body: dict[str, Any] | None = None,
|
|
44
|
+
record_body: bool = False,
|
|
45
|
+
) -> dict[str, Any]:
|
|
46
|
+
"""Record a single API call trace.
|
|
47
|
+
|
|
48
|
+
Enforces INV-09: request and response bodies are omitted unless record_body is True.
|
|
49
|
+
"""
|
|
50
|
+
trace_path = self.trace_dir / f"{session_id}.jsonl"
|
|
51
|
+
|
|
52
|
+
entry: dict[str, Any] = {
|
|
53
|
+
"v": 1,
|
|
54
|
+
"session": session_id,
|
|
55
|
+
"call": call_index,
|
|
56
|
+
"ts_start": ts_start,
|
|
57
|
+
"ts_first_token": ts_first_token,
|
|
58
|
+
"ts_end": ts_end,
|
|
59
|
+
"provider": provider,
|
|
60
|
+
"api": api,
|
|
61
|
+
"model": model,
|
|
62
|
+
"mode": mode,
|
|
63
|
+
"params": params or {},
|
|
64
|
+
"fingerprints": fingerprints or {"tools": [], "system": [], "messages": []},
|
|
65
|
+
"usage": usage
|
|
66
|
+
or {
|
|
67
|
+
"raw": {},
|
|
68
|
+
"read": 0,
|
|
69
|
+
"write": 0,
|
|
70
|
+
"uncached": 0,
|
|
71
|
+
"output": 0,
|
|
72
|
+
},
|
|
73
|
+
"breaks": breaks or [],
|
|
74
|
+
"changes": changes or [],
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
# INV-09: No prompt content in trace unless record_body=True
|
|
78
|
+
if record_body and body is not None:
|
|
79
|
+
entry["body"] = body
|
|
80
|
+
|
|
81
|
+
with open(trace_path, "a", encoding="utf-8") as f:
|
|
82
|
+
f.write(json.dumps(entry) + "\n")
|
|
83
|
+
|
|
84
|
+
return entry
|
|
85
|
+
|
|
86
|
+
def read_session(self, session_id: str) -> list[dict[str, Any]]:
|
|
87
|
+
"""Read all trace entries recorded for a session."""
|
|
88
|
+
trace_path = self.trace_dir / f"{session_id}.jsonl"
|
|
89
|
+
if not trace_path.exists():
|
|
90
|
+
return []
|
|
91
|
+
entries: list[dict[str, Any]] = []
|
|
92
|
+
with open(trace_path, encoding="utf-8") as f:
|
|
93
|
+
for line in f:
|
|
94
|
+
line = line.strip()
|
|
95
|
+
if line:
|
|
96
|
+
entries.append(json.loads(line))
|
|
97
|
+
return entries
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
_default_recorder: TraceRecorder | None = None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def get_trace_recorder(trace_dir: str | Path | None = None) -> TraceRecorder:
|
|
104
|
+
global _default_recorder
|
|
105
|
+
if trace_dir is not None:
|
|
106
|
+
return TraceRecorder(trace_dir)
|
|
107
|
+
if _default_recorder is None:
|
|
108
|
+
_default_recorder = TraceRecorder()
|
|
109
|
+
return _default_recorder
|