matrix-terminal-posthog-cv/app/llm_client.py
Kyle Stevenson c0d41413a6 backend core
2026-08-11 14:20:56 +01:00

78 lines
2.9 KiB
Python

import json
import logging
from collections.abc import AsyncIterator
import httpx
from .config import LLAMACPP_BASE_URL, LLAMACPP_MODEL
logger = logging.getLogger(__name__)
# No read timeout as model generation can take a while to stream.
STREAM_TIMEOUT = httpx.Timeout(connect=10.0, read=None, write=10.0, pool=10.0)
WARMUP_TIMEOUT = httpx.Timeout(connect=10.0, read=60.0, write=10.0, pool=10.0)
async def stream_chat(messages: list[dict], model: str | None = None) -> AsyncIterator[str]:
"""
Streams llama.cpp /v1/chat/completions SSE response,
"""
payload = {"model": model or LLAMACPP_MODEL, "messages": messages, "stream": True}
url = f"{LLAMACPP_BASE_URL}/v1/chat/completions"
try:
async with (
httpx.AsyncClient(timeout=STREAM_TIMEOUT) as client,
client.stream("POST", url, json=payload) as response,
):
if response.status_code != httpx.codes.OK:
body = await response.aread()
detail = body.decode(errors="ignore")
error = f"llama.cpp server returned {response.status_code}: {detail}"
yield json.dumps({"error": error}) + "\n"
return
async for line in response.aiter_lines():
if not line.startswith("data: "):
continue
data = line.removeprefix("data: ").strip()
if data == "[DONE]":
return
try:
chunk = json.loads(data)
except json.JSONDecodeError:
continue
choices = chunk.get("choices") or [{}]
content = choices[0].get("delta", {}).get("content")
if content:
yield json.dumps({"content": content}) + "\n"
except httpx.ConnectError:
error = f"Could not connect to llama.cpp server at {LLAMACPP_BASE_URL}. Is it running?"
yield json.dumps({"error": error}) + "\n"
except httpx.HTTPError as exc:
yield json.dumps({"error": str(exc)}) + "\n"
async def warm_up(system_prompt: str) -> None:
"""
Warms up llama.cpp's slot KV cache with the system prompt so the user's first real
message only has to prefill its own tokens, not the whole persona. Includes a throwaway
user turn when rendering a system-only prompt.
"""
payload = {
"model": LLAMACPP_MODEL,
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": "Hi"},
],
"max_tokens": 1,
"stream": False,
}
url = f"{LLAMACPP_BASE_URL}/v1/chat/completions"
try:
async with httpx.AsyncClient(timeout=WARMUP_TIMEOUT) as client:
response = await client.post(url, json=payload)
response.raise_for_status()
except httpx.HTTPError:
logger.warning("llama.cpp warmup request failed", exc_info=True)