conversation_manager.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. def create_anthropic_client(api_key: str, base_url: str) -> Anthropic:
  12. """
  13. 创建 Anthropic 客户端,支持自定义认证格式
  14. 自定义 API 代理需要 'Authorization: Bearer <token>' 格式,
  15. 而不是 Anthropic SDK 默认的 'x-api-key' header。
  16. """
  17. # 创建自定义 httpx client,设置正确的 Authorization header
  18. http_client = httpx.Client(
  19. headers={"Authorization": f"Bearer {api_key}"},
  20. timeout=120.0
  21. )
  22. return Anthropic(base_url=base_url, http_client=http_client)
  23. class ConversationManager:
  24. """管理包含工具调用的多轮对话"""
  25. def __init__(
  26. self,
  27. api_key: str,
  28. base_url: str,
  29. model: str,
  30. session_id: str = None,
  31. mcp_tokens: dict = None
  32. ):
  33. self.api_key = api_key
  34. self.base_url = base_url
  35. self.model = model
  36. self.session_id = session_id
  37. self.mcp_tokens = mcp_tokens or {} # MCP 服务器 token 映射
  38. self.tool_handler = ToolCallHandler(session_id=session_id, mcp_tokens=mcp_tokens)
  39. self._cached_tools = None
  40. self._tool_to_server_map = {} # 工具名到服务器 ID 的映射
  41. # 使用自定义 client,支持 Bearer token 认证
  42. self.client = create_anthropic_client(api_key, base_url)
  43. async def get_available_tools(self) -> List[Dict[str, Any]]:
  44. """获取可用的 Claude 格式工具列表(带缓存)"""
  45. if self._cached_tools is not None:
  46. return self._cached_tools
  47. # 从 MCP 服务器发现工具(带 token)
  48. mcp_tools = await MCPClient.get_all_tools_with_tokens_async(
  49. self.session_id, self.mcp_tokens
  50. )
  51. # 转换为 Claude 格式
  52. claude_tools = []
  53. for tool in mcp_tools:
  54. claude_tool = ToolConverter.mcp_to_claude_tool(tool)
  55. claude_tools.append(claude_tool)
  56. # 构建工具名到服务器 ID 的映射
  57. server_id = tool.get("_server_id", "")
  58. if server_id:
  59. self._tool_to_server_map[claude_tool["name"]] = server_id
  60. self._cached_tools = claude_tools
  61. return claude_tools
  62. @classmethod
  63. async def get_tools_async(cls, session_id: str = None) -> List[Dict[str, Any]]:
  64. """
  65. 类方法:获取可用的工具列表(异步)
  66. 用于 API 端点直接调用,无需创建完整实例
  67. """
  68. mcp_tools = await MCPClient.get_all_tools_async(session_id)
  69. return ToolConverter.convert_mcp_tools(mcp_tools)
  70. @staticmethod
  71. def get_tools(session_id: str = None) -> List[Dict[str, Any]]:
  72. """
  73. 静态方法:获取可用的工具列表(同步)
  74. 用于 API 端点直接调用
  75. """
  76. return asyncio.run(ConversationManager.get_tools_async(session_id))
  77. async def chat(
  78. self,
  79. user_message: str,
  80. conversation_history: List[Dict[str, Any]] = None,
  81. max_turns: int = 5
  82. ) -> Dict[str, Any]:
  83. """
  84. 执行多轮对话(自动处理工具调用)
  85. Args:
  86. user_message: 用户消息
  87. conversation_history: 对话历史
  88. max_turns: 最大对话轮数(防止无限循环)
  89. Returns:
  90. 最终响应和对话历史
  91. """
  92. if conversation_history is None:
  93. conversation_history = []
  94. messages = conversation_history.copy()
  95. messages.append({
  96. "role": "user",
  97. "content": user_message
  98. })
  99. current_messages = messages
  100. response_text = ""
  101. tool_calls_made = []
  102. for turn in range(max_turns):
  103. # 获取可用工具
  104. tools = await self.get_available_tools()
  105. # 调用 Claude API
  106. if tools:
  107. response = self.client.messages.create(
  108. model=self.model,
  109. max_tokens=4096,
  110. messages=current_messages,
  111. tools=tools
  112. )
  113. else:
  114. response = self.client.messages.create(
  115. model=self.model,
  116. max_tokens=4096,
  117. messages=current_messages
  118. )
  119. # 检查响应中是否有 tool_use
  120. content_blocks = []
  121. tool_use_blocks = []
  122. text_blocks = []
  123. for block in response.content:
  124. block_type = getattr(block, "type", None)
  125. if block_type == "tool_use":
  126. # 工具调用块
  127. block_dict = {
  128. "type": "tool_use",
  129. "id": getattr(block, "id", ""),
  130. "name": getattr(block, "name", ""),
  131. "input": getattr(block, "input", {})
  132. }
  133. content_blocks.append(block_dict)
  134. tool_use_blocks.append(block_dict)
  135. else:
  136. # 文本块
  137. text_content = getattr(block, "text", "")
  138. if text_content:
  139. text_blocks.append({
  140. "type": "text",
  141. "text": text_content
  142. })
  143. content_blocks.append({
  144. "type": "text",
  145. "text": text_content
  146. })
  147. response_text += text_content
  148. # 如果没有工具调用,返回结果
  149. if not tool_use_blocks:
  150. return {
  151. "response": response_text,
  152. "messages": current_messages,
  153. "tool_calls": tool_calls_made
  154. }
  155. # 处理工具调用
  156. tool_results = await self.tool_handler.process_tool_use_blocks(
  157. tool_use_blocks,
  158. self._tool_to_server_map
  159. )
  160. # 记录工具调用
  161. for tr in tool_results:
  162. tool_calls_made.append({
  163. "tool": tr.get("tool_name"),
  164. "result": tr.get("result", {})
  165. })
  166. # 构建工具结果消息
  167. tool_result_message = ToolCallHandler.create_tool_result_message(
  168. tool_results
  169. )
  170. # 添加到消息历史
  171. current_messages.append({
  172. "role": "assistant",
  173. "content": content_blocks
  174. })
  175. current_messages.append(tool_result_message)
  176. # 达到最大轮数
  177. return {
  178. "response": response_text,
  179. "messages": current_messages,
  180. "tool_calls": tool_calls_made,
  181. "warning": "达到最大对话轮数"
  182. }
  183. @staticmethod
  184. def format_history_for_claude(history: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
  185. """
  186. 格式化对话历史为 Claude API 格式
  187. Args:
  188. history: 原始对话历史
  189. Returns:
  190. Claude API 格式的消息列表
  191. """
  192. formatted = []
  193. for msg in history:
  194. role = msg.get("role")
  195. content = msg.get("content")
  196. if role == "user":
  197. if isinstance(content, str):
  198. formatted.append({"role": "user", "content": content})
  199. elif isinstance(content, list):
  200. formatted.append({"role": "user", "content": content})
  201. elif role == "assistant":
  202. if isinstance(content, str):
  203. formatted.append({"role": "assistant", "content": content})
  204. elif isinstance(content, list):
  205. formatted.append({"role": "assistant", "content": content})
  206. return formatted