43 lines
1.6 KiB
Python
43 lines
1.6 KiB
Python
"""
|
||
POST /api/session/history — 存储历史对话上下文(由 java-mock 内部调用)
|
||
"""
|
||
from fastapi import APIRouter, Request
|
||
from fastapi.responses import JSONResponse
|
||
from pydantic import BaseModel, Field
|
||
|
||
from security.internal_auth import verify_internal_request
|
||
from services.session_store import save_room_history
|
||
|
||
router = APIRouter(tags=["会话历史"])
|
||
|
||
|
||
class HistoryMessage(BaseModel):
|
||
role: str = Field(..., description="消息角色:`user` 或 `assistant`")
|
||
content: str = Field(..., description="消息内容")
|
||
|
||
|
||
class SetHistoryRequest(BaseModel):
|
||
room_id: str = Field(..., description="RTC 房间 ID(与 getScenes 返回的 rtc.RoomId 一致)")
|
||
messages: list[HistoryMessage] = Field(..., description="历史消息列表")
|
||
|
||
|
||
@router.post(
|
||
"/api/session/history",
|
||
summary="写入房间历史上下文",
|
||
description=(
|
||
"在 `StartVoiceChat` 之前调用,将历史对话注入该房间的上下文缓存。\n\n"
|
||
"后续 `/api/chat_callback` 调用时会自动将缓存的历史 prepend 到每次 LLM 请求的 messages 前,"
|
||
"实现多轮对话的上下文延续。\n\n"
|
||
"**鉴权**:需附加内部服务签名 Header(由 java-mock 自动添加)。"
|
||
),
|
||
responses={
|
||
401: {"description": "内部签名校验失败"},
|
||
},
|
||
)
|
||
async def set_history(request: Request, body: SetHistoryRequest):
|
||
if not verify_internal_request(request.headers):
|
||
return JSONResponse({"code": 401, "message": "鉴权失败"}, status_code=401)
|
||
|
||
save_room_history(body.room_id, [m.model_dump() for m in body.messages])
|
||
return JSONResponse({"code": 200})
|