Commit bee95282 by sunqi02

消息发送接入机器人服务

1 parent 6d7282f9
import logging import logging
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from typing import Optional, List from typing import Dict, Optional, List
from app.service.agent_hub import AgentHub from app.service.agent_hub import AgentHub
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
...@@ -25,7 +25,7 @@ class PositionInfo(BaseModel): ...@@ -25,7 +25,7 @@ class PositionInfo(BaseModel):
class AgentInfo(BaseModel): class AgentInfo(BaseModel):
agent_id: int = Field(..., description="Agent ID,对应 agent.code") agent_id: int = Field(..., description="Agent ID,对应 agent.code")
agent_name: str = Field(..., description="Agent 名称") bot_code: str = Field(..., description="机器人账号,格式 channel:bot_id,用于发送消息")
class MessageInfo(BaseModel): class MessageInfo(BaseModel):
...@@ -84,21 +84,27 @@ async def chat( ...@@ -84,21 +84,27 @@ async def chat(
if request.group and request.group.group_contact_id: if request.group and request.group.group_contact_id:
room_id = request.group.group_contact_id room_id = request.group.group_contact_id
# 4. 提取 allowed_agent_codes:agent_id → 内部 agent code 映射 # 4. 提取 allowed_agent_codes 和 bot_code_mapping:agent_id → 内部 agent code 映射
allowed_agent_codes: Optional[list] = None allowed_agent_codes: Optional[list] = None
bot_code_mapping: Optional[Dict[str, str]] = None
if request.agents: if request.agents:
# 构建 agent.code → 内部名称(dict key)映射 # 构建 agent.code → 内部名称(dict key)映射
code_to_name = { code_to_name = {
cfg.code: name for name, cfg in agent_hub.agents.items() cfg.code: name for name, cfg in agent_hub.agents.items()
} }
allowed_agent_codes = [] allowed_agent_codes = []
bot_code_mapping = {}
for agent_info in request.agents: for agent_info in request.agents:
agent_code_str = str(agent_info.agent_id) agent_code_str = str(agent_info.agent_id)
internal_name = code_to_name.get(agent_code_str) internal_name = code_to_name.get(agent_code_str)
if internal_name and internal_name != "main": if internal_name:
allowed_agent_codes.append(internal_name) if internal_name != "main":
allowed_agent_codes.append(internal_name)
bot_code_mapping[internal_name] = agent_info.bot_code
if not allowed_agent_codes: if not allowed_agent_codes:
allowed_agent_codes = None # 无有效子 agent,走默认路由 allowed_agent_codes = None # 无有效子 agent,走默认路由
if not bot_code_mapping:
bot_code_mapping = None
# 5. 后台异步处理 # 5. 后台异步处理
background_tasks.add_task( background_tasks.add_task(
...@@ -110,6 +116,7 @@ async def chat( ...@@ -110,6 +116,7 @@ async def chat(
user_query=query, user_query=query,
file_url=file_url, file_url=file_url,
allowed_agent_codes=allowed_agent_codes, allowed_agent_codes=allowed_agent_codes,
bot_code_mapping=bot_code_mapping,
) )
return {"status": "ok", "session_id": request.session_id} return {"status": "ok", "session_id": request.session_id}
...@@ -123,6 +130,7 @@ async def _process_message_async( ...@@ -123,6 +130,7 @@ async def _process_message_async(
user_query: str, user_query: str,
file_url: Optional[str], file_url: Optional[str],
allowed_agent_codes: Optional[list], allowed_agent_codes: Optional[list],
bot_code_mapping: Optional[Dict[str, str]] = None,
): ):
"""后台执行 Agent 处理流程,异常不影响 HTTP 响应。""" """后台执行 Agent 处理流程,异常不影响 HTTP 响应。"""
try: try:
...@@ -133,6 +141,7 @@ async def _process_message_async( ...@@ -133,6 +141,7 @@ async def _process_message_async(
user_query=user_query, user_query=user_query,
file_url=file_url, file_url=file_url,
allowed_agent_codes=allowed_agent_codes, allowed_agent_codes=allowed_agent_codes,
bot_code_mapping=bot_code_mapping,
) )
except Exception: except Exception:
logger.exception( logger.exception(
......
...@@ -5,9 +5,9 @@ from app.hooks.base import Hook ...@@ -5,9 +5,9 @@ from app.hooks.base import Hook
class IMSender(Protocol): class IMSender(Protocol):
"""Protocol for IM service — implementation in Task 5""" """Protocol for IM service — matches 机器人对接说明 API"""
async def send_message( async def send_message(
self, account: str, content: str, room_id: str, mentioned_list: list[str] self, bot_code: str, content: str, contact_id: str, at_list: str = ""
) -> Dict[str, Any]: ) -> Dict[str, Any]:
... ...
...@@ -33,23 +33,27 @@ class PostReplyHook(Hook): ...@@ -33,23 +33,27 @@ class PostReplyHook(Hook):
response_content = context.get("response_content") response_content = context.get("response_content")
room_id = context.get("room_id") room_id = context.get("room_id")
mentioned_list = context.get("mentioned_list", []) mentioned_list = context.get("mentioned_list", [])
bot_code_mapping = context.get("bot_code_mapping", {})
if not agent_name or not response_content: if not agent_name or not response_content:
return None return None
bot_account = self.account_mapping.get(agent_name) # bot_code 优先从请求映射中取,兜底用静态配置
if not bot_account: bot_code = bot_code_mapping.get(agent_name) or self.account_mapping.get(agent_name)
if not bot_code:
return None return None
clean_content = self._strip_thinking_blocks(response_content) clean_content = self._strip_thinking_blocks(response_content)
if not clean_content: if not clean_content:
return None return None
at_list = ",".join(mentioned_list) if mentioned_list else ""
result = await self.im_service.send_message( result = await self.im_service.send_message(
account=bot_account, bot_code=bot_code,
content=clean_content, content=clean_content,
room_id=room_id, contact_id=room_id,
mentioned_list=mentioned_list at_list=at_list,
) )
return result return result
......
...@@ -207,6 +207,7 @@ class AgentHub: ...@@ -207,6 +207,7 @@ class AgentHub:
channel: str = "wechat_group", channel: str = "wechat_group",
file_url: Optional[str] = None, file_url: Optional[str] = None,
allowed_agent_codes: Optional[list] = None, allowed_agent_codes: Optional[list] = None,
bot_code_mapping: Optional[Dict[str, str]] = None,
) -> Dict[str, Any]: ) -> Dict[str, Any]:
""" """
Process a user message end-to-end. Process a user message end-to-end.
...@@ -316,7 +317,8 @@ class AgentHub: ...@@ -316,7 +317,8 @@ class AgentHub:
"agent_name": target_agent, "agent_name": target_agent,
"response_content": response_content, "response_content": response_content,
"room_id": room_id, "room_id": room_id,
"mentioned_list": [user_id] "mentioned_list": [user_id],
"bot_code_mapping": bot_code_mapping or {},
}) })
processing_time_ms = (time.time() - start_time) * 1000 processing_time_ms = (time.time() - start_time) * 1000
......
"""Console IM service — prints hook output instead of sending to real IM.""" """Console IM service — prints hook output instead of sending to real IM."""
import json import json
from typing import Dict, List, Any, Optional from typing import Dict, Any, Optional
class ConsoleIMService: class ConsoleIMService:
...@@ -11,17 +11,19 @@ class ConsoleIMService: ...@@ -11,17 +11,19 @@ class ConsoleIMService:
async def send_message( async def send_message(
self, self,
account: str, bot_code: str,
content: str, content: str,
room_id: str, contact_id: str,
mentioned_list: Optional[List[str]] = None, at_list: str = "",
) -> Dict[str, Any]: ) -> Dict[str, Any]:
payload = { payload = {
"account": account, "bot_code": bot_code,
"content": content, "content": content,
"room_id": room_id, "contact_id": contact_id,
"mentioned_list": mentioned_list or [], "msg_type": "text",
} }
if at_list:
payload["at_list"] = at_list
print("\n" + "=" * 50) print("\n" + "=" * 50)
print(" [Hook: post_reply] → 计划发送到 IM") print(" [Hook: post_reply] → 计划发送到 IM")
...@@ -29,7 +31,7 @@ class ConsoleIMService: ...@@ -29,7 +31,7 @@ class ConsoleIMService:
print(json.dumps(payload, ensure_ascii=False, indent=2)) print(json.dumps(payload, ensure_ascii=False, indent=2))
print("=" * 50 + "\n") print("=" * 50 + "\n")
return {"status": "printed", "account": account} return {"status": "printed", "bot_code": bot_code}
async def close(self): async def close(self):
pass pass
from typing import Dict, List, Any, Optional from typing import Dict, Any, Optional
import httpx import httpx
...@@ -8,7 +8,11 @@ class IMServiceError(Exception): ...@@ -8,7 +8,11 @@ class IMServiceError(Exception):
class IMService: class IMService:
"""Service for sending messages via IM (自建服务)""" """Service for sending messages via IM business API (机器人对接说明)
Calls: POST {base_url}/api/v1/business/messages/send
Auth: X-Api-Key header
"""
def __init__(self, base_url: str, api_key: Optional[str] = None): def __init__(self, base_url: str, api_key: Optional[str] = None):
self.base_url = base_url.rstrip("/") self.base_url = base_url.rstrip("/")
...@@ -23,25 +27,35 @@ class IMService: ...@@ -23,25 +27,35 @@ class IMService:
async def send_message( async def send_message(
self, self,
account: str, bot_code: str,
content: str, content: str,
room_id: str, contact_id: str,
mentioned_list: List[str] = None at_list: str = "",
) -> Dict[str, Any]: ) -> Dict[str, Any]:
"""Send a text message via IM business API.
Args:
bot_code: 机器人账号,格式 channel:bot_id (e.g. wt_ww:RBT001)
content: 消息正文
contact_id: 目标群/联系人 ID (c_contacts.contact_id)
at_list: @列表,逗号分隔成员昵称 (群聊有效)
"""
payload = { payload = {
"account": account, "contact_id": contact_id,
"content": content, "content": content,
"room_id": room_id, "bot_code": bot_code,
"mentioned_list": mentioned_list or [] "msg_type": "text",
} }
if at_list:
payload["at_list"] = at_list
headers = {"Content-Type": "application/json"} headers = {"Content-Type": "application/json"}
if self.api_key: if self.api_key:
headers["Authorization"] = f"Bearer {self.api_key}" headers["X-Api-Key"] = self.api_key
try: try:
response = await self.client.post( response = await self.client.post(
f"{self.base_url}/api/send_message", f"{self.base_url}/api/v1/business/messages/send",
json=payload, json=payload,
headers=headers headers=headers
) )
......
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
"position_name": "驻店销售岗" "position_name": "驻店销售岗"
}, },
"agents": [ "agents": [
{"agent_id": 101, "agent_name": "会议纪要 Agent"} {"agent_id": 101, "bot_code": "wt_ww:bot_meeting_001"}
], ],
"messages": [ "messages": [
{ {
......
...@@ -111,7 +111,7 @@ def _make_request( ...@@ -111,7 +111,7 @@ def _make_request(
"position_code": "store_sales", "position_code": "store_sales",
"position_name": "驻店销售岗", "position_name": "驻店销售岗",
}, },
"agents": agents or [{"agent_id": 101, "agent_name": "会议纪要 Agent"}], "agents": agents or [{"agent_id": 101, "bot_code": "wt_ww:bot_meeting_001"}],
"messages": [ "messages": [
{ {
"msg_id": "m1", "msg_id": "m1",
...@@ -249,7 +249,7 @@ class TestChatCompletionsAPI: ...@@ -249,7 +249,7 @@ class TestChatCompletionsAPI:
json=_make_request( json=_make_request(
session_id="sess_agent_filter", session_id="sess_agent_filter",
query="你好", query="你好",
agents=[{"agent_id": 101, "agent_name": "会议纪要 Agent"}], agents=[{"agent_id": 101, "bot_code": "wt_ww:bot_meeting_001"}],
), ),
) )
...@@ -400,6 +400,76 @@ class TestPostReplyHook: ...@@ -400,6 +400,76 @@ class TestPostReplyHook:
assert result is None assert result is None
mock_im.send_message.assert_not_called() mock_im.send_message.assert_not_called()
@pytest.mark.asyncio
async def test_uses_bot_code_from_request_mapping(self):
"""bot_code_mapping 优先于 account_mapping"""
from app.hooks.post_reply import PostReplyHook
mock_im = AsyncMock()
mock_im.send_message.return_value = {"code": 0}
hook = PostReplyHook(
im_service=mock_im, account_mapping={"main": "static_bot"}
)
await hook.execute({
"agent_name": "main",
"response_content": "回复",
"room_id": "room_001",
"mentioned_list": [],
"bot_code_mapping": {"main": "wt_ww:request_bot"},
})
mock_im.send_message.assert_called_once()
kwargs = mock_im.send_message.call_args[1]
assert kwargs["bot_code"] == "wt_ww:request_bot"
@pytest.mark.asyncio
async def test_falls_back_to_account_mapping(self):
"""bot_code_mapping 为空时,回退到 account_mapping"""
from app.hooks.post_reply import PostReplyHook
mock_im = AsyncMock()
mock_im.send_message.return_value = {"code": 0}
hook = PostReplyHook(
im_service=mock_im, account_mapping={"main": "static_bot"}
)
await hook.execute({
"agent_name": "main",
"response_content": "回复",
"room_id": "room_001",
})
kwargs = mock_im.send_message.call_args[1]
assert kwargs["bot_code"] == "static_bot"
@pytest.mark.asyncio
async def test_sends_with_new_param_names(self):
"""验证 IM 调用使用 bot_code / contact_id / at_list 参数"""
from app.hooks.post_reply import PostReplyHook
mock_im = AsyncMock()
mock_im.send_message.return_value = {"code": 0}
hook = PostReplyHook(
im_service=mock_im, account_mapping={"meeting": "wt_ww:bot_001"}
)
await hook.execute({
"agent_name": "meeting",
"response_content": "会议纪要已整理",
"room_id": "wr_xxxxx",
"mentioned_list": ["张三", "李四"],
})
kwargs = mock_im.send_message.call_args[1]
assert kwargs["bot_code"] == "wt_ww:bot_001"
assert kwargs["contact_id"] == "wr_xxxxx"
assert kwargs["content"] == "会议纪要已整理"
assert kwargs["at_list"] == "张三,李四"
# ═══════════════════════════════════════════════════════════════════ # ═══════════════════════════════════════════════════════════════════
# AgentHub 路由逻辑测试(直接调用 process_message) # AgentHub 路由逻辑测试(直接调用 process_message)
......
"""read_file tool unit tests — sandbox security, path normalization, truncation."""
import pytest
import tempfile
import shutil
from pathlib import Path
from unittest.mock import MagicMock, AsyncMock
from app.config.loader import ConfigLoader
from app.service.session_service import SessionService
from app.service.agent_hub import AgentHub
from agentscope.message._message_block import TextBlock
# ── Fixture: 创建使用临时目录的 AgentHub ─────────────────────────
@pytest.fixture
def sandbox_root(tmp_path):
"""Create a temporary project root with test files."""
# Create app/ subdirectory so AgentHub path resolution works
app_dir = tmp_path / "app"
app_dir.mkdir()
# Create test files
(tmp_path / "config.json").write_text('{"key": "value"}', encoding="utf-8")
(tmp_path / "skills").mkdir()
(tmp_path / "skills" / "SKILL.md").write_text("# My Skill", encoding="utf-8")
# Create a large file (>10000 chars)
(tmp_path / "large.txt").write_text("A" * 15000, encoding="utf-8")
# Create a nested file
(tmp_path / "a" / "b").mkdir(parents=True)
(tmp_path / "a" / "b" / "deep.txt").write_text("deep content", encoding="utf-8")
return tmp_path
@pytest.fixture
def hub_with_sandbox(sandbox_root, db_session):
"""Create an AgentHub whose read_file tool is sandboxed to tmp_path."""
session_service = SessionService(db_session)
im_service = MagicMock()
im_service.send_message = AsyncMock(return_value={"code": 200})
hub = AgentHub(
config_loader=ConfigLoader(),
session_service=session_service,
im_service=im_service,
)
# Override the read_file tool with one rooted at sandbox_root
# by creating a new closure with the test root
from agentscope.tool import Toolkit
read_file_func = _make_read_file_with_root(sandbox_root)
# Replace in master toolkit and all agent toolkits
hub.toolkit.register_tool_function(
read_file_func,
func_name="read_file",
group_name="basic",
namesake_strategy="override",
)
for agent_tk in hub.agent_toolkits.values():
agent_tk.register_tool_function(
read_file_func,
func_name="read_file",
group_name="basic",
namesake_strategy="override",
)
return hub
def _make_read_file_with_root(root_dir: Path):
"""Create a read_file closure with a custom root directory."""
root_dir = root_dir.resolve()
async def read_file(file_path: str):
from agentscope.tool._response import ToolResponse
try:
normalized = file_path.replace("\\", "/")
if normalized.startswith("./"):
normalized = normalized[2:]
full_path = (root_dir / normalized).resolve()
if not str(full_path).startswith(str(root_dir)):
return ToolResponse(
content=[TextBlock(type="text", text="❌ Access denied: path escapes project root")]
)
if not full_path.exists():
return ToolResponse(
content=[TextBlock(type="text", text=f"❌ File not found: {file_path}")]
)
if not full_path.is_file():
return ToolResponse(
content=[TextBlock(type="text", text=f"❌ Not a file: {file_path}")]
)
content = full_path.read_text(encoding="utf-8")
if len(content) > 10000:
content = content[:10000] + "\n...[truncated]"
return ToolResponse(content=[TextBlock(type="text", text=content)])
except Exception as e:
return ToolResponse(
content=[TextBlock(type="text", text=f"❌ Error reading file: {str(e)}")]
)
return read_file
# ── Helper: 提取 ToolResponse 文本 ──
def _extract_text(resp):
"""Extract text from ToolResponse (content blocks may be dicts or TextBlock)."""
block = resp.content[0]
if isinstance(block, dict):
return block["text"]
return block.text
# ═══════════════════════════════════════════════════════════════════
# read_file 工具测试
# ═══════════════════════════════════════════════════════════════════
class TestReadFileTool:
async def _call_tool(self, toolkit, file_path: str):
"""Helper: call read_file via toolkit and return collected responses."""
gen = await toolkit.call_tool_function(
{"name": "read_file", "input": {"file_path": file_path}}
)
results = []
async for resp in gen:
results.append(resp)
return results
@pytest.mark.asyncio
async def test_read_existing_file(self, hub_with_sandbox):
"""成功读取项目根目录下的文件"""
results = await self._call_tool(hub_with_sandbox.toolkit, "config.json")
text = _extract_text(results[-1])
assert '"key": "value"' in text
@pytest.mark.asyncio
async def test_read_nested_file(self, hub_with_sandbox):
"""读取嵌套目录中的文件"""
results = await self._call_tool(hub_with_sandbox.toolkit, "a/b/deep.txt")
text = _extract_text(results[-1])
assert text == "deep content"
@pytest.mark.asyncio
async def test_read_skill_md(self, hub_with_sandbox):
"""读取 SKILL.md 文件"""
results = await self._call_tool(hub_with_sandbox.toolkit, "skills/SKILL.md")
text = _extract_text(results[-1])
assert "# My Skill" in text
@pytest.mark.asyncio
async def test_file_not_found(self, hub_with_sandbox):
"""文件不存在 → 返回错误信息"""
results = await self._call_tool(hub_with_sandbox.toolkit, "nonexistent.txt")
text = _extract_text(results[-1])
assert "❌" in text
assert "not found" in text.lower() or "Not found" in text
@pytest.mark.asyncio
async def test_not_a_file_directory(self, hub_with_sandbox):
"""路径是目录而非文件 → 返回错误"""
results = await self._call_tool(hub_with_sandbox.toolkit, "skills")
text = _extract_text(results[-1])
assert "❌" in text
assert "Not a file" in text or "not a file" in text.lower()
@pytest.mark.asyncio
async def test_path_traversal_blocked(self, hub_with_sandbox):
"""路径穿越攻击 ../../etc/passwd → 沙箱拒绝"""
results = await self._call_tool(hub_with_sandbox.toolkit, "../../etc/passwd")
text = _extract_text(results[-1])
assert "Access denied" in text or "escapes" in text.lower()
@pytest.mark.asyncio
async def test_path_traversal_with_dot_prefix(self, hub_with_sandbox):
"""./../../etc/passwd → 沙箱拒绝"""
results = await self._call_tool(hub_with_sandbox.toolkit, "./../../etc/passwd")
text = _extract_text(results[-1])
assert "Access denied" in text or "escapes" in text.lower()
@pytest.mark.asyncio
async def test_large_file_truncated(self, hub_with_sandbox):
"""超过 10000 字符的文件被截断"""
results = await self._call_tool(hub_with_sandbox.toolkit, "large.txt")
text = _extract_text(results[-1])
assert "[truncated]" in text
assert len(text) < 15000
@pytest.mark.asyncio
async def test_path_with_leading_dot_slash(self, hub_with_sandbox):
"""./config.json 路径前缀被正确规范化"""
results = await self._call_tool(hub_with_sandbox.toolkit, "./config.json")
text = _extract_text(results[-1])
assert '"key": "value"' in text
@pytest.mark.asyncio
async def test_path_with_backslash(self, hub_with_sandbox):
"""Windows 风格路径 a\\b\\deep.txt 被规范化"""
results = await self._call_tool(hub_with_sandbox.toolkit, "a\\b\\deep.txt")
text = _extract_text(results[-1])
assert text == "deep content"
@pytest.mark.asyncio
async def test_absolute_path_outside_sandbox_blocked(self, hub_with_sandbox):
"""绝对路径指向沙箱外 → 拒绝"""
results = await self._call_tool(hub_with_sandbox.toolkit, "/etc/hostname")
text = _extract_text(results[-1])
assert "Access denied" in text or "not found" in text.lower() or "Error" in text
class TestReadFileToolRegistration:
"""Verify read_file is properly registered in the toolkit."""
def test_read_file_in_toolkit_schemas(self):
"""read_file 出现在 toolkit JSON schema 中"""
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from app.infrastructure.database import Base
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
Base.metadata.create_all(bind=engine)
Session = sessionmaker(bind=engine)
db = Session()
im_service = MagicMock()
im_service.send_message = AsyncMock(return_value={"code": 200})
hub = AgentHub(
config_loader=ConfigLoader(),
session_service=SessionService(db),
im_service=im_service,
)
schemas = hub.toolkit.get_json_schemas()
names = [s["function"]["name"] for s in schemas]
assert "read_file" in names
# Verify schema has file_path parameter
read_file_schema = next(s for s in schemas if s["function"]["name"] == "read_file")
assert "file_path" in read_file_schema["function"]["parameters"]["properties"]
db.close()
def test_read_file_in_all_agent_toolkits(self):
"""read_file 注册到所有 agent 的专属 toolkit"""
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from app.infrastructure.database import Base
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
Base.metadata.create_all(bind=engine)
Session = sessionmaker(bind=engine)
db = Session()
im_service = MagicMock()
im_service.send_message = AsyncMock(return_value={"code": 200})
hub = AgentHub(
config_loader=ConfigLoader(),
session_service=SessionService(db),
im_service=im_service,
)
for agent_code, agent_tk in hub.agent_toolkits.items():
names = [s["function"]["name"] for s in agent_tk.get_json_schemas()]
assert "read_file" in names, f"read_file missing from {agent_code} toolkit"
db.close()
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!