-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcpp_client.py
More file actions
75 lines (63 loc) · 2.46 KB
/
cpp_client.py
File metadata and controls
75 lines (63 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
"""Simple IPC client to communicate with the C++ backend executable.
Protocol: send a single JSON object per line with {"prompt": "..."}
Backend returns a single JSON object per line with {"answer": "..."}
The client launches the executable at `cpp_backend/build/askai_backend` if present.
"""
import json
import os
import subprocess
import threading
import queue
from pathlib import Path
from typing import Optional
class CppBackendClient:
def __init__(self, exe_path: Optional[Path] = None):
self.exe_path = exe_path or Path(__file__).with_name("cpp_backend").joinpath("build", "askai_backend")
self.proc = None
self._read_q = queue.Queue()
def available(self) -> bool:
return self.exe_path.exists()
def start(self):
if not self.available():
return False
if self.proc is not None:
return True
self.proc = subprocess.Popen([str(self.exe_path)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
threading.Thread(target=self._reader_thread, daemon=True).start()
return True
def _reader_thread(self):
assert self.proc and self.proc.stdout
for line in self.proc.stdout:
self._read_q.put(line.strip())
def ask(self, prompt: str, timeout: float = 5.0) -> str:
if not self.start():
raise RuntimeError("C++ backend executable not available: %s" % self.exe_path)
payload = json.dumps({"prompt": prompt})
assert self.proc and self.proc.stdin
self.proc.stdin.write(payload + "\n")
self.proc.stdin.flush()
try:
line = self._read_q.get(timeout=timeout)
except queue.Empty:
raise RuntimeError("Timeout waiting for C++ backend response")
try:
data = json.loads(line)
return data.get("answer", "")
except Exception:
return line
def stop(self):
if self.proc:
try:
self.proc.stdin.write("quit\n")
self.proc.stdin.flush()
except Exception:
pass
self.proc.terminate()
self.proc = None
client = CppBackendClient()
if __name__ == "__main__":
if not client.available():
print("C++ backend not found at", client.exe_path)
else:
client.start()
print(client.ask("What is the capital of France?"))