2026-01-22 05:57:13 +08:00
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
|
|
from collections.abc import Callable
|
2026-02-21 02:48:20 +08:00
|
|
|
|
from pathlib import PurePosixPath
|
2026-01-22 05:57:13 +08:00
|
|
|
|
from typing import Any
|
|
|
|
|
|
|
2026-02-21 02:48:20 +08:00
|
|
|
|
from deepagents.middleware.skills import SKILLS_SYSTEM_PROMPT
|
2026-01-22 05:57:13 +08:00
|
|
|
|
from langchain.agents.middleware import AgentMiddleware, ModelRequest, ModelResponse
|
2026-01-29 22:48:48 +08:00
|
|
|
|
from langchain_core.messages import SystemMessage
|
2026-01-22 05:57:13 +08:00
|
|
|
|
|
|
|
|
|
|
from src.agents.common import load_chat_model
|
2026-01-29 22:48:48 +08:00
|
|
|
|
from src.agents.common.tools import get_buildin_tools, get_kb_based_tools
|
2026-01-22 06:54:14 +08:00
|
|
|
|
from src.services.mcp_service import get_enabled_mcp_tools
|
2026-02-21 02:48:20 +08:00
|
|
|
|
from src.services.skill_service import get_skill_prompt_metadata_by_slugs
|
2026-01-29 22:48:48 +08:00
|
|
|
|
from src.utils.datetime_utils import shanghai_now
|
2026-01-22 11:40:09 +08:00
|
|
|
|
from src.utils.logging_config import logger
|
2026-01-22 05:57:13 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class RuntimeConfigMiddleware(AgentMiddleware):
|
2026-01-22 06:54:14 +08:00
|
|
|
|
"""运行时配置中间件 - 应用模型/工具/知识库/MCP/提示词配置
|
|
|
|
|
|
|
|
|
|
|
|
注意:所有可能用到的知识库工具必须在初始化时预加载并注册到 self.tools
|
|
|
|
|
|
运行时根据配置从 self.tools 中筛选工具,不能动态添加新工具
|
2026-01-30 12:40:54 +08:00
|
|
|
|
|
|
|
|
|
|
支持自定义上下文字段名称,以便在不同场景(如主智能体/子智能体)使用不同的配置字段
|
2026-01-22 06:54:14 +08:00
|
|
|
|
"""
|
|
|
|
|
|
|
2026-01-30 12:40:54 +08:00
|
|
|
|
def __init__(
|
|
|
|
|
|
self,
|
|
|
|
|
|
*,
|
|
|
|
|
|
extra_tools: list[Any] | None = None,
|
|
|
|
|
|
model_context_name: str = "model",
|
|
|
|
|
|
system_prompt_context_name: str = "system_prompt",
|
|
|
|
|
|
tools_context_name: str = "tools",
|
|
|
|
|
|
knowledges_context_name: str = "knowledges",
|
|
|
|
|
|
mcps_context_name: str = "mcps",
|
2026-02-21 02:48:20 +08:00
|
|
|
|
skills_context_name: str = "skills",
|
2026-01-30 13:34:11 +08:00
|
|
|
|
enable_model_override: bool = True,
|
|
|
|
|
|
enable_system_prompt_override: bool = True,
|
|
|
|
|
|
enable_tools_override: bool = True,
|
2026-02-21 02:48:20 +08:00
|
|
|
|
enable_skills_prompt_override: bool = True,
|
|
|
|
|
|
skills_sources_for_prompt: list[str] | None = None,
|
2026-01-30 12:40:54 +08:00
|
|
|
|
):
|
2026-01-22 06:54:14 +08:00
|
|
|
|
"""初始化中间件
|
|
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
extra_tools: 额外工具列表(从 create_agent 的 tools 参数传入)
|
2026-01-30 12:40:54 +08:00
|
|
|
|
model_context_name: 上下文中的模型字段名称(默认 "model")
|
|
|
|
|
|
system_prompt_context_name: 上下文中的系统提示词字段名称(默认 "system_prompt")
|
|
|
|
|
|
tools_context_name: 上下文中的工具列表字段名称(默认 "tools")
|
|
|
|
|
|
knowledges_context_name: 上下文中的知识库列表字段名称(默认 "knowledges")
|
|
|
|
|
|
mcps_context_name: 上下文中的 MCP 服务器列表字段名称(默认 "mcps")
|
2026-02-21 02:48:20 +08:00
|
|
|
|
skills_context_name: 上下文中的 skills 列表字段名称(默认 "skills")
|
2026-01-30 13:34:11 +08:00
|
|
|
|
enable_model_override: 是否允许覆盖模型配置(默认 True)
|
|
|
|
|
|
enable_system_prompt_override: 是否允许覆盖系统提示词(默认 True)
|
|
|
|
|
|
enable_tools_override: 是否允许覆盖工具列表(默认 True)
|
2026-02-21 02:48:20 +08:00
|
|
|
|
enable_skills_prompt_override: 是否启用 skills 提示段注入(默认 True)
|
|
|
|
|
|
skills_sources_for_prompt: skills 来源路径(用于提示词展示,默认 ["/skills/"])
|
2026-01-22 06:54:14 +08:00
|
|
|
|
"""
|
|
|
|
|
|
super().__init__()
|
2026-01-30 12:40:54 +08:00
|
|
|
|
# 存储自定义字段名称
|
|
|
|
|
|
self.model_context_name = model_context_name
|
|
|
|
|
|
self.system_prompt_context_name = system_prompt_context_name
|
|
|
|
|
|
self.tools_context_name = tools_context_name
|
|
|
|
|
|
self.knowledges_context_name = knowledges_context_name
|
|
|
|
|
|
self.mcps_context_name = mcps_context_name
|
2026-02-21 02:48:20 +08:00
|
|
|
|
self.skills_context_name = skills_context_name
|
2026-01-30 13:34:11 +08:00
|
|
|
|
# 存储覆盖配置
|
|
|
|
|
|
self.enable_model_override = enable_model_override
|
|
|
|
|
|
self.enable_system_prompt_override = enable_system_prompt_override
|
|
|
|
|
|
self.enable_tools_override = enable_tools_override
|
2026-02-21 02:48:20 +08:00
|
|
|
|
self.enable_skills_prompt_override = enable_skills_prompt_override
|
|
|
|
|
|
self.skills_sources_for_prompt = skills_sources_for_prompt or ["/skills/"]
|
2026-02-03 03:29:16 +08:00
|
|
|
|
|
|
|
|
|
|
self.tools: list[Any] = []
|
|
|
|
|
|
# 预加载工具列表(仅当启用工具覆盖时)
|
|
|
|
|
|
if self.enable_tools_override:
|
|
|
|
|
|
self.kb_tools = get_kb_based_tools()
|
|
|
|
|
|
self.buildin_tools = get_buildin_tools()
|
|
|
|
|
|
self.tools = self.kb_tools + self.buildin_tools + (extra_tools or [])
|
|
|
|
|
|
elif extra_tools:
|
|
|
|
|
|
logger.warning(
|
|
|
|
|
|
"RuntimeConfigMiddleware: extra_tools 参数已提供,但 enable_tools_override=False,"
|
|
|
|
|
|
"将忽略 extra_tools 并不会应用任何工具覆盖。"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
2026-01-30 12:40:54 +08:00
|
|
|
|
logger.debug(
|
|
|
|
|
|
f"Initialized RuntimeConfigMiddleware with custom field names: model={model_context_name}, "
|
|
|
|
|
|
f"system_prompt={system_prompt_context_name}, tools={tools_context_name}, "
|
2026-02-21 02:48:20 +08:00
|
|
|
|
f"knowledges={knowledges_context_name}, mcps={mcps_context_name}, "
|
|
|
|
|
|
f"skills={skills_context_name}"
|
2026-01-30 12:40:54 +08:00
|
|
|
|
)
|
2026-01-22 06:54:14 +08:00
|
|
|
|
|
2026-01-22 05:57:13 +08:00
|
|
|
|
async def awrap_model_call(
|
|
|
|
|
|
self, request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse]
|
|
|
|
|
|
) -> ModelResponse:
|
|
|
|
|
|
runtime_context = request.runtime.context
|
2026-01-30 13:34:11 +08:00
|
|
|
|
overrides: dict[str, Any] = {}
|
|
|
|
|
|
|
|
|
|
|
|
# 1. 模型覆盖(可选)
|
|
|
|
|
|
if self.enable_model_override:
|
|
|
|
|
|
model = load_chat_model(getattr(runtime_context, self.model_context_name, None))
|
|
|
|
|
|
overrides["model"] = model
|
|
|
|
|
|
|
|
|
|
|
|
# 2. 工具覆盖(可选)
|
|
|
|
|
|
if self.enable_tools_override:
|
|
|
|
|
|
enabled_tools = await self.get_tools_from_context(runtime_context)
|
|
|
|
|
|
existing_tools = list(request.tools or [])
|
|
|
|
|
|
merged_tools = []
|
|
|
|
|
|
for t_bind in existing_tools:
|
2026-01-30 19:35:11 +08:00
|
|
|
|
# (1) 已启用的工具保留
|
|
|
|
|
|
# (2) 非本中间件管理的工具保留
|
2026-02-02 21:44:10 +08:00
|
|
|
|
if t_bind.name in [t.name for t in enabled_tools] or t_bind.name not in [t.name for t in self.tools]:
|
2026-01-30 13:34:11 +08:00
|
|
|
|
merged_tools.append(t_bind)
|
|
|
|
|
|
overrides["tools"] = merged_tools
|
2026-01-30 19:35:11 +08:00
|
|
|
|
logger.debug(f"RuntimeConfigMiddleware selected tools: {[t.name for t in merged_tools]}")
|
|
|
|
|
|
|
2026-01-30 13:34:11 +08:00
|
|
|
|
# 3. 系统提示词覆盖(可选)
|
|
|
|
|
|
if self.enable_system_prompt_override:
|
|
|
|
|
|
cur_datetime = f"当前时间:{shanghai_now().strftime('%Y-%m-%d %H:%M:%S')} UTC"
|
|
|
|
|
|
system_prompt = getattr(runtime_context, self.system_prompt_context_name, "") or ""
|
2026-02-21 02:48:20 +08:00
|
|
|
|
merged_system_prompt = f"{cur_datetime}\n\n{system_prompt}"
|
|
|
|
|
|
|
|
|
|
|
|
configured_skills = getattr(runtime_context, self.skills_context_name, None) or []
|
|
|
|
|
|
if self.enable_skills_prompt_override and configured_skills:
|
|
|
|
|
|
if self._supports_skill_prompt(request):
|
|
|
|
|
|
skills_meta = get_skill_prompt_metadata_by_slugs(configured_skills)
|
|
|
|
|
|
skills_section = self._build_skills_section(skills_meta)
|
|
|
|
|
|
merged_system_prompt = f"{merged_system_prompt}\n\n{skills_section}"
|
|
|
|
|
|
else:
|
|
|
|
|
|
logger.warning(
|
|
|
|
|
|
"RuntimeConfigMiddleware: skills configured but read_file unavailable, skip skills prompt"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
content_blocks = list(request.system_message.content_blocks) if request.system_message else []
|
|
|
|
|
|
new_content = content_blocks + [{"type": "text", "text": merged_system_prompt}]
|
2026-01-30 13:34:11 +08:00
|
|
|
|
new_system_message = SystemMessage(content=new_content)
|
|
|
|
|
|
overrides["system_message"] = new_system_message
|
|
|
|
|
|
|
|
|
|
|
|
if overrides:
|
|
|
|
|
|
request = request.override(**overrides)
|
2026-01-22 05:57:13 +08:00
|
|
|
|
|
|
|
|
|
|
return await handler(request)
|
2026-01-22 06:54:14 +08:00
|
|
|
|
|
|
|
|
|
|
async def get_tools_from_context(self, context) -> list:
|
|
|
|
|
|
"""从上下文配置中获取工具列表"""
|
|
|
|
|
|
selected_tools = []
|
|
|
|
|
|
|
2026-01-30 12:40:54 +08:00
|
|
|
|
# 1. 基础工具 (从 context.tools 中筛选)
|
|
|
|
|
|
tools = getattr(context, self.tools_context_name, None)
|
|
|
|
|
|
if tools:
|
2026-01-22 06:54:14 +08:00
|
|
|
|
tools_map = {t.name: t for t in self.tools}
|
2026-01-30 12:40:54 +08:00
|
|
|
|
for tool_name in tools:
|
2026-01-22 06:54:14 +08:00
|
|
|
|
if tool_name in tools_map:
|
|
|
|
|
|
selected_tools.append(tools_map[tool_name])
|
|
|
|
|
|
|
|
|
|
|
|
# 2. 知识库工具
|
2026-01-30 12:40:54 +08:00
|
|
|
|
knowledges = getattr(context, self.knowledges_context_name, None)
|
|
|
|
|
|
if knowledges:
|
|
|
|
|
|
kb_tools = get_kb_based_tools(db_names=knowledges)
|
2026-01-22 06:54:14 +08:00
|
|
|
|
selected_tools.extend(kb_tools)
|
|
|
|
|
|
|
|
|
|
|
|
# 3. MCP 工具(使用统一入口,自动过滤 disabled_tools)
|
2026-01-30 12:40:54 +08:00
|
|
|
|
mcps = getattr(context, self.mcps_context_name, None)
|
|
|
|
|
|
if mcps:
|
|
|
|
|
|
for server_name in mcps:
|
2026-01-22 06:54:14 +08:00
|
|
|
|
mcp_tools = await get_enabled_mcp_tools(server_name)
|
|
|
|
|
|
selected_tools.extend(mcp_tools)
|
|
|
|
|
|
|
|
|
|
|
|
return selected_tools
|
2026-02-21 02:48:20 +08:00
|
|
|
|
|
|
|
|
|
|
def _supports_skill_prompt(self, request: ModelRequest) -> bool:
|
|
|
|
|
|
"""仅当请求工具中包含 read_file 时,才注入 skills 指引。"""
|
|
|
|
|
|
for tool in request.tools or []:
|
|
|
|
|
|
if getattr(tool, "name", None) == "read_file":
|
|
|
|
|
|
return True
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
def _format_skills_locations(self, sources: list[str]) -> str:
|
|
|
|
|
|
locations = []
|
|
|
|
|
|
for i, source_path in enumerate(sources):
|
|
|
|
|
|
name = PurePosixPath(source_path.rstrip("/")).name.capitalize()
|
|
|
|
|
|
suffix = " (higher priority)" if i == len(sources) - 1 else ""
|
|
|
|
|
|
locations.append(f"**{name} Skills**: `{source_path}`{suffix}")
|
|
|
|
|
|
return "\n".join(locations)
|
|
|
|
|
|
|
|
|
|
|
|
def _format_skills_list(self, skills_meta: list[dict[str, str]]) -> str:
|
|
|
|
|
|
if not skills_meta:
|
|
|
|
|
|
return f"(No skills available yet. You can create skills in {' or '.join(self.skills_sources_for_prompt)})"
|
|
|
|
|
|
|
|
|
|
|
|
lines = []
|
|
|
|
|
|
for skill in skills_meta:
|
|
|
|
|
|
lines.append(f"- **{skill['name']}**: {skill['description']}")
|
|
|
|
|
|
lines.append(f" -> Read `{skill['path']}` for full instructions")
|
|
|
|
|
|
return "\n".join(lines)
|
|
|
|
|
|
|
|
|
|
|
|
def _build_skills_section(self, skills_meta: list[dict[str, str]]) -> str:
|
|
|
|
|
|
skills_locations = self._format_skills_locations(self.skills_sources_for_prompt)
|
|
|
|
|
|
skills_list = self._format_skills_list(skills_meta)
|
|
|
|
|
|
return SKILLS_SYSTEM_PROMPT.format(
|
|
|
|
|
|
skills_locations=skills_locations,
|
|
|
|
|
|
skills_list=skills_list,
|
|
|
|
|
|
)
|