mirror of
https://github.com/zhenxun-org/zhenxun_bot.git
synced 2026-10-05 11:49:59 +08:00
* ♻️ refactor(core): 重构 AI 能力与定时任务调度系统 - 【AI 能力与工具】重构 Capability 注册与管理机制,引入 CapabilityManager 统一管理 - 移除全局能力注册表,改用声明式装饰器 `@capability` 进行解耦注册 - 重构工具解析器链,使用统一的 BaseToolResolver 代替原有的多个特定解析器 - 增强工具查询过滤,支持通配符匹配、工具箱过滤和排除标签 - 【定时任务调度】重构定时任务管理器,引入 SchedulerRegistry 统一管理任务元数据 - 引入 JobConfig 聚合定时任务配置,支持用户维度的定时任务调度 - 重构执行分发器,支持并发限制、串行间隔和随机延迟打散 - 【运行上下文】引入 ScheduledDeps 以支持后台和定时任务环境下的依赖注入 - 优化 RunContext,支持从定时任务上下文快速构造,并提供 emit 辅助方法 - 【日志与监控】引入 AILoggerProxy,实现 AI 各模块的专属日志输出 - 将各模块的全局 logger 替换为对应的模块专属日志代理 - 【其他优化】修复 Pydantic V1 兼容层中 model_validator 的装饰器兼容性问题 - 在非交互式环境(如定时任务)中自动隐藏 HITL 交互工具以节省 Token * ♻️ refactor(core): 优化内部导入路径并提升 Pydantic 兼容性 - 【重构】将 `services/ai` 模块内的绝对导入重构为相对导入,优化包结构 - 【重构】移除不必要的 `if TYPE_CHECKING` 保护,通过 `from __future__ import annotations` 直接导入类型 - 【清理】清理 `core/messages/types.py` 中未使用的 `AssistantContentUnion` 等联合类型定义 - 【优化】在 `utils/pydantic_compat.py` 中新增 `model_rebuild` 兼容函数,统一 Pydantic V1/V2 的模型重建逻辑 - 【优化】将部分函数内部的延迟导入提升至模块顶部,规范代码结构 * ♻️ refactor(imports): 优化导入路径为相对导入并清理冗余导入 - 【重构】将 AI 服务相关模块中的绝对导入路径修改为相对导入,提升模块内聚性与可移植性 - 【清理】移除多处函数内部或类方法中未使用的冗余导入,避免循环引用和资源浪费 - 【格式化】微调部分工具装饰器和返回语句的格式与尾随逗号 * 🚨 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>
169 lines
5.3 KiB
Python
169 lines
5.3 KiB
Python
"""
|
|
LLM 适配器工厂类
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import fnmatch
|
|
from typing import Any, ClassVar
|
|
|
|
import httpx
|
|
|
|
from zhenxun.services.ai.core.exceptions import ConfigurationException
|
|
from zhenxun.services.ai.core.models import ModelIdentity
|
|
|
|
from .base import BaseAdapter, RequestData
|
|
|
|
|
|
class LLMAdapterFactory:
|
|
"""适配器注册与按 API 类型分发的统一入口。"""
|
|
|
|
_adapters: ClassVar[dict[str, BaseAdapter]] = {}
|
|
_api_type_mapping: ClassVar[dict[str, str]] = {}
|
|
|
|
@classmethod
|
|
def initialize(cls) -> None:
|
|
"""初始化默认适配器"""
|
|
if cls._adapters:
|
|
return
|
|
|
|
from .deepseek import DeepSeekAdapter
|
|
from .doubao import DoubaoAdapter
|
|
from .gemini import GeminiAdapter
|
|
from .glm import GLMAdapter
|
|
from .jina import JinaAdapter
|
|
from .mimo import MiMoAdapter
|
|
from .minimax import MiniMaxAdapter
|
|
from .openai import OpenAIAdapter, OpenAIResponsesAdapter
|
|
from .openrouter import OpenRouterAdapter
|
|
|
|
cls.register_adapter(OpenAIAdapter())
|
|
cls.register_adapter(OpenAIResponsesAdapter())
|
|
cls.register_adapter(OpenRouterAdapter())
|
|
cls.register_adapter(DeepSeekAdapter())
|
|
cls.register_adapter(JinaAdapter())
|
|
cls.register_adapter(GeminiAdapter())
|
|
cls.register_adapter(GLMAdapter())
|
|
cls.register_adapter(SmartAdapter())
|
|
cls.register_adapter(MiMoAdapter())
|
|
cls.register_adapter(MiniMaxAdapter())
|
|
cls.register_adapter(DoubaoAdapter())
|
|
|
|
@classmethod
|
|
def register_adapter(cls, adapter: BaseAdapter) -> None:
|
|
"""注册适配器"""
|
|
adapter_key = adapter.api_type
|
|
cls._adapters[adapter_key] = adapter
|
|
|
|
for api_type in adapter.supported_api_types:
|
|
cls._api_type_mapping[api_type] = adapter_key
|
|
|
|
@classmethod
|
|
def get_adapter(cls, api_type: str) -> BaseAdapter:
|
|
"""获取适配器"""
|
|
cls.initialize()
|
|
|
|
adapter_key = cls._api_type_mapping.get(api_type)
|
|
if not adapter_key:
|
|
raise ConfigurationException(
|
|
f"不支持的API类型: {api_type}",
|
|
details={
|
|
"api_type": api_type,
|
|
"supported_types": list(cls._api_type_mapping.keys()),
|
|
},
|
|
)
|
|
|
|
return cls._adapters[adapter_key]
|
|
|
|
@classmethod
|
|
def list_supported_types(cls) -> list[str]:
|
|
"""列出所有支持的API类型"""
|
|
cls.initialize()
|
|
return list(cls._api_type_mapping.keys())
|
|
|
|
@classmethod
|
|
def list_adapters(cls) -> dict[str, BaseAdapter]:
|
|
"""列出所有注册的适配器"""
|
|
cls.initialize()
|
|
return cls._adapters.copy()
|
|
|
|
|
|
def get_adapter_for_api_type(api_type: str) -> BaseAdapter:
|
|
"""按 API 类型获取适配器实例。"""
|
|
return LLMAdapterFactory.get_adapter(api_type)
|
|
|
|
|
|
def register_adapter(adapter: BaseAdapter) -> None:
|
|
"""向工厂注册新的适配器实例。"""
|
|
LLMAdapterFactory.register_adapter(adapter)
|
|
|
|
|
|
class SmartAdapter(BaseAdapter):
|
|
"""
|
|
智能路由适配器。
|
|
本身不处理序列化,而是根据规则委托给 OpenAIAdapter 或 GeminiAdapter。
|
|
"""
|
|
|
|
@property
|
|
def log_sanitization_context(self) -> str:
|
|
"""返回智能路由适配器的默认日志清洗上下文。"""
|
|
return "openai_request"
|
|
|
|
_ROUTING_RULES: ClassVar[list[tuple[str, str]]] = [
|
|
("*nano-banana*", "gemini"),
|
|
("*gemini*", "gemini"),
|
|
("*deepseek*", "deepseek"),
|
|
("*minimax*", "minimax"),
|
|
("*gpt*", "openai_responses"),
|
|
]
|
|
_DEFAULT_API_TYPE: ClassVar[str] = "openai"
|
|
|
|
def __init__(self):
|
|
"""初始化模型名到目标适配器的路由缓存。"""
|
|
self._adapter_cache: dict[str, BaseAdapter] = {}
|
|
|
|
@property
|
|
def api_type(self) -> str:
|
|
"""适配器主类型标识。"""
|
|
return "smart"
|
|
|
|
@property
|
|
def supported_api_types(self) -> list[str]:
|
|
"""当前适配器支持的 API 类型列表。"""
|
|
return ["smart"]
|
|
|
|
def _get_delegate_adapter(self, identity: ModelIdentity) -> BaseAdapter:
|
|
"""
|
|
核心路由逻辑:决定使用哪个适配器 (带缓存)
|
|
"""
|
|
if identity.api_type and identity.api_type != "smart":
|
|
return get_adapter_for_api_type(identity.api_type)
|
|
|
|
model_name = identity.model_name
|
|
if model_name in self._adapter_cache:
|
|
return self._adapter_cache[model_name]
|
|
|
|
target_api_type = self._DEFAULT_API_TYPE
|
|
model_name_lower = model_name.lower()
|
|
|
|
for pattern, api_type in self._ROUTING_RULES:
|
|
if fnmatch.fnmatch(model_name_lower, pattern):
|
|
target_api_type = api_type
|
|
break
|
|
|
|
adapter = get_adapter_for_api_type(target_api_type)
|
|
self._adapter_cache[model_name] = adapter
|
|
return adapter
|
|
|
|
async def prepare_payload(
|
|
self, identity: ModelIdentity, api_key: str, request: Any
|
|
) -> RequestData:
|
|
adapter = self._get_delegate_adapter(identity)
|
|
return await adapter.prepare_payload(identity, api_key, request)
|
|
|
|
async def parse_payload(
|
|
self, identity: ModelIdentity, request: Any, raw_response: httpx.Response
|
|
) -> Any:
|
|
adapter = self._get_delegate_adapter(identity)
|
|
return await adapter.parse_payload(identity, request, raw_response)
|