|
| 1 | +import logging |
| 2 | +from uuid import UUID |
| 3 | + |
| 4 | +from fastapi import APIRouter, Depends, HTTPException |
| 5 | +from opentelemetry import trace |
| 6 | + |
| 7 | +from app.api.deps import AuthContextDep, SessionDep |
| 8 | +from app.api.permissions import Permission, require_permission |
| 9 | +from app.core.rate_monitor import monitor_rate |
| 10 | +from app.core.telemetry import log_context |
| 11 | +from app.crud.jobs import JobCrud |
| 12 | +from app.models import JobStatus, JobType |
| 13 | +from app.models.guardrails import ( |
| 14 | + GuardrailsCallbackData, |
| 15 | + GuardrailsJobImmediatePublic, |
| 16 | + GuardrailsJobPublic, |
| 17 | + GuardrailsRequest, |
| 18 | +) |
| 19 | +from app.services.guardrails.jobs import start_job |
| 20 | +from app.utils import APIResponse, load_description, validate_callback_url |
| 21 | + |
| 22 | +logger = logging.getLogger(__name__) |
| 23 | + |
| 24 | +router = APIRouter(tags=["Guardrails"]) |
| 25 | +guardrails_callback_router = APIRouter() |
| 26 | + |
| 27 | + |
| 28 | +@router.post( |
| 29 | + "/guardrails", |
| 30 | + description=load_description("guardrails/apply_guardrails.md"), |
| 31 | + response_model=APIResponse[GuardrailsJobImmediatePublic], |
| 32 | + callbacks=guardrails_callback_router.routes, |
| 33 | + dependencies=[ |
| 34 | + Depends(require_permission(Permission.REQUIRE_PROJECT)), |
| 35 | + Depends(monitor_rate("llm_call")), |
| 36 | + ], |
| 37 | +) |
| 38 | +def apply_guardrails_endpoint( |
| 39 | + _current_user: AuthContextDep, |
| 40 | + session: SessionDep, |
| 41 | + request: GuardrailsRequest, |
| 42 | +) -> APIResponse[GuardrailsJobImmediatePublic]: |
| 43 | + """Initiate a guardrails-only job. Returns the job_id immediately; the |
| 44 | + sanitised text is delivered via callback_url (or polled via GET).""" |
| 45 | + project_id = _current_user.project_.id |
| 46 | + organization_id = _current_user.organization_.id |
| 47 | + |
| 48 | + with log_context( |
| 49 | + tag="guardrails", |
| 50 | + system="guardrails", |
| 51 | + lifecycle="api.guardrails.apply", |
| 52 | + project_id=project_id, |
| 53 | + organization_id=organization_id, |
| 54 | + callback_enabled=request.callback_url is not None, |
| 55 | + ): |
| 56 | + span = trace.get_current_span() |
| 57 | + if span.is_recording(): |
| 58 | + span.set_attribute("kaapi.project_id", project_id) |
| 59 | + span.set_attribute("kaapi.organization_id", organization_id) |
| 60 | + span.set_attribute( |
| 61 | + "guardrails.callback_enabled", request.callback_url is not None |
| 62 | + ) |
| 63 | + |
| 64 | + if request.callback_url: |
| 65 | + validate_callback_url(str(request.callback_url)) |
| 66 | + |
| 67 | + job = start_job( |
| 68 | + db=session, |
| 69 | + request=request, |
| 70 | + project_id=project_id, |
| 71 | + organization_id=organization_id, |
| 72 | + ) |
| 73 | + |
| 74 | + if span.is_recording(): |
| 75 | + span.set_attribute("guardrails.job_id", str(job.id)) |
| 76 | + |
| 77 | + message = ( |
| 78 | + "Guardrails are being applied; the sanitised text will be delivered via callback." |
| 79 | + if request.callback_url |
| 80 | + else "Guardrails are being applied; poll GET /guardrails/{job_id} for the result." |
| 81 | + ) |
| 82 | + |
| 83 | + return APIResponse.success_response( |
| 84 | + data=GuardrailsJobImmediatePublic( |
| 85 | + job_id=job.id, |
| 86 | + status=job.status.value, |
| 87 | + message=message, |
| 88 | + job_inserted_at=job.inserted_at, |
| 89 | + job_updated_at=job.updated_at, |
| 90 | + ) |
| 91 | + ) |
| 92 | + |
| 93 | + |
| 94 | +@router.get( |
| 95 | + "/guardrails/{job_id}", |
| 96 | + response_model=APIResponse[GuardrailsJobPublic], |
| 97 | + dependencies=[Depends(require_permission(Permission.REQUIRE_PROJECT))], |
| 98 | +) |
| 99 | +def get_guardrails_job_status( |
| 100 | + _current_user: AuthContextDep, |
| 101 | + session: SessionDep, |
| 102 | + job_id: UUID, |
| 103 | +) -> APIResponse[GuardrailsJobPublic]: |
| 104 | + """Poll for a /guardrails job's status and result. |
| 105 | +
|
| 106 | + On SUCCESS the sanitised text is rehydrated from the persisted upstream |
| 107 | + response stored on ``job.meta``. |
| 108 | + """ |
| 109 | + project_id = _current_user.project_.id |
| 110 | + |
| 111 | + with log_context( |
| 112 | + tag="guardrails", |
| 113 | + system="guardrails", |
| 114 | + lifecycle="api.guardrails.status", |
| 115 | + job_id=job_id, |
| 116 | + project_id=project_id, |
| 117 | + organization_id=_current_user.organization_.id, |
| 118 | + ): |
| 119 | + job = JobCrud(session=session).get(job_id=job_id, project_id=project_id) |
| 120 | + if not job or job.job_type != JobType.LLM_GUARDRAILS: |
| 121 | + # 404 (not 403) to avoid leaking existence of non-guardrails jobs. |
| 122 | + raise HTTPException(status_code=404, detail="Job not found") |
| 123 | + |
| 124 | + meta = job.meta if isinstance(job.meta, dict) else {} |
| 125 | + callback_blob = meta.get("callback") if isinstance(meta, dict) else None |
| 126 | + |
| 127 | + warnings: list[str] = [] |
| 128 | + if isinstance(callback_blob, dict): |
| 129 | + raw_warnings = callback_blob.get("warnings") |
| 130 | + if isinstance(raw_warnings, list): |
| 131 | + warnings = [w for w in raw_warnings if isinstance(w, str)] |
| 132 | + |
| 133 | + guardrails_response: GuardrailsCallbackData | None = None |
| 134 | + if job.status == JobStatus.SUCCESS: |
| 135 | + response_blob = meta.get("response") or {} |
| 136 | + data_blob = ( |
| 137 | + response_blob.get("data") if isinstance(response_blob, dict) else None |
| 138 | + ) or {} |
| 139 | + safe_text = ( |
| 140 | + data_blob.get("safe_text") if isinstance(data_blob, dict) else None |
| 141 | + ) |
| 142 | + request_blob = meta.get("request") or {} |
| 143 | + original_text = ( |
| 144 | + request_blob.get("text") if isinstance(request_blob, dict) else None |
| 145 | + ) |
| 146 | + value = safe_text if isinstance(safe_text, str) else (original_text or "") |
| 147 | + |
| 148 | + response_id: str | None = None |
| 149 | + if isinstance(callback_blob, dict): |
| 150 | + rid = callback_blob.get("response_id") |
| 151 | + if isinstance(rid, str): |
| 152 | + response_id = rid |
| 153 | + |
| 154 | + guardrails_response = GuardrailsCallbackData.model_validate( |
| 155 | + { |
| 156 | + "response": { |
| 157 | + "response_id": response_id, |
| 158 | + "output": { |
| 159 | + "type": "text", |
| 160 | + "content": {"format": "text", "value": value}, |
| 161 | + }, |
| 162 | + }, |
| 163 | + "usage": ( |
| 164 | + data_blob.get("usage") |
| 165 | + if isinstance(data_blob, dict) |
| 166 | + and isinstance(data_blob.get("usage"), dict) |
| 167 | + else {} |
| 168 | + ), |
| 169 | + "provider_raw_response": None, |
| 170 | + } |
| 171 | + ) |
| 172 | + |
| 173 | + return APIResponse.success_response( |
| 174 | + data=GuardrailsJobPublic( |
| 175 | + job_id=job.id, |
| 176 | + status=job.status.value, |
| 177 | + guardrails_response=guardrails_response, |
| 178 | + error_message=job.error_message, |
| 179 | + warnings=warnings, |
| 180 | + ) |
| 181 | + ) |
0 commit comments