okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-clean-3 (321794636): docs and history (cleanup step 3, items 3.0-3.10); release manifest and capability table with checks, history/ with pointers, link check, tools/ split, bench index; owner OK'd the wording 11-082b36e8a02

main
5.0 KiB85 linesraw
1"""#3493: does an agent-Harness-style run reuse its prefix with the server's DEFAULT conversation cache?
2
3    python research/tools/live-probes-2026-10/harness_reuse_probe.py http://127.0.0.1:8080 [--turns 4] [--main-tokens 6000] [--key KEY]
4
5An agent Harness keeps a long MAIN conversation (system prompt, tools, a growing list of tool results) and, between its
6turns, sends shorter side conversations (a sub-agent, a summary) with their own system prompts.  Every turn of either one
7extends the previous request of the same conversation.  With the conversation cache off, the engine holds one prompt, so
8each switch to the other conversation read the whole prompt again (the report: Reused = 0 on 12 of 12 requests).
9
10The probe sends MAIN1 SUB1 MAIN2 SUB2 ... and reads the server's /metrics before and after each request: the tokens the
11request took from the cache ("reused") out of its prompt.  Exit code 0 when every follow-up turn (all but the first of
12each conversation) reused more than half of its prompt, 1 otherwise.  Needs an idle server; sampling is greedy, 8 new tokens.
13"""
14from __future__ import annotations
15
16import argparse
17import json
18import sys
19import time
20import urllib.request
21
22
23def post(url, key, body, timeout=600):
24    req = urllib.request.Request(url + "/v1/chat/completions", data=json.dumps(body).encode(),
25                                 headers={"Content-Type": "application/json", **({"Authorization": "Bearer " + key} if key else {})})
26    with urllib.request.urlopen(req, timeout=timeout) as response:
27        return json.load(response)
28
29
30def metrics(url, key):
31    req = urllib.request.Request(url + "/metrics", headers={"Authorization": "Bearer " + key} if key else {})
32    with urllib.request.urlopen(req, timeout=20) as response:
33        return json.load(response)
34
35
36def filler(tag, n_words):
37    """Deterministic text of about n_words words that differs per tag (so two conversations share no prefix)."""
38    words = ["%s%d" % (tag, i % 977) for i in range(n_words)]
39    return " ".join(words)
40
41
42def main() -> int:
43    ap = argparse.ArgumentParser()
44    ap.add_argument("url")
45    ap.add_argument("--turns", type=int, default=4)
46    ap.add_argument("--main-tokens", type=int, default=6000, help="about this many tokens in the main conversation's first request")
47    ap.add_argument("--sub-tokens", type=int, default=1500)
48    ap.add_argument("--step-tokens", type=int, default=500, help="what every turn adds (a tool result)")
49    ap.add_argument("--key", default=None)
50    a = ap.parse_args()
51    url = a.url.rstrip("/")
52    model = (json.load(urllib.request.urlopen(url + "/v1/models", timeout=20))["data"][0]["id"]
53             if not a.key else json.load(urllib.request.urlopen(urllib.request.Request(url + "/v1/models", headers={"Authorization": "Bearer " + a.key}), timeout=20))["data"][0]["id"])
54    conv = {"MAIN": [{"role": "system", "content": "You are the main coding agent. " + filler("m", a.main_tokens // 2)}],
55            "SUB": [{"role": "system", "content": "You are a sub-agent that summarizes. " + filler("s", a.sub_tokens // 2)}]}
56    rows, ok = [], True
57    for turn in range(a.turns):
58        for name, step in (("MAIN", a.step_tokens), ("SUB", a.step_tokens // 2)):
59            conv[name].append({"role": "user", "content": "tool result %d: %s Reply with one word." % (turn, filler(name[0].lower() + "t%d" % turn, step // 2))})
60            before = metrics(a.url.rstrip("/"), a.key).get("conversation_cache") or {}
61            t0 = time.time()
62            reply = post(url, a.key, {"model": model, "messages": conv[name], "max_tokens": 8, "temperature": 0,
63                                      "chat_template_kwargs": {"enable_thinking": False}})
64            took = time.time() - t0
65            after = metrics(url, a.key).get("conversation_cache") or {}
66            prompt = (reply.get("usage") or {}).get("prompt_tokens", 0)
67            reused = int(after.get("reused_tokens", 0)) - int(before.get("reused_tokens", 0))
68            conv[name].append({"role": "assistant", "content": (reply["choices"][0]["message"].get("content") or "ok")})
69            first = turn == 0
70            good = first or reused * 2 > prompt
71            ok = ok and good
72            rows.append((name, turn + 1, prompt, reused, took, good))
73            print("%-4s turn %d: prompt %6d tokens, reused %6d (%3.0f%%), %5.1f s%s" % (
74                name, turn + 1, prompt, reused, 100.0 * reused / max(prompt, 1), took, "" if good else "   <-- not reused"), flush=True)
75    follow = [r for r in rows if r[1] > 1]
76    total_prompt = sum(r[2] for r in follow)
77    total_reused = sum(r[3] for r in follow)
78    print("follow-up turns: %d, reused %d of %d prompt tokens (%.0f%%); conversation cache: %s" % (
79        len(follow), total_reused, total_prompt, 100.0 * total_reused / max(total_prompt, 1),
80        json.dumps({k: v for k, v in (metrics(url, a.key).get("conversation_cache") or {}).items() if k in ("enabled", "budget_mib", "slots", "parked", "requests_reused")})))
81    return 0 if ok else 1
82
83
84if __name__ == "__main__":
85    sys.exit(main())