- complete_json(): log model/max_tokens + raw provider text (1500 cap) when json.loads fails, so a truncated judge reply is diagnosable from the log - complete()/complete_conversation(): log reasoning_content head on empty content (hidden reasoning starves the shared max_tokens cap) - simulator.judge(): max_tokens 2000 -> 6000 (server accepts 8000) - tests: pin judge budget; new test_llm_failure_logging.py pins the logging (autouse fixture restores app.llm logger disabled by alembic fileConfig) 547 passed. Incident #4 (500 char 125).
238 lines
9.1 KiB
Python
238 lines
9.1 KiB
Python
"""OpenAI-compatible LLM client (OpenAI / DeepSeek / custom base URL).
|
|
|
|
Mirrors the MiroFish provider-agnostic pattern. Credentials live in .env only.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import logging
|
|
import re
|
|
import time
|
|
from typing import Any
|
|
|
|
from openai import OpenAI
|
|
|
|
from .config import Config
|
|
|
|
|
|
class LLMError(Exception):
|
|
pass
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def _strip_thinking_trace(text: str) -> str:
|
|
"""Remove ReACT-style chain-of-thought / fences, keep the final JSON text."""
|
|
for fence in ("```json", "```"):
|
|
idx = text.rfind(fence)
|
|
if idx != -1:
|
|
after = text[idx:].lstrip()
|
|
lang_len = after.find("\n")
|
|
body = after[lang_len:] if lang_len != -1 else after
|
|
end = body.rfind("```")
|
|
if end != -1:
|
|
body = body[:end]
|
|
body = body.strip()
|
|
if body:
|
|
return body
|
|
for marker in ("\n\n[", "\n\n{"):
|
|
idx = text.rfind(marker)
|
|
if idx != -1:
|
|
candidate = text[idx:].strip()
|
|
if candidate and candidate[0] in "{[":
|
|
return candidate
|
|
return text
|
|
|
|
|
|
class LLMClient:
|
|
def __init__(
|
|
self,
|
|
*,
|
|
base_url: str | None = None,
|
|
api_key: str | None = None,
|
|
model: str | None = None,
|
|
) -> None:
|
|
self.base_url = base_url or Config.LLM_BASE_URL
|
|
self.api_key = api_key or Config.LLM_API_KEY
|
|
self.model = model or Config.LLM_MODEL
|
|
if not self.api_key:
|
|
raise LLMError("LLM_API_KEY is not configured in .env")
|
|
if not self.base_url:
|
|
raise LLMError("LLM_BASE_URL is not configured (unknown provider)")
|
|
self.max_attempts = max(1, Config.LLM_MAX_ATTEMPTS)
|
|
self.retry_delay = Config.LLM_RETRY_DELAY_SECONDS
|
|
self.client = OpenAI(base_url=self.base_url, api_key=self.api_key, timeout=180.0, max_retries=0)
|
|
|
|
def _create(self, *, model: str, temperature: float, max_tokens: int, messages, extra_body):
|
|
"""Run chat.completions.create, retrying transient failures.
|
|
|
|
The local LLM server is shared (it also serves Hermes): a concurrent long
|
|
generation serializes requests, so a request can be dropped by a client
|
|
timeout or a connection reset while it is queued. Retry those transient
|
|
cases (openai.APIConnectionError — incl. APITimeoutError) up to
|
|
Config.LLM_MAX_ATTEMPTS times so chat survives the queue; a 4xx from the
|
|
server (bad key/model) is NOT transient and raises immediately.
|
|
"""
|
|
import logging
|
|
from openai import APIConnectionError
|
|
|
|
logger = logging.getLogger(__name__)
|
|
for attempt in range(1, self.max_attempts + 1):
|
|
try:
|
|
return self.client.chat.completions.create(
|
|
model=model,
|
|
temperature=temperature,
|
|
max_tokens=max_tokens,
|
|
messages=messages,
|
|
extra_body=extra_body,
|
|
)
|
|
except APIConnectionError as exc:
|
|
if attempt == self.max_attempts:
|
|
raise
|
|
logger.warning(
|
|
"LLM attempt %d/%d failed (%s); retrying in %.1fs",
|
|
attempt,
|
|
self.max_attempts,
|
|
exc,
|
|
self.retry_delay,
|
|
)
|
|
time.sleep(self.retry_delay)
|
|
# Unreachable: the loop either returns a response or raises.
|
|
raise LLMError("LLM call failed after retries")
|
|
|
|
def complete(
|
|
self,
|
|
system_prompt: str,
|
|
user_prompt: str,
|
|
*,
|
|
temperature: float = 0.5,
|
|
max_tokens: int = 3000,
|
|
thinking: bool = True,
|
|
) -> str:
|
|
# Always keep reasoning SEPARATE (llama.cpp: enable_thinking=true puts it in
|
|
# reasoning_content, content stays clean). Omitting the field or false makes
|
|
# the model write the chain inline into content — which corrupts JSON
|
|
# responses ("Unterminated string" live 500) and persona parsing. The
|
|
# `thinking` param is retained for API compatibility; on this provider the
|
|
# mode is always "separated".
|
|
extra_body = {"enable_thinking": True}
|
|
try:
|
|
resp = self._create(
|
|
model=self.model,
|
|
temperature=temperature,
|
|
max_tokens=max_tokens,
|
|
messages=[
|
|
{"role": "system", "content": system_prompt},
|
|
{"role": "user", "content": user_prompt},
|
|
],
|
|
extra_body=extra_body,
|
|
)
|
|
except Exception as exc: # network/auth/provider
|
|
raise LLMError(f"LLM call failed: {exc}") from exc
|
|
text = (resp.choices[0].message.content or "").strip()
|
|
if not text:
|
|
# content empty even with budget: the hidden reasoning consumed the
|
|
# whole max_tokens (it is a shared cap on this llama.cpp endpoint).
|
|
reasoning = getattr(resp.choices[0].message, "reasoning_content", "") or ""
|
|
logger.error(
|
|
"LLM returned empty content (model=%s max_tokens=%d); the hidden "
|
|
"reasoning (shared cap) likely consumed the whole budget. "
|
|
"reasoning_content head (first 1500 chars): %s",
|
|
self.model,
|
|
max_tokens,
|
|
reasoning[:1500],
|
|
)
|
|
raise LLMError("LLM returned empty response")
|
|
return text
|
|
|
|
def complete_json(
|
|
self,
|
|
system_prompt: str,
|
|
user_prompt: str,
|
|
*,
|
|
temperature: float = 0.2,
|
|
max_tokens: int = 6000,
|
|
thinking: bool = True,
|
|
) -> dict[str, Any]:
|
|
text = self.complete(
|
|
system_prompt,
|
|
user_prompt,
|
|
temperature=temperature,
|
|
max_tokens=max_tokens,
|
|
thinking=thinking,
|
|
)
|
|
text = _strip_thinking_trace(text)
|
|
try:
|
|
return json.loads(text)
|
|
except json.JSONDecodeError:
|
|
# Last-ditch: strip leading text before the first { or [
|
|
match = re.search(r"[{\[].*[}\]]", text, re.DOTALL)
|
|
if match:
|
|
try:
|
|
return json.loads(match.group(0))
|
|
except json.JSONDecodeError:
|
|
pass
|
|
# The raw provider output is the only thing that explains a JSON
|
|
# failure (truncated mid-string, inline reasoning, code fence) —
|
|
# log it, capped, so live 500s are debuggable from the server log.
|
|
snippet = text if len(text) <= 1500 else text[:1500] + "…[truncated]"
|
|
logger.error(
|
|
"LLM returned invalid JSON (model=%s max_tokens=%d)\n--- raw output (first %d chars) ---\n%s\n--- end raw output ---",
|
|
self.model,
|
|
max_tokens,
|
|
min(len(text), 1500),
|
|
snippet,
|
|
)
|
|
raise LLMError("LLM returned invalid JSON") from None
|
|
|
|
def complete_conversation(
|
|
self,
|
|
messages: list[dict[str, str]],
|
|
*,
|
|
temperature: float = 0.6,
|
|
max_tokens: int = 1200,
|
|
) -> str:
|
|
# Normalize internal role labels (customer/seller) to the roles an OpenAI-compatible
|
|
# chat endpoint accepts: system/user/assistant. customer=assistant (the persona/LLM),
|
|
# seller=user (the trainee). Anything else maps to a safe default.
|
|
api_messages = []
|
|
for m in messages:
|
|
role = (m.get("role") or "").lower()
|
|
if role == "system":
|
|
mapped = "system"
|
|
elif role in ("customer", "assistant"):
|
|
mapped = "assistant"
|
|
elif role in ("seller", "user"):
|
|
mapped = "user"
|
|
else:
|
|
mapped = "user"
|
|
api_messages.append({"role": mapped, "content": m.get("text") or m.get("content") or ""})
|
|
try:
|
|
# enable_thinking=true keeps the model's reasoning in reasoning_content
|
|
# so the reply text stays clean (see complete()).
|
|
resp = self._create(
|
|
model=self.model,
|
|
temperature=temperature,
|
|
max_tokens=max_tokens,
|
|
messages=api_messages,
|
|
extra_body={"enable_thinking": True},
|
|
)
|
|
except Exception as exc:
|
|
raise LLMError(f"LLM call failed: {exc}") from exc
|
|
text = (resp.choices[0].message.content or "").strip()
|
|
if not text:
|
|
# content empty even with budget: the hidden reasoning consumed the
|
|
# whole max_tokens (it is a shared cap on this llama.cpp endpoint).
|
|
reasoning = getattr(resp.choices[0].message, "reasoning_content", "") or ""
|
|
logger.error(
|
|
"LLM returned empty content (model=%s max_tokens=%d); the hidden "
|
|
"reasoning (shared cap) likely consumed the whole budget. "
|
|
"reasoning_content head (first 1500 chars): %s",
|
|
self.model,
|
|
max_tokens,
|
|
reasoning[:1500],
|
|
)
|
|
raise LLMError("LLM returned empty response")
|
|
return text
|