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/live.py ADDED
@@ -0,0 +1,1443 @@
1
+ """compache in the request path.
2
+
3
+ `Live` sits between an application and its model provider and sees every model
4
+ call as the JSON that goes over the wire. For each call it can do three things:
5
+
6
+ - apply a fitted policy: replace archived parts by their notice, mark the
7
+ conversation cacheable, answer the model's `reopen` calls unseen, and keep
8
+ the cache warm with pings;
9
+ - record the conversation without keeping any of its text: sizes, times and the
10
+ provider's usage, as `compache.record` describes;
11
+ - ask the model, on a sample of turns, which earlier parts its reply needed:
12
+ in a short request of its own once the reply is in, or in the reply itself,
13
+ where the note is taken out before the application sees it.
14
+
15
+ With no policy it changes nothing in the requests and only records. That is how
16
+ a workload is learned going forward when past traces cannot be read.
17
+
18
+ The application never has to notice. A request shape this module does not know
19
+ is passed through untouched. A request the provider refuses after it was
20
+ changed is sent again as the application wrote it. A note is taken out of a
21
+ reply whatever else goes wrong.
22
+
23
+ `compache.wrap` puts a `Live` inside a provider's SDK client and
24
+ `compache proxy` behind a base URL. `Live.exchange` is the one entry they share.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import hashlib
30
+ import json
31
+ import logging
32
+ import re
33
+ import threading
34
+ import time
35
+ import uuid
36
+ from collections import OrderedDict
37
+ from dataclasses import dataclass, field, replace
38
+ from pathlib import Path
39
+ from typing import Any, Callable, Iterator
40
+
41
+ from . import notes as notes_
42
+ from . import wire
43
+ from .api import Policy
44
+ from .optimizer.recovery import REOPEN_TOOL
45
+ from .record import Recorder
46
+ from .threads import cache_read_reported, canonical_usage
47
+
48
+ __all__ = ["Live", "Result"]
49
+
50
+ logger = logging.getLogger(__name__)
51
+
52
+ _REOPEN = REOPEN_TOOL["function"]["name"]
53
+ # The tool as a model in a live conversation is told about it: what a notice is, and what to do with one.
54
+ _REOPEN_TOOL = {
55
+ "type": "function",
56
+ "function": {
57
+ "name": _REOPEN,
58
+ "description": (
59
+ "Read text of this conversation that was archived to save space. An archived part "
60
+ "shows a short notice with a reference such as ctx:1a2b3c in place of its text. Give "
61
+ "that reference to read the part, or give a short distinctive phrase to search every "
62
+ "archived part for it. Use it whenever what you need is no longer visible, and before "
63
+ "telling the user that you do not have something."
64
+ ),
65
+ "parameters": {
66
+ "type": "object",
67
+ "properties": {
68
+ "reference": {
69
+ "type": "string",
70
+ "description": (
71
+ "The ctx: reference from a notice, or a few distinctive words to search "
72
+ "the archived parts for."
73
+ ),
74
+ },
75
+ "offset": {
76
+ "type": "integer",
77
+ "description": "Leave out at first. For a long part, the next_offset of the last result.",
78
+ },
79
+ },
80
+ "required": ["reference"],
81
+ "additionalProperties": False,
82
+ },
83
+ },
84
+ }
85
+ _REOPEN_HOW = (
86
+ "Earlier parts of this conversation may be archived to save space. An archived part shows a "
87
+ 'notice like [Archived to save space. Call reopen("ctx:...") to read this part.] in place of '
88
+ "its text. Nothing is lost: an archived part is still part of the conversation, and the "
89
+ "reopen tool reads it. When a question needs something that is not visible, and always "
90
+ "before you tell the user that you do not have or cannot find something, call reopen: with "
91
+ "the reference from a notice to read that part, or with a few distinctive words to search "
92
+ "all archived parts. Then answer from what it returns. Do not reopen parts you do not need, "
93
+ "and never mention archiving, notices or the reopen tool to the user."
94
+ )
95
+ _NOT_FOUND = (
96
+ "No archived part matches that. Try other or fewer distinctive words from the text you "
97
+ "need, or the reference of a notice."
98
+ )
99
+ # What a model is shown of a fetched part: its text and where it goes on, not the names parts go by here.
100
+ _SHOWN = (
101
+ "status",
102
+ "handle",
103
+ "offset",
104
+ "length",
105
+ "text",
106
+ "next_offset",
107
+ "next_reference",
108
+ "total",
109
+ "matches",
110
+ "message",
111
+ )
112
+ _HANDLE = re.compile(r"ctx:[0-9a-f]{24}")
113
+ _REFUSED = (400, 422)
114
+ # What Claude's cache marks ask for where they name no lifetime.
115
+ _FIVE_MINUTES = 300
116
+ _ROUNDS = 3
117
+ # A note is one line. The room is for a model that reasons before it writes: on Claude Haiku
118
+ # 5.5 that took a median of some 500 tokens, and more than 1,000 for one note in twelve.
119
+ _NOTE_TOKENS = 2048
120
+ # What stands in for the further pieces of a part whose first piece carries the notice.
121
+ _GONE = "…"
122
+
123
+
124
+ @dataclass
125
+ class Result:
126
+ """What came back from a provider: a status, headers, and a JSON body or a stream.
127
+
128
+ `events` is an iterator of bytes for a streamed reply. `raw` is the body as
129
+ it arrived, and is None once `json` no longer is what arrived. `close`
130
+ releases the connection of a stream that is abandoned.
131
+ """
132
+
133
+ status: int
134
+ headers: Any = None
135
+ json: Any = None
136
+ events: Iterator[bytes] | None = None
137
+ raw: bytes | None = None
138
+ close: Callable[[], None] | None = None
139
+
140
+
141
+ @dataclass(frozen=True)
142
+ class _Said:
143
+ """A reply's text, standing where the next request will carry it as a slot."""
144
+
145
+ text: str
146
+
147
+
148
+ @dataclass
149
+ class _Found:
150
+ """One retrieved part: the pieces of text of one tool result."""
151
+
152
+ slots: list
153
+
154
+ @property
155
+ def text(self) -> str:
156
+ return "\n\n".join(s.text for s in self.slots)
157
+
158
+
159
+ @dataclass
160
+ class _Segment:
161
+ """One turn of a request: the slots of its question, its retrieved parts, the slots of its answer."""
162
+
163
+ inputs: list = field(default_factory=list)
164
+ retrievals: list = field(default_factory=list)
165
+ outputs: list = field(default_factory=list)
166
+
167
+ @property
168
+ def question(self) -> str:
169
+ return "\n\n".join(s.text for s in self.inputs)
170
+
171
+ @property
172
+ def answer(self) -> str:
173
+ return "\n\n".join(s.text for s in self.outputs if s.text)
174
+
175
+
176
+ @dataclass
177
+ class _Pending:
178
+ """The turn that is being answered."""
179
+
180
+ index: int
181
+ started_at: float
182
+ ended_at: float = 0.0
183
+ turn: Any = None
184
+ retrievals: int = 0
185
+ calls: int = 0
186
+ first_usage: Any = None
187
+ last_usage: Any = None
188
+ model: str | None = None
189
+ asked: bool = False
190
+ refs: list | None = None
191
+ older: bool = False
192
+ cited: tuple = ()
193
+ # Parts the model fetched back while answering.
194
+ reopened: list = field(default_factory=list)
195
+
196
+
197
+ @dataclass
198
+ class _Conversation:
199
+ # The name its policy session and its parts go by, and the name it is recorded under.
200
+ thread_id: str
201
+ chain: str
202
+ record_id: str = ""
203
+ session: Any = None
204
+ # The cache lifetime its requests ask for, where the policy was fitted for another than the default.
205
+ lifetime: float | None = None
206
+ # Whether it is planned under a cache that lives five minutes.
207
+ five_minutes: bool = False
208
+ # Whether it can only be planned under the default, and whether its session still has to be made anew for that.
209
+ default_lifetime: bool = False
210
+ stale: bool = False
211
+ turns: int = 0
212
+ pending: _Pending | None = None
213
+ lock: Any = field(default_factory=threading.RLock)
214
+ # What a ping is built from: the dialect, the last request without mark or note, its answer, how to send.
215
+ last: tuple | None = None
216
+ pings_off: bool = False
217
+ # Whether the model has the `reopen` tool: from the first archived part on.
218
+ reopens: bool = False
219
+ # How often a turn had to be asked again as the application wrote it.
220
+ fell_back: int = 0
221
+ system_bytes: int = 0
222
+ tools_bytes: int = 0
223
+ # The latest time this conversation has seen.
224
+ at: float = float("-inf")
225
+ # When a call that was made elsewhere really happened: its start while it is prepared, then its end.
226
+ when: float | None = None
227
+ # When this process last sent the conversation this one takes up again, whole.
228
+ sent_whole: float | None = None
229
+
230
+
231
+ @dataclass
232
+ class _Call:
233
+ """One model call on its way: the conversation it belongs to and the forms of its request."""
234
+
235
+ conversation: _Conversation
236
+ dialect: Any
237
+ turns: list
238
+ chains: list
239
+ send: Callable[[Any], Result]
240
+ body: Any
241
+ plain: Any
242
+ marked: Any
243
+ outgoing: Any
244
+ asked: bool = False
245
+ carrier: str | None = None
246
+ # Ask for the note in a request of its own, once the reply is in.
247
+ apart: bool = False
248
+ # Whether a note can be asked of this call at all.
249
+ asks: bool = True
250
+
251
+
252
+ def _segments(slots) -> list[_Segment]:
253
+ """Turns of a request: a question opens one, and everything up to the next question is its."""
254
+ turns: list[_Segment] = []
255
+ waiting = []
256
+ for slot in slots:
257
+ if not slot.text and not slot.closes:
258
+ continue
259
+ if slot.kind == "input":
260
+ if not turns or turns[-1].outputs:
261
+ turns.append(_Segment(retrievals=waiting))
262
+ waiting = []
263
+ turns[-1].inputs.append(slot)
264
+ elif slot.kind == "retrieval":
265
+ found = turns[-1].retrievals if turns else waiting
266
+ if (
267
+ found
268
+ and slot.group is not None
269
+ and found[-1].slots[-1].group == slot.group
270
+ ):
271
+ # Another piece of the same tool result.
272
+ found[-1].slots.append(slot)
273
+ else:
274
+ found.append(_Found([slot]))
275
+ elif turns:
276
+ turns[-1].outputs.append(slot)
277
+ return turns
278
+
279
+
280
+ def _link(chain: str, segment: _Segment) -> str:
281
+ said = [segment.question, [s.text for s in segment.retrievals], segment.answer]
282
+ return hashlib.sha256((chain + json.dumps(said)).encode()).hexdigest()
283
+
284
+
285
+ def _size(text: str) -> int:
286
+ return len(text.encode("utf-8"))
287
+
288
+
289
+ def _notice(placeholder: str) -> str:
290
+ """The session's notice in words a model acts on: the tool to call and what to give it.
291
+
292
+ It is exactly as long as the notice it stands for, so the sizes the policy counts on hold.
293
+ """
294
+ found = _HANDLE.search(placeholder)
295
+ if found is None:
296
+ return placeholder
297
+ return (
298
+ f'[Archived to save space. Call reopen("{found.group()}") to read this part.]'
299
+ )
300
+
301
+
302
+ def _for_model(found: dict) -> dict:
303
+ """The answer to a `reopen` call as the model reads it."""
304
+ if found.get("status") == "not_found":
305
+ return {"status": "not_found", "hint": _NOT_FOUND}
306
+ shown = {k: v for k, v in found.items() if k in _SHOWN}
307
+ if isinstance(shown.get("matches"), list):
308
+ shown["matches"] = [
309
+ {k: m[k] for k in ("handle", "offset", "excerpt") if k in m}
310
+ for m in shown["matches"]
311
+ ]
312
+ return shown
313
+
314
+
315
+ def _position(part_id: str) -> tuple:
316
+ """Where a part sits in its conversation: its turn, then question, retrieved text, answer."""
317
+ head, _, tail = part_id.rpartition(":")
318
+ if tail.isdigit():
319
+ return int(head.rsplit(":", 2)[-2]), 1, int(tail)
320
+ return int(head.rsplit(":", 1)[-1]), 0 if tail == "input" else 2, 0
321
+
322
+
323
+ def _digest(value) -> str:
324
+ return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()
325
+
326
+
327
+ def _turn_usage(first, last) -> dict | None:
328
+ """One usage for a turn: the last call's input, all of its output, what the first call found cached."""
329
+ first, last = canonical_usage(first), canonical_usage(last)
330
+ if first is None or last is None or first == last:
331
+ return first or last
332
+ left = min(last["cache_read"] + last["cache_write"], last["input"])
333
+ return {
334
+ "input": last["input"],
335
+ "output": first["output"] + last["output"],
336
+ "cache_read": first["cache_read"],
337
+ "cache_write": max(0, left - first["cache_read"]) if last["cache_write"] else 0,
338
+ }
339
+
340
+
341
+ class Live:
342
+ """A policy applied, a record kept and notes asked, on every model call that passes.
343
+
344
+ `policy` is a `Policy`, a path to one, or None to change nothing and only
345
+ record. `record` is a folder for a record without text, or a `Recorder`.
346
+ `sample` is the share of turns whose reply is asked what it needed, and
347
+ `notes` says how: `"apart"` in a short request of its own after the reply,
348
+ which leaves the reply untouched by construction, or `"inline"` in the
349
+ reply itself, which saves that request and lets the note weigh on the
350
+ answer. Notes need a record to go to.
351
+ """
352
+
353
+ def __init__(
354
+ self,
355
+ policy=None,
356
+ *,
357
+ record=None,
358
+ sample: float = 0.0,
359
+ notes: str = "apart",
360
+ salt: str = "",
361
+ clock: Callable[[], float] = time.time,
362
+ max_conversations: int = 4096,
363
+ ):
364
+ if isinstance(policy, (str, Path)):
365
+ policy = Policy.load(policy)
366
+ if notes not in ("apart", "inline"):
367
+ raise ValueError("notes: expected 'apart' or 'inline'")
368
+ if not 0 <= sample <= 1:
369
+ raise ValueError("sample: expected a share between 0 and 1")
370
+ self.policy = policy
371
+ self.recorder = Recorder(record) if isinstance(record, (str, Path)) else record
372
+ if sample and self.recorder is None:
373
+ raise ValueError(
374
+ "sample: notes need a record to go to. Give `record` a folder"
375
+ )
376
+ self.sample = sample
377
+ self.notes, self.salt, self.clock = notes, salt, clock
378
+ recipe = policy.recipe if policy is not None else None
379
+ if recipe is not None and recipe.cited_answer_runs != 0 and not sample:
380
+ # Here an answer is known to cite a text only through its note.
381
+ logger.warning(
382
+ "compache: this policy keeps the text that answers cite, and no reply is asked "
383
+ "what it cited. Give `sample` the rate at which the policy's record was made."
384
+ )
385
+ self._limit = max_conversations
386
+ self._lock = threading.RLock()
387
+ self._by_chain: OrderedDict[str, _Conversation] = OrderedDict()
388
+ self._names: dict[str, int] = {}
389
+ # The conversation a name was last seen in, for a host that tells us about it by name.
390
+ self._latest: OrderedDict[str, _Conversation] = OrderedDict()
391
+ self._bad_schemas: set[str] = set()
392
+ self._refusals = 0
393
+ self._notes_off = False
394
+ self._apart: list[threading.Thread] = []
395
+ # The thread that sends the keep-warm pings, once `compache.wrap.start_pings` made one.
396
+ self.pinger = None
397
+ # What happened so far, for a caller that wants to know.
398
+ self.stats = dict.fromkeys(
399
+ (
400
+ "calls",
401
+ "passed_through",
402
+ "turns",
403
+ "asked",
404
+ "noted",
405
+ "leaked",
406
+ "retried",
407
+ "reopened",
408
+ "pings",
409
+ "policy_refused",
410
+ "fell_back",
411
+ "stood_down",
412
+ ),
413
+ 0,
414
+ )
415
+
416
+ # -- conversations -------------------------------------------------------
417
+
418
+ def _conversation(
419
+ self, thread: str | None, turns: list[_Segment]
420
+ ) -> tuple[_Conversation, list[str]]:
421
+ """The conversation a request continues, found by what it has said so far."""
422
+ seed = "thread:" + thread if thread else "auto"
423
+ chains = [hashlib.sha256(seed.encode()).hexdigest()]
424
+ for segment in turns[:-1]:
425
+ chains.append(_link(chains[-1], segment))
426
+ done = len(turns) - 1
427
+ with self._lock:
428
+ found = self._by_chain.get(chains[-1]) if thread or done else None
429
+ if found is None and done:
430
+ # Its last turn may have been answered without the answer passing here.
431
+ earlier = self._by_chain.get(chains[-2]) if thread or done > 1 else None
432
+ if (
433
+ earlier is not None
434
+ and earlier.pending is not None
435
+ and earlier.pending.index == done
436
+ ):
437
+ found = earlier
438
+ if found is None:
439
+ name = record = thread or "c-" + uuid.uuid4().hex[:16]
440
+ if thread:
441
+ # A name can be met again: after a restart, or shared by several conversations.
442
+ count = self._names[thread] = self._names.get(thread, 0) + 1
443
+ if count > 1:
444
+ name = f"{thread}#{count}"
445
+ record = thread if done else f"{thread}~{count}"
446
+ found = _Conversation(name, chains[0], record)
447
+ earlier = self._latest.get(thread) if thread else None
448
+ if earlier is not None and not earlier.reopens:
449
+ found.sent_whole = earlier.at
450
+ if self.policy is not None:
451
+ self._start(found, name)
452
+ if thread:
453
+ # A named conversation is found again from its first call. An unnamed one only
454
+ # once it has an answer, since any two may open with the same words.
455
+ self._index(found, chains[0])
456
+ else:
457
+ self._by_chain.move_to_end(found.chain)
458
+ if thread:
459
+ self._latest[thread] = found
460
+ self._latest.move_to_end(thread)
461
+ while len(self._latest) > self._limit:
462
+ self._latest.popitem(last=False)
463
+ return found, chains
464
+
465
+ def _now(self, conversation: _Conversation) -> float:
466
+ """The time, and never one this conversation has already passed: a clock can step back."""
467
+ now = self.clock() if conversation.when is None else conversation.when
468
+ conversation.at = max(now, conversation.at + 1e-3)
469
+ return conversation.at
470
+
471
+ def _index(self, conversation: _Conversation, chain: str) -> None:
472
+ with self._lock:
473
+ if self._by_chain.get(conversation.chain) is conversation:
474
+ del self._by_chain[conversation.chain]
475
+ conversation.chain = chain
476
+ self._by_chain[chain] = conversation
477
+ while len(self._by_chain) > self._limit:
478
+ self._by_chain.popitem(last=False)
479
+
480
+ # -- one model call ------------------------------------------------------
481
+
482
+ def exchange(
483
+ self,
484
+ path: str,
485
+ body: Any,
486
+ send: Callable[[Any], Result],
487
+ *,
488
+ thread: str | None = None,
489
+ ) -> Result:
490
+ """Carry one model call: `send(body)` performs it and returns a `Result`.
491
+
492
+ `path` is the request path, which says which API it is. `thread` names
493
+ the conversation. Without a name the conversation is recognized by what
494
+ it has said so far.
495
+ """
496
+ return self._exchange(path, body, send, thread)
497
+
498
+ def observe(
499
+ self,
500
+ path: str,
501
+ body: Any,
502
+ reply: Any,
503
+ *,
504
+ thread: str | None = None,
505
+ at: tuple[float, float] | None = None,
506
+ ask: Callable[[Any], Result] | None = None,
507
+ ) -> None:
508
+ """Keep the books on a model call that something else made.
509
+
510
+ `body` is the request and `reply` the response, both as JSON. `at` is
511
+ when the call went out and when its reply was in, as timestamps. `ask`
512
+ performs a request of our own, such as a note's, and returns a
513
+ `Result`; without it no note is asked. There is nothing to apply a
514
+ policy to, so a `Live` that observes has none.
515
+ """
516
+ if self.policy is not None:
517
+ raise ValueError(
518
+ "observe: a call that was already made has no request to change"
519
+ )
520
+
521
+ def send(payload):
522
+ if payload is body:
523
+ return Result(200, json=reply)
524
+ return ask(payload) if ask is not None else Result(501)
525
+
526
+ self._exchange(path, body, send, thread, at, ask is not None)
527
+
528
+ # -- a host that makes the requests itself ---------------------------------
529
+
530
+ def view(self, path: str, body: Any, *, thread: str) -> Any:
531
+ """The request as the policy would send it, for a host that sends it itself.
532
+
533
+ Such a host, an agent's context engine for one, gives the application a say
534
+ in what a request holds and in nothing else. Parts of earlier turns the
535
+ policy archived come back as their notice, and how to fetch them back joins
536
+ the system prompt. `heard` tells what the provider billed, `reopen` answers
537
+ the model's calls, and `conclude` closes the turn. `thread` names the
538
+ conversation. The request itself is left as it was.
539
+ """
540
+ if not isinstance(body, dict):
541
+ return body
542
+ dialect = wire.dialect_for(path)
543
+ try:
544
+ scan = dialect.scan(body)
545
+ turns = _segments(scan.slots)
546
+ if not turns or not scan.awaiting:
547
+ return body
548
+ conversation, chains = self._conversation(thread, turns)
549
+ except Exception:
550
+ self.stats["passed_through"] += 1
551
+ return body
552
+ with conversation.lock:
553
+ try:
554
+ call = self._prepare(
555
+ conversation, chains, dialect, body, scan, turns, None, asks=False
556
+ )
557
+ except Exception:
558
+ logger.warning(
559
+ "compache: a request was passed on unchanged", exc_info=True
560
+ )
561
+ self.stats["passed_through"] += 1
562
+ return body
563
+ self.stats["calls"] += 1
564
+ return call.plain
565
+
566
+ def heard(self, thread: str, usage: Any, *, model: str | None = None) -> None:
567
+ """What one model call of a conversation shown to `view` was billed, as the provider counts it."""
568
+ conversation = self._latest.get(thread)
569
+ if conversation is None:
570
+ return
571
+ with conversation.lock:
572
+ if conversation.pending is None:
573
+ return
574
+ conversation.pending.calls += 1
575
+ try:
576
+ self._ledger(
577
+ conversation, "answer", wire.Reply(usage=usage, model=model)
578
+ )
579
+ except Exception:
580
+ logger.warning("compache: a call was not recorded", exc_info=True)
581
+
582
+ def reopen(self, thread: str, reference: str, offset: Any = 0) -> dict:
583
+ """The answer to the model's `reopen` call in a conversation shown to `view`, as it is to be read."""
584
+ conversation = self._latest.get(thread)
585
+ if conversation is None or conversation.session is None:
586
+ return {
587
+ "status": "error",
588
+ "message": "there is nothing archived in this conversation",
589
+ }
590
+ with conversation.lock:
591
+ answers = self._reopen(
592
+ conversation,
593
+ [
594
+ {
595
+ "id": "reopen",
596
+ "arguments": {"reference": reference, "offset": offset},
597
+ }
598
+ ],
599
+ )
600
+ return json.loads(answers["reopen"])
601
+
602
+ def conclude(self, path: str, body: Any, *, thread: str) -> None:
603
+ """Close the turn that `body` ends on, where the host's own reply ended it.
604
+
605
+ `body` holds the conversation up to and including that answer. A
606
+ conversation that was never shown to `view` is not recorded, and a
607
+ turn that still waits for a tool goes on.
608
+ """
609
+ try:
610
+ dialect = wire.dialect_for(path)
611
+ scan = dialect.scan(body)
612
+ turns = _segments(scan.slots)
613
+ if not turns or not turns[-1].outputs or dialect.waits_for_tools(body):
614
+ return
615
+ conversation, chains = self._conversation(thread, turns)
616
+ with conversation.lock:
617
+ now = self._now(conversation)
618
+ self._catch_up(conversation, chains, turns, now, scan)
619
+ pending = conversation.pending
620
+ if pending is not None and pending.index == len(turns):
621
+ self._finish(
622
+ conversation, _link(chains[-1], turns[-1]), turns[-1], now
623
+ )
624
+ except Exception:
625
+ logger.warning("compache: a turn was not recorded", exc_info=True)
626
+
627
+ # -- the cache lifetime --------------------------------------------------
628
+
629
+ def _start(self, conversation, name) -> Any:
630
+ """Apply the policy to a conversation from here on. Returns the policy."""
631
+ policy = self.policy
632
+ if conversation.default_lifetime:
633
+ policy = policy.at_default_lifetime()
634
+ conversation.session = policy.session(name)
635
+ conversation.lifetime = policy.cache_lifetime
636
+ conversation.five_minutes = policy.spec.cache_ttl_seconds == _FIVE_MINUTES
637
+ return policy
638
+
639
+ @staticmethod
640
+ def _asking(conversation, body):
641
+ """A request made here, asking for the cache lifetime the conversation is planned under."""
642
+ if conversation.session is None:
643
+ return body
644
+ if conversation.lifetime is not None:
645
+ return wire.with_lifetime(body, conversation.lifetime)
646
+ return wire.with_default_lifetime(body) if conversation.five_minutes else body
647
+
648
+ @staticmethod
649
+ def _plan_default(conversation) -> None:
650
+ """Plan a conversation under the provider's default lifetime, from its next turn on."""
651
+ conversation.default_lifetime = conversation.stale = True
652
+ conversation.lifetime = None
653
+
654
+ def _lifetime_refused(self, conversation) -> None:
655
+ """The provider takes a request only under its default lifetime: so is everything planned from now on."""
656
+ logger.warning(
657
+ "compache: cache entries of %g seconds are refused, "
658
+ "planning on the provider's default from now on",
659
+ conversation.lifetime,
660
+ )
661
+ self._plan_default(conversation)
662
+ policy = self.policy
663
+ if policy is not None:
664
+ self.policy = policy.at_default_lifetime()
665
+
666
+ def _exchange(self, path, body, send, thread, at=None, asks=True) -> Result:
667
+ self.stats["calls"] += 1
668
+ dialect = wire.dialect_for(path)
669
+ try:
670
+ scan = (
671
+ dialect.scan(body)
672
+ if dialect is not None and isinstance(body, dict)
673
+ else None
674
+ )
675
+ turns = _segments(scan.slots) if scan is not None else []
676
+ if not turns or not scan.awaiting:
677
+ raise ValueError("nothing here to decide on")
678
+ scan.stream = scan.stream or wire.streams(path)
679
+ conversation, chains = self._conversation(thread, turns)
680
+ except Exception:
681
+ # A shape this does not know: the application's request goes out as it is.
682
+ self.stats["passed_through"] += 1
683
+ return send(body)
684
+ with conversation.lock:
685
+ try:
686
+ conversation.when = at[0] if at is not None else None
687
+ try:
688
+ if conversation.lifetime is not None and not wire.has_cache_mark(
689
+ dialect.with_cache_mark(body)
690
+ ):
691
+ # Nothing in this request could ask for it.
692
+ self._plan_default(conversation)
693
+ call = self._prepare(
694
+ conversation,
695
+ chains,
696
+ dialect,
697
+ body,
698
+ scan,
699
+ turns,
700
+ send,
701
+ asks,
702
+ )
703
+ except Exception:
704
+ logger.warning(
705
+ "compache: a request was passed on unchanged", exc_info=True
706
+ )
707
+ self.stats["passed_through"] += 1
708
+ return send(body)
709
+ if at is not None:
710
+ conversation.when = at[1]
711
+ return self._carry(call, scan)
712
+ finally:
713
+ conversation.when = None
714
+
715
+ def _prepare(
716
+ self, conversation, chains, dialect, body, scan, turns, send, asks=True
717
+ ) -> _Call:
718
+ """Bring the conversation up to this request and work out what to send for it."""
719
+ now, number, current = self._now(conversation), len(turns), turns[-1]
720
+ conversation.system_bytes = _size(scan.system)
721
+ conversation.tools_bytes = _size(json.dumps(scan.tools)) if scan.tools else 0
722
+ plain = body
723
+ try:
724
+ self._catch_up(conversation, chains, turns, now, scan)
725
+ pending, found = (
726
+ conversation.pending,
727
+ [slot.text for slot in current.retrievals],
728
+ )
729
+ if pending is None or pending.index != number:
730
+ conversation.last = None
731
+ pending = conversation.pending = _Pending(
732
+ number, now, retrievals=len(found)
733
+ )
734
+ if conversation.session is not None:
735
+ pending.turn = conversation.session.prepare(
736
+ current.question,
737
+ found,
738
+ at=now,
739
+ system_prompt=scan.system,
740
+ tools=scan.tools,
741
+ )
742
+ elif len(found) > pending.retrievals:
743
+ if conversation.session is not None:
744
+ pending.turn = conversation.session.extend(
745
+ pending.turn, found[pending.retrievals :]
746
+ )
747
+ pending.retrievals = len(found)
748
+ if conversation.session is not None:
749
+ plain = self._apply(conversation, dialect, body, scan, turns)
750
+ except Exception:
751
+ # The policy cannot be applied here. From now on this conversation is only recorded.
752
+ logger.warning(
753
+ "compache: policy not applied to a conversation", exc_info=True
754
+ )
755
+ self._stand_down(conversation, number, now)
756
+ plain = body
757
+ marked = (
758
+ self._asking(conversation, dialect.with_cache_mark(plain))
759
+ if conversation.session is not None
760
+ else plain
761
+ )
762
+ call = _Call(
763
+ conversation,
764
+ dialect,
765
+ turns,
766
+ chains,
767
+ send,
768
+ body,
769
+ plain,
770
+ marked,
771
+ marked,
772
+ asks=asks,
773
+ )
774
+ try:
775
+ call.outgoing, call.asked, call.carrier = self._with_note(call, scan)
776
+ except Exception:
777
+ logger.warning("compache: a note was not asked", exc_info=True)
778
+ return call
779
+
780
+ def _carry(self, call: _Call, scan) -> Result:
781
+ """Send the request, fall back to plainer forms of it if it is refused, and read the reply."""
782
+ conversation, pending = call.conversation, call.conversation.pending
783
+ result = call.send(call.outgoing)
784
+ result = self._under_default(call, result)
785
+ if result.status in _REFUSED and call.outgoing is not call.marked:
786
+ # Refused with the note in it: send it without.
787
+ self._note_refused(call)
788
+ self.stats["retried"] += 1
789
+ call.outgoing, call.asked, call.carrier = call.marked, False, None
790
+ result = self._under_default(call, call.send(call.outgoing))
791
+ if result.status in _REFUSED and call.outgoing is not call.body:
792
+ # Refused with the policy applied: send what the application wrote.
793
+ self.stats["retried"] += 1
794
+ self.stats["policy_refused"] += 1
795
+ self._stand_down(conversation, pending.index, pending.started_at)
796
+ call.plain = call.marked = call.outgoing = call.body
797
+ call.asked, call.carrier = False, None
798
+ result = call.send(call.body)
799
+ pending = conversation.pending
800
+ pending.asked = pending.asked or call.asked
801
+ if result.status >= 400 or (result.json is None and result.events is None):
802
+ return result
803
+ if result.events is not None:
804
+ return replace(result, events=self._stream(call, result))
805
+ return self._settle(call, result)
806
+
807
+ def _under_default(self, call: _Call, result: Result) -> Result:
808
+ """What became of a request. One that was refused goes out again under the default lifetime.
809
+
810
+ Only that tells whether the lifetime was why: what a provider says about it differs.
811
+ """
812
+ conversation = call.conversation
813
+ if result.status not in _REFUSED or conversation.lifetime is None:
814
+ return result
815
+ self.stats["retried"] += 1
816
+ marked = wire.without_lifetime(call.marked)
817
+ noted = call.outgoing is not call.marked
818
+ outgoing = wire.without_lifetime(call.outgoing) if noted else marked
819
+ again = call.send(outgoing)
820
+ if again.status in _REFUSED:
821
+ return result
822
+ if again.status < 400:
823
+ call.marked, call.outgoing = marked, outgoing
824
+ self._lifetime_refused(conversation)
825
+ return again
826
+
827
+ def _catch_up(self, conversation, chains, turns, now, scan) -> None:
828
+ """Bring a conversation's state up to the turns a request shows as answered."""
829
+ done = len(turns) - 1
830
+ pending = conversation.pending
831
+ renew = conversation.stale and pending is None
832
+ if conversation.turns == done and not renew:
833
+ return
834
+ if pending is not None and pending.index == done == conversation.turns + 1:
835
+ # Answered without the answer passing here: take it from the request.
836
+ last = turns[done - 1]
837
+ found = [slot.text for slot in last.retrievals]
838
+ if conversation.session is not None and len(found) > pending.retrievals:
839
+ pending.turn = conversation.session.extend(
840
+ pending.turn, found[pending.retrievals :]
841
+ )
842
+ self._finish(conversation, chains[done], last, now)
843
+ return
844
+ # A conversation met in the middle: walk the policy through what was said.
845
+ conversation.pending, conversation.turns, conversation.stale = None, 0, False
846
+ if self.policy is not None:
847
+ policy = self._start(conversation, conversation.thread_id)
848
+ # When it was said is not known, and a process that meets a conversation in the middle
849
+ # has usually just been started: the provider's cache is taken to have expired. It has
850
+ # not where this process sent the conversation itself, before a turn was asked again.
851
+ before = now - policy.spec.cache_ttl_seconds - 60
852
+ if conversation.sent_whole is not None:
853
+ before = max(before, min(conversation.sent_whole, now - 1e-3))
854
+ for k, segment in enumerate(turns[:done]):
855
+ at = before - (done - k) * 1e-3
856
+ # Behind the same instructions and tools as now, or they would look changed.
857
+ turn = conversation.session.prepare(
858
+ segment.question,
859
+ [s.text for s in segment.retrievals],
860
+ at=at,
861
+ system_prompt=scan.system,
862
+ tools=scan.tools,
863
+ )
864
+ conversation.session.complete(turn, segment.answer, at=at)
865
+ conversation.turns = done
866
+ self._index(conversation, chains[done])
867
+
868
+ def _stand_down(self, conversation, number, now) -> None:
869
+ """Stop applying the policy to a conversation. It is still recorded."""
870
+ if conversation.session is not None:
871
+ self.stats["stood_down"] += 1
872
+ conversation.session = conversation.lifetime = None
873
+ conversation.stale = False
874
+ if conversation.pending is None or conversation.pending.index != number:
875
+ conversation.pending = _Pending(number, now)
876
+ conversation.pending.turn = None
877
+
878
+ def _apply(self, conversation, dialect, body, scan, turns) -> Any:
879
+ """The request with every archived part replaced by its notice, and the tool to fetch one back."""
880
+ turn, name = conversation.pending.turn, conversation.thread_id
881
+ out = body
882
+ if turn.archived_ids:
883
+ notice = {
884
+ p.part_id: _notice(p.text)
885
+ for p in turn.parts
886
+ if p.part_id in turn.archived_ids
887
+ }
888
+ for k, segment in enumerate(turns, 1):
889
+ pieces = [
890
+ (f"{name}:{k}:input", segment.inputs),
891
+ (f"{name}:{k}:output", segment.outputs),
892
+ ]
893
+ pieces += [
894
+ (f"{name}:{k}:retrieval:{j}", found.slots)
895
+ for j, found in enumerate(segment.retrievals, 1)
896
+ ]
897
+ for part_id, slots in pieces:
898
+ if part_id in notice:
899
+ for i, slot in enumerate(slots):
900
+ out = wire.set_text(
901
+ dialect, out, slot.path, _GONE if i else notice[part_id]
902
+ )
903
+ conversation.reopens = True
904
+ can_answer = not scan.stream or dialect.Stream is not wire.TextStream
905
+ if (
906
+ conversation.reopens
907
+ and can_answer
908
+ and _REOPEN not in dialect.tool_names(body)
909
+ ):
910
+ # A model that is offered the tool while nothing is archived calls it for nothing. So it
911
+ # comes with the first notice, and stays: the first cut rewrites the request from near
912
+ # its start anyway, and after that the tool never changes what is cached.
913
+ out = dialect.with_tool(out, _REOPEN_TOOL, _REOPEN_HOW)
914
+ return out
915
+
916
+ # -- notes ---------------------------------------------------------------
917
+
918
+ def _with_note(self, call: _Call, scan):
919
+ """The request as it goes out, whether its reply is asked for a note, and how the note travels.
920
+
921
+ A note is asked apart, once the reply is in: the reply is then what it
922
+ would have been. With `notes="inline"` it rides in a reply that can be
923
+ read in full before the application sees it, as a last line of text or
924
+ as a property of a JSON schema, and a reply it spoiled is asked again
925
+ without. A streamed reply cannot be taken back once it is shown, so it
926
+ is always asked apart.
927
+ """
928
+ dialect, marked, conversation = call.dialect, call.marked, call.conversation
929
+ if not self.sample or self._notes_off or not call.asks:
930
+ return marked, False, None
931
+ sampled = notes_.sampled(
932
+ conversation.record_id, len(call.turns), self.sample, self.salt
933
+ )
934
+ schema = dialect.schema(call.body)
935
+ extended = notes_.extend_schema(schema) if schema is not None else None
936
+ if (
937
+ self.notes == "apart"
938
+ or scan.stream
939
+ # A call that was made elsewhere has gone out: only a note after it is possible.
940
+ or conversation.when is not None
941
+ # A schema that cannot take the property, or that the provider refused with it.
942
+ or (schema is not None and extended is None)
943
+ or (schema is not None and _digest(schema) in self._bad_schemas)
944
+ ):
945
+ call.apart = sampled
946
+ return marked, False, None
947
+ if schema is not None:
948
+ # On every turn, asked or not, so that the schema the provider caches stays one.
949
+ outgoing, carrier = dialect.with_schema(marked, extended), "json"
950
+ else:
951
+ outgoing, carrier = marked, "text"
952
+ if not sampled:
953
+ return outgoing, False, carrier
954
+ listing = self._listing(conversation, call.turns)
955
+ return (
956
+ dialect.with_note(outgoing, notes_.instruction(listing, carrier=carrier)),
957
+ True,
958
+ carrier,
959
+ )
960
+
961
+ def _listing(self, conversation, turns, pending=None) -> list[dict]:
962
+ """The conversation as a reply may name it. An archived part is listed without words.
963
+
964
+ `pending` is the turn the reply belongs to, for a note that is asked
965
+ once the conversation may have moved on.
966
+ """
967
+ pending = pending or conversation.pending
968
+ turn = pending.turn if pending is not None else None
969
+ gone = turn.archived_ids if turn is not None else ()
970
+ name, listing = conversation.thread_id, []
971
+ for k, segment in enumerate(turns, 1):
972
+ entry = {
973
+ "input": None if f"{name}:{k}:input" in gone else segment.question,
974
+ "retrievals": [
975
+ None if f"{name}:{k}:retrieval:{j}" in gone else slot.text
976
+ for j, slot in enumerate(segment.retrievals, 1)
977
+ ],
978
+ }
979
+ if k < len(turns):
980
+ entry["output"] = (
981
+ None if f"{name}:{k}:output" in gone else segment.answer
982
+ )
983
+ listing.append(entry)
984
+ return listing
985
+
986
+ def _note_refused(self, call: _Call) -> None:
987
+ schema = call.dialect.schema(call.body)
988
+ if schema is not None:
989
+ self._bad_schemas.add(_digest(schema))
990
+ self._refusals += 1
991
+ if self._refusals >= 3 and not self._notes_off:
992
+ self._notes_off = True
993
+ logger.warning("compache: notes switched off after three refused requests")
994
+
995
+ def _take_note(self, call: _Call, content, pending=None) -> None:
996
+ """Keep what a reply named, as labels."""
997
+ pending = pending or call.conversation.pending
998
+ if pending is None:
999
+ return
1000
+ listing = self._listing(call.conversation, call.turns, pending)
1001
+ note = notes_.resolve(content, listing, call.conversation.thread_id)
1002
+ pending.refs, pending.older, pending.cited = (
1003
+ notes_.labels_of(note),
1004
+ note.older,
1005
+ note.cited,
1006
+ )
1007
+ self.stats["noted"] += 1
1008
+ self._refusals = 0
1009
+
1010
+ def _without_note(self, call: _Call, data):
1011
+ """A whole reply with its note taken out, and the note. Touches no state, so it cannot fail halfway."""
1012
+ dialect, found = call.dialect, None
1013
+ reply = dialect.reply(data)
1014
+ if call.carrier == "text":
1015
+ for path in reply.paths:
1016
+ clean, got = notes_.read(wire.get(data, path))
1017
+ if got is not None:
1018
+ data, found = wire.put(data, path, clean), got
1019
+ if found is not None:
1020
+ data = dialect.prune(data)
1021
+ elif call.carrier == "json" and reply.paths:
1022
+ clean, labels = notes_.split_json(wire.get(data, reply.paths[0]))
1023
+ if labels is not None:
1024
+ data, found = wire.put(data, reply.paths[0], clean), labels
1025
+ return data, found
1026
+
1027
+ # -- replies -------------------------------------------------------------
1028
+
1029
+ def _settle(self, call: _Call, result: Result, kind: str = "answer") -> Result:
1030
+ """Read a whole reply: answer `reopen` calls, take the note out, and keep the books."""
1031
+ conversation, dialect = call.conversation, call.dialect
1032
+ data, sent, rounds = result.json, call.outgoing, 0
1033
+ try:
1034
+ reply = dialect.reply(data)
1035
+ self._ledger(conversation, kind, reply)
1036
+ while (
1037
+ conversation.session is not None
1038
+ and reply.calls
1039
+ and all(c["name"] == _REOPEN for c in reply.calls)
1040
+ ):
1041
+ rounds += 1
1042
+ if rounds > _ROUNDS:
1043
+ break
1044
+ answers = self._reopen(conversation, reply.calls)
1045
+ sent = self._asking(
1046
+ conversation, dialect.after_tools(sent, data, answers)
1047
+ )
1048
+ again = call.send(sent)
1049
+ if again.status >= 400 or again.json is None:
1050
+ return again
1051
+ result, data = again, again.json
1052
+ reply = dialect.reply(data)
1053
+ self._ledger(conversation, "reopen", reply)
1054
+ # A reply asked for a note that says nothing is asked again without the note first.
1055
+ if call.outgoing is not call.body and (
1056
+ rounds > _ROUNDS or not (call.asked or reply.text or reply.calls)
1057
+ ):
1058
+ # The model goes on fetching, or says nothing: what it was shown does not do for
1059
+ # this turn. It is asked once more, exactly as the application wrote it.
1060
+ again = self._as_written(call)
1061
+ if again.status >= 400 or again.json is None:
1062
+ return again
1063
+ result, data = again, again.json
1064
+ reply = dialect.reply(data)
1065
+ self._ledger(conversation, "retry", reply)
1066
+ if any(c["name"] == _REOPEN for c in reply.calls):
1067
+ # Called beside the application's own tools: the application never sees ours.
1068
+ data = dialect.without_tool(data, _REOPEN)
1069
+ except Exception:
1070
+ logger.warning("compache: a reply was not read", exc_info=True)
1071
+ try:
1072
+ data, found = self._without_note(call, data)
1073
+ except Exception:
1074
+ logger.warning("compache: a reply was passed on as it came", exc_info=True)
1075
+ return result
1076
+ try:
1077
+ reply = dialect.reply(data)
1078
+ if call.outgoing is not call.marked and self._spoiled(call, reply, found):
1079
+ # The note got in the way of the answer: ask again without it.
1080
+ self.stats["retried"] += 1
1081
+ again = call.send(call.marked)
1082
+ if again.status < 400 and again.json is not None:
1083
+ plain = replace(
1084
+ call, outgoing=call.marked, asked=False, carrier=None
1085
+ )
1086
+ return self._settle(plain, again, "retry")
1087
+ if found is not None and call.asked:
1088
+ self._take_note(call, found)
1089
+ self._after(call, reply.text, reply.calls)
1090
+ except Exception:
1091
+ logger.warning("compache: a reply was not recorded", exc_info=True)
1092
+ # `raw` stays with a body that was not touched, so that it can go back byte for byte.
1093
+ return result if data is result.json else replace(result, json=data, raw=None)
1094
+
1095
+ def _spoiled(self, call: _Call, reply, found) -> bool:
1096
+ """Whether a reply that was asked for a note is not what it would have been without.
1097
+
1098
+ A label where the reader would see it, a property that could not be
1099
+ cut out, nothing left once the note is out, or an answer the output
1100
+ limit ended: the note took room the answer may have needed.
1101
+ """
1102
+ if call.carrier == "json":
1103
+ return f'"{notes_.KEY}"' in reply.text or (call.asked and reply.cut)
1104
+ if not call.asked:
1105
+ return False
1106
+ if found is not None and notes_.leaked(reply.text):
1107
+ self.stats["leaked"] += 1
1108
+ return True
1109
+ return reply.cut or not (reply.text or reply.calls)
1110
+
1111
+ def _stream(self, call: _Call, result: Result) -> Iterator[bytes]:
1112
+ """A streamed reply passed on as it arrives, with our own tool calls answered on the way."""
1113
+ conversation, dialect = call.conversation, call.dialect
1114
+ tool = _REOPEN if conversation.session is not None else None
1115
+ editor = dialect.Stream(dialect, tool)
1116
+ sent, rounds, events, closers = call.outgoing, 0, result.events, [result.close]
1117
+ kind, counted = "answer", False
1118
+ try:
1119
+ while True:
1120
+ for raw, name, data in wire.sse_events(events):
1121
+ yield from editor.feed(raw, name, data)
1122
+ if not editor.again or kind == "retry":
1123
+ break
1124
+ rounds += 1
1125
+ with conversation.lock:
1126
+ self._ledger(conversation, kind, editor)
1127
+ if rounds > _ROUNDS:
1128
+ # The model goes on fetching: it is asked as the application wrote it.
1129
+ again, kind = self._as_written(call), "retry"
1130
+ else:
1131
+ answers = self._reopen(conversation, editor.ours)
1132
+ sent = self._asking(
1133
+ conversation,
1134
+ dialect.after_tools(sent, editor.said, answers),
1135
+ )
1136
+ again, kind = call.send(sent), "reopen"
1137
+ closers.append(again.close)
1138
+ if again.status >= 400 or again.events is None:
1139
+ # No further round came: the one before it is already in the books.
1140
+ counted = True
1141
+ break
1142
+ events = again.events
1143
+ editor.next_round()
1144
+ yield from editor.end()
1145
+ finally:
1146
+ for close in closers:
1147
+ if close is not None:
1148
+ close()
1149
+ with conversation.lock:
1150
+ try:
1151
+ if not counted:
1152
+ self._ledger(conversation, kind, editor)
1153
+ if editor.finished:
1154
+ self._after(call, editor.text, editor.calls)
1155
+ except Exception:
1156
+ logger.warning(
1157
+ "compache: a streamed reply was not recorded", exc_info=True
1158
+ )
1159
+
1160
+ def _as_written(self, call: _Call) -> Result:
1161
+ """Send the application's own request for a turn the policy's view did not do for.
1162
+
1163
+ A conversation that needs this twice is left alone from then on: its
1164
+ users should not wait for fetches that lead nowhere.
1165
+ """
1166
+ conversation = call.conversation
1167
+ self.stats["retried"] += 1
1168
+ self.stats["fell_back"] += 1
1169
+ conversation.fell_back += 1
1170
+ call.asked, call.carrier = False, None
1171
+ result = call.send(call.body)
1172
+ if conversation.fell_back >= 2 and conversation.session is not None:
1173
+ pending = conversation.pending
1174
+ self._stand_down(conversation, pending.index, pending.started_at)
1175
+ return result
1176
+
1177
+ def _reopen(self, conversation, calls) -> dict:
1178
+ """Answers to the model's `reopen` calls, by call ID."""
1179
+ answers = {}
1180
+ for call in calls:
1181
+ self.stats["reopened"] += 1
1182
+ arguments = call.get("arguments") or {}
1183
+ try:
1184
+ # An application may paste what it retrieved into its questions: search those too.
1185
+ found = conversation.session.reopen(
1186
+ str(arguments.get("reference", "")),
1187
+ int(arguments.get("offset") or 0),
1188
+ search=("retrieval", "input", "output"),
1189
+ )
1190
+ except Exception as error:
1191
+ found = {"status": "error", "message": str(error)}
1192
+ pending = conversation.pending
1193
+ if pending is not None and found.get("status") == "ok":
1194
+ part = found.get("part_id")
1195
+ if part and part not in pending.reopened:
1196
+ pending.reopened.append(part)
1197
+ answers[call["id"]] = json.dumps(_for_model(found), ensure_ascii=False)
1198
+ return answers
1199
+
1200
+ def _after(self, call: _Call, text: str, calls) -> None:
1201
+ """A reply has been read: the turn goes on with tool calls, or ends with this answer."""
1202
+ conversation, pending = call.conversation, call.conversation.pending
1203
+ if pending is None:
1204
+ return
1205
+ pending.calls += 1
1206
+ if calls:
1207
+ # The application runs its tools and comes back with their results.
1208
+ return
1209
+ current = call.turns[-1]
1210
+ closed = replace(
1211
+ current,
1212
+ outputs=[*current.outputs, _Said(text)] if text else current.outputs,
1213
+ )
1214
+ if pending.asked:
1215
+ self.stats["asked"] += 1
1216
+ self._finish(
1217
+ conversation,
1218
+ _link(call.chains[-1], closed),
1219
+ closed,
1220
+ self._now(conversation),
1221
+ )
1222
+ # A ping is built from the last request, which is kept only while one is planned.
1223
+ planned = (
1224
+ conversation.session is not None
1225
+ and not conversation.stale
1226
+ and conversation.session.next_ping_at
1227
+ )
1228
+ conversation.last = (
1229
+ (call.dialect, call.plain, text, call.send) if planned else None
1230
+ )
1231
+ if call.apart and not self._notes_off:
1232
+ self.stats["asked"] += 1
1233
+ worker = threading.Thread(
1234
+ target=self._ask_apart, args=(call, closed, pending), daemon=True
1235
+ )
1236
+ self._apart = [t for t in self._apart if t.is_alive()] + [worker]
1237
+ worker.start()
1238
+
1239
+ def _ask_apart(self, call: _Call, closed: _Segment, pending: _Pending) -> None:
1240
+ """Ask in a request of its own what the reply needed, and add the answer to the record."""
1241
+ conversation, dialect = call.conversation, call.dialect
1242
+ try:
1243
+ listing = self._listing(conversation, call.turns, pending)
1244
+ text = closed.outputs[-1].text if closed.outputs else ""
1245
+ # In plain text, whatever form the application asked its own answer in.
1246
+ body = dialect.follow_up(
1247
+ dialect.without_schema(call.marked),
1248
+ text,
1249
+ notes_.instruction(listing, carrier="apart"),
1250
+ _NOTE_TOKENS,
1251
+ )
1252
+ if body is None:
1253
+ return
1254
+ reply = self._whole(dialect, call.send(self._asking(conversation, body)))
1255
+ if reply is None:
1256
+ self._note_refused(call)
1257
+ return
1258
+ _, found = notes_.read(reply.text)
1259
+ with conversation.lock:
1260
+ self._ledger(conversation, "note", reply, pending.index)
1261
+ if found is None:
1262
+ return
1263
+ pending.asked = True
1264
+ self._take_note(call, found, pending)
1265
+ self._write_turn(conversation, pending, closed, pending.ended_at)
1266
+ except Exception:
1267
+ logger.warning("compache: a note was not asked", exc_info=True)
1268
+
1269
+ @staticmethod
1270
+ def _whole(dialect, result: Result):
1271
+ """The reply to a request of our own, read in full. None if the provider refused it.
1272
+
1273
+ It comes as JSON, or as a stream where the path always streams: that is read to its end.
1274
+ """
1275
+ if result.status >= 400:
1276
+ return None
1277
+ if result.json is not None:
1278
+ return dialect.reply(result.json)
1279
+ if result.events is None:
1280
+ return None
1281
+ editor = dialect.Stream(dialect)
1282
+ try:
1283
+ for raw, name, data in wire.sse_events(result.events):
1284
+ editor.feed(raw, name, data)
1285
+ finally:
1286
+ if result.close is not None:
1287
+ result.close()
1288
+ return editor
1289
+
1290
+ def drain(self, timeout: float | None = None) -> None:
1291
+ """Wait for notes that are being asked apart."""
1292
+ for worker in self._apart:
1293
+ worker.join(timeout)
1294
+
1295
+ def _finish(self, conversation, chain, segment, now) -> None:
1296
+ """Close the pending turn: tell the policy, write the record, and index what was said."""
1297
+ pending = conversation.pending
1298
+ pending.ended_at = max(now, pending.started_at)
1299
+ if conversation.session is not None and pending.turn is not None:
1300
+ visible = {
1301
+ p.part_id
1302
+ for p in pending.turn.parts
1303
+ if p.kind == "retrieval" and p.part_id not in pending.turn.archived_ids
1304
+ }
1305
+ try:
1306
+ conversation.session.complete(
1307
+ pending.turn,
1308
+ segment.answer,
1309
+ at=pending.ended_at,
1310
+ usage=pending.first_usage,
1311
+ last_usage=pending.last_usage if pending.calls > 1 else None,
1312
+ cited_part_ids=[i for i in pending.cited if i in visible],
1313
+ )
1314
+ except Exception:
1315
+ logger.warning(
1316
+ "compache: a turn was not taken by the policy", exc_info=True
1317
+ )
1318
+ self.stats["stood_down"] += 1
1319
+ conversation.session = conversation.lifetime = None
1320
+ self._write_turn(conversation, pending, segment, pending.ended_at)
1321
+ self.stats["turns"] += 1
1322
+ conversation.turns, conversation.pending = pending.index, None
1323
+ self._index(conversation, chain)
1324
+
1325
+ def _write_turn(self, conversation, pending, segment, ended_at) -> None:
1326
+ if self.recorder is None:
1327
+ return
1328
+ self.recorder.turn(
1329
+ conversation.record_id,
1330
+ pending.index,
1331
+ started_at=pending.started_at,
1332
+ ended_at=ended_at,
1333
+ model=pending.model,
1334
+ sizes={
1335
+ "input": _size(segment.question),
1336
+ "retrievals": [_size(s.text) for s in segment.retrievals],
1337
+ "output": _size(segment.answer),
1338
+ "system": conversation.system_bytes,
1339
+ "tools": conversation.tools_bytes,
1340
+ },
1341
+ usage=_turn_usage(pending.first_usage, pending.last_usage),
1342
+ read_reported=cache_read_reported(pending.first_usage),
1343
+ calls=max(1, pending.calls),
1344
+ asked=pending.asked,
1345
+ refs=self._named(pending),
1346
+ older=pending.older,
1347
+ )
1348
+
1349
+ @staticmethod
1350
+ def _named(pending) -> list | None:
1351
+ """What a turn's note named, and what its reply fetched back: it needed that too."""
1352
+ if pending.refs is None or not pending.reopened:
1353
+ return pending.refs
1354
+ fetched = notes_.labels_of(notes_.Note(needs=tuple(pending.reopened)))
1355
+ return list(dict.fromkeys([*pending.refs, *fetched]))
1356
+
1357
+ def _ledger(self, conversation, kind, source, turn=None) -> None:
1358
+ """Count one model call. `source` has the `usage`, `cost` and `model` of its reply."""
1359
+ pending = conversation.pending
1360
+ if pending is not None and kind in ("answer", "reopen", "retry"):
1361
+ if pending.first_usage is None:
1362
+ pending.first_usage = source.usage
1363
+ pending.last_usage = source.usage
1364
+ pending.model = source.model or pending.model
1365
+ if self.recorder is None:
1366
+ return
1367
+ archived = None
1368
+ if turn is None:
1369
+ turn = pending.index if pending is not None else conversation.turns
1370
+ if pending is not None and pending.turn is not None and kind != "ping":
1371
+ gone = sorted(pending.turn.archived_ids, key=_position)
1372
+ archived = notes_.labels_of(notes_.Note(needs=tuple(gone)))
1373
+ self.recorder.call(
1374
+ conversation.record_id,
1375
+ turn,
1376
+ kind,
1377
+ at=self.clock() if conversation.when is None else conversation.when,
1378
+ model=source.model,
1379
+ usage=canonical_usage(source.usage),
1380
+ cost=source.cost,
1381
+ archived=archived,
1382
+ )
1383
+
1384
+ # -- pings ---------------------------------------------------------------
1385
+
1386
+ def next_ping_at(self) -> float | None:
1387
+ """When the earliest keep-warm ping of any conversation is due, or None."""
1388
+ with self._lock:
1389
+ waiting = [c for c in self._by_chain.values() if self._may_ping(c)]
1390
+ due = [c.session.next_ping_at for c in waiting]
1391
+ return min((at for at in due if at is not None), default=None)
1392
+
1393
+ @staticmethod
1394
+ def _may_ping(conversation) -> bool:
1395
+ return (
1396
+ conversation.session is not None
1397
+ and conversation.last is not None
1398
+ and conversation.pending is None
1399
+ and not conversation.pings_off
1400
+ )
1401
+
1402
+ def tick(self, now: float | None = None) -> int:
1403
+ """Send the keep-warm pings that are due. Returns how many went out."""
1404
+ now = self.clock() if now is None else now
1405
+ with self._lock:
1406
+ candidates = [c for c in self._by_chain.values() if self._may_ping(c)]
1407
+ sent = 0
1408
+ for conversation in candidates:
1409
+ if not conversation.lock.acquire(blocking=False):
1410
+ continue
1411
+ try:
1412
+ sent += self._ping(conversation, now)
1413
+ except Exception:
1414
+ logger.warning("compache: a keep-warm ping failed", exc_info=True)
1415
+ conversation.pings_off = True
1416
+ finally:
1417
+ conversation.lock.release()
1418
+ return sent
1419
+
1420
+ def _ping(self, conversation, now) -> int:
1421
+ session = conversation.session
1422
+ if not self._may_ping(conversation):
1423
+ return 0
1424
+ due = session.next_ping_at
1425
+ if due is None or due > now or session.ping(at=now) is None:
1426
+ return 0
1427
+ dialect, plain, answer, send = conversation.last
1428
+ body = dialect.follow_up(plain, answer, ".", 1)
1429
+ if body is None:
1430
+ conversation.pings_off = True
1431
+ return 0
1432
+ reply, usage = (
1433
+ self._whole(dialect, send(self._asking(conversation, body))),
1434
+ None,
1435
+ )
1436
+ if reply is not None:
1437
+ usage = reply.usage
1438
+ self._ledger(conversation, "ping", reply)
1439
+ else:
1440
+ conversation.pings_off = True
1441
+ session.ping_sent(at=now, usage=usage, completed_at=max(now, self.clock()))
1442
+ self.stats["pings"] += 1
1443
+ return 1