mirror of
https://github.com/zhenxun-org/zhenxun_bot.git
synced 2026-10-19 19:20:03 +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>
171 lines
5.8 KiB
Python
171 lines
5.8 KiB
Python
import base64
|
|
import json
|
|
from typing import Any
|
|
|
|
import httpx
|
|
|
|
from zhenxun.services.ai.core.messages import (
|
|
AudioPart,
|
|
AudioResponse,
|
|
ImagePart,
|
|
LLMMessage,
|
|
SpeechRequest,
|
|
TextPart,
|
|
UsageInfo,
|
|
VideoPart,
|
|
)
|
|
from zhenxun.services.ai.core.models import (
|
|
ModelCapabilities,
|
|
ModelIdentity,
|
|
)
|
|
from zhenxun.services.ai.core.options import TTSConfig
|
|
from zhenxun.services.ai.llm.adapters.base import BaseAdapter, RequestData
|
|
|
|
from .base import BaseAudioHandler
|
|
from .openai_handlers import (
|
|
OpenAIConfigMapper,
|
|
OpenAIMessageConverter,
|
|
OpenAITextHandler,
|
|
OpenAIToolSerializer,
|
|
)
|
|
|
|
|
|
class MiMoToolSerializer(OpenAIToolSerializer):
|
|
"""MiMo 工具序列化器,负责拦截并构造独有的 web_search 工具"""
|
|
|
|
def serialize_server_tools(
|
|
self, tools: list[Any], capabilities: ModelCapabilities
|
|
) -> list[dict[str, Any]]:
|
|
res = []
|
|
for t in tools:
|
|
type_id = getattr(t, "type_id", "unknown")
|
|
if type_id not in capabilities.supported_native_tools:
|
|
continue
|
|
if type_id == "web_search":
|
|
res.append(
|
|
{
|
|
"type": "web_search",
|
|
"max_keyword": getattr(t, "max_keyword", 3),
|
|
"force_search": getattr(t, "force_search", True),
|
|
"limit": getattr(t, "limit", 1),
|
|
}
|
|
)
|
|
return res
|
|
|
|
|
|
class MiMoMessageConverter(OpenAIMessageConverter):
|
|
"""MiMo 消息转换器,拦截处理特有的音视频多模态结构"""
|
|
|
|
async def convert_messages_async(
|
|
self, messages: list[LLMMessage]
|
|
) -> list[dict[str, Any]]:
|
|
openai_messages = await super().convert_messages_async(messages)
|
|
|
|
for o_msg, o_orig in zip(openai_messages, messages):
|
|
if o_msg["role"] == "user":
|
|
content_parts = []
|
|
for part in o_orig.content:
|
|
if isinstance(part, TextPart):
|
|
content_parts.append({"type": "text", "text": part.text})
|
|
elif isinstance(part, ImagePart):
|
|
src = (
|
|
part.url
|
|
if part.url
|
|
else await part.get_data_uri(part.mime_type or "image/jpeg")
|
|
)
|
|
content_parts.append(
|
|
{"type": "image_url", "image_url": {"url": src}}
|
|
)
|
|
elif isinstance(part, VideoPart):
|
|
src = (
|
|
part.url
|
|
if part.url
|
|
else await part.get_data_uri(part.mime_type or "video/mp4")
|
|
)
|
|
content_parts.append(
|
|
{
|
|
"type": "video_url",
|
|
"video_url": {"url": src},
|
|
"fps": getattr(part, "fps", 2),
|
|
"media_resolution": getattr(
|
|
part, "media_resolution", "default"
|
|
),
|
|
}
|
|
)
|
|
elif isinstance(part, AudioPart):
|
|
src = (
|
|
part.url
|
|
if part.url
|
|
else await part.get_data_uri(part.mime_type or "audio/mp3")
|
|
)
|
|
content_parts.append(
|
|
{"type": "input_audio", "input_audio": {"data": src}}
|
|
)
|
|
o_msg["content"] = content_parts
|
|
return openai_messages
|
|
|
|
|
|
class MiMoTextHandler(OpenAITextHandler):
|
|
"""MiMo 文本对话处理器集成"""
|
|
|
|
def __init__(self, api_type: str = "mimo"):
|
|
super().__init__(api_type=api_type)
|
|
self.converter = MiMoMessageConverter(api_type=api_type)
|
|
self.serializer = MiMoToolSerializer(api_type=api_type)
|
|
self.mapper = OpenAIConfigMapper(api_type=api_type)
|
|
|
|
|
|
class MiMoAudioHandler(BaseAudioHandler):
|
|
"""MiMo TTS 接口实现:挂载在 Chat Completions 端点上"""
|
|
|
|
def prepare_speech_request(
|
|
self,
|
|
adapter: BaseAdapter,
|
|
identity: ModelIdentity,
|
|
api_key: str,
|
|
request: SpeechRequest,
|
|
) -> RequestData:
|
|
input_text = request.input_text
|
|
config = request.config or TTSConfig()
|
|
|
|
config_voice = (
|
|
config.mimo_options.voice_id if hasattr(config, "mimo_options") else None
|
|
)
|
|
voice = (
|
|
config_voice
|
|
or request.voice
|
|
or identity.capabilities.default_voice_id
|
|
or "mimo_default"
|
|
)
|
|
|
|
url = adapter.get_api_url(identity, "/v1/chat/completions")
|
|
headers = adapter.get_base_headers(api_key)
|
|
|
|
body = {
|
|
"model": identity.model_name,
|
|
"messages": [{"role": "assistant", "content": input_text}],
|
|
"audio": {
|
|
"format": config.response_format
|
|
if config.response_format in ("wav", "pcm16")
|
|
else "wav",
|
|
"voice": voice,
|
|
},
|
|
}
|
|
return RequestData(url=url, headers=headers, body=body)
|
|
|
|
async def parse_speech_response(
|
|
self,
|
|
adapter: BaseAdapter,
|
|
identity: ModelIdentity,
|
|
raw_response: httpx.Response,
|
|
) -> AudioResponse:
|
|
data = json.loads(await raw_response.aread())
|
|
adapter.validate_response(data)
|
|
audio_b64 = data["choices"][0]["message"]["audio"]["data"]
|
|
return AudioResponse(
|
|
audio_bytes=base64.b64decode(audio_b64),
|
|
audio_format="wav",
|
|
usage=UsageInfo(),
|
|
model_name=identity.model_name,
|
|
)
|