✨ feat(llm): 优化 DeepSeek 适配器 (#2160)
检查bot是否运行正常 / bot check (push) Canceled after 0s
CodeQL Code Security Analysis / Analyze (python) (push) Canceled after 0s
Ruff Lint / Ruff Lint (push) Canceled after 0s
Sequential Lint and Type Check / ruff-call (push) Canceled after 0s
Release Drafter / Update Release Draft (push) Canceled after 0s
Force Sync to Aliyun / sync (push) Canceled after 0s
Update Version / update-version (push) Canceled after 0s
Sequential Lint and Type Check / pyright-call (push) Canceled after 0s

* ✨ feat(llm): 新增 Grok 适配器及 API 密钥重置指令

- 新增 Grok 适配器并支持原生推特检索工具 `x_search`
- 优化 DeepSeek 适配器以迁移至 Responses 协议,增强多模态支持
- 在 LLM 管理插件中新增 `llm reset` 子命令以重置 Key 状态
- 增强 MCP 连接异常处理及流关闭容错能力

* 🚨 auto fix by pre-commit hooks

---------

Co-authored-by: webjoin111 <455457521@qq.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This commit is contained in:
Rumio
2026-09-22 09:02:15 +08:00
committed by GitHub
co-authored by webjoin111 pre-commit-ci[bot]
parent 39ed1ade14
commit 33d6ea1335
13 changed files with 307 additions and 52 deletions
+54 -28
View File
@@ -1,24 +1,27 @@
from typing import Any
from zhenxun.services.ai.core.messages import ImagePart, LLMMessage
from zhenxun.services.ai.core.models import (
ModelCapabilities,
ModelDetail,
ModelIdentity,
)
from zhenxun.services.ai.core.options import GenerationConfig
from zhenxun.services.ai.core.options import GenerationConfig, ResponseFormat
from .handlers.openai_handlers import (
OpenAIConfigMapper,
OpenAITextHandler,
OpenAIToolSerializer,
OpenAIResponsesTextHandler,
ResponsesConfigMapper,
ResponsesMessageConverter,
ResponsesResponseParser,
ResponsesToolSerializer,
)
from .openai import OpenAICompatAdapter
from .openai import OpenAIResponsesAdapter
class DeepSeekToolSerializer(OpenAIToolSerializer):
class DeepSeekToolSerializer(ResponsesToolSerializer):
"""
专门针对 DeepSeek 的工具序列化器。
负责抹平 Pydantic Schema 与 DeepSeek Strict Mode 之间的差异。
由于继承了 ResponsesToolSerializer,已自动获得 web_search 工具的原生格式支持。
"""
def __init__(self, api_type: str = "deepseek"):
@@ -68,7 +71,35 @@ class DeepSeekToolSerializer(OpenAIToolSerializer):
return pipeline.run(schema)
class DeepSeekConfigMapper(OpenAIConfigMapper):
class DeepSeekMessageConverter(ResponsesMessageConverter):
"""DeepSeek 专属 Responses 消息转换器"""
def __init__(self, api_type: str = "deepseek"):
super().__init__(api_type=api_type)
async def convert_messages_async(
self, messages: list[LLMMessage]
) -> list[dict[str, Any]]:
input_items = await super().convert_messages_async(messages)
image_parts = [
p for msg in messages for p in msg.content if isinstance(p, ImagePart)
]
img_idx = 0
for item in input_items:
if item.get("role") in ("user", "developer") and "content" in item:
for c in item["content"]:
if c.get("type") == "input_image":
if img_idx < len(image_parts):
part = image_parts[img_idx]
img_idx += 1
if getattr(part, "media_resolution", None):
c["detail"] = str(part.media_resolution).lower()
return input_items
class DeepSeekConfigMapper(ResponsesConfigMapper):
"""DeepSeek 的专属配置映射器"""
def map_config(
@@ -77,39 +108,38 @@ class DeepSeekConfigMapper(OpenAIConfigMapper):
model_detail: ModelDetail | None = None,
capabilities: ModelCapabilities | None = None,
) -> dict[str, Any]:
"""映射生成参数并处理 DeepSeek 专有 `thinking` 与响应格式差异。"""
params = super().map_config(config, model_detail, capabilities)
"""拦截并处理 DeepSeek 目前无法严格遵循复杂 json_schema 的问题"""
if (
config.output.response_format == ResponseFormat.JSON
and config.output.response_schema
):
config.output.response_schema = None
if "response_format" in params:
rf = params["response_format"]
if isinstance(rf, dict) and rf.get("type") == "json_schema":
params["response_format"] = {"type": "json_object"}
return params
return super().map_config(config, model_detail, capabilities)
class DeepSeekTextHandler(OpenAITextHandler):
"""DeepSeek 专有文本处理器,替换了特定序列化组件"""
class DeepSeekTextHandler(OpenAIResponsesTextHandler):
"""DeepSeek 专有 Responses 文本对话处理器,组装所有定制化子件"""
def __init__(self, api_type: str = "deepseek"):
"""替换 OpenAI 默认组件为 DeepSeek 专用实现。"""
super().__init__(api_type=api_type)
self.converter = DeepSeekMessageConverter(api_type=api_type)
self.serializer = DeepSeekToolSerializer(api_type=api_type)
self.mapper = DeepSeekConfigMapper(api_type=api_type)
self.parser = ResponsesResponseParser()
class DeepSeekAdapter(OpenAICompatAdapter):
"""DeepSeek 官方 API 适配器"""
class DeepSeekAdapter(OpenAIResponsesAdapter):
"""DeepSeek Responses API 适配器"""
def __init__(self):
"""初始化 DeepSeek 适配器并挂载文本处理器。"""
super().__init__()
self.text_handler = DeepSeekTextHandler(api_type=self.api_type)
@property
def log_sanitization_context(self) -> str:
"""返回 DeepSeek 请求日志清洗上下文。"""
return "openai_request"
"""复用 Responses API 的日志清洗上下文。"""
return "openai_responses_request"
@property
def api_type(self) -> str:
@@ -120,7 +150,3 @@ class DeepSeekAdapter(OpenAICompatAdapter):
def supported_api_types(self) -> list[str]:
"""当前适配器支持的 API 类型列表。"""
return ["deepseek"]
def get_chat_endpoint(self, identity: ModelIdentity) -> str:
"""返回对话端点,优先使用模型级自定义端点。"""
return "/v1/chat/completions"