Commit db93fecb by sunqi02

feat: integrate ToolManager with ReAct loop into AgentHub._call_model

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
1 parent 646dac80
import json
import time import time
import httpx import httpx
from typing import Dict, List, Optional, Any from typing import Dict, List, Optional, Any
from app.config.loader import ConfigLoader from app.config.loader import ConfigLoader
from app.config.settings import AgentConfig, SkillConfig, ModelConfig from app.config.settings import AgentConfig, SkillConfig, ModelConfig
from app.service.session_service import SessionService from app.service.session_service import SessionService
from app.service.tool_manager import ToolManager
from app.hooks.post_reply import PostReplyHook from app.hooks.post_reply import PostReplyHook
...@@ -44,6 +46,7 @@ class AgentHub: ...@@ -44,6 +46,7 @@ class AgentHub:
account_mapping=agent_to_account account_mapping=agent_to_account
) )
self.tool_manager = ToolManager()
self._model_client: Optional[httpx.AsyncClient] = None self._model_client: Optional[httpx.AsyncClient] = None
@property @property
...@@ -179,10 +182,22 @@ class AgentHub: ...@@ -179,10 +182,22 @@ class AgentHub:
else: else:
system_prompt = self._build_sub_agent_prompt(target_agent, context) system_prompt = self._build_sub_agent_prompt(target_agent, context)
history_section = self._build_history_section(messages) # 构建 messages 列表(支持 ReAct tool calling)
full_prompt = f"{system_prompt}\n\n## 对话历史\n{history_section}\n\n## 用户问题\n{user_query}" api_messages: list[dict[str, Any]] = [{"role": "system", "content": system_prompt}]
response_content = await self._call_model(full_prompt) # 历史对话作为独立消息
recent = messages[-10:]
for msg in recent:
role = "user" if msg.role == "user" else "assistant"
api_messages.append({"role": role, "content": msg.content or ""})
api_messages.append({"role": "user", "content": user_query})
tool_schemas = self.tool_manager.get_tool_schemas()
response_content = await self._call_model(
api_messages,
tools=tool_schemas if tool_schemas else None,
)
# Store messages # Store messages
self.session_service.add_message( self.session_service.add_message(
...@@ -220,34 +235,81 @@ class AgentHub: ...@@ -220,34 +235,81 @@ class AgentHub:
"processing_time_ms": round(processing_time_ms, 2) "processing_time_ms": round(processing_time_ms, 2)
} }
async def _call_model(self, prompt: str) -> str: async def _call_model(
"""Call the shared model with the assembled prompt.""" self,
messages: list[dict],
tools: Optional[list[dict]] = None,
max_iterations: int = 10,
) -> str:
"""
Call the model with messages and optional tools.
If tools are provided and the model returns tool_calls,
execute them via ToolManager and loop (ReAct) up to max_iterations.
"""
headers = { headers = {
"Authorization": f"Bearer {self.main_model_config.api_key}", "Authorization": f"Bearer {self.main_model_config.api_key}",
"Content-Type": "application/json" "Content-Type": "application/json"
} }
payload = { current_messages = list(messages)
"model": self.main_model_config.model_name,
"messages": [{"role": "user", "content": prompt}], for iteration in range(max_iterations):
"temperature": 0.7 payload: dict[str, Any] = {
} "model": self.main_model_config.model_name,
"messages": current_messages,
try: "temperature": 0.7
response = await self.model_client.post( }
f"{self.main_model_config.api_base}/chat/completions", if tools:
json=payload, payload["tools"] = tools
headers=headers
) try:
response.raise_for_status() response = await self.model_client.post(
result = response.json() f"{self.main_model_config.api_base}/chat/completions",
return result["choices"][0]["message"]["content"] json=payload,
except httpx.HTTPStatusError as e: headers=headers
raise AgentHubError(f"模型API返回错误: {e.response.status_code}") )
except httpx.RequestError as e: response.raise_for_status()
raise AgentHubError(f"模型API请求失败: {e}") result = response.json()
except (KeyError, IndexError) as e: choice = result["choices"][0]
raise AgentHubError(f"模型返回格式异常: {e}") msg = choice["message"]
except httpx.HTTPStatusError as e:
raise AgentHubError(f"模型API返回错误: {e.response.status_code}")
except httpx.RequestError as e:
raise AgentHubError(f"模型API请求失败: {e}")
except (KeyError, IndexError) as e:
raise AgentHubError(f"模型返回格式异常: {e}")
# 纯文本回复 → 直接返回
if not msg.get("tool_calls"):
return msg.get("content", "")
# 有 tool_calls → 执行工具并注入结果
current_messages.append({
"role": "assistant",
"content": msg.get("content"),
"tool_calls": msg["tool_calls"]
})
for tc in msg["tool_calls"]:
func_info = tc["function"]
tool_name = func_info["name"]
try:
tool_input = json.loads(func_info["arguments"])
except json.JSONDecodeError:
tool_input = {}
tool_result = self.tool_manager.call_tool({
"name": tool_name,
"input": tool_input,
})
current_messages.append({
"role": "tool",
"tool_call_id": tc["id"],
"content": json.dumps(tool_result, ensure_ascii=False),
})
raise AgentHubError("ReAct循环超过最大次数(10)")
async def close(self): async def close(self):
"""Clean up resources.""" """Clean up resources."""
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!