conversation_manager.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. """
  2. 多轮对话管理器 - 处理包含工具调用的多轮对话
  3. """
  4. import asyncio
  5. from typing import Dict, List, Any, Optional
  6. import httpx
  7. from anthropic import Anthropic
  8. from mcp_client import MCPClient
  9. from tool_converter import ToolConverter
  10. from tool_handler import ToolCallHandler
  11. # ========== 默认组件提示(降级方案) ==========
  12. # 当前端未发送组件列表时使用的默认提示
  13. DEFAULT_COMPONENTS_PROMPT = """### 可用的 json-render 组件
  14. 你可以使用基础组件来展示结构化数据:
  15. - `card`: 卡片容器
  16. - `stack`: 布局容器
  17. - `heading`: 标题 (h1-h6)
  18. - `text`: 文本内容
  19. - `button`: 按钮
  20. - `badge`: 徽章标签
  21. - `code-block`: 代码块
  22. - `data-table`: 数据表格
  23. 将组件 JSON 包含在 markdown 代码块中返回。
  24. """
  25. # ========== 基础 System Prompt ==========
  26. # 不包含组件列表和 MCP 工具说明,由 _build_system_prompt 动态构建
  27. BASE_SYSTEM_PROMPT = """你是一个 AI 助手,可以通过调用 MCP 工具来帮助用户完成任务。
  28. ## 当前状态
  29. {MCP_STATUS}
  30. ## 重要:你可以返回 UI 组件
  31. 除了普通文本,你还可以返回 **json-render 组件 spec** 来展示更丰富的 UI。组件 spec 是一个 JSON 对象,前端会自动渲染成 UI 组件。
  32. ### 组件格式
  33. 返回组件时,使用以下 JSON 格式(在你的回复中包裹在 ```json 中):
  34. ```json
  35. {
  36. "type": "组件类型",
  37. "其他属性": "..."
  38. }
  39. ```
  40. ### 使用指南
  41. 1. **调用工具后,优先使用对应组件展示结果**
  42. - 根据工具返回的数据类型选择合适的组件
  43. - 组件必须放在代码块中返回
  44. 2. **你可以混合文本和组件**
  45. - 先用文本解释结果
  46. - 然后用组件展示数据
  47. 3. **给出操作建议时使用按钮组件**
  48. - 用户查看列表后,建议"下一页"、"筛选"等操作
  49. - 使用 `button` 或 `suggestion-buttons` 组件
  50. {MCP_TOOLS_GUIDE}
  51. """
  52. # 小说相关操作说明(只有启用相关 MCP 时才显示)
  53. NOVEL_TOOLS_GUIDE = """### 小说相关操作(重要)
  54. 当用户说"查看小说:xxx"、"小说详情:xxx"或点击小说卡片时:
  55. 1. 从消息中提取小说标题或 ID
  56. 2. 使用 `get_novel_detail` 工具获取小说数据(需要提供 novel_id 参数)
  57. 3. 使用 `novel-detail` 组件展示结果,格式如下:
  58. ```json
  59. {
  60. "type": "novel-detail",
  61. "novel": {
  62. "id": "小说ID",
  63. "title": "小说标题",
  64. "author": "作者",
  65. "category": "分类",
  66. "description": "简介",
  67. "status": "状态",
  68. "chapterCount": 章节数,
  69. "wordCount": 字数,
  70. "viewCount": 阅读量,
  71. "isVip": 是否VIP
  72. }
  73. }
  74. ```
  75. """
  76. # 无 MCP 工具时的提示
  77. NO_TOOLS_GUIDE = """### 注意
  78. 当前没有启用任何 MCP 服务器,因此你没有可用的工具。你只能:
  79. - 进行普通对话
  80. - 返回 json-render 组件来展示信息
  81. 如果用户询问关于翻译、小说等功能,请告知用户需要先在 MCP 管理页面启用相关服务器。
  82. """
  83. def create_anthropic_client(api_key: str, base_url: str) -> Anthropic:
  84. """
  85. 创建 Anthropic 客户端,支持自定义认证格式
  86. 自定义 API 代理需要 'Authorization: Bearer <token>' 格式,
  87. 而不是 Anthropic SDK 默认的 'x-api-key' header。
  88. """
  89. # 创建自定义 httpx client,设置正确的 Authorization header
  90. http_client = httpx.Client(
  91. headers={"Authorization": f"Bearer {api_key}"},
  92. timeout=120.0
  93. )
  94. return Anthropic(base_url=base_url, http_client=http_client)
  95. class ConversationManager:
  96. """管理包含工具调用的多轮对话"""
  97. def __init__(
  98. self,
  99. api_key: str,
  100. base_url: str,
  101. model: str,
  102. session_id: str = None,
  103. mcp_tokens: dict = None,
  104. components_prompt: str = None,
  105. enabled_mcp_list: list = None # 新增:前端传递的已启用 MCP 列表
  106. ):
  107. self.api_key = api_key
  108. self.base_url = base_url
  109. self.model = model
  110. self.session_id = session_id
  111. self.mcp_tokens = mcp_tokens or {} # MCP 服务器 token 映射
  112. self.enabled_mcp_list = enabled_mcp_list # 前端传递的已启用 MCP 列表
  113. # 组件提示词(由前端动态提供)
  114. self.components_prompt = components_prompt or DEFAULT_COMPONENTS_PROMPT
  115. # 构建完整的系统提示词
  116. self.system_prompt = self._build_system_prompt()
  117. # DEBUG: 打印接收到的 token 和启用列表
  118. print(f"[DEBUG ConversationManager.__init__] mcp_tokens keys: {list(self.mcp_tokens.keys())}")
  119. print(f"[DEBUG ConversationManager.__init__] enabled_mcp_list: {self.enabled_mcp_list}")
  120. print(f"[DEBUG ConversationManager.__init__] Using dynamic components: {components_prompt is not None}")
  121. for k, v in self.mcp_tokens.items():
  122. print(f"[DEBUG ConversationManager.__init__] {k}: {v[:30] if v else 'None'}...")
  123. self.tool_handler = ToolCallHandler(session_id=session_id, mcp_tokens=mcp_tokens)
  124. self._cached_tools = None
  125. self._tool_to_server_map = {} # 工具名到服务器 ID 的映射
  126. # 使用自定义 client,支持 Bearer token 认证
  127. self.client = create_anthropic_client(api_key, base_url)
  128. def _build_system_prompt(self) -> str:
  129. """构建完整的系统提示词(基础提示 + MCP 状态 + 工具指南 + 组件列表)"""
  130. # 根据 enabled_mcp_list 构建 MCP 状态提示和工具指南
  131. if self.enabled_mcp_list is not None and len(self.enabled_mcp_list) == 0:
  132. # 所有 MCP 都被禁用
  133. mcp_status = """**重要:当前没有启用任何 MCP 服务器**
  134. 你没有可用的 MCP 工具。如果用户询问关于翻译、小说、组件等功能,请告诉用户:
  135. - 当前没有启用任何 MCP 服务器
  136. - 请前往 MCP 管理页面启用需要的服务器
  137. - 启用后刷新页面即可使用相关功能
  138. 你仍然可以使用基础的对话能力和返回 json-render 组件来帮助用户。"""
  139. mcp_tools_guide = NO_TOOLS_GUIDE
  140. elif self.enabled_mcp_list is not None and len(self.enabled_mcp_list) > 0:
  141. # 部分或全部 MCP 已启用
  142. enabled_names = ", ".join(self.enabled_mcp_list)
  143. mcp_status = f"""**已启用的 MCP 服务器**: {enabled_names}
  144. 你可以调用这些 MCP 服务器的工具来帮助用户完成任务。"""
  145. # 检查是否有小说相关的 MCP 启用
  146. has_novel_mcp = any('novel-platform' in mcp or 'novel' in mcp for mcp in self.enabled_mcp_list)
  147. if has_novel_mcp:
  148. mcp_tools_guide = NOVEL_TOOLS_GUIDE
  149. else:
  150. mcp_tools_guide = ""
  151. else:
  152. # enabled_mcp_list 是 None,使用配置文件的默认状态
  153. mcp_status = """你可以通过调用 MCP 工具来帮助用户完成任务。"""
  154. mcp_tools_guide = NOVEL_TOOLS_GUIDE # 默认显示小说工具指南
  155. # 替换占位符并添加组件列表
  156. prompt = BASE_SYSTEM_PROMPT.replace("{MCP_STATUS}", mcp_status)
  157. prompt = prompt.replace("{MCP_TOOLS_GUIDE}", mcp_tools_guide)
  158. return prompt + "\n\n" + self.components_prompt
  159. async def get_available_tools(self) -> List[Dict[str, Any]]:
  160. """获取可用的 Claude 格式工具列表(带缓存)"""
  161. if self._cached_tools is not None:
  162. return self._cached_tools
  163. # 从 MCP 服务器发现工具(带 token 和启用列表)
  164. mcp_tools = await MCPClient.get_all_tools_with_tokens_async(
  165. self.session_id,
  166. self.mcp_tokens,
  167. self.enabled_mcp_list # 传递前端传递的已启用 MCP 列表
  168. )
  169. # 转换为 Claude 格式
  170. claude_tools = []
  171. for tool in mcp_tools:
  172. claude_tool = ToolConverter.mcp_to_claude_tool(tool)
  173. claude_tools.append(claude_tool)
  174. # 构建工具名到服务器 ID 的映射
  175. server_id = tool.get("_server_id", "")
  176. if server_id:
  177. self._tool_to_server_map[claude_tool["name"]] = server_id
  178. self._cached_tools = claude_tools
  179. return claude_tools
  180. @classmethod
  181. async def get_tools_async(cls, session_id: str = None) -> List[Dict[str, Any]]:
  182. """
  183. 类方法:获取可用的工具列表(异步)
  184. 用于 API 端点直接调用,无需创建完整实例
  185. """
  186. mcp_tools = await MCPClient.get_all_tools_async(session_id)
  187. return ToolConverter.convert_mcp_tools(mcp_tools)
  188. @staticmethod
  189. def get_tools(session_id: str = None) -> List[Dict[str, Any]]:
  190. """
  191. 静态方法:获取可用的工具列表(同步)
  192. 用于 API 端点直接调用
  193. """
  194. return asyncio.run(ConversationManager.get_tools_async(session_id))
  195. async def chat(
  196. self,
  197. user_message: str,
  198. conversation_history: List[Dict[str, Any]] = None,
  199. max_turns: int = 5
  200. ) -> Dict[str, Any]:
  201. """
  202. 执行多轮对话(自动处理工具调用)
  203. Args:
  204. user_message: 用户消息
  205. conversation_history: 对话历史
  206. max_turns: 最大对话轮数(防止无限循环)
  207. Returns:
  208. 最终响应和对话历史
  209. """
  210. if conversation_history is None:
  211. conversation_history = []
  212. messages = conversation_history.copy()
  213. messages.append({
  214. "role": "user",
  215. "content": user_message
  216. })
  217. current_messages = messages
  218. response_text = ""
  219. tool_calls_made = []
  220. for turn in range(max_turns):
  221. # 获取可用工具
  222. tools = await self.get_available_tools()
  223. # 调用 Claude API
  224. if tools:
  225. response = self.client.messages.create(
  226. model=self.model,
  227. max_tokens=4096,
  228. system=self.system_prompt, # 使用动态系统提示
  229. messages=current_messages,
  230. tools=tools
  231. )
  232. else:
  233. response = self.client.messages.create(
  234. model=self.model,
  235. max_tokens=4096,
  236. system=self.system_prompt, # 使用动态系统提示
  237. messages=current_messages
  238. )
  239. # 检查响应中是否有 tool_use
  240. content_blocks = []
  241. tool_use_blocks = []
  242. text_blocks = []
  243. for block in response.content:
  244. block_type = getattr(block, "type", None)
  245. if block_type == "tool_use":
  246. # 工具调用块
  247. block_dict = {
  248. "type": "tool_use",
  249. "id": getattr(block, "id", ""),
  250. "name": getattr(block, "name", ""),
  251. "input": getattr(block, "input", {})
  252. }
  253. content_blocks.append(block_dict)
  254. tool_use_blocks.append(block_dict)
  255. else:
  256. # 文本块
  257. text_content = getattr(block, "text", "")
  258. if text_content:
  259. text_blocks.append({
  260. "type": "text",
  261. "text": text_content
  262. })
  263. content_blocks.append({
  264. "type": "text",
  265. "text": text_content
  266. })
  267. response_text += text_content
  268. # 如果没有工具调用,返回结果
  269. if not tool_use_blocks:
  270. return {
  271. "response": response_text,
  272. "messages": current_messages,
  273. "tool_calls": tool_calls_made
  274. }
  275. # 处理工具调用
  276. tool_results = await self.tool_handler.process_tool_use_blocks(
  277. tool_use_blocks,
  278. self._tool_to_server_map
  279. )
  280. # 记录工具调用
  281. for tr in tool_results:
  282. tool_calls_made.append({
  283. "tool": tr.get("tool_name"),
  284. "result": tr.get("result", {})
  285. })
  286. # 构建工具结果消息
  287. tool_result_message = ToolCallHandler.create_tool_result_message(
  288. tool_results
  289. )
  290. # 添加到消息历史
  291. current_messages.append({
  292. "role": "assistant",
  293. "content": content_blocks
  294. })
  295. current_messages.append(tool_result_message)
  296. # 达到最大轮数
  297. return {
  298. "response": response_text,
  299. "messages": current_messages,
  300. "tool_calls": tool_calls_made,
  301. "warning": "达到最大对话轮数"
  302. }
  303. @staticmethod
  304. def format_history_for_claude(history: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
  305. """
  306. 格式化对话历史为 Claude API 格式
  307. Args:
  308. history: 原始对话历史
  309. Returns:
  310. Claude API 格式的消息列表
  311. """
  312. formatted = []
  313. for msg in history:
  314. role = msg.get("role")
  315. content = msg.get("content")
  316. if role == "user":
  317. if isinstance(content, str):
  318. formatted.append({"role": "user", "content": content})
  319. elif isinstance(content, list):
  320. formatted.append({"role": "user", "content": content})
  321. elif role == "assistant":
  322. if isinstance(content, str):
  323. formatted.append({"role": "assistant", "content": content})
  324. elif isinstance(content, list):
  325. formatted.append({"role": "assistant", "content": content})
  326. return formatted