Files
leleka/scripts/cp/synth_session.py
T

198 lines
8.1 KiB
Python

#!/usr/bin/env python3
"""Offline tooling (experiments only; production stays Python-free): synthesize Codex-shaped Responses API request material
from a captured session (the engine-side capture holds the rendered prompt token ids, not the HTTP bodies).
synth_session.py TOKENIZER_DIR CAPTURE_DIR LAST_REQ_INDEX OUT.json [--extend CAPTURE2 LAST2]
The last request's prompt is decoded with the pinned vocabulary and the chat template is inverted: system block (tools, merged
instructions), user messages, assistant turns (`<think>` reasoning, text, `<tool_call>` markup) and `<tool_response>` user turns become
Responses `instructions`, `tools`, and `input` items (message / reasoning / function_call / function_call_output) exactly as Codex
replays them. OUT.json holds the invariant part of a request and the item list with its round boundaries, plus the captured prompt
ids of the last request so a harness can check that rendering + tokenizing the synthesized body reproduces the capture exactly.
With --extend the items of a second capture (call ids and text tagged so no two items are byte-identical) are appended, to reach
history sizes beyond the capture.
"""
import json
import re
import sys
sys.path.insert(0, __file__.rsplit("/", 1)[0] if "/" in __file__ else ".")
from tok_py import Vocab # noqa: E402
CALL_RE = re.compile(r"<tool_call>\n<function=([^>]+)>\n(.*?)</function>\n</tool_call>", re.S)
PARAM_RE = re.compile(r"<parameter=([^>]+)>\n(.*?)\n</parameter>\n", re.S)
RESP_RE = re.compile(r"<tool_response>\n(.*?)\n</tool_response>", re.S)
def split_segments(text):
segs = []
pos = 0
marker = "<|im_start|>"
idx = [m.start() for m in re.finditer(re.escape(marker), text)]
for a, b in zip(idx, idx[1:] + [len(text)]):
seg = text[a + len(marker):b]
segs.append(seg)
return segs
def parse_system(seg):
# seg = "system\n...<|im_end|>\n"
body = seg[len("system\n"):]
assert body.endswith("<|im_end|>\n"), body[-40:]
body = body[: -len("<|im_end|>\n")]
tools_start = body.index("<tools>\n") + len("<tools>\n")
tools_end = body.index("\n</tools>")
tools = [json.loads(l) for l in body[tools_start:tools_end].split("\n")]
rest = body[tools_end + len("\n</tools>"):]
marker = "</IMPORTANT>"
k = rest.index(marker) + len(marker)
tail = rest[k:]
assert tail.startswith("\n\n"), repr(tail[:30])
instructions = tail[2:]
flat = []
for t in tools:
f = t["function"]
o = {"type": "function", "name": f["name"]}
if "description" in f:
o["description"] = f["description"]
if "strict" in f:
o["strict"] = f["strict"]
if "parameters" in f:
o["parameters"] = f["parameters"]
flat.append(o)
return instructions, flat
def message(role, text):
kind = "output_text" if role == "assistant" else "input_text"
return {"type": "message", "role": role, "content": [{"type": kind, "text": text}]}
def arg_value(raw, schema):
prop = (schema or {}).get("properties", {})
kind = None
return raw, prop
def parse_assistant(seg, tools, serial):
body = seg[len("assistant\n"):]
assert body.endswith("<|im_end|>\n"), repr(body[-30:])
body = body[: -len("<|im_end|>\n")]
assert body.startswith("<think>\n")
close = body.index("\n</think>\n\n")
reasoning = body[len("<think>\n"):close]
content = body[close + len("\n</think>\n\n"):]
items = []
if reasoning:
items.append({"type": "reasoning", "summary": [], "content": [{"type": "reasoning_text", "text": reasoning}]})
first = content.find("<tool_call>\n")
text = content if first < 0 else content[:first]
text = text.strip()
if text:
items.append(message("assistant", text))
calls = []
for m in CALL_RE.finditer(content):
name, params = m.group(1), m.group(2)
schema = next((t.get("parameters") for t in tools if t["name"] == name), None) or {}
props = schema.get("properties", {})
args = {}
for p in PARAM_RE.finditer(params):
pname, raw = p.group(1), p.group(2)
ptype = props.get(pname, {}).get("type")
if ptype == "string" or ptype is None:
args[pname] = raw
else:
try:
args[pname] = json.loads(raw)
except ValueError:
args[pname] = raw
serial[0] += 1
call_id = f"call_{serial[0]:06d}"
calls.append(call_id)
items.append({"type": "function_call", "name": name, "call_id": call_id,
"arguments": json.dumps(args, ensure_ascii=False, separators=(",", ":"))})
return items, calls
def parse_user(seg, pending_calls):
body = seg[len("user\n"):]
assert body.endswith("<|im_end|>\n")
body = body[: -len("<|im_end|>\n")]
if body.startswith("<tool_response>\n") and pending_calls:
outs = [m.group(1) for m in RESP_RE.finditer(body)]
assert len(outs) == len(pending_calls), (len(outs), len(pending_calls))
return [{"type": "function_call_output", "call_id": c, "output": o} for c, o in zip(pending_calls, outs)], True
return [message("user", body)], False
def build(vocab, capture, last, serial):
req = json.load(open(f"{capture}/req-{last:06d}.json"))
ids = req["prompt_ids"]
text = vocab.decode(ids)
segs = split_segments(text)
instructions, tools = parse_system(segs[0])
items, rounds = [], []
pending = []
# the final segment is the generation prompt "assistant\n<think>\n"
assert segs[-1] == "assistant\n<think>\n", repr(segs[-1])
for seg in segs[1:-1]:
if seg.startswith("assistant\n"):
new, calls = parse_assistant(seg, tools, serial)
items += new
pending = calls
else:
new, was_output = parse_user(seg, pending)
items += new
pending = []
# a request can be made after a user message or after tool outputs
rounds.append(len(items))
return instructions, tools, items, rounds, ids
def retag(items, rounds, tag):
out = []
for it in items:
it = json.loads(json.dumps(it))
if it["type"] == "message":
it["content"][0]["text"] = f"[{tag}] " + it["content"][0]["text"]
elif it["type"] == "function_call_output":
it["output"] = f"[{tag}] " + it["output"]
elif it["type"] == "reasoning":
it["content"][0]["text"] = f"[{tag}] " + it["content"][0]["text"]
elif it["type"] == "function_call":
it["call_id"] = it["call_id"].replace("call_", f"call_{tag}_")
out.append(it)
# call ids in outputs
for it in out:
if it["type"] == "function_call_output":
it["call_id"] = it["call_id"].replace("call_", f"call_{tag}_")
return out
def main():
argv = sys.argv[1:]
tok_dir, capture, last, out = argv[0], argv[1], int(argv[2]), argv[3]
extend = None
if "--extend" in argv:
k = argv.index("--extend")
extend = (argv[k + 1], int(argv[k + 2]))
vocab = Vocab(tok_dir)
serial = [0]
instructions, tools, items, rounds, ids = build(vocab, capture, last, serial)
doc = {"instructions": instructions, "tools": tools, "items": items, "rounds": rounds,
"capture_prompt_ids": ids, "capture_items": len(items)}
if extend:
i2, t2, items2, rounds2, _ = build(vocab, extend[0], extend[1], serial)
# skip the leading environment/task user messages of the second session: keep from its first assistant turn
first_assistant = next(n for n, it in enumerate(items2) if it["type"] in ("reasoning", "function_call") or (it["type"] == "message" and it["role"] == "assistant"))
base = len(items)
tail = retag(items2[first_assistant:], rounds2, "x")
doc["items"] = items + tail
doc["rounds"] = rounds + [base + (r - first_assistant) for r in rounds2 if r > first_assistant]
json.dump(doc, open(out, "w", encoding="utf-8"), ensure_ascii=False)
print(f"items={len(doc['items'])} rounds={len(doc['rounds'])} tools={len(tools)} instructions_bytes={len(instructions)} capture_tokens={len(ids)}")
if __name__ == "__main__":
main()