diff options
Diffstat (limited to 'deckit/modules')
| -rw-r--r-- | deckit/modules/assistant.py | 114 |
1 files changed, 114 insertions, 0 deletions
diff --git a/deckit/modules/assistant.py b/deckit/modules/assistant.py index 088cac3..3069876 100644 --- a/deckit/modules/assistant.py +++ b/deckit/modules/assistant.py @@ -104,3 +104,117 @@ def hears(models, wanted): or next((m for m in local if m.get("status") != "unloaded"), None)) inputs = m.get("inputs") if m else None return inputs is None or "audio" in inputs + + +def make(cfg: dict) -> Module: + shell = os.path.expanduser(cfg.get("assistant", {}).get("shell", "")) + lock = threading.Lock() # guards st + send_lock = threading.Lock() # one writer on the socket at a time + stop = threading.Event() + st = blank() + conn = {"sock": None, "qarma": None} + + def send(cmd): + s = conn["sock"] + if s is None: + raise ModuleError("assistant not running") + try: + with send_lock: + s.sendall((json.dumps(cmd) + "\n").encode()) + except OSError as e: + raise ModuleError(f"assistant: {e}") from None + + def wanted(): + # Caller holds lock. As the canvas: the chat's pick, else the + # preferred model, else none (the daemon uses what is loaded). + return st["chatModel"] or (st["catalog"] or {}).get("preferred") or None + + def with_model(cmd): + with lock: + m = wanted() + return {**cmd, "model": m} if m else cmd + + def loop(): + while not stop.is_set(): + s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + s.connect(str(SOCK)) + except OSError as e: + s.close() + with lock: + st.update(connected=False, error=str(e) or type(e).__name__) + stop.wait(5) + continue + conn["sock"] = s + with lock: + st.update(connected=True, error=None) + try: + send({"type": "models"}) + for line in s.makefile("r", encoding="utf-8"): + try: + e = json.loads(line) + except ValueError: + continue + with lock: + fold(st, e) + except (OSError, ModuleError): + pass + conn["sock"] = None + s.close() + with lock: + st.update(connected=False, error="disconnected") + stop.wait(5) + + def state(): + with lock: + out = json.loads(json.dumps(st)) # a copy: the reader keeps writing + out["wanted"] = wanted() + out["hears"] = hears(st["models"], out["wanted"]) + return out + + def ask(body): + text = body.get("text") + if not isinstance(text, str) or not text.strip(): + raise ModuleError("text required") + send(with_model({"type": "ask", "text": text})) + + def model(body): + mid = body.get("id") + with lock: + m = next((x for x in st["models"] if x.get("id") == mid), None) + if m is None: + raise ModuleError("unknown model") + was_cloud = any(x.get("cloud") and x.get("id") == wanted() for x in st["models"]) + # Moving a chat with turns to the cloud sends its history there. + if m.get("cloud") and not was_cloud and st["turns"]: + st["notice"] = f"History in this chat goes to {m.get('provider')}." + st["chatModel"] = mid + + def voice(data): + if data[:4] != b"RIFF" or data[8:12] != b"WAVE": + raise ModuleError("not a WAV") + VOICE.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + tmp = VOICE.with_suffix(".tmp") + tmp.write_bytes(data) + os.replace(tmp, VOICE) + send(with_model({"type": "ask", "text": "", "audio": str(VOICE)})) + + def close(): + stop.set() + s = conn["sock"] + if s is not None: + try: + s.shutdown(socket.SHUT_RDWR) + except OSError: + pass + + return Module( + name="assistant", title="Assistant", state=state, + actions={"ask": ask, "stop": lambda b: send({"type": "stop"}), + "new": lambda b: send({"type": "new"}), + "models": lambda b: send({"type": "models"}), + "model": model, "voice": voice}, + uploads={"voice": ("audio/wav", MAX_VOICE)}, + start=lambda: threading.Thread(target=loop, daemon=True).start(), + stop=close, + ) |
