Files
zhenxun_bot/zhenxun/services/ai/llm/builder.py
T
922d092650 ♻️ refactor(core): 重构 AI 能力与定时任务调度系统 (#2148)
* ♻️ 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>
2026-07-10 09:14:06 +08:00

210 lines
7.1 KiB
Python

"""
LLM 生成配置相关类和函数
"""
from typing import Any, Literal
from typing_extensions import Self
from zhenxun.services.ai.core.exceptions import ConfigurationException
from zhenxun.services.ai.core.options import (
GenerationConfig,
ResponseFormat,
)
from zhenxun.services.ai.utils.logger import log_llm as logger
from zhenxun.utils.pydantic_compat import model_json_schema, model_validate
class GeminiIntentNamespace:
"""Gemini 专属高级参数构建域"""
def __init__(self, builder: "IntentBuilder"):
self._builder = builder
def set_safety_threshold(self, threshold: str) -> "IntentBuilder":
"""强制设置 Gemini 安全阈值 (如 BLOCK_NONE, BLOCK_ONLY_HIGH)"""
self._builder._config.gemini_options.safety_settings = {
"HARM_CATEGORY_HARASSMENT": threshold,
"HARM_CATEGORY_HATE_SPEECH": threshold,
"HARM_CATEGORY_SEXUALLY_EXPLICIT": threshold,
"HARM_CATEGORY_DANGEROUS_CONTENT": threshold,
}
return self._builder
class OpenAIIntentNamespace:
"""OpenAI 专属高级参数构建域"""
def __init__(self, builder: "IntentBuilder"):
self._builder = builder
def enable_server_storage(self, store: bool = True) -> "IntentBuilder":
"""设置是否在 OpenAI 服务端留存请求记录"""
self._builder._config.openai_options.store = store
return self._builder
class IntentBuilder:
"""
基于能力意图声明的构建器 (Intent-Driven Builder)。
完全屏蔽底层厂商参数差异,面向开发者提供 Fluent API。
"""
def __init__(self):
self._config = GenerationConfig()
@property
def gemini(self) -> GeminiIntentNamespace:
return GeminiIntentNamespace(self)
@property
def openai(self) -> OpenAIIntentNamespace:
return OpenAIIntentNamespace(self)
def with_reasoning(self, level: str | None = None) -> Self:
"""
跨厂商统一的思考/推理等级意图声明。
自动向下转换为底层合法参数,并阻止不兼容模型的非法调用。
"""
if level:
self._config.common.reasoning_effort = level
if level.lower() != "none":
self._config.gemini_options.include_thoughts = True
return self
def with_local_cache(self, ttl: int = 3600) -> Self:
"""
显式开启本次 LLM 网络请求的极速本地缓存。
对于相同模型、相同参数、相同 Prompt 的请求,将直接返回本地记忆,免去网络开销。
适用于 Embedding、确定性的结构化抽取或工作流节点。
"""
self._config.custom_kwargs["__cache_ttl__"] = ttl
return self
def with_json_output(self) -> Self:
"""
基础结构化意图:要求大模型输出通用 JSON 格式(不校验 Schema)。
"""
self._config.output.response_format = ResponseFormat.JSON
self._config.output.response_mime_type = "application/json"
self._config.output.structured_output_strategy = "native"
return self
def require_structured_output(self, schema: Any, strict: bool = True) -> Self:
"""
强制要求结构化输出意图。
支持自动处理 Pydantic 模型并转换为厂商所需的 JSON Schema。
"""
import inspect
from pydantic import BaseModel
from zhenxun.services.ai.core.options import StructuredOutputStrategy
self._config.output.response_format = ResponseFormat.JSON
self._config.output.response_mime_type = "application/json"
if schema:
if inspect.isclass(schema) and issubclass(schema, BaseModel):
self._config.output.response_schema = model_json_schema(schema)
else:
from typing import cast
self._config.output.response_schema = cast(dict[str, Any], schema)
if strict:
self._config.output.structured_output_strategy = (
StructuredOutputStrategy.NATIVE
)
return self
def config_core(
self,
temperature: float | None = None,
max_tokens: int | None = None,
top_p: float | None = None,
) -> Self:
"""
配置底层核心采样参数(如 temperature, max_tokens 等)。
"""
if temperature is not None:
self._config.common.temperature = temperature
if max_tokens is not None:
self._config.common.max_tokens = max_tokens
if top_p is not None:
self._config.common.top_p = top_p
return self
def with_safety_level(self, level: str = "moderate") -> Self:
"""
安全合规意图。
level 取值: 'strict' (最严格), 'moderate' (中等), 'none' (完全无限制)。
"""
from zhenxun.services.ai.config import get_gemini_safety_threshold
if level == "strict":
self.gemini.set_safety_threshold("BLOCK_LOW_AND_ABOVE")
elif level == "none":
self.gemini.set_safety_threshold("BLOCK_NONE")
else:
self.gemini.set_safety_threshold(get_gemini_safety_threshold())
return self
def with_image_generation_params(
self, aspect_ratio: str = "16:9", resolution: str = "1K"
) -> Self:
"""
生图意图:统一配置图像生成的比例与分辨率。
"""
self._config.media.aspect_ratio = aspect_ratio
self._config.media.resolution = resolution
return self
def with_vision_optimization(
self, quality: Literal["low", "medium", "high", "standard", "hd"] = "high"
) -> Self:
"""
视觉优化意图。
"""
self._config.media.quality = quality
return self
def with_provider_raw_kwargs(self, provider_name: str, **kwargs) -> Self:
"""厂商逃生舱:直接注入特有参数"""
provider_name = provider_name.lower()
if provider_name == "openai":
for k, v in kwargs.items():
setattr(self._config.openai_options, k, v)
elif provider_name == "gemini":
for k, v in kwargs.items():
setattr(self._config.gemini_options, k, v)
else:
self._config.custom_kwargs.update(kwargs)
return self
def build(self) -> GenerationConfig:
"""构建最终的配置对象"""
return self._config
def validate_override_params(
override_config: dict[str, Any] | GenerationConfig | None,
) -> GenerationConfig:
"""验证和标准化覆盖参数"""
if override_config is None:
return GenerationConfig()
if isinstance(override_config, GenerationConfig):
return override_config
if isinstance(override_config, dict):
try:
return model_validate(GenerationConfig, override_config)
except Exception as e:
logger.warning(f"覆盖配置参数验证失败: {e}")
raise ConfigurationException(
f"无效的覆盖配置参数: {e}",
cause=e,
)
raise ConfigurationException(
f"不支持的配置类型: {type(override_config)}",
)