unis-oa/backend/app/service/llm.py

568 lines
24 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""大模型调用客户端:五种报文各自的收发都在这里,业务侧只看到「发出去、拿回一段话」。
设计上的三条约定:
* **只依赖标准库**(``urllib``),与 Hub 客户端一致,不为了调个接口再引一个 httpx;
* **协议差异只体现在三处**:请求体长什么样、正文在响应的哪一段、模型清单怎么列。
路径与鉴权头由 :class:`app.llmconfig.Connection` 拼好,这里只管收发;
* **错误一律翻成一句能照着改的中文**。服务商返回的原文进日志,界面上只留
「密钥不对 / 地址填错了 / 被限流了」这类结论,并且过一遍 :func:`~app.llmconfig.redact`
把密钥摘掉。
入口三个:
``chat(conn, prompt)`` 单轮对话,业务功能与界面试运行都用它;
``list_models(conn)`` 拉服务商那边的模型清单,填「可选模型」时省一次手抄;
``probe(conn)`` 「测试连通」按钮:先列模型,再发一条 1 token 的对话,
两步都能过才算通,返回哪一步验了什么。
"""
from __future__ import annotations
import ipaddress
import json
import logging
import socket
import time
import urllib.parse
import urllib.error
import urllib.request
from dataclasses import dataclass, field
from typing import Any, Sequence
from .. import dbconfig, llmconfig
from ..llmconfig import (
PROTOCOL_AZURE,
PROTOCOL_GEMINI,
PROTOCOL_OLLAMA,
Connection,
LLMConfigError,
redact,
)
logger = logging.getLogger("unisoa.llm")
#: 响应体读取上限:模型返回撑死几十 KB,超大只可能是地址指到了别的地方
MAX_RESPONSE_BYTES = 4 * 1024 * 1024
#: 试运行的提示词与回复在日志里截断到这里
LOG_TEXT_LIMIT = 400
#: 走直连(不看环境变量里的 http_proxy)的目标:回环、内网网段、链路本地
#: 目录里的 Ollama / vLLM / LM Studio / Xinference 与大多数自建网关都长这样,
#: 而开发机上常见的 clash/v2ray 代理(``http_proxy=127.0.0.1:7890``)并不会自己
#: 放行 127.0.0.1,照默认走代理就是「地址明明对,却一直连不上」。
_DIRECT_NETWORKS = tuple(
ipaddress.ip_network(prefix)
for prefix in ("127.0.0.0/8", "::1/128", "10.0.0.0/8", "172.16.0.0/12",
"192.168.0.0/16", "169.254.0.0/16", "100.64.0.0/10")
)
def _wants_direct(url: str) -> bool:
"""这个地址该直连吗:主机名是 localhost,或 IP 落在回环/内网网段里。"""
host = (urllib.parse.urlsplit(url).hostname or "").lower()
if not host:
return False
if host == "localhost":
return True
try:
address = ipaddress.ip_address(host)
except ValueError:
return False
return any(address in network for network in _DIRECT_NETWORKS)
def _opener_for(url: str):
"""回环/内网直连,公网按环境变量的代理走(``no_proxy`` 照旧管用)。"""
if _wants_direct(url):
return urllib.request.build_opener(urllib.request.ProxyHandler({}))
return urllib.request.build_opener()
class LLMError(Exception):
"""调用大模型失败。``retryable`` 决定是否值得按全局补试次数再来一次。"""
def __init__(self, message: str, *, status: int = 0, retryable: bool = False, detail: str = "") -> None:
super().__init__(message)
self.message = message
self.status = status
self.retryable = retryable
self.detail = detail or message
@dataclass
class ChatResult:
"""一次对话的结果。``text`` 是正文,``usage`` 原样留着服务商给的那一小段。"""
text: str = ""
model: str = ""
latency_ms: int = 0
usage: dict[str, Any] = field(default_factory=dict)
finish_reason: str = ""
def as_dict(self) -> dict[str, Any]:
return {
"text": self.text,
"model": self.model,
"latency_ms": self.latency_ms,
"usage": self.usage,
"finish_reason": self.finish_reason,
}
@dataclass
class ProbeResult:
"""「测试连通」的结论:两步各自的结果 + 一句总结。"""
ok: bool = False
message: str = ""
model: str = ""
latency_ms: int = 0
models: tuple[str, ...] = ()
model_source: str = ""
steps: list[dict[str, Any]] = field(default_factory=list)
def as_dict(self) -> dict[str, Any]:
return {
"ok": self.ok,
"message": self.message,
"model": self.model,
"latency_ms": self.latency_ms,
"models": list(self.models),
"model_source": self.model_source,
"steps": self.steps,
}
# ---------------------------------------------------------------------------
# HTTP:一层薄薄的 urllib
# ---------------------------------------------------------------------------
def _request(
conn: Connection,
url: str,
*,
method: str = "POST",
payload: dict[str, Any] | None = None,
timeout: int | None = None,
) -> tuple[int, bytes]:
"""发一个请求,返回 ``(状态码, 响应体)``。非 2xx 不在这里翻译,交给上层按协议处理。"""
body = None if payload is None else json.dumps(payload, ensure_ascii=False).encode("utf-8")
seconds = int(timeout or conn.timeout_seconds or 60)
request = urllib.request.Request(url, data=body, headers=conn.headers(), method=method)
started = time.monotonic()
try:
with _opener_for(url).open(request, timeout=seconds) as response:
data = response.read(MAX_RESPONSE_BYTES + 1)
status = int(getattr(response, "status", 200) or 200)
except urllib.error.HTTPError as exc:
# 错误响应体里往往写着原因(quota、模型名不对),留着给上层判读
raw = exc.read(MAX_RESPONSE_BYTES) if exc.fp else b""
logger.info("LLM %s 返回 %s:%s(%.0fms)", conn.label, exc.code, _brief(raw), (time.monotonic() - started) * 1000)
return int(exc.code), raw
except urllib.error.URLError as exc:
reason = str(getattr(exc, "reason", exc) or exc)
if _timeout_like(exc):
raise LLMError(
f"{seconds} 秒内没连上或没回话:可能是地址写错、对方排队太久,或本机到这个地址不通",
retryable=True,
detail=reason,
) from exc
hint = "" if _wants_direct(url) else ";本机设了 http_proxy,必要时把地址写进 no_proxy 试试"
raise LLMError(f"连不上这个地址:{reason}{hint}", retryable=True, detail=reason) from exc
except (TimeoutError, socket.timeout, OSError) as exc:
# 读超时在 macOS 上是裸 OSError 而不是 URLError,这里认出来才说得出「超时」
if _timeout_like(exc):
raise LLMError(
f"{seconds} 秒内没连上或没回话:可能是地址写错、对方排队太久,或本机到这个地址不通",
retryable=True,
detail=str(exc),
) from exc
raise LLMError(f"请求没发出去:{exc}", retryable=True, detail=str(exc)) from exc
if len(data) > MAX_RESPONSE_BYTES:
raise LLMError("返回的内容异常地大,接口地址是不是指到别的地方了?", detail=url)
logger.debug("LLM %s %s -> %s(%.0fms)", conn.label, method, status, (time.monotonic() - started) * 1000)
return status, data
def _json(conn: Connection, url: str, raw: bytes, status: int) -> dict[str, Any]:
try:
payload = json.loads(raw.decode("utf-8", "replace") or "{}")
except ValueError as exc:
raise LLMError(
"对方返回的不是 JSON:接口地址多半填到了控制台或网页那一层",
status=status,
detail=redact(raw.decode("utf-8", "replace")[:500], conn.api_key),
) from exc
if isinstance(payload, list):
return {"data": payload}
if not isinstance(payload, dict):
raise LLMError("对方返回的内容看不懂", status=status, detail=str(payload)[:300])
return payload
def _brief(raw: bytes) -> str:
text = (raw or b"").decode("utf-8", "replace").strip().replace("\n", " ")
return text[:300]
def _timeout_like(exc: BaseException) -> bool:
"""这一坨异常到底是不是超时。
同一个「等太久」在不同平台/Python 版本里能长成三种样子:``URLError(TimeoutError)``、
直接抛 ``socket.timeout``,异常文本也叫 "timed out" 或 "The read operation timed out"。
认错了就会把「超时」报成一句没头没尾的「请求没发出去」。
"""
if isinstance(exc, (TimeoutError, socket.timeout)):
return True
reason = getattr(exc, "reason", None)
if isinstance(reason, (TimeoutError, socket.timeout)):
return True
text = str(getattr(exc, "reason", "") or exc).lower()
return "timed out" in text or "timeout" in text
def _fail(conn: Connection, status: int, payload: dict[str, Any], raw: bytes) -> LLMError:
"""把服务商的错误翻成一句中文。
各家错误口径不一样(``error.message`` / ``message`` / ``error_message`` /
Gemini 的 ``error.message``),这里都认一遍,取不到就退回状态码那句。
"""
error = payload.get("error") if isinstance(payload.get("error"), dict) else {}
detail_text = str(
error.get("message")
or payload.get("message")
or payload.get("error_message")
or payload.get("msg")
or _brief(raw)
).strip()
lowered = detail_text.lower()
secrets = (conn.api_key,)
if status in (401, 403):
text = "密钥不对或没有这个权限(401/403)"
elif status == 404:
text = "地址或模型找不到(404)"
if conn.protocol in (llmconfig.PROTOCOL_OPENAI, PROTOCOL_AZURE):
text += ":OpenAI 兼容协议的接口地址要填到前缀那一段,例如 https://api.openai.com/v1;模型名也要跟服务商给的一致"
elif status == 429:
text = "被限流了(429):配额用完或请求太快,稍后再试"
elif status == 400:
text = "请求被拒绝(400):模型名或参数不对"
elif status >= 500:
text = f"服务商那边出错了({status}),稍后再试"
else:
text = f"服务商返回 {status}"
if detail_text:
text = f"{text}|{detail_text[:300]}"
retryable = status >= 500 or status == 429
logger.warning("LLM %s 调用失败 %s:%s", conn.label, status, redact(detail_text, *secrets))
return LLMError(redact(text, *secrets), status=status, retryable=retryable, detail=redact(detail_text, *secrets))
def _raise_for_status(conn: Connection, status: int, raw: bytes, url: str) -> dict[str, Any]:
"""2xx 就解析 JSON 返回,否则抛 :class:`LLMError`。"""
if 200 <= status < 300:
return _json(conn, url, raw, status)
try:
payload = json.loads(raw.decode("utf-8", "replace") or "{}")
if not isinstance(payload, dict):
payload = {}
except ValueError:
payload = {}
raise _fail(conn, status, payload, raw)
def _with_retry(conn: Connection, action):
"""按全局补试次数(``ai_retries``)重试「连不上 / 超时 / 5xx / 限流」这类错误。"""
attempts = max(0, min(5, int(dbconfig.value("ai_retries", 2) or 0))) + 1
last: LLMError | None = None
for attempt in range(attempts):
try:
return action()
except LLMError as exc:
last = exc
if not exc.retryable or attempt + 1 >= attempts:
break
logger.info("LLM %s 第 %s 次失败(%s),补试", conn.label, attempt + 1, exc.message)
time.sleep(min(2.0, 0.4 * (attempt + 1)))
raise last or LLMError("调用失败")
# ---------------------------------------------------------------------------
# 请求体:按协议搭
# ---------------------------------------------------------------------------
Message = dict[str, str]
def _messages(prompt: str, history: Sequence[Message] | None, system: str) -> list[Message]:
turns: list[Message] = []
if system:
turns.append({"role": "system", "content": system})
for item in history or []:
role = str(item.get("role") or "user")
if role not in {"user", "assistant", "system"}:
role = "user"
turns.append({"role": role, "content": str(item.get("content") or "")})
turns.append({"role": "user", "content": prompt})
return turns
def _build_payload(conn: Connection, model: str, turns: list[Message], *, max_tokens: int, temperature: float) -> dict:
"""把统一的「消息 + 参数」翻译成各家要的请求体。"""
extra = dict(conn.extra_body or {})
if conn.protocol in (llmconfig.PROTOCOL_OPENAI, PROTOCOL_AZURE):
payload: dict[str, Any] = {"model": model, "messages": turns, "stream": False}
if max_tokens > 0:
payload["max_tokens"] = max_tokens
payload["temperature"] = temperature
elif conn.protocol == llmconfig.PROTOCOL_ANTHROPIC:
system_parts = [item["content"] for item in turns if item["role"] == "system"]
payload = {
"model": model,
# Anthropic 把 system 单独拎出来,而且 max_tokens 是必填
"system": "\n\n".join(system_parts),
"messages": [item for item in turns if item["role"] != "system"],
"max_tokens": max_tokens or 1024,
"temperature": temperature,
}
elif conn.protocol == PROTOCOL_GEMINI:
system_parts = [item["content"] for item in turns if item["role"] == "system"]
payload = {
"contents": [
{"role": "model" if item["role"] == "assistant" else "user", "parts": [{"text": item["content"]}]}
for item in turns
if item["role"] != "system"
],
"generationConfig": {"temperature": temperature, "maxOutputTokens": max_tokens or 1024},
}
if system_parts:
payload["systemInstruction"] = {"parts": [{"text": "\n\n".join(system_parts)}]}
elif conn.protocol == PROTOCOL_OLLAMA:
options: dict[str, Any] = {"temperature": temperature}
if max_tokens > 0:
options["num_predict"] = max_tokens
payload = {"model": model, "messages": turns, "stream": False, "options": options}
else: # pragma: no cover - 新加协议忘了在这里补时按 OpenAI 发,至少不是崩
payload = {"model": model, "messages": turns, "stream": False}
payload.update(extra)
return payload
# ---------------------------------------------------------------------------
# 响应解读:正文在哪一段
# ---------------------------------------------------------------------------
def _read_reply(conn: Connection, payload: dict[str, Any]) -> tuple[str, str, str, dict[str, Any]]:
"""返回 ``(正文, 实际用的模型, 结束原因, usage)``。"""
if conn.protocol in (llmconfig.PROTOCOL_OPENAI, PROTOCOL_AZURE):
choices = payload.get("choices") or []
if not choices:
raise LLMError("对方回了一个空答复(没有 choices)", detail=str(payload)[:300])
first = choices[0] if isinstance(choices[0], dict) else {}
message = first.get("message") if isinstance(first.get("message"), dict) else {}
text = str(message.get("content") or first.get("text") or "")
return text, str(payload.get("model") or first.get("model") or ""), str(first.get("finish_reason") or ""), _usage(payload)
if conn.protocol == llmconfig.PROTOCOL_ANTHROPIC:
blocks = payload.get("content") or []
text = "".join(
str(block.get("text") or "") for block in blocks if isinstance(block, dict) and block.get("type") in (None, "text")
)
return text, str(payload.get("model") or ""), str(payload.get("stop_reason") or ""), _usage(payload)
if conn.protocol == PROTOCOL_GEMINI:
candidates = payload.get("candidates") or []
first = candidates[0] if candidates and isinstance(candidates[0], dict) else {}
parts = ((first.get("content") or {}).get("parts") or []) if isinstance(first.get("content"), dict) else []
text = "".join(str(part.get("text") or "") for part in parts if isinstance(part, dict))
return text, str(payload.get("modelVersion") or ""), str(first.get("finishReason") or ""), _usage(payload)
if conn.protocol == PROTOCOL_OLLAMA:
message = payload.get("message") if isinstance(payload.get("message"), dict) else {}
return (
str(message.get("content") or payload.get("response") or ""),
str(payload.get("model") or ""),
str(payload.get("done_reason") or ""),
_usage(payload),
)
raise LLMError(f"暂时不认得协议 {conn.protocol} 的返回格式") # pragma: no cover
def _usage(payload: dict[str, Any]) -> dict[str, Any]:
for key in ("usage", "usageMetadata", "usage_metadata"):
value = payload.get(key)
if isinstance(value, dict):
return {str(k): v for k, v in value.items() if isinstance(v, (int, float))}
return {}
def _read_model_ids(conn: Connection, payload: dict[str, Any]) -> tuple[str, ...]:
"""模型清单:OpenAI/Anthropic 是 ``data[].id``,Gemini 是 ``models[].name``,Ollama 是 ``models[].name``。"""
out: list[str] = []
def push(name: str) -> None:
name = str(name or "").strip()
if name and name not in out:
out.append(name)
if conn.protocol == PROTOCOL_GEMINI:
for item in payload.get("models") or []:
if not isinstance(item, dict):
continue
methods = item.get("supportedGenerationMethods") or []
if methods and "generateContent" not in [str(method) for method in methods]:
continue
push(str(item.get("name") or "").split("/")[-1])
else:
rows = payload.get("data")
if rows is None:
rows = payload.get("models") or payload.get("body") or []
for item in rows if isinstance(rows, list) else []:
if isinstance(item, str):
push(item)
elif isinstance(item, dict):
push(str(item.get("id") or item.get("name") or item.get("model") or ""))
return tuple(out)
# ---------------------------------------------------------------------------
# 对外三个入口
# ---------------------------------------------------------------------------
def chat(
conn: Connection,
prompt: str,
*,
model: str = "",
history: Sequence[Message] | None = None,
system: str = "",
max_tokens: int | None = None,
temperature: float | None = None,
) -> ChatResult:
"""单轮对话。``prompt`` 为空直接挡掉:空提示词各家给的错千差万别。"""
text_prompt = str(prompt or "").strip()
if not text_prompt:
raise LLMConfigError("要说的话不能为空")
used_model = conn.pick_model(model)
turns = _messages(text_prompt, history, system or conn.system_prompt)
tokens = int(conn.max_tokens if max_tokens is None else max_tokens)
temp = float(conn.temperature if temperature is None else temperature)
payload = _build_payload(conn, used_model, turns, max_tokens=tokens, temperature=temp)
url = conn.chat_url(used_model)
def once() -> ChatResult:
started = time.monotonic()
status, raw = _request(conn, url, payload=payload)
body = _raise_for_status(conn, status, raw, url)
reply, real_model, finish, usage = _read_reply(conn, body)
return ChatResult(
text=reply,
model=real_model or used_model,
latency_ms=int((time.monotonic() - started) * 1000),
usage=usage,
finish_reason=finish,
)
result = _with_retry(conn, once)
if not result.text.strip():
reason = f"(结束原因 {result.finish_reason})" if result.finish_reason else ""
raise LLMError(f"对方连上了,但没给出文字内容{reason}:可能是内容被安全策略拦下,或 max_tokens 给小了")
return result
def list_models(conn: Connection) -> tuple[str, ...]:
"""拉服务商那边的模型清单。协议不支持列模型时抛一句说明。"""
url = conn.models_url()
if not url:
raise LLMConfigError("这个协议没有「列出模型」接口,模型名请照服务商文档手填")
def once() -> tuple[str, ...]:
status, raw = _request(conn, url, method="GET", timeout=min(20, conn.timeout_seconds or 20))
body = _raise_for_status(conn, status, raw, url)
return _read_model_ids(conn, body)
models = _with_retry(conn, once)
if not models:
raise LLMError("对方回通了但没列出任何模型:可能是这个密钥看不到模型,或该地址不提供列模型接口", detail=url)
return models
def probe(conn: Connection, *, model: str = "", prompt: str = "") -> ProbeResult:
"""「测试连通」:先试列模型,再发一条最短对话,两步都记下来。
分两步是因为它们会分别失败:地址与密钥对了但模型名写错时,列模型能过、对话报 400;
反过来有些网关不给列模型接口,列模型失败但对话是好的。所以**以对话成功为准**,
列模型只当加分项,失败只在步骤里说明。
"""
steps: list[dict[str, Any]] = []
models: tuple[str, ...] = ()
source = ""
try:
models = list_models(conn)
source = "remote"
steps.append({"name": "models", "ok": True, "message": f"列出 {len(models)} 个模型"})
except (LLMError, LLMConfigError) as exc:
message = exc.message if isinstance(exc, LLMError) else str(exc)
steps.append({"name": "models", "ok": False, "message": message})
asked = (model or "").strip()
if not asked:
# 没指定就用配置里的默认模型;配置里也没写就用对方列出来的第一个
asked = conn.default_model or (models[0] if models else "")
if not asked:
detail = steps[0]["message"] if steps else ""
raise LLMError(
"还没法发对话测试:既没配默认模型,对方也没列出模型清单"
+ (f"(列模型:{detail})" if detail else ",请先填一个模型名"),
detail=detail,
)
try:
result = chat(conn, prompt or "ping", model=asked, max_tokens=16)
except (LLMError, LLMConfigError) as exc:
message = exc.message if isinstance(exc, LLMError) else str(exc)
steps.append({"name": "chat", "ok": False, "message": message, "model": asked})
return ProbeResult(
ok=False, message=message, model=asked, models=models, model_source=source, steps=steps
)
steps.append(
{
"name": "chat",
"ok": True,
"model": result.model or asked,
"message": f"{result.latency_ms}ms 回了 {len(result.text.strip())} 个字",
}
)
return ProbeResult(
ok=True,
message=f"连通正常:{result.model or asked} 在 {result.latency_ms}ms 内答上了",
model=result.model or asked,
latency_ms=result.latency_ms,
models=models,
model_source=source,
steps=steps,
)
def generate(prompt: str, *, provider_id: str = "", model: str = "", rows: Sequence[Any] = ()) -> ChatResult:
"""业务侧入口:没点名接入时用默认接入;总闸(``ai_enabled``)关着直接拒。
``rows`` 由调用方给(通常是 ``oa_ai_provider`` 的全部启用行),这里不碰数据库,
免得业务代码被会话生命周期绑住。
"""
if not dbconfig.value("ai_enabled", False):
raise LLMConfigError("大模型能力当前是关闭的:到 系统设置 里打开「启用大模型能力」再试")
wanted = (provider_id or "").strip()
if wanted:
chosen = [row for row in rows if str(getattr(row, "id", "")) == wanted]
if not chosen:
raise LLMConfigError("指定的大模型接入不存在")
if not bool(getattr(chosen[0], "enabled", True)):
raise LLMConfigError(f"「{chosen[0].name}」已停用,请先启用或换一条接入")
conn = llmconfig.connection(chosen[0])
else:
conn = llmconfig.default_connection(rows)
return chat(conn, prompt, model=model)