Commit d11f16eb by sunqi02

feat(layer1): replace httpx with OpenAIChatModel + OpenAIChatFormatter

Replace the raw httpx HTTP client with AgentScope's native
OpenAIChatModel and OpenAIChatFormatter classes for model calls.

Changes:
- Remove `import httpx` and `_model_client` property
- Add `self.model` (OpenAIChatModel) and `self.formatter` (OpenAIChatFormatter)
- Add `_dict_to_msg()` helper to convert API dicts to Msg objects for the formatter
- Rewrite `_call_model()` to use AgentScope model + formatter pipeline
- Parse ChatResponse content blocks (TextBlock/ToolUseBlock) directly
- `close()` becomes a no-op since AgentScope manages its own client lifecycle

Verification: All 22 tests pass (14 agent_hub + 8 session_service_internal)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
1 parent 8e1e87fa
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
from agentscope.model import OpenAIChatModel
from agentscope.formatter import OpenAIChatFormatter
from agentscope.message import Msg
from agentscope.message._message_block import TextBlock, ToolUseBlock, ToolResultBlock
class AgentHubError(Exception):
......@@ -47,13 +49,13 @@ class AgentHub:
)
self.tool_manager = ToolManager()
self._model_client: Optional[httpx.AsyncClient] = None
@property
def model_client(self) -> httpx.AsyncClient:
if self._model_client is None:
self._model_client = httpx.AsyncClient(timeout=60.0)
return self._model_client
self.model = OpenAIChatModel(
model_name=self.main_model_config.model_name,
api_key=self.main_model_config.api_key,
stream=False,
client_kwargs={"base_url": self.main_model_config.api_base}
)
self.formatter = OpenAIChatFormatter()
def _build_main_prompt(self, context: Dict[str, Any]) -> str:
"""
......@@ -113,6 +115,48 @@ class AgentHub:
return prompt
def _dict_to_msg(self, m: dict) -> Msg:
"""Convert a chat completion API dict to a Msg object for the formatter."""
role = m.get("role", "user")
content = m.get("content", "")
# Handle assistant messages with tool_calls
tool_calls = m.get("tool_calls")
if role == "assistant" and tool_calls:
blocks = []
if content:
blocks.append(TextBlock(type="text", text=content))
for tc in tool_calls:
func = tc["function"]
try:
args = json.loads(func["arguments"])
except (json.JSONDecodeError, KeyError):
args = {}
blocks.append(ToolUseBlock(
type="tool_use",
id=tc["id"],
name=func["name"],
input=args,
))
return Msg(name=role, role=role, content=blocks)
# Handle tool result messages (role="tool")
if role == "tool":
return Msg(
name="tool",
role="user", # Carrier role; formatter emits correct role="tool" for ToolResultBlock
content=[
ToolResultBlock(
type="tool_result",
id=m.get("tool_call_id", ""),
name="",
output=m.get("content", ""),
)
],
)
return Msg(name=role, role=role, content=content)
def _build_history_section(self, messages: List) -> str:
"""Build conversation history section from recent messages."""
if not messages:
......@@ -243,62 +287,57 @@ class AgentHub:
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"
}
"""Call the model via AgentScope OpenAIChatModel with ReAct tool-calling loop."""
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
# Convert dicts to Msg objects, then format for the API
msgs = [self._dict_to_msg(m) for m in current_messages]
formatted = await self.formatter.format(msgs)
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:
if tools:
response = await self.model(formatted, tools=tools)
else:
response = await self.model(formatted)
except Exception 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", "")
# Parse ChatResponse content blocks
text_parts = []
tool_use_blocks = []
for block in (response.content or []):
if block.get("type") == "text":
text_parts.append(block.get("text", ""))
elif block.get("type") == "tool_use":
tool_use_blocks.append(block)
text_content = "\n".join(text_parts)
# 有 tool_calls → 执行工具并注入结果
if not tool_use_blocks:
return text_content
# Tool calling: append assistant message with tool_calls
current_messages.append({
"role": "assistant",
"content": msg.get("content"),
"tool_calls": msg["tool_calls"]
"content": text_content,
"tool_calls": [
{
"id": tb["id"],
"type": "function",
"function": {
"name": tb["name"],
"arguments": json.dumps(tb["input"], ensure_ascii=False),
}
}
for tb in tool_use_blocks
],
})
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 = {}
# Execute tools and append results
for tb in tool_use_blocks:
tool_name = tb["name"]
tool_input = tb.get("input", {})
tool_result = self.tool_manager.call_tool({
"name": tool_name,
......@@ -307,14 +346,12 @@ class AgentHub:
current_messages.append({
"role": "tool",
"tool_call_id": tc["id"],
"tool_call_id": tb["id"],
"content": json.dumps(tool_result, ensure_ascii=False),
})
raise AgentHubError("ReAct循环超过最大次数(10)")
async def close(self):
"""Clean up resources."""
if self._model_client is not None:
await self._model_client.aclose()
self._model_client = None
"""Clean up resources (no-op with AgentScope)."""
pass
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!