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/defaults.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""A policy for when there is nothing to fit on yet.
|
|
2
|
+
|
|
3
|
+
compache fits a policy to your own conversations. Before any are recorded,
|
|
4
|
+
`default_policy` gives one fitted to a default workload instead: the one the
|
|
5
|
+
cost calculator opens with. It is a place to start from while a record of your
|
|
6
|
+
own traffic builds up, not a substitute for it: a default is one point, and
|
|
7
|
+
your workload is somewhere else.
|
|
8
|
+
|
|
9
|
+
policy = compache.default_policy("claude-sonnet-5-5")
|
|
10
|
+
client = compache.wrap(client, policy, record="compache-record", sample=0.1)
|
|
11
|
+
...
|
|
12
|
+
policy = compache.fit("compache-record") # once there is enough of it
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import math
|
|
18
|
+
import random
|
|
19
|
+
|
|
20
|
+
from .api import Policy, fit
|
|
21
|
+
from .record import SIZES_ONLY
|
|
22
|
+
|
|
23
|
+
__all__ = ["WORKLOAD", "default_policy", "default_workload"]
|
|
24
|
+
|
|
25
|
+
# The calculator's default workload (site/engine.mjs). Sizes in tokens, delays in minutes.
|
|
26
|
+
# `needs` gives, per kind of part, the chance that a turn needs one from an earlier turn
|
|
27
|
+
# and how many turns back it lies: median and 95th percentile, as measured on DocChat.
|
|
28
|
+
WORKLOAD = {
|
|
29
|
+
"threads": 40,
|
|
30
|
+
"turns": (8, 20),
|
|
31
|
+
"question_tokens": 200,
|
|
32
|
+
"retrieved_tokens": (25_000, 45_000),
|
|
33
|
+
"answer_tokens": 500,
|
|
34
|
+
"system_tokens": 2_048,
|
|
35
|
+
"away_minutes": (4, 60),
|
|
36
|
+
"answer_seconds": 5,
|
|
37
|
+
"needs": {
|
|
38
|
+
"input": (0.15, 1, 20),
|
|
39
|
+
"retrieval": (0.15, 3, 30),
|
|
40
|
+
"output": (0.20, 1, 35),
|
|
41
|
+
},
|
|
42
|
+
}
|
|
43
|
+
_Z95 = 1.6448536269514722
|
|
44
|
+
_START = 1_767_225_600 # 2026-01-01T00:00:00Z
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _lognormal(rng: random.Random, median: float, p95: float) -> float:
|
|
48
|
+
sigma = math.log(p95 / median) / _Z95 if p95 > median else 0.0
|
|
49
|
+
return median * math.exp(sigma * rng.gauss(0, 1))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def default_workload(seed: int = 42, **changes) -> tuple[list[dict], list[dict]]:
|
|
53
|
+
"""Threads and labels drawn from the default workload. `changes` replace entries of `WORKLOAD`.
|
|
54
|
+
|
|
55
|
+
The threads carry sizes, not text, as a record of `compache.record` does.
|
|
56
|
+
The same seed always gives the same threads.
|
|
57
|
+
"""
|
|
58
|
+
given = {**WORKLOAD, **changes}
|
|
59
|
+
rng = random.Random(seed)
|
|
60
|
+
threads, labels = [], []
|
|
61
|
+
for i in range(given["threads"]):
|
|
62
|
+
name = f"default-{i:03d}"
|
|
63
|
+
turns = max(1, min(160, round(_lognormal(rng, *given["turns"]))))
|
|
64
|
+
at, runs = _START + i * 86_400, []
|
|
65
|
+
for n in range(1, turns + 1):
|
|
66
|
+
if n > 1:
|
|
67
|
+
at += 60 * _lognormal(rng, *given["away_minutes"])
|
|
68
|
+
end = at + given["answer_seconds"]
|
|
69
|
+
runs.append(
|
|
70
|
+
{
|
|
71
|
+
"started_at": round(at, 3),
|
|
72
|
+
"ended_at": round(end, 3),
|
|
73
|
+
"input": {"bytes": 4 * given["question_tokens"]},
|
|
74
|
+
"retrievals": [
|
|
75
|
+
{
|
|
76
|
+
"bytes": 4
|
|
77
|
+
* round(_lognormal(rng, *given["retrieved_tokens"]))
|
|
78
|
+
}
|
|
79
|
+
],
|
|
80
|
+
"output": {"bytes": 4 * given["answer_tokens"]},
|
|
81
|
+
}
|
|
82
|
+
)
|
|
83
|
+
at = end
|
|
84
|
+
needed = []
|
|
85
|
+
for kind, (chance, back, back_p95) in given["needs"].items():
|
|
86
|
+
if n > 1 and rng.random() < chance:
|
|
87
|
+
lag = max(1, round(_lognormal(rng, back, back_p95)))
|
|
88
|
+
if lag < n:
|
|
89
|
+
suffix = "retrieval:1" if kind == "retrieval" else kind
|
|
90
|
+
needed.append(f"{name}:{n - lag}:{suffix}")
|
|
91
|
+
labels.append(
|
|
92
|
+
{"thread_id": name, "run": n, "needs": [needed] if needed else []}
|
|
93
|
+
)
|
|
94
|
+
threads.append(
|
|
95
|
+
{
|
|
96
|
+
"thread_id": name,
|
|
97
|
+
"provenance": SIZES_ONLY,
|
|
98
|
+
"system_bytes": 4 * given["system_tokens"],
|
|
99
|
+
"runs": runs,
|
|
100
|
+
}
|
|
101
|
+
)
|
|
102
|
+
return threads, labels
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def default_policy(model, *, seed: int = 42, **changes) -> Policy:
|
|
106
|
+
"""The policy fitted to the default workload, for `model`.
|
|
107
|
+
|
|
108
|
+
`model` is a known model name or a model spec, as for `fit`. `changes`
|
|
109
|
+
replace entries of `WORKLOAD`, for a default that is nearer to what you
|
|
110
|
+
expect, such as `retrieved_tokens=(4_000, 9_000)`.
|
|
111
|
+
"""
|
|
112
|
+
threads, labels = default_workload(seed, **changes)
|
|
113
|
+
return fit(threads, labels, model=model)
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
{"thread_id": "tts-performance-management-s1", "run": 1, "needs": []}
|
|
2
|
+
{"thread_id": "tts-performance-management-s1", "run": 2, "needs": []}
|
|
3
|
+
{"thread_id": "tts-performance-management-s1", "run": 3, "needs": [[{"part_id": "tts-performance-management-s1:2:input", "quote": "When should I sit down with my team for end-of-year check-ins, and what's the deadline for wrapping up their FY25 goals in HR Links?"}], [{"part_id": "tts-performance-management-s1:2:output", "quote": "Supervisors hold the end-of-year one-on-one meetings with their direct reports between October 23 and November 7, 2025. If those meetings don't close out the FY25 plans, TTS's internal deadline is Nov"}], [{"part_id": "tts-performance-management-s1:2:retrieval:2", "quote": "Oct 23 - Nov 7, 2025 | Supervisors hold 1:1 performance review meetings with their direct reports"}]]}
|
|
4
|
+
{"thread_id": "tts-performance-management-s1", "run": 4, "needs": [[{"part_id": "tts-performance-management-s1:3:input", "quote": "And before those 1:1s, when do my reports need their own self-review done?"}, {"part_id": "tts-performance-management-s1:3:output", "quote": "The handbook asks employees to begin their self-assessments starting October 1, 2025, and the self-assessment submittal is due October 17, 2025. After that, there is an audit of self-assessment comple"}, {"part_id": "tts-performance-management-s1:4:retrieval:6", "quote": "What is currently underway?"}]]}
|
|
5
|
+
{"thread_id": "tts-performance-management-s1", "run": 5, "needs": []}
|
|
6
|
+
{"thread_id": "tts-performance-management-s1", "run": 6, "needs": [[{"part_id": "tts-performance-management-s1:5:input", "quote": "Once I start writing up notes on my team, is there anything I should keep in mind about how they get stored?"}, {"part_id": "tts-performance-management-s1:5:output", "quote": "The handbook says to take notes on nearly everything, typed in a Google Doc or handwritten, and then review them later to organize them into themes, turn them into action items, and flag follow-ups. I"}, {"part_id": "tts-performance-management-s1:6:retrieval:6", "quote": "Lastly, ask questions in the most open channel possible; default to asking about"}]]}
|
|
7
|
+
{"thread_id": "tts-performance-management-s1", "run": 7, "needs": []}
|
|
8
|
+
{"thread_id": "tts-performance-management-s1", "run": 8, "needs": []}
|
|
9
|
+
{"thread_id": "tts-performance-management-s1", "run": 9, "needs": [[{"part_id": "tts-performance-management-s1:6:retrieval:6", "quote": "Lastly, ask questions in the most open channel possible; default to asking about"}]]}
|
|
10
|
+
{"thread_id": "tts-performance-management-s1", "run": 10, "needs": [[{"part_id": "tts-performance-management-s1:1:output", "quote": "Only supervisors can officially submit a participant reviewer nomination in HR Links."}, {"part_id": "tts-performance-management-s1:8:output", "quote": "The handbook gives one example: asking fellow supervisors how they handle performance reviews with union employees, or how they gather feedback from their direct reports. Questions like these are a go"}, {"part_id": "tts-performance-management-s1:9:output", "quote": "No, the handbook says you don't need to act right away unless the problem is an immediate emergency."}]]}
|
|
11
|
+
{"thread_id": "tts-performance-management-m1", "run": 1, "needs": null}
|
|
12
|
+
{"thread_id": "tts-performance-management-m1", "run": 2, "needs": []}
|
|
13
|
+
{"thread_id": "tts-performance-management-m1", "run": 3, "needs": [[{"part_id": "tts-performance-management-m1:2:input", "quote": "One of my people sent me their self-assessment for the mid-year, and now they want to pull it back to make some changes. I haven't finished their mid-year review yet. Are they allowed to do that?"}, {"part_id": "tts-performance-management-m1:2:output", "quote": "Yes. The handbook says an employee can \"stop sharing\" their self-assessment with you to make adjustments, as long as your mid-year for them has not been completed. Since you haven't finished their rev"}, {"part_id": "tts-performance-management-m1:3:retrieval:6", "quote": "Awards – Learn about the available awards within GSA."}]]}
|
|
14
|
+
{"thread_id": "tts-performance-management-m1", "run": 4, "needs": []}
|
|
15
|
+
{"thread_id": "tts-performance-management-m1", "run": 5, "needs": []}
|
|
16
|
+
{"thread_id": "tts-performance-management-m1", "run": 6, "needs": []}
|
|
17
|
+
{"thread_id": "tts-performance-management-m1", "run": 7, "needs": [[{"part_id": "tts-performance-management-m1:6:input", "quote": "For me, with five people across two zones, what does the handbook suggest if the work I hand out starts missing due dates?"}, {"part_id": "tts-performance-management-m1:6:output", "quote": "The delegation case studies under Play 7 give a scenario rather than a set answer. In it, tasks are running late, and the team says they feel burned out and overwhelmed by competing demands. The handb"}, {"part_id": "tts-performance-management-m1:7:retrieval:5", "quote": "During your routine 1:1s, ask how people are."}]]}
|
|
18
|
+
{"thread_id": "tts-performance-management-m1", "run": 8, "needs": []}
|
|
19
|
+
{"thread_id": "tts-performance-management-m1", "run": 9, "needs": []}
|
|
20
|
+
{"thread_id": "tts-performance-management-m1", "run": 10, "needs": []}
|
|
21
|
+
{"thread_id": "tts-performance-management-m1", "run": 11, "needs": []}
|
|
22
|
+
{"thread_id": "tts-performance-management-m1", "run": 12, "needs": []}
|
|
23
|
+
{"thread_id": "tts-performance-management-m1", "run": 13, "needs": [[{"part_id": "tts-performance-management-m1:12:input", "quote": "Which performance management courses does the handbook point supervisors to? I'm new and want to know where to start."}, {"part_id": "tts-performance-management-m1:12:output", "quote": "The online Performance Management Program covers an overview refresher, cascading goals, writing SMART performance plans, writing self-assessments, planning an effective appraisal (newly added), and a"}, {"part_id": "tts-performance-management-m1:13:retrieval:6", "quote": "There is no magic formula for delegation."}]]}
|
|
24
|
+
{"thread_id": "tts-performance-management-m1", "run": 14, "needs": [[{"part_id": "tts-performance-management-m1:13:retrieval:6", "quote": "There is no magic formula for delegation."}]]}
|
|
25
|
+
{"thread_id": "tts-performance-management-m1", "run": 15, "needs": []}
|
|
26
|
+
{"thread_id": "tts-performance-management-m1", "run": 16, "needs": [[{"part_id": "tts-performance-management-m1:12:input", "quote": "Which performance management courses does the handbook point supervisors to? I'm new and want to know where to start."}]]}
|
|
27
|
+
{"thread_id": "tts-performance-management-m1", "run": 17, "needs": []}
|
|
28
|
+
{"thread_id": "tts-performance-management-m1", "run": 18, "needs": []}
|
|
29
|
+
{"thread_id": "tts-performance-management-m1", "run": 19, "needs": null}
|
|
30
|
+
{"thread_id": "tts-performance-management-m1", "run": 20, "needs": [[{"part_id": "tts-performance-management-m1:19:input", "quote": "Is there any training on the performance side of the job, like writing goals or dealing with someone who's struggling?"}, {"part_id": "tts-performance-management-m1:19:output", "quote": "The handbook lists training in two places. Through HR Links Online, you can take courses on creating and submitting a performance plan, approving a performance plan, completing a mid-year progress rev"}, {"part_id": "tts-performance-management-m1:20:retrieval:6", "quote": "TTS Handbook: performance management and supervisor resources › Performance Management Supervisor Resources › Discussing performance expectations with a new direct report\nWhen an employee joins TTS or"}]]}
|
|
31
|
+
{"thread_id": "tts-performance-management-m1", "run": 21, "needs": null}
|
|
32
|
+
{"thread_id": "tts-performance-management-m1", "run": 22, "needs": []}
|
|
33
|
+
{"thread_id": "tts-performance-management-m1", "run": 23, "needs": []}
|
|
34
|
+
{"thread_id": "tts-performance-management-m1", "run": 24, "needs": [[{"part_id": "tts-performance-management-m1:23:retrieval:6", "quote": "TTS Handbook: performance management and supervisor resources › Performance Management Supervisor Resources\nThis page contains additional resources and trainings for supervisors who are\ngoing through "}]]}
|
|
35
|
+
{"thread_id": "tts-performance-management-m1", "run": 25, "needs": []}
|
|
36
|
+
{"thread_id": "tts-performance-management-m1", "run": 26, "needs": []}
|
|
37
|
+
{"thread_id": "tts-office-of-operations-s1", "run": 1, "needs": []}
|
|
38
|
+
{"thread_id": "tts-office-of-operations-s1", "run": 2, "needs": []}
|
|
39
|
+
{"thread_id": "tts-office-of-operations-s1", "run": 3, "needs": []}
|
|
40
|
+
{"thread_id": "tts-office-of-operations-s1", "run": 4, "needs": []}
|
|
41
|
+
{"thread_id": "tts-office-of-operations-s1", "run": 5, "needs": [[{"part_id": "tts-office-of-operations-s1:4:input", "quote": "I'm putting together a blog post for the team. How many people should be credited on it, and is it only the ones who wrote it?"}, {"part_id": "tts-office-of-operations-s1:4:output", "quote": "The handbook's Authorship guidance says a blog post's authors should be only the people who actively contributed significant portions of its text. It also says posts should generally be written by one"}], [{"part_id": "tts-office-of-operations-s1:1:input", "quote": "Our team wants to put up a prototype that only our staff and a partner agency will use. What has to be true before we can run it without waiting on more sign-off?"}], [{"part_id": "tts-office-of-operations-s1:1:output", "quote": "A system can run under the approved pre-existing security authorization without further authorization only if every condition is met. It must be deployed to cloud.gov, must not interact with or change"}]]}
|
|
42
|
+
{"thread_id": "tts-office-of-operations-s1", "run": 6, "needs": []}
|
|
43
|
+
{"thread_id": "tts-office-of-operations-s1", "run": 7, "needs": [[{"part_id": "tts-office-of-operations-s1:4:output", "quote": "The handbook's Authorship guidance says a blog post's authors should be only the people who actively contributed significant portions of its text."}]]}
|
|
44
|
+
{"thread_id": "tts-office-of-operations-s1", "run": 8, "needs": null}
|
|
45
|
+
{"thread_id": "tts-office-of-operations-s1", "run": 9, "needs": []}
|
|
46
|
+
{"thread_id": "tts-office-of-operations-s1", "run": 10, "needs": []}
|
|
47
|
+
{"thread_id": "tts-office-of-operations-m1", "run": 1, "needs": null}
|
|
48
|
+
{"thread_id": "tts-office-of-operations-m1", "run": 2, "needs": []}
|
|
49
|
+
{"thread_id": "tts-office-of-operations-m1", "run": 3, "needs": []}
|
|
50
|
+
{"thread_id": "tts-office-of-operations-m1", "run": 4, "needs": null}
|
|
51
|
+
{"thread_id": "tts-office-of-operations-m1", "run": 5, "needs": []}
|
|
52
|
+
{"thread_id": "tts-office-of-operations-m1", "run": 6, "needs": []}
|
|
53
|
+
{"thread_id": "tts-office-of-operations-m1", "run": 7, "needs": [[{"part_id": "tts-office-of-operations-m1:6:retrieval:1", "quote": "`FISMA Ready Baseline Ubuntu (TIMESTAMP - Packer)`, where `TIMESTAMP` will be a"}]]}
|
|
54
|
+
{"thread_id": "tts-office-of-operations-m1", "run": 8, "needs": []}
|
|
55
|
+
{"thread_id": "tts-office-of-operations-m1", "run": 9, "needs": []}
|
|
56
|
+
{"thread_id": "tts-office-of-operations-m1", "run": 10, "needs": null}
|
|
57
|
+
{"thread_id": "tts-office-of-operations-m1", "run": 11, "needs": []}
|
|
58
|
+
{"thread_id": "tts-office-of-operations-m1", "run": 12, "needs": []}
|
|
59
|
+
{"thread_id": "tts-office-of-operations-m1", "run": 13, "needs": []}
|
|
60
|
+
{"thread_id": "tts-office-of-operations-m1", "run": 14, "needs": []}
|
|
61
|
+
{"thread_id": "tts-office-of-operations-m1", "run": 15, "needs": []}
|
|
62
|
+
{"thread_id": "tts-office-of-operations-m1", "run": 16, "needs": []}
|
|
63
|
+
{"thread_id": "tts-office-of-operations-m1", "run": 17, "needs": [[{"part_id": "tts-office-of-operations-m1:12:retrieval:2", "quote": "TTS Handbook: office of operations and launching software › Guidelines for speaking at events › Guidelines for speaking in your personal capacity\n- There is a general prohibition on receiving compensa"}]]}
|
|
64
|
+
{"thread_id": "tts-office-of-operations-m1", "run": 18, "needs": [[{"part_id": "tts-office-of-operations-m1:17:input", "quote": "And if they cover my flights and hotel, is that allowed?"}, {"part_id": "tts-office-of-operations-m1:17:output", "quote": "Yes, the handbook says you can accept travel and event-related expenses from the sponsor or organizer. You would still need to take leave to attend. Keep in mind the general prohibition on receiving c"}, {"part_id": "tts-office-of-operations-m1:18:retrieval:1", "quote": "It's always okay to politely decline speaking invitations."}]]}
|
|
65
|
+
{"thread_id": "tts-office-of-operations-m1", "run": 19, "needs": []}
|
|
66
|
+
{"thread_id": "tts-office-of-operations-m1", "run": 20, "needs": [[{"part_id": "tts-office-of-operations-m1:19:input", "quote": "Going back to the cloud sandbox access, once I've filled out the form, can I contact that tech group just to check where my request stands?"}, {"part_id": "tts-office-of-operations-m1:19:output", "quote": "Yes. The handbook says that once you've completed the form, you can contact the TTS Tech Portfolio by the email or Slack channel I mentioned to ask any questions or check on the status of a request. T"}, {"part_id": "tts-office-of-operations-m1:20:retrieval:6", "quote": "TTS Handbook: office of operations and launching software › Guidelines for speaking at events\n_This guide was created with content from the GSA's Office of Strategic\nCommunications (OSC)\nFAS Speaker G"}]]}
|
|
67
|
+
{"thread_id": "tts-office-of-operations-m1", "run": 21, "needs": [[{"part_id": "tts-office-of-operations-m1:13:retrieval:1", "quote": "If you or someone is speaking at an event, it is okay to pre-plan or post live"}, {"part_id": "tts-office-of-operations-m1:14:input", "quote": "Ok, and if people reply to my post while I'm there, can I jump in and answer them?"}, {"part_id": "tts-office-of-operations-m1:14:output", "quote": "Not right away. The handbook says that if you want to engage in a discussion in your professional capacity as a GSA employee, you should let the TTS Outreach & Stakeholder Engagement team know beforeh"}, {"part_id": "tts-office-of-operations-m1:21:retrieval:4", "quote": "If it feels like a marathon, make it a series"}]]}
|
|
68
|
+
{"thread_id": "tts-office-of-operations-m1", "run": 22, "needs": []}
|
|
69
|
+
{"thread_id": "tts-office-of-operations-m1", "run": 23, "needs": [[{"part_id": "tts-office-of-operations-m1:22:retrieval:2", "quote": "arrange a call with the event host and ask them the following questions."}]]}
|
|
70
|
+
{"thread_id": "tts-office-of-operations-m1", "run": 24, "needs": [[{"part_id": "tts-office-of-operations-m1:23:input", "quote": "Do I need my manager to weigh in before I reach out to the organizers?"}, {"part_id": "tts-office-of-operations-m1:23:output", "quote": "Yes. The handbook says you and your supervisor should first decide that the opportunity is good for you and TTS, and only then should you set up the call with the event host. Once you've settled on go"}, {"part_id": "tts-office-of-operations-m1:24:retrieval:1", "quote": "TTS Handbook: office of operations and launching software › Blogging Guide › Multiple authors\nSome posts may have significant amounts of text written by more than two people,\nin which case every contr"}]]}
|
|
71
|
+
{"thread_id": "tts-office-of-operations-m1", "run": 25, "needs": [[{"part_id": "tts-office-of-operations-m1:10:retrieval:1", "quote": "Necessary security and compliance actions"}]]}
|
|
Binary file
|
compache/errors.py
ADDED
compache/hermes.py
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
"""compache as a Hermes Agent context engine.
|
|
2
|
+
|
|
3
|
+
Hermes lets a context engine choose what a request holds (`select_context`), and nothing
|
|
4
|
+
else has to change: the conversation Hermes keeps is untouched. compache's engine replaces
|
|
5
|
+
archived parts by their notice, gives the model a `reopen` tool for them, and leaves
|
|
6
|
+
everything else to Hermes. When a conversation outgrows the model, Hermes' own compressor
|
|
7
|
+
does what it always did.
|
|
8
|
+
|
|
9
|
+
pip install compache
|
|
10
|
+
|
|
11
|
+
# ~/.hermes/plugins/compache/__init__.py (a ContextEngine for Hermes)
|
|
12
|
+
from compache.hermes import register
|
|
13
|
+
|
|
14
|
+
# ~/.hermes/config.yaml
|
|
15
|
+
context:
|
|
16
|
+
engine: compache
|
|
17
|
+
|
|
18
|
+
The policy is read from COMPACHE_POLICY, a record without any text is kept in
|
|
19
|
+
COMPACHE_RECORD. Both are optional. Set COMPACHE_RECORD first, with no policy: compache
|
|
20
|
+
then only records, and `compache fit` on the folder gives the policy.
|
|
21
|
+
|
|
22
|
+
Notes are not asked here, and no keep-warm pings are sent: Hermes sends the requests, so
|
|
23
|
+
compache has no request of its own to send. `compache proxy` does both.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import json
|
|
29
|
+
import logging
|
|
30
|
+
import os
|
|
31
|
+
from typing import Any
|
|
32
|
+
|
|
33
|
+
from . import wire
|
|
34
|
+
from .live import Live, _REOPEN_TOOL
|
|
35
|
+
|
|
36
|
+
__all__ = ["make", "register"]
|
|
37
|
+
|
|
38
|
+
logger = logging.getLogger(__name__)
|
|
39
|
+
|
|
40
|
+
_PATH = "/v1/chat/completions"
|
|
41
|
+
_REOPEN = _REOPEN_TOOL["function"]["name"]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _from_environment() -> Live:
|
|
45
|
+
return Live(
|
|
46
|
+
os.environ.get("COMPACHE_POLICY") or None,
|
|
47
|
+
record=os.environ.get("COMPACHE_RECORD") or None,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _same_lifetime(live: Live) -> None:
|
|
52
|
+
"""Say so where Hermes' cache marks ask for another lifetime than the policy counts on.
|
|
53
|
+
|
|
54
|
+
Hermes marks the requests, so what it asks for is its own setting.
|
|
55
|
+
"""
|
|
56
|
+
spec = live.policy.spec if live.policy is not None else None
|
|
57
|
+
if spec is None or "claude" not in spec.model_id:
|
|
58
|
+
return
|
|
59
|
+
wanted = wire.TTLS.get(spec.cache_ttl_seconds)
|
|
60
|
+
if wanted is None:
|
|
61
|
+
return
|
|
62
|
+
try:
|
|
63
|
+
from hermes_cli.config import load_config_readonly
|
|
64
|
+
|
|
65
|
+
asked = (load_config_readonly().get("prompt_caching") or {}).get(
|
|
66
|
+
"cache_ttl", "auto"
|
|
67
|
+
)
|
|
68
|
+
except Exception:
|
|
69
|
+
return
|
|
70
|
+
# Its default, "auto", moves to an hour after a conversation's first pause.
|
|
71
|
+
if str(asked) != wanted:
|
|
72
|
+
logger.warning(
|
|
73
|
+
"compache: the policy counts on %s cache entries and Hermes asks for %s. "
|
|
74
|
+
"Set prompt_caching.cache_ttl to %s in config.yaml",
|
|
75
|
+
wanted,
|
|
76
|
+
asked,
|
|
77
|
+
wanted,
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def make(live: Live | None = None):
|
|
82
|
+
"""The engine, for Hermes' own `ctx.register_context_engine`.
|
|
83
|
+
|
|
84
|
+
Hermes is imported only here, so that the package installs without it.
|
|
85
|
+
"""
|
|
86
|
+
from agent.context_engine import ContextEngine
|
|
87
|
+
|
|
88
|
+
# Every engine Hermes makes, one per agent, shares one policy and one record.
|
|
89
|
+
shared: dict[str, Any] = {"live": live, "checked": False}
|
|
90
|
+
|
|
91
|
+
class Compache(ContextEngine):
|
|
92
|
+
"""Chooses what a request holds by a fitted policy. `compress` stays Hermes' own."""
|
|
93
|
+
|
|
94
|
+
# What the host reads off every engine.
|
|
95
|
+
last_prompt_tokens = 0
|
|
96
|
+
last_completion_tokens = 0
|
|
97
|
+
last_total_tokens = 0
|
|
98
|
+
threshold_tokens = 0
|
|
99
|
+
context_length = 0
|
|
100
|
+
compression_count = 0
|
|
101
|
+
|
|
102
|
+
def __init__(self):
|
|
103
|
+
super().__init__()
|
|
104
|
+
if shared["live"] is None:
|
|
105
|
+
shared["live"] = _from_environment()
|
|
106
|
+
if not shared["checked"]:
|
|
107
|
+
shared["checked"] = True
|
|
108
|
+
_same_lifetime(shared["live"])
|
|
109
|
+
self.live = shared["live"]
|
|
110
|
+
self.session = "session"
|
|
111
|
+
self.model = ""
|
|
112
|
+
self._route: dict[str, Any] = {}
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def name(self) -> str:
|
|
116
|
+
return "compache"
|
|
117
|
+
|
|
118
|
+
def clone_for_agent(self):
|
|
119
|
+
"""One engine per agent. The policy, the record and what was seen are shared."""
|
|
120
|
+
return type(self)()
|
|
121
|
+
|
|
122
|
+
# -- what the request holds ------------------------------------------------
|
|
123
|
+
|
|
124
|
+
def on_session_start(self, session_id: str, **kwargs) -> None:
|
|
125
|
+
self.session = str(session_id or "session")
|
|
126
|
+
|
|
127
|
+
def on_session_reset(self) -> None:
|
|
128
|
+
super().on_session_reset()
|
|
129
|
+
|
|
130
|
+
def select_context(
|
|
131
|
+
self,
|
|
132
|
+
request_messages: list,
|
|
133
|
+
*,
|
|
134
|
+
conversation_messages=None,
|
|
135
|
+
incoming_message=None,
|
|
136
|
+
budget_tokens: int = 0,
|
|
137
|
+
):
|
|
138
|
+
"""The messages with archived parts as their notice. None when nothing is archived."""
|
|
139
|
+
body = {"model": self.model, "messages": request_messages}
|
|
140
|
+
shown = self.live.view(_PATH, body, thread=self.session)
|
|
141
|
+
messages = shown.get("messages") if isinstance(shown, dict) else None
|
|
142
|
+
return (
|
|
143
|
+
messages
|
|
144
|
+
if messages is not None and messages is not request_messages
|
|
145
|
+
else None
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
# -- the model fetching an archived part back -------------------------------
|
|
149
|
+
|
|
150
|
+
def get_tool_schemas(self) -> list:
|
|
151
|
+
"""`reopen`, which reads an archived part. It is shown only when there can be one."""
|
|
152
|
+
if self.live.policy is None:
|
|
153
|
+
return []
|
|
154
|
+
function = _REOPEN_TOOL["function"]
|
|
155
|
+
return [
|
|
156
|
+
{
|
|
157
|
+
"name": function["name"],
|
|
158
|
+
"description": function["description"],
|
|
159
|
+
"parameters": function["parameters"],
|
|
160
|
+
}
|
|
161
|
+
]
|
|
162
|
+
|
|
163
|
+
def handle_tool_call(self, name: str, args: dict, **kwargs) -> str:
|
|
164
|
+
if name != _REOPEN:
|
|
165
|
+
return super().handle_tool_call(name, args, **kwargs)
|
|
166
|
+
args = args if isinstance(args, dict) else {}
|
|
167
|
+
answer = self.live.reopen(
|
|
168
|
+
self.session, str(args.get("reference", "")), args.get("offset")
|
|
169
|
+
)
|
|
170
|
+
return json.dumps(answer, ensure_ascii=False)
|
|
171
|
+
|
|
172
|
+
# -- what came back --------------------------------------------------------
|
|
173
|
+
|
|
174
|
+
def update_from_response(self, usage: dict) -> None:
|
|
175
|
+
self.last_prompt_tokens = int(usage.get("prompt_tokens") or 0)
|
|
176
|
+
self.last_completion_tokens = int(usage.get("completion_tokens") or 0)
|
|
177
|
+
self.last_total_tokens = int(usage.get("total_tokens") or 0)
|
|
178
|
+
self.live.heard(self.session, _usage(usage), model=self.model or None)
|
|
179
|
+
|
|
180
|
+
def on_turn_complete(
|
|
181
|
+
self, messages: list, usage: dict | None = None, **kwargs
|
|
182
|
+
) -> None:
|
|
183
|
+
self.live.conclude(
|
|
184
|
+
_PATH, {"model": self.model, "messages": messages}, thread=self.session
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
# -- when a conversation outgrows the model, Hermes' own compressor -------------------
|
|
188
|
+
|
|
189
|
+
def update_model(
|
|
190
|
+
self,
|
|
191
|
+
model: str,
|
|
192
|
+
context_length: int,
|
|
193
|
+
base_url: str = "",
|
|
194
|
+
api_key: str = "",
|
|
195
|
+
provider: str = "",
|
|
196
|
+
api_mode: str = "",
|
|
197
|
+
) -> None:
|
|
198
|
+
self.model = str(model or "")
|
|
199
|
+
self.context_length = int(context_length or 0)
|
|
200
|
+
self._route = {
|
|
201
|
+
"model": self.model,
|
|
202
|
+
"base_url": base_url,
|
|
203
|
+
"api_key": api_key,
|
|
204
|
+
"provider": provider,
|
|
205
|
+
"api_mode": api_mode,
|
|
206
|
+
"config_context_length": self.context_length or None,
|
|
207
|
+
"quiet_mode": True,
|
|
208
|
+
}
|
|
209
|
+
try:
|
|
210
|
+
super().update_model(
|
|
211
|
+
model, context_length, base_url, api_key, provider, api_mode
|
|
212
|
+
)
|
|
213
|
+
except Exception:
|
|
214
|
+
# A Hermes of another version: its threshold is not essential here.
|
|
215
|
+
self.threshold_tokens = int(
|
|
216
|
+
self.context_length * self.threshold_percent
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
def should_compress(self, prompt_tokens: int | None = None) -> bool:
|
|
220
|
+
"""Only when a conversation is about to outgrow the model."""
|
|
221
|
+
tokens = self.last_prompt_tokens if prompt_tokens is None else prompt_tokens
|
|
222
|
+
return self.threshold_tokens > 0 and tokens >= self.threshold_tokens
|
|
223
|
+
|
|
224
|
+
def compress(
|
|
225
|
+
self,
|
|
226
|
+
messages: list,
|
|
227
|
+
current_tokens=None,
|
|
228
|
+
focus_topic=None,
|
|
229
|
+
force: bool = False,
|
|
230
|
+
memory_context: str = "",
|
|
231
|
+
) -> list:
|
|
232
|
+
fallback = self._default()
|
|
233
|
+
if fallback is None:
|
|
234
|
+
return messages
|
|
235
|
+
self.compression_count += 1
|
|
236
|
+
return fallback.compress(
|
|
237
|
+
messages,
|
|
238
|
+
current_tokens,
|
|
239
|
+
focus_topic=focus_topic,
|
|
240
|
+
force=force,
|
|
241
|
+
memory_context=memory_context,
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
def _default(self):
|
|
245
|
+
"""Hermes' built-in compressor, made for the model that is in use."""
|
|
246
|
+
if not self._route:
|
|
247
|
+
return None
|
|
248
|
+
try:
|
|
249
|
+
from agent.context_compressor import ContextCompressor
|
|
250
|
+
|
|
251
|
+
return ContextCompressor(**self._route)
|
|
252
|
+
except Exception:
|
|
253
|
+
logger.warning(
|
|
254
|
+
"compache: Hermes' own compressor could not be made, nothing was compressed",
|
|
255
|
+
exc_info=True,
|
|
256
|
+
)
|
|
257
|
+
return None
|
|
258
|
+
|
|
259
|
+
return Compache()
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _usage(usage: dict) -> dict:
|
|
263
|
+
"""Hermes' token counts in the OpenAI form: its prompt total counts what was read or written.
|
|
264
|
+
|
|
265
|
+
What Hermes does not report is left out: a missing count is not a zero.
|
|
266
|
+
"""
|
|
267
|
+
details = {
|
|
268
|
+
ours: int(usage[theirs] or 0)
|
|
269
|
+
for ours, theirs in (
|
|
270
|
+
("cached_tokens", "cache_read_tokens"),
|
|
271
|
+
("cache_write_tokens", "cache_write_tokens"),
|
|
272
|
+
)
|
|
273
|
+
if usage.get(theirs) is not None
|
|
274
|
+
}
|
|
275
|
+
return {
|
|
276
|
+
"prompt_tokens": int(usage.get("prompt_tokens") or 0),
|
|
277
|
+
"completion_tokens": int(usage.get("completion_tokens") or 0),
|
|
278
|
+
**({"prompt_tokens_details": details} if details else {}),
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def register(ctx) -> None:
|
|
283
|
+
"""Hermes' plugin entry: hands it the engine (`register_context_engine`)."""
|
|
284
|
+
ctx.register_context_engine(make())
|