stram response, like ais

This commit is contained in:
Stefano Zini
2026-11-05 08:50:19 +01:00
parent d3c6816181
commit 19de4654ff
6 changed files with 72 additions and 18 deletions
+20
View File
@@ -193,6 +193,26 @@ def post(body, vision, timeout):
if e.code == 400: raise # callers retry 400 without response_format
raise RuntimeError(f"Copilot {r[1]}: HTTP {e.code} {e.read()[:300].decode(errors='replace')}") from e
def stream(body, timeout):
"""Like post() for text calls, but yields the reply text as it is generated (OpenAI SSE: local llama-server and Copilot).
Anthropic is not streamed here: its whole reply is yielded at once."""
k = current(False); r = REMOTE.get(k)
if r and r[3] == "anthropic": yield content(post(body, False, timeout), "ask"); return
if not r:
req = urllib.request.Request(f"http://127.0.0.1:{PORT}/v1/chat/completions", json.dumps({**body, "model": k, "stream": True}).encode(), {"Content-Type": "application/json"}); op = _open
else:
tok, base = _token(r[3])
b = {**{x: v for x, v in body.items() if x != "chat_template_kwargs"}, "model": r[1], "stream": True}
req = urllib.request.Request(base + "/chat/completions", json.dumps(b).encode(), {"Authorization": "Bearer " + tok, "Content-Type": "application/json", **_HDR}); op = _ropen()
with op(req, timeout=timeout) as f:
for line in f:
# SSE lines look like b"data: {json}"; the stream ends with "data: [DONE]".
if not line.startswith(b"data: "): continue
d = line[6:].strip()
if d == b"[DONE]": break
ch = json.loads(d).get("choices")
if ch and ch[0].get("delta", {}).get("content"): yield ch[0]["delta"]["content"]
# Persist the GUI choice as "<vision key> <text key>" in out/_global/llm.txt (read by current()).
def choose(vision_key, text_key): CHOICE.write_text(f"{vision_key} {text_key}")