Commit a1db4827 by sunqi02

灾后重建

1 parent 392bbb3e
import logging
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
from pydantic import BaseModel, Field
from typing import Optional, List
from app.service.agent_hub import AgentHub
logger = logging.getLogger(__name__)
router = APIRouter()
# ── 新请求 Schema ──
class GroupInfo(BaseModel):
group_contact_id: Optional[str] = Field(None, description="群联系人ID")
group_name: Optional[str] = Field(None, description="群名称")
bot_code: Optional[str] = Field(None, description="机器人编码")
class PositionInfo(BaseModel):
position_id: Optional[int] = Field(None, description="岗位ID")
position_code: Optional[str] = Field(None, description="岗位编码")
position_name: Optional[str] = Field(None, description="岗位名称")
class AgentInfo(BaseModel):
agent_id: int = Field(..., description="Agent ID,对应 agent.code")
agent_name: str = Field(..., description="Agent 名称")
class MessageInfo(BaseModel):
msg_id: str = Field(..., description="消息ID")
msg_time: str = Field(..., description="消息时间")
sender_id: str = Field(..., description="发送者ID")
sender_name: Optional[str] = Field(None, description="发送者名称")
msg_type: str = Field(..., description="消息类型: text / image")
msg_content: str = Field(default="", description="消息内容(text 为文本,image 为图片 URL)")
payload: Optional[dict] = Field(default_factory=dict, description="扩展字段")
class ChatRequest(BaseModel):
session_id: str = Field(..., description="会话ID")
group: Optional[GroupInfo] = Field(default=None, description="群信息")
position: Optional[PositionInfo] = Field(default=None, description="岗位信息")
agents: List[AgentInfo] = Field(default_factory=list, description="可用 Agent 列表")
messages: List[MessageInfo] = Field(..., min_length=1, description="消息列表")
def get_agent_hub():
from app.main import agent_hub_instance
return agent_hub_instance
@router.post("/completions")
async def chat(
request: ChatRequest,
background_tasks: BackgroundTasks,
agent_hub: AgentHub = Depends(get_agent_hub),
):
"""
接收消息后立即返回 200,Agent 在后台异步处理。
处理结果通过 PostReplyHook 发送到 IM。
"""
# 1. 提取 query:text 消息的 msg_content 用 \n 拼接
text_parts = []
file_url: Optional[str] = None
for msg in request.messages:
if msg.msg_type == "text":
if msg.msg_content:
text_parts.append(msg.msg_content)
elif msg.msg_type == "image":
if msg.msg_content and file_url is None:
file_url = msg.msg_content # 取第一张图片 URL
query = "\n".join(text_parts)
if not query:
raise HTTPException(status_code=400, detail="messages 中没有文本消息")
# 2. 提取 user_id:取最后一条消息的 sender_id
user_id = request.messages[-1].sender_id
# 3. 提取 room_id
room_id = ""
if request.group and request.group.group_contact_id:
room_id = request.group.group_contact_id
# 4. 提取 allowed_agent_codes:agent_id → 内部 agent code 映射
allowed_agent_codes: Optional[list] = None
if request.agents:
# 构建 agent.code → 内部名称(dict key)映射
code_to_name = {
cfg.code: name for name, cfg in agent_hub.agents.items()
}
allowed_agent_codes = []
for agent_info in request.agents:
agent_code_str = str(agent_info.agent_id)
internal_name = code_to_name.get(agent_code_str)
if internal_name and internal_name != "main":
allowed_agent_codes.append(internal_name)
if not allowed_agent_codes:
allowed_agent_codes = None # 无有效子 agent,走默认路由
# 5. 后台异步处理
background_tasks.add_task(
_process_message_async,
agent_hub=agent_hub,
session_id=request.session_id,
room_id=room_id,
user_id=user_id,
user_query=query,
file_url=file_url,
allowed_agent_codes=allowed_agent_codes,
)
return {"status": "ok", "session_id": request.session_id}
async def _process_message_async(
agent_hub: AgentHub,
session_id: str,
room_id: str,
user_id: str,
user_query: str,
file_url: Optional[str],
allowed_agent_codes: Optional[list],
):
"""后台执行 Agent 处理流程,异常不影响 HTTP 响应。"""
try:
await agent_hub.process_message(
session_id=session_id,
room_id=room_id,
user_id=user_id,
user_query=user_query,
file_url=file_url,
allowed_agent_codes=allowed_agent_codes,
)
except Exception:
logger.exception(
"Agent 后台处理失败: session=%s user=%s query=%s",
session_id, user_id, user_query[:50],
)
from fastapi import APIRouter from fastapi import APIRouter
from app.api.v1.endpoints import agent_group_helper, agents, position_tags, skills, routing, analytics, qrcode_channel, official_site_tab, official_site_agent_display, official_site_upload, official_site_home, methodology, wecom_sync, wecom_jobs from app.api.v1.endpoints import agent_group_helper, agent_hub, agents, position_tags, skills, routing, analytics, qrcode_channel, official_site_tab, official_site_agent_display, official_site_upload, official_site_home, methodology, wecom_sync, wecom_jobs
api_router = APIRouter() api_router = APIRouter()
api_router.include_router(agent_group_helper.router, tags=["agent-group-helper"]) api_router.include_router(agent_group_helper.router, tags=["agent-group-helper"])
...@@ -16,3 +16,4 @@ api_router.include_router(official_site_home.router, tags=["official-site-home"] ...@@ -16,3 +16,4 @@ api_router.include_router(official_site_home.router, tags=["official-site-home"]
api_router.include_router(methodology.router, tags=["methodology"]) api_router.include_router(methodology.router, tags=["methodology"])
api_router.include_router(wecom_sync.router, tags=["wecom-sync"]) api_router.include_router(wecom_sync.router, tags=["wecom-sync"])
api_router.include_router(wecom_jobs.router, tags=["wecom-jobs"]) api_router.include_router(wecom_jobs.router, tags=["wecom-jobs"])
api_router.include_router(agent_hub.router, prefix="/api/v1/chat", tags=["chat"])
#!/bin/bash
# 模拟用户消息发送到 Agent 服务
# 用法: ./send_test.sh "你的问题"
# 例如: ./send_test.sh "帮我整理上周的会议纪要"
QUERY="${1:-你好,请问你能帮我什么?}"
API_URL="${API_URL:-http://localhost:8000/api/v1/chat/completions}"
echo "=========================================="
echo " 发送测试消息到 AgentHub"
echo "=========================================="
echo ""
echo "提问: ${QUERY}"
echo ""
# 用 jq 替换 messages[0].msg_content 字段
if command -v jq &> /dev/null; then
PAYLOAD=$(jq --arg q "${QUERY}" '.messages[0].msg_content = $q' test_request.json)
else
PAYLOAD=$(sed "s/{{QUERY}}/${QUERY}/g" test_request.json)
fi
echo "--- 请求体 ---"
echo "${PAYLOAD}" | python3 -m json.tool 2>/dev/null || echo "${PAYLOAD}"
echo ""
echo "--- 开始请求 ---"
echo "POST ${API_URL}"
echo ""
HTTP_CODE=$(curl -s -w "\n%{http_code}" -X POST "${API_URL}" \
-H "Content-Type: application/json" \
-d "${PAYLOAD}")
# 分离 body 和 status code
BODY=$(echo "${HTTP_CODE}" | sed '$d')
STATUS=$(echo "${HTTP_CODE}" | tail -n1)
echo "--- 响应 (HTTP ${STATUS}) ---"
echo "${BODY}" | python3 -m json.tool 2>/dev/null || echo "${BODY}"
echo ""
echo "=========================================="
echo " 完成"
echo "=========================================="
...@@ -2,7 +2,7 @@ import pytest ...@@ -2,7 +2,7 @@ import pytest
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from app.main import app from app.main import app
from app.model.agent import Agent, AgentPosition, AgentSkill, AgentUser from app.model.agent import Agent, AgentPosition, AgentSkill
from app.model.agent_group import QrcodeChannel from app.model.agent_group import QrcodeChannel
from app.model.position_tag import PositionTag from app.model.position_tag import PositionTag
from app.model.skill import Skill from app.model.skill import Skill
...@@ -17,7 +17,6 @@ def clean_db(): ...@@ -17,7 +17,6 @@ def clean_db():
db.query(Skill).delete() db.query(Skill).delete()
db.query(QrcodeChannel).delete() db.query(QrcodeChannel).delete()
db.query(PositionTag).delete() db.query(PositionTag).delete()
db.query(AgentUser).delete()
db.query(AgentSkill).delete() db.query(AgentSkill).delete()
db.query(AgentPosition).delete() db.query(AgentPosition).delete()
db.query(Agent).delete() db.query(Agent).delete()
......
...@@ -6,7 +6,7 @@ from pathlib import Path ...@@ -6,7 +6,7 @@ from pathlib import Path
from unittest.mock import MagicMock, AsyncMock from unittest.mock import MagicMock, AsyncMock
from app.config.loader import ConfigLoader from app.config.loader import ConfigLoader
from app.service.session_service import SessionService from app.service.active_session_service import ActiveSessionService
from app.service.agent_hub import AgentHub from app.service.agent_hub import AgentHub
from agentscope.message._message_block import TextBlock from agentscope.message._message_block import TextBlock
...@@ -37,9 +37,9 @@ def sandbox_root(tmp_path): ...@@ -37,9 +37,9 @@ def sandbox_root(tmp_path):
@pytest.fixture @pytest.fixture
def hub_with_sandbox(sandbox_root, db_session): def hub_with_sandbox(sandbox_root):
"""Create an AgentHub whose read_file tool is sandboxed to tmp_path.""" """Create an AgentHub whose read_file tool is sandboxed to tmp_path."""
session_service = SessionService(db_session) session_service = ActiveSessionService()
im_service = MagicMock() im_service = MagicMock()
im_service.send_message = AsyncMock(return_value={"code": 200}) im_service.send_message = AsyncMock(return_value={"code": 200})
...@@ -226,22 +226,12 @@ class TestReadFileToolRegistration: ...@@ -226,22 +226,12 @@ class TestReadFileToolRegistration:
def test_read_file_in_toolkit_schemas(self): def test_read_file_in_toolkit_schemas(self):
"""read_file 出现在 toolkit JSON schema 中""" """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 = MagicMock()
im_service.send_message = AsyncMock(return_value={"code": 200}) im_service.send_message = AsyncMock(return_value={"code": 200})
hub = AgentHub( hub = AgentHub(
config_loader=ConfigLoader(), config_loader=ConfigLoader(),
session_service=SessionService(db), session_service=ActiveSessionService(),
im_service=im_service, im_service=im_service,
) )
...@@ -253,31 +243,17 @@ class TestReadFileToolRegistration: ...@@ -253,31 +243,17 @@ class TestReadFileToolRegistration:
read_file_schema = next(s for s in schemas if s["function"]["name"] == "read_file") 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"] assert "file_path" in read_file_schema["function"]["parameters"]["properties"]
db.close()
def test_read_file_in_all_agent_toolkits(self): def test_read_file_in_all_agent_toolkits(self):
"""read_file 注册到所有 agent 的专属 toolkit""" """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 = MagicMock()
im_service.send_message = AsyncMock(return_value={"code": 200}) im_service.send_message = AsyncMock(return_value={"code": 200})
hub = AgentHub( hub = AgentHub(
config_loader=ConfigLoader(), config_loader=ConfigLoader(),
session_service=SessionService(db), session_service=ActiveSessionService(),
im_service=im_service, im_service=im_service,
) )
for agent_code, agent_tk in hub.agent_toolkits.items(): for agent_code, agent_tk in hub.agent_toolkits.items():
names = [s["function"]["name"] for s in agent_tk.get_json_schemas()] 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" 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!