Commit 9d4f1051 by sunqi02

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

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