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 KiB122 linesraw
1#!/usr/bin/env python3
2"""A tiny terminal chat for a running Strata server (start it with run-<model>.bat / run-<model>.sh first).
3
4    python tools/chat.py [--port 8080] [--think none|low|medium|high]
5
6Type a message and press Enter.  /image <path> attaches a picture to your next message (when the server was set up
7with images), /think <none|low|medium|high> sets how long the model thinks first, /reset starts a new conversation,
8/quit leaves.  Standard library only.
9"""
10from __future__ import annotations
11
12import argparse
13import base64
14import json
15import mimetypes
16import os
17import sys
18import time
19import urllib.request
20
21from highlight import StreamHighlighter
22
23
24def stream(url, messages, think, max_tokens):
25    body = {"model": "strata", "messages": messages, "stream": True, "max_tokens": max_tokens,
26            "reasoning_effort": think}
27    req = urllib.request.Request(url, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
28    with urllib.request.urlopen(req, timeout=3600) as r:
29        for raw in r:
30            line = raw.decode("utf-8", "replace").strip()
31            if not line.startswith("data: ") or line == "data: [DONE]":
32                continue
33            d = json.loads(line[6:])["choices"][0]["delta"]
34            yield d.get("reasoning_content") or "", d.get("content") or ""
35
36
37def main() -> int:
38    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
39    ap.add_argument("--port", type=int, default=8080)
40    ap.add_argument("--host", default="127.0.0.1")
41    ap.add_argument("--think", default="medium", choices=["none", "low", "medium", "high"],
42                    help="how long the model thinks before answering (none = answer directly)")
43    ap.add_argument("--no-think", action="store_true", help="same as --think none")
44    ap.add_argument("--max-tokens", type=int, default=4096)
45    a = ap.parse_args()
46    url = f"http://{a.host}:{a.port}/v1/chat/completions"
47    gray, reset = ("\033[90m", "\033[0m") if sys.stdout.isatty() else ("", "")
48    hl = StreamHighlighter(color=sys.stdout.isatty())
49    messages, pending = [], []
50    think = "none" if a.no_think else a.think
51    print(f"Strata chat ({url}).  /image <path> = attach a picture, /think none|low|medium|high (now: {think}), "
52          f"/reset = new conversation, /quit = leave.")
53    while True:
54        try:
55            user = input("\nyou> ").strip()
56        except (EOFError, KeyboardInterrupt):
57            print()
58            return 0
59        if user in ("/quit", "/exit"):
60            return 0
61        if user == "/reset":
62            messages, pending = [], []
63            print("(new conversation)")
64            continue
65        if user.startswith("/think"):
66            level = user[6:].strip().lower()
67            if level in ("none", "low", "medium", "high"):
68                think = level
69                print(f"(thinking: {think})")
70            else:
71                print("(usage: /think none|low|medium|high)")
72            continue
73        if user.startswith("/image"):
74            path = user[6:].strip().strip('"').strip("'")
75            if not os.path.isfile(path):
76                print(f"(no such file: {path or '?'} - usage: /image <path to a picture>)")
77                continue
78            mime = mimetypes.guess_type(path)[0] or "image/jpeg"
79            data = base64.b64encode(open(path, "rb").read()).decode()
80            pending.append({"type": "image_url", "image_url": {"url": f"data:{mime};base64,{data}"}})
81            print(f"(picture attached: {os.path.basename(path)} - now type your question)")
82            continue
83        if not user:
84            continue
85        if pending:
86            messages.append({"role": "user", "content": [*pending, {"type": "text", "text": user}]})
87            pending = []
88        else:
89            messages.append({"role": "user", "content": user})
90        answer, n, t0 = [], 0, time.time()
91        print("model> ", end="", flush=True)
92        try:
93            in_think = False
94            for reasoning, content in stream(url, messages, think, a.max_tokens):
95                if reasoning:
96                    if not in_think:
97                        print(gray, end="")
98                        in_think = True
99                    print(reasoning, end="", flush=True)
100                if content:
101                    if in_think:
102                        print(reset + "\n", end="")
103                        in_think = False
104                    print(hl.feed(content), end="", flush=True)
105                    answer.append(content)
106                n += 1
107            if in_think:
108                print(reset, end="")
109            out = hl.flush()
110            if out:
111                print(out, end="")
112        except OSError as e:
113            print(f"\n(could not reach the server at {url}: {e})")
114            messages.pop()
115            continue
116        dt = time.time() - t0
117        print(f"\n{gray}[{n} chunks in {dt:.1f} s]{reset}")
118        messages.append({"role": "assistant", "content": "".join(answer)})
119
120
121if __name__ == "__main__":
122    sys.exit(main())