refactor: 重构聊天模块支持 SSE 断线重连及用户上下文隔离
This commit is contained in:
@@ -48,6 +48,7 @@ from v1.users.dependencies import get_current_user
|
||||
router = APIRouter(prefix="/agent", tags=["agent"])
|
||||
logger = get_logger("v1.agent.router")
|
||||
_LAST_EVENT_ID_RE = re.compile(r"^\d+-\d+$")
|
||||
_RUN_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,128}$")
|
||||
_MAX_SSE_CONNECTIONS_PER_USER = 3
|
||||
_SSE_SLOT_TTL_SECONDS = 15 * 60
|
||||
_TERMINAL_RUN_EVENT_TYPES = {"RUN_FINISHED", "RUN_ERROR"}
|
||||
@@ -120,6 +121,11 @@ def _is_terminal_run_event(event: dict[str, object]) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def _is_target_run_event(event: dict[str, object], *, target_run_id: str) -> bool:
|
||||
run_id = event.get("runId")
|
||||
return isinstance(run_id, str) and run_id == target_run_id
|
||||
|
||||
|
||||
@router.post(
|
||||
"/runs", response_model=TaskAcceptedResponse, status_code=status.HTTP_202_ACCEPTED
|
||||
)
|
||||
@@ -188,9 +194,19 @@ async def stream_events(
|
||||
thread_id: str,
|
||||
service: Annotated[AgentService, Depends(get_agent_service)],
|
||||
current_user: Annotated[CurrentUser, Depends(get_current_user)],
|
||||
run_id: str | None = Query(default=None, alias="runId"),
|
||||
last_event_id: str | None = Header(default=None, alias="Last-Event-ID"),
|
||||
idle_limit: int = Query(default=300, ge=1, le=3600),
|
||||
) -> StreamingResponse:
|
||||
if run_id is None or _RUN_ID_RE.fullmatch(run_id) is None:
|
||||
raise ApiProblemError(
|
||||
status_code=422,
|
||||
detail=problem_payload(
|
||||
code="AGENT_INVALID_RUN_ID",
|
||||
detail="Invalid runId",
|
||||
),
|
||||
)
|
||||
|
||||
if last_event_id is not None and (
|
||||
len(last_event_id) > 32 or _LAST_EVENT_ID_RE.fullmatch(last_event_id) is None
|
||||
):
|
||||
@@ -255,6 +271,8 @@ async def stream_events(
|
||||
if not row_id or not isinstance(event, dict):
|
||||
continue
|
||||
cursor = row_id
|
||||
if not _is_target_run_event(event, target_run_id=run_id):
|
||||
continue
|
||||
yield to_sse_event(row_id, event)
|
||||
if _is_terminal_run_event(event):
|
||||
terminal_event_reached = True
|
||||
|
||||
Reference in New Issue
Block a user