Files
ecom-dmb/apps/agent/api/routers/chat.py
T

82 lines
2.3 KiB
Python

"""对话与历史消息。"""
from __future__ import annotations
import json
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field
from sse_starlette.sse import EventSourceResponse
from api.deps import chat_service, current_actor
from api.response import ok
from application.chat_service import ChatService
from domain.models import Actor
router = APIRouter(prefix="/sessions", tags=["chat"])
class ChatBody(BaseModel):
content: str = Field(min_length=1, max_length=20000)
@router.get("/{thread_id}/messages")
async def list_messages(
thread_id: str,
actor: Actor = Depends(current_actor),
svc: ChatService = Depends(chat_service),
):
try:
rows = await svc.list_messages(actor, thread_id)
except LookupError as e:
raise HTTPException(status_code=404, detail=str(e)) from e
return ok(
{
"items": [
{
"id": m.id,
"seq": m.seq,
"role": m.role.value,
"content": m.content,
"createdAt": m.created_at.isoformat() + "Z",
}
for m in rows
]
}
)
@router.post("/{thread_id}/chat")
async def chat_stream(
thread_id: str,
body: ChatBody,
actor: Actor = Depends(current_actor),
svc: ChatService = Depends(chat_service),
):
"""SSE 流式,不走 ApiResponse 包装。"""
async def gen():
try:
async for chunk in svc.stream_chat(actor, thread_id, body.content):
yield {"event": "token", "data": json.dumps({"text": chunk}, ensure_ascii=False)}
yield {"event": "done", "data": "{}"}
except LookupError as e:
yield {"event": "error", "data": json.dumps({"message": str(e)}, ensure_ascii=False)}
except ValueError as e:
yield {"event": "error", "data": json.dumps({"message": str(e)}, ensure_ascii=False)}
except Exception as e:
yield {
"event": "error",
"data": json.dumps({"message": str(e)}, ensure_ascii=False),
}
return EventSourceResponse(
gen(),
headers={
"Cache-Control": "no-cache, no-transform",
"X-Accel-Buffering": "no",
"Connection": "keep-alive",
},
ping=15,
)