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 httpx
from typing import Dict, List, Optional, Any
from app.config.loader import ConfigLoader
from app.config.settings import AgentConfig, SkillConfig, ModelConfig
from app.service.session_service import SessionService
from app.service.tool_manager import ToolManager
from app.hooks.post_reply import PostReplyHook
......@@ -44,6 +46,7 @@ class AgentHub:
account_mapping=agent_to_account
)
self.tool_manager = ToolManager()
self._model_client: Optional[httpx.AsyncClient] = None
@property
......@@ -179,10 +182,22 @@ class AgentHub:
else:
system_prompt = self._build_sub_agent_prompt(target_agent, context)
history_section = self._build_history_section(messages)
full_prompt = f"{system_prompt}\n\n## 对话历史\n{history_section}\n\n## 用户问题\n{user_query}"
# 构建 messages 列表(支持 ReAct tool calling)
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
self.session_service.add_message(
......@@ -220,34 +235,81 @@ class AgentHub:
"processing_time_ms": round(processing_time_ms, 2)
}
async def _call_model(self, prompt: str) -> str:
"""Call the shared model with the assembled prompt."""
async def _call_model(
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 = {
"Authorization": f"Bearer {self.main_model_config.api_key}",
"Content-Type": "application/json"
}
payload = {
"model": self.main_model_config.model_name,
"messages": [{"role": "user", "content": prompt}],
"temperature": 0.7
}
try:
response = await self.model_client.post(
f"{self.main_model_config.api_base}/chat/completions",
json=payload,
headers=headers
)
response.raise_for_status()
result = response.json()
return result["choices"][0]["message"]["content"]
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}")
current_messages = list(messages)
for iteration in range(max_iterations):
payload: dict[str, Any] = {
"model": self.main_model_config.model_name,
"messages": current_messages,
"temperature": 0.7
}
if tools:
payload["tools"] = tools
try:
response = await self.model_client.post(
f"{self.main_model_config.api_base}/chat/completions",
json=payload,
headers=headers
)
response.raise_for_status()
result = response.json()
choice = result["choices"][0]
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):
"""Clean up resources."""
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!