Files
CyberGril/src/cybergril/providers/llm/openai_compat.py
T
xiaomoandmultica-agent b8ec832f35 HEL-908: terminal chat.cancelled + no-revive gate for text interrupt; reasoning/content separation at the adapter seam
Bug 1 (recorded call1): server-side cancel ended the voice SSE without a
terminal frame BEFORE the first delta (worker.log:108 SDK retry 13ms after
the text POST); the adapter raised a connection error, livekit-agents 1.8.8
silently retried the same turn_id, the retry re-acquired the gate, cancelled
the user's text turn and re-spoke a full ~32s reply. The HEL-907 claim that
the _retry_on_chunk_sent guard never worked is corrected: the guard only
applies after output (output_sent), verified against the installed SDK
source. Fix: explicit chat.cancelled terminal frame; a cancelled turn_id is
refused re-activation (never touches the newer active turn); the worker ends
cancelled turns on the SDK's own 499 path (no retry) and stops the cached
playout via SpeechHandle.interrupt(); a server_cancelled latch short-circuits
any re-entry with zero network. Failed-turn retries, completed-turn replay
and receipt validation are unchanged (dedicated tests).

Bug 2 (recorded row id=12): the endpoint streams implicit-open reasoning
plus a stray </think> inline in content into subtitles and TTS. Fix:
ReasoningSeparator at the OpenAI-compat adapter seam (cross-chunk safe,
reasoning_content field side-channel on LLMDelta.reasoning, never persisted)
plus a turn-level split before persist/final/receipt. Recorded stream
replays clean at every chunk size; normal zh/en content preserved
byte-for-byte; documented residual: implicit-open reasoning whose closer
lies beyond the 128-char hold streams partially (persistence stays clean).

Offline verification: .venv311 full suite 445 passed / 5 skipped (2
pre-existing test_r3 failures fail identically at 5625de6); real-SDK harness
(livekit-agents 1.8.8, agent venv) 5/5; reasoning separation 37/37; ruff
clean. Zero real requests, zero deployment, no dependency changes.

Co-authored-by: multica-agent <github@multica.ai>
2026-10-28 21:27:08 +08:00

154 lines
5.2 KiB
Python

"""OpenAI 兼容的 LLM 适配器。
一个适配器覆盖:DeepSeek / Qwen / vLLM / llama.cpp / Ollama / OpenRouter /
以及任何实现了 /v1/chat/completions 的服务。
这是全项目唯一一个"几乎不需要自定义"的地方——因为 LLM 领域
已经被 OpenAI 的接口事实统一了。
"""
from __future__ import annotations
import json
from collections.abc import AsyncIterator
import httpx
from ...contracts import (
Capabilities,
HealthStatus,
LLMDelta,
LLMMessage,
Modality,
Streaming,
)
from ..base import ProviderError
from .base import LLMProvider
from .reasoning import ReasoningSeparator
class OpenAICompatLLM(LLMProvider):
"""任何 OpenAI 兼容端点。"""
name = "openai_compat"
def __init__(
self,
*,
base_url: str,
model: str,
api_key: str | None = None,
timeout: float = 60.0,
languages: frozenset[str] = frozenset({"zh", "en"}),
max_context: int | None = None,
) -> None:
self.base_url = base_url.rstrip("/")
self.model = model
self._api_key = api_key
self._client = httpx.AsyncClient(
base_url=self.base_url,
timeout=httpx.Timeout(timeout, connect=10.0),
headers=self._headers(api_key),
)
self._languages = languages
self._max_context = max_context
@staticmethod
def _headers(api_key: str | None) -> dict[str, str]:
h = {"Content-Type": "application/json"}
if api_key:
h["Authorization"] = f"Bearer {api_key}"
return h
@property
def capabilities(self) -> Capabilities:
return Capabilities(
modality=Modality.TEXT,
streaming=Streaming.NATIVE,
languages=self._languages,
max_input=self._max_context,
)
async def health(self) -> HealthStatus:
try:
r = await self._client.get("/models", timeout=5.0)
return HealthStatus(ok=r.is_success and any(m.get("id") == self.model for m in r.json().get("data", [])), detail=str(r.status_code))
except (httpx.HTTPError, ValueError, TypeError, AttributeError) as exc:
return HealthStatus(ok=False, detail=f"{type(exc).__name__}: {exc}")
async def stream(
self,
messages: list[LLMMessage],
*,
temperature: float | None = None,
max_tokens: int | None = None,
stop: list[str] | None = None,
extra: dict[str, object] | None = None,
) -> AsyncIterator[LLMDelta]:
payload: dict[str, object] = {
"model": self.model,
"messages": [{"role": m.role, "content": m.content} for m in messages],
"stream": True,
}
if temperature is not None:
payload["temperature"] = temperature
if max_tokens is not None:
payload["max_tokens"] = max_tokens
if stop:
payload["stop"] = stop
if extra:
payload.update(extra)
async with self._client.stream(
"POST", "/chat/completions", json=payload
) as resp:
if resp.status_code >= 400:
body = (await resp.aread()).decode("utf-8", "replace")
raise ProviderError(
f"LLM {self.name} HTTP {resp.status_code}: {body[:400]}"
)
# HEL-908: reasoning/user-content separation at the adapter seam —
# reasoning_content deltas (DeepSeek-style field) go to the
# reasoning side-channel, inline <think> conventions are stripped
# cross-chunk; only visible text ever reaches delta.text.
separator = ReasoningSeparator()
async for line in resp.aiter_lines():
if not line.startswith("data:"):
continue
data = line[5:].strip()
if data == "[DONE]":
tail_visible, tail_reasoning = separator.finish()
if tail_visible or tail_reasoning:
yield LLMDelta(text=tail_visible, reasoning=tail_reasoning)
yield LLMDelta(done=True)
return
try:
obj = json.loads(data)
except json.JSONDecodeError:
continue
choice = (obj.get("choices") or [{}])[0]
delta = choice.get("delta") or {}
text = delta.get("content") or ""
field_reasoning = (
delta.get("reasoning_content") or delta.get("reasoning") or ""
)
visible, dropped = separator.feed(text) if text else ("", "")
reasoning = dropped + field_reasoning
finish = choice.get("finish_reason")
usage = obj.get("usage") or {}
if visible or reasoning or finish or usage:
yield LLMDelta(
text=visible,
reasoning=reasoning,
done=False,
finish_reason=finish,
usage=usage if isinstance(usage, dict) else {},
)
async def aclose(self) -> None:
await self._client.aclose()