mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-25 03:49:19 +08:00
feat: 新增agent
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
"""对话与历史消息。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from sse_starlette.sse import EventSourceResponse
|
||||
|
||||
from app.deps import chat_service, current_actor
|
||||
from app.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,
|
||||
)
|
||||
Reference in New Issue
Block a user