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

149 lines
4.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""对话与历史消息。"""
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, session_service
from api.response import ok
from application.chat_service import ChatService
from application.client_tool_gate import get_client_tool_gate
from application.session_service import SessionService
from domain.models import Actor
router = APIRouter(prefix="/sessions", tags=["chat"])
class ChatBody(BaseModel):
content: str = Field(min_length=1, max_length=20000)
# 发布场景:当前表单快照,注入 system(不再走 ui_get_publish_snapshot)
formSnapshot: dict | None = None
class ClientToolResultBody(BaseModel):
"""浏览器执行 ui_set_* 后的真实结果,唤醒挂起的工具轮。"""
toolCallId: str = Field(min_length=1, max_length=200)
ok: bool
message: str = Field(default="", max_length=2000)
@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 event in svc.stream_chat(
actor,
thread_id,
body.content,
form_snapshot=body.formSnapshot,
):
if event.kind == "token" and event.text:
yield {
"event": "token",
"data": json.dumps({"text": event.text}, ensure_ascii=False),
}
elif event.kind == "tool":
yield {
"event": "tool",
"data": json.dumps(
{
"phase": event.phase,
"name": event.name,
"label": event.label,
},
ensure_ascii=False,
),
}
elif event.kind == "client_tool":
yield {
"event": "client_tool",
"data": json.dumps(
{
"toolCallId": event.tool_call_id,
"name": event.name,
"args": event.args or {},
"label": event.label,
},
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,
)
@router.post("/{thread_id}/client-tool-results")
async def submit_client_tool_result(
thread_id: str,
body: ClientToolResultBody,
actor: Actor = Depends(current_actor),
sessions: SessionService = Depends(session_service),
):
"""前端工具回执。对上当前轮等待则 accepted=true;迟到或未知 id 仍 200,避免打断页面。"""
try:
await sessions.require_owned(actor, thread_id)
except LookupError as e:
raise HTTPException(status_code=404, detail=str(e)) from e
accepted = get_client_tool_gate().submit(
thread_id,
body.toolCallId.strip(),
body.ok,
body.message,
)
return ok({"accepted": accepted})