stram response, like ais
This commit is contained in:
+20
-4
@@ -65,19 +65,24 @@ def make_pdf(name):
|
||||
return pdf
|
||||
|
||||
|
||||
def ask_once(q):
|
||||
"""Start models, answer, always stop what we started (serialized: one ask at a time)."""
|
||||
def ask_events(q):
|
||||
"""Start models, yield memory.ask_stream events, always stop what we started (serialized: one ask at a time)."""
|
||||
with LOCK:
|
||||
own = []
|
||||
try:
|
||||
# Embed (CPU) and chat LLM start first; both are stopped in finally.
|
||||
own = [p for p in (llama.start_embed(log=db.GLOBAL / "embed.log"), llama.start(vision=False, log=db.GLOBAL / "llama.log")) if p is not None]
|
||||
# Answer with the running models.
|
||||
return memory.ask(q)
|
||||
yield from memory.ask_stream(q)
|
||||
finally:
|
||||
for p in own: p.terminate()
|
||||
|
||||
|
||||
def ask_once(q):
|
||||
"""Whole answer as {"answer", "sources"} (the non-streaming /ask)."""
|
||||
ev = list(ask_events(q))
|
||||
return {"answer": "".join(e["t"] for e in ev if "t" in e).strip() or "Risposta non disponibile.", "sources": ev[0]["sources"]}
|
||||
|
||||
|
||||
def now(): return time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
@@ -483,6 +488,17 @@ class H(BaseHTTPRequestHandler):
|
||||
if ask_blocked(): return self._send("pipeline in corso: riprova dopo".encode(), 409)
|
||||
try: self._json(ask_once(q["q"]))
|
||||
except Exception as e: return self._send(f"errore: {e!r}".encode(), 503)
|
||||
elif u.path == "/ask_stream":
|
||||
if not q.get("q", "").strip(): return self._send("domanda vuota".encode(), 400)
|
||||
if ask_blocked(): return self._send("pipeline in corso: riprova dopo".encode(), 409)
|
||||
# NDJSON, one event per line, no Content-Length: the connection closes at the end (HTTP/1.0 handler).
|
||||
self.send_response(200); self.send_header("Access-Control-Allow-Origin", "*"); self.send_header("Content-Type", "application/x-ndjson; charset=utf-8"); self.send_header("Cache-Control", "no-cache"); self.end_headers()
|
||||
try:
|
||||
for e in ask_events(q["q"]): self.wfile.write(json.dumps(e, ensure_ascii=False).encode() + b"\n"); self.wfile.flush()
|
||||
except Exception as e:
|
||||
# Headers are already sent, so the error travels as an event.
|
||||
try: self.wfile.write(json.dumps({"err": repr(e)}).encode() + b"\n")
|
||||
except OSError: pass
|
||||
else: self._send(b"not found", 404)
|
||||
# POST: ingestion (/chunk, /events, /upload), recording control, and actions.
|
||||
def do_POST(self):
|
||||
|
||||
Reference in New Issue
Block a user