conversation_manager.py 7.4 KB

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