236 lines
11 KiB
Python
236 lines
11 KiB
Python
"""大语言模型(LLM)文本适配器。
|
||
|
||
大模型只负责角色与场景一致性提示词、分镜文案改写等文本任务。定妆图、
|
||
场景图与关键帧一律由独立的图像模型生成,避免把两种能力混在同一份配置里。
|
||
|
||
协议以 OpenAI 兼容的 ``/chat/completions`` 为主。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
from typing import Any
|
||
|
||
import httpx
|
||
|
||
from app.providers.base import (AssetGenRequest, AssetGenResult, Capabilities, FatalProviderError,
|
||
RetryableProviderError, TextProviderAdapter)
|
||
from app.providers.http_generic import _client, _headers, _raise_for_response, get_path, render_template
|
||
from app.providers.studio_assets import MockTextProvider
|
||
|
||
|
||
def _float(config: dict, key: str, default: float | None = None) -> float | None:
|
||
value = config.get(key)
|
||
if value is None or value == "":
|
||
return default
|
||
try:
|
||
return float(value)
|
||
except (TypeError, ValueError):
|
||
return default
|
||
|
||
|
||
def _int(config: dict, key: str, default: int | None = None) -> int | None:
|
||
value = config.get(key)
|
||
if value is None or value == "":
|
||
return default
|
||
try:
|
||
return int(value)
|
||
except (TypeError, ValueError):
|
||
return default
|
||
|
||
|
||
def image_parts(images: list[Any]) -> list[dict]:
|
||
"""把 images 转成多模态片段:字符串直接是图;`{"url","label"}` 会先插一句文字说明。
|
||
|
||
画面质检必须让模型分清「哪几张是镜头帧、哪几张是定妆参考照」,
|
||
否则它会把参考照当成第 1~3 帧,回报一堆根本不存在的「机位跳变」。
|
||
"""
|
||
parts: list[dict] = []
|
||
for item in images:
|
||
if isinstance(item, dict):
|
||
url, label = str(item.get("url") or ""), str(item.get("label") or "")
|
||
else:
|
||
url, label = str(item or ""), ""
|
||
if not url:
|
||
continue
|
||
if label:
|
||
parts.append({"type": "text", "text": label})
|
||
parts.append({"type": "image_url", "image_url": {"url": url}})
|
||
return parts
|
||
|
||
|
||
def _attach_images(body: Any, images: list[Any]) -> Any:
|
||
"""把图片以 OpenAI 多模态格式并进最后一条 user 消息(文本保持原位)。
|
||
|
||
请求体模板是给用户自定义的,`content` 可能已经是数组,也可能整串就是
|
||
`{{prompt}}`;两种都要能塞图,否则画面质检只能在默认模板下工作。
|
||
"""
|
||
if not isinstance(body, dict):
|
||
return body
|
||
messages = body.get("messages")
|
||
if not isinstance(messages, list) or not messages:
|
||
return body
|
||
for index in range(len(messages) - 1, -1, -1):
|
||
message = messages[index]
|
||
if not isinstance(message, dict) or str(message.get("role", "user")) != "user":
|
||
continue
|
||
content = message.get("content")
|
||
if isinstance(content, list):
|
||
parts = list(content)
|
||
elif isinstance(content, str):
|
||
parts = [{"type": "text", "text": content}]
|
||
else:
|
||
continue
|
||
parts += image_parts(images)
|
||
messages[index] = {**message, "content": parts}
|
||
break
|
||
return body
|
||
|
||
|
||
class HttpLLMProvider(TextProviderAdapter):
|
||
"""OpenAI 兼容的纯文本 LLM 适配器。"""
|
||
|
||
_name = "http_llm"
|
||
|
||
@property
|
||
def name(self) -> str:
|
||
return self._name
|
||
|
||
def is_available(self, config: dict | None = None) -> bool:
|
||
config = config or {}
|
||
return bool(config.get("base_url") or config.get("url"))
|
||
|
||
def capabilities(self, config: dict | None = None) -> Capabilities:
|
||
# 看图:默认认为 OpenAI 兼容的对话模型能吃 image_url,模型中心可显式关掉;
|
||
# 关掉后画面质检自动跳过,不会把「模型不支持图」伪装成「画面没问题」。
|
||
vision = bool((config or {}).get("vision", True))
|
||
return Capabilities(modes=("chat", "prompt"), resolutions=(), aspect_ratios=(),
|
||
min_duration=0, max_duration=0,
|
||
max_reference_images=(3 if vision else 0), vision=vision,
|
||
notes="大语言模型:提示词补全、文案改写" + ("、画面质检(看图)" if vision else ""))
|
||
|
||
# ------------------------------------------------------------ 文本
|
||
def generate(self, request: AssetGenRequest, config: dict | None = None) -> AssetGenResult:
|
||
config = dict(config or {})
|
||
if request.kind == "image":
|
||
raise FatalProviderError("大模型不支持图像生成;请使用独立的图像模型",
|
||
code="unsupported_media_type")
|
||
return self._generate_text(request, config)
|
||
|
||
def _generate_text(self, request: AssetGenRequest, config: dict) -> AssetGenResult:
|
||
base_url = str(config.get("base_url") or "").rstrip("/")
|
||
url = str(config.get("url") or (f"{base_url}/chat/completions" if base_url else ""))
|
||
if not url:
|
||
raise FatalProviderError("大模型缺少 base_url / url 配置", code="provider_not_configured")
|
||
model = str(request.params.get("model") or config.get("model") or "")
|
||
ctx = {"prompt": request.prompt, "model": model, "params": request.params or {},
|
||
"system": config.get("system_prompt") or ""}
|
||
body = render_template(config.get("body") or {
|
||
"model": "{{model}}",
|
||
"messages": [{"role": "user", "content": "{{prompt}}"}],
|
||
}, ctx)
|
||
if isinstance(body, dict):
|
||
body.setdefault("model", model)
|
||
# 采样参数:用户在模型管理中心配置的默认值优先
|
||
for key in ("temperature", "top_p", "max_tokens", "presence_penalty",
|
||
"frequency_penalty", "seed"):
|
||
if key in body:
|
||
continue
|
||
# 单次请求(如画面质检要 temperature=0)优先于模型中心默认值
|
||
for source in (request.params or {}, config):
|
||
if source.get(key) is not None:
|
||
body[key] = source[key]
|
||
break
|
||
if config.get("stream"):
|
||
body["stream"] = bool(config.get("stream"))
|
||
# extra_body:思考型模型(qwen3.7-plus 等)的 enable_thinking / thinking_budget
|
||
# 只在请求体里才生效,OpenAI 兼容协议没有标准字段,这里统一由它透传。
|
||
# 供应商默认 < 单次请求覆盖,便于「快速规划」临时关掉深度思考。
|
||
for extra in (config.get("extra_body"), (request.params or {}).get("extra_body")):
|
||
if isinstance(extra, dict):
|
||
body.update(extra)
|
||
images = [url for url in ((request.params or {}).get("images") or [])
|
||
if (url.get("url") if isinstance(url, dict) else url)]
|
||
if images:
|
||
if not bool(config.get("vision", True)):
|
||
raise FatalProviderError(
|
||
f"模型 {model} 未开启「支持看图」,无法执行画面质检;"
|
||
"请在模型中心勾选后重试", code="vision_disabled")
|
||
body = _attach_images(body, images)
|
||
headers = _headers(config, "")
|
||
# 深度思考的规划请求动辄输出几千 token,90 秒默认超时会把正常等待掐成
|
||
# 「网络异常」,用户只能看到长时间转圈后报错,所以 LLM 单独放宽到 4 分钟。
|
||
timeout_cfg = dict(config)
|
||
timeout_cfg.setdefault("timeout_seconds", 240)
|
||
# 带图请求(画面质检一次要传七八张)由调用方自己定等待上限更稳妥
|
||
req_timeout = (request.params or {}).get("timeout_seconds")
|
||
if req_timeout:
|
||
timeout_cfg["timeout_seconds"] = float(req_timeout)
|
||
with _client(timeout_cfg) as client:
|
||
try:
|
||
resp = client.post(url, headers=headers, json=body)
|
||
except httpx.HTTPError as exc:
|
||
raise RetryableProviderError(f"大模型请求网络异常:{exc}") from exc
|
||
_raise_for_response(resp, context="大模型请求")
|
||
data = resp.json()
|
||
text = get_path(data, config.get("text_path", "choices.0.message.content"))
|
||
if text is None:
|
||
text = get_path(data, "text") or get_path(data, "output_text")
|
||
if not text:
|
||
raise FatalProviderError(f"大模型响应缺少内容:{data}", code="missing_text")
|
||
usage = data.get("usage") or {}
|
||
return AssetGenResult(text=str(text).strip(),
|
||
metadata={"provider": "http_llm", "model": model,
|
||
"usage": usage})
|
||
|
||
# ------------------------------------------------------------ 连通性探测
|
||
def diagnose(self, config: dict | None = None) -> dict:
|
||
cfg = dict(config or {})
|
||
base_url = str(cfg.get("base_url") or "").rstrip("/")
|
||
info: dict[str, Any] = {"available": False, "message": "", "base_url": base_url}
|
||
if not base_url:
|
||
info["message"] = "未配置 Base URL"
|
||
return info
|
||
url = str(cfg.get("models_url") or f"{base_url}/models")
|
||
headers = _headers(cfg, "")
|
||
try:
|
||
with httpx.Client(timeout=float(cfg.get("probe_timeout", 8))) as client:
|
||
resp = client.get(url, headers=headers)
|
||
if resp.status_code >= 400:
|
||
info["message"] = f"模型列表不可用(HTTP {resp.status_code}):{resp.text[:200]}"
|
||
return info
|
||
data = resp.json()
|
||
except httpx.HTTPError as exc:
|
||
info["message"] = f"连接失败:{exc}"
|
||
return info
|
||
except Exception as exc: # 探测不应打挂页面
|
||
info["message"] = f"探测异常:{type(exc).__name__}: {exc}"
|
||
return info
|
||
ids = [str(item.get("id")) for item in (data.get("data") or []) if isinstance(item, dict)]
|
||
info["available"] = True
|
||
info["message"] = f"连接正常,可用量模型 {len(ids)} 个"
|
||
info["models"] = ids[:20]
|
||
return info
|
||
|
||
|
||
class MockLLMProvider(TextProviderAdapter):
|
||
"""离线自检用的纯文本大模型。"""
|
||
|
||
_name = "mock_llm"
|
||
|
||
def __init__(self) -> None:
|
||
self._text = MockTextProvider()
|
||
|
||
@property
|
||
def name(self) -> str:
|
||
return self._name
|
||
|
||
def capabilities(self, config: dict | None = None) -> Capabilities:
|
||
return Capabilities(modes=("chat", "prompt"), resolutions=(), aspect_ratios=(),
|
||
min_duration=0, max_duration=0, max_reference_images=0,
|
||
notes="离线自检用大模型:仅验证结构化文本与提示词链路")
|
||
|
||
def generate(self, request: AssetGenRequest, config: dict | None = None) -> AssetGenResult:
|
||
if request.kind == "image":
|
||
raise FatalProviderError("Mock 大模型不支持图像生成;请使用独立图像模型",
|
||
code="unsupported_media_type")
|
||
return self._text.generate(request, config)
|