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/wrapper.py
ADDED
|
@@ -0,0 +1,609 @@
|
|
|
1
|
+
"""Dynamic wrapper proxy for LLM clients supporting observe and safe modes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import copy
|
|
6
|
+
import inspect
|
|
7
|
+
import logging
|
|
8
|
+
import time
|
|
9
|
+
from collections.abc import AsyncIterator, Callable, Iterator
|
|
10
|
+
from decimal import Decimal
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from ctxcache import CtxCachePrefixBreak
|
|
14
|
+
from ctxcache.adapters import (
|
|
15
|
+
NormalizedUsage,
|
|
16
|
+
parse_anthropic_usage,
|
|
17
|
+
parse_bedrock_converse_usage,
|
|
18
|
+
parse_gemini_usage,
|
|
19
|
+
parse_openai_usage,
|
|
20
|
+
)
|
|
21
|
+
from ctxcache.cost import CallCost, compute_call_cost
|
|
22
|
+
from ctxcache.guard import PrefixGuard
|
|
23
|
+
from ctxcache.layout import (
|
|
24
|
+
LayoutMemory,
|
|
25
|
+
optimize_chat_messages,
|
|
26
|
+
optimize_converse_system,
|
|
27
|
+
optimize_layout,
|
|
28
|
+
)
|
|
29
|
+
from ctxcache.ledger import Ledger
|
|
30
|
+
from ctxcache.otel import record_span
|
|
31
|
+
from ctxcache.planner import get_ttl_optimizer, plan_breakpoints
|
|
32
|
+
from ctxcache.segments import contents_as_messages, segment_request
|
|
33
|
+
from ctxcache.sim.tokens import count_text_tokens
|
|
34
|
+
from ctxcache.trace import TraceRecorder, get_trace_recorder
|
|
35
|
+
|
|
36
|
+
logger = logging.getLogger(__name__)
|
|
37
|
+
|
|
38
|
+
# Arguments CtxCache understands and the model API does not.
|
|
39
|
+
_CTXCACHE_ONLY = frozenset({"session_id"})
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class WrappedMethod:
|
|
43
|
+
"""Intercepts client creation calls to measure, protect, and trace prompt caching."""
|
|
44
|
+
|
|
45
|
+
def __init__(
|
|
46
|
+
self,
|
|
47
|
+
target_fn: Callable[..., Any],
|
|
48
|
+
provider: str,
|
|
49
|
+
api: str,
|
|
50
|
+
mode: str,
|
|
51
|
+
record: bool,
|
|
52
|
+
strict: bool,
|
|
53
|
+
recorder: TraceRecorder | None = None,
|
|
54
|
+
ledger: Ledger | None = None,
|
|
55
|
+
):
|
|
56
|
+
self._target_fn = target_fn
|
|
57
|
+
self.provider = provider
|
|
58
|
+
self.api = api
|
|
59
|
+
self.mode = mode
|
|
60
|
+
self.record = record
|
|
61
|
+
self.strict = strict
|
|
62
|
+
self.recorder = recorder or get_trace_recorder()
|
|
63
|
+
self.ledger = ledger or Ledger()
|
|
64
|
+
self.guard = PrefixGuard(strict=strict)
|
|
65
|
+
self._layout_memory: dict[str, LayoutMemory] = {}
|
|
66
|
+
self._call_counter = 0
|
|
67
|
+
self._first_seen_tools_order: dict[str, list[dict[str, Any]]] = {}
|
|
68
|
+
|
|
69
|
+
def _process_safe_request(
|
|
70
|
+
self, kwargs: dict[str, Any], session_id: str
|
|
71
|
+
) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]:
|
|
72
|
+
"""Safe mode request processing:
|
|
73
|
+
|
|
74
|
+
- Restores first-seen tool order if reordered (INV-02)
|
|
75
|
+
- Preserves exact message and tool content
|
|
76
|
+
- Adds cache planning metadata
|
|
77
|
+
- Evaluates prefix guard divergence
|
|
78
|
+
"""
|
|
79
|
+
mod_kwargs = copy.deepcopy(kwargs)
|
|
80
|
+
breaks_list: list[dict[str, Any]] = []
|
|
81
|
+
changes_list: list[dict[str, Any]] = []
|
|
82
|
+
|
|
83
|
+
# 1. Restore first-seen tool order if application reordered them
|
|
84
|
+
tools = mod_kwargs.get("tools")
|
|
85
|
+
if tools and isinstance(tools, list):
|
|
86
|
+
if session_id not in self._first_seen_tools_order:
|
|
87
|
+
self._first_seen_tools_order[session_id] = list(tools)
|
|
88
|
+
else:
|
|
89
|
+
first_seen = self._first_seen_tools_order[session_id]
|
|
90
|
+
first_seen_names = [str(t.get("name", "")) for t in first_seen]
|
|
91
|
+
current_names = [str(t.get("name", "")) for t in tools]
|
|
92
|
+
if (
|
|
93
|
+
sorted(first_seen_names) == sorted(current_names)
|
|
94
|
+
and first_seen_names != current_names
|
|
95
|
+
):
|
|
96
|
+
# Restore first-seen order!
|
|
97
|
+
tool_map = {str(t.get("name", "")): t for t in tools}
|
|
98
|
+
restored_tools = [
|
|
99
|
+
tool_map[name] for name in first_seen_names if name in tool_map
|
|
100
|
+
]
|
|
101
|
+
mod_kwargs["tools"] = restored_tools
|
|
102
|
+
changes_list.append(
|
|
103
|
+
{
|
|
104
|
+
"kind": "tool_order_restored",
|
|
105
|
+
"first_seen_order": first_seen_names,
|
|
106
|
+
"reordered_order": current_names,
|
|
107
|
+
"details": "Restored first-seen tool order to protect prefix cache",
|
|
108
|
+
}
|
|
109
|
+
)
|
|
110
|
+
breaks_list.append(
|
|
111
|
+
{
|
|
112
|
+
"cause": "tools_reordered",
|
|
113
|
+
"user_caused": True,
|
|
114
|
+
"level": "tools",
|
|
115
|
+
"details": "Restored first-seen tool order in safe mode",
|
|
116
|
+
}
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
# In optimize mode: optimize layout (relocate volatile system prompts, offload large tool outputs)
|
|
120
|
+
if self.mode == "optimize":
|
|
121
|
+
layout_memory = self._layout_memory.setdefault(session_id, LayoutMemory())
|
|
122
|
+
raw_messages = mod_kwargs.get("messages")
|
|
123
|
+
chat_messages: list[dict[str, Any]] | None = None
|
|
124
|
+
if isinstance(raw_messages, list) and all(
|
|
125
|
+
isinstance(item, dict) for item in raw_messages
|
|
126
|
+
):
|
|
127
|
+
typed_messages: list[dict[str, Any]] = list(raw_messages)
|
|
128
|
+
if any(message.get("role") == "system" for message in typed_messages):
|
|
129
|
+
chat_messages = typed_messages
|
|
130
|
+
system_value = mod_kwargs.get("system", "")
|
|
131
|
+
if isinstance(system_value, list):
|
|
132
|
+
raw_for_converse = mod_kwargs.get("messages", [])
|
|
133
|
+
converse_messages = raw_for_converse if isinstance(raw_for_converse, list) else []
|
|
134
|
+
opt_system, opt_messages, layout_changes = optimize_converse_system(
|
|
135
|
+
system_value,
|
|
136
|
+
converse_messages,
|
|
137
|
+
tools=mod_kwargs.get("tools"),
|
|
138
|
+
memory=layout_memory,
|
|
139
|
+
)
|
|
140
|
+
if opt_system != system_value:
|
|
141
|
+
mod_kwargs["system"] = opt_system
|
|
142
|
+
if opt_messages != converse_messages:
|
|
143
|
+
mod_kwargs["messages"] = opt_messages
|
|
144
|
+
changes_list.extend(layout_changes)
|
|
145
|
+
elif not mod_kwargs.get("system") and chat_messages is not None:
|
|
146
|
+
opt_messages, layout_changes = optimize_chat_messages(
|
|
147
|
+
chat_messages,
|
|
148
|
+
tools=mod_kwargs.get("tools"),
|
|
149
|
+
memory=layout_memory,
|
|
150
|
+
)
|
|
151
|
+
if opt_messages != chat_messages:
|
|
152
|
+
mod_kwargs["messages"] = opt_messages
|
|
153
|
+
changes_list.extend(layout_changes)
|
|
154
|
+
else:
|
|
155
|
+
system_text = system_value if isinstance(system_value, str) else ""
|
|
156
|
+
layout_system, layout_messages, layout_changes = optimize_layout(
|
|
157
|
+
system=system_text,
|
|
158
|
+
messages=mod_kwargs.get("messages", []),
|
|
159
|
+
tools=mod_kwargs.get("tools"),
|
|
160
|
+
memory=layout_memory,
|
|
161
|
+
)
|
|
162
|
+
if layout_system != system_text:
|
|
163
|
+
mod_kwargs["system"] = layout_system
|
|
164
|
+
if layout_messages != mod_kwargs.get("messages", []):
|
|
165
|
+
mod_kwargs["messages"] = layout_messages
|
|
166
|
+
changes_list.extend(layout_changes)
|
|
167
|
+
|
|
168
|
+
# 2. Segment request. Gemini puts the prompt in ``contents``, not ``messages``.
|
|
169
|
+
# Counting only ``messages`` scored that prompt as 0 tokens.
|
|
170
|
+
messages = mod_kwargs.get("messages") or []
|
|
171
|
+
if not messages and "contents" in mod_kwargs:
|
|
172
|
+
messages = contents_as_messages(mod_kwargs.get("contents"))
|
|
173
|
+
system = mod_kwargs.get("system", "")
|
|
174
|
+
segments = segment_request(
|
|
175
|
+
system=system,
|
|
176
|
+
tools=mod_kwargs.get("tools"),
|
|
177
|
+
messages=messages,
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
# 3. Guard divergence check (raises CtxCachePrefixBreak if strict=True)
|
|
181
|
+
total_tokens = sum(count_text_tokens(str(s.data)) for s in segments)
|
|
182
|
+
event = self.guard.evaluate_call(
|
|
183
|
+
curr_params={k: v for k, v in kwargs.items() if k in ("model", "temperature")},
|
|
184
|
+
curr_tools=mod_kwargs.get("tools", []),
|
|
185
|
+
curr_system=str(system),
|
|
186
|
+
curr_messages=messages,
|
|
187
|
+
total_tokens=total_tokens,
|
|
188
|
+
ts=time.time(),
|
|
189
|
+
)
|
|
190
|
+
if event is not None:
|
|
191
|
+
breaks_list.append(
|
|
192
|
+
{
|
|
193
|
+
"cause": event.cause,
|
|
194
|
+
"user_caused": event.user_caused,
|
|
195
|
+
"level": event.level,
|
|
196
|
+
"details": event.details,
|
|
197
|
+
}
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
# 4. Plan breakpoints and TTL optimization (§5.4)
|
|
201
|
+
from ctxcache import get_current_session
|
|
202
|
+
|
|
203
|
+
curr_session = get_current_session()
|
|
204
|
+
expected_calls = 2
|
|
205
|
+
expected_pause = False
|
|
206
|
+
if curr_session is not None:
|
|
207
|
+
if curr_session._expected_calls is not None:
|
|
208
|
+
expected_calls = curr_session._expected_calls
|
|
209
|
+
expected_pause = curr_session._expected_pause
|
|
210
|
+
|
|
211
|
+
get_ttl_optimizer().record_call(session_id)
|
|
212
|
+
|
|
213
|
+
plan = plan_breakpoints(
|
|
214
|
+
provider=self.provider,
|
|
215
|
+
segments=segments,
|
|
216
|
+
expected_calls=expected_calls,
|
|
217
|
+
session_id=session_id,
|
|
218
|
+
expected_pause=expected_pause,
|
|
219
|
+
)
|
|
220
|
+
if plan.should_cache and plan.prompt_cache_key:
|
|
221
|
+
mod_kwargs["prompt_cache_key"] = plan.prompt_cache_key
|
|
222
|
+
|
|
223
|
+
return mod_kwargs, breaks_list, changes_list
|
|
224
|
+
|
|
225
|
+
def _outbound_kwargs(self, send_kwargs: dict[str, Any]) -> dict[str, Any]:
|
|
226
|
+
"""Drop CtxCache-only arguments before the provider sees the call.
|
|
227
|
+
|
|
228
|
+
``prompt_cache_key`` is an OpenAI field. Gemini and Converse reject it.
|
|
229
|
+
"""
|
|
230
|
+
cleaned = {key: value for key, value in send_kwargs.items() if key not in _CTXCACHE_ONLY}
|
|
231
|
+
if self.provider != "openai":
|
|
232
|
+
cleaned.pop("prompt_cache_key", None)
|
|
233
|
+
return cleaned
|
|
234
|
+
|
|
235
|
+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
|
236
|
+
self._call_counter += 1
|
|
237
|
+
call_idx = self._call_counter
|
|
238
|
+
session_id = str(kwargs.get("session_id", "default"))
|
|
239
|
+
|
|
240
|
+
send_kwargs = kwargs
|
|
241
|
+
recorded_breaks: list[dict[str, Any]] = []
|
|
242
|
+
recorded_changes: list[dict[str, Any]] = []
|
|
243
|
+
|
|
244
|
+
if self.mode == "observe":
|
|
245
|
+
# INV-01: observe sends byte-identical requests
|
|
246
|
+
send_kwargs = kwargs
|
|
247
|
+
elif self.mode in ("safe", "optimize"):
|
|
248
|
+
try:
|
|
249
|
+
send_kwargs, recorded_breaks, recorded_changes = self._process_safe_request(
|
|
250
|
+
kwargs, session_id
|
|
251
|
+
)
|
|
252
|
+
except CtxCachePrefixBreak:
|
|
253
|
+
raise
|
|
254
|
+
except Exception as e:
|
|
255
|
+
# INV-07: Fail-open: internal error sends original request unchanged and records ctxcache_error
|
|
256
|
+
logger.exception(
|
|
257
|
+
"CtxCache internal error; failing open with original request: %s", e
|
|
258
|
+
)
|
|
259
|
+
send_kwargs = kwargs
|
|
260
|
+
recorded_breaks.append(
|
|
261
|
+
{
|
|
262
|
+
"cause": "ctxcache_error",
|
|
263
|
+
"user_caused": False,
|
|
264
|
+
"level": "system",
|
|
265
|
+
"details": f"Internal CtxCache exception: {e}",
|
|
266
|
+
}
|
|
267
|
+
)
|
|
268
|
+
|
|
269
|
+
ts_start = time.time()
|
|
270
|
+
model_name = str(kwargs.get("model", "unknown"))
|
|
271
|
+
response = self._target_fn(*args, **self._outbound_kwargs(send_kwargs))
|
|
272
|
+
|
|
273
|
+
if inspect.isasyncgen(response):
|
|
274
|
+
return self._wrap_async_stream(
|
|
275
|
+
response,
|
|
276
|
+
args=args,
|
|
277
|
+
kwargs=kwargs,
|
|
278
|
+
session_id=session_id,
|
|
279
|
+
call_idx=call_idx,
|
|
280
|
+
model_name=model_name,
|
|
281
|
+
ts_start=ts_start,
|
|
282
|
+
recorded_breaks=recorded_breaks,
|
|
283
|
+
recorded_changes=recorded_changes,
|
|
284
|
+
)
|
|
285
|
+
if inspect.iscoroutine(response):
|
|
286
|
+
return self._wrap_coroutine(
|
|
287
|
+
response,
|
|
288
|
+
args=args,
|
|
289
|
+
kwargs=kwargs,
|
|
290
|
+
session_id=session_id,
|
|
291
|
+
call_idx=call_idx,
|
|
292
|
+
model_name=model_name,
|
|
293
|
+
ts_start=ts_start,
|
|
294
|
+
recorded_breaks=recorded_breaks,
|
|
295
|
+
recorded_changes=recorded_changes,
|
|
296
|
+
)
|
|
297
|
+
if self._is_sync_stream(response, kwargs.get("stream")):
|
|
298
|
+
return self._wrap_sync_stream(
|
|
299
|
+
response,
|
|
300
|
+
args=args,
|
|
301
|
+
kwargs=kwargs,
|
|
302
|
+
session_id=session_id,
|
|
303
|
+
call_idx=call_idx,
|
|
304
|
+
model_name=model_name,
|
|
305
|
+
ts_start=ts_start,
|
|
306
|
+
recorded_breaks=recorded_breaks,
|
|
307
|
+
recorded_changes=recorded_changes,
|
|
308
|
+
)
|
|
309
|
+
|
|
310
|
+
self._finalize_call(
|
|
311
|
+
response,
|
|
312
|
+
args=args,
|
|
313
|
+
kwargs=kwargs,
|
|
314
|
+
session_id=session_id,
|
|
315
|
+
call_idx=call_idx,
|
|
316
|
+
model_name=model_name,
|
|
317
|
+
ts_start=ts_start,
|
|
318
|
+
ts_end=time.time(),
|
|
319
|
+
ts_first_token=None,
|
|
320
|
+
recorded_breaks=recorded_breaks,
|
|
321
|
+
recorded_changes=recorded_changes,
|
|
322
|
+
)
|
|
323
|
+
return response
|
|
324
|
+
|
|
325
|
+
def _is_sync_stream(self, response: Any, stream_flag: Any) -> bool:
|
|
326
|
+
if not stream_flag or isinstance(response, (str, bytes, dict, list)):
|
|
327
|
+
return False
|
|
328
|
+
return isinstance(response, Iterator)
|
|
329
|
+
|
|
330
|
+
def _finalize_call(
|
|
331
|
+
self,
|
|
332
|
+
response: Any,
|
|
333
|
+
*,
|
|
334
|
+
args: tuple[Any, ...],
|
|
335
|
+
kwargs: dict[str, Any],
|
|
336
|
+
session_id: str,
|
|
337
|
+
call_idx: int,
|
|
338
|
+
model_name: str,
|
|
339
|
+
ts_start: float,
|
|
340
|
+
ts_end: float,
|
|
341
|
+
ts_first_token: float | None,
|
|
342
|
+
recorded_breaks: list[dict[str, Any]],
|
|
343
|
+
recorded_changes: list[dict[str, Any]],
|
|
344
|
+
) -> None:
|
|
345
|
+
normalized_usage = (
|
|
346
|
+
self._extract_usage(response)
|
|
347
|
+
if response is not None
|
|
348
|
+
else NormalizedUsage(read=0, write=0, uncached=0, output=0, total_input=0, raw={})
|
|
349
|
+
)
|
|
350
|
+
try:
|
|
351
|
+
cost_info = compute_call_cost(
|
|
352
|
+
provider=self.provider,
|
|
353
|
+
model=model_name,
|
|
354
|
+
read_tokens=normalized_usage.read,
|
|
355
|
+
write_tokens=normalized_usage.write,
|
|
356
|
+
uncached_tokens=normalized_usage.uncached,
|
|
357
|
+
output_tokens=normalized_usage.output,
|
|
358
|
+
)
|
|
359
|
+
except KeyError as exc:
|
|
360
|
+
logger.warning("No sourced price for %s/%s", self.provider, model_name)
|
|
361
|
+
cost_info = CallCost(
|
|
362
|
+
actual_cost=Decimal("0"),
|
|
363
|
+
uncached_baseline=Decimal("0"),
|
|
364
|
+
savings_amount=Decimal("0"),
|
|
365
|
+
cost_ratio=Decimal("1"),
|
|
366
|
+
)
|
|
367
|
+
recorded_breaks.append(
|
|
368
|
+
{
|
|
369
|
+
"cause": "ctxcache_error",
|
|
370
|
+
"user_caused": False,
|
|
371
|
+
"level": "system",
|
|
372
|
+
"details": f"No sourced price in providers.toml: {exc}",
|
|
373
|
+
}
|
|
374
|
+
)
|
|
375
|
+
|
|
376
|
+
prefix_was_stable = not any(
|
|
377
|
+
item.get("cause") not in ("ctxcache_error",) for item in recorded_breaks
|
|
378
|
+
)
|
|
379
|
+
if (
|
|
380
|
+
self.mode in ("safe", "optimize")
|
|
381
|
+
and call_idx > 1
|
|
382
|
+
and prefix_was_stable
|
|
383
|
+
and normalized_usage.read == 0
|
|
384
|
+
and normalized_usage.total_input >= self.guard.min_prefix_tokens
|
|
385
|
+
):
|
|
386
|
+
recorded_breaks.append(
|
|
387
|
+
{
|
|
388
|
+
"cause": "provider_miss",
|
|
389
|
+
"user_caused": False,
|
|
390
|
+
"level": "system",
|
|
391
|
+
"details": "Identical prefix had 0 cached tokens reported by the provider",
|
|
392
|
+
}
|
|
393
|
+
)
|
|
394
|
+
|
|
395
|
+
self.ledger.record_call(
|
|
396
|
+
session_id=session_id,
|
|
397
|
+
call_index=call_idx,
|
|
398
|
+
ts_start=ts_start,
|
|
399
|
+
ts_end=ts_end,
|
|
400
|
+
provider=self.provider,
|
|
401
|
+
model=model_name,
|
|
402
|
+
mode=self.mode,
|
|
403
|
+
read_tokens=normalized_usage.read,
|
|
404
|
+
write_tokens=normalized_usage.write,
|
|
405
|
+
uncached_tokens=normalized_usage.uncached,
|
|
406
|
+
output_tokens=normalized_usage.output,
|
|
407
|
+
cost_usd=cost_info.actual_cost,
|
|
408
|
+
breaks_count=len(recorded_breaks),
|
|
409
|
+
)
|
|
410
|
+
record_span(
|
|
411
|
+
session_id=session_id,
|
|
412
|
+
call_index=call_idx,
|
|
413
|
+
provider=self.provider,
|
|
414
|
+
model=model_name,
|
|
415
|
+
mode=self.mode,
|
|
416
|
+
read_tokens=normalized_usage.read,
|
|
417
|
+
write_tokens=normalized_usage.write,
|
|
418
|
+
uncached_tokens=normalized_usage.uncached,
|
|
419
|
+
output_tokens=normalized_usage.output,
|
|
420
|
+
cost_usd=str(cost_info.actual_cost),
|
|
421
|
+
breaks_count=len(recorded_breaks),
|
|
422
|
+
)
|
|
423
|
+
body_to_record = None
|
|
424
|
+
if self.record and response is not None:
|
|
425
|
+
body_to_record = {
|
|
426
|
+
"request": {
|
|
427
|
+
"args": [str(a) for a in args],
|
|
428
|
+
"kwargs": {k: v for k, v in kwargs.items() if k != "client"},
|
|
429
|
+
},
|
|
430
|
+
"response": self._extract_response_body(response),
|
|
431
|
+
}
|
|
432
|
+
self.recorder.record_call(
|
|
433
|
+
session_id=session_id,
|
|
434
|
+
call_index=call_idx,
|
|
435
|
+
ts_start=ts_start,
|
|
436
|
+
ts_end=ts_end,
|
|
437
|
+
ts_first_token=ts_first_token,
|
|
438
|
+
provider=self.provider,
|
|
439
|
+
api=self.api,
|
|
440
|
+
model=model_name,
|
|
441
|
+
mode=self.mode,
|
|
442
|
+
params={
|
|
443
|
+
k: v
|
|
444
|
+
for k, v in kwargs.items()
|
|
445
|
+
if k in ("temperature", "top_p", "max_tokens", "stream")
|
|
446
|
+
},
|
|
447
|
+
fingerprints={"tools": [], "system": [], "messages": []},
|
|
448
|
+
usage={
|
|
449
|
+
"raw": normalized_usage.raw,
|
|
450
|
+
"read": normalized_usage.read,
|
|
451
|
+
"write": normalized_usage.write,
|
|
452
|
+
"uncached": normalized_usage.uncached,
|
|
453
|
+
"output": normalized_usage.output,
|
|
454
|
+
"cost_usd": str(cost_info.actual_cost),
|
|
455
|
+
},
|
|
456
|
+
breaks=recorded_breaks,
|
|
457
|
+
changes=recorded_changes,
|
|
458
|
+
body=body_to_record,
|
|
459
|
+
record_body=self.record,
|
|
460
|
+
)
|
|
461
|
+
|
|
462
|
+
def _wrap_sync_stream(
|
|
463
|
+
self,
|
|
464
|
+
response: Iterator[Any],
|
|
465
|
+
**finish: Any,
|
|
466
|
+
) -> Iterator[Any]:
|
|
467
|
+
def chunks() -> Iterator[Any]:
|
|
468
|
+
first_at: float | None = None
|
|
469
|
+
last: Any = None
|
|
470
|
+
try:
|
|
471
|
+
for item in response:
|
|
472
|
+
if first_at is None:
|
|
473
|
+
first_at = time.time()
|
|
474
|
+
last = item
|
|
475
|
+
yield item
|
|
476
|
+
finally:
|
|
477
|
+
self._finalize_quietly(last, ts_first_token=first_at, **finish)
|
|
478
|
+
|
|
479
|
+
return chunks()
|
|
480
|
+
|
|
481
|
+
def _wrap_coroutine(self, response: Any, **finish: Any) -> Any:
|
|
482
|
+
async def awaited() -> Any:
|
|
483
|
+
inner = await response
|
|
484
|
+
self._finalize_quietly(inner, ts_first_token=None, ts_end=time.time(), **finish)
|
|
485
|
+
return inner
|
|
486
|
+
|
|
487
|
+
return awaited()
|
|
488
|
+
|
|
489
|
+
def _wrap_async_stream(self, response: AsyncIterator[Any], **finish: Any) -> AsyncIterator[Any]:
|
|
490
|
+
async def chunks() -> AsyncIterator[Any]:
|
|
491
|
+
first_at: float | None = None
|
|
492
|
+
last: Any = None
|
|
493
|
+
try:
|
|
494
|
+
async for item in response:
|
|
495
|
+
if first_at is None:
|
|
496
|
+
first_at = time.time()
|
|
497
|
+
last = item
|
|
498
|
+
yield item
|
|
499
|
+
finally:
|
|
500
|
+
self._finalize_quietly(last, ts_first_token=first_at, **finish)
|
|
501
|
+
|
|
502
|
+
return chunks()
|
|
503
|
+
|
|
504
|
+
def _finalize_quietly(self, response: Any, **finish: Any) -> None:
|
|
505
|
+
try:
|
|
506
|
+
self._finalize_call(
|
|
507
|
+
response,
|
|
508
|
+
ts_end=finish.pop("ts_end", time.time()),
|
|
509
|
+
**finish,
|
|
510
|
+
)
|
|
511
|
+
except Exception:
|
|
512
|
+
logger.exception("CtxCache could not record a finished call")
|
|
513
|
+
|
|
514
|
+
def _extract_usage(self, response: Any) -> NormalizedUsage:
|
|
515
|
+
"""Normalize usage across providers into read, write, uncached, output (INV-06)."""
|
|
516
|
+
if hasattr(response, "usage") and response.usage is not None:
|
|
517
|
+
raw_u = response.usage
|
|
518
|
+
if self.provider == "bedrock" or (
|
|
519
|
+
isinstance(raw_u, dict) and "cacheReadInputTokens" in raw_u
|
|
520
|
+
):
|
|
521
|
+
return parse_bedrock_converse_usage(raw_u)
|
|
522
|
+
if self.provider == "anthropic" or (
|
|
523
|
+
isinstance(raw_u, dict) and "cache_read_input_tokens" in raw_u
|
|
524
|
+
):
|
|
525
|
+
return parse_anthropic_usage(raw_u)
|
|
526
|
+
return parse_openai_usage(raw_u)
|
|
527
|
+
|
|
528
|
+
if hasattr(response, "usage_metadata") and response.usage_metadata is not None:
|
|
529
|
+
return parse_gemini_usage(response.usage_metadata)
|
|
530
|
+
|
|
531
|
+
# Default fallback: zero usage
|
|
532
|
+
return NormalizedUsage(read=0, write=0, uncached=0, output=0, total_input=0, raw={})
|
|
533
|
+
|
|
534
|
+
def _extract_response_body(self, response: Any) -> Any:
|
|
535
|
+
if hasattr(response, "model_dump"):
|
|
536
|
+
return response.model_dump()
|
|
537
|
+
if hasattr(response, "to_dict"):
|
|
538
|
+
return response.to_dict()
|
|
539
|
+
return str(response)
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
class WrappedClientProxy:
|
|
543
|
+
"""Proxy that wraps a provider client's create/generate methods."""
|
|
544
|
+
|
|
545
|
+
def __init__(
|
|
546
|
+
self,
|
|
547
|
+
target_client: Any,
|
|
548
|
+
mode: str = "safe",
|
|
549
|
+
record: bool = False,
|
|
550
|
+
strict: bool = False,
|
|
551
|
+
recorder: TraceRecorder | None = None,
|
|
552
|
+
ledger: Ledger | None = None,
|
|
553
|
+
):
|
|
554
|
+
self._target_client = target_client
|
|
555
|
+
self.mode = mode
|
|
556
|
+
self.record = record
|
|
557
|
+
self.strict = strict
|
|
558
|
+
self.recorder = recorder
|
|
559
|
+
self.ledger = ledger
|
|
560
|
+
self._sub_proxies: dict[str, Any] = {}
|
|
561
|
+
self._wrapped_methods: dict[str, WrappedMethod] = {}
|
|
562
|
+
|
|
563
|
+
def __getattr__(self, name: str) -> Any:
|
|
564
|
+
attr = getattr(self._target_client, name)
|
|
565
|
+
|
|
566
|
+
if name in ("messages", "chat", "models", "responses", "completions"):
|
|
567
|
+
if name not in self._sub_proxies:
|
|
568
|
+
self._sub_proxies[name] = WrappedClientProxy(
|
|
569
|
+
attr,
|
|
570
|
+
mode=self.mode,
|
|
571
|
+
record=self.record,
|
|
572
|
+
strict=self.strict,
|
|
573
|
+
recorder=self.recorder,
|
|
574
|
+
ledger=self.ledger,
|
|
575
|
+
)
|
|
576
|
+
return self._sub_proxies[name]
|
|
577
|
+
|
|
578
|
+
if name in ("create", "generate_content") and callable(attr):
|
|
579
|
+
if name not in self._wrapped_methods:
|
|
580
|
+
provider = "gemini"
|
|
581
|
+
api = name
|
|
582
|
+
target_class_name = self._target_client.__class__.__name__.lower()
|
|
583
|
+
if "anthropic" in target_class_name or "messages" in target_class_name:
|
|
584
|
+
provider = "anthropic"
|
|
585
|
+
api = "messages"
|
|
586
|
+
elif "bedrock" in target_class_name:
|
|
587
|
+
provider = "bedrock"
|
|
588
|
+
api = "converse"
|
|
589
|
+
elif "openai" in target_class_name or "chat" in target_class_name:
|
|
590
|
+
provider = "openai"
|
|
591
|
+
api = "chat"
|
|
592
|
+
elif any(k in target_class_name for k in ("gemini", "models", "genai")):
|
|
593
|
+
provider = "gemini"
|
|
594
|
+
api = "generate_content"
|
|
595
|
+
|
|
596
|
+
self._wrapped_methods[name] = WrappedMethod(
|
|
597
|
+
attr,
|
|
598
|
+
provider=provider,
|
|
599
|
+
api=api,
|
|
600
|
+
mode=self.mode,
|
|
601
|
+
record=self.record,
|
|
602
|
+
strict=self.strict,
|
|
603
|
+
recorder=self.recorder,
|
|
604
|
+
ledger=self.ledger,
|
|
605
|
+
)
|
|
606
|
+
|
|
607
|
+
return self._wrapped_methods[name]
|
|
608
|
+
|
|
609
|
+
return attr
|