Commit 9d4f1051 by sunqi02

保存对话的session_id,就是机器人服务的group_contact_id。

1 parent 251bebb2
import logging
import uuid
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
from pydantic import BaseModel, Field
from typing import Optional, List
......@@ -42,7 +41,6 @@ class MessageInfo(BaseModel):
class ChatRequest(BaseModel):
session_id: Optional[str] = Field(None, 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 列表")
......@@ -64,9 +62,12 @@ async def chat(
接收消息后立即返回 200,Agent 在后台异步处理。
处理结果通过 PostReplyHook 发送到 IM。
"""
# 0. session_id 缺失时自动生成
if not request.session_id:
request.session_id = f"sess_{uuid.uuid4().hex[:12]}"
# 0. session_id = group_contact_id
session_id = ""
if request.group and request.group.group_contact_id:
session_id = request.group.group_contact_id
if not session_id:
raise HTTPException(status_code=400, detail="group.group_contact_id 不能为空")
# 1. 提取 query:text 消息的 msg_content 用 \n 拼接
text_parts = []
......@@ -86,12 +87,7 @@ async def chat(
# 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 映射
# 3. 提取 allowed_agent_codes:agent_id → 内部 agent code 映射
allowed_agent_codes: Optional[list] = None
if request.agents:
# 构建 agent.code → 内部名称(dict key)映射
......@@ -107,19 +103,19 @@ async def chat(
if not allowed_agent_codes:
allowed_agent_codes = None # 无有效子 agent,走默认路由
# 5. 后台异步处理
# 4. 后台异步处理
background_tasks.add_task(
_process_message_async,
agent_hub=agent_hub,
session_id=request.session_id,
room_id=room_id,
session_id=session_id,
room_id=session_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}
return {"status": "ok", "session_id": session_id}
async def _process_message_async(
......
......@@ -4,13 +4,13 @@
"type": "openai_compatible",
"api_base": "https://dashscope.aliyuncs.com/compatible-mode/v1",
"model_name": "qwen3.6-plus",
"api_key": "sk-107dd26bca184e39bd1744af7d634488"
"api_key": "sk-5476217fc5a74a8a9b37f1d8779e935a"
},
"summary": {
"type": "openai_compatible",
"api_base": "https://dashscope.aliyuncs.com/compatible-mode/v1",
"model_name": "qwen3.6-plus",
"api_key": "sk-107dd26bca184e39bd1744af7d634488"
"api_key": "sk-5476217fc5a74a8a9b37f1d8779e935a"
}
},
"meeting_minutes": {
......@@ -18,13 +18,13 @@
"type": "dashscope_asr",
"api_base": "https://dashscope.aliyuncs.com/api/v1",
"model_name": "fun-asr",
"api_key": "sk-107dd26bca184e39bd1744af7d634488"
"api_key": "sk-5476217fc5a74a8a9b37f1d8779e935a"
},
"qwen3.6-plus": {
"type": "openai_compatible",
"api_base": "https://dashscope.aliyuncs.com/compatible-mode/v1",
"model_name": "qwen3.6-plus",
"api_key": "sk-107dd26bca184e39bd1744af7d634488"
"api_key": "sk-5476217fc5a74a8a9b37f1d8779e935a"
},
"oss": {
"access_key_id": "LTAI5tB2Q3EJFmaosMYN3uPc",
......
......@@ -60,16 +60,14 @@ client = TestClient(fastapi_app)
# ── Helper: 构造新格式请求体 ──
def _make_request(
session_id: str = "sess_test",
query: str = "你好",
agents: list = None,
group_contact_id: str = "room_001",
sender_id: str = "user_001",
extra_messages: list = None,
) -> dict:
"""构造符合新 API 格式的请求体。"""
"""构造符合新 API 格式的请求体。session_id = group_contact_id。"""
body = {
"session_id": session_id,
"group": {
"group_contact_id": group_contact_id,
"group_name": "测试群",
......@@ -113,12 +111,12 @@ def _get_session_messages(session_id: str) -> list:
class TestChatCompletionsAPI:
def test_returns_200_with_new_format(self):
"""新格式请求 → 立即返回 200 + session_id"""
"""新格式请求 → 立即返回 200 + session_id (=group_contact_id)"""
with patch.object(test_hub, 'model', new=_make_mock_model_reply("你好")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
resp = client.post(
"/api/v1/chat/completions",
json=_make_request(session_id="sess_api_001", query="你好"),
json=_make_request(group_contact_id="sess_api_001", query="你好"),
)
assert resp.status_code == 200
......@@ -127,20 +125,21 @@ class TestChatCompletionsAPI:
assert data["session_id"] == "sess_api_001"
def test_session_created_from_group_contact_id(self):
"""group_contact_id → room_id, 会话被创建"""
"""group_contact_id → session_id + room_id, 会话被创建"""
with patch.object(test_hub, 'model', new=_make_mock_model_reply("收到")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
resp = client.post(
"/api/v1/chat/completions",
json=_make_request(
session_id="sess_api_002",
query="测试",
group_contact_id="grp_room_99",
),
)
assert resp.status_code == 200
session_data = test_hub.session_service.store.get("sess_api_002")
data = resp.json()["data"]
assert data["session_id"] == "grp_room_99"
session_data = test_hub.session_service.store.get("grp_room_99")
assert session_data is not None
assert session_data["room_id"] == "grp_room_99"
......@@ -151,7 +150,7 @@ class TestChatCompletionsAPI:
resp = client.post(
"/api/v1/chat/completions",
json=_make_request(
session_id="sess_api_003",
group_contact_id="sess_api_003",
query="你好",
extra_messages=[
{
......@@ -180,7 +179,7 @@ class TestChatCompletionsAPI:
resp = client.post(
"/api/v1/chat/completions",
json={
"session_id": "sess_img_001",
"group": {"group_contact_id": "sess_img_001"},
"messages": [
{
"msg_id": "m1",
......@@ -212,7 +211,7 @@ class TestChatCompletionsAPI:
resp = client.post(
"/api/v1/chat/completions",
json=_make_request(
session_id="sess_agent_filter",
group_contact_id="sess_agent_filter",
query="你好",
agents=[{"agent_id": 101, "agent_name": "会议纪要 Agent"}],
),
......@@ -224,7 +223,7 @@ class TestChatCompletionsAPI:
"""缺少 messages 字段 → 400"""
resp = client.post(
"/api/v1/chat/completions",
json={"session_id": "sess_no_msg"},
json={"group": {"group_contact_id": "grp_no_msg"}},
)
assert resp.status_code == 400
......@@ -233,7 +232,7 @@ class TestChatCompletionsAPI:
resp = client.post(
"/api/v1/chat/completions",
json={
"session_id": "sess_empty_msg",
"group": {"group_contact_id": "grp_empty_msg"},
"messages": [],
},
)
......@@ -244,7 +243,7 @@ class TestChatCompletionsAPI:
resp = client.post(
"/api/v1/chat/completions",
json={
"session_id": "sess_img_only",
"group": {"group_contact_id": "grp_img_only"},
"messages": [
{
"msg_id": "m1",
......@@ -259,29 +258,24 @@ class TestChatCompletionsAPI:
)
assert resp.status_code == 400
def test_session_id_auto_generated(self):
"""不传 session_id → 自动生成 sess_ 前缀"""
with patch.object(test_hub, 'model', new=_make_mock_model_reply("你好")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
resp = client.post(
"/api/v1/chat/completions",
json={
"messages": [
{
"msg_id": "m1",
"msg_time": "2026-05-23T10:00:00Z",
"sender_id": "u1",
"msg_type": "text",
"msg_content": "你好",
"payload": {},
}
],
},
)
assert resp.status_code == 200
data = resp.json()["data"]
assert data["status"] == "ok"
assert data["session_id"].startswith("sess_")
def test_missing_group_contact_id_returns_400(self):
"""不传 group.group_contact_id → 400"""
resp = client.post(
"/api/v1/chat/completions",
json={
"messages": [
{
"msg_id": "m1",
"msg_time": "2026-05-23T10:00:00Z",
"sender_id": "u1",
"msg_type": "text",
"msg_content": "你好",
"payload": {},
}
],
},
)
assert resp.status_code == 400
def test_agents_without_name(self):
"""agents 不含 agent_name → 不报错"""
......@@ -290,7 +284,7 @@ class TestChatCompletionsAPI:
resp = client.post(
"/api/v1/chat/completions",
json={
"session_id": "sess_no_name",
"group": {"group_contact_id": "grp_no_name"},
"agents": [{"agent_id": 101}],
"messages": [
{
......@@ -313,7 +307,7 @@ class TestChatCompletionsAPI:
resp = client.post(
"/api/v1/chat/completions",
json={
"session_id": "sess_steward",
"group": {"group_contact_id": "grp_steward"},
"agents": [
{"agent_id": 101, "bot_id": "bot_001", "is_steward": True},
{"agent_id": 102, "bot_id": "bot_002", "is_steward": False},
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!