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 json
import time import time
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.service.session_service import SessionService from app.service.session_service import SessionService
from app.service.tool_manager import ToolManager from app.service.tool_manager import ToolManager
from app.hooks.post_reply import PostReplyHook 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): class AgentHubError(Exception):
...@@ -47,13 +49,13 @@ class AgentHub: ...@@ -47,13 +49,13 @@ class AgentHub:
) )
self.tool_manager = ToolManager() self.tool_manager = ToolManager()
self._model_client: Optional[httpx.AsyncClient] = None self.model = OpenAIChatModel(
model_name=self.main_model_config.model_name,
@property api_key=self.main_model_config.api_key,
def model_client(self) -> httpx.AsyncClient: stream=False,
if self._model_client is None: client_kwargs={"base_url": self.main_model_config.api_base}
self._model_client = httpx.AsyncClient(timeout=60.0) )
return self._model_client self.formatter = OpenAIChatFormatter()
def _build_main_prompt(self, context: Dict[str, Any]) -> str: def _build_main_prompt(self, context: Dict[str, Any]) -> str:
""" """
...@@ -113,6 +115,48 @@ class AgentHub: ...@@ -113,6 +115,48 @@ class AgentHub:
return prompt 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: def _build_history_section(self, messages: List) -> str:
"""Build conversation history section from recent messages.""" """Build conversation history section from recent messages."""
if not messages: if not messages:
...@@ -243,62 +287,57 @@ class AgentHub: ...@@ -243,62 +287,57 @@ class AgentHub:
tools: Optional[list[dict]] = None, tools: Optional[list[dict]] = None,
max_iterations: int = 10, max_iterations: int = 10,
) -> str: ) -> str:
""" """Call the model via AgentScope OpenAIChatModel with ReAct tool-calling loop."""
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"
}
current_messages = list(messages) current_messages = list(messages)
for iteration in range(max_iterations): for iteration in range(max_iterations):
payload: dict[str, Any] = { # Convert dicts to Msg objects, then format for the API
"model": self.main_model_config.model_name, msgs = [self._dict_to_msg(m) for m in current_messages]
"messages": current_messages, formatted = await self.formatter.format(msgs)
"temperature": 0.7
}
if tools:
payload["tools"] = tools
try: try:
response = await self.model_client.post( if tools:
f"{self.main_model_config.api_base}/chat/completions", response = await self.model(formatted, tools=tools)
json=payload, else:
headers=headers response = await self.model(formatted)
) except Exception as e:
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}") raise AgentHubError(f"模型API请求失败: {e}")
except (KeyError, IndexError) as e:
raise AgentHubError(f"模型返回格式异常: {e}")
# 纯文本回复 → 直接返回 # Parse ChatResponse content blocks
if not msg.get("tool_calls"): text_parts = []
return msg.get("content", "") 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({ current_messages.append({
"role": "assistant", "role": "assistant",
"content": msg.get("content"), "content": text_content,
"tool_calls": msg["tool_calls"] "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"]: # Execute tools and append results
func_info = tc["function"] for tb in tool_use_blocks:
tool_name = func_info["name"] tool_name = tb["name"]
try: tool_input = tb.get("input", {})
tool_input = json.loads(func_info["arguments"])
except json.JSONDecodeError:
tool_input = {}
tool_result = self.tool_manager.call_tool({ tool_result = self.tool_manager.call_tool({
"name": tool_name, "name": tool_name,
...@@ -307,14 +346,12 @@ class AgentHub: ...@@ -307,14 +346,12 @@ class AgentHub:
current_messages.append({ current_messages.append({
"role": "tool", "role": "tool",
"tool_call_id": tc["id"], "tool_call_id": tb["id"],
"content": json.dumps(tool_result, ensure_ascii=False), "content": json.dumps(tool_result, ensure_ascii=False),
}) })
raise AgentHubError("ReAct循环超过最大次数(10)") raise AgentHubError("ReAct循环超过最大次数(10)")
async def close(self): async def close(self):
"""Clean up resources.""" """Clean up resources (no-op with AgentScope)."""
if self._model_client is not None: pass
await self._model_client.aclose()
self._model_client = None
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!