2026-09-09 21:55:37 +08:00
|
|
|
|
from collections.abc import AsyncIterator
|
|
|
|
|
|
from dataclasses import asdict
|
|
|
|
|
|
|
2026-09-20 14:33:30 +08:00
|
|
|
|
from fastapi import APIRouter, Depends, Path, Request, status
|
2026-09-09 21:55:37 +08:00
|
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
|
|
from starlette.responses import StreamingResponse
|
|
|
|
|
|
|
|
|
|
|
|
from app.api.dependencies.auth import build_request_context
|
|
|
|
|
|
from app.api.dependencies.database import get_session
|
2026-09-11 14:08:55 +08:00
|
|
|
|
from app.api.dependencies.negotiation import accepts_event_stream
|
2026-09-10 15:55:54 +08:00
|
|
|
|
from app.api.dependencies.rate_limit import enforce_rate_limit
|
2026-09-09 21:55:37 +08:00
|
|
|
|
from app.api.schemas.agent_runs import (
|
2026-09-10 15:55:54 +08:00
|
|
|
|
AgentRunAcceptedEnvelope,
|
2026-09-09 21:55:37 +08:00
|
|
|
|
AgentRunAcceptedResponse,
|
|
|
|
|
|
AgentRunCreateRequest,
|
2026-09-10 15:55:54 +08:00
|
|
|
|
AgentRunStatusEnvelope,
|
2026-09-09 21:55:37 +08:00
|
|
|
|
AgentRunStatusResponse,
|
|
|
|
|
|
)
|
|
|
|
|
|
from app.api.views.agent_run_sse import encode_events, recovery_events
|
|
|
|
|
|
from app.core.config import get_settings
|
|
|
|
|
|
from app.core.contracts import AgentRequest, RequestContext
|
2026-09-10 15:55:54 +08:00
|
|
|
|
from app.core.errors import SseNotAcceptableError
|
2026-09-09 21:55:37 +08:00
|
|
|
|
from app.service.agent_run_application_service import AgentRunApplicationService
|
|
|
|
|
|
from app.service.run_query_service import RunQueryService
|
|
|
|
|
|
|
2026-09-10 15:55:54 +08:00
|
|
|
|
router = APIRouter(prefix="/api/v1/agent-runs", tags=["agent-runs"],
|
|
|
|
|
|
dependencies=[Depends(enforce_rate_limit)])
|
|
|
|
|
|
|
|
|
|
|
|
@router.post(
|
|
|
|
|
|
"",
|
|
|
|
|
|
response_model=AgentRunAcceptedEnvelope,
|
|
|
|
|
|
status_code=status.HTTP_202_ACCEPTED,
|
|
|
|
|
|
)
|
2026-09-09 21:55:37 +08:00
|
|
|
|
async def create_agent_run(
|
|
|
|
|
|
payload: AgentRunCreateRequest,
|
|
|
|
|
|
request: Request,
|
|
|
|
|
|
context: RequestContext = Depends(build_request_context), # noqa: B008
|
|
|
|
|
|
session: AsyncSession = Depends(get_session), # noqa: B008
|
2026-09-10 15:55:54 +08:00
|
|
|
|
) -> AgentRunAcceptedEnvelope:
|
2026-09-09 21:55:37 +08:00
|
|
|
|
request.state.request_context = context
|
|
|
|
|
|
accepted = await AgentRunApplicationService(session).accept(
|
|
|
|
|
|
AgentRequest(**payload.model_dump()), context)
|
2026-09-10 15:55:54 +08:00
|
|
|
|
return AgentRunAcceptedEnvelope(
|
|
|
|
|
|
data=AgentRunAcceptedResponse(
|
|
|
|
|
|
run_id=accepted.run_id, trace_id=accepted.trace_id, status=accepted.status,
|
|
|
|
|
|
status_url=f"/api/v1/agent-runs/{accepted.run_id}",
|
|
|
|
|
|
events_url=f"/api/v1/agent-runs/{accepted.run_id}/events",
|
|
|
|
|
|
),
|
|
|
|
|
|
meta={"trace_id": context.trace_id},
|
2026-09-09 21:55:37 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-09-10 15:55:54 +08:00
|
|
|
|
@router.get("/{run_id}", response_model=AgentRunStatusEnvelope)
|
2026-09-09 21:55:37 +08:00
|
|
|
|
async def get_agent_run(
|
2026-09-20 14:33:30 +08:00
|
|
|
|
run_id: str = Path(min_length=1, max_length=64, pattern=r"^[A-Za-z0-9_-]+$"),
|
|
|
|
|
|
context: RequestContext = Depends(build_request_context), # noqa: B008
|
2026-09-10 15:55:54 +08:00
|
|
|
|
) -> AgentRunStatusEnvelope:
|
|
|
|
|
|
"""查询运行(文档 §6.3)。
|
|
|
|
|
|
|
|
|
|
|
|
文档 §3.3 与 §6.3 都把成功响应定义为 `{data, meta:{trace_id}}` 信封;此前这里
|
|
|
|
|
|
直接返回资源对象,客户端必须为这一个接口特判。**只改包装结构**:`data` 内的字段名
|
|
|
|
|
|
与语义保持原样,`meta.trace_id` 用本次请求的 trace(`data.trace_id` 仍是运行自身的
|
|
|
|
|
|
追踪标识,两者语义不同,不能互相替代)。
|
|
|
|
|
|
"""
|
|
|
|
|
|
snapshot = await RunQueryService().get(run_id, context)
|
|
|
|
|
|
return AgentRunStatusEnvelope(
|
|
|
|
|
|
data=AgentRunStatusResponse(**asdict(snapshot)),
|
|
|
|
|
|
meta={"trace_id": context.trace_id},
|
|
|
|
|
|
)
|
2026-09-09 21:55:37 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.get("/{run_id}/events")
|
|
|
|
|
|
async def stream_agent_run_events(
|
2026-09-10 15:55:54 +08:00
|
|
|
|
request: Request,
|
2026-09-20 14:33:30 +08:00
|
|
|
|
run_id: str = Path(min_length=1, max_length=64, pattern=r"^[A-Za-z0-9_-]+$"),
|
2026-09-10 15:55:54 +08:00
|
|
|
|
context: RequestContext = Depends(build_request_context), # noqa: B008
|
2026-09-09 21:55:37 +08:00
|
|
|
|
) -> StreamingResponse:
|
|
|
|
|
|
query = RunQueryService()
|
2026-09-10 15:55:54 +08:00
|
|
|
|
# 顺序按文档 §6.4 的主要错误列举:RUN_NOT_FOUND(含 AGENT_PERMISSION_DENIED 同级的
|
|
|
|
|
|
# 可见性判定)在前、SSE_NOT_ACCEPTABLE 在后。可见性先行(auth 依赖已先于本函数执行)
|
|
|
|
|
|
# 才能保证"运行是否存在"不因 Accept 头而异:否则用任意 run_id + 非法 Accept 探测,
|
|
|
|
|
|
# 406 与 404 的差异就等价于一次存在性枚举。
|
2026-09-09 21:55:37 +08:00
|
|
|
|
initial = await query.get(run_id, context)
|
2026-09-10 15:55:54 +08:00
|
|
|
|
if not accepts_event_stream(request.headers.get("Accept")):
|
|
|
|
|
|
raise SseNotAcceptableError("Accept 必须接受 text/event-stream")
|
2026-09-09 21:55:37 +08:00
|
|
|
|
|
|
|
|
|
|
async def generate() -> AsyncIterator[str]:
|
|
|
|
|
|
start_sent = False
|
|
|
|
|
|
async for snapshot in query.watch(initial, context):
|
|
|
|
|
|
if snapshot is None:
|
|
|
|
|
|
yield ": heartbeat\n\n"
|
|
|
|
|
|
continue
|
|
|
|
|
|
result = snapshot.result or {}
|
|
|
|
|
|
events = recovery_events(
|
|
|
|
|
|
run_id=snapshot.run_id, trace_id=snapshot.trace_id, status=snapshot.status,
|
|
|
|
|
|
error_code=snapshot.error_code, content=result.get("content"),
|
|
|
|
|
|
tool_calls=result.get("tool_calls"),
|
|
|
|
|
|
replay=initial.status in {"succeeded", "failed", "cancelled"},
|
|
|
|
|
|
chunk_size=get_settings().sse_chunk_characters,
|
|
|
|
|
|
)
|
|
|
|
|
|
for encoded in encode_events(run_id, events[1:] if start_sent else events):
|
|
|
|
|
|
yield encoded
|
|
|
|
|
|
start_sent = True
|
|
|
|
|
|
|
|
|
|
|
|
return StreamingResponse(generate(), media_type="text/event-stream",
|
|
|
|
|
|
headers={"Cache-Control": "no-cache"})
|