Commit 9c4e1f28 by sunqi02

更新接口流程

https://github.com/mattpocock/skills
接口的内容和请求流程
1 parent 846ee6ff
from fastapi import APIRouter, Depends, HTTPException import logging
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from typing import Optional from typing import Optional, List
from sqlalchemy.orm import Session from app.service.agent_hub import AgentHub
from app.infrastructure.database import get_db
from app.schema.common import ApiResponse logger = logging.getLogger(__name__)
from app.service.agent_hub import AgentHub, AgentHubError
router = APIRouter() router = APIRouter()
class ChatRequest(BaseModel): # ── 新请求 Schema ──
session_id: str = Field(..., description="会话ID")
user_id: str = Field(..., description="用户ID") class GroupInfo(BaseModel):
room_id: str = Field(default="", description="群ID") group_contact_id: Optional[str] = Field(None, description="群联系人ID")
channel: str = Field(default="wechat_group", description="消息渠道") group_name: Optional[str] = Field(None, description="群名称")
query: str = Field(..., description="用户问题") bot_code: Optional[str] = Field(None, description="机器人编码")
mentioned_agent_code: Optional[str] = Field(None, description="@提及的Agent编码")
file_url: Optional[str] = Field(None, description="文件URL")
class PositionInfo(BaseModel):
position_id: Optional[int] = Field(None, description="岗位ID")
position_code: Optional[str] = Field(None, description="岗位编码") 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 ChatResponse(BaseModel):
session_id: str
response_agent_code: str
response_content: str
routing_reason: str
processing_time_ms: float
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="扩展字段")
def get_agent_hub(db: Session = Depends(get_db)):
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 from app.main import agent_hub_instance
return agent_hub_instance return agent_hub_instance
@router.post("/completions", response_model=ChatResponse) @router.post("/completions")
async def chat( async def chat(
request: ChatRequest, request: ChatRequest,
background_tasks: BackgroundTasks,
agent_hub: AgentHub = Depends(get_agent_hub), agent_hub: AgentHub = Depends(get_agent_hub),
db: Session = Depends(get_db),
): ):
try: """
# Resolve position_code -> allowed agent codes 接收消息后立即返回 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 allowed_agent_codes: Optional[list] = None
if request.position_code: if request.agents:
from app.model.position_tag import PositionTag # 构建 agent.code → 内部名称(dict key)映射
from app.model.agent import Agent, AgentPosition code_to_name = {
cfg.code: name for name, cfg in agent_hub.agents.items()
pos_tag = db.query(PositionTag).filter( }
PositionTag.code == request.position_code allowed_agent_codes = []
).first() for agent_info in request.agents:
agent_code_str = str(agent_info.agent_id)
if pos_tag: internal_name = code_to_name.get(agent_code_str)
agent_ids = [ if internal_name and internal_name != "main":
row.agent_id allowed_agent_codes.append(internal_name)
for row in db.query(AgentPosition.agent_id).filter( if not allowed_agent_codes:
AgentPosition.position_id == pos_tag.id allowed_agent_codes = None # 无有效子 agent,走默认路由
).all()
] # 5. 后台异步处理
if agent_ids: background_tasks.add_task(
agents = db.query(Agent.code).filter( _process_message_async,
Agent.id.in_(agent_ids), agent_hub=agent_hub,
Agent.is_deleted == False,
).all()
allowed_agent_codes = [a.code for a in agents]
result = await agent_hub.process_message(
session_id=request.session_id, session_id=request.session_id,
room_id=request.room_id, room_id=room_id,
user_id=request.user_id, user_id=user_id,
user_query=request.query, user_query=query,
mentioned_agent_code=request.mentioned_agent_code, file_url=file_url,
channel=request.channel,
file_url=request.file_url,
allowed_agent_codes=allowed_agent_codes, allowed_agent_codes=allowed_agent_codes,
) )
return ChatResponse(**result)
except AgentHubError as e: return {"status": "ok", "session_id": request.session_id}
raise HTTPException(status_code=502, detail=str(e))
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e)) 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],
)
...@@ -287,7 +287,12 @@ class AgentHub: ...@@ -287,7 +287,12 @@ class AgentHub:
) )
# Run ReAct loop via framework # Run ReAct loop via framework
user_msg = Msg("user", user_query, "user") # If there's an image URL, append it to the query so the agent can see it
effective_query = user_query
if file_url:
effective_query = f"{user_query}\n\n[用户发送了一张图片: {file_url}]"
user_msg = Msg("user", effective_query, "user")
response_msg = await agent.reply(user_msg) response_msg = await agent.reply(user_msg)
response_content = response_msg.get_text_content() response_content = response_msg.get_text_content()
......
...@@ -2,14 +2,14 @@ ...@@ -2,14 +2,14 @@
"agents": { "agents": {
"main": { "main": {
"name": "主 Agent", "name": "主 Agent",
"code": "main", "code": "100",
"role": "coordinator", "role": "coordinator",
"prompt_template": "你是{company}的智能助手,负责协调各个岗位Agent协作回答用户问题。\n\n## 核心规则(必须遵守)\n\n1. 当用户问题属于某个子Agent的职责范围时,你**必须调用 call_sub_agent 工具**来委托处理,**严禁**自己编造处理结果或口头描述\"正在处理\"。\n2. 收到子Agent返回结果后,直接整合回复用户,不要再次调用同一个子Agent。\n3. 只有当问题明确不属于任何子Agent职责时,才可以直接回答。\n\n## 可用子Agent(通过 call_sub_agent 调用)\n\n{duties}\n\n## 工具使用提醒\n\n你有一个 call_sub_agent(agent_code, instruction) 工具。用户不会看到你的内部思考过程,请直接用行动代替描述。", "prompt_template": "你是{company}的智能助手,负责协调各个岗位Agent协作回答用户问题。\n\n## 核心规则(必须遵守)\n\n1. 当用户问题属于某个子Agent的职责范围时,你**必须调用 call_sub_agent 工具**来委托处理,**严禁**自己编造处理结果或口头描述\"正在处理\"。\n2. 收到子Agent返回结果后,直接整合回复用户,不要再次调用同一个子Agent。\n3. 只有当问题明确不属于任何子Agent职责时,才可以直接回答。\n\n## 可用子Agent(通过 call_sub_agent 调用)\n\n{duties}\n\n## 工具使用提醒\n\n你有一个 call_sub_agent(agent_code, instruction) 工具。用户不会看到你的内部思考过程,请直接用行动代替描述。",
"skills": [] "skills": []
}, },
"meeting": { "meeting": {
"name": "会议纪要 Agent", "name": "会议纪要 Agent",
"code": "meeting", "code": "101",
"role": "会议纪要助手", "role": "会议纪要助手",
"prompt_template": "你是{company}的会议纪要助手,职责包括:{duties}。请根据用户的需求,帮助处理会议纪要相关的任务。", "prompt_template": "你是{company}的会议纪要助手,职责包括:{duties}。请根据用户的需求,帮助处理会议纪要相关的任务。",
"skills": ["meeting_minutes"] "skills": ["meeting_minutes"]
......
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
# 模拟用户消息发送到 Agent 服务 # 模拟用户消息发送到 Agent 服务
# 用法: ./send_test.sh "你的问题" # 用法: ./send_test.sh "你的问题"
# 例如: ./send_test.sh "帮我整理上周的会议纪要" # 例如: ./send_test.sh "帮我整理上周的会议纪要"
# ./send_test.sh "@meeting 帮我整理会议纪要"
QUERY="${1:-你好,请问你能帮我什么?}" QUERY="${1:-你好,请问你能帮我什么?}"
API_URL="${API_URL:-http://localhost:8000/api/v1/chat/completions}" API_URL="${API_URL:-http://localhost:8000/api/v1/chat/completions}"
...@@ -14,9 +13,9 @@ echo "" ...@@ -14,9 +13,9 @@ echo ""
echo "提问: ${QUERY}" echo "提问: ${QUERY}"
echo "" echo ""
# 用 jq 替换 query 字段(如果安装了 jq),否则用 sed # 用 jq 替换 messages[0].msg_content 字段
if command -v jq &> /dev/null; then if command -v jq &> /dev/null; then
PAYLOAD=$(jq --arg q "${QUERY}" '.query = $q' test_request.json) PAYLOAD=$(jq --arg q "${QUERY}" '.messages[0].msg_content = $q' test_request.json)
else else
PAYLOAD=$(sed "s/{{QUERY}}/${QUERY}/g" test_request.json) PAYLOAD=$(sed "s/{{QUERY}}/${QUERY}/g" test_request.json)
fi fi
......
{ {
"session_id": "test_sess_001", "session_id": "test_sess_001",
"user_id": "test_user_001", "group": {
"room_id": "test_room_001", "group_contact_id": "test_room_001",
"channel": "wechat_group", "group_name": "测试群",
"query": "{{QUERY}}", "bot_code": "test_bot"
"mentioned_agent_code": null, },
"file_url": null, "position": {
"position_code": "conference_assistant" "position_id": 1,
"position_code": "store_sales",
"position_name": "驻店销售岗"
},
"agents": [
{"agent_id": 101, "agent_name": "会议纪要 Agent"}
],
"messages": [
{
"msg_id": "m1",
"msg_time": "2026-05-23T10:00:00Z",
"sender_id": "test_user_001",
"sender_name": "测试用户",
"msg_type": "text",
"msg_content": "{{QUERY}}",
"payload": {}
}
]
} }
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!