Files
rag-technical-docs-assistant/app/main.py
T
amirhosein mazaheri 117fda7cc9 feat(voice): specialize prompt for Isfahan Industrial Parks, emit source excerpts, and bound generation
- Specialize voice assistant identity and agent system prompt for «شرکت شهرک‌های صنعتی اصفهان» (English instructions with Persian proper names)
- Emit bounded chunk text excerpts (up to 2000 chars) and identify primary_source in realtime sources events
- Bound OpenAI output generation via OPENAI_REALTIME_MAX_OUTPUT_TOKENS and add answer_limited event
- Handle old-turn search cancellation safely on turn supersession
- Add end-to-end search tracing pipeline and diagnostic CLI
- Add database organization title and settings update script
2026-10-12 17:35:28 +03:30

197 lines
8.6 KiB
Python

"""Modular API: startup reconciliation gates admission; no prototype imports."""
import asyncio
from contextlib import asynccontextmanager
from uuid import UUID, uuid4
from fastapi import FastAPI, Request, HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from fastapi.middleware.cors import CORSMiddleware
from app.api.v1.auth import router as auth_router, identity_router
from app.api.v1.conversations import router as conversations_router
from app.api.v1.live import router as voice_router
from app.api.v1.documents import router as documents_router
from app.api.v1.knowledge import router as knowledge_router
from app.api.v1 import dependencies
from app.infrastructure.blocking import blocking, shutdown_pool
from app.modules.voice.configuration import VoiceSettings
from app.modules.voice.registry import shutdown
import logging
import sys
_app_logger = logging.getLogger("app")
_app_logger.setLevel(logging.INFO)
if not any(isinstance(h, logging.StreamHandler) for h in _app_logger.handlers):
_sh = logging.StreamHandler(sys.stderr)
_sh.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] [%(name)s] %(message)s", datefmt="%Y-%m-%d %H:%M:%S"))
_app_logger.addHandler(_sh)
@asynccontextmanager
async def lifespan(app):
app.state.ready = False
engine = None
startup_error = None
try:
engine = dependencies.get_engine()
lifecycle = dependencies.get_lifecycle_service(engine)
await blocking(dependencies.prepare_search_tools)
await blocking(lifecycle.reconcile_startup)
app.state.ready = True
yield
except BaseException as exc:
startup_error = exc
raise
finally:
app.state.ready = False
async def cleanup():
try:
await asyncio.wait_for(shutdown(), 6)
finally:
try:
runner = dependencies._TOOL_RUNNER
if runner is not None:
await asyncio.wait_for(asyncio.to_thread(runner.close), 6)
finally:
try:
if engine is not None:
engine.dispose()
finally:
dependencies._TOOL_RUNNER = None
dependencies._ENGINE = dependencies._AUTH_SERVICE = dependencies._LIFECYCLE_SERVICE = dependencies._SEARCH_SERVICE = None
shutdown_pool()
task = asyncio.create_task(cleanup())
try:
await asyncio.shield(task)
except asyncio.CancelledError:
# Cleanup retains ownership after cancellation, including startup.
try:
await asyncio.shield(task)
except Exception:
if startup_error is None:
raise
if startup_error is None:
raise
except Exception:
if startup_error is None:
raise
API_DESCRIPTION = """
## 🤖 Technical Documentation Assistant API
A modular, production-ready backend combining RAG (Retrieval-Augmented Generation) document search with bidirectional live voice streaming.
---
### 🔑 Authentication & Security
* **Session Cookies:** Authenticated requests rely on the opaque `rag_session` HTTP-only cookie.
* **CSRF Protection:** State-changing requests (`POST`, `PATCH`, `DELETE`) require `X-CSRF-Token` header.
* **Host & Origin Validation:** Requests are filtered by strict loopback/trusted host gating.
### 📚 Core Modules
1. **Authentication:** User login/logout and session validation.
2. **Conversations:** Creation and state tracking for multi-turn chats.
3. **Voice Sessions:** Realtime bidirectional voice via WebSocket stream.
4. **Documents:** Document upload (PDF, DOCX, Markdown, Images), automated extraction, and quality control.
5. **Knowledge & Configuration:** Organizational knowledge selection and runtime capabilities discovery.
6. **Health & Monitoring:** Kubernetes/Docker liveness and readiness probes.
"""
TAGS_METADATA = [
{
"name": "Authentication",
"description": "User login, session lifecycle management, CSRF validation, and identity introspection.",
},
{
"name": "Conversations",
"description": "Creating and managing multi-turn text and voice conversations.",
},
{
"name": "Voice Sessions",
"description": "Bidirectional realtime voice sessions and WebSocket audio streaming endpoints.",
},
{
"name": "Documents",
"description": "Document ingestion pipeline, file intake, OCR review workflows, and error retries.",
},
{
"name": "Knowledge & Configuration",
"description": "Organizational knowledge selection, revision fencing, and assistant capabilities inquiry.",
},
{
"name": "Health & Monitoring",
"description": "Service liveness and readiness probes for orchestrators and monitoring.",
},
]
SWAGGER_UI_PARAMETERS = {
"defaultModelsExpandDepth": -1, # Collapse Schemas section by default for clean view
"docExpansion": "list", # Group endpoints neatly by tag
"filter": True, # Real-time search filter bar
"syntaxHighlight.theme": "monokai", # Modern dark syntax highlight for JSON
"tryItOutEnabled": True, # One-click try it out
"persistAuthorization": True, # Persist auth cookies across reloads
"displayRequestDuration": True, # Show execution duration in ms
}
app = FastAPI(
title='Technical Documentation Assistant API',
description=API_DESCRIPTION,
version='1.0.0',
openapi_tags=TAGS_METADATA,
swagger_ui_parameters=SWAGGER_UI_PARAMETERS,
lifespan=lifespan,
)
app.state.ready = False
config = VoiceSettings()
app.add_middleware(CORSMiddleware, allow_origins=list(config.trusted_origins), allow_credentials=True,
allow_methods=['GET','POST','PATCH','OPTIONS'], allow_headers=['Content-Type','X-CSRF-Token','X-Request-ID','Idempotency-Key','Accept','Authorization'],
expose_headers=['X-Request-ID','Idempotency-Replayed'])
@app.middleware('http')
async def transport(request, call_next):
try:
request_id = str(UUID(request.headers.get('x-request-id', '')))
except (ValueError, TypeError):
request_id = str(uuid4())
request.state.request_id = request_id
if request.headers.get('host') not in config.trusted_hosts:
result = envelope(request, 'FORBIDDEN', 403)
elif not app.state.ready and request.url.path not in ('/health/live','/health/ready'):
result = envelope(request, 'DEPENDENCY_UNAVAILABLE', 503)
else:
result = await call_next(request)
result.headers['X-Request-ID'] = request_id
return result
def envelope(request, code, status, details=None):
return JSONResponse(status_code=status, headers={'Retry-After':'60'} if status == 429 else {}, content={'error': {'code': code,
'message': 'Request could not be completed.', 'request_id': getattr(request.state, 'request_id', str(uuid4())),
'retryable': status in (429,503), **({'details':details} if details else {})}})
@app.exception_handler(StarletteHTTPException)
@app.exception_handler(HTTPException)
async def http_error(request, exc):
detail = exc.detail if isinstance(exc.detail, dict) else {}
return envelope(request, detail.get('code', 'NOT_FOUND' if exc.status_code == 404 else 'REQUEST_FAILED'), exc.status_code, detail.get('details'))
@app.exception_handler(RequestValidationError)
async def dto_error(request, exc):
return envelope(request, 'VALIDATION_ERROR', 422)
@app.exception_handler(Exception)
async def unexpected_error(request, exc):
return envelope(request, 'DEPENDENCY_UNAVAILABLE', 503)
for router in (auth_router, identity_router, conversations_router, voice_router, documents_router, knowledge_router):
app.include_router(router, prefix='/api/v1')
@app.get('/health/live', tags=['Health & Monitoring'], summary='Liveness Probe', description='Returns HTTP 200 if the API process is alive and receiving traffic.')
def live():
return {'status': 'ok'}
@app.get('/health/ready', tags=['Health & Monitoring'], summary='Readiness Probe', description='Returns HTTP 200 if the database and search dependencies have reconciled and the API is ready to serve requests.')
def ready():
return JSONResponse(status_code=200 if app.state.ready else 503,
content={'status': 'ready', 'ingestion': 'available'} if app.state.ready else {'status': 'not_ready'})