From 0b1ca7a3fefb1ccd1c03dd58e3b6349baef9ccda Mon Sep 17 00:00:00 2001 From: "Eunice(Eunyoung) Shin" Date: Sat, 4 Jul 2026 16:43:12 +0900 Subject: [PATCH] feat: add report generation trigger/status endpoints (AI service proxy) Wires the missing trigger for the 5-agent report generation feature - until now, the DB tables (PR #97) and the AI service's endpoint existed but nothing in BE ever called it. POST /api/v1/sessions/{session_id}/reports/generate - resolves patient_ref_id/therapist_id from the session row itself (caller only needs session_id + optional selected_analysis/history_session_count), then proxies to AI's POST /internal/ai/sessions/{session_id}/reports/generate. GET /api/v1/report-generation-runs/{run_id} - proxies to AI's status endpoint. Follows report_chat.py's established ReportChatService pattern exactly: _get_accessible_session() authorization check (ADMIN or owning SLP only), sync httpx client with the same single-retry-on-RequestError policy for ai-service's spot-node connection drops. Verified: routes register at the expected paths (checked via app.routes), unit tests (130) pass. Integration tests need a local Postgres on port 5432 per tests/conftest.py's hardcoded URL; this machine has an unrelated native postgres already bound there, so those specific tests (test_report_chat.py, pre-existing, unrelated to this change) couldn't be exercised locally - not caused by this change. --- app/api/v1/api.py | 2 + app/api/v1/endpoints/report_generation.py | 45 +++++++++ app/schemas/report_generation.py | 32 ++++++ app/services/report_generation.py | 115 ++++++++++++++++++++++ 4 files changed, 194 insertions(+) create mode 100644 app/api/v1/endpoints/report_generation.py create mode 100644 app/schemas/report_generation.py create mode 100644 app/services/report_generation.py diff --git a/app/api/v1/api.py b/app/api/v1/api.py index 2ce16c9..4717647 100644 --- a/app/api/v1/api.py +++ b/app/api/v1/api.py @@ -11,6 +11,7 @@ from app.api.v1.endpoints.patients import router as patients_router from app.api.v1.endpoints.report import router as report_router from app.api.v1.endpoints.report_chat import router as report_chat_router +from app.api.v1.endpoints.report_generation import router as report_generation_router from app.api.v1.endpoints.session_transcript import router as session_transcript_router from app.api.v1.endpoints.sessions import router as sessions_router from app.api.v1.endpoints.templates import router as templates_router @@ -27,6 +28,7 @@ api_v1_router.include_router(analysis_router, prefix="/analysis-jobs", tags=["analysis-jobs"]) api_v1_router.include_router(report_router, prefix="/reports", tags=["reports"]) api_v1_router.include_router(report_chat_router, prefix="/reports", tags=["report-chat"]) +api_v1_router.include_router(report_generation_router, tags=["report-generation"]) api_v1_router.include_router(templates_router, prefix="/templates", tags=["templates"]) api_v1_router.include_router(transcript_router, prefix="/transcripts", tags=["transcripts"]) api_v1_router.include_router(insight_map_router, prefix="/insight-map", tags=["insight-map"]) diff --git a/app/api/v1/endpoints/report_generation.py b/app/api/v1/endpoints/report_generation.py new file mode 100644 index 0000000..2647fce --- /dev/null +++ b/app/api/v1/endpoints/report_generation.py @@ -0,0 +1,45 @@ +"""5-Agent 리포트 생성 트리거/조회 엔드포인트 (AI 서비스 프록시).""" + +from __future__ import annotations + +import uuid + +from fastapi import APIRouter, Depends +from sqlalchemy.orm import Session + +from app.api.dependencies import get_current_user +from app.core.db import get_db_session +from app.schemas.auth import UserRead +from app.schemas.report_generation import ( + ReportGenerationCreateRequest, + ReportGenerationCreateResponse, + ReportGenerationStatusResponse, +) +from app.services.report_generation import ReportGenerationService + +router = APIRouter() + + +@router.post( + "/sessions/{session_id}/reports/generate", response_model=ReportGenerationCreateResponse +) +def create_report_generation_run( + session_id: uuid.UUID, + request: ReportGenerationCreateRequest, + current_user: UserRead = Depends(get_current_user), + db: Session = Depends(get_db_session), +) -> ReportGenerationCreateResponse: + service = ReportGenerationService(db) + return service.create_run(session_id, request, current_user) + + +@router.get( + "/report-generation-runs/{run_id}", response_model=ReportGenerationStatusResponse +) +def get_report_generation_run( + run_id: uuid.UUID, + current_user: UserRead = Depends(get_current_user), + db: Session = Depends(get_db_session), +) -> ReportGenerationStatusResponse: + service = ReportGenerationService(db) + return service.get_run(run_id, current_user) diff --git a/app/schemas/report_generation.py b/app/schemas/report_generation.py new file mode 100644 index 0000000..a101904 --- /dev/null +++ b/app/schemas/report_generation.py @@ -0,0 +1,32 @@ +"""5-Agent 리포트 생성 트리거/조회 스키마 (AI 서비스 프록시).""" + +from __future__ import annotations + +import uuid + +from pydantic import BaseModel + + +class ReportGenerationCreateRequest(BaseModel): + """session_id는 path param으로 받으므로 patient_ref_id/therapist_id는 + 서버가 세션 row에서 직접 채운다 (report_chat/audio 서비스와 동일 신뢰 경계). + """ + + selected_analysis: list[str] = ["MLU", "TTR", "NDW"] + history_session_count: int = 5 + + +class ReportGenerationCreateResponse(BaseModel): + run_id: uuid.UUID + status: str + + +class ReportGenerationStatusResponse(BaseModel): + run_id: uuid.UUID + status: str + current_node: str | None = None + retry_summary: dict[str, int] | None = None + report_draft_id: uuid.UUID | None = None + quality_scores: dict[str, float] | None = None + failure_code: str | None = None + reason_codes: list[str] | None = None diff --git a/app/services/report_generation.py b/app/services/report_generation.py new file mode 100644 index 0000000..edeca2d --- /dev/null +++ b/app/services/report_generation.py @@ -0,0 +1,115 @@ +"""5-Agent 리포트 생성: 세션 접근권한 확인 후 AI 서비스로 프록시한다. + +report_chat.py의 _call_ai_service()와 동일한 재시도/에러 매핑 패턴을 따른다. +AI 서비스는 session_id/patient_ref_id/therapist_id로 자체 권한도 다시 +검증하므로(app.services.authorization_service), 여기서의 권한 확인은 +"이 요청 자체를 보낼 자격"만 확인하는 1차 관문이다. +""" + +from __future__ import annotations + +import logging +import uuid + +import httpx +from fastapi import HTTPException, status +from sqlalchemy.orm import Session as DbSession + +from app.core.config import get_settings +from app.core.enums import SessionStatus, UserRole +from app.repositories.session import SessionRepository +from app.schemas.auth import UserRead +from app.schemas.report_generation import ( + ReportGenerationCreateRequest, + ReportGenerationCreateResponse, + ReportGenerationStatusResponse, +) + +settings = get_settings() +logger = logging.getLogger(__name__) + +_AI_SERVICE_MAX_ATTEMPTS = 2 + + +class ReportGenerationService: + def __init__(self, db: DbSession) -> None: + self._db = db + self._session_repository = SessionRepository(db) + + def create_run( + self, + session_id: uuid.UUID, + request: ReportGenerationCreateRequest, + current_user: UserRead, + ) -> ReportGenerationCreateResponse: + session = self._get_accessible_session(session_id, current_user) + + payload = { + "patient_ref_id": str(session.patient_ref_id), + "therapist_id": str(session.slp_id), + "selected_analysis": request.selected_analysis, + "history_session_count": request.history_session_count, + } + result = self._call_ai_service( + "post", f"/internal/ai/sessions/{session_id}/reports/generate", json=payload + ) + return ReportGenerationCreateResponse(**result) + + def get_run( + self, run_id: uuid.UUID, current_user: UserRead + ) -> ReportGenerationStatusResponse: + result = self._call_ai_service( + "get", + f"/internal/ai/report-generation-runs/{run_id}", + params={"therapist_id": str(current_user.id)}, + ) + return ReportGenerationStatusResponse(**result) + + def _get_accessible_session(self, session_id: uuid.UUID, current_user: UserRead): + session = self._session_repository.get_by_id(session_id) + if session is None or session.status == SessionStatus.DELETED: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Session not found.", + ) + if current_user.role == UserRole.ADMIN: + return session + if current_user.role == UserRole.SLP and session.slp_id == current_user.id: + return session + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="You do not have access to this session.", + ) + + # ai-service는 cpu-worker와 spot NodePool을 공유한다 - report_chat.py의 + # _call_ai_service()와 동일한 이유로, 연결 자체가 끊긴 경우(RequestError)에 + # 한해 한 번만 재시도한다. + def _call_ai_service(self, method: str, path: str, **kwargs) -> dict: + url = f"{settings.ai_service_base_url}{path}" + last_exc: httpx.RequestError | None = None + for attempt in range(1, _AI_SERVICE_MAX_ATTEMPTS + 1): + try: + with httpx.Client(timeout=60.0) as client: + resp = client.request(method, url, **kwargs) + resp.raise_for_status() + return resp.json() + except httpx.HTTPStatusError as exc: + if exc.response.status_code == 404: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, detail="Run not found." + ) from exc + raise HTTPException( + status_code=status.HTTP_502_BAD_GATEWAY, + detail=f"AI service error: {exc.response.status_code}", + ) from exc + except httpx.RequestError as exc: + last_exc = exc + logger.warning( + f"[report-generation] AI 서비스 연결 실패 (attempt {attempt}/" + f"{_AI_SERVICE_MAX_ATTEMPTS}): {exc}" + ) + + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="AI service is unreachable.", + ) from last_exc