compache 0.14.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.
Files changed (47) hide show
  1. compache/__init__.py +54 -0
  2. compache/__main__.py +3 -0
  3. compache/_tls.py +47 -0
  4. compache/api.py +761 -0
  5. compache/cli.py +665 -0
  6. compache/defaults.py +113 -0
  7. compache/demo/labels.jsonl +71 -0
  8. compache/demo/threads.jsonl.gz +0 -0
  9. compache/errors.py +5 -0
  10. compache/hermes.py +284 -0
  11. compache/labels.py +336 -0
  12. compache/langchain.py +65 -0
  13. compache/langfuse.py +738 -0
  14. compache/litellm.py +306 -0
  15. compache/live.py +1443 -0
  16. compache/mlflow.py +439 -0
  17. compache/models.json +156 -0
  18. compache/models.py +156 -0
  19. compache/notes.py +365 -0
  20. compache/optimizer/__init__.py +51 -0
  21. compache/optimizer/cache_breaks.py +755 -0
  22. compache/optimizer/contracts.py +196 -0
  23. compache/optimizer/distribution.py +1384 -0
  24. compache/optimizer/edit_accounting.py +324 -0
  25. compache/optimizer/header_traffic.py +225 -0
  26. compache/optimizer/host_ledger.py +318 -0
  27. compache/optimizer/parts.py +435 -0
  28. compache/optimizer/recovery.py +250 -0
  29. compache/optimizer/replay.py +638 -0
  30. compache/optimizer/retention.py +996 -0
  31. compache/optimizer/session.py +1269 -0
  32. compache/optimizer/shared_prefix.py +465 -0
  33. compache/optimizer/solve.py +382 -0
  34. compache/optimizer/usage.py +49 -0
  35. compache/otel.py +390 -0
  36. compache/profile.py +643 -0
  37. compache/proxy.py +352 -0
  38. compache/py.typed +0 -0
  39. compache/record.py +238 -0
  40. compache/threads.py +892 -0
  41. compache/wire.py +1548 -0
  42. compache/wrap.py +417 -0
  43. compache-0.14.0.dist-info/METADATA +174 -0
  44. compache-0.14.0.dist-info/RECORD +47 -0
  45. compache-0.14.0.dist-info/WHEEL +4 -0
  46. compache-0.14.0.dist-info/entry_points.txt +6 -0
  47. compache-0.14.0.dist-info/licenses/LICENCE.md +202 -0
compache/litellm.py ADDED
@@ -0,0 +1,306 @@
1
+ """compache for LiteLLM.
2
+
3
+ Two ways in, alone or together.
4
+
5
+ `install` puts a `Live` in the path of LiteLLM's OpenAI-compatible calls (OpenAI,
6
+ OpenRouter, Azure and every other provider LiteLLM reaches that way), sync and async,
7
+ whole and streamed. The policy is applied, notes are asked and pings go out as with
8
+ `compache.wrap`:
9
+
10
+ import compache, litellm
11
+ live = compache.Live("policy.json", record="compache-record", sample=0.1)
12
+ compache.litellm.install(live)
13
+ with compache.thread("conversation-17"):
14
+ litellm.completion(model="openrouter/anthropic/claude-haiku-5.5", messages=messages)
15
+
16
+ `Callback` is a LiteLLM callback that only records, whatever the provider, for teams
17
+ that want to learn a policy first. It reads the conversation's name from `metadata`:
18
+
19
+ litellm.callbacks = [compache.litellm.Callback(record="compache-record", sample=0.1)]
20
+ litellm.completion(..., metadata={"session_id": "conversation-17"})
21
+
22
+ In a LiteLLM proxy, name `compache.litellm.callback` under `litellm_settings.callbacks`
23
+ and set COMPACHE_RECORD to a folder (COMPACHE_SAMPLE and COMPACHE_NOTES are optional).
24
+
25
+ A provider that LiteLLM calls over its own HTTP handlers, such as Anthropic's Messages
26
+ API, goes through `compache proxy` with `api_base="http://127.0.0.1:8787"`.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import asyncio
32
+ import itertools
33
+ import logging
34
+ import os
35
+ from typing import Any
36
+
37
+ from .live import Live, Result
38
+ from .wrap import async_http_client, http_client, per_loop_transport
39
+
40
+ __all__ = ["Callback", "install"]
41
+
42
+ logger = logging.getLogger(__name__)
43
+
44
+ _CHAT_CALLS = ("completion", "acompletion", "", None)
45
+ _numbers = itertools.count(1)
46
+
47
+
48
+ def install(live: Live, *, pings: bool = True) -> Live:
49
+ """Put `live` in the path of every OpenAI-compatible call that LiteLLM makes from now on.
50
+
51
+ It sets `litellm.client_session` and `litellm.aclient_session`, which LiteLLM gives
52
+ to the OpenAI SDK, and forgets the clients it made before. `pings` lets a background
53
+ thread send the policy's keep-warm pings. Returns `live`.
54
+ """
55
+ import httpx
56
+ import litellm
57
+
58
+ options = {"timeout": httpx.Timeout(600.0, connect=10.0), "follow_redirects": True}
59
+ litellm.client_session = http_client(
60
+ live, inner=httpx.Client(**options), pings=pings
61
+ )
62
+ # One client for every event loop of the process, so its connections belong to the loop that uses them.
63
+ litellm.aclient_session = async_http_client(
64
+ live, inner=per_loop_transport(httpx), pings=pings, **options
65
+ )
66
+ cache = getattr(litellm, "in_memory_llm_clients_cache", None)
67
+ for name in ("flush_cache", "clear"):
68
+ if callable(getattr(cache, name, None)):
69
+ getattr(cache, name)()
70
+ break
71
+ return live
72
+
73
+
74
+ def _plain(value: Any) -> Any:
75
+ """A message or reply as plain JSON: LiteLLM keeps replies as objects of its own."""
76
+ dump = getattr(value, "model_dump", None)
77
+ if callable(dump):
78
+ return dump(exclude_none=True)
79
+ if isinstance(value, dict):
80
+ return {k: _plain(v) for k, v in value.items()}
81
+ if isinstance(value, (list, tuple)):
82
+ return [_plain(v) for v in value]
83
+ return value
84
+
85
+
86
+ def _usage(usage: Any, cost: Any) -> dict | None:
87
+ """LiteLLM's usage in the form of the OpenAI API, which counts what was read or written in the total.
88
+
89
+ What the provider does not report is left out: a missing count is not a zero.
90
+ """
91
+ if usage is None:
92
+ return None
93
+ usage = _plain(usage)
94
+ details = usage.get("prompt_tokens_details") or {}
95
+ found = {
96
+ "cached_tokens": usage.get(
97
+ "cache_read_input_tokens", details.get("cached_tokens")
98
+ ),
99
+ "cache_write_tokens": usage.get(
100
+ "cache_creation_input_tokens", details.get("cache_write_tokens")
101
+ ),
102
+ }
103
+ out = {
104
+ "prompt_tokens": usage.get("prompt_tokens") or 0,
105
+ "completion_tokens": usage.get("completion_tokens") or 0,
106
+ }
107
+ if any(v is not None for v in found.values()):
108
+ out["prompt_tokens_details"] = {k: v for k, v in found.items() if v is not None}
109
+ # LiteLLM says 0 where it has no price for the model.
110
+ if isinstance(cost, (int, float)) and cost > 0:
111
+ out["cost"] = float(cost)
112
+ return out
113
+
114
+
115
+ def _seconds(moment: Any) -> float:
116
+ return moment.timestamp() if hasattr(moment, "timestamp") else float(moment)
117
+
118
+
119
+ def _metadata(kwargs: dict) -> dict:
120
+ metadata = (kwargs.get("litellm_params") or {}).get("metadata")
121
+ return metadata if isinstance(metadata, dict) else {}
122
+
123
+
124
+ def _session(kwargs: dict) -> str | None:
125
+ """The name of the conversation a call belongs to, from its metadata."""
126
+ metadata = _metadata(kwargs)
127
+ for value in (
128
+ metadata.get("session_id"),
129
+ (kwargs.get("litellm_params") or {}).get("litellm_session_id"),
130
+ metadata.get("litellm_session_id"),
131
+ ):
132
+ if isinstance(value, (str, int)) and str(value):
133
+ return str(value)
134
+ return None
135
+
136
+
137
+ class _Observer:
138
+ """Sees LiteLLM's finished calls and hands them to a `Live` that only records."""
139
+
140
+ def __init__(self, live: Live):
141
+ self.live = live
142
+
143
+ def see(self, kwargs: dict, response: Any, start: Any, end: Any) -> None:
144
+ """One finished call, whole or streamed. Never raises: a callback must not break a call."""
145
+ try:
146
+ self._see(kwargs, response, start, end)
147
+ except Exception:
148
+ logger.warning("compache: a LiteLLM call was not recorded", exc_info=True)
149
+
150
+ def _see(self, kwargs, response, start, end) -> None:
151
+ if kwargs.get("call_type") not in _CHAT_CALLS or _metadata(kwargs).get(
152
+ "compache_note"
153
+ ):
154
+ return
155
+ if kwargs.get("cache_hit"):
156
+ # LiteLLM answered from a cache of its own. No model was called.
157
+ return
158
+ streamed = kwargs.get("complete_streaming_response") or kwargs.get(
159
+ "async_complete_streaming_response"
160
+ )
161
+ reply = _plain(streamed or response)
162
+ if not isinstance(reply, dict) or not reply.get("choices"):
163
+ return
164
+ reply["usage"] = _usage(
165
+ getattr(streamed or response, "usage", None) or reply.get("usage"),
166
+ kwargs.get("response_cost"),
167
+ )
168
+ # A LiteLLM proxy answers under its own name for the model. What was called is in the call.
169
+ reply["model"] = kwargs.get("model") or reply.get("model")
170
+ optional = kwargs.get("optional_params") or {}
171
+ body = {
172
+ "model": kwargs.get("model"),
173
+ "messages": [_plain(m) for m in kwargs.get("messages") or ()],
174
+ }
175
+ tools = optional.get("tools") or kwargs.get("tools")
176
+ if tools:
177
+ body["tools"] = _plain(tools)
178
+ self.live.observe(
179
+ "/v1/chat/completions",
180
+ body,
181
+ reply,
182
+ thread=_session(kwargs),
183
+ at=(_seconds(start), _seconds(end)),
184
+ ask=_asker(kwargs) if self.live.sample else None,
185
+ )
186
+
187
+
188
+ # How a call reaches its provider, as LiteLLM keeps it with the call.
189
+ _CONNECTION = (
190
+ "api_base",
191
+ "api_key",
192
+ "api_version",
193
+ "azure_ad_token",
194
+ "azure_ad_token_provider",
195
+ "azure_password",
196
+ "azure_username",
197
+ "client_id",
198
+ "client_secret",
199
+ "extra_headers",
200
+ "organization",
201
+ "region_name",
202
+ "ssl_verify",
203
+ "tenant_id",
204
+ "timeout",
205
+ )
206
+ _CONNECTIONS = ("aws_", "vertex_", "watsonx_")
207
+
208
+
209
+ def _asker(kwargs: dict):
210
+ """A function that asks the model what its reply needed, through LiteLLM with this call's own settings."""
211
+ params = {
212
+ **(kwargs.get("optional_params") or {}),
213
+ **(kwargs.get("litellm_params") or {}),
214
+ }
215
+ connection = {
216
+ key: value
217
+ for key, value in params.items()
218
+ if value is not None and (key in _CONNECTION or key.startswith(_CONNECTIONS))
219
+ }
220
+
221
+ def ask(body: dict) -> Result:
222
+ import litellm
223
+
224
+ provider = kwargs.get("custom_llm_provider")
225
+ model = body.get("model") or kwargs.get("model") or ""
226
+ if provider and not str(model).startswith(f"{provider}/"):
227
+ model = f"{provider}/{model}"
228
+ request = {
229
+ **connection,
230
+ "model": model,
231
+ "messages": body["messages"],
232
+ "max_tokens": body.get("max_tokens") or body.get("max_completion_tokens"),
233
+ "metadata": {"compache_note": True},
234
+ "tools": body.get("tools"),
235
+ # A note is worth one try.
236
+ "num_retries": 0,
237
+ }
238
+ try:
239
+ response = litellm.completion(
240
+ **{k: v for k, v in request.items() if v is not None}
241
+ )
242
+ except Exception as error:
243
+ # Counted with the refusals: after three of them no more notes are asked.
244
+ logger.info("compache: a note was not asked", exc_info=True)
245
+ status = getattr(error, "status_code", None)
246
+ return Result(status if isinstance(status, int) and status >= 400 else 502)
247
+ return Result(200, json=_plain(response))
248
+
249
+ return ask
250
+
251
+
252
+ def Callback( # named like a class: it makes an instance of one that LiteLLM has to provide
253
+ live: Live | None = None, *, record=None, sample: float = 0.0, notes: str = "apart"
254
+ ):
255
+ """A LiteLLM callback that records every call, and asks notes when `sample` is set.
256
+
257
+ `Callback(record="compache-record", sample=0.1)` is an instance to put in
258
+ `litellm.callbacks`. LiteLLM is needed only when it is made. Its `Live` is
259
+ on it as `compache`.
260
+ """
261
+ from litellm.integrations.custom_logger import CustomLogger
262
+
263
+ if live is None:
264
+ live = Live(record=record, sample=sample, notes=notes)
265
+ seen = _Observer(live)
266
+
267
+ class _Compache(CustomLogger):
268
+ """Records what LiteLLM did. The text of the calls goes nowhere."""
269
+
270
+ compache = live
271
+
272
+ def __init__(self):
273
+ super().__init__()
274
+ # LiteLLM drops a callback whose class name and plain attributes it already has.
275
+ # A number of its own keeps two of these, which record in different places, apart.
276
+ self.number = next(_numbers)
277
+
278
+ def log_success_event(self, kwargs, response_obj, start_time, end_time):
279
+ seen.see(kwargs, response_obj, start_time, end_time)
280
+
281
+ async def async_log_success_event(
282
+ self, kwargs, response_obj, start_time, end_time
283
+ ):
284
+ await asyncio.to_thread(
285
+ seen.see, kwargs, response_obj, start_time, end_time
286
+ )
287
+
288
+ return _Compache()
289
+
290
+
291
+ def __getattr__(name: str) -> Any:
292
+ """`compache.litellm.callback`: an instance made from the environment, for a LiteLLM proxy's config."""
293
+ if name != "callback":
294
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
295
+ folder = os.environ.get("COMPACHE_RECORD")
296
+ if not folder:
297
+ raise RuntimeError(
298
+ "compache.litellm.callback: set COMPACHE_RECORD to the folder to record into"
299
+ )
300
+ made = Callback(
301
+ record=folder,
302
+ sample=float(os.environ.get("COMPACHE_SAMPLE") or 0),
303
+ notes=os.environ.get("COMPACHE_NOTES") or "apart",
304
+ )
305
+ globals()["callback"] = made
306
+ return made