interplane.Get Omega
Read in your language

aienos.com

Source of www.aienos.com, served from my own hardware

Brought by drakestapleton

branch main Branches Tags History

aienos.com / scripts / allen / gen_answers.py

142 lines · 6392 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Generate the answer cache (answers/answers.json) offline through the shared model.
3
4Each question is sent as a visitor's exact anonymous first turn (allen_speed.generation_messages:
5system prompt + catalog, the anonymous opening, the question with its stable cards) at
6temperature 0, one request at a time and only while the server's /health reports at most
7--max-inflight requests. Entries already in --out whose key still matches are kept as they are.
8The gateway serves an entry only while its prefix_sha and grounding_sha match the live files,
9and regenerates stale entries itself (allen_chat.py App.regen).
10
11 python3 gen_answers.py --out answers/answers.json \\
12 --catalog /var/lib/allen-catalog/catalog.txt \\
13 --catalog-detail /var/lib/allen-catalog/catalog-detail.jsonl \\
14 --catalog-retrieve /opt/allen-catalog/retrieve.py
15"""
16
17import argparse
18import http.client
19import json
20import os
21import sys
22import time
23
24sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
25import allen_chat # noqa: E402 (its constants, so the opening matches byte for byte)
26import allen_speed # noqa: E402
27
28HERE = os.path.dirname(os.path.abspath(__file__))
29MODEL = allen_chat.MODEL
30
31
32def health(host, port, headers):
33 try:
34 c = http.client.HTTPConnection(host, port, timeout=5)
35 c.request("GET", "/health", headers=headers)
36 r = c.getresponse()
37 d = json.loads(r.read(4096))
38 c.close()
39 return d if r.status == 200 and d.get("status") == "ok" else None
40 except (OSError, ValueError, http.client.HTTPException):
41 return None
42
43
44def write(path, entries):
45 tmp = path + ".tmp"
46 with open(tmp, "w", encoding="utf-8") as f:
47 json.dump({"format": 1, "entries": sorted(entries.values(), key=lambda e: e["id"])}, f,
48 ensure_ascii=False, indent=1, sort_keys=True)
49 f.write("\n")
50 os.replace(tmp, path)
51
52
53def main():
54 ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
55 ap.add_argument("--questions", default=os.path.join(HERE, "answers", "questions.json"))
56 ap.add_argument("--out", default=os.path.join(HERE, "answers", "answers.json"))
57 ap.add_argument("--system-prompt", default=os.path.join(HERE, "system-prompt.txt"))
58 ap.add_argument("--catalog", required=True)
59 ap.add_argument("--catalog-detail")
60 ap.add_argument("--catalog-retrieve")
61 ap.add_argument("--learn-dir")
62 ap.add_argument("--upstream", default="127.0.0.1:18091")
63 ap.add_argument("--max-inflight", type=int, default=2)
64 ap.add_argument("--max-tokens", type=int, default=1024)
65 ap.add_argument("--only", nargs="*", help="question ids to (re)generate even if still valid")
66 ap.add_argument("--log", help="JSON lines: one timing record per request")
67 ap.add_argument("--tools", default="", help="the gateway's --tools registry, when production sets one")
68 a = ap.parse_args()
69
70 with open(a.system_prompt, encoding="utf-8") as f:
71 prompt = f.read()
72 tools = allen_chat.load_tools(a.tools) if a.tools else None
73 specs = list(tools.TOOLS) if tools else []
74 if tools: # the same composition as App.system_text()
75 prompt = allen_speed.join_system(prompt, tools.SYSTEM_PROMPT.strip() + "\n")
76 with open(a.catalog, encoding="utf-8") as f:
77 text = allen_speed.join_system(prompt, f.read())
78 psha = allen_speed.prefix_key(allen_speed.sha256_bytes(text.encode()), specs)
79 cards = allen_speed.Cards(a.catalog_detail, a.catalog_retrieve, a.learn_dir, a.catalog)
80 cards.refresh()
81 opening = [{"role": "user", "content": allen_chat.OPEN_USER_ANON},
82 {"role": "assistant", "content": allen_chat.GREETING_ANON}]
83 with open(a.questions, encoding="utf-8") as f:
84 questions = json.load(f)["questions"]
85 have = {}
86 if os.path.exists(a.out):
87 with open(a.out, encoding="utf-8") as f:
88 have = {e["id"]: e for e in json.load(f)["entries"]}
89 store = allen_speed.Answers()
90 host, _, port = a.upstream.rpartition(":")
91 port = int(port)
92 token = os.environ.get("ALLEN_UPSTREAM_TOKEN", "").strip()
93 headers = {"Authorization": "Bearer " + token} if token else {}
94 log = open(a.log, "a", encoding="utf-8") if a.log else None
95 out = {}
96 for q in questions:
97 old = have.get(q["id"])
98 if old and not (a.only and q["id"] in a.only) and old["q"] == q["q"] \
99 and store.valid(old, psha, cards):
100 out[q["id"]] = dict(old, alt=q.get("alt") or [])
101 continue
102 if a.only and q["id"] not in a.only:
103 if old:
104 out[q["id"]] = old
105 continue
106 while True:
107 h = health(host, port, headers)
108 if h and int(h.get("in_flight", 0)) <= a.max_inflight:
109 break
110 time.sleep(3)
111 req = {"model": MODEL, "max_tokens": a.max_tokens, "temperature": 0, "stream": False,
112 "messages": allen_speed.generation_messages(text, opening, q["q"], cards)}
113 if specs:
114 req.update(tools=specs, tool_choice="none")
115 body = json.dumps(req).encode()
116 t0 = time.monotonic()
117 c = http.client.HTTPConnection(host, port, timeout=600)
118 c.request("POST", "/v1/chat/completions", body, dict(headers, **{"Content-Type": "application/json"}))
119 r = c.getresponse()
120 res = json.loads(r.read(1 << 20))
121 c.close()
122 ms = int((time.monotonic() - t0) * 1000)
123 ch = res["choices"][0]
124 answer = (ch["message"]["content"] or "").strip()
125 rec = {"id": q["id"], "status": r.status, "ms": ms, "in_flight_before": int(h.get("in_flight", 0)),
126 "finish": ch.get("finish_reason"), "usage": res.get("usage")}
127 print(json.dumps(rec), flush=True)
128 if log:
129 log.write(json.dumps(rec) + "\n")
130 log.flush()
131 if r.status != 200 or ch.get("finish_reason") != "stop" or not answer:
132 print("skip %s: not a complete answer" % q["id"], file=sys.stderr)
133 continue
134 out[q["id"]] = allen_speed.make_entry(q, answer, psha, cards, MODEL,
135 time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))
136 write(a.out, out)
137 write(a.out, out)
138 print("entries %d, prefix_sha %s" % (len(out), psha))
139
140
141if __name__ == "__main__":
142 main()