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.
- compache/__init__.py +54 -0
- compache/__main__.py +3 -0
- compache/_tls.py +47 -0
- compache/api.py +761 -0
- compache/cli.py +665 -0
- compache/defaults.py +113 -0
- compache/demo/labels.jsonl +71 -0
- compache/demo/threads.jsonl.gz +0 -0
- compache/errors.py +5 -0
- compache/hermes.py +284 -0
- compache/labels.py +336 -0
- compache/langchain.py +65 -0
- compache/langfuse.py +738 -0
- compache/litellm.py +306 -0
- compache/live.py +1443 -0
- compache/mlflow.py +439 -0
- compache/models.json +156 -0
- compache/models.py +156 -0
- compache/notes.py +365 -0
- compache/optimizer/__init__.py +51 -0
- compache/optimizer/cache_breaks.py +755 -0
- compache/optimizer/contracts.py +196 -0
- compache/optimizer/distribution.py +1384 -0
- compache/optimizer/edit_accounting.py +324 -0
- compache/optimizer/header_traffic.py +225 -0
- compache/optimizer/host_ledger.py +318 -0
- compache/optimizer/parts.py +435 -0
- compache/optimizer/recovery.py +250 -0
- compache/optimizer/replay.py +638 -0
- compache/optimizer/retention.py +996 -0
- compache/optimizer/session.py +1269 -0
- compache/optimizer/shared_prefix.py +465 -0
- compache/optimizer/solve.py +382 -0
- compache/optimizer/usage.py +49 -0
- compache/otel.py +390 -0
- compache/profile.py +643 -0
- compache/proxy.py +352 -0
- compache/py.typed +0 -0
- compache/record.py +238 -0
- compache/threads.py +892 -0
- compache/wire.py +1548 -0
- compache/wrap.py +417 -0
- compache-0.14.0.dist-info/METADATA +174 -0
- compache-0.14.0.dist-info/RECORD +47 -0
- compache-0.14.0.dist-info/WHEEL +4 -0
- compache-0.14.0.dist-info/entry_points.txt +6 -0
- compache-0.14.0.dist-info/licenses/LICENCE.md +202 -0
compache/labels.py
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
"""Dependency labels: which earlier parts of a thread a turn needed.
|
|
2
|
+
|
|
3
|
+
One JSON object per labelled run:
|
|
4
|
+
|
|
5
|
+
{"thread_id": "t-17", "run": 7, "needs": [["t-17:3:output"], ["t-17:2:retrieval:1"]]}
|
|
6
|
+
|
|
7
|
+
`needs` lists alternatives. Any one of them, with all of its parts in view, is
|
|
8
|
+
enough to answer the turn. `[]` means the turn needs nothing earlier and `null`
|
|
9
|
+
means nobody could tell. A part is its ID, or `{"part_id", "quote"}` when the
|
|
10
|
+
validator should check a verbatim quote from it.
|
|
11
|
+
|
|
12
|
+
The fit reads the canonical form, which `normalize_label` produces: a
|
|
13
|
+
`status` and `task_requirements`, each with `historical_context_needed` and
|
|
14
|
+
`alternatives`. A row that already carries `task_requirements` is canonical.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import copy
|
|
20
|
+
|
|
21
|
+
from .errors import ContractError
|
|
22
|
+
from .threads import Thread
|
|
23
|
+
|
|
24
|
+
__all__ = ["build_packet", "label_index", "normalize_label", "validate_label"]
|
|
25
|
+
|
|
26
|
+
_STATUSES = ("complete", "partial", "unassessable")
|
|
27
|
+
_NEEDED = ("yes", "no", "unknown")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _status(part: dict) -> str:
|
|
31
|
+
return part.get(
|
|
32
|
+
"content_status", "available" if part.get("text") is not None else "missing"
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _available(part: dict) -> bool:
|
|
37
|
+
return _status(part) == "available" and part.get("text") is not None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _target(part: dict) -> dict:
|
|
41
|
+
"""The run's own question or answer as a labeller may see it."""
|
|
42
|
+
shown = {
|
|
43
|
+
k: v for k, v in part.items() if k in ("part_id", "text", "content_status")
|
|
44
|
+
}
|
|
45
|
+
if not _available(part):
|
|
46
|
+
shown["text"] = None
|
|
47
|
+
return shown
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def build_packet(thread: Thread | dict, target_run_id: str) -> dict:
|
|
51
|
+
"""Everything a labeller may see for one run: its question, its answer and its request.
|
|
52
|
+
|
|
53
|
+
Later runs, split names and anything outside the request are left out.
|
|
54
|
+
"""
|
|
55
|
+
if isinstance(thread, dict):
|
|
56
|
+
thread = Thread(thread)
|
|
57
|
+
if not isinstance(thread, Thread):
|
|
58
|
+
raise ContractError("thread must be Thread or dict")
|
|
59
|
+
# Read the validated thread in place. Only the packet returned below is copied.
|
|
60
|
+
data, parts = thread._data, {}
|
|
61
|
+
for run in data["runs"]:
|
|
62
|
+
for kind, items in (
|
|
63
|
+
("input", [run["input"]]),
|
|
64
|
+
("retrieval", run["retrievals"]),
|
|
65
|
+
("output", [run["output"]]),
|
|
66
|
+
):
|
|
67
|
+
for part in items:
|
|
68
|
+
entry = {
|
|
69
|
+
"part_id": part["part_id"],
|
|
70
|
+
"origin_run_id": run["run_id"],
|
|
71
|
+
"origin_run_index": run["run_index"],
|
|
72
|
+
"kind": kind,
|
|
73
|
+
"text": part.get("text") if _available(part) else None,
|
|
74
|
+
"content_status": _status(part),
|
|
75
|
+
}
|
|
76
|
+
if kind == "retrieval":
|
|
77
|
+
entry.update(
|
|
78
|
+
{k: part[k] for k in ("document_id", "version", "chunk_id")}
|
|
79
|
+
)
|
|
80
|
+
parts[part["part_id"]] = entry
|
|
81
|
+
if run["run_id"] == target_run_id:
|
|
82
|
+
visible = [parts[x] for x in run["generation"]["request_part_ids"]]
|
|
83
|
+
notes = [
|
|
84
|
+
"Visible source text unavailable: " + p["part_id"]
|
|
85
|
+
for p in visible
|
|
86
|
+
if p["text"] is None
|
|
87
|
+
]
|
|
88
|
+
if not _available(run["output"]):
|
|
89
|
+
notes.append("Target output is unavailable.")
|
|
90
|
+
return copy.deepcopy(
|
|
91
|
+
{
|
|
92
|
+
"schema_version": "compache-label-input-v1",
|
|
93
|
+
"thread_id": data["thread_id"],
|
|
94
|
+
"target_run_id": target_run_id,
|
|
95
|
+
"target_run_index": run["run_index"],
|
|
96
|
+
"target_question": _target(run["input"]),
|
|
97
|
+
"target_output": _target(run["output"]),
|
|
98
|
+
"request_parts": visible,
|
|
99
|
+
"request_coverage": "partial" if notes else "complete",
|
|
100
|
+
"coverage_notes": notes,
|
|
101
|
+
}
|
|
102
|
+
)
|
|
103
|
+
raise ContractError("target run not found: " + str(target_run_id))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _source(value) -> dict:
|
|
107
|
+
if isinstance(value, str) and value:
|
|
108
|
+
return {"part_id": value}
|
|
109
|
+
if (
|
|
110
|
+
isinstance(value, dict)
|
|
111
|
+
and isinstance(value.get("part_id"), str)
|
|
112
|
+
and not set(value) - {"part_id", "quote"}
|
|
113
|
+
):
|
|
114
|
+
return dict(value)
|
|
115
|
+
raise ContractError("a needed part is a part ID or {part_id, quote}")
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _target_run(row: dict, thread: Thread):
|
|
119
|
+
run_id = row.get("run_id", row.get("target_run_id"))
|
|
120
|
+
index = row.get("run")
|
|
121
|
+
for run in thread.runs:
|
|
122
|
+
if run.run_id == run_id or (run_id is None and run.run_index == index):
|
|
123
|
+
return run
|
|
124
|
+
raise ContractError(
|
|
125
|
+
f"label names no run of thread {thread.thread_id}: {run_id or index!r}"
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def normalize_label(row: dict, thread: Thread) -> dict:
|
|
130
|
+
"""The canonical form of one label row for a run of `thread`."""
|
|
131
|
+
if not isinstance(row, dict):
|
|
132
|
+
raise ContractError("label must be an object")
|
|
133
|
+
if "task_requirements" in row:
|
|
134
|
+
return row
|
|
135
|
+
if "needs" not in row:
|
|
136
|
+
raise ContractError("a label carries `needs`: alternatives, [] or null")
|
|
137
|
+
run = _target_run(row, thread)
|
|
138
|
+
needs = row["needs"]
|
|
139
|
+
if needs is None:
|
|
140
|
+
status, needed, alternatives = "unassessable", "unknown", []
|
|
141
|
+
elif not isinstance(needs, list):
|
|
142
|
+
raise ContractError("needs must be a list of alternatives, or null")
|
|
143
|
+
else:
|
|
144
|
+
alternatives = []
|
|
145
|
+
for alternative in needs:
|
|
146
|
+
if isinstance(alternative, (str, dict)):
|
|
147
|
+
alternative = [alternative]
|
|
148
|
+
if not isinstance(alternative, list) or not alternative:
|
|
149
|
+
raise ContractError("an alternative is a nonempty list of parts")
|
|
150
|
+
alternatives.append({"sources": [_source(s) for s in alternative]})
|
|
151
|
+
origin = thread.part_origin
|
|
152
|
+
|
|
153
|
+
def current(alternative):
|
|
154
|
+
return all(
|
|
155
|
+
origin.get(s["part_id"], (None, 0))[1] == run.run_index
|
|
156
|
+
for s in alternative["sources"]
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
# A set of this run's own parts that is enough means no history is needed.
|
|
160
|
+
needed = "no" if not alternatives or any(map(current, alternatives)) else "yes"
|
|
161
|
+
if not alternatives:
|
|
162
|
+
alternatives = [{"sources": [{"part_id": run.input.part_id}]}]
|
|
163
|
+
status = "complete"
|
|
164
|
+
return {
|
|
165
|
+
"schema_version": "compache-label-v2",
|
|
166
|
+
"thread_id": thread.thread_id,
|
|
167
|
+
"target_run_id": run.run_id,
|
|
168
|
+
"status": status,
|
|
169
|
+
"task_requirements": [
|
|
170
|
+
{
|
|
171
|
+
"requirement_id": "needs",
|
|
172
|
+
"historical_context_needed": needed,
|
|
173
|
+
"alternatives": alternatives,
|
|
174
|
+
}
|
|
175
|
+
],
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _packet_errors(packet) -> list[str]:
|
|
180
|
+
if not isinstance(packet, dict):
|
|
181
|
+
return ["packet: expected object"]
|
|
182
|
+
required = (
|
|
183
|
+
"thread_id",
|
|
184
|
+
"target_run_id",
|
|
185
|
+
"target_run_index",
|
|
186
|
+
"target_question",
|
|
187
|
+
"target_output",
|
|
188
|
+
"request_parts",
|
|
189
|
+
)
|
|
190
|
+
if any(key not in packet for key in required):
|
|
191
|
+
return ["packet: missing required fields"]
|
|
192
|
+
parts = packet["request_parts"]
|
|
193
|
+
if (
|
|
194
|
+
not isinstance(packet["target_question"], dict)
|
|
195
|
+
or not isinstance(packet["target_output"], dict)
|
|
196
|
+
or not isinstance(parts, list)
|
|
197
|
+
or type(packet["target_run_index"]) is not int
|
|
198
|
+
):
|
|
199
|
+
return ["packet: invalid question, output, index or request_parts"]
|
|
200
|
+
if any(
|
|
201
|
+
not isinstance(p, dict)
|
|
202
|
+
or not isinstance(p.get("part_id"), str)
|
|
203
|
+
or p.get("kind") not in ("input", "retrieval", "output")
|
|
204
|
+
or type(p.get("origin_run_index")) is not int
|
|
205
|
+
or (p.get("text") is not None and not isinstance(p.get("text"), str))
|
|
206
|
+
for p in parts
|
|
207
|
+
):
|
|
208
|
+
return ["packet: invalid request part"]
|
|
209
|
+
ids = [p["part_id"] for p in parts]
|
|
210
|
+
if len(ids) != len(set(ids)):
|
|
211
|
+
return ["packet: duplicate request part"]
|
|
212
|
+
target = packet["target_run_index"]
|
|
213
|
+
if (
|
|
214
|
+
packet["target_question"].get("part_id") not in ids
|
|
215
|
+
or packet["target_output"].get("part_id") in ids
|
|
216
|
+
):
|
|
217
|
+
return ["packet: current input/output visibility mismatch"]
|
|
218
|
+
if any(
|
|
219
|
+
p["origin_run_index"] > target
|
|
220
|
+
or (p["origin_run_index"] == target and p["kind"] == "output")
|
|
221
|
+
for p in parts
|
|
222
|
+
):
|
|
223
|
+
return ["packet: future or foreign source"]
|
|
224
|
+
return []
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def validate_label(label, packet) -> list[str]:
|
|
228
|
+
"""Problems with one canonical label, checked against what its run could see.
|
|
229
|
+
|
|
230
|
+
A source must be a part of the run's request with available text. A quote,
|
|
231
|
+
when given, must be found in it verbatim. `no` needs an alternative made of
|
|
232
|
+
the run's own parts, `yes` needs alternatives that each reach back. This
|
|
233
|
+
checks consistency, not whether the labeller judged the turn correctly.
|
|
234
|
+
"""
|
|
235
|
+
errors = _packet_errors(packet)
|
|
236
|
+
if errors:
|
|
237
|
+
return errors
|
|
238
|
+
if not isinstance(label, dict):
|
|
239
|
+
return ["label: expected object"]
|
|
240
|
+
for key in ("thread_id", "target_run_id"):
|
|
241
|
+
if label.get(key) != packet[key]:
|
|
242
|
+
errors.append(f"{key}: does not match packet")
|
|
243
|
+
if label.get("status") not in _STATUSES:
|
|
244
|
+
errors.append("status: expected complete, partial or unassessable")
|
|
245
|
+
requirements = label.get("task_requirements")
|
|
246
|
+
if not isinstance(requirements, list) or not all(
|
|
247
|
+
isinstance(r, dict) for r in requirements
|
|
248
|
+
):
|
|
249
|
+
return errors + ["task_requirements: expected a list of objects"]
|
|
250
|
+
parts = {p["part_id"]: p for p in packet["request_parts"]}
|
|
251
|
+
target = packet["target_run_index"]
|
|
252
|
+
names = [r.get("requirement_id") for r in requirements]
|
|
253
|
+
if len(names) != len(set(names)):
|
|
254
|
+
errors.append("duplicate task requirement IDs")
|
|
255
|
+
for requirement in requirements:
|
|
256
|
+
name = "task/" + str(requirement.get("requirement_id"))
|
|
257
|
+
needed = requirement.get("historical_context_needed")
|
|
258
|
+
alternatives = requirement.get("alternatives")
|
|
259
|
+
if needed not in _NEEDED:
|
|
260
|
+
errors.append(name + ": historical_context_needed is yes, no or unknown")
|
|
261
|
+
if not isinstance(alternatives, list):
|
|
262
|
+
errors.append(name + ": alternatives must be a list")
|
|
263
|
+
continue
|
|
264
|
+
own_parts_suffice = False
|
|
265
|
+
for alternative in alternatives:
|
|
266
|
+
sources = (
|
|
267
|
+
alternative.get("sources") if isinstance(alternative, dict) else None
|
|
268
|
+
)
|
|
269
|
+
if not isinstance(sources, list) or not sources:
|
|
270
|
+
errors.append(name + ": empty alternative is not sufficient evidence")
|
|
271
|
+
continue
|
|
272
|
+
ids = [s.get("part_id") if isinstance(s, dict) else None for s in sources]
|
|
273
|
+
if len(ids) != len(set(ids)):
|
|
274
|
+
errors.append(name + ": duplicate sources in alternative")
|
|
275
|
+
reaches_back = False
|
|
276
|
+
for source, part_id in zip(sources, ids):
|
|
277
|
+
part = parts.get(part_id)
|
|
278
|
+
if part is None:
|
|
279
|
+
errors.append(
|
|
280
|
+
f"{name}: source is absent, future, or not visible: {part_id}"
|
|
281
|
+
)
|
|
282
|
+
reaches_back = True
|
|
283
|
+
continue
|
|
284
|
+
reaches_back = reaches_back or part["origin_run_index"] < target
|
|
285
|
+
if part.get("text") is None:
|
|
286
|
+
errors.append(name + ": unavailable source content")
|
|
287
|
+
elif "quote" in source and (
|
|
288
|
+
not isinstance(source["quote"], str)
|
|
289
|
+
or not source["quote"]
|
|
290
|
+
or source["quote"] not in part["text"]
|
|
291
|
+
):
|
|
292
|
+
errors.append(f"{name}/{part_id}: quote not found verbatim")
|
|
293
|
+
own_parts_suffice = own_parts_suffice or not reaches_back
|
|
294
|
+
if needed == "no" and not own_parts_suffice:
|
|
295
|
+
errors.append(
|
|
296
|
+
name + ": no history requires a sufficient current-source alternative"
|
|
297
|
+
)
|
|
298
|
+
elif needed == "yes" and (not alternatives or own_parts_suffice):
|
|
299
|
+
errors.append(
|
|
300
|
+
name + ": history needed conflicts with sufficient alternatives"
|
|
301
|
+
)
|
|
302
|
+
return errors[:100]
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def label_index(threads: list[Thread], labels: list[dict]) -> dict:
|
|
306
|
+
"""Validated canonical labels by target run. A packet is built only for a labelled run."""
|
|
307
|
+
# Labels are keyed by run ID, so a collision between threads could leak a
|
|
308
|
+
# held-out observation.
|
|
309
|
+
thread_ids = [t.thread_id for t in threads]
|
|
310
|
+
run_ids = [r.run_id for t in threads for r in t.runs]
|
|
311
|
+
if len(set(thread_ids)) != len(thread_ids) or len(set(run_ids)) != len(run_ids):
|
|
312
|
+
raise ContractError(
|
|
313
|
+
"training/evaluation requires globally unique thread and run IDs"
|
|
314
|
+
)
|
|
315
|
+
by_id = {t.thread_id: t for t in threads}
|
|
316
|
+
owner = {r.run_id: t for t in threads for r in t.runs}
|
|
317
|
+
result = {}
|
|
318
|
+
for row in labels:
|
|
319
|
+
thread = by_id.get(row.get("thread_id")) if isinstance(row, dict) else None
|
|
320
|
+
if thread is None and isinstance(row, dict):
|
|
321
|
+
thread = owner.get(row.get("target_run_id", row.get("run_id")))
|
|
322
|
+
if thread is None:
|
|
323
|
+
raise ContractError(
|
|
324
|
+
"label targets must be unique runs in the supplied traces"
|
|
325
|
+
)
|
|
326
|
+
label = normalize_label(row, thread)
|
|
327
|
+
run_id = label.get("target_run_id")
|
|
328
|
+
if owner.get(run_id) is not thread or run_id in result:
|
|
329
|
+
raise ContractError(
|
|
330
|
+
"label targets must be unique runs in the supplied traces"
|
|
331
|
+
)
|
|
332
|
+
errors = validate_label(label, build_packet(thread, run_id))
|
|
333
|
+
if errors:
|
|
334
|
+
raise ContractError(f"invalid label for {run_id}: " + "; ".join(errors[:3]))
|
|
335
|
+
result[run_id] = label
|
|
336
|
+
return result
|
compache/langchain.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""compache for LangChain and LangGraph agents.
|
|
2
|
+
|
|
3
|
+
LangChain's chat models send through the provider SDKs, so compache goes in at
|
|
4
|
+
the same place as for the SDKs themselves: the HTTP client. What an agent adds
|
|
5
|
+
is a thread ID, and `middleware` passes it on as the conversation's name.
|
|
6
|
+
|
|
7
|
+
live = compache.Live("policy.json", record="compache-record", sample=0.1)
|
|
8
|
+
model = ChatOpenAI(model="gpt-6-luna", **compache.langchain.clients(live))
|
|
9
|
+
agent = create_agent(model, tools, middleware=[compache.langchain.middleware()])
|
|
10
|
+
agent.invoke({"messages": [...]}, {"configurable": {"thread_id": "conversation-17"}})
|
|
11
|
+
|
|
12
|
+
A chat model that takes no HTTP client, such as `ChatAnthropic`, is pointed at
|
|
13
|
+
`compache proxy` with its base URL instead.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from .live import Live
|
|
19
|
+
from .wrap import async_http_client, http_client, thread
|
|
20
|
+
|
|
21
|
+
__all__ = ["clients", "middleware"]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def clients(live: Live, *, pings: bool = True) -> dict:
|
|
25
|
+
"""The `http_client` and `http_async_client` arguments of `ChatOpenAI`, with `live` in the path.
|
|
26
|
+
|
|
27
|
+
`pings` lets a background thread send the policy's keep-warm pings.
|
|
28
|
+
"""
|
|
29
|
+
return {
|
|
30
|
+
"http_client": http_client(live, pings=pings),
|
|
31
|
+
"http_async_client": async_http_client(live, pings=pings),
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _thread_id(request) -> str | None:
|
|
36
|
+
"""The thread ID a model call runs under, from the agent's runtime or the graph's config."""
|
|
37
|
+
info = getattr(getattr(request, "runtime", None), "execution_info", None)
|
|
38
|
+
found = getattr(info, "thread_id", None)
|
|
39
|
+
if found is None:
|
|
40
|
+
try:
|
|
41
|
+
from langgraph.config import get_config
|
|
42
|
+
|
|
43
|
+
found = (get_config().get("configurable") or {}).get("thread_id")
|
|
44
|
+
except Exception:
|
|
45
|
+
found = None
|
|
46
|
+
return None if found is None else str(found)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def middleware():
|
|
50
|
+
"""An agent middleware that names every model call's conversation after the thread it runs in.
|
|
51
|
+
|
|
52
|
+
It changes nothing else, so it can go anywhere in the list.
|
|
53
|
+
"""
|
|
54
|
+
from langchain.agents.middleware import AgentMiddleware
|
|
55
|
+
|
|
56
|
+
class Compache(AgentMiddleware):
|
|
57
|
+
def wrap_model_call(self, request, handler):
|
|
58
|
+
with thread(_thread_id(request)):
|
|
59
|
+
return handler(request)
|
|
60
|
+
|
|
61
|
+
async def awrap_model_call(self, request, handler):
|
|
62
|
+
with thread(_thread_id(request)):
|
|
63
|
+
return await handler(request)
|
|
64
|
+
|
|
65
|
+
return Compache()
|