mirror of
https://github.com/zhenxun-org/zhenxun_bot.git
synced 2026-10-05 03:39:59 +08:00
* ✨ feat!(llm): 重构并升级大语言模型服务为全新 AI 智能体框架 - 【重构】将原 services/llm 重构并迁移至全新的 services/ai 架构,提供向下兼容垫片 - 【新增】引入 Agent、Team、Workflow 三大智能体与工作流编排范式 - 【新增】引入基于 RAG 的长期向量记忆与中期槽位记忆系统 - 【新增】引入基于 Docker 的安全代码执行沙箱环境 - 【新增】支持 MCP 协议,允许动态管理和调用 MCP 服务 - 【新增】引入输入输出安全合规护栏与自愈反思机制 - 【优化】重构并优化多厂商 API 适配器 (Gemini, OpenAI, DeepSeek, GLM 等) - 【优化】优化日志脱敏与 Token 预估机制 - 【移除】移除旧版 llm default 和 llm reset-key 命令,新增 llm mcp 管理命令 * 🔧 chore(deps): 更新项目依赖与配置 - 添加 mcp、jieba 和 aiodocker 依赖到配置文件及 requirements.txt - 在 pyright 配置中设置 reportMissingImports 为 none - 调整 .gitignore 中 resources 目录的忽略规则 * ♻️ refactor(tools): 重构工具终止机制并清理知识库日志输出 - 统一使用 `context.state["__end_run__"]` 替代 `EndRunResult` 控制任务结束 - 移除文件系统和向量知识库检索工具中 `ToolResult` 的 `.with_log` 调用 - 调整指令处理器(Directive)的返回值为 `tool_res.output` - 修复部分类型检查警告并优化联合类型判断语法 * ♻️ refactor(tools): 重构工具副作用指令与控制流熔断机制 - 引入 `DirectivePayload` 及 `ToolResult` 的子类以结构化表达工具副作用 - 移除通过 `context.state` 传递魔术变量的隐式控制流设计 - 重构 `DirectiveManager` 处理器接口,直接在处理器中修改 `AgentState` 并构建 `AgentRunResult` - 在 `StandardAgentExecutor` 中统一通过 `directive_manager` 调度工具返回的副作用指令 - 补全 `MessageBuilder` 中部分核心方法的文档注释 * 🐛 fix(sandbox): 修复 Docker 沙箱容器状态检测与会话清理逻辑 -【修复】修正 `is_alive` 中直接读取私有属性的问题,改用 `show()` 返回值 -【修复】解决 `execute_code` 中缓存的执行器与当前会话不一致的问题 -【优化】在清理工作区前增加容器存活检测,避免向已死容器发送请求 -【优化】创建容器时增加运行状态校验,若已停止则自动从缓存中移除并重建 -【优化】优化容器销毁和清理逻辑,静默处理容器不存在 (404) 的异常 * 📝 docs(core): 补充核心模块初始化方法的文档注释 * 🚨 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>
229 lines
7.7 KiB
Python
229 lines
7.7 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.log import 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 DeepSeekIntentNamespace:
|
|
"""DeepSeek 专属高级参数构建域"""
|
|
|
|
def __init__(self, builder: "IntentBuilder"):
|
|
self._builder = builder
|
|
|
|
def disable_thinking(self) -> "IntentBuilder":
|
|
"""显式关闭 DeepSeek 的思维链"""
|
|
self._builder._config.deepseek_options.thinking = False
|
|
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)
|
|
|
|
@property
|
|
def deepseek(self) -> DeepSeekIntentNamespace:
|
|
return DeepSeekIntentNamespace(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
|
|
self._config.deepseek_options.thinking = True
|
|
else:
|
|
self._config.deepseek_options.thinking = False
|
|
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)}",
|
|
)
|