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,144 @@
|
|
|
1
|
+
"""LangGraph and LangChain middleware for CtxCache prompt caching (BUILD_HANDBOOK §6.1, M3)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import ctxcache
|
|
8
|
+
from ctxcache.guard import PrefixGuard
|
|
9
|
+
from ctxcache.layout import optimize_layout
|
|
10
|
+
from ctxcache.trace import TraceRecorder, get_trace_recorder
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class CtxCacheMiddleware:
|
|
14
|
+
"""LangGraph middleware / callback interceptor for prompt caching.
|
|
15
|
+
|
|
16
|
+
- Restores first-seen tool order across graph executions.
|
|
17
|
+
- Relocates volatile timestamps and session markers in optimize mode.
|
|
18
|
+
- Enforces append-only message history and detects prefix breaks.
|
|
19
|
+
- Adds provider cache_control breakpoints where appropriate.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
def __init__(
|
|
23
|
+
self,
|
|
24
|
+
mode: ctxcache.Mode = "safe",
|
|
25
|
+
session_id: str = "langgraph-session",
|
|
26
|
+
provider: str = "gemini",
|
|
27
|
+
recorder: TraceRecorder | None = None,
|
|
28
|
+
strict: bool = False,
|
|
29
|
+
):
|
|
30
|
+
self.mode = mode
|
|
31
|
+
self.session_id = session_id
|
|
32
|
+
self.provider = provider
|
|
33
|
+
self.recorder = recorder or get_trace_recorder()
|
|
34
|
+
self.strict = strict
|
|
35
|
+
self.guard = PrefixGuard(strict=strict)
|
|
36
|
+
self.first_seen_tools: list[str] = []
|
|
37
|
+
self._call_count = 0
|
|
38
|
+
|
|
39
|
+
def transform_messages(
|
|
40
|
+
self,
|
|
41
|
+
messages: list[Any],
|
|
42
|
+
tools: list[dict[str, Any]] | None = None,
|
|
43
|
+
system: str = "",
|
|
44
|
+
) -> tuple[str, list[Any], list[dict[str, Any]]]:
|
|
45
|
+
"""Process messages and system prompt before passing to model in LangGraph node."""
|
|
46
|
+
self._call_count += 1
|
|
47
|
+
changes: list[dict[str, Any]] = []
|
|
48
|
+
|
|
49
|
+
if self.mode == "observe":
|
|
50
|
+
return system, messages, []
|
|
51
|
+
|
|
52
|
+
# Restore tool ordering if seen before (safe / optimize mode)
|
|
53
|
+
clean_tools = list(tools) if tools else []
|
|
54
|
+
if clean_tools:
|
|
55
|
+
current_names = [
|
|
56
|
+
t.get("name") if isinstance(t, dict) else getattr(t, "name", None)
|
|
57
|
+
for t in clean_tools
|
|
58
|
+
]
|
|
59
|
+
valid_names = [n for n in current_names if n]
|
|
60
|
+
if not self.first_seen_tools and valid_names:
|
|
61
|
+
self.first_seen_tools = list(valid_names)
|
|
62
|
+
elif self.first_seen_tools and valid_names != self.first_seen_tools:
|
|
63
|
+
tool_map = {n: t for n, t in zip(valid_names, clean_tools, strict=False)}
|
|
64
|
+
reordered = [tool_map[n] for n in self.first_seen_tools if n in tool_map]
|
|
65
|
+
for t in clean_tools:
|
|
66
|
+
if t not in reordered:
|
|
67
|
+
reordered.append(t)
|
|
68
|
+
clean_tools = reordered
|
|
69
|
+
|
|
70
|
+
# Standardize message dicts
|
|
71
|
+
msg_dicts: list[dict[str, Any]] = []
|
|
72
|
+
for m in messages:
|
|
73
|
+
if isinstance(m, dict):
|
|
74
|
+
msg_dicts.append(dict(m))
|
|
75
|
+
elif hasattr(m, "content"):
|
|
76
|
+
role = "user"
|
|
77
|
+
type_name = getattr(m, "type", "")
|
|
78
|
+
if "human" in type_name or "user" in type_name:
|
|
79
|
+
role = "user"
|
|
80
|
+
elif "ai" in type_name or "assistant" in type_name:
|
|
81
|
+
role = "assistant"
|
|
82
|
+
elif "system" in type_name:
|
|
83
|
+
role = "system"
|
|
84
|
+
elif "tool" in type_name:
|
|
85
|
+
role = "tool"
|
|
86
|
+
msg_dicts.append({"role": role, "content": getattr(m, "content", "")})
|
|
87
|
+
else:
|
|
88
|
+
msg_dicts.append({"role": "user", "content": str(m)})
|
|
89
|
+
|
|
90
|
+
new_system = system
|
|
91
|
+
new_msgs = msg_dicts
|
|
92
|
+
|
|
93
|
+
if self.mode == "optimize":
|
|
94
|
+
new_system, new_msgs, opt_changes = optimize_layout(
|
|
95
|
+
system=system,
|
|
96
|
+
messages=msg_dicts,
|
|
97
|
+
tools=clean_tools,
|
|
98
|
+
)
|
|
99
|
+
changes.extend(opt_changes)
|
|
100
|
+
|
|
101
|
+
# Evaluate prefix guard
|
|
102
|
+
import time
|
|
103
|
+
|
|
104
|
+
self.guard.evaluate_call(
|
|
105
|
+
curr_params={"model": "default"},
|
|
106
|
+
curr_tools=clean_tools,
|
|
107
|
+
curr_system=new_system,
|
|
108
|
+
curr_messages=new_msgs,
|
|
109
|
+
total_tokens=sum(len(str(m.get("content", ""))) // 4 for m in new_msgs),
|
|
110
|
+
ts=time.time(),
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
return new_system, new_msgs, changes
|
|
114
|
+
|
|
115
|
+
def __call__(self, state: dict[str, Any]) -> dict[str, Any]:
|
|
116
|
+
"""Functional middleware invocation on LangGraph state dict."""
|
|
117
|
+
if self.mode == "observe":
|
|
118
|
+
return dict(state)
|
|
119
|
+
|
|
120
|
+
messages = state.get("messages", [])
|
|
121
|
+
tools = state.get("tools")
|
|
122
|
+
system = state.get("system", "")
|
|
123
|
+
|
|
124
|
+
opt_sys, opt_msgs, changes = self.transform_messages(
|
|
125
|
+
messages=messages, tools=tools, system=system
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
new_state = dict(state)
|
|
129
|
+
new_state["messages"] = opt_msgs
|
|
130
|
+
if opt_sys:
|
|
131
|
+
new_state["system"] = opt_sys
|
|
132
|
+
if changes:
|
|
133
|
+
new_state["_ctxcache_changes"] = changes
|
|
134
|
+
|
|
135
|
+
return new_state
|
|
136
|
+
|
|
137
|
+
# LangChain / LangGraph BaseCallbackHandler interface compatibility
|
|
138
|
+
def on_llm_start(self, serialized: dict[str, Any], prompts: list[str], **kwargs: Any) -> None:
|
|
139
|
+
"""Invoked when LLM starts running in LangChain."""
|
|
140
|
+
pass
|
|
141
|
+
|
|
142
|
+
def on_llm_end(self, response: Any, **kwargs: Any) -> None:
|
|
143
|
+
"""Invoked when LLM finishes running in LangChain."""
|
|
144
|
+
pass
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""OpenAI Agents SDK integration adapter for CtxCache prompt caching (BUILD_HANDBOOK §6.1, M3)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import ctxcache
|
|
8
|
+
from ctxcache.wrapper import WrappedClientProxy
|
|
9
|
+
|
|
10
|
+
_DEFAULT_AGENTS_CLIENT: Any = None
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def set_default_openai_client(client: Any) -> None:
|
|
14
|
+
"""Set the default client for the OpenAI Agents SDK."""
|
|
15
|
+
global _DEFAULT_AGENTS_CLIENT
|
|
16
|
+
if not isinstance(client, WrappedClientProxy):
|
|
17
|
+
_DEFAULT_AGENTS_CLIENT = ctxcache.wrap(client, mode="safe")
|
|
18
|
+
else:
|
|
19
|
+
_DEFAULT_AGENTS_CLIENT = client
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def get_default_openai_client() -> Any:
|
|
23
|
+
"""Retrieve the configured default client for OpenAI Agents SDK."""
|
|
24
|
+
return _DEFAULT_AGENTS_CLIENT
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def wrap_agents_client(
|
|
28
|
+
client: Any,
|
|
29
|
+
mode: ctxcache.Mode = "safe",
|
|
30
|
+
record: bool = False,
|
|
31
|
+
strict: bool = False,
|
|
32
|
+
recorder: ctxcache.TraceRecorder | None = None,
|
|
33
|
+
) -> Any:
|
|
34
|
+
"""Wrap an OpenAI or AsyncOpenAI client for the Agents SDK.
|
|
35
|
+
|
|
36
|
+
Usage:
|
|
37
|
+
from openai import OpenAI
|
|
38
|
+
from ctxcache.integrations.openai_agents import wrap_agents_client
|
|
39
|
+
|
|
40
|
+
wrapped = wrap_agents_client(OpenAI(), mode="safe")
|
|
41
|
+
"""
|
|
42
|
+
return ctxcache.wrap(client, mode=mode, record=record, strict=strict, recorder=recorder)
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Pydantic AI integration adapter for CtxCache prompt caching (BUILD_HANDBOOK §6.1, M3)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import ctxcache
|
|
8
|
+
from ctxcache.wrapper import WrappedClientProxy
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def wrap_pydantic_ai_client(
|
|
12
|
+
client: Any,
|
|
13
|
+
mode: ctxcache.Mode = "safe",
|
|
14
|
+
record: bool = False,
|
|
15
|
+
strict: bool = False,
|
|
16
|
+
recorder: ctxcache.TraceRecorder | None = None,
|
|
17
|
+
) -> Any:
|
|
18
|
+
"""Wrap an API client intended for Pydantic AI models.
|
|
19
|
+
|
|
20
|
+
Usage:
|
|
21
|
+
from pydantic_ai.models.anthropic import AnthropicModel
|
|
22
|
+
from ctxcache.integrations.pydantic_ai import wrap_pydantic_ai_client
|
|
23
|
+
|
|
24
|
+
wrapped = wrap_pydantic_ai_client(anthropic_client, mode="safe")
|
|
25
|
+
model = AnthropicModel("model-name", anthropic_client=wrapped)
|
|
26
|
+
"""
|
|
27
|
+
return ctxcache.wrap(client, mode=mode, record=record, strict=strict, recorder=recorder)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class CtxCachePydanticAIModel:
|
|
31
|
+
"""Proxy adapter wrapping a Pydantic AI model instance to enforce prompt cache stability."""
|
|
32
|
+
|
|
33
|
+
def __init__(self, model: Any, mode: ctxcache.Mode = "safe"):
|
|
34
|
+
self.underlying_model = model
|
|
35
|
+
self.mode = mode
|
|
36
|
+
# If model has client attribute, wrap it
|
|
37
|
+
for attr in ("client", "_client", "anthropic_client", "openai_client"):
|
|
38
|
+
if hasattr(model, attr):
|
|
39
|
+
raw_c = getattr(model, attr)
|
|
40
|
+
if not isinstance(raw_c, WrappedClientProxy):
|
|
41
|
+
setattr(model, attr, ctxcache.wrap(raw_c, mode=mode))
|
|
42
|
+
|
|
43
|
+
def __getattr__(self, name: str) -> Any:
|
|
44
|
+
return getattr(self.underlying_model, name)
|
ctxcache/layout.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
"""Prompt layout optimization and volatile relocation (BUILD_HANDBOOK §5.1, INV-05)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from ctxcache.fingerprint import fingerprint_message
|
|
8
|
+
from ctxcache.guard import VOLATILE_PATTERN
|
|
9
|
+
from ctxcache.offload import offload_large_tool_outputs
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class LayoutMemory:
|
|
13
|
+
"""Exact suffixes already sent, so a later turn can repeat those bytes.
|
|
14
|
+
|
|
15
|
+
Keyed by the index and fingerprint of the application's original message.
|
|
16
|
+
A rewritten message does not match, and the old suffix is not applied to it.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def __init__(self) -> None:
|
|
20
|
+
self._by_index: dict[int, tuple[str, str]] = {}
|
|
21
|
+
|
|
22
|
+
def suffix_for(self, index: int, message: dict[str, Any]) -> str | None:
|
|
23
|
+
found = self._by_index.get(index)
|
|
24
|
+
if found is None:
|
|
25
|
+
return None
|
|
26
|
+
digest, suffix = found
|
|
27
|
+
if digest != fingerprint_message(message):
|
|
28
|
+
return None
|
|
29
|
+
return suffix
|
|
30
|
+
|
|
31
|
+
def remember(self, index: int, message: dict[str, Any], suffix: str) -> None:
|
|
32
|
+
self._by_index[index] = (fingerprint_message(message), suffix)
|
|
33
|
+
|
|
34
|
+
def __bool__(self) -> bool:
|
|
35
|
+
return bool(self._by_index)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _with_suffix(message: dict[str, Any], suffix: str) -> dict[str, Any]:
|
|
39
|
+
updated = dict(message)
|
|
40
|
+
content = updated.get("content", "")
|
|
41
|
+
if isinstance(content, str):
|
|
42
|
+
updated["content"] = f"{content}{suffix}"
|
|
43
|
+
elif isinstance(content, list):
|
|
44
|
+
blocks: list[Any] = []
|
|
45
|
+
for block in content:
|
|
46
|
+
blocks.append(dict(block) if isinstance(block, dict) else block)
|
|
47
|
+
blocks.append({"text": suffix.lstrip("\n")})
|
|
48
|
+
updated["content"] = blocks
|
|
49
|
+
return updated
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _runtime_suffix(snippets: list[str]) -> str:
|
|
53
|
+
block = "\n".join(snippets)
|
|
54
|
+
return f"\n\n[Runtime Context:\n{block}]"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def relocate_volatile_in_system(
|
|
58
|
+
system: str,
|
|
59
|
+
messages: list[dict[str, Any]],
|
|
60
|
+
memory: LayoutMemory | None = None,
|
|
61
|
+
) -> tuple[str, list[dict[str, Any]], list[dict[str, Any]]]:
|
|
62
|
+
"""Relocate volatile elements from static system prompt to the user turn tail (INV-05).
|
|
63
|
+
|
|
64
|
+
Returns (optimized_system, optimized_messages, changes).
|
|
65
|
+
|
|
66
|
+
When ``memory`` is set, a suffix already sent on a message is written again
|
|
67
|
+
unchanged. A new clock is attached only to a user message that has not been
|
|
68
|
+
sent yet. Writing the new clock onto an earlier message would change bytes
|
|
69
|
+
the provider already saw.
|
|
70
|
+
"""
|
|
71
|
+
if not system and not memory:
|
|
72
|
+
return system, messages, []
|
|
73
|
+
|
|
74
|
+
lines = system.splitlines() if system else []
|
|
75
|
+
static_lines: list[str] = []
|
|
76
|
+
relocated_snippets: list[str] = []
|
|
77
|
+
|
|
78
|
+
for line in lines:
|
|
79
|
+
if VOLATILE_PATTERN.search(line):
|
|
80
|
+
relocated_snippets.append(line.strip())
|
|
81
|
+
else:
|
|
82
|
+
static_lines.append(line)
|
|
83
|
+
|
|
84
|
+
if not relocated_snippets and not memory:
|
|
85
|
+
return system, messages, []
|
|
86
|
+
|
|
87
|
+
optimized_system = "\n".join(static_lines).strip()
|
|
88
|
+
optimized_messages = [dict(m) for m in messages]
|
|
89
|
+
changes: list[dict[str, Any]] = []
|
|
90
|
+
|
|
91
|
+
target_idx = None
|
|
92
|
+
for idx in range(len(optimized_messages) - 1, -1, -1):
|
|
93
|
+
if optimized_messages[idx].get("role") == "user":
|
|
94
|
+
target_idx = idx
|
|
95
|
+
break
|
|
96
|
+
|
|
97
|
+
if memory is not None:
|
|
98
|
+
for idx, message in enumerate(optimized_messages):
|
|
99
|
+
if idx == target_idx:
|
|
100
|
+
continue
|
|
101
|
+
stored = memory.suffix_for(idx, message)
|
|
102
|
+
if stored:
|
|
103
|
+
optimized_messages[idx] = _with_suffix(message, stored)
|
|
104
|
+
changes.append(
|
|
105
|
+
{
|
|
106
|
+
"kind": "volatile_retained",
|
|
107
|
+
"source": "system",
|
|
108
|
+
"target_message_index": idx,
|
|
109
|
+
}
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
if not relocated_snippets:
|
|
113
|
+
return optimized_system, optimized_messages, changes
|
|
114
|
+
|
|
115
|
+
suffix = _runtime_suffix(relocated_snippets)
|
|
116
|
+
if target_idx is not None:
|
|
117
|
+
original = optimized_messages[target_idx]
|
|
118
|
+
stored = memory.suffix_for(target_idx, original) if memory is not None else None
|
|
119
|
+
if stored is not None:
|
|
120
|
+
optimized_messages[target_idx] = _with_suffix(original, stored)
|
|
121
|
+
changes.append(
|
|
122
|
+
{
|
|
123
|
+
"kind": "volatile_retained",
|
|
124
|
+
"source": "system",
|
|
125
|
+
"target_message_index": target_idx,
|
|
126
|
+
"snippets_not_written": relocated_snippets,
|
|
127
|
+
}
|
|
128
|
+
)
|
|
129
|
+
else:
|
|
130
|
+
content = original.get("content", "")
|
|
131
|
+
if isinstance(content, (str, list)):
|
|
132
|
+
optimized_messages[target_idx] = _with_suffix(original, suffix)
|
|
133
|
+
if memory is not None:
|
|
134
|
+
memory.remember(target_idx, original, suffix)
|
|
135
|
+
changes.append(
|
|
136
|
+
{
|
|
137
|
+
"kind": "volatile_relocated",
|
|
138
|
+
"source": "system",
|
|
139
|
+
"target_message_index": target_idx,
|
|
140
|
+
"snippets": relocated_snippets,
|
|
141
|
+
}
|
|
142
|
+
)
|
|
143
|
+
else:
|
|
144
|
+
block = "\n".join(relocated_snippets)
|
|
145
|
+
optimized_messages.append({"role": "user", "content": f"[Runtime Context:\n{block}]"})
|
|
146
|
+
changes.append(
|
|
147
|
+
{
|
|
148
|
+
"kind": "volatile_relocated",
|
|
149
|
+
"source": "system",
|
|
150
|
+
"target_message_index": len(optimized_messages) - 1,
|
|
151
|
+
"snippets": relocated_snippets,
|
|
152
|
+
}
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
return optimized_system, optimized_messages, changes
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def optimize_layout(
|
|
159
|
+
system: str,
|
|
160
|
+
messages: list[dict[str, Any]],
|
|
161
|
+
tools: list[dict[str, Any]] | None = None,
|
|
162
|
+
memory: LayoutMemory | None = None,
|
|
163
|
+
) -> tuple[str, list[dict[str, Any]], list[dict[str, Any]]]:
|
|
164
|
+
"""Apply all optimize-mode layout transformations and record all changes (INV-05)."""
|
|
165
|
+
all_changes: list[dict[str, Any]] = []
|
|
166
|
+
|
|
167
|
+
# 1. Relocate volatile elements from system prefix to tail
|
|
168
|
+
new_system, new_messages, reloc_changes = relocate_volatile_in_system(
|
|
169
|
+
system, messages, memory=memory
|
|
170
|
+
)
|
|
171
|
+
all_changes.extend(reloc_changes)
|
|
172
|
+
|
|
173
|
+
# 2. Offload large tool outputs if read tool is registered
|
|
174
|
+
new_messages, offload_changes = offload_large_tool_outputs(new_messages, tools)
|
|
175
|
+
all_changes.extend(offload_changes)
|
|
176
|
+
|
|
177
|
+
return new_system, new_messages, all_changes
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def optimize_converse_system(
|
|
181
|
+
system: list[Any],
|
|
182
|
+
messages: list[dict[str, Any]],
|
|
183
|
+
tools: list[dict[str, Any]] | None = None,
|
|
184
|
+
memory: LayoutMemory | None = None,
|
|
185
|
+
) -> tuple[list[Any], list[dict[str, Any]], list[dict[str, Any]]]:
|
|
186
|
+
"""Move a clock out of Converse system text and leave cache checkpoints alone.
|
|
187
|
+
|
|
188
|
+
A Converse system is a list of blocks. Text blocks hold the instructions.
|
|
189
|
+
A ``cachePoint`` block is copied through unchanged, because that is the
|
|
190
|
+
marker the provider uses to reuse the prefix.
|
|
191
|
+
"""
|
|
192
|
+
text_parts = [
|
|
193
|
+
str(block["text"])
|
|
194
|
+
for block in system
|
|
195
|
+
if isinstance(block, dict) and isinstance(block.get("text"), str)
|
|
196
|
+
]
|
|
197
|
+
joined = "\n".join(text_parts)
|
|
198
|
+
messages_in = [dict(message) for message in messages]
|
|
199
|
+
new_text, new_messages, changes = relocate_volatile_in_system(
|
|
200
|
+
joined, messages_in, memory=memory
|
|
201
|
+
)
|
|
202
|
+
new_messages, offload_changes = offload_large_tool_outputs(new_messages, tools)
|
|
203
|
+
changes = [*changes, *offload_changes]
|
|
204
|
+
if new_text == joined and new_messages == messages_in and not changes:
|
|
205
|
+
return system, messages, []
|
|
206
|
+
|
|
207
|
+
rebuilt: list[Any] = []
|
|
208
|
+
placed = False
|
|
209
|
+
for block in system:
|
|
210
|
+
if isinstance(block, dict) and isinstance(block.get("text"), str):
|
|
211
|
+
if not placed:
|
|
212
|
+
updated = dict(block)
|
|
213
|
+
updated["text"] = new_text
|
|
214
|
+
rebuilt.append(updated)
|
|
215
|
+
placed = True
|
|
216
|
+
elif isinstance(block, dict):
|
|
217
|
+
rebuilt.append(dict(block))
|
|
218
|
+
else:
|
|
219
|
+
rebuilt.append(block)
|
|
220
|
+
if not placed:
|
|
221
|
+
rebuilt.insert(0, {"text": new_text})
|
|
222
|
+
return rebuilt, new_messages, changes
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def optimize_chat_messages(
|
|
226
|
+
messages: list[dict[str, Any]],
|
|
227
|
+
tools: list[dict[str, Any]] | None = None,
|
|
228
|
+
memory: LayoutMemory | None = None,
|
|
229
|
+
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
|
230
|
+
"""Relocate volatile lines inside an OpenAI-style system message.
|
|
231
|
+
|
|
232
|
+
Chat Completions keeps the system text in ``messages``, not a top-level
|
|
233
|
+
``system`` field. The non-volatile lines stay in that message. The clock
|
|
234
|
+
moves onto the latest user message.
|
|
235
|
+
"""
|
|
236
|
+
system_idx = None
|
|
237
|
+
for idx, message in enumerate(messages):
|
|
238
|
+
if (
|
|
239
|
+
isinstance(message, dict)
|
|
240
|
+
and message.get("role") == "system"
|
|
241
|
+
and isinstance(message.get("content"), str)
|
|
242
|
+
):
|
|
243
|
+
system_idx = idx
|
|
244
|
+
break
|
|
245
|
+
if system_idx is None:
|
|
246
|
+
new_messages, changes = offload_large_tool_outputs(list(messages), tools)
|
|
247
|
+
return new_messages, changes
|
|
248
|
+
|
|
249
|
+
system = str(messages[system_idx]["content"])
|
|
250
|
+
rest = [dict(message) for i, message in enumerate(messages) if i != system_idx]
|
|
251
|
+
new_system, new_rest, changes = optimize_layout(system, rest, tools, memory=memory)
|
|
252
|
+
system_message = dict(messages[system_idx])
|
|
253
|
+
system_message["content"] = new_system
|
|
254
|
+
head = [dict(message) for message in messages[:system_idx]]
|
|
255
|
+
return head + [system_message] + new_rest, changes
|
ctxcache/ledger.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""SQLite summary ledger for session and call metrics (BUILD_HANDBOOK §4.1, INV-09)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import sqlite3
|
|
7
|
+
from decimal import Decimal
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Ledger:
|
|
13
|
+
"""Manages SQLite storage of session and call cache performance metrics."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, db_path: str | Path | None = None):
|
|
16
|
+
if db_path is None:
|
|
17
|
+
ctxcache_dir = os.environ.get("CTXCACHE_HOME", os.path.expanduser("~/.ctxcache"))
|
|
18
|
+
self.db_path = Path(ctxcache_dir) / "ledger.sqlite"
|
|
19
|
+
else:
|
|
20
|
+
self.db_path = Path(db_path)
|
|
21
|
+
|
|
22
|
+
self.db_path.parent.mkdir(parents=True, exist_ok=True)
|
|
23
|
+
self._init_db()
|
|
24
|
+
|
|
25
|
+
def _get_connection(self) -> sqlite3.Connection:
|
|
26
|
+
conn = sqlite3.connect(self.db_path)
|
|
27
|
+
conn.row_factory = sqlite3.Row
|
|
28
|
+
return conn
|
|
29
|
+
|
|
30
|
+
def _init_db(self) -> None:
|
|
31
|
+
with self._get_connection() as conn:
|
|
32
|
+
conn.execute(
|
|
33
|
+
"""
|
|
34
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
35
|
+
session_id TEXT PRIMARY KEY,
|
|
36
|
+
created_at REAL NOT NULL,
|
|
37
|
+
total_calls INTEGER NOT NULL DEFAULT 0,
|
|
38
|
+
total_input INTEGER NOT NULL DEFAULT 0,
|
|
39
|
+
total_read INTEGER NOT NULL DEFAULT 0,
|
|
40
|
+
total_write INTEGER NOT NULL DEFAULT 0,
|
|
41
|
+
total_uncached INTEGER NOT NULL DEFAULT 0,
|
|
42
|
+
total_output INTEGER NOT NULL DEFAULT 0,
|
|
43
|
+
cost_usd TEXT NOT NULL DEFAULT '0.0',
|
|
44
|
+
read_share REAL NOT NULL DEFAULT 0.0
|
|
45
|
+
)
|
|
46
|
+
"""
|
|
47
|
+
)
|
|
48
|
+
conn.execute(
|
|
49
|
+
"""
|
|
50
|
+
CREATE TABLE IF NOT EXISTS calls (
|
|
51
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
52
|
+
session_id TEXT NOT NULL,
|
|
53
|
+
call_index INTEGER NOT NULL,
|
|
54
|
+
ts_start REAL NOT NULL,
|
|
55
|
+
ts_end REAL NOT NULL,
|
|
56
|
+
provider TEXT NOT NULL,
|
|
57
|
+
model TEXT NOT NULL,
|
|
58
|
+
mode TEXT NOT NULL,
|
|
59
|
+
read_tokens INTEGER NOT NULL,
|
|
60
|
+
write_tokens INTEGER NOT NULL,
|
|
61
|
+
uncached_tokens INTEGER NOT NULL,
|
|
62
|
+
output_tokens INTEGER NOT NULL,
|
|
63
|
+
cost_usd TEXT NOT NULL,
|
|
64
|
+
breaks_count INTEGER NOT NULL DEFAULT 0,
|
|
65
|
+
FOREIGN KEY(session_id) REFERENCES sessions(session_id)
|
|
66
|
+
)
|
|
67
|
+
"""
|
|
68
|
+
)
|
|
69
|
+
conn.commit()
|
|
70
|
+
|
|
71
|
+
def record_call(
|
|
72
|
+
self,
|
|
73
|
+
*,
|
|
74
|
+
session_id: str,
|
|
75
|
+
call_index: int,
|
|
76
|
+
ts_start: float,
|
|
77
|
+
ts_end: float,
|
|
78
|
+
provider: str,
|
|
79
|
+
model: str,
|
|
80
|
+
mode: str,
|
|
81
|
+
read_tokens: int,
|
|
82
|
+
write_tokens: int,
|
|
83
|
+
uncached_tokens: int,
|
|
84
|
+
output_tokens: int,
|
|
85
|
+
cost_usd: Decimal,
|
|
86
|
+
breaks_count: int = 0,
|
|
87
|
+
) -> None:
|
|
88
|
+
"""Record call summary into SQLite ledger without prompt content (INV-09)."""
|
|
89
|
+
tot_in = read_tokens + write_tokens + uncached_tokens
|
|
90
|
+
with self._get_connection() as conn:
|
|
91
|
+
# 1. Insert call record
|
|
92
|
+
conn.execute(
|
|
93
|
+
"""
|
|
94
|
+
INSERT INTO calls (
|
|
95
|
+
session_id, call_index, ts_start, ts_end, provider, model, mode,
|
|
96
|
+
read_tokens, write_tokens, uncached_tokens, output_tokens, cost_usd, breaks_count
|
|
97
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
98
|
+
""",
|
|
99
|
+
(
|
|
100
|
+
session_id,
|
|
101
|
+
call_index,
|
|
102
|
+
ts_start,
|
|
103
|
+
ts_end,
|
|
104
|
+
provider,
|
|
105
|
+
model,
|
|
106
|
+
mode,
|
|
107
|
+
read_tokens,
|
|
108
|
+
write_tokens,
|
|
109
|
+
uncached_tokens,
|
|
110
|
+
output_tokens,
|
|
111
|
+
str(cost_usd),
|
|
112
|
+
breaks_count,
|
|
113
|
+
),
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
# 2. Update or insert session summary
|
|
117
|
+
cur = conn.execute("SELECT * FROM sessions WHERE session_id = ?", (session_id,))
|
|
118
|
+
row = cur.fetchone()
|
|
119
|
+
if row is None:
|
|
120
|
+
r_share = float(read_tokens) / tot_in if tot_in > 0 else 0.0
|
|
121
|
+
conn.execute(
|
|
122
|
+
"""
|
|
123
|
+
INSERT INTO sessions (
|
|
124
|
+
session_id, created_at, total_calls, total_input, total_read,
|
|
125
|
+
total_write, total_uncached, total_output, cost_usd, read_share
|
|
126
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
127
|
+
""",
|
|
128
|
+
(
|
|
129
|
+
session_id,
|
|
130
|
+
ts_start,
|
|
131
|
+
1,
|
|
132
|
+
tot_in,
|
|
133
|
+
read_tokens,
|
|
134
|
+
write_tokens,
|
|
135
|
+
uncached_tokens,
|
|
136
|
+
output_tokens,
|
|
137
|
+
str(cost_usd),
|
|
138
|
+
r_share,
|
|
139
|
+
),
|
|
140
|
+
)
|
|
141
|
+
else:
|
|
142
|
+
new_calls = row["total_calls"] + 1
|
|
143
|
+
new_input = row["total_input"] + tot_in
|
|
144
|
+
new_read = row["total_read"] + read_tokens
|
|
145
|
+
new_write = row["total_write"] + write_tokens
|
|
146
|
+
new_uncached = row["total_uncached"] + uncached_tokens
|
|
147
|
+
new_output = row["total_output"] + output_tokens
|
|
148
|
+
new_cost = str(Decimal(row["cost_usd"]) + cost_usd)
|
|
149
|
+
new_share = float(new_read) / new_input if new_input > 0 else 0.0
|
|
150
|
+
|
|
151
|
+
conn.execute(
|
|
152
|
+
"""
|
|
153
|
+
UPDATE sessions SET
|
|
154
|
+
total_calls = ?, total_input = ?, total_read = ?,
|
|
155
|
+
total_write = ?, total_uncached = ?, total_output = ?,
|
|
156
|
+
cost_usd = ?, read_share = ?
|
|
157
|
+
WHERE session_id = ?
|
|
158
|
+
""",
|
|
159
|
+
(
|
|
160
|
+
new_calls,
|
|
161
|
+
new_input,
|
|
162
|
+
new_read,
|
|
163
|
+
new_write,
|
|
164
|
+
new_uncached,
|
|
165
|
+
new_output,
|
|
166
|
+
new_cost,
|
|
167
|
+
new_share,
|
|
168
|
+
session_id,
|
|
169
|
+
),
|
|
170
|
+
)
|
|
171
|
+
conn.commit()
|
|
172
|
+
|
|
173
|
+
def get_session_summary(self, session_id: str) -> dict[str, Any] | None:
|
|
174
|
+
with self._get_connection() as conn:
|
|
175
|
+
cur = conn.execute("SELECT * FROM sessions WHERE session_id = ?", (session_id,))
|
|
176
|
+
row = cur.fetchone()
|
|
177
|
+
if row is None:
|
|
178
|
+
return None
|
|
179
|
+
return dict(row)
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""CtxCache Memory subsystem: temporal structured facts with cache-friendly placement (BUILD_HANDBOOK §5.7)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from ctxcache.memory.checks import MemoryWriteError, validate_fact_write
|
|
6
|
+
from ctxcache.memory.recall import (
|
|
7
|
+
get_default_memory_store,
|
|
8
|
+
pin,
|
|
9
|
+
recall,
|
|
10
|
+
remember,
|
|
11
|
+
set_default_memory_store,
|
|
12
|
+
)
|
|
13
|
+
from ctxcache.memory.store import Fact, MemoryStore
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"Fact",
|
|
17
|
+
"MemoryStore",
|
|
18
|
+
"MemoryWriteError",
|
|
19
|
+
"validate_fact_write",
|
|
20
|
+
"remember",
|
|
21
|
+
"recall",
|
|
22
|
+
"pin",
|
|
23
|
+
"get_default_memory_store",
|
|
24
|
+
"set_default_memory_store",
|
|
25
|
+
]
|