"""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 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]}" ) async for line in resp.aiter_lines(): if not line.startswith("data:"): continue data = line[5:].strip() if data == "[DONE]": 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 "" finish = choice.get("finish_reason") usage = obj.get("usage") or {} if text or finish or usage: yield LLMDelta( text=text, done=False, finish_reason=finish, usage=usage if isinstance(usage, dict) else {}, ) async def aclose(self) -> None: await self._client.aclose()