606 lines
28 KiB
Python
606 lines
28 KiB
Python
"""大模型服务商目录与接入解析:**各家怎么连、报文怎么发,只写在这一个文件里**。
|
||
|
||
为什么要分「服务商」和「协议」两层
|
||
市面上真正不同的只是**报文格式**(``protocol``):OpenAI 兼容、Anthropic、
|
||
Gemini、Ollama、Azure OpenAI 五种;剩下的服务商(DeepSeek、通义千问、Kimi、
|
||
智谱、豆包、硅基流动……)都是 OpenAI 兼容壳子里的一家,差别只在站点地址、
|
||
模型名和文档。所以:
|
||
|
||
* ``protocol`` 决定「怎么发」(鉴权头放哪儿、路径拼什么、响应里哪一段是正文);
|
||
* ``provider`` 决定「界面上默认填什么」(站点地址、模型清单、密钥叫什么、文档链接)。
|
||
|
||
两层分开的好处是:公司自建网关、私有化部署、暂时没进目录的小厂,都能用
|
||
``custom`` + 选一个协议接进来,不用等这里加代码。
|
||
|
||
一条接入配置长什么样
|
||
存在 ``oa_ai_provider`` 表里(系统设置 -> 大模型接入),界面上保存即生效:
|
||
业务侧每次调用现读这一行,改完地址/密钥下一条请求就走新的,不重启进程。
|
||
|
||
``base_url`` 填到哪一层
|
||
OpenAI 兼容协议要填到 **接口前缀**(含 ``/v1`` 或网关自己那一段),
|
||
本模块只在其后拼 ``chat/completions``;Anthropic / Gemini 填 **站点根**,
|
||
模块补 ``/v1/messages`` / ``/{版本}/models``;已经把这些路径写进 base_url 的
|
||
网关也认(拼路径时不会重复同一段)。
|
||
|
||
密钥
|
||
``api_key`` 存库、只进不出:接口只回 ``api_key_set``,本模块产出的任何
|
||
字符串(含错误消息)都先过 :func:`redact`,免得报错把密钥带到界面上。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from dataclasses import dataclass, field
|
||
from typing import Any, Iterable
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 协议:报文格式,一共五种
|
||
# ---------------------------------------------------------------------------
|
||
|
||
PROTOCOL_OPENAI = "openai"
|
||
PROTOCOL_AZURE = "azure_openai"
|
||
PROTOCOL_ANTHROPIC = "anthropic"
|
||
PROTOCOL_GEMINI = "gemini"
|
||
PROTOCOL_OLLAMA = "ollama"
|
||
|
||
#: 鉴权方式:请求头名字与写法
|
||
AUTH_BEARER = "bearer" # Authorization: Bearer <key>
|
||
AUTH_API_KEY_HEADER = "api_key" # api-key: <key>(Azure OpenAI)
|
||
AUTH_X_API_KEY = "x_api_key" # x-api-key + anthropic-version(Anthropic)
|
||
AUTH_GOOGLE_KEY = "google_key" # x-goog-api-key: <key>(Gemini)
|
||
AUTH_NONE = "none" # 本地推理服务,不鉴权
|
||
|
||
AUTH_LABELS = {
|
||
AUTH_BEARER: "Authorization: Bearer",
|
||
AUTH_API_KEY_HEADER: "api-key 请求头",
|
||
AUTH_X_API_KEY: "x-api-key 请求头",
|
||
AUTH_GOOGLE_KEY: "x-goog-api-key 请求头",
|
||
AUTH_NONE: "不需要密钥",
|
||
}
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class Protocol:
|
||
"""一种报文格式:路径怎么拼、密钥放哪儿、响应读哪一段。"""
|
||
|
||
key: str
|
||
label: str
|
||
auth: str
|
||
help: str = ""
|
||
#: 接口前缀后面紧跟的路径
|
||
chat_path: str = ""
|
||
#: 列模型的路径;空串 = 这家没有「列出模型」接口,界面上只能手填模型名
|
||
models_path: str = ""
|
||
#: base_url 里已经带了这一段就不再补
|
||
version_prefix: str = ""
|
||
#: 需要填 API 版本号的协议(Azure 的 api-version / Gemini 的 v1beta)
|
||
needs_api_version: bool = False
|
||
#: 密钥是不是必须的(本地服务可不填)
|
||
key_required: bool = True
|
||
|
||
|
||
PROTOCOLS: tuple[Protocol, ...] = (
|
||
Protocol(
|
||
PROTOCOL_OPENAI,
|
||
"OpenAI 兼容(Chat Completions)",
|
||
AUTH_BEARER,
|
||
"绝大多数国内外厂商、推理框架和自建网关都是这个壳子:接口前缀填到 /v1(或网关自定义那一段),"
|
||
"后面拼 chat/completions。",
|
||
chat_path="chat/completions",
|
||
models_path="models",
|
||
),
|
||
Protocol(
|
||
PROTOCOL_AZURE,
|
||
"Azure OpenAI",
|
||
AUTH_API_KEY_HEADER,
|
||
"接口前缀要填完整到部署名,例如 https://资源名.openai.azure.com/openai/deployments/部署名,"
|
||
"版本号写在下面「API 版本」里。",
|
||
chat_path="chat/completions",
|
||
needs_api_version=True,
|
||
),
|
||
Protocol(
|
||
PROTOCOL_ANTHROPIC,
|
||
"Anthropic Messages",
|
||
AUTH_X_API_KEY,
|
||
"Claude 官方报文;站点根地址即可(会自动补 /v1/messages),密钥走 x-api-key 请求头。",
|
||
chat_path="messages",
|
||
models_path="models",
|
||
version_prefix="/v1",
|
||
key_required=False, # 网关代理也常见,交给服务商预设决定
|
||
),
|
||
Protocol(
|
||
PROTOCOL_GEMINI,
|
||
"Google Gemini",
|
||
AUTH_GOOGLE_KEY,
|
||
"站点根地址(默认 generativelanguage.googleapis.com),路径按 版本/模型 拼 "
|
||
"generateContent;密钥走 x-goog-api-key 请求头。",
|
||
chat_path="generateContent",
|
||
models_path="models",
|
||
version_prefix="/v1beta",
|
||
needs_api_version=True,
|
||
),
|
||
Protocol(
|
||
PROTOCOL_OLLAMA,
|
||
"Ollama",
|
||
AUTH_NONE,
|
||
"本机或内网的 Ollama 服务:不鉴权,用原生 /api/chat。装了 Ollama 也可直接选"
|
||
"「OpenAI 兼容」协议,前缀填 http://127.0.0.1:11434/v1。",
|
||
chat_path="api/chat",
|
||
models_path="api/tags",
|
||
key_required=False,
|
||
),
|
||
)
|
||
|
||
BY_PROTOCOL: dict[str, Protocol] = {protocol.key: protocol for protocol in PROTOCOLS}
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 服务商:界面上的下拉列表,选中即带出默认值
|
||
# ---------------------------------------------------------------------------
|
||
|
||
CATEGORY_CN = "国内厂商"
|
||
CATEGORY_OVERSEA = "海外厂商"
|
||
CATEGORY_LOCAL = "本地 / 私有化"
|
||
CATEGORY_GATEWAY = "网关与自定义"
|
||
|
||
CATEGORIES = (CATEGORY_CN, CATEGORY_OVERSEA, CATEGORY_LOCAL, CATEGORY_GATEWAY)
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class ProviderSpec:
|
||
"""一家服务商在目录里的预设:协议、默认地址、常用模型、密钥怎么称呼、文档。"""
|
||
|
||
key: str
|
||
label: str
|
||
protocol: str
|
||
category: str
|
||
base_url: str = ""
|
||
vendor: str = ""
|
||
#: 界面上密钥输入框的标签(有的厂叫 Secret Key、有的叫 API Token)
|
||
key_label: str = "API Key"
|
||
#: 这一家是否一定要密钥(本地推理服务为 False)
|
||
key_required: bool = True
|
||
#: 默认模型清单;空 = 由用户自己填(模型名即部署名的厂商一律留空)
|
||
models: tuple[str, ...] = ()
|
||
#: 建议填的 API 版本(Azure / Gemini 用)
|
||
api_version: str = ""
|
||
docs: str = ""
|
||
note: str = ""
|
||
|
||
|
||
def _p(**kwargs: Any) -> ProviderSpec:
|
||
return ProviderSpec(**kwargs)
|
||
|
||
|
||
PROVIDERS: tuple[ProviderSpec, ...] = (
|
||
# ------------------------------------------------------------- 国内厂商
|
||
_p(key="dashscope", label="阿里云百炼(通义千问)", vendor="阿里云", protocol=PROTOCOL_OPENAI,
|
||
category=CATEGORY_CN, base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
|
||
models=("qwen-plus", "qwen-max", "qwen-turbo"),
|
||
docs="https://help.aliyun.com/zh/model-studio/use-qwen-by-calling-api",
|
||
note="走百炼的 OpenAI 兼容端点;老 DashScope 原生报文不在本目录里,用「自定义」接。"),
|
||
_p(key="deepseek", label="DeepSeek 深度求索", vendor="DeepSeek", protocol=PROTOCOL_OPENAI,
|
||
category=CATEGORY_CN, base_url="https://api.deepseek.com/v1",
|
||
models=("deepseek-chat", "deepseek-reasoner"),
|
||
docs="https://api-docs.deepseek.com/",
|
||
note="deepseek-reasoner 是推理模型,回答前先输出思维链,超时给宽一点。"),
|
||
_p(key="zhipu", label="智谱 GLM", vendor="智谱 AI", protocol=PROTOCOL_OPENAI, category=CATEGORY_CN,
|
||
base_url="https://open.bigmodel.cn/api/paas/v4", key_label="API Key",
|
||
models=("glm-4-plus", "glm-4-flash"),
|
||
docs="https://open.bigmodel.cn/dev/api"),
|
||
_p(key="moonshot", label="Kimi(月之暗面)", vendor="月之暗面", protocol=PROTOCOL_OPENAI,
|
||
category=CATEGORY_CN, base_url="https://api.moonshot.cn/v1",
|
||
models=("kimi-latest", "moonshot-v1-32k"),
|
||
docs="https://platform.moonshot.cn/docs/api/chat"),
|
||
_p(key="doubao", label="火山方舟(豆包)", vendor="字节跳动 火山引擎", protocol=PROTOCOL_OPENAI,
|
||
category=CATEGORY_CN, base_url="https://ark.cn-beijing.volces.com/api/v3", key_label="API Key",
|
||
docs="https://www.volcengine.com/docs/82379/1298454",
|
||
note="模型名要填控制台上推理接入点的标识(一般是 ep-开头的一串),不是一个词。"),
|
||
_p(key="hunyuan", label="腾讯云混元", vendor="腾讯云", protocol=PROTOCOL_OPENAI, category=CATEGORY_CN,
|
||
base_url="https://api.hunyuan.cloud.tencent.com/v1", key_label="API Key",
|
||
models=("hunyuan-pro", "hunyuan-lite"),
|
||
docs="https://cloud.tencent.com/document/product/1729/104729"),
|
||
_p(key="spark", label="讯飞星火", vendor="科大讯飞", protocol=PROTOCOL_OPENAI, category=CATEGORY_CN,
|
||
base_url="https://spark-api-open.xf-yun.com/v1", key_label="APIKey",
|
||
docs="https://www.xfyun.cn/doc/spark/HTTP%20Api.html",
|
||
note="模型名填控制台里的版本名(例如 4.0Ultra、generalv3.5)。"),
|
||
_p(key="baichuan", label="百川智能", vendor="百川智能", protocol=PROTOCOL_OPENAI, category=CATEGORY_CN,
|
||
base_url="https://api.baichuan-ai.com/v1", models=("Baichuan4", "Baichuan3-Turbo"),
|
||
docs="https://platform.baichuan-ai.com/docs/api"),
|
||
_p(key="yi", label="零一万物 Yi", vendor="零一万物", protocol=PROTOCOL_OPENAI, category=CATEGORY_CN,
|
||
base_url="https://api.lingyiwanwu.com/v1", models=("yi-lightning", "yi-large"),
|
||
docs="https://platform.lingyiwanwu.com/docs"),
|
||
_p(key="stepfun", label="阶跃星辰 Step", vendor="阶跃星辰", protocol=PROTOCOL_OPENAI,
|
||
category=CATEGORY_CN, base_url="https://api.stepfun.com/v1", models=("step-1-8k",),
|
||
docs="https://platform.stepfun.com/docs/llms.txt"),
|
||
_p(key="siliconflow", label="硅基流动 SiliconFlow", vendor="硅基流动", protocol=PROTOCOL_OPENAI,
|
||
category=CATEGORY_CN, base_url="https://api.siliconflow.cn/v1",
|
||
models=("deepseek-ai/DeepSeek-V3", "Qwen/Qwen2.5-7B-Instruct"),
|
||
docs="https://docs.siliconflow.cn/cn/api-reference/chat-completions"),
|
||
_p(key="minimax", label="MiniMax", vendor="MiniMax", protocol=PROTOCOL_OPENAI, category=CATEGORY_CN,
|
||
base_url="https://api.minimaxi.com/v1", models=("MiniMax-Text-01",),
|
||
docs="https://www.minimaxi.com/document/OpenAI%20API"),
|
||
# ------------------------------------------------------------- 海外厂商
|
||
_p(key="openai", label="OpenAI", vendor="OpenAI", protocol=PROTOCOL_OPENAI, category=CATEGORY_OVERSEA,
|
||
base_url="https://api.openai.com/v1", models=("gpt-4o-mini", "gpt-4o"),
|
||
docs="https://platform.openai.com/docs/api-reference/chat"),
|
||
_p(key="anthropic", label="Anthropic Claude", vendor="Anthropic", protocol=PROTOCOL_ANTHROPIC,
|
||
category=CATEGORY_OVERSEA, base_url="https://api.anthropic.com",
|
||
models=("claude-sonnet-4-20250514", "claude-3-5-haiku-20241022"),
|
||
docs="https://docs.anthropic.com/en/api/messages"),
|
||
_p(key="gemini", label="Google Gemini", vendor="Google", protocol=PROTOCOL_GEMINI,
|
||
category=CATEGORY_OVERSEA, base_url="https://generativelanguage.googleapis.com",
|
||
key_label="API Key", api_version="v1beta",
|
||
models=("gemini-2.0-flash", "gemini-1.5-pro"),
|
||
docs="https://ai.google.dev/gemini-api/docs"),
|
||
_p(key="azure_openai", label="Azure OpenAI", vendor="微软 Azure", protocol=PROTOCOL_AZURE,
|
||
category=CATEGORY_OVERSEA, base_url="", key_label="API Key", api_version="2024-10-21",
|
||
docs="https://learn.microsoft.com/azure/ai-services/openai/reference",
|
||
note="接口前缀填到部署名那一层:https://<资源名>.openai.azure.com/openai/deployments/<部署名>。"),
|
||
_p(key="xai", label="xAI Grok", vendor="xAI", protocol=PROTOCOL_OPENAI, category=CATEGORY_OVERSEA,
|
||
base_url="https://api.x.ai/v1", models=("grok-2-latest",), docs="https://docs.x.ai/api"),
|
||
_p(key="groq", label="Groq", vendor="Groq", protocol=PROTOCOL_OPENAI, category=CATEGORY_OVERSEA,
|
||
base_url="https://api.groq.com/openai/v1", models=("llama-3.3-70b-versatile",),
|
||
docs="https://console.groq.com/docs/openai"),
|
||
_p(key="openrouter", label="OpenRouter", vendor="OpenRouter", protocol=PROTOCOL_OPENAI,
|
||
category=CATEGORY_GATEWAY, base_url="https://openrouter.ai/api/v1",
|
||
models=("openai/gpt-4o-mini", "anthropic/claude-3.5-sonnet"),
|
||
docs="https://openrouter.ai/docs/api-reference"),
|
||
# -------------------------------------------------------- 本地 / 私有化
|
||
_p(key="ollama", label="Ollama(本机)", vendor="Ollama", protocol=PROTOCOL_OLLAMA,
|
||
category=CATEGORY_LOCAL, base_url="http://127.0.0.1:11434", key_required=False,
|
||
models=("qwen2.5", "llama3.1"), docs="https://github.com/ollama/ollama/blob/main/docs/api.md",
|
||
note="模型名就是 ollama list 里的那个名字,列表能直接从服务上拉回来。"),
|
||
_p(key="vllm", label="vLLM(自建)", vendor="vLLM", protocol=PROTOCOL_OPENAI, category=CATEGORY_LOCAL,
|
||
base_url="http://127.0.0.1:8000/v1", key_required=False,
|
||
docs="https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html",
|
||
note="启动 vllm serve 时带了 --api-key 才需要填密钥。"),
|
||
_p(key="xinference", label="Xinference", vendor="Xorbits", protocol=PROTOCOL_OPENAI,
|
||
category=CATEGORY_LOCAL, base_url="http://127.0.0.1:9997/v1", key_required=False,
|
||
docs="https://inference.readthedocs.io/zh-cn/latest/user_guide/clients/use_openai_api.html"),
|
||
_p(key="lm_studio", label="LM Studio", vendor="LM Studio", protocol=PROTOCOL_OPENAI,
|
||
category=CATEGORY_LOCAL, base_url="http://localhost:1234/v1", key_required=False,
|
||
docs="https://lmstudio.ai/docs/basics/server",
|
||
note="要在 LM Studio 里把本地服务器打开;模型名用服务里已加载的那个。"),
|
||
# --------------------------------------------------------- 网关与自定义
|
||
_p(key="custom", label="自定义 / 其他网关", vendor="自定义", protocol=PROTOCOL_OPENAI,
|
||
category=CATEGORY_GATEWAY, key_required=False,
|
||
note="公司自建网关、暂时没进目录的厂商都选这个:先挑报文协议,再填接口前缀和密钥。"),
|
||
)
|
||
|
||
BY_PROVIDER: dict[str, ProviderSpec] = {spec.key: spec for spec in PROVIDERS}
|
||
|
||
|
||
class LLMConfigError(ValueError):
|
||
"""接入配置本身有问题(地址不对、协议不认识……)。文本直接给界面看。"""
|
||
|
||
|
||
# --------------------------------------------------------------------------
|
||
# 目录查询:界面与校验都用这里,不再各抄一份
|
||
# --------------------------------------------------------------------------
|
||
|
||
|
||
def provider_spec(key: str) -> ProviderSpec | None:
|
||
return BY_PROVIDER.get((key or "").strip())
|
||
|
||
|
||
def protocol_spec(key: str) -> Protocol | None:
|
||
return BY_PROTOCOL.get((key or "").strip())
|
||
|
||
|
||
def known_provider(key: str) -> bool:
|
||
return provider_spec(key) is not None
|
||
|
||
|
||
def known_protocol(key: str) -> bool:
|
||
return protocol_spec(key) is not None
|
||
|
||
|
||
def default_protocol(provider: str) -> str:
|
||
spec = provider_spec(provider)
|
||
return spec.protocol if spec else PROTOCOL_OPENAI
|
||
|
||
|
||
def default_api_version(provider: str) -> str:
|
||
spec = provider_spec(provider)
|
||
return spec.api_version if spec else ""
|
||
|
||
|
||
def requires_key(provider: str, protocol: str) -> bool:
|
||
"""这一家是不是非要密钥。服务商预设说了算,预设缺失时退回协议的要求。"""
|
||
spec = provider_spec(provider)
|
||
if spec is not None and spec.key_required:
|
||
return True
|
||
if spec is not None and not spec.key_required:
|
||
return False
|
||
proto = protocol_spec(protocol)
|
||
return bool(proto and proto.key_required)
|
||
|
||
|
||
def protocol_options() -> list[dict[str, Any]]:
|
||
return [
|
||
{
|
||
"value": protocol.key,
|
||
"label": protocol.label,
|
||
"help": protocol.help,
|
||
# 界面上「API 版本」那一栏显不显示,跟着协议走,前端不猜
|
||
"needs_api_version": protocol.needs_api_version,
|
||
"can_list_models": bool(protocol.models_path),
|
||
}
|
||
for protocol in PROTOCOLS
|
||
]
|
||
|
||
|
||
def catalog() -> dict[str, Any]:
|
||
"""给界面的目录:服务商列表(带默认值)+ 协议列表(带说明)。
|
||
|
||
前端照着渲染,不硬编码任何一家服务商的站点地址;以后这里加一行,界面上就有。
|
||
"""
|
||
providers = [
|
||
{
|
||
"key": spec.key,
|
||
"label": spec.label,
|
||
"vendor": spec.vendor,
|
||
"category": spec.category,
|
||
"protocol": spec.protocol,
|
||
"base_url": spec.base_url,
|
||
"key_label": spec.key_label,
|
||
"key_required": spec.key_required,
|
||
"api_version": spec.api_version,
|
||
"models": list(spec.models),
|
||
"docs": spec.docs,
|
||
"note": spec.note,
|
||
}
|
||
for spec in PROVIDERS
|
||
]
|
||
return {
|
||
"categories": list(CATEGORIES),
|
||
"providers": providers,
|
||
"protocols": protocol_options(),
|
||
"auth_labels": AUTH_LABELS,
|
||
"hint": "选服务商只是带出默认值,站点地址、模型名、报文协议都能改;"
|
||
"目录里没有的厂商选「自定义」再挑协议。",
|
||
}
|
||
|
||
|
||
# --------------------------------------------------------------------------
|
||
# 值清洗
|
||
# --------------------------------------------------------------------------
|
||
|
||
|
||
def clean_base_url(value: str) -> str:
|
||
"""接口前缀:补协议头、去结尾斜杠;只认 http/https。
|
||
|
||
这里是唯一能把请求发往外网的地方,所以宁可挡一下:``file://``、带空格、
|
||
带用户名的地址一律不收(报错文案要说清该填成什么样,运维是照着文档粘的)。
|
||
"""
|
||
text = str(value or "").strip().strip("\"'")
|
||
if not text:
|
||
return ""
|
||
if any(char.isspace() for char in text):
|
||
raise LLMConfigError("接口地址中间不能有空格")
|
||
if text.endswith("/chat/completions") or text.endswith("/messages") or text.endswith("/generateContent"):
|
||
raise LLMConfigError("接口地址填到前缀那一段就行,结尾的 chat/completions 这类路径系统会自己补")
|
||
if "://" not in text:
|
||
text = f"http://{text}"
|
||
scheme, _, rest = text.partition("://")
|
||
if scheme.lower() not in {"http", "https"}:
|
||
raise LLMConfigError("接口地址只能用 http 或 https")
|
||
host = rest.split("/")[0]
|
||
if "@" in host:
|
||
raise LLMConfigError("接口地址里不要带账号密码,密钥填在下面的密钥输入框")
|
||
if not host.replace(".", "").replace("-", "").replace("_", ""):
|
||
raise LLMConfigError("接口地址不像一个主机名,例如 https://api.openai.com/v1")
|
||
return text.rstrip("/")
|
||
|
||
|
||
def clean_model_list(value: Any) -> tuple[str, ...]:
|
||
"""模型清单:支持数组、逗号/换行分隔的字符串;去重保序。"""
|
||
if value is None:
|
||
return ()
|
||
if isinstance(value, str):
|
||
parts = value.replace(",", ",").replace("\n", ",").replace(";", ",").split(",")
|
||
elif isinstance(value, (list, tuple, set)):
|
||
parts = [str(item) for item in value]
|
||
else:
|
||
raise LLMConfigError("模型清单要填成数组,或者用英文逗号分隔")
|
||
out: list[str] = []
|
||
for part in parts:
|
||
name = str(part).strip()
|
||
if name and name not in out:
|
||
out.append(name)
|
||
return tuple(out)
|
||
|
||
|
||
def clean_json_object(value: Any, label: str) -> dict[str, Any]:
|
||
if value is None or value == "":
|
||
return {}
|
||
if isinstance(value, str):
|
||
import json
|
||
|
||
try:
|
||
value = json.loads(value or "{}")
|
||
except ValueError as exc:
|
||
raise LLMConfigError(f"{label}要写成 JSON 对象,例如 {{\"top_p\": 0.9}}") from exc
|
||
if not isinstance(value, dict):
|
||
raise LLMConfigError(f"{label}要写成 JSON 对象")
|
||
return {str(key): item for key, item in value.items()}
|
||
|
||
|
||
def clean_api_version(value: str) -> str:
|
||
text = str(value or "").strip().lstrip("v").strip()
|
||
raw = str(value or "").strip()
|
||
# Gemini 的版本段是 v1beta 这种写法,得把 v 还回去;Azure 的是日期串,原样留着。
|
||
return raw if raw.lower().startswith("v") else text
|
||
|
||
|
||
# --------------------------------------------------------------------------
|
||
# 一条接入配置 -> 一次调用要用的东西
|
||
# --------------------------------------------------------------------------
|
||
|
||
|
||
@dataclass
|
||
class Connection:
|
||
"""从 ``oa_ai_provider`` 一行折出来的可调用连接。
|
||
|
||
只装「发请求要用的东西」,路径也在这里拼完,客户端拿到就能发;
|
||
``label`` 用来把错误说清楚是哪一个接入出的问题。
|
||
"""
|
||
|
||
id: str
|
||
label: str
|
||
provider: str
|
||
protocol: str
|
||
base_url: str
|
||
api_key: str = ""
|
||
api_version: str = ""
|
||
models: tuple[str, ...] = ()
|
||
default_model: str = ""
|
||
temperature: float = 0.7
|
||
max_tokens: int = 1024
|
||
timeout_seconds: int = 60
|
||
extra_headers: dict[str, Any] = field(default_factory=dict)
|
||
extra_body: dict[str, Any] = field(default_factory=dict)
|
||
system_prompt: str = ""
|
||
|
||
# -- 路径 --------------------------------------------------------------
|
||
|
||
def chat_url(self, model: str = "") -> str:
|
||
proto = protocol_spec(self.protocol) or BY_PROTOCOL[PROTOCOL_OPENAI]
|
||
if self.protocol == PROTOCOL_GEMINI:
|
||
version = self.api_version or "v1beta"
|
||
return f"{self.base_url}/{version}/models/{model}:generateContent"
|
||
base = self._join(proto.chat_path, proto.version_prefix)
|
||
url = f"{base}/{proto.chat_path}"
|
||
if self.protocol == PROTOCOL_AZURE:
|
||
version = self.api_version or "2024-10-21"
|
||
url = f"{url}?api-version={version}"
|
||
return url
|
||
|
||
def models_url(self) -> str:
|
||
proto = protocol_spec(self.protocol) or BY_PROTOCOL[PROTOCOL_OPENAI]
|
||
if not proto.models_path:
|
||
return ""
|
||
if self.protocol == PROTOCOL_GEMINI:
|
||
version = self.api_version or "v1beta"
|
||
return f"{self.base_url}/{version}/models"
|
||
return f"{self._join(proto.models_path, proto.version_prefix)}/{proto.models_path}"
|
||
|
||
def _join(self, path: str, version_prefix: str) -> str:
|
||
"""拼路径:base_url 里已经带了 ``/v1`` 这类前缀就不再重复一次。"""
|
||
base = self.base_url.rstrip("/")
|
||
if not version_prefix:
|
||
return base
|
||
if base.endswith(version_prefix) or base.endswith(f"{version_prefix}/"):
|
||
return base
|
||
return f"{base}{version_prefix}"
|
||
|
||
# -- 请求头 ------------------------------------------------------------
|
||
|
||
def headers(self) -> dict[str, str]:
|
||
proto = protocol_spec(self.protocol) or BY_PROTOCOL[PROTOCOL_OPENAI]
|
||
head = {"Content-Type": "application/json", "Accept": "application/json"}
|
||
key = self.api_key.strip()
|
||
if proto.auth == AUTH_BEARER and key:
|
||
head["Authorization"] = f"Bearer {key}"
|
||
elif proto.auth == AUTH_API_KEY_HEADER and key:
|
||
head["api-key"] = key
|
||
elif proto.auth == AUTH_X_API_KEY:
|
||
if key:
|
||
head["x-api-key"] = key
|
||
head["anthropic-version"] = self.api_version or "2023-06-01"
|
||
elif proto.auth == AUTH_GOOGLE_KEY and key:
|
||
head["x-goog-api-key"] = key
|
||
for name, value in (self.extra_headers or {}).items():
|
||
if value is None:
|
||
continue
|
||
head[str(name)] = str(value)
|
||
return head
|
||
|
||
# -- 模型 --------------------------------------------------------------
|
||
|
||
def model_options(self) -> tuple[str, ...]:
|
||
"""界面上能选的模型:配置里的清单,默认模型一定在里面。"""
|
||
models = list(self.models)
|
||
if self.default_model and self.default_model not in models:
|
||
models.insert(0, self.default_model)
|
||
return tuple(models)
|
||
|
||
def pick_model(self, model: str = "") -> str:
|
||
"""没点名用哪个模型时:先用配置的默认模型,再退到清单第一个。"""
|
||
wanted = (model or "").strip()
|
||
if wanted:
|
||
return wanted
|
||
if self.default_model:
|
||
return self.default_model
|
||
if self.models:
|
||
return self.models[0]
|
||
raise LLMConfigError(f"「{self.label}」还没有可用模型:请先拉取模型列表,或手动填一个模型名")
|
||
|
||
|
||
def connection(row: Any) -> Connection:
|
||
"""``models.AiProvider`` -> :class:`Connection`。每次调用现读,界面上改完立刻生效。"""
|
||
protocol = str(getattr(row, "protocol", "") or PROTOCOL_OPENAI)
|
||
if not known_protocol(protocol):
|
||
raise LLMConfigError(f"「{row.name}」的报文协议 {protocol} 系统不认识,请重新选择")
|
||
base_url = clean_base_url(str(getattr(row, "base_url", "") or ""))
|
||
if not base_url:
|
||
raise LLMConfigError(f"「{row.name}」没有填接口地址,请先在系统设置 -> 大模型接入里补上")
|
||
if requires_key(str(getattr(row, "provider", "") or ""), protocol) and not str(
|
||
getattr(row, "api_key", "") or ""
|
||
).strip():
|
||
raise LLMConfigError(f"「{row.name}」还没有填 API Key,填好保存后即可使用")
|
||
return Connection(
|
||
id=str(getattr(row, "id", "") or ""),
|
||
label=str(getattr(row, "name", "") or "未命名接入"),
|
||
provider=str(getattr(row, "provider", "") or "custom"),
|
||
protocol=protocol,
|
||
base_url=base_url,
|
||
api_key=str(getattr(row, "api_key", "") or ""),
|
||
api_version=str(getattr(row, "api_version", "") or "") or default_api_version(
|
||
str(getattr(row, "provider", "") or "")
|
||
),
|
||
models=tuple(str(item) for item in (getattr(row, "models", None) or [])),
|
||
default_model=str(getattr(row, "default_model", "") or ""),
|
||
temperature=float(getattr(row, "temperature", 0.7) if getattr(row, "temperature", None) is not None else 0.7),
|
||
max_tokens=int(getattr(row, "max_tokens", 1024) or 1024),
|
||
timeout_seconds=int(getattr(row, "timeout_seconds", 60) or 60),
|
||
extra_headers=dict(getattr(row, "extra_headers", None) or {}),
|
||
extra_body=dict(getattr(row, "extra_body", None) or {}),
|
||
system_prompt=str(getattr(row, "system_prompt", "") or ""),
|
||
)
|
||
|
||
|
||
def default_connection(rows: Iterable[Any]) -> Connection:
|
||
"""业务侧没点名用哪条接入时:先取「默认接入」,没有就取第一条启用的。"""
|
||
enabled = [row for row in rows if bool(getattr(row, "enabled", True))]
|
||
if not enabled:
|
||
raise LLMConfigError("还没有启用中的大模型接入:请到 系统设置 -> 大模型接入 里新增并启用")
|
||
wanted = next((row for row in enabled if getattr(row, "is_default", False)), enabled[0])
|
||
return connection(wanted)
|
||
|
||
|
||
def redact(text: str, *secrets: str) -> str:
|
||
"""把密钥从任何要出门的字符串里抹掉:报错、日志、界面提示都先过这一道。"""
|
||
out = str(text or "")
|
||
for secret in secrets:
|
||
token = str(secret or "")
|
||
if len(token) >= 4:
|
||
out = out.replace(token, "***")
|
||
return out
|
||
|
||
|
||
def key_hint(row: Any) -> str:
|
||
"""界面上密钥那一栏的提示语:说清这一家怎么认密钥。"""
|
||
spec = provider_spec(str(getattr(row, "provider", "") or ""))
|
||
proto = protocol_spec(str(getattr(row, "protocol", "") or ""))
|
||
if proto is not None and proto.auth == AUTH_NONE:
|
||
return "这个协议不鉴权,留空即可"
|
||
note = f"(鉴权方式:{AUTH_LABELS.get(proto.auth, '请求头')})" if proto else ""
|
||
if str(getattr(row, "api_key", "") or "").strip():
|
||
# 已经配过了:最该说的是"留空不等于清空",不然谁敢在编辑界面上点保存
|
||
return f"已设置,留空表示不修改{note}"
|
||
if spec is not None and not spec.key_required:
|
||
# 本地服务与自建网关:一般能留空,但网关自己开了鉴权还得填
|
||
return f"这一家通常不需要密钥;网关开了鉴权就照着填{note}"
|
||
return f"填了之后接口不再回显明文{note}"
|