Spaces:
Paused
Paused
Commit ·
f3bcb28
1
Parent(s): c84e946
TensorWall Demo for HuggingFace Spaces
Browse files- Landing page with project description
- One-click demo access
- SQLite database with automatic table creation
- Frontend/Backend/Caddy stack
This view is limited to 50 files because it contains too many changes. See raw diff
- .gitignore +42 -0
- Caddyfile +34 -0
- Dockerfile +80 -0
- backend/.env.example +67 -0
- backend/.env.production.example +74 -0
- backend/Dockerfile +28 -0
- backend/__init__.py +2 -0
- backend/adapters/__init__.py +51 -0
- backend/adapters/abuse/__init__.py +12 -0
- backend/adapters/abuse/in_memory_abuse_adapter.py +375 -0
- backend/adapters/audit/__init__.py +16 -0
- backend/adapters/audit/postgres_audit_adapter.py +397 -0
- backend/adapters/cache/__init__.py +15 -0
- backend/adapters/cache/redis_client.py +260 -0
- backend/adapters/encryption/__init__.py +12 -0
- backend/adapters/encryption/aws_kms_adapter.py +313 -0
- backend/adapters/encryption/in_memory_adapter.py +196 -0
- backend/adapters/exporters/__init__.py +11 -0
- backend/adapters/feature/__init__.py +5 -0
- backend/adapters/feature/in_memory_feature_adapter.py +280 -0
- backend/adapters/llm/__init__.py +22 -0
- backend/adapters/llm/anthropic_adapter.py +240 -0
- backend/adapters/llm/mock_adapter.py +174 -0
- backend/adapters/llm/ollama_adapter.py +175 -0
- backend/adapters/llm/openai_adapter.py +156 -0
- backend/adapters/llm/openai_embedding_adapter.py +70 -0
- backend/adapters/model_registry/__init__.py +16 -0
- backend/adapters/model_registry/in_memory_adapter.py +534 -0
- backend/adapters/model_registry/postgres_adapter.py +523 -0
- backend/adapters/observability/__init__.py +16 -0
- backend/adapters/observability/in_memory_adapter.py +439 -0
- backend/adapters/observability/langfuse_adapter.py +323 -0
- backend/adapters/observability/prometheus_adapter.py +475 -0
- backend/adapters/postgres/__init__.py +14 -0
- backend/adapters/postgres/budget_repository_adapter.py +327 -0
- backend/adapters/postgres/policy_repository_adapter.py +254 -0
- backend/adapters/prometheus/__init__.py +16 -0
- backend/adapters/prometheus/metrics_adapter.py +460 -0
- backend/adapters/redis/__init__.py +18 -0
- backend/adapters/redis/cache_adapter.py +278 -0
- backend/adapters/tracing/__init__.py +14 -0
- backend/adapters/tracing/in_memory_adapter.py +275 -0
- backend/adapters/tracing/opentelemetry_adapter.py +415 -0
- backend/adapters/tracing/postgres_adapter.py +471 -0
- backend/alembic.ini +42 -0
- backend/alembic/env.py +89 -0
- backend/alembic/script.py.mako +26 -0
- backend/alembic/versions/001_initial_schema.py +502 -0
- backend/api/__init__.py +3 -0
- backend/api/admin/__init__.py +25 -0
.gitignore
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.py[cod]
|
| 4 |
+
*.pyo
|
| 5 |
+
*.egg-info/
|
| 6 |
+
.eggs/
|
| 7 |
+
dist/
|
| 8 |
+
build/
|
| 9 |
+
*.egg
|
| 10 |
+
|
| 11 |
+
# Environment
|
| 12 |
+
.env
|
| 13 |
+
.env.local
|
| 14 |
+
.env.*.local
|
| 15 |
+
*.env
|
| 16 |
+
|
| 17 |
+
# Node
|
| 18 |
+
node_modules/
|
| 19 |
+
.next/
|
| 20 |
+
.npm/
|
| 21 |
+
*.log
|
| 22 |
+
|
| 23 |
+
# IDE
|
| 24 |
+
.idea/
|
| 25 |
+
.vscode/
|
| 26 |
+
*.swp
|
| 27 |
+
*.swo
|
| 28 |
+
|
| 29 |
+
# OS
|
| 30 |
+
.DS_Store
|
| 31 |
+
Thumbs.db
|
| 32 |
+
|
| 33 |
+
# Test
|
| 34 |
+
.coverage
|
| 35 |
+
.pytest_cache/
|
| 36 |
+
htmlcov/
|
| 37 |
+
|
| 38 |
+
# Data
|
| 39 |
+
*.db
|
| 40 |
+
*.sqlite
|
| 41 |
+
*.sqlite3
|
| 42 |
+
data/
|
Caddyfile
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
:7860 {
|
| 2 |
+
# Logs
|
| 3 |
+
log {
|
| 4 |
+
output stdout
|
| 5 |
+
format console
|
| 6 |
+
}
|
| 7 |
+
|
| 8 |
+
# API Backend - strip /api prefix
|
| 9 |
+
handle_path /api/* {
|
| 10 |
+
reverse_proxy localhost:8000
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
# Direct backend routes (health, docs, openapi)
|
| 14 |
+
handle /health/* {
|
| 15 |
+
reverse_proxy localhost:8000
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
handle /v1/* {
|
| 19 |
+
reverse_proxy localhost:8000
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
handle /docs {
|
| 23 |
+
reverse_proxy localhost:8000
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
handle /openapi.json {
|
| 27 |
+
reverse_proxy localhost:8000
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
# Frontend Next.js (everything else)
|
| 31 |
+
handle {
|
| 32 |
+
reverse_proxy localhost:3000
|
| 33 |
+
}
|
| 34 |
+
}
|
Dockerfile
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --- Étape 1 : Build du Frontend (Next.js) ---
|
| 2 |
+
FROM node:20-slim AS frontend-builder
|
| 3 |
+
WORKDIR /app/frontend
|
| 4 |
+
|
| 5 |
+
COPY frontend/package*.json ./
|
| 6 |
+
RUN npm ci --quiet
|
| 7 |
+
|
| 8 |
+
COPY frontend/ ./
|
| 9 |
+
ENV NODE_ENV=production
|
| 10 |
+
ENV NEXT_TELEMETRY_DISABLED=1
|
| 11 |
+
ENV NEXT_PUBLIC_API_URL=/api
|
| 12 |
+
ENV NEXT_PUBLIC_DEMO_MODE=true
|
| 13 |
+
|
| 14 |
+
RUN npm run build
|
| 15 |
+
|
| 16 |
+
# --- Étape 2 : Runtime Final ---
|
| 17 |
+
FROM python:3.11-slim
|
| 18 |
+
|
| 19 |
+
# Installation des dépendances (Node, Caddy, Outils)
|
| 20 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 21 |
+
curl \
|
| 22 |
+
gcc \
|
| 23 |
+
gnupg \
|
| 24 |
+
debian-keyring \
|
| 25 |
+
debian-archive-keyring \
|
| 26 |
+
apt-transport-https \
|
| 27 |
+
&& curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
|
| 28 |
+
&& apt-get install -y nodejs \
|
| 29 |
+
&& curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg \
|
| 30 |
+
&& curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | tee /etc/apt/sources.list.d/caddy-stable.list \
|
| 31 |
+
&& apt-get update \
|
| 32 |
+
&& apt-get install -y caddy \
|
| 33 |
+
&& apt-get clean && rm -rf /var/lib/apt/lists/*
|
| 34 |
+
|
| 35 |
+
WORKDIR /app
|
| 36 |
+
|
| 37 |
+
# Backend - Installation des dépendances
|
| 38 |
+
COPY backend/requirements.txt ./backend/
|
| 39 |
+
RUN pip install --no-cache-dir -r backend/requirements.txt aiosqlite uvicorn
|
| 40 |
+
|
| 41 |
+
COPY backend/ ./backend/
|
| 42 |
+
|
| 43 |
+
# Frontend - Copie du build
|
| 44 |
+
COPY --from=frontend-builder /app/frontend/.next ./frontend/.next
|
| 45 |
+
COPY --from=frontend-builder /app/frontend/node_modules ./frontend/node_modules
|
| 46 |
+
COPY --from=frontend-builder /app/frontend/package.json ./frontend/
|
| 47 |
+
COPY --from=frontend-builder /app/frontend/public ./frontend/public
|
| 48 |
+
COPY --from=frontend-builder /app/frontend/next.config.js ./frontend/
|
| 49 |
+
|
| 50 |
+
# Configuration Hugging Face Space
|
| 51 |
+
COPY Caddyfile /etc/caddy/Caddyfile
|
| 52 |
+
COPY start.sh /app/start.sh
|
| 53 |
+
RUN chmod +x /app/start.sh
|
| 54 |
+
|
| 55 |
+
# Variables d'environnement critiques
|
| 56 |
+
ENV PYTHONUNBUFFERED=1
|
| 57 |
+
ENV PYTHONDONTWRITEBYTECODE=1
|
| 58 |
+
ENV PYTHONPATH=/app
|
| 59 |
+
ENV NODE_ENV=production
|
| 60 |
+
ENV NEXT_TELEMETRY_DISABLED=1
|
| 61 |
+
ENV PORT=7860
|
| 62 |
+
ENV DATABASE_URL=sqlite+aiosqlite:////app/data/tensorwall.db
|
| 63 |
+
ENV ENVIRONMENT=demo
|
| 64 |
+
ENV DEMO_MODE=true
|
| 65 |
+
ENV DEBUG=false
|
| 66 |
+
ENV JWT_SECRET_KEY=hf-demo-secret-key-change-this-for-prod
|
| 67 |
+
ENV CORS_ORIGINS_RAW=*
|
| 68 |
+
|
| 69 |
+
# Gestion des permissions pour l'utilisateur 1000 (Hugging Face)
|
| 70 |
+
RUN mkdir -p /app/data && chmod -R 777 /app/data && \
|
| 71 |
+
chmod -R 755 /app/backend /app/frontend
|
| 72 |
+
|
| 73 |
+
USER 1000
|
| 74 |
+
|
| 75 |
+
EXPOSE 7860
|
| 76 |
+
|
| 77 |
+
HEALTHCHECK --interval=30s --timeout=10s --start-period=180s --retries=5 \
|
| 78 |
+
CMD curl -sf http://localhost:7860/api/health/live || exit 1
|
| 79 |
+
|
| 80 |
+
CMD ["/app/start.sh"]
|
backend/.env.example
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# =============================================================================
|
| 2 |
+
# TensorWall - Environment Variables
|
| 3 |
+
# =============================================================================
|
| 4 |
+
# Copy to .env for local development
|
| 5 |
+
# In production (Fly.io), set via: fly secrets set KEY=value
|
| 6 |
+
|
| 7 |
+
# =============================================================================
|
| 8 |
+
# Environment
|
| 9 |
+
# =============================================================================
|
| 10 |
+
ENVIRONMENT=development
|
| 11 |
+
DEBUG=true
|
| 12 |
+
LOG_LEVEL=debug
|
| 13 |
+
|
| 14 |
+
# =============================================================================
|
| 15 |
+
# Server
|
| 16 |
+
# =============================================================================
|
| 17 |
+
HOST=0.0.0.0
|
| 18 |
+
PORT=8000
|
| 19 |
+
|
| 20 |
+
# =============================================================================
|
| 21 |
+
# CORS (comma-separated origins)
|
| 22 |
+
# =============================================================================
|
| 23 |
+
# Development
|
| 24 |
+
CORS_ORIGINS=http://localhost:3000,http://localhost:5173
|
| 25 |
+
# Production: CORS_ORIGINS=https://app.example.com
|
| 26 |
+
|
| 27 |
+
# =============================================================================
|
| 28 |
+
# Database
|
| 29 |
+
# =============================================================================
|
| 30 |
+
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/tensorwall
|
| 31 |
+
REDIS_URL=redis://localhost:6379
|
| 32 |
+
|
| 33 |
+
# =============================================================================
|
| 34 |
+
# JWT Authentication (REQUIRED)
|
| 35 |
+
# =============================================================================
|
| 36 |
+
# Generate secure key: python -c "import secrets; print(secrets.token_urlsafe(32))"
|
| 37 |
+
JWT_SECRET_KEY=dev-secret-key-change-in-production
|
| 38 |
+
|
| 39 |
+
# =============================================================================
|
| 40 |
+
# LLM Providers
|
| 41 |
+
# =============================================================================
|
| 42 |
+
OPENAI_API_URL=https://api.openai.com/v1
|
| 43 |
+
OPENAI_API_KEY=
|
| 44 |
+
ANTHROPIC_API_URL=https://api.anthropic.com/v1
|
| 45 |
+
ANTHROPIC_API_KEY=
|
| 46 |
+
|
| 47 |
+
# =============================================================================
|
| 48 |
+
# Email Alerts (SMTP)
|
| 49 |
+
# =============================================================================
|
| 50 |
+
SMTP_HOST=
|
| 51 |
+
SMTP_PORT=587
|
| 52 |
+
SMTP_USER=
|
| 53 |
+
SMTP_PASSWORD=
|
| 54 |
+
SMTP_FROM_EMAIL=alerts@example.com
|
| 55 |
+
SMTP_FROM_NAME=TensorWall
|
| 56 |
+
|
| 57 |
+
# =============================================================================
|
| 58 |
+
# Gateway Settings
|
| 59 |
+
# =============================================================================
|
| 60 |
+
MAX_LATENCY_MS=50
|
| 61 |
+
DEFAULT_MAX_TOKENS=4096
|
| 62 |
+
|
| 63 |
+
# =============================================================================
|
| 64 |
+
# Audit
|
| 65 |
+
# =============================================================================
|
| 66 |
+
AUDIT_RETENTION_DAYS=90
|
| 67 |
+
STORE_PROMPTS=false
|
backend/.env.production.example
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# =============================================================================
|
| 2 |
+
# TensorWall - Production Environment Configuration
|
| 3 |
+
# =============================================================================
|
| 4 |
+
# SECURITY: Copy this file to .env and set all values before deploying
|
| 5 |
+
# NEVER commit .env files with real credentials to version control
|
| 6 |
+
# =============================================================================
|
| 7 |
+
|
| 8 |
+
# -----------------------------------------------------------------------------
|
| 9 |
+
# Environment Settings
|
| 10 |
+
# -----------------------------------------------------------------------------
|
| 11 |
+
ENVIRONMENT=production
|
| 12 |
+
DEBUG=false
|
| 13 |
+
|
| 14 |
+
# -----------------------------------------------------------------------------
|
| 15 |
+
# Server Configuration
|
| 16 |
+
# -----------------------------------------------------------------------------
|
| 17 |
+
HOST=0.0.0.0
|
| 18 |
+
PORT=8000
|
| 19 |
+
|
| 20 |
+
# -----------------------------------------------------------------------------
|
| 21 |
+
# CORS (add your production domains)
|
| 22 |
+
# -----------------------------------------------------------------------------
|
| 23 |
+
CORS_ORIGINS=["https://your-domain.com","https://admin.your-domain.com"]
|
| 24 |
+
|
| 25 |
+
# -----------------------------------------------------------------------------
|
| 26 |
+
# Database (REQUIRED - use strong credentials)
|
| 27 |
+
# -----------------------------------------------------------------------------
|
| 28 |
+
DATABASE_URL=postgresql://tensorwall_user:STRONG_PASSWORD_HERE@db-host:5432/tensorwall
|
| 29 |
+
REDIS_URL=redis://:REDIS_PASSWORD@redis-host:6379/0
|
| 30 |
+
|
| 31 |
+
# -----------------------------------------------------------------------------
|
| 32 |
+
# JWT Authentication (REQUIRED - generate secure random key)
|
| 33 |
+
# Generate with: python -c "import secrets; print(secrets.token_urlsafe(64))"
|
| 34 |
+
# -----------------------------------------------------------------------------
|
| 35 |
+
JWT_SECRET_KEY=GENERATE_A_SECURE_RANDOM_KEY_64_CHARS_MINIMUM
|
| 36 |
+
JWT_ALGORITHM=HS256
|
| 37 |
+
ACCESS_TOKEN_EXPIRE_MINUTES=15
|
| 38 |
+
REFRESH_TOKEN_EXPIRE_DAYS=7
|
| 39 |
+
|
| 40 |
+
# -----------------------------------------------------------------------------
|
| 41 |
+
# Cookie Settings (REQUIRED for HTTPS)
|
| 42 |
+
# -----------------------------------------------------------------------------
|
| 43 |
+
COOKIE_SECURE=true
|
| 44 |
+
COOKIE_HTTPONLY=true
|
| 45 |
+
COOKIE_SAMESITE=lax
|
| 46 |
+
|
| 47 |
+
# -----------------------------------------------------------------------------
|
| 48 |
+
# LLM Provider URLs
|
| 49 |
+
# -----------------------------------------------------------------------------
|
| 50 |
+
OPENAI_API_URL=https://api.openai.com/v1
|
| 51 |
+
ANTHROPIC_API_URL=https://api.anthropic.com/v1
|
| 52 |
+
OLLAMA_API_URL=http://ollama-host:11434
|
| 53 |
+
|
| 54 |
+
# -----------------------------------------------------------------------------
|
| 55 |
+
# Audit & Privacy (GDPR compliant defaults)
|
| 56 |
+
# -----------------------------------------------------------------------------
|
| 57 |
+
AUDIT_RETENTION_DAYS=90
|
| 58 |
+
STORE_PROMPTS=false
|
| 59 |
+
|
| 60 |
+
# -----------------------------------------------------------------------------
|
| 61 |
+
# Email Alerts (Optional - for budget/security alerts)
|
| 62 |
+
# -----------------------------------------------------------------------------
|
| 63 |
+
SMTP_HOST=smtp.your-provider.com
|
| 64 |
+
SMTP_PORT=587
|
| 65 |
+
SMTP_USER=alerts@your-domain.com
|
| 66 |
+
SMTP_PASSWORD=SMTP_PASSWORD_HERE
|
| 67 |
+
ALERT_FROM_EMAIL=alerts@your-domain.com
|
| 68 |
+
|
| 69 |
+
# -----------------------------------------------------------------------------
|
| 70 |
+
# Gateway Performance
|
| 71 |
+
# -----------------------------------------------------------------------------
|
| 72 |
+
MAX_LATENCY_MS=50
|
| 73 |
+
DEFAULT_MAX_TOKENS=4096
|
| 74 |
+
DEFAULT_MAX_CONTEXT=128000
|
backend/Dockerfile
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
# Install system dependencies
|
| 6 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 7 |
+
gcc \
|
| 8 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 9 |
+
|
| 10 |
+
# Copy requirements first for dependency caching
|
| 11 |
+
COPY requirements.txt .
|
| 12 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 13 |
+
|
| 14 |
+
# Copy application into backend/ subdirectory to preserve import paths
|
| 15 |
+
COPY . ./backend/
|
| 16 |
+
|
| 17 |
+
# Production settings
|
| 18 |
+
ENV PYTHONUNBUFFERED=1
|
| 19 |
+
ENV PYTHONDONTWRITEBYTECODE=1
|
| 20 |
+
ENV PYTHONPATH=/app
|
| 21 |
+
|
| 22 |
+
# Health check
|
| 23 |
+
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
| 24 |
+
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health/live')" || exit 1
|
| 25 |
+
|
| 26 |
+
# Run with production settings
|
| 27 |
+
EXPOSE 8000
|
| 28 |
+
CMD ["uvicorn", "backend.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "2"]
|
backend/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LLM Governance Gateway
|
| 2 |
+
__version__ = "0.2.0"
|
backend/adapters/__init__.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Adapters Layer - Driven Adapters (implementations).
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Les Adapters implémentent les Ports (interfaces).
|
| 4 |
+
Implémentations natives utilisant directement les libs (httpx, SQLAlchemy, redis.asyncio).
|
| 5 |
+
|
| 6 |
+
Structure:
|
| 7 |
+
- llm/ : Adapters pour les providers LLM (OpenAI, Anthropic, etc.)
|
| 8 |
+
- postgres/ : Adapters pour les repositories PostgreSQL
|
| 9 |
+
- redis/ : Adapters pour le cache Redis
|
| 10 |
+
- audit/ : Adapters pour l'audit logging
|
| 11 |
+
- prometheus/ : Adapters pour les métriques Prometheus
|
| 12 |
+
- abuse/ : Adapters pour la détection d'abus
|
| 13 |
+
- feature/ : Adapters pour le registre de features
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from backend.adapters.llm import OpenAIAdapter, AnthropicAdapter, MockAdapter
|
| 17 |
+
from backend.adapters.postgres import PolicyRepositoryAdapter, BudgetRepositoryAdapter
|
| 18 |
+
from backend.adapters.redis import (
|
| 19 |
+
RedisCacheAdapter,
|
| 20 |
+
InMemoryCacheAdapter,
|
| 21 |
+
create_redis_cache_adapter,
|
| 22 |
+
)
|
| 23 |
+
from backend.adapters.audit import PostgresAuditAdapter, InMemoryAuditAdapter
|
| 24 |
+
from backend.adapters.prometheus import PrometheusMetricsAdapter, InMemoryMetricsAdapter
|
| 25 |
+
from backend.adapters.abuse import InMemoryAbuseAdapter
|
| 26 |
+
from backend.adapters.feature import InMemoryFeatureAdapter
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
__all__ = [
|
| 30 |
+
# LLM Adapters
|
| 31 |
+
"OpenAIAdapter",
|
| 32 |
+
"AnthropicAdapter",
|
| 33 |
+
"MockAdapter",
|
| 34 |
+
# Repository Adapters
|
| 35 |
+
"PolicyRepositoryAdapter",
|
| 36 |
+
"BudgetRepositoryAdapter",
|
| 37 |
+
# Cache Adapters
|
| 38 |
+
"RedisCacheAdapter",
|
| 39 |
+
"InMemoryCacheAdapter",
|
| 40 |
+
"create_redis_cache_adapter",
|
| 41 |
+
# Audit Adapters
|
| 42 |
+
"PostgresAuditAdapter",
|
| 43 |
+
"InMemoryAuditAdapter",
|
| 44 |
+
# Metrics Adapters
|
| 45 |
+
"PrometheusMetricsAdapter",
|
| 46 |
+
"InMemoryMetricsAdapter",
|
| 47 |
+
# Abuse Adapters
|
| 48 |
+
"InMemoryAbuseAdapter",
|
| 49 |
+
# Feature Adapters
|
| 50 |
+
"InMemoryFeatureAdapter",
|
| 51 |
+
]
|
backend/adapters/abuse/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Abuse Detection Adapters.
|
| 2 |
+
|
| 3 |
+
Adapters pour la détection d'abus:
|
| 4 |
+
- InMemoryAbuseAdapter: Pour les tests (sans Redis)
|
| 5 |
+
- RedisAbuseAdapter: Pour la production (avec Redis)
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from backend.adapters.abuse.in_memory_abuse_adapter import InMemoryAbuseAdapter
|
| 9 |
+
|
| 10 |
+
__all__ = [
|
| 11 |
+
"InMemoryAbuseAdapter",
|
| 12 |
+
]
|
backend/adapters/abuse/in_memory_abuse_adapter.py
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""InMemory Abuse Adapter - Implémentation native pour les tests.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Adapter natif qui implémente directement
|
| 4 |
+
l'interface AbuseDetectorPort sans dépendre de Redis.
|
| 5 |
+
Utile pour les tests unitaires et d'intégration.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from collections import defaultdict
|
| 9 |
+
from dataclasses import dataclass
|
| 10 |
+
import hashlib
|
| 11 |
+
import json
|
| 12 |
+
import time
|
| 13 |
+
|
| 14 |
+
from backend.ports.abuse_detector import (
|
| 15 |
+
AbuseDetectorPort,
|
| 16 |
+
AbuseCheckResult,
|
| 17 |
+
AbuseType,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@dataclass
|
| 22 |
+
class RequestSignature:
|
| 23 |
+
"""Signature d'une requête pour la déduplication."""
|
| 24 |
+
|
| 25 |
+
hash: str
|
| 26 |
+
timestamp: float
|
| 27 |
+
app_id: str
|
| 28 |
+
feature: str
|
| 29 |
+
model: str
|
| 30 |
+
input_hash: str
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class InMemoryAbuseAdapter(AbuseDetectorPort):
|
| 34 |
+
"""Adapter en mémoire pour la détection d'abus.
|
| 35 |
+
|
| 36 |
+
Implémentation sans Redis pour les tests. Stocke tout en mémoire.
|
| 37 |
+
Configurable pour simuler différents scénarios de blocage.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
# Patterns suspects dans le contenu
|
| 41 |
+
SUSPICIOUS_PATTERNS = [
|
| 42 |
+
"call yourself",
|
| 43 |
+
"repeat this request",
|
| 44 |
+
"call this api again",
|
| 45 |
+
"infinite loop",
|
| 46 |
+
"keep calling",
|
| 47 |
+
"recursive call",
|
| 48 |
+
]
|
| 49 |
+
|
| 50 |
+
def __init__(
|
| 51 |
+
self,
|
| 52 |
+
max_identical_requests: int = 5,
|
| 53 |
+
identical_request_window_seconds: int = 60,
|
| 54 |
+
max_errors_per_minute: int = 20,
|
| 55 |
+
max_requests_per_minute: int = 100,
|
| 56 |
+
dedup_window_seconds: int = 5,
|
| 57 |
+
cost_spike_multiplier: float = 10.0,
|
| 58 |
+
):
|
| 59 |
+
"""Initialise l'adapter.
|
| 60 |
+
|
| 61 |
+
Args:
|
| 62 |
+
max_identical_requests: Nombre max de requêtes identiques
|
| 63 |
+
identical_request_window_seconds: Fenêtre pour les requêtes identiques
|
| 64 |
+
max_errors_per_minute: Nombre max d'erreurs par minute
|
| 65 |
+
max_requests_per_minute: Nombre max de requêtes par minute
|
| 66 |
+
dedup_window_seconds: Fenêtre de déduplication
|
| 67 |
+
cost_spike_multiplier: Multiplicateur pour détecter les spikes de coût
|
| 68 |
+
"""
|
| 69 |
+
self.max_identical_requests = max_identical_requests
|
| 70 |
+
self.identical_request_window_seconds = identical_request_window_seconds
|
| 71 |
+
self.max_errors_per_minute = max_errors_per_minute
|
| 72 |
+
self.max_requests_per_minute = max_requests_per_minute
|
| 73 |
+
self.dedup_window_seconds = dedup_window_seconds
|
| 74 |
+
self.cost_spike_multiplier = cost_spike_multiplier
|
| 75 |
+
|
| 76 |
+
# Storage
|
| 77 |
+
self._signatures: dict[str, list[tuple[float, str]]] = defaultdict(list)
|
| 78 |
+
self._requests: dict[str, list[float]] = defaultdict(list)
|
| 79 |
+
self._errors: dict[str, list[float]] = defaultdict(list)
|
| 80 |
+
self._costs: dict[str, list[float]] = defaultdict(list)
|
| 81 |
+
self._blocked_until: dict[str, float] = {}
|
| 82 |
+
|
| 83 |
+
# Configurable blocks for testing
|
| 84 |
+
self._force_block: dict[str, AbuseCheckResult] = {}
|
| 85 |
+
|
| 86 |
+
def configure_block(self, app_id: str, result: AbuseCheckResult) -> None:
|
| 87 |
+
"""Configure un blocage forcé pour les tests.
|
| 88 |
+
|
| 89 |
+
Args:
|
| 90 |
+
app_id: Identifiant de l'application
|
| 91 |
+
result: Résultat à retourner (doit avoir blocked=True)
|
| 92 |
+
"""
|
| 93 |
+
if result.blocked:
|
| 94 |
+
self._force_block[app_id] = result
|
| 95 |
+
|
| 96 |
+
def clear_forced_blocks(self) -> None:
|
| 97 |
+
"""Efface tous les blocages forcés."""
|
| 98 |
+
self._force_block.clear()
|
| 99 |
+
|
| 100 |
+
async def check_request(
|
| 101 |
+
self,
|
| 102 |
+
app_id: str,
|
| 103 |
+
feature: str,
|
| 104 |
+
model: str,
|
| 105 |
+
messages: list[dict],
|
| 106 |
+
request_id: str | None = None,
|
| 107 |
+
) -> AbuseCheckResult:
|
| 108 |
+
"""Vérifie si une requête doit être bloquée pour abus."""
|
| 109 |
+
now = time.time()
|
| 110 |
+
|
| 111 |
+
# Check forced block (for testing)
|
| 112 |
+
if app_id in self._force_block:
|
| 113 |
+
return self._force_block[app_id]
|
| 114 |
+
|
| 115 |
+
# Check if currently blocked
|
| 116 |
+
blocked_result = self._check_blocked(app_id, now)
|
| 117 |
+
if blocked_result:
|
| 118 |
+
return blocked_result
|
| 119 |
+
|
| 120 |
+
# Generate request signature
|
| 121 |
+
signature = self._generate_signature(app_id, feature, model, messages)
|
| 122 |
+
|
| 123 |
+
# Check for duplicate/loop
|
| 124 |
+
loop_result = self._check_loop(app_id, signature, now)
|
| 125 |
+
if loop_result.blocked:
|
| 126 |
+
self._apply_cooldown(app_id, 30, now)
|
| 127 |
+
return loop_result
|
| 128 |
+
|
| 129 |
+
# Check rate spike
|
| 130 |
+
rate_result = self._check_rate_spike(app_id, now)
|
| 131 |
+
if rate_result.blocked:
|
| 132 |
+
self._apply_cooldown(app_id, 60, now)
|
| 133 |
+
return rate_result
|
| 134 |
+
|
| 135 |
+
# Check for self-reference patterns
|
| 136 |
+
self_ref_result = self._check_self_reference(messages)
|
| 137 |
+
if self_ref_result.blocked:
|
| 138 |
+
return self_ref_result
|
| 139 |
+
|
| 140 |
+
# Record this request
|
| 141 |
+
self._record_request(app_id, signature, now)
|
| 142 |
+
|
| 143 |
+
return AbuseCheckResult(blocked=False)
|
| 144 |
+
|
| 145 |
+
async def record_error(self, app_id: str) -> AbuseCheckResult:
|
| 146 |
+
"""Enregistre une erreur pour la détection de retry storm."""
|
| 147 |
+
now = time.time()
|
| 148 |
+
|
| 149 |
+
# Add error timestamp
|
| 150 |
+
self._errors[app_id].append(now)
|
| 151 |
+
|
| 152 |
+
# Remove old errors
|
| 153 |
+
cutoff = now - 60 # 1 minute window
|
| 154 |
+
self._errors[app_id] = [t for t in self._errors[app_id] if t > cutoff]
|
| 155 |
+
|
| 156 |
+
# Check if too many errors
|
| 157 |
+
error_count = len(self._errors[app_id])
|
| 158 |
+
if error_count > self.max_errors_per_minute:
|
| 159 |
+
self._apply_cooldown(app_id, 120, now)
|
| 160 |
+
return AbuseCheckResult(
|
| 161 |
+
blocked=True,
|
| 162 |
+
abuse_type=AbuseType.RETRY_STORM,
|
| 163 |
+
reason=f"Too many errors ({error_count}) in 60s window",
|
| 164 |
+
details={"error_count": error_count},
|
| 165 |
+
cooldown_seconds=120,
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
return AbuseCheckResult(blocked=False)
|
| 169 |
+
|
| 170 |
+
async def record_cost(self, app_id: str, cost: float) -> AbuseCheckResult:
|
| 171 |
+
"""Enregistre un coût pour la détection de cost spike."""
|
| 172 |
+
self._costs[app_id].append(cost)
|
| 173 |
+
|
| 174 |
+
# Keep only last 100 costs
|
| 175 |
+
if len(self._costs[app_id]) > 100:
|
| 176 |
+
self._costs[app_id] = self._costs[app_id][-100:]
|
| 177 |
+
|
| 178 |
+
costs = self._costs[app_id]
|
| 179 |
+
if len(costs) >= 10:
|
| 180 |
+
avg_cost = sum(costs[:-1]) / (len(costs) - 1)
|
| 181 |
+
if cost > avg_cost * self.cost_spike_multiplier and avg_cost > 0.001:
|
| 182 |
+
return AbuseCheckResult(
|
| 183 |
+
blocked=False, # Warning only, not blocking
|
| 184 |
+
abuse_type=AbuseType.COST_SPIKE,
|
| 185 |
+
reason=f"Cost spike detected: ${cost:.4f} vs avg ${avg_cost:.4f}",
|
| 186 |
+
details={
|
| 187 |
+
"current_cost": cost,
|
| 188 |
+
"average_cost": avg_cost,
|
| 189 |
+
"multiplier": cost / avg_cost if avg_cost > 0 else 0,
|
| 190 |
+
},
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
return AbuseCheckResult(blocked=False)
|
| 194 |
+
|
| 195 |
+
async def clear_app_data(self, app_id: str) -> None:
|
| 196 |
+
"""Efface toutes les données d'une application."""
|
| 197 |
+
self._signatures.pop(app_id, None)
|
| 198 |
+
self._requests.pop(app_id, None)
|
| 199 |
+
self._errors.pop(app_id, None)
|
| 200 |
+
self._costs.pop(app_id, None)
|
| 201 |
+
self._blocked_until.pop(app_id, None)
|
| 202 |
+
self._force_block.pop(app_id, None)
|
| 203 |
+
|
| 204 |
+
# Also clear signature keys that start with app_id
|
| 205 |
+
keys_to_remove = [
|
| 206 |
+
k for k in self._signatures.keys() if k.startswith(f"{app_id}:")
|
| 207 |
+
]
|
| 208 |
+
for key in keys_to_remove:
|
| 209 |
+
del self._signatures[key]
|
| 210 |
+
|
| 211 |
+
def clear_all(self) -> None:
|
| 212 |
+
"""Efface toutes les données (pour les tests)."""
|
| 213 |
+
self._signatures.clear()
|
| 214 |
+
self._requests.clear()
|
| 215 |
+
self._errors.clear()
|
| 216 |
+
self._costs.clear()
|
| 217 |
+
self._blocked_until.clear()
|
| 218 |
+
self._force_block.clear()
|
| 219 |
+
|
| 220 |
+
def _check_blocked(self, app_id: str, now: float) -> AbuseCheckResult | None:
|
| 221 |
+
"""Vérifie si l'application est actuellement bloquée."""
|
| 222 |
+
if app_id in self._blocked_until:
|
| 223 |
+
blocked_until = self._blocked_until[app_id]
|
| 224 |
+
if now < blocked_until:
|
| 225 |
+
remaining = int(blocked_until - now)
|
| 226 |
+
return AbuseCheckResult(
|
| 227 |
+
blocked=True,
|
| 228 |
+
abuse_type=AbuseType.SUSPICIOUS_PATTERN,
|
| 229 |
+
reason=f"Application temporarily blocked for {remaining}s",
|
| 230 |
+
cooldown_seconds=remaining,
|
| 231 |
+
)
|
| 232 |
+
else:
|
| 233 |
+
# Block expired
|
| 234 |
+
del self._blocked_until[app_id]
|
| 235 |
+
return None
|
| 236 |
+
|
| 237 |
+
def _check_loop(
|
| 238 |
+
self,
|
| 239 |
+
app_id: str,
|
| 240 |
+
signature: RequestSignature,
|
| 241 |
+
now: float,
|
| 242 |
+
) -> AbuseCheckResult:
|
| 243 |
+
"""Vérifie les boucles de requêtes."""
|
| 244 |
+
key = f"{app_id}:{signature.input_hash}"
|
| 245 |
+
|
| 246 |
+
# Remove old signatures
|
| 247 |
+
cutoff = now - self.identical_request_window_seconds
|
| 248 |
+
self._signatures[key] = [
|
| 249 |
+
(ts, h) for ts, h in self._signatures[key] if ts > cutoff
|
| 250 |
+
]
|
| 251 |
+
|
| 252 |
+
# Count identical requests
|
| 253 |
+
identical_count = len(self._signatures[key])
|
| 254 |
+
|
| 255 |
+
if identical_count >= self.max_identical_requests:
|
| 256 |
+
return AbuseCheckResult(
|
| 257 |
+
blocked=True,
|
| 258 |
+
abuse_type=AbuseType.LOOP_DETECTED,
|
| 259 |
+
reason=f"Identical request repeated {identical_count} times",
|
| 260 |
+
details={
|
| 261 |
+
"identical_count": identical_count,
|
| 262 |
+
"window_seconds": self.identical_request_window_seconds,
|
| 263 |
+
},
|
| 264 |
+
cooldown_seconds=30,
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
# Check for exact duplicates in short window
|
| 268 |
+
dedup_cutoff = now - self.dedup_window_seconds
|
| 269 |
+
recent = [ts for ts, _ in self._signatures[key] if ts > dedup_cutoff]
|
| 270 |
+
|
| 271 |
+
if len(recent) > 0:
|
| 272 |
+
return AbuseCheckResult(
|
| 273 |
+
blocked=True,
|
| 274 |
+
abuse_type=AbuseType.DUPLICATE_REQUEST,
|
| 275 |
+
reason=f"Duplicate request within {self.dedup_window_seconds}s",
|
| 276 |
+
details={"dedup_window": self.dedup_window_seconds},
|
| 277 |
+
cooldown_seconds=5,
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
return AbuseCheckResult(blocked=False)
|
| 281 |
+
|
| 282 |
+
def _check_rate_spike(self, app_id: str, now: float) -> AbuseCheckResult:
|
| 283 |
+
"""Vérifie les augmentations soudaines de trafic."""
|
| 284 |
+
# Remove old requests
|
| 285 |
+
minute_ago = now - 60
|
| 286 |
+
self._requests[app_id] = [t for t in self._requests[app_id] if t > minute_ago]
|
| 287 |
+
|
| 288 |
+
recent_count = len(self._requests[app_id])
|
| 289 |
+
|
| 290 |
+
# Use >= because the current request hasn't been recorded yet
|
| 291 |
+
if recent_count >= self.max_requests_per_minute:
|
| 292 |
+
return AbuseCheckResult(
|
| 293 |
+
blocked=True,
|
| 294 |
+
abuse_type=AbuseType.RATE_SPIKE,
|
| 295 |
+
reason=f"Rate limit exceeded: {recent_count}/min > {self.max_requests_per_minute}/min",
|
| 296 |
+
details={
|
| 297 |
+
"current_rate": recent_count,
|
| 298 |
+
"limit": self.max_requests_per_minute,
|
| 299 |
+
},
|
| 300 |
+
cooldown_seconds=60,
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
return AbuseCheckResult(blocked=False)
|
| 304 |
+
|
| 305 |
+
def _check_self_reference(self, messages: list[dict]) -> AbuseCheckResult:
|
| 306 |
+
"""Vérifie les patterns de self-référence."""
|
| 307 |
+
for msg in messages:
|
| 308 |
+
content = msg.get("content", "").lower()
|
| 309 |
+
for pattern in self.SUSPICIOUS_PATTERNS:
|
| 310 |
+
if pattern in content:
|
| 311 |
+
return AbuseCheckResult(
|
| 312 |
+
blocked=True,
|
| 313 |
+
abuse_type=AbuseType.SELF_REFERENCE,
|
| 314 |
+
reason=f"Self-referencing pattern detected: '{pattern}'",
|
| 315 |
+
details={"pattern": pattern},
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
return AbuseCheckResult(blocked=False)
|
| 319 |
+
|
| 320 |
+
def _generate_signature(
|
| 321 |
+
self,
|
| 322 |
+
app_id: str,
|
| 323 |
+
feature: str,
|
| 324 |
+
model: str,
|
| 325 |
+
messages: list[dict],
|
| 326 |
+
) -> RequestSignature:
|
| 327 |
+
"""Génère une signature pour une requête."""
|
| 328 |
+
content = json.dumps(messages, sort_keys=True)
|
| 329 |
+
input_hash = hashlib.sha256(content.encode()).hexdigest()[:16]
|
| 330 |
+
|
| 331 |
+
full_hash = hashlib.sha256(
|
| 332 |
+
f"{app_id}:{feature}:{model}:{input_hash}".encode()
|
| 333 |
+
).hexdigest()[:16]
|
| 334 |
+
|
| 335 |
+
return RequestSignature(
|
| 336 |
+
hash=full_hash,
|
| 337 |
+
timestamp=time.time(),
|
| 338 |
+
app_id=app_id,
|
| 339 |
+
feature=feature,
|
| 340 |
+
model=model,
|
| 341 |
+
input_hash=input_hash,
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
def _record_request(
|
| 345 |
+
self,
|
| 346 |
+
app_id: str,
|
| 347 |
+
signature: RequestSignature,
|
| 348 |
+
now: float,
|
| 349 |
+
) -> None:
|
| 350 |
+
"""Enregistre une requête."""
|
| 351 |
+
# Record signature
|
| 352 |
+
key = f"{app_id}:{signature.input_hash}"
|
| 353 |
+
self._signatures[key].append((now, signature.hash))
|
| 354 |
+
|
| 355 |
+
# Record request timestamp
|
| 356 |
+
self._requests[app_id].append(now)
|
| 357 |
+
|
| 358 |
+
def _apply_cooldown(self, app_id: str, seconds: int, now: float) -> None:
|
| 359 |
+
"""Applique un cooldown à une application."""
|
| 360 |
+
self._blocked_until[app_id] = now + seconds
|
| 361 |
+
|
| 362 |
+
# Test helpers
|
| 363 |
+
def get_request_count(self, app_id: str) -> int:
|
| 364 |
+
"""Retourne le nombre de requêtes enregistrées."""
|
| 365 |
+
return len(self._requests.get(app_id, []))
|
| 366 |
+
|
| 367 |
+
def get_error_count(self, app_id: str) -> int:
|
| 368 |
+
"""Retourne le nombre d'erreurs enregistrées."""
|
| 369 |
+
return len(self._errors.get(app_id, []))
|
| 370 |
+
|
| 371 |
+
def is_blocked(self, app_id: str) -> bool:
|
| 372 |
+
"""Vérifie si l'application est bloquée."""
|
| 373 |
+
if app_id in self._blocked_until:
|
| 374 |
+
return time.time() < self._blocked_until[app_id]
|
| 375 |
+
return app_id in self._force_block
|
backend/adapters/audit/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Audit Adapters - Implémentations natives.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Ces adapters implémentent le Port AuditLogPort
|
| 4 |
+
en utilisant directement SQLAlchemy ou des structures en mémoire.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from backend.adapters.audit.postgres_audit_adapter import (
|
| 8 |
+
PostgresAuditAdapter,
|
| 9 |
+
InMemoryAuditAdapter,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
__all__ = [
|
| 14 |
+
"PostgresAuditAdapter",
|
| 15 |
+
"InMemoryAuditAdapter",
|
| 16 |
+
]
|
backend/adapters/audit/postgres_audit_adapter.py
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Audit Adapters - Implémentations natives.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Adapters natifs qui implémentent directement
|
| 4 |
+
l'interface AuditLogPort en utilisant SQLAlchemy ou en mémoire.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
from typing import Any
|
| 9 |
+
from sqlalchemy import select, and_
|
| 10 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 11 |
+
|
| 12 |
+
from backend.ports.audit_log import AuditLogPort, AuditEntry
|
| 13 |
+
from backend.db.models import AuditLog as DBAuditLog, AuditEventType as DBAuditEventType
|
| 14 |
+
from backend.db.session import get_db_context
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class PostgresAuditAdapter(AuditLogPort):
|
| 18 |
+
"""Adapter natif pour l'audit log en PostgreSQL.
|
| 19 |
+
|
| 20 |
+
Implémente directement l'interface AuditLogPort en utilisant
|
| 21 |
+
SQLAlchemy pour les opérations de base de données.
|
| 22 |
+
Aucune dépendance au code legacy (audit/).
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
def __init__(self, session: AsyncSession | None = None):
|
| 26 |
+
"""Initialise l'adapter.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
session: Session SQLAlchemy optionnelle. Si non fournie,
|
| 30 |
+
une nouvelle session sera créée pour chaque opération.
|
| 31 |
+
"""
|
| 32 |
+
self._session = session
|
| 33 |
+
|
| 34 |
+
def _to_db(self, entry: AuditEntry) -> dict[str, Any]:
|
| 35 |
+
"""Convertit une AuditEntry vers les valeurs pour SQLAlchemy.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
entry: Entrée d'audit du domaine
|
| 39 |
+
|
| 40 |
+
Returns:
|
| 41 |
+
Dict des valeurs pour créer le modèle DB
|
| 42 |
+
"""
|
| 43 |
+
# Map event_type to DB enum
|
| 44 |
+
event_type_map = {
|
| 45 |
+
"llm_request": DBAuditEventType.REQUEST,
|
| 46 |
+
"request": DBAuditEventType.REQUEST,
|
| 47 |
+
"response": DBAuditEventType.RESPONSE,
|
| 48 |
+
"policy_decision": DBAuditEventType.POLICY_DECISION,
|
| 49 |
+
"budget_check": DBAuditEventType.BUDGET_CHECK,
|
| 50 |
+
"security_check": DBAuditEventType.SECURITY_CHECK,
|
| 51 |
+
"error": DBAuditEventType.ERROR,
|
| 52 |
+
}
|
| 53 |
+
db_event_type = event_type_map.get(entry.event_type, DBAuditEventType.REQUEST)
|
| 54 |
+
|
| 55 |
+
return {
|
| 56 |
+
"event_type": db_event_type,
|
| 57 |
+
"request_id": entry.request_id,
|
| 58 |
+
"app_id": entry.app_id,
|
| 59 |
+
"owner": entry.user_id,
|
| 60 |
+
"model": entry.model,
|
| 61 |
+
"policy_decision": entry.action,
|
| 62 |
+
"policy_reason": entry.details.get("policy_reasons", []),
|
| 63 |
+
"blocked": entry.outcome in ("denied_policy", "denied_budget", "blocked"),
|
| 64 |
+
"extra_data": {
|
| 65 |
+
"org_id": entry.org_id,
|
| 66 |
+
"outcome": entry.outcome,
|
| 67 |
+
"duration_ms": entry.duration_ms,
|
| 68 |
+
"input_tokens": entry.input_tokens,
|
| 69 |
+
"output_tokens": entry.output_tokens,
|
| 70 |
+
"cost_usd": entry.cost_usd,
|
| 71 |
+
**entry.details,
|
| 72 |
+
},
|
| 73 |
+
"timestamp": entry.timestamp,
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
def _from_db(self, db_audit: DBAuditLog) -> AuditEntry:
|
| 77 |
+
"""Convertit un modèle SQLAlchemy vers le domaine.
|
| 78 |
+
|
| 79 |
+
Args:
|
| 80 |
+
db_audit: Modèle SQLAlchemy AuditLog
|
| 81 |
+
|
| 82 |
+
Returns:
|
| 83 |
+
Entité domain AuditEntry
|
| 84 |
+
"""
|
| 85 |
+
extra_data = db_audit.extra_data or {}
|
| 86 |
+
|
| 87 |
+
return AuditEntry(
|
| 88 |
+
event_type=db_audit.event_type.value,
|
| 89 |
+
request_id=db_audit.request_id or "",
|
| 90 |
+
app_id=db_audit.app_id or "",
|
| 91 |
+
org_id=extra_data.get("org_id"),
|
| 92 |
+
user_id=db_audit.owner,
|
| 93 |
+
model=db_audit.model,
|
| 94 |
+
action=db_audit.policy_decision,
|
| 95 |
+
outcome=extra_data.get("outcome"),
|
| 96 |
+
details={
|
| 97 |
+
"environment": db_audit.environment,
|
| 98 |
+
"feature": db_audit.feature,
|
| 99 |
+
"policy_reason": db_audit.policy_reason,
|
| 100 |
+
"security_issues": db_audit.security_issues,
|
| 101 |
+
"error": db_audit.error,
|
| 102 |
+
},
|
| 103 |
+
timestamp=db_audit.timestamp,
|
| 104 |
+
duration_ms=extra_data.get("duration_ms"),
|
| 105 |
+
input_tokens=extra_data.get("input_tokens"),
|
| 106 |
+
output_tokens=extra_data.get("output_tokens"),
|
| 107 |
+
cost_usd=extra_data.get("cost_usd"),
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
async def log(self, entry: AuditEntry) -> None:
|
| 111 |
+
"""Enregistre une entrée d'audit.
|
| 112 |
+
|
| 113 |
+
Args:
|
| 114 |
+
entry: L'entrée d'audit à enregistrer
|
| 115 |
+
"""
|
| 116 |
+
async with self._get_session() as session:
|
| 117 |
+
values = self._to_db(entry)
|
| 118 |
+
db_audit = DBAuditLog(**values)
|
| 119 |
+
session.add(db_audit)
|
| 120 |
+
await session.flush()
|
| 121 |
+
|
| 122 |
+
async def log_request(
|
| 123 |
+
self,
|
| 124 |
+
request_id: str,
|
| 125 |
+
app_id: str,
|
| 126 |
+
model: str,
|
| 127 |
+
outcome: str,
|
| 128 |
+
details: dict[str, Any] | None = None,
|
| 129 |
+
) -> None:
|
| 130 |
+
"""Enregistre une requête LLM.
|
| 131 |
+
|
| 132 |
+
Args:
|
| 133 |
+
request_id: Identifiant de la requête
|
| 134 |
+
app_id: Identifiant de l'application
|
| 135 |
+
model: Modèle utilisé
|
| 136 |
+
outcome: Résultat (allowed, denied, etc.)
|
| 137 |
+
details: Détails supplémentaires
|
| 138 |
+
"""
|
| 139 |
+
entry = AuditEntry(
|
| 140 |
+
event_type="request",
|
| 141 |
+
request_id=request_id,
|
| 142 |
+
app_id=app_id,
|
| 143 |
+
model=model,
|
| 144 |
+
outcome=outcome,
|
| 145 |
+
details=details or {},
|
| 146 |
+
)
|
| 147 |
+
await self.log(entry)
|
| 148 |
+
|
| 149 |
+
async def log_policy_decision(
|
| 150 |
+
self,
|
| 151 |
+
request_id: str,
|
| 152 |
+
app_id: str,
|
| 153 |
+
policy_id: str,
|
| 154 |
+
action: str,
|
| 155 |
+
reason: str,
|
| 156 |
+
) -> None:
|
| 157 |
+
"""Enregistre une décision de policy.
|
| 158 |
+
|
| 159 |
+
Args:
|
| 160 |
+
request_id: Identifiant de la requête
|
| 161 |
+
app_id: Identifiant de l'application
|
| 162 |
+
policy_id: Identifiant de la policy
|
| 163 |
+
action: Action prise (allow, warn, deny)
|
| 164 |
+
reason: Raison de la décision
|
| 165 |
+
"""
|
| 166 |
+
entry = AuditEntry(
|
| 167 |
+
event_type="policy_decision",
|
| 168 |
+
request_id=request_id,
|
| 169 |
+
app_id=app_id,
|
| 170 |
+
action=action,
|
| 171 |
+
details={
|
| 172 |
+
"policy_id": policy_id,
|
| 173 |
+
"reason": reason,
|
| 174 |
+
},
|
| 175 |
+
)
|
| 176 |
+
await self.log(entry)
|
| 177 |
+
|
| 178 |
+
async def get_entries(
|
| 179 |
+
self,
|
| 180 |
+
app_id: str | None = None,
|
| 181 |
+
org_id: str | None = None,
|
| 182 |
+
event_type: str | None = None,
|
| 183 |
+
start_time: datetime | None = None,
|
| 184 |
+
end_time: datetime | None = None,
|
| 185 |
+
limit: int = 100,
|
| 186 |
+
) -> list[AuditEntry]:
|
| 187 |
+
"""Récupère les entrées d'audit filtrées.
|
| 188 |
+
|
| 189 |
+
Args:
|
| 190 |
+
app_id: Filtrer par application
|
| 191 |
+
org_id: Filtrer par organisation (dans extra_data)
|
| 192 |
+
event_type: Filtrer par type d'événement
|
| 193 |
+
start_time: Date de début
|
| 194 |
+
end_time: Date de fin
|
| 195 |
+
limit: Nombre maximum d'entrées
|
| 196 |
+
|
| 197 |
+
Returns:
|
| 198 |
+
Liste des entrées d'audit
|
| 199 |
+
"""
|
| 200 |
+
async with self._get_session() as session:
|
| 201 |
+
query = select(DBAuditLog)
|
| 202 |
+
|
| 203 |
+
# Build filters
|
| 204 |
+
filters = []
|
| 205 |
+
|
| 206 |
+
if app_id:
|
| 207 |
+
filters.append(DBAuditLog.app_id == app_id)
|
| 208 |
+
|
| 209 |
+
if event_type:
|
| 210 |
+
event_type_map = {
|
| 211 |
+
"request": DBAuditEventType.REQUEST,
|
| 212 |
+
"response": DBAuditEventType.RESPONSE,
|
| 213 |
+
"policy_decision": DBAuditEventType.POLICY_DECISION,
|
| 214 |
+
"budget_check": DBAuditEventType.BUDGET_CHECK,
|
| 215 |
+
"security_check": DBAuditEventType.SECURITY_CHECK,
|
| 216 |
+
"error": DBAuditEventType.ERROR,
|
| 217 |
+
}
|
| 218 |
+
if event_type in event_type_map:
|
| 219 |
+
filters.append(DBAuditLog.event_type == event_type_map[event_type])
|
| 220 |
+
|
| 221 |
+
if start_time:
|
| 222 |
+
filters.append(DBAuditLog.timestamp >= start_time)
|
| 223 |
+
|
| 224 |
+
if end_time:
|
| 225 |
+
filters.append(DBAuditLog.timestamp <= end_time)
|
| 226 |
+
|
| 227 |
+
if filters:
|
| 228 |
+
query = query.where(and_(*filters))
|
| 229 |
+
|
| 230 |
+
# Order and limit
|
| 231 |
+
query = query.order_by(DBAuditLog.timestamp.desc()).limit(limit)
|
| 232 |
+
|
| 233 |
+
result = await session.execute(query)
|
| 234 |
+
db_entries = result.scalars().all()
|
| 235 |
+
|
| 236 |
+
entries = [self._from_db(entry) for entry in db_entries]
|
| 237 |
+
|
| 238 |
+
# Filter by org_id if specified (stored in extra_data)
|
| 239 |
+
if org_id:
|
| 240 |
+
entries = [e for e in entries if e.org_id == org_id]
|
| 241 |
+
|
| 242 |
+
return entries
|
| 243 |
+
|
| 244 |
+
def _get_session(self):
|
| 245 |
+
"""Retourne une session SQLAlchemy (context manager async).
|
| 246 |
+
|
| 247 |
+
Si une session a été fournie au constructeur, l'utilise.
|
| 248 |
+
Sinon, crée une nouvelle session via le context manager.
|
| 249 |
+
"""
|
| 250 |
+
if self._session:
|
| 251 |
+
return _SessionWrapper(self._session)
|
| 252 |
+
else:
|
| 253 |
+
return get_db_context()
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
class _SessionWrapper:
|
| 257 |
+
"""Wrapper pour utiliser une session existante comme context manager."""
|
| 258 |
+
|
| 259 |
+
def __init__(self, session: AsyncSession):
|
| 260 |
+
self._session = session
|
| 261 |
+
|
| 262 |
+
async def __aenter__(self):
|
| 263 |
+
return self._session
|
| 264 |
+
|
| 265 |
+
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
| 266 |
+
# Ne pas fermer la session fournie
|
| 267 |
+
pass
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
class InMemoryAuditAdapter(AuditLogPort):
|
| 271 |
+
"""Adapter en mémoire pour l'audit log (pour les tests).
|
| 272 |
+
|
| 273 |
+
Stocke les entrées d'audit en mémoire sans persistance.
|
| 274 |
+
Utile pour les tests unitaires et d'intégration.
|
| 275 |
+
"""
|
| 276 |
+
|
| 277 |
+
def __init__(self):
|
| 278 |
+
"""Initialise l'adapter avec un stockage vide."""
|
| 279 |
+
self._entries: list[AuditEntry] = []
|
| 280 |
+
|
| 281 |
+
async def log(self, entry: AuditEntry) -> None:
|
| 282 |
+
"""Enregistre une entrée d'audit en mémoire.
|
| 283 |
+
|
| 284 |
+
Args:
|
| 285 |
+
entry: L'entrée d'audit à enregistrer
|
| 286 |
+
"""
|
| 287 |
+
self._entries.append(entry)
|
| 288 |
+
|
| 289 |
+
async def log_request(
|
| 290 |
+
self,
|
| 291 |
+
request_id: str,
|
| 292 |
+
app_id: str,
|
| 293 |
+
model: str,
|
| 294 |
+
outcome: str,
|
| 295 |
+
details: dict[str, Any] | None = None,
|
| 296 |
+
) -> None:
|
| 297 |
+
"""Enregistre une requête LLM.
|
| 298 |
+
|
| 299 |
+
Args:
|
| 300 |
+
request_id: Identifiant de la requête
|
| 301 |
+
app_id: Identifiant de l'application
|
| 302 |
+
model: Modèle utilisé
|
| 303 |
+
outcome: Résultat (allowed, denied, etc.)
|
| 304 |
+
details: Détails supplémentaires
|
| 305 |
+
"""
|
| 306 |
+
entry = AuditEntry(
|
| 307 |
+
event_type="request",
|
| 308 |
+
request_id=request_id,
|
| 309 |
+
app_id=app_id,
|
| 310 |
+
model=model,
|
| 311 |
+
outcome=outcome,
|
| 312 |
+
details=details or {},
|
| 313 |
+
)
|
| 314 |
+
await self.log(entry)
|
| 315 |
+
|
| 316 |
+
async def log_policy_decision(
|
| 317 |
+
self,
|
| 318 |
+
request_id: str,
|
| 319 |
+
app_id: str,
|
| 320 |
+
policy_id: str,
|
| 321 |
+
action: str,
|
| 322 |
+
reason: str,
|
| 323 |
+
) -> None:
|
| 324 |
+
"""Enregistre une décision de policy.
|
| 325 |
+
|
| 326 |
+
Args:
|
| 327 |
+
request_id: Identifiant de la requête
|
| 328 |
+
app_id: Identifiant de l'application
|
| 329 |
+
policy_id: Identifiant de la policy
|
| 330 |
+
action: Action prise (allow, warn, deny)
|
| 331 |
+
reason: Raison de la décision
|
| 332 |
+
"""
|
| 333 |
+
entry = AuditEntry(
|
| 334 |
+
event_type="policy_decision",
|
| 335 |
+
request_id=request_id,
|
| 336 |
+
app_id=app_id,
|
| 337 |
+
action=action,
|
| 338 |
+
details={
|
| 339 |
+
"policy_id": policy_id,
|
| 340 |
+
"reason": reason,
|
| 341 |
+
},
|
| 342 |
+
)
|
| 343 |
+
await self.log(entry)
|
| 344 |
+
|
| 345 |
+
async def get_entries(
|
| 346 |
+
self,
|
| 347 |
+
app_id: str | None = None,
|
| 348 |
+
org_id: str | None = None,
|
| 349 |
+
event_type: str | None = None,
|
| 350 |
+
start_time: datetime | None = None,
|
| 351 |
+
end_time: datetime | None = None,
|
| 352 |
+
limit: int = 100,
|
| 353 |
+
) -> list[AuditEntry]:
|
| 354 |
+
"""Récupère les entrées d'audit filtrées.
|
| 355 |
+
|
| 356 |
+
Args:
|
| 357 |
+
app_id: Filtrer par application
|
| 358 |
+
org_id: Filtrer par organisation
|
| 359 |
+
event_type: Filtrer par type d'événement
|
| 360 |
+
start_time: Date de début
|
| 361 |
+
end_time: Date de fin
|
| 362 |
+
limit: Nombre maximum d'entrées
|
| 363 |
+
|
| 364 |
+
Returns:
|
| 365 |
+
Liste des entrées d'audit
|
| 366 |
+
"""
|
| 367 |
+
entries = self._entries.copy()
|
| 368 |
+
|
| 369 |
+
# Apply filters
|
| 370 |
+
if app_id:
|
| 371 |
+
entries = [e for e in entries if e.app_id == app_id]
|
| 372 |
+
|
| 373 |
+
if org_id:
|
| 374 |
+
entries = [e for e in entries if e.org_id == org_id]
|
| 375 |
+
|
| 376 |
+
if event_type:
|
| 377 |
+
entries = [e for e in entries if e.event_type == event_type]
|
| 378 |
+
|
| 379 |
+
if start_time:
|
| 380 |
+
entries = [e for e in entries if e.timestamp >= start_time]
|
| 381 |
+
|
| 382 |
+
if end_time:
|
| 383 |
+
entries = [e for e in entries if e.timestamp <= end_time]
|
| 384 |
+
|
| 385 |
+
# Sort by timestamp descending and limit
|
| 386 |
+
entries.sort(key=lambda e: e.timestamp, reverse=True)
|
| 387 |
+
|
| 388 |
+
return entries[:limit]
|
| 389 |
+
|
| 390 |
+
def clear(self) -> None:
|
| 391 |
+
"""Vide toutes les entrées d'audit."""
|
| 392 |
+
self._entries.clear()
|
| 393 |
+
|
| 394 |
+
@property
|
| 395 |
+
def entries(self) -> list[AuditEntry]:
|
| 396 |
+
"""Accès direct aux entrées pour les tests."""
|
| 397 |
+
return self._entries
|
backend/adapters/cache/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Cache module for TensorWall."""
|
| 2 |
+
|
| 3 |
+
from backend.adapters.cache.redis_client import (
|
| 4 |
+
get_redis,
|
| 5 |
+
init_redis,
|
| 6 |
+
close_redis,
|
| 7 |
+
RedisCache,
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
__all__ = [
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Redis client for caching and rate limiting."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from typing import Optional, Any
|
| 5 |
+
import redis.asyncio as redis
|
| 6 |
+
|
| 7 |
+
from backend.core.config import settings
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
# Global Redis connection pool
|
| 11 |
+
_redis_pool: Optional[redis.Redis] = None
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
async def init_redis() -> redis.Redis:
|
| 15 |
+
"""Initialize Redis connection pool."""
|
| 16 |
+
global _redis_pool
|
| 17 |
+
if _redis_pool is None:
|
| 18 |
+
_redis_pool = redis.from_url(
|
| 19 |
+
settings.redis_url,
|
| 20 |
+
encoding="utf-8",
|
| 21 |
+
decode_responses=True,
|
| 22 |
+
)
|
| 23 |
+
return _redis_pool
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
async def get_redis() -> redis.Redis:
|
| 27 |
+
"""Get Redis connection."""
|
| 28 |
+
if _redis_pool is None:
|
| 29 |
+
await init_redis()
|
| 30 |
+
return _redis_pool
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
async def close_redis() -> None:
|
| 34 |
+
"""Close Redis connection pool."""
|
| 35 |
+
global _redis_pool
|
| 36 |
+
if _redis_pool:
|
| 37 |
+
await _redis_pool.close()
|
| 38 |
+
_redis_pool = None
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class RedisCache:
|
| 42 |
+
"""High-level cache operations."""
|
| 43 |
+
|
| 44 |
+
# Key prefixes
|
| 45 |
+
PREFIX_CREDENTIALS = "creds:"
|
| 46 |
+
PREFIX_BUDGET = "budget:"
|
| 47 |
+
PREFIX_RATE_LIMIT = "rate:"
|
| 48 |
+
PREFIX_POLICY = "policy:"
|
| 49 |
+
|
| 50 |
+
def __init__(self, redis_client: redis.Redis):
|
| 51 |
+
self.redis = redis_client
|
| 52 |
+
|
| 53 |
+
# =========================================================================
|
| 54 |
+
# Credentials Cache
|
| 55 |
+
# =========================================================================
|
| 56 |
+
|
| 57 |
+
async def get_credentials(self, api_key_hash: str) -> Optional[dict]:
|
| 58 |
+
"""Get cached credentials by API key hash."""
|
| 59 |
+
key = f"{self.PREFIX_CREDENTIALS}{api_key_hash}"
|
| 60 |
+
data = await self.redis.get(key)
|
| 61 |
+
if data:
|
| 62 |
+
return json.loads(data)
|
| 63 |
+
return None
|
| 64 |
+
|
| 65 |
+
async def set_credentials(
|
| 66 |
+
self,
|
| 67 |
+
api_key_hash: str,
|
| 68 |
+
credentials: dict,
|
| 69 |
+
ttl_seconds: int = 300, # 5 minutes
|
| 70 |
+
) -> None:
|
| 71 |
+
"""Cache credentials."""
|
| 72 |
+
key = f"{self.PREFIX_CREDENTIALS}{api_key_hash}"
|
| 73 |
+
await self.redis.setex(key, ttl_seconds, json.dumps(credentials))
|
| 74 |
+
|
| 75 |
+
async def invalidate_credentials(self, api_key_hash: str) -> None:
|
| 76 |
+
"""Invalidate cached credentials."""
|
| 77 |
+
key = f"{self.PREFIX_CREDENTIALS}{api_key_hash}"
|
| 78 |
+
await self.redis.delete(key)
|
| 79 |
+
|
| 80 |
+
# =========================================================================
|
| 81 |
+
# Budget Tracking
|
| 82 |
+
# =========================================================================
|
| 83 |
+
|
| 84 |
+
async def get_budget_spend(
|
| 85 |
+
self,
|
| 86 |
+
app_id: str,
|
| 87 |
+
feature: Optional[str] = None,
|
| 88 |
+
environment: Optional[str] = None,
|
| 89 |
+
) -> float:
|
| 90 |
+
"""Get current budget spend from cache."""
|
| 91 |
+
key = self._budget_key(app_id, feature, environment)
|
| 92 |
+
spend = await self.redis.get(key)
|
| 93 |
+
return float(spend) if spend else 0.0
|
| 94 |
+
|
| 95 |
+
async def increment_budget_spend(
|
| 96 |
+
self,
|
| 97 |
+
app_id: str,
|
| 98 |
+
amount: float,
|
| 99 |
+
feature: Optional[str] = None,
|
| 100 |
+
environment: Optional[str] = None,
|
| 101 |
+
ttl_seconds: int = 86400 * 31, # 31 days
|
| 102 |
+
) -> float:
|
| 103 |
+
"""Increment budget spend and return new total."""
|
| 104 |
+
key = self._budget_key(app_id, feature, environment)
|
| 105 |
+
|
| 106 |
+
# Use INCRBYFLOAT for atomic increment
|
| 107 |
+
# Convert to cents for precision
|
| 108 |
+
amount_cents = int(amount * 100)
|
| 109 |
+
new_cents = await self.redis.incrbyfloat(key, amount_cents)
|
| 110 |
+
|
| 111 |
+
# Set TTL if key is new
|
| 112 |
+
ttl = await self.redis.ttl(key)
|
| 113 |
+
if ttl == -1: # No expiry set
|
| 114 |
+
await self.redis.expire(key, ttl_seconds)
|
| 115 |
+
|
| 116 |
+
return float(new_cents) / 100
|
| 117 |
+
|
| 118 |
+
async def reset_budget_spend(
|
| 119 |
+
self,
|
| 120 |
+
app_id: str,
|
| 121 |
+
feature: Optional[str] = None,
|
| 122 |
+
environment: Optional[str] = None,
|
| 123 |
+
) -> None:
|
| 124 |
+
"""Reset budget spend to zero."""
|
| 125 |
+
key = self._budget_key(app_id, feature, environment)
|
| 126 |
+
await self.redis.delete(key)
|
| 127 |
+
|
| 128 |
+
def _budget_key(
|
| 129 |
+
self,
|
| 130 |
+
app_id: str,
|
| 131 |
+
feature: Optional[str],
|
| 132 |
+
environment: Optional[str],
|
| 133 |
+
) -> str:
|
| 134 |
+
"""Build budget cache key."""
|
| 135 |
+
parts = [self.PREFIX_BUDGET, app_id]
|
| 136 |
+
if feature:
|
| 137 |
+
parts.append(feature)
|
| 138 |
+
if environment:
|
| 139 |
+
parts.append(environment)
|
| 140 |
+
return ":".join(parts)
|
| 141 |
+
|
| 142 |
+
# =========================================================================
|
| 143 |
+
# Rate Limiting
|
| 144 |
+
# =========================================================================
|
| 145 |
+
|
| 146 |
+
async def check_rate_limit(
|
| 147 |
+
self,
|
| 148 |
+
identifier: str,
|
| 149 |
+
limit: int,
|
| 150 |
+
window_seconds: int = 60,
|
| 151 |
+
) -> tuple[bool, int, int]:
|
| 152 |
+
"""
|
| 153 |
+
Check rate limit using sliding window.
|
| 154 |
+
Returns: (allowed, current_count, remaining)
|
| 155 |
+
"""
|
| 156 |
+
key = f"{self.PREFIX_RATE_LIMIT}{identifier}"
|
| 157 |
+
|
| 158 |
+
# Use Redis pipeline for atomic operations
|
| 159 |
+
pipe = self.redis.pipeline()
|
| 160 |
+
|
| 161 |
+
# Increment counter
|
| 162 |
+
pipe.incr(key)
|
| 163 |
+
# Set expiry if new key
|
| 164 |
+
pipe.expire(key, window_seconds, nx=True)
|
| 165 |
+
# Get TTL
|
| 166 |
+
pipe.ttl(key)
|
| 167 |
+
|
| 168 |
+
results = await pipe.execute()
|
| 169 |
+
current_count = results[0]
|
| 170 |
+
# results[2] is TTL, not needed here
|
| 171 |
+
|
| 172 |
+
allowed = current_count <= limit
|
| 173 |
+
remaining = max(0, limit - current_count)
|
| 174 |
+
|
| 175 |
+
return allowed, current_count, remaining
|
| 176 |
+
|
| 177 |
+
async def get_rate_limit_status(
|
| 178 |
+
self,
|
| 179 |
+
identifier: str,
|
| 180 |
+
limit: int,
|
| 181 |
+
) -> dict:
|
| 182 |
+
"""Get current rate limit status."""
|
| 183 |
+
key = f"{self.PREFIX_RATE_LIMIT}{identifier}"
|
| 184 |
+
|
| 185 |
+
pipe = self.redis.pipeline()
|
| 186 |
+
pipe.get(key)
|
| 187 |
+
pipe.ttl(key)
|
| 188 |
+
results = await pipe.execute()
|
| 189 |
+
|
| 190 |
+
current_count = int(results[0]) if results[0] else 0
|
| 191 |
+
ttl = results[1] if results[1] > 0 else 0
|
| 192 |
+
|
| 193 |
+
return {
|
| 194 |
+
"current": current_count,
|
| 195 |
+
"limit": limit,
|
| 196 |
+
"remaining": max(0, limit - current_count),
|
| 197 |
+
"reset_in_seconds": ttl,
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
# =========================================================================
|
| 201 |
+
# Policy Cache
|
| 202 |
+
# =========================================================================
|
| 203 |
+
|
| 204 |
+
async def get_policies(self, app_id: str) -> Optional[list[dict]]:
|
| 205 |
+
"""Get cached policies for an application."""
|
| 206 |
+
key = f"{self.PREFIX_POLICY}{app_id}"
|
| 207 |
+
data = await self.redis.get(key)
|
| 208 |
+
if data:
|
| 209 |
+
return json.loads(data)
|
| 210 |
+
return None
|
| 211 |
+
|
| 212 |
+
async def set_policies(
|
| 213 |
+
self,
|
| 214 |
+
app_id: str,
|
| 215 |
+
policies: list[dict],
|
| 216 |
+
ttl_seconds: int = 60, # 1 minute
|
| 217 |
+
) -> None:
|
| 218 |
+
"""Cache policies for an application."""
|
| 219 |
+
key = f"{self.PREFIX_POLICY}{app_id}"
|
| 220 |
+
await self.redis.setex(key, ttl_seconds, json.dumps(policies))
|
| 221 |
+
|
| 222 |
+
async def invalidate_policies(self, app_id: str) -> None:
|
| 223 |
+
"""Invalidate cached policies."""
|
| 224 |
+
key = f"{self.PREFIX_POLICY}{app_id}"
|
| 225 |
+
await self.redis.delete(key)
|
| 226 |
+
|
| 227 |
+
# =========================================================================
|
| 228 |
+
# Generic Cache Operations
|
| 229 |
+
# =========================================================================
|
| 230 |
+
|
| 231 |
+
async def get(self, key: str) -> Optional[str]:
|
| 232 |
+
"""Get a value from cache."""
|
| 233 |
+
return await self.redis.get(key)
|
| 234 |
+
|
| 235 |
+
async def set(
|
| 236 |
+
self,
|
| 237 |
+
key: str,
|
| 238 |
+
value: Any,
|
| 239 |
+
ttl_seconds: Optional[int] = None,
|
| 240 |
+
) -> None:
|
| 241 |
+
"""Set a value in cache."""
|
| 242 |
+
if ttl_seconds:
|
| 243 |
+
await self.redis.setex(key, ttl_seconds, json.dumps(value))
|
| 244 |
+
else:
|
| 245 |
+
await self.redis.set(key, json.dumps(value))
|
| 246 |
+
|
| 247 |
+
async def delete(self, key: str) -> None:
|
| 248 |
+
"""Delete a key from cache."""
|
| 249 |
+
await self.redis.delete(key)
|
| 250 |
+
|
| 251 |
+
async def exists(self, key: str) -> bool:
|
| 252 |
+
"""Check if a key exists."""
|
| 253 |
+
return await self.redis.exists(key) > 0
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
# Helper to get cache instance
|
| 257 |
+
async def get_cache() -> RedisCache:
|
| 258 |
+
"""Get Redis cache instance."""
|
| 259 |
+
redis_client = await get_redis()
|
| 260 |
+
return RedisCache(redis_client)
|
backend/adapters/encryption/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Encryption Adapters.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Implémentations du EncryptionPort.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from backend.adapters.encryption.in_memory_adapter import InMemoryEncryptionAdapter
|
| 7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
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""AWS KMS Encryption Adapter.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Implémentation production du EncryptionPort
|
| 4 |
+
utilisant AWS Key Management Service pour le chiffrement.
|
| 5 |
+
|
| 6 |
+
Ce module fournit:
|
| 7 |
+
- Chiffrement/déchiffrement via AWS KMS
|
| 8 |
+
- Envelope encryption pour les données volumineuses
|
| 9 |
+
- Support de rotation de clés via alias
|
| 10 |
+
- Caching des data keys pour performance
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import base64
|
| 14 |
+
import hashlib
|
| 15 |
+
import hmac
|
| 16 |
+
import os
|
| 17 |
+
from datetime import datetime, timedelta
|
| 18 |
+
from typing import Any
|
| 19 |
+
|
| 20 |
+
from cryptography.fernet import Fernet
|
| 21 |
+
|
| 22 |
+
from backend.ports.encryption import EncryptionPort, KeyRotationStatus
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class AWSKMSEncryptionAdapter(EncryptionPort):
|
| 26 |
+
"""
|
| 27 |
+
AWS KMS implementation of encryption.
|
| 28 |
+
|
| 29 |
+
Uses envelope encryption:
|
| 30 |
+
1. KMS generates/encrypts a data key
|
| 31 |
+
2. Data key is used locally for Fernet encryption
|
| 32 |
+
3. Encrypted data key is stored with the ciphertext
|
| 33 |
+
|
| 34 |
+
This approach:
|
| 35 |
+
- Minimizes KMS API calls
|
| 36 |
+
- Allows encryption of large data
|
| 37 |
+
- Provides key rotation via KMS aliases
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
def __init__(
|
| 41 |
+
self,
|
| 42 |
+
kms_key_id: str | None = None,
|
| 43 |
+
region: str = "us-east-1",
|
| 44 |
+
cache_ttl_seconds: int = 300,
|
| 45 |
+
boto_client: Any = None,
|
| 46 |
+
):
|
| 47 |
+
"""
|
| 48 |
+
Initialize AWS KMS adapter.
|
| 49 |
+
|
| 50 |
+
Args:
|
| 51 |
+
kms_key_id: KMS key ID, ARN, or alias (e.g., 'alias/my-key')
|
| 52 |
+
region: AWS region
|
| 53 |
+
cache_ttl_seconds: How long to cache data keys
|
| 54 |
+
boto_client: Optional boto3 KMS client (for testing)
|
| 55 |
+
"""
|
| 56 |
+
self._kms_key_id = kms_key_id or os.environ.get(
|
| 57 |
+
"AWS_KMS_KEY_ID", "alias/tensorwall"
|
| 58 |
+
)
|
| 59 |
+
self._region = region
|
| 60 |
+
self._cache_ttl = cache_ttl_seconds
|
| 61 |
+
self._kms_client = boto_client
|
| 62 |
+
|
| 63 |
+
# Cached data key for envelope encryption
|
| 64 |
+
self._cached_data_key: bytes | None = None
|
| 65 |
+
self._cached_encrypted_key: bytes | None = None
|
| 66 |
+
self._cache_expires: datetime | None = None
|
| 67 |
+
self._fernet: Fernet | None = None
|
| 68 |
+
|
| 69 |
+
# Key rotation state
|
| 70 |
+
self._rotation_in_progress = False
|
| 71 |
+
self._old_key_id: str | None = None
|
| 72 |
+
|
| 73 |
+
def _get_kms_client(self):
|
| 74 |
+
"""Get or create KMS client."""
|
| 75 |
+
if self._kms_client:
|
| 76 |
+
return self._kms_client
|
| 77 |
+
|
| 78 |
+
try:
|
| 79 |
+
import boto3
|
| 80 |
+
|
| 81 |
+
self._kms_client = boto3.client("kms", region_name=self._region)
|
| 82 |
+
return self._kms_client
|
| 83 |
+
except ImportError:
|
| 84 |
+
raise RuntimeError(
|
| 85 |
+
"boto3 is required for AWS KMS adapter. Install with: pip install boto3"
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
async def _get_data_key(self) -> tuple[bytes, bytes]:
|
| 89 |
+
"""Get or generate a data key for envelope encryption."""
|
| 90 |
+
now = datetime.now()
|
| 91 |
+
|
| 92 |
+
# Return cached key if valid
|
| 93 |
+
if self._cached_data_key and self._cache_expires and now < self._cache_expires:
|
| 94 |
+
return self._cached_data_key, self._cached_encrypted_key
|
| 95 |
+
|
| 96 |
+
# Generate new data key from KMS
|
| 97 |
+
client = self._get_kms_client()
|
| 98 |
+
response = client.generate_data_key(
|
| 99 |
+
KeyId=self._kms_key_id,
|
| 100 |
+
KeySpec="AES_256",
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
plaintext_key = response["Plaintext"]
|
| 104 |
+
encrypted_key = response["CiphertextBlob"]
|
| 105 |
+
|
| 106 |
+
# Cache the key
|
| 107 |
+
self._cached_data_key = plaintext_key
|
| 108 |
+
self._cached_encrypted_key = encrypted_key
|
| 109 |
+
self._cache_expires = now + timedelta(seconds=self._cache_ttl)
|
| 110 |
+
|
| 111 |
+
# Create Fernet with the data key
|
| 112 |
+
fernet_key = base64.urlsafe_b64encode(plaintext_key[:32])
|
| 113 |
+
self._fernet = Fernet(fernet_key)
|
| 114 |
+
|
| 115 |
+
return plaintext_key, encrypted_key
|
| 116 |
+
|
| 117 |
+
async def _decrypt_data_key(self, encrypted_key: bytes) -> bytes:
|
| 118 |
+
"""Decrypt a data key using KMS."""
|
| 119 |
+
client = self._get_kms_client()
|
| 120 |
+
response = client.decrypt(
|
| 121 |
+
CiphertextBlob=encrypted_key,
|
| 122 |
+
KeyId=self._kms_key_id,
|
| 123 |
+
)
|
| 124 |
+
return response["Plaintext"]
|
| 125 |
+
|
| 126 |
+
# -------------------------------------------------------------------------
|
| 127 |
+
# Core Encryption
|
| 128 |
+
# -------------------------------------------------------------------------
|
| 129 |
+
|
| 130 |
+
async def encrypt(self, plaintext: str) -> str:
|
| 131 |
+
"""
|
| 132 |
+
Encrypt using envelope encryption.
|
| 133 |
+
|
| 134 |
+
Output format: base64(encrypted_data_key + fernet_token)
|
| 135 |
+
"""
|
| 136 |
+
_, encrypted_key = await self._get_data_key()
|
| 137 |
+
|
| 138 |
+
# Encrypt with Fernet (uses cached data key)
|
| 139 |
+
fernet_token = self._fernet.encrypt(plaintext.encode())
|
| 140 |
+
|
| 141 |
+
# Combine encrypted data key with ciphertext
|
| 142 |
+
combined = len(encrypted_key).to_bytes(4, "big") + encrypted_key + fernet_token
|
| 143 |
+
|
| 144 |
+
return base64.urlsafe_b64encode(combined).decode()
|
| 145 |
+
|
| 146 |
+
async def decrypt(self, ciphertext: str) -> str:
|
| 147 |
+
"""Decrypt envelope-encrypted data."""
|
| 148 |
+
try:
|
| 149 |
+
combined = base64.urlsafe_b64decode(ciphertext.encode())
|
| 150 |
+
|
| 151 |
+
# Extract encrypted data key length and key
|
| 152 |
+
key_length = int.from_bytes(combined[:4], "big")
|
| 153 |
+
encrypted_key = combined[4 : 4 + key_length]
|
| 154 |
+
fernet_token = combined[4 + key_length :]
|
| 155 |
+
|
| 156 |
+
# Decrypt data key
|
| 157 |
+
data_key = await self._decrypt_data_key(encrypted_key)
|
| 158 |
+
|
| 159 |
+
# Create Fernet and decrypt
|
| 160 |
+
fernet_key = base64.urlsafe_b64encode(data_key[:32])
|
| 161 |
+
fernet = Fernet(fernet_key)
|
| 162 |
+
|
| 163 |
+
return fernet.decrypt(fernet_token).decode()
|
| 164 |
+
|
| 165 |
+
except Exception as e:
|
| 166 |
+
raise ValueError(f"Decryption failed: {e}")
|
| 167 |
+
|
| 168 |
+
async def encrypt_bytes(self, data: bytes) -> bytes:
|
| 169 |
+
"""Encrypt bytes using envelope encryption."""
|
| 170 |
+
_, encrypted_key = await self._get_data_key()
|
| 171 |
+
|
| 172 |
+
fernet_token = self._fernet.encrypt(data)
|
| 173 |
+
combined = len(encrypted_key).to_bytes(4, "big") + encrypted_key + fernet_token
|
| 174 |
+
|
| 175 |
+
return combined
|
| 176 |
+
|
| 177 |
+
async def decrypt_bytes(self, encrypted_data: bytes) -> bytes:
|
| 178 |
+
"""Decrypt bytes."""
|
| 179 |
+
try:
|
| 180 |
+
key_length = int.from_bytes(encrypted_data[:4], "big")
|
| 181 |
+
encrypted_key = encrypted_data[4 : 4 + key_length]
|
| 182 |
+
fernet_token = encrypted_data[4 + key_length :]
|
| 183 |
+
|
| 184 |
+
data_key = await self._decrypt_data_key(encrypted_key)
|
| 185 |
+
fernet_key = base64.urlsafe_b64encode(data_key[:32])
|
| 186 |
+
fernet = Fernet(fernet_key)
|
| 187 |
+
|
| 188 |
+
return fernet.decrypt(fernet_token)
|
| 189 |
+
|
| 190 |
+
except Exception as e:
|
| 191 |
+
raise ValueError(f"Decryption failed: {e}")
|
| 192 |
+
|
| 193 |
+
# -------------------------------------------------------------------------
|
| 194 |
+
# API Key Encryption
|
| 195 |
+
# -------------------------------------------------------------------------
|
| 196 |
+
|
| 197 |
+
async def encrypt_api_key(self, api_key: str) -> str:
|
| 198 |
+
"""Encrypt an API key."""
|
| 199 |
+
return await self.encrypt(api_key)
|
| 200 |
+
|
| 201 |
+
async def decrypt_api_key(self, encrypted_key: str) -> str:
|
| 202 |
+
"""Decrypt an API key."""
|
| 203 |
+
return await self.decrypt(encrypted_key)
|
| 204 |
+
|
| 205 |
+
# -------------------------------------------------------------------------
|
| 206 |
+
# Hashing
|
| 207 |
+
# -------------------------------------------------------------------------
|
| 208 |
+
|
| 209 |
+
async def hash_key(self, key: str, salt: str | None = None) -> str:
|
| 210 |
+
"""Hash a key using SHA-256."""
|
| 211 |
+
if salt:
|
| 212 |
+
key = f"{salt}:{key}"
|
| 213 |
+
return hashlib.sha256(key.encode()).hexdigest()
|
| 214 |
+
|
| 215 |
+
async def verify_key_hash(
|
| 216 |
+
self,
|
| 217 |
+
key: str,
|
| 218 |
+
hash_value: str,
|
| 219 |
+
salt: str | None = None,
|
| 220 |
+
) -> bool:
|
| 221 |
+
"""Verify a key against its hash."""
|
| 222 |
+
computed_hash = await self.hash_key(key, salt)
|
| 223 |
+
return hmac.compare_digest(computed_hash, hash_value)
|
| 224 |
+
|
| 225 |
+
# -------------------------------------------------------------------------
|
| 226 |
+
# Key Rotation
|
| 227 |
+
# -------------------------------------------------------------------------
|
| 228 |
+
|
| 229 |
+
async def setup_key_rotation(self, old_key: str, new_key: str) -> None:
|
| 230 |
+
"""
|
| 231 |
+
Setup key rotation.
|
| 232 |
+
|
| 233 |
+
For KMS, rotation is handled via key aliases:
|
| 234 |
+
- old_key: Previous KMS key ID/alias
|
| 235 |
+
- new_key: New KMS key ID/alias
|
| 236 |
+
|
| 237 |
+
New encryptions use new key, decryptions try both.
|
| 238 |
+
"""
|
| 239 |
+
self._old_key_id = old_key
|
| 240 |
+
self._kms_key_id = new_key
|
| 241 |
+
self._rotation_in_progress = True
|
| 242 |
+
|
| 243 |
+
# Clear cache to force new key usage
|
| 244 |
+
self._cached_data_key = None
|
| 245 |
+
self._cached_encrypted_key = None
|
| 246 |
+
self._cache_expires = None
|
| 247 |
+
self._fernet = None
|
| 248 |
+
|
| 249 |
+
async def rotate_encrypted_value(self, encrypted_data: str) -> str:
|
| 250 |
+
"""Re-encrypt data with the current key."""
|
| 251 |
+
# Decrypt with old or new key
|
| 252 |
+
plaintext = await self.decrypt(encrypted_data)
|
| 253 |
+
|
| 254 |
+
# Re-encrypt with current key
|
| 255 |
+
return await self.encrypt(plaintext)
|
| 256 |
+
|
| 257 |
+
async def get_rotation_status(self) -> KeyRotationStatus:
|
| 258 |
+
"""Get key rotation status."""
|
| 259 |
+
return KeyRotationStatus(
|
| 260 |
+
rotation_in_progress=self._rotation_in_progress,
|
| 261 |
+
old_key_valid=self._old_key_id is not None,
|
| 262 |
+
new_key_active=True,
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
async def complete_rotation(self) -> None:
|
| 266 |
+
"""Complete key rotation."""
|
| 267 |
+
self._rotation_in_progress = False
|
| 268 |
+
self._old_key_id = None
|
| 269 |
+
|
| 270 |
+
# -------------------------------------------------------------------------
|
| 271 |
+
# Utility Methods
|
| 272 |
+
# -------------------------------------------------------------------------
|
| 273 |
+
|
| 274 |
+
async def is_encrypted(self, data: str) -> bool:
|
| 275 |
+
"""Check if data appears to be envelope-encrypted."""
|
| 276 |
+
try:
|
| 277 |
+
decoded = base64.urlsafe_b64decode(data.encode())
|
| 278 |
+
# Check minimum size: 4 bytes length + some key + some data
|
| 279 |
+
if len(decoded) < 100:
|
| 280 |
+
return False
|
| 281 |
+
key_length = int.from_bytes(decoded[:4], "big")
|
| 282 |
+
# Reasonable key length check
|
| 283 |
+
return 100 <= key_length <= 500
|
| 284 |
+
except Exception:
|
| 285 |
+
return False
|
| 286 |
+
|
| 287 |
+
async def safe_decrypt(self, data: str) -> str | None:
|
| 288 |
+
"""Attempt to decrypt, returning None on failure."""
|
| 289 |
+
try:
|
| 290 |
+
return await self.decrypt(data)
|
| 291 |
+
except ValueError:
|
| 292 |
+
return None
|
| 293 |
+
|
| 294 |
+
async def generate_key(self) -> str:
|
| 295 |
+
"""
|
| 296 |
+
Generate a new data key.
|
| 297 |
+
|
| 298 |
+
Note: For KMS, this returns a new plaintext data key
|
| 299 |
+
that can be used with Fernet locally.
|
| 300 |
+
"""
|
| 301 |
+
client = self._get_kms_client()
|
| 302 |
+
response = client.generate_data_key(
|
| 303 |
+
KeyId=self._kms_key_id,
|
| 304 |
+
KeySpec="AES_256",
|
| 305 |
+
)
|
| 306 |
+
return base64.urlsafe_b64encode(response["Plaintext"]).decode()
|
| 307 |
+
|
| 308 |
+
def invalidate_cache(self) -> None:
|
| 309 |
+
"""Invalidate the data key cache."""
|
| 310 |
+
self._cached_data_key = None
|
| 311 |
+
self._cached_encrypted_key = None
|
| 312 |
+
self._cache_expires = None
|
| 313 |
+
self._fernet = None
|
backend/adapters/encryption/in_memory_adapter.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""In-Memory Encryption Adapter.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Implémentation native du EncryptionPort
|
| 4 |
+
utilisant Fernet pour le chiffrement symétrique.
|
| 5 |
+
|
| 6 |
+
Cette implémentation fournit:
|
| 7 |
+
- Chiffrement Fernet (AES-128-CBC + HMAC-SHA256)
|
| 8 |
+
- Support de rotation de clés via MultiFernet
|
| 9 |
+
- Hachage SHA-256 pour les clés API gateway
|
| 10 |
+
- Dérivation de clé PBKDF2 optionnelle
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import base64
|
| 14 |
+
import hashlib
|
| 15 |
+
import hmac
|
| 16 |
+
|
| 17 |
+
from cryptography.fernet import Fernet, InvalidToken, MultiFernet
|
| 18 |
+
from cryptography.hazmat.primitives import hashes
|
| 19 |
+
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
|
| 20 |
+
|
| 21 |
+
from backend.ports.encryption import EncryptionPort, KeyRotationStatus
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class InMemoryEncryptionAdapter(EncryptionPort):
|
| 25 |
+
"""
|
| 26 |
+
Native implementation of encryption using Fernet.
|
| 27 |
+
|
| 28 |
+
Fernet provides:
|
| 29 |
+
- AES-128-CBC encryption
|
| 30 |
+
- HMAC-SHA256 authentication
|
| 31 |
+
- Timestamp-based token format
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
def __init__(
|
| 35 |
+
self,
|
| 36 |
+
key: str | None = None,
|
| 37 |
+
derive_from_secret: str | None = None,
|
| 38 |
+
salt: str = "gateway-salt-v1",
|
| 39 |
+
):
|
| 40 |
+
"""
|
| 41 |
+
Initialize encryption adapter.
|
| 42 |
+
|
| 43 |
+
Args:
|
| 44 |
+
key: Direct Fernet key (base64-encoded)
|
| 45 |
+
derive_from_secret: Secret to derive key from using PBKDF2
|
| 46 |
+
salt: Salt for key derivation
|
| 47 |
+
"""
|
| 48 |
+
self._fernet: Fernet | None = None
|
| 49 |
+
self._multi_fernet: MultiFernet | None = None
|
| 50 |
+
self._rotation_in_progress = False
|
| 51 |
+
self._old_key_valid = False
|
| 52 |
+
|
| 53 |
+
if key:
|
| 54 |
+
self._fernet = Fernet(key.encode() if isinstance(key, str) else key)
|
| 55 |
+
elif derive_from_secret:
|
| 56 |
+
derived_key = self._derive_key(derive_from_secret, salt)
|
| 57 |
+
self._fernet = Fernet(derived_key)
|
| 58 |
+
else:
|
| 59 |
+
# Generate a new key for testing
|
| 60 |
+
self._fernet = Fernet(Fernet.generate_key())
|
| 61 |
+
|
| 62 |
+
def _derive_key(self, secret: str, salt: str) -> bytes:
|
| 63 |
+
"""Derive a Fernet key from a secret using PBKDF2."""
|
| 64 |
+
kdf = PBKDF2HMAC(
|
| 65 |
+
algorithm=hashes.SHA256(),
|
| 66 |
+
length=32,
|
| 67 |
+
salt=salt.encode(),
|
| 68 |
+
iterations=480000,
|
| 69 |
+
)
|
| 70 |
+
return base64.urlsafe_b64encode(kdf.derive(secret.encode()))
|
| 71 |
+
|
| 72 |
+
# -------------------------------------------------------------------------
|
| 73 |
+
# Core Encryption
|
| 74 |
+
# -------------------------------------------------------------------------
|
| 75 |
+
|
| 76 |
+
async def encrypt(self, plaintext: str) -> str:
|
| 77 |
+
"""Encrypt a string."""
|
| 78 |
+
encrypted = self._fernet.encrypt(plaintext.encode())
|
| 79 |
+
return encrypted.decode()
|
| 80 |
+
|
| 81 |
+
async def decrypt(self, ciphertext: str) -> str:
|
| 82 |
+
"""Decrypt a string."""
|
| 83 |
+
try:
|
| 84 |
+
fernet = self._multi_fernet or self._fernet
|
| 85 |
+
decrypted = fernet.decrypt(ciphertext.encode())
|
| 86 |
+
return decrypted.decode()
|
| 87 |
+
except InvalidToken:
|
| 88 |
+
raise ValueError("Invalid encrypted data or wrong key")
|
| 89 |
+
|
| 90 |
+
async def encrypt_bytes(self, data: bytes) -> bytes:
|
| 91 |
+
"""Encrypt bytes."""
|
| 92 |
+
return self._fernet.encrypt(data)
|
| 93 |
+
|
| 94 |
+
async def decrypt_bytes(self, encrypted_data: bytes) -> bytes:
|
| 95 |
+
"""Decrypt bytes."""
|
| 96 |
+
try:
|
| 97 |
+
fernet = self._multi_fernet or self._fernet
|
| 98 |
+
return fernet.decrypt(encrypted_data)
|
| 99 |
+
except InvalidToken:
|
| 100 |
+
raise ValueError("Invalid encrypted data or wrong key")
|
| 101 |
+
|
| 102 |
+
# -------------------------------------------------------------------------
|
| 103 |
+
# API Key Encryption
|
| 104 |
+
# -------------------------------------------------------------------------
|
| 105 |
+
|
| 106 |
+
async def encrypt_api_key(self, api_key: str) -> str:
|
| 107 |
+
"""Encrypt an API key for storage."""
|
| 108 |
+
return await self.encrypt(api_key)
|
| 109 |
+
|
| 110 |
+
async def decrypt_api_key(self, encrypted_key: str) -> str:
|
| 111 |
+
"""Decrypt a stored API key."""
|
| 112 |
+
return await self.decrypt(encrypted_key)
|
| 113 |
+
|
| 114 |
+
# -------------------------------------------------------------------------
|
| 115 |
+
# Hashing
|
| 116 |
+
# -------------------------------------------------------------------------
|
| 117 |
+
|
| 118 |
+
async def hash_key(self, key: str, salt: str | None = None) -> str:
|
| 119 |
+
"""Hash a key using SHA-256."""
|
| 120 |
+
if salt:
|
| 121 |
+
key = f"{salt}:{key}"
|
| 122 |
+
return hashlib.sha256(key.encode()).hexdigest()
|
| 123 |
+
|
| 124 |
+
async def verify_key_hash(
|
| 125 |
+
self,
|
| 126 |
+
key: str,
|
| 127 |
+
hash_value: str,
|
| 128 |
+
salt: str | None = None,
|
| 129 |
+
) -> bool:
|
| 130 |
+
"""Verify a key against its hash using constant-time comparison."""
|
| 131 |
+
computed_hash = await self.hash_key(key, salt)
|
| 132 |
+
return hmac.compare_digest(computed_hash, hash_value)
|
| 133 |
+
|
| 134 |
+
# -------------------------------------------------------------------------
|
| 135 |
+
# Key Rotation
|
| 136 |
+
# -------------------------------------------------------------------------
|
| 137 |
+
|
| 138 |
+
async def setup_key_rotation(self, old_key: str, new_key: str) -> None:
|
| 139 |
+
"""Configure key rotation with MultiFernet."""
|
| 140 |
+
old_fernet = Fernet(old_key.encode())
|
| 141 |
+
new_fernet = Fernet(new_key.encode())
|
| 142 |
+
|
| 143 |
+
# New key first for encryption, both for decryption
|
| 144 |
+
self._multi_fernet = MultiFernet([new_fernet, old_fernet])
|
| 145 |
+
self._fernet = new_fernet
|
| 146 |
+
self._rotation_in_progress = True
|
| 147 |
+
self._old_key_valid = True
|
| 148 |
+
|
| 149 |
+
async def rotate_encrypted_value(self, encrypted_data: str) -> str:
|
| 150 |
+
"""Re-encrypt data with the current key."""
|
| 151 |
+
if not self._multi_fernet:
|
| 152 |
+
return encrypted_data
|
| 153 |
+
|
| 154 |
+
try:
|
| 155 |
+
decrypted = self._multi_fernet.decrypt(encrypted_data.encode())
|
| 156 |
+
return self._fernet.encrypt(decrypted).decode()
|
| 157 |
+
except InvalidToken:
|
| 158 |
+
raise ValueError("Failed to rotate encrypted value")
|
| 159 |
+
|
| 160 |
+
async def get_rotation_status(self) -> KeyRotationStatus:
|
| 161 |
+
"""Get key rotation status."""
|
| 162 |
+
return KeyRotationStatus(
|
| 163 |
+
rotation_in_progress=self._rotation_in_progress,
|
| 164 |
+
old_key_valid=self._old_key_valid,
|
| 165 |
+
new_key_active=True,
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
async def complete_rotation(self) -> None:
|
| 169 |
+
"""Complete key rotation, disabling old key."""
|
| 170 |
+
self._multi_fernet = None
|
| 171 |
+
self._rotation_in_progress = False
|
| 172 |
+
self._old_key_valid = False
|
| 173 |
+
|
| 174 |
+
# -------------------------------------------------------------------------
|
| 175 |
+
# Utility Methods
|
| 176 |
+
# -------------------------------------------------------------------------
|
| 177 |
+
|
| 178 |
+
async def is_encrypted(self, data: str) -> bool:
|
| 179 |
+
"""Check if data appears to be Fernet-encrypted."""
|
| 180 |
+
try:
|
| 181 |
+
decoded = base64.urlsafe_b64decode(data.encode())
|
| 182 |
+
# Fernet tokens start with version byte (0x80) and are at least 73 bytes
|
| 183 |
+
return len(decoded) >= 73 and decoded[0] == 0x80
|
| 184 |
+
except Exception:
|
| 185 |
+
return False
|
| 186 |
+
|
| 187 |
+
async def safe_decrypt(self, data: str) -> str | None:
|
| 188 |
+
"""Attempt to decrypt, returning None on failure."""
|
| 189 |
+
try:
|
| 190 |
+
return await self.decrypt(data)
|
| 191 |
+
except (ValueError, InvalidToken):
|
| 192 |
+
return None
|
| 193 |
+
|
| 194 |
+
async def generate_key(self) -> str:
|
| 195 |
+
"""Generate a new Fernet key."""
|
| 196 |
+
return Fernet.generate_key().decode()
|
backend/adapters/exporters/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exporters - .
|
| 2 |
+
|
| 3 |
+
Provides basic metrics export for observability.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from backend.adapters.prometheus.metrics_adapter import InMemoryMetricsAdapter
|
| 7 |
+
|
| 8 |
+
# Create a singleton metrics exporter
|
| 9 |
+
metrics_exporter = InMemoryMetricsAdapter()
|
| 10 |
+
|
| 11 |
+
__all__ = ["metrics_exporter"]
|
backend/adapters/feature/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Feature Adapters - Implémentations du FeatureRegistryPort."""
|
| 2 |
+
|
| 3 |
+
from backend.adapters.feature.in_memory_feature_adapter import InMemoryFeatureAdapter
|
| 4 |
+
|
| 5 |
+
__all__ = ["InMemoryFeatureAdapter"]
|
backend/adapters/feature/in_memory_feature_adapter.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""InMemory Feature Adapter - Implémentation pour les tests.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Adapter natif qui implémente directement
|
| 4 |
+
l'interface FeatureRegistryPort sans dépendre de la base de données.
|
| 5 |
+
Utile pour les tests unitaires et d'intégration.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from collections import defaultdict
|
| 9 |
+
from dataclasses import dataclass
|
| 10 |
+
from typing import Optional
|
| 11 |
+
|
| 12 |
+
from backend.ports.feature_registry import (
|
| 13 |
+
FeatureRegistryPort,
|
| 14 |
+
FeatureDefinition,
|
| 15 |
+
FeatureCheckResult,
|
| 16 |
+
FeatureAction,
|
| 17 |
+
FeatureDecision,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@dataclass
|
| 22 |
+
class AppConfig:
|
| 23 |
+
"""Configuration d'une application."""
|
| 24 |
+
|
| 25 |
+
strict_mode: bool = True
|
| 26 |
+
default_feature_id: Optional[str] = None
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class InMemoryFeatureAdapter(FeatureRegistryPort):
|
| 30 |
+
"""Adapter en mémoire pour le registre de features.
|
| 31 |
+
|
| 32 |
+
Implémentation sans base de données pour les tests.
|
| 33 |
+
Stocke tout en mémoire.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
def __init__(self, default_strict_mode: bool = True):
|
| 37 |
+
"""Initialise l'adapter.
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
default_strict_mode: Mode strict par défaut pour nouvelles apps
|
| 41 |
+
"""
|
| 42 |
+
self.default_strict_mode = default_strict_mode
|
| 43 |
+
self._features: dict[str, dict[str, FeatureDefinition]] = defaultdict(dict)
|
| 44 |
+
self._app_configs: dict[str, AppConfig] = {}
|
| 45 |
+
|
| 46 |
+
def _get_app_config(self, app_id: str) -> AppConfig:
|
| 47 |
+
"""Récupère ou crée la config d'une application."""
|
| 48 |
+
if app_id not in self._app_configs:
|
| 49 |
+
self._app_configs[app_id] = AppConfig(strict_mode=self.default_strict_mode)
|
| 50 |
+
return self._app_configs[app_id]
|
| 51 |
+
|
| 52 |
+
async def check_feature(
|
| 53 |
+
self,
|
| 54 |
+
app_id: str,
|
| 55 |
+
feature_id: Optional[str],
|
| 56 |
+
action: FeatureAction,
|
| 57 |
+
model: str,
|
| 58 |
+
environment: str,
|
| 59 |
+
estimated_tokens: Optional[int] = None,
|
| 60 |
+
estimated_cost_usd: Optional[float] = None,
|
| 61 |
+
) -> FeatureCheckResult:
|
| 62 |
+
"""Vérifie si une requête est autorisée pour une feature."""
|
| 63 |
+
config = self._get_app_config(app_id)
|
| 64 |
+
app_features = self._features.get(app_id, {})
|
| 65 |
+
|
| 66 |
+
# Si pas de features enregistrées, mode permissif
|
| 67 |
+
if not app_features:
|
| 68 |
+
return FeatureCheckResult(
|
| 69 |
+
allowed=True,
|
| 70 |
+
decision=FeatureDecision.ALLOWED_NO_REGISTRY,
|
| 71 |
+
reason=f"Application {app_id} has no feature registry (permissive mode)",
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
# Résoudre la feature
|
| 75 |
+
resolved_feature_id = feature_id or config.default_feature_id
|
| 76 |
+
|
| 77 |
+
if not resolved_feature_id:
|
| 78 |
+
if config.strict_mode:
|
| 79 |
+
return FeatureCheckResult(
|
| 80 |
+
allowed=False,
|
| 81 |
+
decision=FeatureDecision.DENIED_NO_FEATURE_SPECIFIED,
|
| 82 |
+
reason="No feature specified and no default feature configured (strict mode)",
|
| 83 |
+
)
|
| 84 |
+
else:
|
| 85 |
+
return FeatureCheckResult(
|
| 86 |
+
allowed=True,
|
| 87 |
+
decision=FeatureDecision.ALLOWED_PERMISSIVE,
|
| 88 |
+
reason="No feature specified but strict mode is disabled",
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
# Vérifier si la feature existe
|
| 92 |
+
feature = app_features.get(resolved_feature_id)
|
| 93 |
+
|
| 94 |
+
if not feature:
|
| 95 |
+
if config.strict_mode:
|
| 96 |
+
return FeatureCheckResult(
|
| 97 |
+
allowed=False,
|
| 98 |
+
decision=FeatureDecision.DENIED_UNKNOWN_FEATURE,
|
| 99 |
+
reason=f"Feature '{resolved_feature_id}' is not registered for application {app_id}",
|
| 100 |
+
feature_id=resolved_feature_id,
|
| 101 |
+
)
|
| 102 |
+
else:
|
| 103 |
+
return FeatureCheckResult(
|
| 104 |
+
allowed=True,
|
| 105 |
+
decision=FeatureDecision.ALLOWED_PERMISSIVE,
|
| 106 |
+
reason=f"Feature '{resolved_feature_id}' unknown but strict mode disabled",
|
| 107 |
+
feature_id=resolved_feature_id,
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
# Vérifier si active
|
| 111 |
+
if not feature.is_active:
|
| 112 |
+
return FeatureCheckResult(
|
| 113 |
+
allowed=False,
|
| 114 |
+
decision=FeatureDecision.DENIED_FEATURE_DISABLED,
|
| 115 |
+
reason=f"Feature '{feature.name}' is currently disabled",
|
| 116 |
+
feature_id=feature.id,
|
| 117 |
+
feature_name=feature.name,
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
# Vérifier l'action
|
| 121 |
+
if feature.allowed_actions and action not in feature.allowed_actions:
|
| 122 |
+
return FeatureCheckResult(
|
| 123 |
+
allowed=False,
|
| 124 |
+
decision=FeatureDecision.DENIED_ACTION_NOT_ALLOWED,
|
| 125 |
+
reason=f"Action '{action.value}' is not allowed for feature '{feature.name}'. Allowed: {[a.value for a in feature.allowed_actions]}",
|
| 126 |
+
feature_id=feature.id,
|
| 127 |
+
feature_name=feature.name,
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
# Vérifier le modèle
|
| 131 |
+
if feature.allowed_models and not self._model_matches(
|
| 132 |
+
model, feature.allowed_models
|
| 133 |
+
):
|
| 134 |
+
return FeatureCheckResult(
|
| 135 |
+
allowed=False,
|
| 136 |
+
decision=FeatureDecision.DENIED_MODEL_NOT_ALLOWED,
|
| 137 |
+
reason=f"Model '{model}' is not allowed for feature '{feature.name}'. Allowed: {feature.allowed_models}",
|
| 138 |
+
feature_id=feature.id,
|
| 139 |
+
feature_name=feature.name,
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
# Vérifier l'environnement
|
| 143 |
+
if (
|
| 144 |
+
feature.allowed_environments
|
| 145 |
+
and environment not in feature.allowed_environments
|
| 146 |
+
):
|
| 147 |
+
return FeatureCheckResult(
|
| 148 |
+
allowed=False,
|
| 149 |
+
decision=FeatureDecision.DENIED_ENVIRONMENT_NOT_ALLOWED,
|
| 150 |
+
reason=f"Environment '{environment}' is not allowed for feature '{feature.name}'. Allowed: {feature.allowed_environments}",
|
| 151 |
+
feature_id=feature.id,
|
| 152 |
+
feature_name=feature.name,
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
# Vérifier les tokens
|
| 156 |
+
if feature.max_tokens_per_request and estimated_tokens:
|
| 157 |
+
if estimated_tokens > feature.max_tokens_per_request:
|
| 158 |
+
return FeatureCheckResult(
|
| 159 |
+
allowed=False,
|
| 160 |
+
decision=FeatureDecision.DENIED_TOKEN_LIMIT,
|
| 161 |
+
reason=f"Estimated tokens ({estimated_tokens}) exceeds limit ({feature.max_tokens_per_request})",
|
| 162 |
+
feature_id=feature.id,
|
| 163 |
+
feature_name=feature.name,
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
# Vérifier le coût
|
| 167 |
+
if feature.max_cost_per_request_usd and estimated_cost_usd:
|
| 168 |
+
if estimated_cost_usd > feature.max_cost_per_request_usd:
|
| 169 |
+
return FeatureCheckResult(
|
| 170 |
+
allowed=False,
|
| 171 |
+
decision=FeatureDecision.DENIED_COST_LIMIT,
|
| 172 |
+
reason=f"Estimated cost (${estimated_cost_usd:.4f}) exceeds limit (${feature.max_cost_per_request_usd:.4f})",
|
| 173 |
+
feature_id=feature.id,
|
| 174 |
+
feature_name=feature.name,
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
# Tout OK - construire les contraintes appliquées
|
| 178 |
+
applied_constraints = {}
|
| 179 |
+
if feature.max_tokens_per_request:
|
| 180 |
+
applied_constraints["max_tokens"] = feature.max_tokens_per_request
|
| 181 |
+
if feature.max_cost_per_request_usd:
|
| 182 |
+
applied_constraints["max_cost_usd"] = feature.max_cost_per_request_usd
|
| 183 |
+
if feature.max_requests_per_minute:
|
| 184 |
+
applied_constraints["max_rpm"] = feature.max_requests_per_minute
|
| 185 |
+
if feature.require_data_separation:
|
| 186 |
+
applied_constraints["require_data_separation"] = True
|
| 187 |
+
if not feature.allow_pii:
|
| 188 |
+
applied_constraints["pii_blocked"] = True
|
| 189 |
+
|
| 190 |
+
return FeatureCheckResult(
|
| 191 |
+
allowed=True,
|
| 192 |
+
decision=FeatureDecision.ALLOWED,
|
| 193 |
+
reason=f"Request allowed for feature '{feature.name}'",
|
| 194 |
+
feature_id=feature.id,
|
| 195 |
+
feature_name=feature.name,
|
| 196 |
+
applied_constraints=applied_constraints,
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
def _model_matches(self, model: str, allowed_models: list[str]) -> bool:
|
| 200 |
+
"""Vérifie si un modèle correspond à la liste autorisée.
|
| 201 |
+
|
| 202 |
+
Supporte les wildcards simples (ex: "gpt-*").
|
| 203 |
+
"""
|
| 204 |
+
model_lower = model.lower()
|
| 205 |
+
for allowed in allowed_models:
|
| 206 |
+
allowed_lower = allowed.lower()
|
| 207 |
+
if allowed_lower.endswith("*"):
|
| 208 |
+
# Wildcard match
|
| 209 |
+
prefix = allowed_lower[:-1]
|
| 210 |
+
if model_lower.startswith(prefix):
|
| 211 |
+
return True
|
| 212 |
+
elif model_lower == allowed_lower:
|
| 213 |
+
return True
|
| 214 |
+
return False
|
| 215 |
+
|
| 216 |
+
async def register_feature(
|
| 217 |
+
self,
|
| 218 |
+
app_id: str,
|
| 219 |
+
feature: FeatureDefinition,
|
| 220 |
+
) -> None:
|
| 221 |
+
"""Enregistre une feature pour une application."""
|
| 222 |
+
self._features[app_id][feature.id] = feature
|
| 223 |
+
|
| 224 |
+
async def remove_feature(
|
| 225 |
+
self,
|
| 226 |
+
app_id: str,
|
| 227 |
+
feature_id: str,
|
| 228 |
+
) -> bool:
|
| 229 |
+
"""Retire une feature du registre."""
|
| 230 |
+
if app_id in self._features and feature_id in self._features[app_id]:
|
| 231 |
+
del self._features[app_id][feature_id]
|
| 232 |
+
return True
|
| 233 |
+
return False
|
| 234 |
+
|
| 235 |
+
async def get_feature(
|
| 236 |
+
self,
|
| 237 |
+
app_id: str,
|
| 238 |
+
feature_id: str,
|
| 239 |
+
) -> Optional[FeatureDefinition]:
|
| 240 |
+
"""Récupère la définition d'une feature."""
|
| 241 |
+
return self._features.get(app_id, {}).get(feature_id)
|
| 242 |
+
|
| 243 |
+
async def list_features(
|
| 244 |
+
self,
|
| 245 |
+
app_id: str,
|
| 246 |
+
) -> list[FeatureDefinition]:
|
| 247 |
+
"""Liste les features d'une application."""
|
| 248 |
+
return list(self._features.get(app_id, {}).values())
|
| 249 |
+
|
| 250 |
+
async def set_strict_mode(
|
| 251 |
+
self,
|
| 252 |
+
app_id: str,
|
| 253 |
+
strict: bool,
|
| 254 |
+
) -> None:
|
| 255 |
+
"""Configure le mode strict pour une application."""
|
| 256 |
+
config = self._get_app_config(app_id)
|
| 257 |
+
config.strict_mode = strict
|
| 258 |
+
|
| 259 |
+
async def set_default_feature(
|
| 260 |
+
self,
|
| 261 |
+
app_id: str,
|
| 262 |
+
feature_id: Optional[str],
|
| 263 |
+
) -> None:
|
| 264 |
+
"""Configure la feature par défaut pour une application."""
|
| 265 |
+
config = self._get_app_config(app_id)
|
| 266 |
+
config.default_feature_id = feature_id
|
| 267 |
+
|
| 268 |
+
# Test helpers
|
| 269 |
+
def clear_all(self) -> None:
|
| 270 |
+
"""Efface toutes les données (pour les tests)."""
|
| 271 |
+
self._features.clear()
|
| 272 |
+
self._app_configs.clear()
|
| 273 |
+
|
| 274 |
+
def get_feature_count(self, app_id: str) -> int:
|
| 275 |
+
"""Retourne le nombre de features enregistrées."""
|
| 276 |
+
return len(self._features.get(app_id, {}))
|
| 277 |
+
|
| 278 |
+
def is_strict_mode(self, app_id: str) -> bool:
|
| 279 |
+
"""Vérifie si le mode strict est activé."""
|
| 280 |
+
return self._get_app_config(app_id).strict_mode
|
backend/adapters/llm/__init__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LLM Adapters - Wrappers autour des providers legacy.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Ces adapters implémentent les Ports LLMProviderPort
|
| 4 |
+
et EmbeddingProviderPort.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from backend.adapters.llm.openai_adapter import OpenAIAdapter
|
| 8 |
+
from backend.adapters.llm.anthropic_adapter import AnthropicAdapter
|
| 9 |
+
from backend.adapters.llm.ollama_adapter import OllamaAdapter
|
| 10 |
+
from backend.adapters.llm.mock_adapter import MockAdapter
|
| 11 |
+
from backend.adapters.llm.openai_embedding_adapter import OpenAIEmbeddingAdapter
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
__all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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Anthropic Adapter - Implémentation native du port LLMProviderPort.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Adapter natif qui implémente directement
|
| 4 |
+
l'interface LLMProviderPort sans dépendre du code legacy.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from typing import AsyncIterator
|
| 8 |
+
import httpx
|
| 9 |
+
import json
|
| 10 |
+
|
| 11 |
+
from backend.ports.llm_provider import LLMProviderPort
|
| 12 |
+
from backend.domain.models import ChatRequest, ChatResponse, ChatMessage
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class AnthropicAdapter(LLMProviderPort):
|
| 16 |
+
"""Adapter natif pour Anthropic Claude API.
|
| 17 |
+
|
| 18 |
+
Implémente directement l'interface LLMProviderPort en utilisant
|
| 19 |
+
httpx pour les appels HTTP. Aucune dépendance au code legacy.
|
| 20 |
+
|
| 21 |
+
Note: Convertit automatiquement le format OpenAI vers le format Anthropic.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
SUPPORTED_MODEL_PREFIX = "claude-"
|
| 25 |
+
DEFAULT_BASE_URL = "https://api.anthropic.com/v1"
|
| 26 |
+
DEFAULT_TIMEOUT = 60.0
|
| 27 |
+
DEFAULT_MAX_TOKENS = 4096
|
| 28 |
+
ANTHROPIC_VERSION = "2023-06-01"
|
| 29 |
+
|
| 30 |
+
def __init__(self, base_url: str | None = None, timeout: float | None = None):
|
| 31 |
+
"""Initialise l'adapter Anthropic.
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
base_url: URL de base de l'API (défaut: https://api.anthropic.com/v1)
|
| 35 |
+
timeout: Timeout des requêtes en secondes (défaut: 60.0)
|
| 36 |
+
"""
|
| 37 |
+
self._base_url = base_url or self.DEFAULT_BASE_URL
|
| 38 |
+
self._timeout = timeout or self.DEFAULT_TIMEOUT
|
| 39 |
+
|
| 40 |
+
@property
|
| 41 |
+
def name(self) -> str:
|
| 42 |
+
return "anthropic"
|
| 43 |
+
|
| 44 |
+
def supports_model(self, model: str) -> bool:
|
| 45 |
+
"""Vérifie si le modèle est supporté par Anthropic."""
|
| 46 |
+
return model.startswith(self.SUPPORTED_MODEL_PREFIX)
|
| 47 |
+
|
| 48 |
+
async def chat(self, request: ChatRequest, api_key: str) -> ChatResponse:
|
| 49 |
+
"""Envoie une requête de chat completion à Anthropic.
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
request: Requête de chat (model, messages, etc.)
|
| 53 |
+
api_key: Clé API Anthropic
|
| 54 |
+
|
| 55 |
+
Returns:
|
| 56 |
+
ChatResponse avec le contenu et les tokens utilisés
|
| 57 |
+
|
| 58 |
+
Raises:
|
| 59 |
+
httpx.HTTPStatusError: Si l'API retourne une erreur
|
| 60 |
+
"""
|
| 61 |
+
system, messages = self._convert_messages(request.messages)
|
| 62 |
+
payload = self._build_payload(request, system, messages, stream=False)
|
| 63 |
+
|
| 64 |
+
async with httpx.AsyncClient(timeout=self._timeout) as client:
|
| 65 |
+
response = await client.post(
|
| 66 |
+
f"{self._base_url}/messages",
|
| 67 |
+
headers=self._build_headers(api_key),
|
| 68 |
+
json=payload,
|
| 69 |
+
)
|
| 70 |
+
response.raise_for_status()
|
| 71 |
+
data = response.json()
|
| 72 |
+
|
| 73 |
+
return self._parse_response(data)
|
| 74 |
+
|
| 75 |
+
async def chat_stream(
|
| 76 |
+
self, request: ChatRequest, api_key: str
|
| 77 |
+
) -> AsyncIterator[str]:
|
| 78 |
+
"""Stream une réponse de chat completion depuis Anthropic.
|
| 79 |
+
|
| 80 |
+
Convertit le format de streaming Anthropic vers le format OpenAI
|
| 81 |
+
pour compatibilité avec les clients existants.
|
| 82 |
+
|
| 83 |
+
Args:
|
| 84 |
+
request: Requête de chat (model, messages, etc.)
|
| 85 |
+
api_key: Clé API Anthropic
|
| 86 |
+
|
| 87 |
+
Yields:
|
| 88 |
+
Chunks de la réponse au format OpenAI SSE data (JSON string)
|
| 89 |
+
|
| 90 |
+
Raises:
|
| 91 |
+
httpx.HTTPStatusError: Si l'API retourne une erreur
|
| 92 |
+
"""
|
| 93 |
+
system, messages = self._convert_messages(request.messages)
|
| 94 |
+
payload = self._build_payload(request, system, messages, stream=True)
|
| 95 |
+
|
| 96 |
+
async with httpx.AsyncClient(timeout=self._timeout) as client:
|
| 97 |
+
async with client.stream(
|
| 98 |
+
"POST",
|
| 99 |
+
f"{self._base_url}/messages",
|
| 100 |
+
headers=self._build_headers(api_key),
|
| 101 |
+
json=payload,
|
| 102 |
+
) as response:
|
| 103 |
+
response.raise_for_status()
|
| 104 |
+
|
| 105 |
+
async for line in response.aiter_lines():
|
| 106 |
+
if line.startswith("data: "):
|
| 107 |
+
data = line[6:]
|
| 108 |
+
try:
|
| 109 |
+
event = json.loads(data)
|
| 110 |
+
# Convertir l'événement Anthropic vers le format OpenAI
|
| 111 |
+
openai_chunk = self._convert_stream_event(event)
|
| 112 |
+
if openai_chunk is None:
|
| 113 |
+
# message_stop event
|
| 114 |
+
break
|
| 115 |
+
if openai_chunk:
|
| 116 |
+
yield json.dumps(openai_chunk)
|
| 117 |
+
except json.JSONDecodeError:
|
| 118 |
+
continue
|
| 119 |
+
|
| 120 |
+
def _build_headers(self, api_key: str) -> dict[str, str]:
|
| 121 |
+
"""Construit les headers HTTP pour Anthropic."""
|
| 122 |
+
return {
|
| 123 |
+
"x-api-key": api_key,
|
| 124 |
+
"anthropic-version": self.ANTHROPIC_VERSION,
|
| 125 |
+
"Content-Type": "application/json",
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
def _convert_messages(
|
| 129 |
+
self, messages: list[ChatMessage]
|
| 130 |
+
) -> tuple[str | None, list[dict]]:
|
| 131 |
+
"""Convertit les messages du format OpenAI vers le format Anthropic.
|
| 132 |
+
|
| 133 |
+
Anthropic gère le message système séparément des autres messages.
|
| 134 |
+
|
| 135 |
+
Args:
|
| 136 |
+
messages: Liste de messages au format OpenAI
|
| 137 |
+
|
| 138 |
+
Returns:
|
| 139 |
+
Tuple (system_message, anthropic_messages)
|
| 140 |
+
"""
|
| 141 |
+
system = None
|
| 142 |
+
anthropic_messages = []
|
| 143 |
+
|
| 144 |
+
for msg in messages:
|
| 145 |
+
if msg.role == "system":
|
| 146 |
+
system = msg.content
|
| 147 |
+
else:
|
| 148 |
+
anthropic_messages.append(
|
| 149 |
+
{
|
| 150 |
+
"role": msg.role,
|
| 151 |
+
"content": msg.content,
|
| 152 |
+
}
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
return system, anthropic_messages
|
| 156 |
+
|
| 157 |
+
def _build_payload(
|
| 158 |
+
self,
|
| 159 |
+
request: ChatRequest,
|
| 160 |
+
system: str | None,
|
| 161 |
+
messages: list[dict],
|
| 162 |
+
stream: bool,
|
| 163 |
+
) -> dict:
|
| 164 |
+
"""Construit le payload de la requête pour Anthropic.
|
| 165 |
+
|
| 166 |
+
Args:
|
| 167 |
+
request: Requête de chat
|
| 168 |
+
system: Message système (optionnel)
|
| 169 |
+
messages: Messages convertis au format Anthropic
|
| 170 |
+
stream: Active le streaming
|
| 171 |
+
|
| 172 |
+
Returns:
|
| 173 |
+
Payload JSON pour l'API Anthropic
|
| 174 |
+
"""
|
| 175 |
+
payload = {
|
| 176 |
+
"model": request.model,
|
| 177 |
+
"messages": messages,
|
| 178 |
+
"max_tokens": request.max_tokens or self.DEFAULT_MAX_TOKENS,
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
if stream:
|
| 182 |
+
payload["stream"] = True
|
| 183 |
+
if system:
|
| 184 |
+
payload["system"] = system
|
| 185 |
+
if request.temperature is not None:
|
| 186 |
+
payload["temperature"] = request.temperature
|
| 187 |
+
|
| 188 |
+
return payload
|
| 189 |
+
|
| 190 |
+
def _parse_response(self, data: dict) -> ChatResponse:
|
| 191 |
+
"""Parse la réponse JSON de l'API Anthropic.
|
| 192 |
+
|
| 193 |
+
Args:
|
| 194 |
+
data: Réponse JSON de l'API Anthropic
|
| 195 |
+
|
| 196 |
+
Returns:
|
| 197 |
+
ChatResponse domain object
|
| 198 |
+
"""
|
| 199 |
+
# Extraire le contenu textuel des blocs
|
| 200 |
+
content = ""
|
| 201 |
+
for block in data.get("content", []):
|
| 202 |
+
if block.get("type") == "text":
|
| 203 |
+
content += block.get("text", "")
|
| 204 |
+
|
| 205 |
+
return ChatResponse(
|
| 206 |
+
id=data["id"],
|
| 207 |
+
model=data["model"],
|
| 208 |
+
content=content,
|
| 209 |
+
input_tokens=data["usage"]["input_tokens"],
|
| 210 |
+
output_tokens=data["usage"]["output_tokens"],
|
| 211 |
+
finish_reason=data.get("stop_reason") or "stop",
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
def _convert_stream_event(self, event: dict) -> dict | None:
|
| 215 |
+
"""Convertit un événement de streaming Anthropic vers le format OpenAI.
|
| 216 |
+
|
| 217 |
+
Args:
|
| 218 |
+
event: Événement SSE Anthropic
|
| 219 |
+
|
| 220 |
+
Returns:
|
| 221 |
+
Chunk au format OpenAI, ou None si message_stop
|
| 222 |
+
"""
|
| 223 |
+
event_type = event.get("type")
|
| 224 |
+
|
| 225 |
+
if event_type == "content_block_delta":
|
| 226 |
+
delta = event.get("delta", {})
|
| 227 |
+
if delta.get("type") == "text_delta":
|
| 228 |
+
return {
|
| 229 |
+
"choices": [
|
| 230 |
+
{
|
| 231 |
+
"delta": {"content": delta.get("text", "")},
|
| 232 |
+
"index": 0,
|
| 233 |
+
}
|
| 234 |
+
]
|
| 235 |
+
}
|
| 236 |
+
elif event_type == "message_stop":
|
| 237 |
+
return None
|
| 238 |
+
|
| 239 |
+
# Ignorer les autres types d'événements
|
| 240 |
+
return {}
|
backend/adapters/llm/mock_adapter.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Mock Adapter - Implémentation native pour les tests.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Adapter natif qui implémente directement
|
| 4 |
+
l'interface LLMProviderPort sans dépendre du code legacy.
|
| 5 |
+
Utile pour les tests unitaires et d'intégration.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from typing import AsyncIterator
|
| 9 |
+
import asyncio
|
| 10 |
+
import json
|
| 11 |
+
import uuid
|
| 12 |
+
|
| 13 |
+
from backend.ports.llm_provider import LLMProviderPort
|
| 14 |
+
from backend.domain.models import ChatRequest, ChatResponse
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class MockAdapter(LLMProviderPort):
|
| 18 |
+
"""Adapter mock natif pour les tests.
|
| 19 |
+
|
| 20 |
+
Simule les réponses LLM sans appeler d'API externe.
|
| 21 |
+
Aucune dépendance au code legacy.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
SUPPORTED_MODEL_PREFIXES = ("mock-",)
|
| 25 |
+
SUPPORTED_MODELS = ("test-model",)
|
| 26 |
+
DEFAULT_LATENCY = 0.1 # Simulated latency in seconds
|
| 27 |
+
STREAM_DELAY = 0.05 # Delay between stream chunks
|
| 28 |
+
|
| 29 |
+
def __init__(
|
| 30 |
+
self,
|
| 31 |
+
latency: float | None = None,
|
| 32 |
+
stream_delay: float | None = None,
|
| 33 |
+
fixed_response: str | None = None,
|
| 34 |
+
):
|
| 35 |
+
"""Initialise l'adapter Mock.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
latency: Latence simulée en secondes (défaut: 0.1)
|
| 39 |
+
stream_delay: Délai entre les chunks de streaming (défaut: 0.05)
|
| 40 |
+
fixed_response: Réponse fixe à retourner (optionnel)
|
| 41 |
+
"""
|
| 42 |
+
self._latency = latency if latency is not None else self.DEFAULT_LATENCY
|
| 43 |
+
self._stream_delay = (
|
| 44 |
+
stream_delay if stream_delay is not None else self.STREAM_DELAY
|
| 45 |
+
)
|
| 46 |
+
self._fixed_response = fixed_response
|
| 47 |
+
|
| 48 |
+
@property
|
| 49 |
+
def name(self) -> str:
|
| 50 |
+
return "mock"
|
| 51 |
+
|
| 52 |
+
def supports_model(self, model: str) -> bool:
|
| 53 |
+
"""Vérifie si le modèle est supporté (modèles mock uniquement)."""
|
| 54 |
+
if model in self.SUPPORTED_MODELS:
|
| 55 |
+
return True
|
| 56 |
+
return any(model.startswith(prefix) for prefix in self.SUPPORTED_MODEL_PREFIXES)
|
| 57 |
+
|
| 58 |
+
async def chat(self, request: ChatRequest, api_key: str) -> ChatResponse:
|
| 59 |
+
"""Retourne une réponse mock.
|
| 60 |
+
|
| 61 |
+
Args:
|
| 62 |
+
request: Requête de chat (model, messages, etc.)
|
| 63 |
+
api_key: Clé API (ignorée pour le mock)
|
| 64 |
+
|
| 65 |
+
Returns:
|
| 66 |
+
ChatResponse avec une réponse simulée
|
| 67 |
+
"""
|
| 68 |
+
# Simuler une latence réseau
|
| 69 |
+
if self._latency > 0:
|
| 70 |
+
await asyncio.sleep(self._latency)
|
| 71 |
+
|
| 72 |
+
# Générer la réponse
|
| 73 |
+
content = self._generate_response(request)
|
| 74 |
+
|
| 75 |
+
# Estimer les tokens (approximation)
|
| 76 |
+
input_tokens = self._estimate_tokens(request.messages)
|
| 77 |
+
output_tokens = self._estimate_tokens_from_text(content)
|
| 78 |
+
|
| 79 |
+
return ChatResponse(
|
| 80 |
+
id=f"mock-{uuid.uuid4().hex[:8]}",
|
| 81 |
+
model=request.model,
|
| 82 |
+
content=content,
|
| 83 |
+
input_tokens=input_tokens,
|
| 84 |
+
output_tokens=output_tokens,
|
| 85 |
+
finish_reason="stop",
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
async def chat_stream(
|
| 89 |
+
self, request: ChatRequest, api_key: str
|
| 90 |
+
) -> AsyncIterator[str]:
|
| 91 |
+
"""Stream une réponse mock mot par mot.
|
| 92 |
+
|
| 93 |
+
Args:
|
| 94 |
+
request: Requête de chat (model, messages, etc.)
|
| 95 |
+
api_key: Clé API (ignorée pour le mock)
|
| 96 |
+
|
| 97 |
+
Yields:
|
| 98 |
+
Chunks de la réponse au format OpenAI SSE data (JSON string)
|
| 99 |
+
"""
|
| 100 |
+
# Obtenir la réponse complète d'abord
|
| 101 |
+
response = await self.chat(request, api_key)
|
| 102 |
+
|
| 103 |
+
# Streamer mot par mot
|
| 104 |
+
words = response.content.split()
|
| 105 |
+
for word in words:
|
| 106 |
+
if self._stream_delay > 0:
|
| 107 |
+
await asyncio.sleep(self._stream_delay)
|
| 108 |
+
chunk = {
|
| 109 |
+
"choices": [
|
| 110 |
+
{
|
| 111 |
+
"delta": {"content": f"{word} "},
|
| 112 |
+
"index": 0,
|
| 113 |
+
}
|
| 114 |
+
]
|
| 115 |
+
}
|
| 116 |
+
yield json.dumps(chunk)
|
| 117 |
+
|
| 118 |
+
# Envoyer le chunk final
|
| 119 |
+
final_chunk = {
|
| 120 |
+
"choices": [
|
| 121 |
+
{
|
| 122 |
+
"delta": {},
|
| 123 |
+
"finish_reason": "stop",
|
| 124 |
+
"index": 0,
|
| 125 |
+
}
|
| 126 |
+
]
|
| 127 |
+
}
|
| 128 |
+
yield json.dumps(final_chunk)
|
| 129 |
+
|
| 130 |
+
def _generate_response(self, request: ChatRequest) -> str:
|
| 131 |
+
"""Génère une réponse mock basée sur le message utilisateur.
|
| 132 |
+
|
| 133 |
+
Args:
|
| 134 |
+
request: Requête de chat
|
| 135 |
+
|
| 136 |
+
Returns:
|
| 137 |
+
Contenu de la réponse simulée
|
| 138 |
+
"""
|
| 139 |
+
if self._fixed_response:
|
| 140 |
+
return self._fixed_response
|
| 141 |
+
|
| 142 |
+
# Trouver le dernier message utilisateur
|
| 143 |
+
user_message = ""
|
| 144 |
+
for msg in request.messages:
|
| 145 |
+
if msg.role == "user":
|
| 146 |
+
user_message = msg.content
|
| 147 |
+
|
| 148 |
+
# Générer une réponse basée sur le message
|
| 149 |
+
if len(user_message) > 50:
|
| 150 |
+
return f"This is a mock response to: '{user_message[:50]}...'"
|
| 151 |
+
return f"This is a mock response to: '{user_message}'"
|
| 152 |
+
|
| 153 |
+
def _estimate_tokens(self, messages: list) -> int:
|
| 154 |
+
"""Estime le nombre de tokens des messages.
|
| 155 |
+
|
| 156 |
+
Args:
|
| 157 |
+
messages: Liste de messages
|
| 158 |
+
|
| 159 |
+
Returns:
|
| 160 |
+
Nombre estimé de tokens
|
| 161 |
+
"""
|
| 162 |
+
total_words = sum(len(msg.content.split()) for msg in messages)
|
| 163 |
+
return int(total_words * 1.3) # Approximation: ~1.3 tokens par mot
|
| 164 |
+
|
| 165 |
+
def _estimate_tokens_from_text(self, text: str) -> int:
|
| 166 |
+
"""Estime le nombre de tokens d'un texte.
|
| 167 |
+
|
| 168 |
+
Args:
|
| 169 |
+
text: Texte à analyser
|
| 170 |
+
|
| 171 |
+
Returns:
|
| 172 |
+
Nombre estimé de tokens
|
| 173 |
+
"""
|
| 174 |
+
return int(len(text.split()) * 1.3)
|
backend/adapters/llm/ollama_adapter.py
ADDED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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Ollama Adapter - Implémentation du port LLMProviderPort pour Ollama.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Adapter qui implémente l'interface LLMProviderPort
|
| 4 |
+
pour les modèles locaux via Ollama (OpenAI-compatible API).
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from typing import AsyncIterator
|
| 8 |
+
import httpx
|
| 9 |
+
|
| 10 |
+
from backend.ports.llm_provider import LLMProviderPort
|
| 11 |
+
from backend.domain.models import ChatRequest, ChatResponse
|
| 12 |
+
from backend.core.config import settings
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class OllamaAdapter(LLMProviderPort):
|
| 16 |
+
"""Adapter pour Ollama (OpenAI-compatible API).
|
| 17 |
+
|
| 18 |
+
Supporte les modèles locaux comme Llama, Mistral, Qwen, etc.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
SUPPORTED_MODEL_PREFIXES = (
|
| 22 |
+
"llama",
|
| 23 |
+
"mistral",
|
| 24 |
+
"mixtral",
|
| 25 |
+
"codellama",
|
| 26 |
+
"phi",
|
| 27 |
+
"gemma",
|
| 28 |
+
"qwen",
|
| 29 |
+
"deepseek",
|
| 30 |
+
"starcoder",
|
| 31 |
+
"wizard",
|
| 32 |
+
"neural-chat",
|
| 33 |
+
"openchat",
|
| 34 |
+
"orca",
|
| 35 |
+
"vicuna",
|
| 36 |
+
"zephyr",
|
| 37 |
+
"dolphin",
|
| 38 |
+
"nous-hermes",
|
| 39 |
+
"solar",
|
| 40 |
+
"yi",
|
| 41 |
+
"falcon",
|
| 42 |
+
"tinyllama",
|
| 43 |
+
"granite",
|
| 44 |
+
"codegemma",
|
| 45 |
+
"minicpm",
|
| 46 |
+
)
|
| 47 |
+
DEFAULT_BASE_URL = "http://localhost:11434"
|
| 48 |
+
DEFAULT_TIMEOUT = 120.0
|
| 49 |
+
|
| 50 |
+
def __init__(self, base_url: str | None = None, timeout: float | None = None):
|
| 51 |
+
"""Initialise l'adapter Ollama.
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
base_url: URL de base de l'API Ollama (défaut: http://localhost:11434)
|
| 55 |
+
timeout: Timeout des requêtes en secondes (défaut: 120.0)
|
| 56 |
+
"""
|
| 57 |
+
self._base_url = base_url or getattr(
|
| 58 |
+
settings, "ollama_api_url", self.DEFAULT_BASE_URL
|
| 59 |
+
)
|
| 60 |
+
self._timeout = timeout or self.DEFAULT_TIMEOUT
|
| 61 |
+
|
| 62 |
+
@property
|
| 63 |
+
def name(self) -> str:
|
| 64 |
+
return "ollama"
|
| 65 |
+
|
| 66 |
+
def supports_model(self, model: str) -> bool:
|
| 67 |
+
"""Vérifie si le modèle est supporté par Ollama."""
|
| 68 |
+
model_lower = model.lower()
|
| 69 |
+
# Check prefixes
|
| 70 |
+
for prefix in self.SUPPORTED_MODEL_PREFIXES:
|
| 71 |
+
if model_lower.startswith(prefix):
|
| 72 |
+
return True
|
| 73 |
+
# Check if it contains a slash (like qwen/qwen2.5-vl-7b)
|
| 74 |
+
if "/" in model:
|
| 75 |
+
model_name = model.split("/")[-1].lower()
|
| 76 |
+
for prefix in self.SUPPORTED_MODEL_PREFIXES:
|
| 77 |
+
if model_name.startswith(prefix):
|
| 78 |
+
return True
|
| 79 |
+
# Also check the org name
|
| 80 |
+
org_name = model.split("/")[0].lower()
|
| 81 |
+
for prefix in self.SUPPORTED_MODEL_PREFIXES:
|
| 82 |
+
if org_name.startswith(prefix):
|
| 83 |
+
return True
|
| 84 |
+
return False
|
| 85 |
+
|
| 86 |
+
async def chat(self, request: ChatRequest, api_key: str = "") -> ChatResponse:
|
| 87 |
+
"""Envoie une requête de chat completion à Ollama.
|
| 88 |
+
|
| 89 |
+
Args:
|
| 90 |
+
request: Requête de chat (model, messages, etc.)
|
| 91 |
+
api_key: Non utilisé pour Ollama (modèles locaux)
|
| 92 |
+
|
| 93 |
+
Returns:
|
| 94 |
+
ChatResponse avec le contenu et les tokens utilisés
|
| 95 |
+
"""
|
| 96 |
+
payload = self._build_payload(request, stream=False)
|
| 97 |
+
|
| 98 |
+
async with httpx.AsyncClient(timeout=self._timeout) as client:
|
| 99 |
+
response = await client.post(
|
| 100 |
+
f"{self._base_url}/v1/chat/completions",
|
| 101 |
+
headers={"Content-Type": "application/json"},
|
| 102 |
+
json=payload,
|
| 103 |
+
)
|
| 104 |
+
response.raise_for_status()
|
| 105 |
+
data = response.json()
|
| 106 |
+
|
| 107 |
+
return self._parse_response(data)
|
| 108 |
+
|
| 109 |
+
async def chat_stream(
|
| 110 |
+
self, request: ChatRequest, api_key: str = ""
|
| 111 |
+
) -> AsyncIterator[str]:
|
| 112 |
+
"""Stream une réponse de chat completion depuis Ollama.
|
| 113 |
+
|
| 114 |
+
Args:
|
| 115 |
+
request: Requête de chat (model, messages, etc.)
|
| 116 |
+
api_key: Non utilisé pour Ollama
|
| 117 |
+
|
| 118 |
+
Yields:
|
| 119 |
+
Chunks de la réponse au format SSE data (JSON string)
|
| 120 |
+
"""
|
| 121 |
+
payload = self._build_payload(request, stream=True)
|
| 122 |
+
|
| 123 |
+
async with httpx.AsyncClient(timeout=self._timeout) as client:
|
| 124 |
+
async with client.stream(
|
| 125 |
+
"POST",
|
| 126 |
+
f"{self._base_url}/v1/chat/completions",
|
| 127 |
+
headers={"Content-Type": "application/json"},
|
| 128 |
+
json=payload,
|
| 129 |
+
) as response:
|
| 130 |
+
response.raise_for_status()
|
| 131 |
+
|
| 132 |
+
async for line in response.aiter_lines():
|
| 133 |
+
if line.startswith("data: "):
|
| 134 |
+
data = line[6:]
|
| 135 |
+
if data == "[DONE]":
|
| 136 |
+
break
|
| 137 |
+
yield data
|
| 138 |
+
|
| 139 |
+
def _build_payload(self, request: ChatRequest, stream: bool) -> dict:
|
| 140 |
+
"""Construit le payload de la requête."""
|
| 141 |
+
# Strip provider prefix if present (lmstudio/, ollama/)
|
| 142 |
+
model = request.model
|
| 143 |
+
for prefix in ("lmstudio/", "ollama/"):
|
| 144 |
+
if model.startswith(prefix):
|
| 145 |
+
model = model[len(prefix) :]
|
| 146 |
+
break
|
| 147 |
+
|
| 148 |
+
payload = {
|
| 149 |
+
"model": model,
|
| 150 |
+
"messages": [
|
| 151 |
+
{"role": msg.role, "content": msg.content} for msg in request.messages
|
| 152 |
+
],
|
| 153 |
+
"stream": stream,
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
if request.max_tokens is not None:
|
| 157 |
+
payload["max_tokens"] = request.max_tokens
|
| 158 |
+
if request.temperature is not None:
|
| 159 |
+
payload["temperature"] = request.temperature
|
| 160 |
+
|
| 161 |
+
return payload
|
| 162 |
+
|
| 163 |
+
def _parse_response(self, data: dict) -> ChatResponse:
|
| 164 |
+
"""Parse la réponse JSON de l'API."""
|
| 165 |
+
choice = data["choices"][0]
|
| 166 |
+
usage = data.get("usage", {})
|
| 167 |
+
|
| 168 |
+
return ChatResponse(
|
| 169 |
+
id=data.get("id", f"ollama-{data.get('model', 'unknown')}"),
|
| 170 |
+
model=data.get("model", "unknown"),
|
| 171 |
+
content=choice["message"]["content"],
|
| 172 |
+
input_tokens=usage.get("prompt_tokens", 0),
|
| 173 |
+
output_tokens=usage.get("completion_tokens", 0),
|
| 174 |
+
finish_reason=choice.get("finish_reason", "stop"),
|
| 175 |
+
)
|
backend/adapters/llm/openai_adapter.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""OpenAI Adapter - Implémentation native du port LLMProviderPort.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Adapter natif qui implémente directement
|
| 4 |
+
l'interface LLMProviderPort sans dépendre du code legacy.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from typing import AsyncIterator
|
| 8 |
+
import httpx
|
| 9 |
+
|
| 10 |
+
from backend.ports.llm_provider import LLMProviderPort
|
| 11 |
+
from backend.domain.models import ChatRequest, ChatResponse
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class OpenAIAdapter(LLMProviderPort):
|
| 15 |
+
"""Adapter natif pour OpenAI API.
|
| 16 |
+
|
| 17 |
+
Implémente directement l'interface LLMProviderPort en utilisant
|
| 18 |
+
httpx pour les appels HTTP. Aucune dépendance au code legacy.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
SUPPORTED_MODEL_PREFIXES = ("gpt-", "o1", "o3")
|
| 22 |
+
SUPPORTED_MODELS = ("chatgpt-4o-latest",)
|
| 23 |
+
DEFAULT_BASE_URL = "https://api.openai.com/v1"
|
| 24 |
+
DEFAULT_TIMEOUT = 60.0
|
| 25 |
+
|
| 26 |
+
def __init__(self, base_url: str | None = None, timeout: float | None = None):
|
| 27 |
+
"""Initialise l'adapter OpenAI.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
base_url: URL de base de l'API (défaut: https://api.openai.com/v1)
|
| 31 |
+
timeout: Timeout des requêtes en secondes (défaut: 60.0)
|
| 32 |
+
"""
|
| 33 |
+
self._base_url = base_url or self.DEFAULT_BASE_URL
|
| 34 |
+
self._timeout = timeout or self.DEFAULT_TIMEOUT
|
| 35 |
+
|
| 36 |
+
@property
|
| 37 |
+
def name(self) -> str:
|
| 38 |
+
return "openai"
|
| 39 |
+
|
| 40 |
+
def supports_model(self, model: str) -> bool:
|
| 41 |
+
"""Vérifie si le modèle est supporté par OpenAI."""
|
| 42 |
+
if model in self.SUPPORTED_MODELS:
|
| 43 |
+
return True
|
| 44 |
+
return any(model.startswith(prefix) for prefix in self.SUPPORTED_MODEL_PREFIXES)
|
| 45 |
+
|
| 46 |
+
async def chat(self, request: ChatRequest, api_key: str) -> ChatResponse:
|
| 47 |
+
"""Envoie une requête de chat completion à OpenAI.
|
| 48 |
+
|
| 49 |
+
Args:
|
| 50 |
+
request: Requête de chat (model, messages, etc.)
|
| 51 |
+
api_key: Clé API OpenAI
|
| 52 |
+
|
| 53 |
+
Returns:
|
| 54 |
+
ChatResponse avec le contenu et les tokens utilisés
|
| 55 |
+
|
| 56 |
+
Raises:
|
| 57 |
+
httpx.HTTPStatusError: Si l'API retourne une erreur
|
| 58 |
+
"""
|
| 59 |
+
payload = self._build_payload(request, stream=False)
|
| 60 |
+
|
| 61 |
+
async with httpx.AsyncClient(timeout=self._timeout) as client:
|
| 62 |
+
response = await client.post(
|
| 63 |
+
f"{self._base_url}/chat/completions",
|
| 64 |
+
headers=self._build_headers(api_key),
|
| 65 |
+
json=payload,
|
| 66 |
+
)
|
| 67 |
+
response.raise_for_status()
|
| 68 |
+
data = response.json()
|
| 69 |
+
|
| 70 |
+
return self._parse_response(data)
|
| 71 |
+
|
| 72 |
+
async def chat_stream(
|
| 73 |
+
self, request: ChatRequest, api_key: str
|
| 74 |
+
) -> AsyncIterator[str]:
|
| 75 |
+
"""Stream une réponse de chat completion depuis OpenAI.
|
| 76 |
+
|
| 77 |
+
Args:
|
| 78 |
+
request: Requête de chat (model, messages, etc.)
|
| 79 |
+
api_key: Clé API OpenAI
|
| 80 |
+
|
| 81 |
+
Yields:
|
| 82 |
+
Chunks de la réponse au format SSE data (JSON string)
|
| 83 |
+
|
| 84 |
+
Raises:
|
| 85 |
+
httpx.HTTPStatusError: Si l'API retourne une erreur
|
| 86 |
+
"""
|
| 87 |
+
payload = self._build_payload(request, stream=True)
|
| 88 |
+
|
| 89 |
+
async with httpx.AsyncClient(timeout=self._timeout) as client:
|
| 90 |
+
async with client.stream(
|
| 91 |
+
"POST",
|
| 92 |
+
f"{self._base_url}/chat/completions",
|
| 93 |
+
headers=self._build_headers(api_key),
|
| 94 |
+
json=payload,
|
| 95 |
+
) as response:
|
| 96 |
+
response.raise_for_status()
|
| 97 |
+
|
| 98 |
+
async for line in response.aiter_lines():
|
| 99 |
+
if line.startswith("data: "):
|
| 100 |
+
data = line[6:]
|
| 101 |
+
if data == "[DONE]":
|
| 102 |
+
break
|
| 103 |
+
yield data
|
| 104 |
+
|
| 105 |
+
def _build_headers(self, api_key: str) -> dict[str, str]:
|
| 106 |
+
"""Construit les headers HTTP."""
|
| 107 |
+
return {
|
| 108 |
+
"Authorization": f"Bearer {api_key}",
|
| 109 |
+
"Content-Type": "application/json",
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
def _build_payload(self, request: ChatRequest, stream: bool) -> dict:
|
| 113 |
+
"""Construit le payload de la requête.
|
| 114 |
+
|
| 115 |
+
Args:
|
| 116 |
+
request: Requête de chat
|
| 117 |
+
stream: Active le streaming
|
| 118 |
+
|
| 119 |
+
Returns:
|
| 120 |
+
Payload JSON pour l'API OpenAI
|
| 121 |
+
"""
|
| 122 |
+
payload = {
|
| 123 |
+
"model": request.model,
|
| 124 |
+
"messages": [
|
| 125 |
+
{"role": msg.role, "content": msg.content} for msg in request.messages
|
| 126 |
+
],
|
| 127 |
+
"stream": stream,
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
if request.max_tokens is not None:
|
| 131 |
+
payload["max_tokens"] = request.max_tokens
|
| 132 |
+
if request.temperature is not None:
|
| 133 |
+
payload["temperature"] = request.temperature
|
| 134 |
+
|
| 135 |
+
return payload
|
| 136 |
+
|
| 137 |
+
def _parse_response(self, data: dict) -> ChatResponse:
|
| 138 |
+
"""Parse la réponse JSON de l'API.
|
| 139 |
+
|
| 140 |
+
Args:
|
| 141 |
+
data: Réponse JSON de l'API OpenAI
|
| 142 |
+
|
| 143 |
+
Returns:
|
| 144 |
+
ChatResponse domain object
|
| 145 |
+
"""
|
| 146 |
+
choice = data["choices"][0]
|
| 147 |
+
usage = data.get("usage", {})
|
| 148 |
+
|
| 149 |
+
return ChatResponse(
|
| 150 |
+
id=data["id"],
|
| 151 |
+
model=data["model"],
|
| 152 |
+
content=choice["message"]["content"],
|
| 153 |
+
input_tokens=usage.get("prompt_tokens", 0),
|
| 154 |
+
output_tokens=usage.get("completion_tokens", 0),
|
| 155 |
+
finish_reason=choice.get("finish_reason"),
|
| 156 |
+
)
|
backend/adapters/llm/openai_embedding_adapter.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""OpenAI Embedding Adapter - Adapter pour les embeddings OpenAI.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Adapter qui implémente le Port EmbeddingProviderPort.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import httpx
|
| 7 |
+
|
| 8 |
+
from backend.ports.embedding_provider import EmbeddingProviderPort
|
| 9 |
+
from backend.domain.models import EmbeddingRequest, EmbeddingResponse, EmbeddingData
|
| 10 |
+
from backend.core.config import settings
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class OpenAIEmbeddingAdapter(EmbeddingProviderPort):
|
| 14 |
+
"""Adapter pour les embeddings OpenAI.
|
| 15 |
+
|
| 16 |
+
Implémente l'interface EmbeddingProviderPort pour OpenAI.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
def __init__(self):
|
| 20 |
+
self.base_url = settings.openai_api_url
|
| 21 |
+
|
| 22 |
+
@property
|
| 23 |
+
def name(self) -> str:
|
| 24 |
+
return "openai"
|
| 25 |
+
|
| 26 |
+
def supports_model(self, model: str) -> bool:
|
| 27 |
+
"""Vérifie si le modèle est un modèle d'embedding OpenAI."""
|
| 28 |
+
return (
|
| 29 |
+
model.startswith("text-embedding-")
|
| 30 |
+
or model == "text-embedding-ada-002"
|
| 31 |
+
or model == "text-embedding-3-small"
|
| 32 |
+
or model == "text-embedding-3-large"
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
async def embed(self, request: EmbeddingRequest, api_key: str) -> EmbeddingResponse:
|
| 36 |
+
"""Génère des embeddings via l'API OpenAI."""
|
| 37 |
+
async with httpx.AsyncClient(timeout=30.0) as client:
|
| 38 |
+
response = await client.post(
|
| 39 |
+
f"{self.base_url}/embeddings",
|
| 40 |
+
headers={
|
| 41 |
+
"Authorization": f"Bearer {api_key}",
|
| 42 |
+
"Content-Type": "application/json",
|
| 43 |
+
},
|
| 44 |
+
json={
|
| 45 |
+
"model": request.model,
|
| 46 |
+
"input": request.input,
|
| 47 |
+
"encoding_format": request.encoding_format,
|
| 48 |
+
},
|
| 49 |
+
)
|
| 50 |
+
response.raise_for_status()
|
| 51 |
+
data = response.json()
|
| 52 |
+
|
| 53 |
+
# Convertir la réponse OpenAI vers le format domain
|
| 54 |
+
embeddings = [
|
| 55 |
+
EmbeddingData(
|
| 56 |
+
index=item["index"],
|
| 57 |
+
embedding=item["embedding"],
|
| 58 |
+
)
|
| 59 |
+
for item in data["data"]
|
| 60 |
+
]
|
| 61 |
+
|
| 62 |
+
return EmbeddingResponse(
|
| 63 |
+
model=data["model"],
|
| 64 |
+
data=embeddings,
|
| 65 |
+
total_tokens=data["usage"]["total_tokens"],
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# Singleton
|
| 70 |
+
openai_embedding_adapter = OpenAIEmbeddingAdapter()
|
backend/adapters/model_registry/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Model Registry Adapters.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Implementations du ModelRegistryPort.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from backend.adapters.model_registry.in_memory_adapter import (
|
| 7 |
+
InMemoryModelRegistryAdapter,
|
| 8 |
+
)
|
| 9 |
+
from backend.adapters.model_registry.postgres_adapter import (
|
| 10 |
+
PostgresModelRegistryAdapter,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
__all__ = [
|
| 14 |
+
"InMemoryModelRegistryAdapter",
|
| 15 |
+
"PostgresModelRegistryAdapter",
|
| 16 |
+
]
|
backend/adapters/model_registry/in_memory_adapter.py
ADDED
|
@@ -0,0 +1,534 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""In-Memory Model Registry Adapter.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Implémentation native du ModelRegistryPort
|
| 4 |
+
avec catalogue de modèles pré-configuré.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
from backend.ports.model_registry import (
|
| 11 |
+
ModelRegistryPort,
|
| 12 |
+
ModelInfo,
|
| 13 |
+
ModelPricing,
|
| 14 |
+
ModelLimits,
|
| 15 |
+
ModelValidation,
|
| 16 |
+
ProviderType,
|
| 17 |
+
ModelStatus,
|
| 18 |
+
ModelCapability,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
# Pre-configured models catalog
|
| 23 |
+
DEFAULT_MODELS: list[ModelInfo] = [
|
| 24 |
+
# OpenAI Models
|
| 25 |
+
ModelInfo(
|
| 26 |
+
model_id="gpt-4o",
|
| 27 |
+
name="GPT-4o",
|
| 28 |
+
provider=ProviderType.OPENAI,
|
| 29 |
+
provider_model_id="gpt-4o",
|
| 30 |
+
description="Most advanced multimodal model",
|
| 31 |
+
capabilities=[
|
| 32 |
+
ModelCapability.CHAT,
|
| 33 |
+
ModelCapability.VISION,
|
| 34 |
+
ModelCapability.FUNCTION_CALLING,
|
| 35 |
+
ModelCapability.STREAMING,
|
| 36 |
+
ModelCapability.JSON_MODE,
|
| 37 |
+
ModelCapability.SYSTEM_PROMPT,
|
| 38 |
+
],
|
| 39 |
+
pricing=ModelPricing(input_per_million=2.50, output_per_million=10.00),
|
| 40 |
+
limits=ModelLimits(
|
| 41 |
+
max_context_tokens=128000, max_output_tokens=16384, max_images=10
|
| 42 |
+
),
|
| 43 |
+
tags=["flagship", "multimodal"],
|
| 44 |
+
),
|
| 45 |
+
ModelInfo(
|
| 46 |
+
model_id="gpt-4o-mini",
|
| 47 |
+
name="GPT-4o Mini",
|
| 48 |
+
provider=ProviderType.OPENAI,
|
| 49 |
+
provider_model_id="gpt-4o-mini",
|
| 50 |
+
description="Affordable and intelligent small model",
|
| 51 |
+
capabilities=[
|
| 52 |
+
ModelCapability.CHAT,
|
| 53 |
+
ModelCapability.VISION,
|
| 54 |
+
ModelCapability.FUNCTION_CALLING,
|
| 55 |
+
ModelCapability.STREAMING,
|
| 56 |
+
ModelCapability.JSON_MODE,
|
| 57 |
+
ModelCapability.SYSTEM_PROMPT,
|
| 58 |
+
],
|
| 59 |
+
pricing=ModelPricing(input_per_million=0.15, output_per_million=0.60),
|
| 60 |
+
limits=ModelLimits(max_context_tokens=128000, max_output_tokens=16384),
|
| 61 |
+
tags=["affordable", "fast"],
|
| 62 |
+
),
|
| 63 |
+
ModelInfo(
|
| 64 |
+
model_id="gpt-4-turbo",
|
| 65 |
+
name="GPT-4 Turbo",
|
| 66 |
+
provider=ProviderType.OPENAI,
|
| 67 |
+
provider_model_id="gpt-4-turbo",
|
| 68 |
+
description="GPT-4 Turbo with vision",
|
| 69 |
+
capabilities=[
|
| 70 |
+
ModelCapability.CHAT,
|
| 71 |
+
ModelCapability.VISION,
|
| 72 |
+
ModelCapability.FUNCTION_CALLING,
|
| 73 |
+
ModelCapability.STREAMING,
|
| 74 |
+
ModelCapability.JSON_MODE,
|
| 75 |
+
ModelCapability.SYSTEM_PROMPT,
|
| 76 |
+
],
|
| 77 |
+
pricing=ModelPricing(input_per_million=10.00, output_per_million=30.00),
|
| 78 |
+
limits=ModelLimits(max_context_tokens=128000, max_output_tokens=4096),
|
| 79 |
+
tags=["vision", "turbo"],
|
| 80 |
+
),
|
| 81 |
+
ModelInfo(
|
| 82 |
+
model_id="gpt-3.5-turbo",
|
| 83 |
+
name="GPT-3.5 Turbo",
|
| 84 |
+
provider=ProviderType.OPENAI,
|
| 85 |
+
provider_model_id="gpt-3.5-turbo",
|
| 86 |
+
description="Fast and cost-effective model",
|
| 87 |
+
capabilities=[
|
| 88 |
+
ModelCapability.CHAT,
|
| 89 |
+
ModelCapability.FUNCTION_CALLING,
|
| 90 |
+
ModelCapability.STREAMING,
|
| 91 |
+
ModelCapability.JSON_MODE,
|
| 92 |
+
ModelCapability.SYSTEM_PROMPT,
|
| 93 |
+
],
|
| 94 |
+
pricing=ModelPricing(input_per_million=0.50, output_per_million=1.50),
|
| 95 |
+
limits=ModelLimits(max_context_tokens=16385, max_output_tokens=4096),
|
| 96 |
+
tags=["affordable", "fast", "legacy"],
|
| 97 |
+
),
|
| 98 |
+
ModelInfo(
|
| 99 |
+
model_id="text-embedding-3-large",
|
| 100 |
+
name="Text Embedding 3 Large",
|
| 101 |
+
provider=ProviderType.OPENAI,
|
| 102 |
+
provider_model_id="text-embedding-3-large",
|
| 103 |
+
description="Most capable embedding model",
|
| 104 |
+
capabilities=[ModelCapability.EMBEDDING],
|
| 105 |
+
pricing=ModelPricing(input_per_million=0.13, output_per_million=0.0),
|
| 106 |
+
limits=ModelLimits(max_context_tokens=8191, max_output_tokens=0),
|
| 107 |
+
tags=["embedding", "large"],
|
| 108 |
+
),
|
| 109 |
+
ModelInfo(
|
| 110 |
+
model_id="text-embedding-3-small",
|
| 111 |
+
name="Text Embedding 3 Small",
|
| 112 |
+
provider=ProviderType.OPENAI,
|
| 113 |
+
provider_model_id="text-embedding-3-small",
|
| 114 |
+
description="Efficient embedding model",
|
| 115 |
+
capabilities=[ModelCapability.EMBEDDING],
|
| 116 |
+
pricing=ModelPricing(input_per_million=0.02, output_per_million=0.0),
|
| 117 |
+
limits=ModelLimits(max_context_tokens=8191, max_output_tokens=0),
|
| 118 |
+
tags=["embedding", "affordable"],
|
| 119 |
+
),
|
| 120 |
+
# Anthropic Models
|
| 121 |
+
ModelInfo(
|
| 122 |
+
model_id="claude-3-5-sonnet",
|
| 123 |
+
name="Claude 3.5 Sonnet",
|
| 124 |
+
provider=ProviderType.ANTHROPIC,
|
| 125 |
+
provider_model_id="claude-3-5-sonnet-20241022",
|
| 126 |
+
description="Most intelligent Claude model",
|
| 127 |
+
capabilities=[
|
| 128 |
+
ModelCapability.CHAT,
|
| 129 |
+
ModelCapability.VISION,
|
| 130 |
+
ModelCapability.FUNCTION_CALLING,
|
| 131 |
+
ModelCapability.STREAMING,
|
| 132 |
+
ModelCapability.SYSTEM_PROMPT,
|
| 133 |
+
],
|
| 134 |
+
pricing=ModelPricing(input_per_million=3.00, output_per_million=15.00),
|
| 135 |
+
limits=ModelLimits(
|
| 136 |
+
max_context_tokens=200000, max_output_tokens=8192, max_images=20
|
| 137 |
+
),
|
| 138 |
+
tags=["flagship", "multimodal"],
|
| 139 |
+
),
|
| 140 |
+
ModelInfo(
|
| 141 |
+
model_id="claude-3-5-haiku",
|
| 142 |
+
name="Claude 3.5 Haiku",
|
| 143 |
+
provider=ProviderType.ANTHROPIC,
|
| 144 |
+
provider_model_id="claude-3-5-haiku-20241022",
|
| 145 |
+
description="Fast and affordable Claude model",
|
| 146 |
+
capabilities=[
|
| 147 |
+
ModelCapability.CHAT,
|
| 148 |
+
ModelCapability.VISION,
|
| 149 |
+
ModelCapability.FUNCTION_CALLING,
|
| 150 |
+
ModelCapability.STREAMING,
|
| 151 |
+
ModelCapability.SYSTEM_PROMPT,
|
| 152 |
+
],
|
| 153 |
+
pricing=ModelPricing(input_per_million=0.80, output_per_million=4.00),
|
| 154 |
+
limits=ModelLimits(max_context_tokens=200000, max_output_tokens=8192),
|
| 155 |
+
tags=["affordable", "fast"],
|
| 156 |
+
),
|
| 157 |
+
ModelInfo(
|
| 158 |
+
model_id="claude-3-opus",
|
| 159 |
+
name="Claude 3 Opus",
|
| 160 |
+
provider=ProviderType.ANTHROPIC,
|
| 161 |
+
provider_model_id="claude-3-opus-20240229",
|
| 162 |
+
description="Most powerful Claude for complex tasks",
|
| 163 |
+
capabilities=[
|
| 164 |
+
ModelCapability.CHAT,
|
| 165 |
+
ModelCapability.VISION,
|
| 166 |
+
ModelCapability.FUNCTION_CALLING,
|
| 167 |
+
ModelCapability.STREAMING,
|
| 168 |
+
ModelCapability.SYSTEM_PROMPT,
|
| 169 |
+
],
|
| 170 |
+
pricing=ModelPricing(input_per_million=15.00, output_per_million=75.00),
|
| 171 |
+
limits=ModelLimits(max_context_tokens=200000, max_output_tokens=4096),
|
| 172 |
+
tags=["powerful", "complex-tasks"],
|
| 173 |
+
),
|
| 174 |
+
# Mistral Models
|
| 175 |
+
ModelInfo(
|
| 176 |
+
model_id="mistral-large",
|
| 177 |
+
name="Mistral Large",
|
| 178 |
+
provider=ProviderType.MISTRAL,
|
| 179 |
+
provider_model_id="mistral-large-latest",
|
| 180 |
+
description="Mistral flagship model",
|
| 181 |
+
capabilities=[
|
| 182 |
+
ModelCapability.CHAT,
|
| 183 |
+
ModelCapability.FUNCTION_CALLING,
|
| 184 |
+
ModelCapability.STREAMING,
|
| 185 |
+
ModelCapability.JSON_MODE,
|
| 186 |
+
ModelCapability.SYSTEM_PROMPT,
|
| 187 |
+
],
|
| 188 |
+
pricing=ModelPricing(input_per_million=2.00, output_per_million=6.00),
|
| 189 |
+
limits=ModelLimits(max_context_tokens=128000, max_output_tokens=4096),
|
| 190 |
+
tags=["flagship"],
|
| 191 |
+
),
|
| 192 |
+
ModelInfo(
|
| 193 |
+
model_id="mistral-small",
|
| 194 |
+
name="Mistral Small",
|
| 195 |
+
provider=ProviderType.MISTRAL,
|
| 196 |
+
provider_model_id="mistral-small-latest",
|
| 197 |
+
description="Fast and efficient Mistral model",
|
| 198 |
+
capabilities=[
|
| 199 |
+
ModelCapability.CHAT,
|
| 200 |
+
ModelCapability.FUNCTION_CALLING,
|
| 201 |
+
ModelCapability.STREAMING,
|
| 202 |
+
ModelCapability.SYSTEM_PROMPT,
|
| 203 |
+
],
|
| 204 |
+
pricing=ModelPricing(input_per_million=0.20, output_per_million=0.60),
|
| 205 |
+
limits=ModelLimits(max_context_tokens=32000, max_output_tokens=4096),
|
| 206 |
+
tags=["affordable", "fast"],
|
| 207 |
+
),
|
| 208 |
+
]
|
| 209 |
+
|
| 210 |
+
# Model aliases
|
| 211 |
+
DEFAULT_ALIASES: dict[str, str] = {
|
| 212 |
+
"gpt-4": "gpt-4-turbo",
|
| 213 |
+
"gpt-4o-latest": "gpt-4o",
|
| 214 |
+
"claude-3-sonnet": "claude-3-5-sonnet",
|
| 215 |
+
"claude-sonnet": "claude-3-5-sonnet",
|
| 216 |
+
"claude-haiku": "claude-3-5-haiku",
|
| 217 |
+
"claude-opus": "claude-3-opus",
|
| 218 |
+
"mistral": "mistral-large",
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
class InMemoryModelRegistryAdapter(ModelRegistryPort):
|
| 223 |
+
"""
|
| 224 |
+
In-memory model registry with pre-configured catalog.
|
| 225 |
+
|
| 226 |
+
Provides default models for OpenAI, Anthropic, and Mistral.
|
| 227 |
+
Supports dynamic discovery for local providers.
|
| 228 |
+
"""
|
| 229 |
+
|
| 230 |
+
def __init__(
|
| 231 |
+
self,
|
| 232 |
+
load_defaults: bool = True,
|
| 233 |
+
http_client: Any = None,
|
| 234 |
+
):
|
| 235 |
+
"""
|
| 236 |
+
Initialize the adapter.
|
| 237 |
+
|
| 238 |
+
Args:
|
| 239 |
+
load_defaults: Whether to load default model catalog
|
| 240 |
+
http_client: Optional HTTP client for local discovery
|
| 241 |
+
"""
|
| 242 |
+
self._models: dict[str, ModelInfo] = {}
|
| 243 |
+
self._aliases: dict[str, str] = dict(DEFAULT_ALIASES)
|
| 244 |
+
self._http_client = http_client
|
| 245 |
+
|
| 246 |
+
if load_defaults:
|
| 247 |
+
for model in DEFAULT_MODELS:
|
| 248 |
+
model.added_at = datetime.now()
|
| 249 |
+
self._models[model.model_id] = model
|
| 250 |
+
|
| 251 |
+
async def list_models(
|
| 252 |
+
self,
|
| 253 |
+
provider: ProviderType | None = None,
|
| 254 |
+
capability: ModelCapability | None = None,
|
| 255 |
+
status: ModelStatus | None = None,
|
| 256 |
+
tags: list[str] | None = None,
|
| 257 |
+
) -> list[ModelInfo]:
|
| 258 |
+
"""List models with optional filters."""
|
| 259 |
+
results = list(self._models.values())
|
| 260 |
+
|
| 261 |
+
if provider:
|
| 262 |
+
results = [m for m in results if m.provider == provider]
|
| 263 |
+
if capability:
|
| 264 |
+
results = [m for m in results if capability in m.capabilities]
|
| 265 |
+
if status:
|
| 266 |
+
results = [m for m in results if m.status == status]
|
| 267 |
+
if tags:
|
| 268 |
+
results = [m for m in results if any(t in m.tags for t in tags)]
|
| 269 |
+
|
| 270 |
+
return sorted(results, key=lambda m: m.name)
|
| 271 |
+
|
| 272 |
+
async def get_model(
|
| 273 |
+
self,
|
| 274 |
+
model_id: str,
|
| 275 |
+
) -> ModelInfo | None:
|
| 276 |
+
"""Get a model by ID."""
|
| 277 |
+
# Check direct ID first
|
| 278 |
+
if model_id in self._models:
|
| 279 |
+
return self._models[model_id]
|
| 280 |
+
|
| 281 |
+
# Try alias
|
| 282 |
+
resolved = await self.resolve_model_alias(model_id)
|
| 283 |
+
if resolved and resolved in self._models:
|
| 284 |
+
return self._models[resolved]
|
| 285 |
+
|
| 286 |
+
return None
|
| 287 |
+
|
| 288 |
+
async def get_model_by_provider_id(
|
| 289 |
+
self,
|
| 290 |
+
provider: ProviderType,
|
| 291 |
+
provider_model_id: str,
|
| 292 |
+
) -> ModelInfo | None:
|
| 293 |
+
"""Get a model by provider ID."""
|
| 294 |
+
for model in self._models.values():
|
| 295 |
+
if (
|
| 296 |
+
model.provider == provider
|
| 297 |
+
and model.provider_model_id == provider_model_id
|
| 298 |
+
):
|
| 299 |
+
return model
|
| 300 |
+
return None
|
| 301 |
+
|
| 302 |
+
async def validate_model(
|
| 303 |
+
self,
|
| 304 |
+
model_id: str,
|
| 305 |
+
capability: ModelCapability | None = None,
|
| 306 |
+
) -> ModelValidation:
|
| 307 |
+
"""Validate a model."""
|
| 308 |
+
model = await self.get_model(model_id)
|
| 309 |
+
|
| 310 |
+
if not model:
|
| 311 |
+
# Try to find similar models
|
| 312 |
+
suggested = None
|
| 313 |
+
for m in self._models.values():
|
| 314 |
+
if model_id.lower() in m.model_id.lower():
|
| 315 |
+
suggested = m.model_id
|
| 316 |
+
break
|
| 317 |
+
|
| 318 |
+
return ModelValidation(
|
| 319 |
+
valid=False,
|
| 320 |
+
model_id=model_id,
|
| 321 |
+
reason=f"Model '{model_id}' not found",
|
| 322 |
+
suggested_model=suggested,
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
if model.status == ModelStatus.UNAVAILABLE:
|
| 326 |
+
return ModelValidation(
|
| 327 |
+
valid=False,
|
| 328 |
+
model_id=model_id,
|
| 329 |
+
provider=model.provider,
|
| 330 |
+
reason="Model is currently unavailable",
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
if model.status == ModelStatus.DEPRECATED:
|
| 334 |
+
suggested = model.metadata.get("replacement")
|
| 335 |
+
return ModelValidation(
|
| 336 |
+
valid=True, # Still usable but deprecated
|
| 337 |
+
model_id=model_id,
|
| 338 |
+
provider=model.provider,
|
| 339 |
+
reason="Model is deprecated",
|
| 340 |
+
suggested_model=suggested,
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
if capability and capability not in model.capabilities:
|
| 344 |
+
return ModelValidation(
|
| 345 |
+
valid=False,
|
| 346 |
+
model_id=model_id,
|
| 347 |
+
provider=model.provider,
|
| 348 |
+
reason=f"Model does not support capability: {capability.value}",
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
return ModelValidation(
|
| 352 |
+
valid=True,
|
| 353 |
+
model_id=model_id,
|
| 354 |
+
provider=model.provider,
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
async def resolve_model_alias(
|
| 358 |
+
self,
|
| 359 |
+
alias: str,
|
| 360 |
+
) -> str | None:
|
| 361 |
+
"""Resolve a model alias."""
|
| 362 |
+
if alias in self._models:
|
| 363 |
+
return alias
|
| 364 |
+
return self._aliases.get(alias)
|
| 365 |
+
|
| 366 |
+
async def register_model(
|
| 367 |
+
self,
|
| 368 |
+
model: ModelInfo,
|
| 369 |
+
) -> ModelInfo:
|
| 370 |
+
"""Register a new model."""
|
| 371 |
+
model.added_at = datetime.now()
|
| 372 |
+
model.updated_at = datetime.now()
|
| 373 |
+
self._models[model.model_id] = model
|
| 374 |
+
return model
|
| 375 |
+
|
| 376 |
+
async def update_model(
|
| 377 |
+
self,
|
| 378 |
+
model_id: str,
|
| 379 |
+
status: ModelStatus | None = None,
|
| 380 |
+
pricing: ModelPricing | None = None,
|
| 381 |
+
limits: ModelLimits | None = None,
|
| 382 |
+
tags: list[str] | None = None,
|
| 383 |
+
) -> ModelInfo:
|
| 384 |
+
"""Update a model."""
|
| 385 |
+
if model_id not in self._models:
|
| 386 |
+
raise ValueError(f"Model {model_id} not found")
|
| 387 |
+
|
| 388 |
+
model = self._models[model_id]
|
| 389 |
+
|
| 390 |
+
if status:
|
| 391 |
+
model.status = status
|
| 392 |
+
if pricing:
|
| 393 |
+
model.pricing = pricing
|
| 394 |
+
if limits:
|
| 395 |
+
model.limits = limits
|
| 396 |
+
if tags:
|
| 397 |
+
model.tags = tags
|
| 398 |
+
|
| 399 |
+
model.updated_at = datetime.now()
|
| 400 |
+
return model
|
| 401 |
+
|
| 402 |
+
async def deprecate_model(
|
| 403 |
+
self,
|
| 404 |
+
model_id: str,
|
| 405 |
+
suggested_replacement: str | None = None,
|
| 406 |
+
) -> ModelInfo:
|
| 407 |
+
"""Deprecate a model."""
|
| 408 |
+
if model_id not in self._models:
|
| 409 |
+
raise ValueError(f"Model {model_id} not found")
|
| 410 |
+
|
| 411 |
+
model = self._models[model_id]
|
| 412 |
+
model.status = ModelStatus.DEPRECATED
|
| 413 |
+
model.deprecated_at = datetime.now()
|
| 414 |
+
model.updated_at = datetime.now()
|
| 415 |
+
|
| 416 |
+
if suggested_replacement:
|
| 417 |
+
model.metadata["replacement"] = suggested_replacement
|
| 418 |
+
|
| 419 |
+
return model
|
| 420 |
+
|
| 421 |
+
async def remove_model(
|
| 422 |
+
self,
|
| 423 |
+
model_id: str,
|
| 424 |
+
) -> bool:
|
| 425 |
+
"""Remove a model."""
|
| 426 |
+
if model_id not in self._models:
|
| 427 |
+
return False
|
| 428 |
+
del self._models[model_id]
|
| 429 |
+
return True
|
| 430 |
+
|
| 431 |
+
async def discover_local_models(
|
| 432 |
+
self,
|
| 433 |
+
provider: ProviderType,
|
| 434 |
+
base_url: str | None = None,
|
| 435 |
+
) -> list[ModelInfo]:
|
| 436 |
+
"""Discover local models."""
|
| 437 |
+
if not self._http_client:
|
| 438 |
+
return []
|
| 439 |
+
|
| 440 |
+
discovered = []
|
| 441 |
+
|
| 442 |
+
try:
|
| 443 |
+
if provider == ProviderType.OLLAMA:
|
| 444 |
+
url = base_url or "http://localhost:11434"
|
| 445 |
+
response = await self._http_client.get(f"{url}/api/tags")
|
| 446 |
+
data = response.json()
|
| 447 |
+
|
| 448 |
+
for model in data.get("models", []):
|
| 449 |
+
model_info = ModelInfo(
|
| 450 |
+
model_id=f"ollama:{model['name']}",
|
| 451 |
+
name=model["name"],
|
| 452 |
+
provider=ProviderType.OLLAMA,
|
| 453 |
+
provider_model_id=model["name"],
|
| 454 |
+
description=f"Ollama local model: {model['name']}",
|
| 455 |
+
capabilities=[
|
| 456 |
+
ModelCapability.CHAT,
|
| 457 |
+
ModelCapability.STREAMING,
|
| 458 |
+
],
|
| 459 |
+
base_url=url,
|
| 460 |
+
tags=["local", "ollama"],
|
| 461 |
+
)
|
| 462 |
+
discovered.append(model_info)
|
| 463 |
+
|
| 464 |
+
elif provider == ProviderType.LMSTUDIO:
|
| 465 |
+
url = base_url or "http://localhost:1234"
|
| 466 |
+
response = await self._http_client.get(f"{url}/v1/models")
|
| 467 |
+
data = response.json()
|
| 468 |
+
|
| 469 |
+
for model in data.get("data", []):
|
| 470 |
+
model_info = ModelInfo(
|
| 471 |
+
model_id=f"lmstudio:{model['id']}",
|
| 472 |
+
name=model.get("id", "Unknown"),
|
| 473 |
+
provider=ProviderType.LMSTUDIO,
|
| 474 |
+
provider_model_id=model["id"],
|
| 475 |
+
description=f"LM Studio local model: {model['id']}",
|
| 476 |
+
capabilities=[
|
| 477 |
+
ModelCapability.CHAT,
|
| 478 |
+
ModelCapability.STREAMING,
|
| 479 |
+
],
|
| 480 |
+
base_url=url,
|
| 481 |
+
tags=["local", "lmstudio"],
|
| 482 |
+
)
|
| 483 |
+
discovered.append(model_info)
|
| 484 |
+
|
| 485 |
+
except Exception:
|
| 486 |
+
pass
|
| 487 |
+
|
| 488 |
+
return discovered
|
| 489 |
+
|
| 490 |
+
async def sync_provider_models(
|
| 491 |
+
self,
|
| 492 |
+
provider: ProviderType,
|
| 493 |
+
) -> int:
|
| 494 |
+
"""Sync models from a provider."""
|
| 495 |
+
discovered = await self.discover_local_models(provider)
|
| 496 |
+
|
| 497 |
+
for model in discovered:
|
| 498 |
+
if model.model_id not in self._models:
|
| 499 |
+
await self.register_model(model)
|
| 500 |
+
|
| 501 |
+
return len(discovered)
|
| 502 |
+
|
| 503 |
+
async def estimate_cost(
|
| 504 |
+
self,
|
| 505 |
+
model_id: str,
|
| 506 |
+
input_tokens: int,
|
| 507 |
+
output_tokens: int,
|
| 508 |
+
) -> float:
|
| 509 |
+
"""Estimate cost for a request."""
|
| 510 |
+
model = await self.get_model(model_id)
|
| 511 |
+
if not model:
|
| 512 |
+
return 0.0
|
| 513 |
+
|
| 514 |
+
input_cost = (input_tokens / 1_000_000) * model.pricing.input_per_million
|
| 515 |
+
output_cost = (output_tokens / 1_000_000) * model.pricing.output_per_million
|
| 516 |
+
|
| 517 |
+
return input_cost + output_cost
|
| 518 |
+
|
| 519 |
+
async def get_pricing(
|
| 520 |
+
self,
|
| 521 |
+
model_id: str,
|
| 522 |
+
) -> ModelPricing | None:
|
| 523 |
+
"""Get pricing for a model."""
|
| 524 |
+
model = await self.get_model(model_id)
|
| 525 |
+
return model.pricing if model else None
|
| 526 |
+
|
| 527 |
+
def add_alias(self, alias: str, model_id: str) -> None:
|
| 528 |
+
"""Add a model alias."""
|
| 529 |
+
self._aliases[alias] = model_id
|
| 530 |
+
|
| 531 |
+
def clear(self) -> None:
|
| 532 |
+
"""Clear all models."""
|
| 533 |
+
self._models.clear()
|
| 534 |
+
self._aliases.clear()
|
backend/adapters/model_registry/postgres_adapter.py
ADDED
|
@@ -0,0 +1,523 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PostgreSQL Model Registry Adapter.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Implémentation persistante du ModelRegistryPort
|
| 4 |
+
utilisant PostgreSQL pour le stockage du catalogue de modèles.
|
| 5 |
+
|
| 6 |
+
Ce module fournit:
|
| 7 |
+
- Stockage persistant des modèles
|
| 8 |
+
- Synchronisation avec providers externes
|
| 9 |
+
- Cache local pour performance
|
| 10 |
+
- Versioning des modèles
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from datetime import datetime
|
| 14 |
+
from typing import Any
|
| 15 |
+
|
| 16 |
+
from sqlalchemy import text
|
| 17 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 18 |
+
|
| 19 |
+
from backend.ports.model_registry import (
|
| 20 |
+
ModelRegistryPort,
|
| 21 |
+
ModelInfo,
|
| 22 |
+
ModelPricing,
|
| 23 |
+
ModelLimits,
|
| 24 |
+
ModelValidation,
|
| 25 |
+
ProviderType,
|
| 26 |
+
ModelStatus,
|
| 27 |
+
ModelCapability,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class PostgresModelRegistryAdapter(ModelRegistryPort):
|
| 32 |
+
"""
|
| 33 |
+
PostgreSQL-backed model registry implementation.
|
| 34 |
+
|
| 35 |
+
Stores model catalog in database with caching layer.
|
| 36 |
+
Supports dynamic model discovery and versioning.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
def __init__(
|
| 40 |
+
self,
|
| 41 |
+
session_factory: Any,
|
| 42 |
+
table_name: str = "model_registry",
|
| 43 |
+
cache_ttl_seconds: int = 300,
|
| 44 |
+
):
|
| 45 |
+
"""
|
| 46 |
+
Initialize PostgreSQL adapter.
|
| 47 |
+
|
| 48 |
+
Args:
|
| 49 |
+
session_factory: SQLAlchemy async session factory
|
| 50 |
+
table_name: Name of the model registry table
|
| 51 |
+
cache_ttl_seconds: Cache TTL in seconds
|
| 52 |
+
"""
|
| 53 |
+
self._session_factory = session_factory
|
| 54 |
+
self._table_name = table_name
|
| 55 |
+
self._cache_ttl = cache_ttl_seconds
|
| 56 |
+
|
| 57 |
+
# Local cache
|
| 58 |
+
self._cache: dict[str, ModelInfo] = {}
|
| 59 |
+
self._cache_time: datetime | None = None
|
| 60 |
+
self._aliases: dict[str, str] = {}
|
| 61 |
+
|
| 62 |
+
async def _get_session(self) -> AsyncSession:
|
| 63 |
+
"""Get a database session."""
|
| 64 |
+
return self._session_factory()
|
| 65 |
+
|
| 66 |
+
async def _ensure_table(self, session: AsyncSession) -> None:
|
| 67 |
+
"""Ensure the model registry table exists."""
|
| 68 |
+
await session.execute(
|
| 69 |
+
text(
|
| 70 |
+
f"""
|
| 71 |
+
CREATE TABLE IF NOT EXISTS {self._table_name} (
|
| 72 |
+
model_id VARCHAR(255) PRIMARY KEY,
|
| 73 |
+
name VARCHAR(255) NOT NULL,
|
| 74 |
+
provider VARCHAR(50) NOT NULL,
|
| 75 |
+
provider_model_id VARCHAR(255) NOT NULL,
|
| 76 |
+
description TEXT,
|
| 77 |
+
capabilities JSONB DEFAULT '[]',
|
| 78 |
+
input_per_million DECIMAL(10, 6) DEFAULT 0,
|
| 79 |
+
output_per_million DECIMAL(10, 6) DEFAULT 0,
|
| 80 |
+
max_context_tokens INTEGER DEFAULT 0,
|
| 81 |
+
max_output_tokens INTEGER DEFAULT 0,
|
| 82 |
+
max_images INTEGER,
|
| 83 |
+
status VARCHAR(50) DEFAULT 'available',
|
| 84 |
+
tags JSONB DEFAULT '[]',
|
| 85 |
+
metadata JSONB DEFAULT '{{}}',
|
| 86 |
+
base_url VARCHAR(500),
|
| 87 |
+
added_at TIMESTAMP DEFAULT NOW(),
|
| 88 |
+
updated_at TIMESTAMP DEFAULT NOW(),
|
| 89 |
+
deprecated_at TIMESTAMP
|
| 90 |
+
)
|
| 91 |
+
"""
|
| 92 |
+
)
|
| 93 |
+
)
|
| 94 |
+
await session.commit()
|
| 95 |
+
|
| 96 |
+
async def _refresh_cache(self) -> None:
|
| 97 |
+
"""Refresh the local cache from database."""
|
| 98 |
+
now = datetime.now()
|
| 99 |
+
if (
|
| 100 |
+
self._cache_time
|
| 101 |
+
and (now - self._cache_time).total_seconds() < self._cache_ttl
|
| 102 |
+
):
|
| 103 |
+
return
|
| 104 |
+
|
| 105 |
+
async with await self._get_session() as session:
|
| 106 |
+
await self._ensure_table(session)
|
| 107 |
+
result = await session.execute(
|
| 108 |
+
text(
|
| 109 |
+
f"""
|
| 110 |
+
SELECT model_id, name, provider, provider_model_id, description,
|
| 111 |
+
capabilities, input_per_million, output_per_million,
|
| 112 |
+
max_context_tokens, max_output_tokens, max_images,
|
| 113 |
+
status, tags, metadata, base_url, added_at, updated_at, deprecated_at
|
| 114 |
+
FROM {self._table_name}
|
| 115 |
+
"""
|
| 116 |
+
)
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
self._cache.clear()
|
| 120 |
+
for row in result.fetchall():
|
| 121 |
+
model = self._row_to_model(row)
|
| 122 |
+
self._cache[model.model_id] = model
|
| 123 |
+
|
| 124 |
+
self._cache_time = now
|
| 125 |
+
|
| 126 |
+
def _row_to_model(self, row: Any) -> ModelInfo:
|
| 127 |
+
"""Convert a database row to ModelInfo."""
|
| 128 |
+
capabilities = [
|
| 129 |
+
ModelCapability(c)
|
| 130 |
+
for c in (row[5] or [])
|
| 131 |
+
if c in [cap.value for cap in ModelCapability]
|
| 132 |
+
]
|
| 133 |
+
|
| 134 |
+
return ModelInfo(
|
| 135 |
+
model_id=row[0],
|
| 136 |
+
name=row[1],
|
| 137 |
+
provider=ProviderType(row[2]),
|
| 138 |
+
provider_model_id=row[3],
|
| 139 |
+
description=row[4] or "",
|
| 140 |
+
capabilities=capabilities,
|
| 141 |
+
pricing=ModelPricing(
|
| 142 |
+
input_per_million=float(row[6] or 0),
|
| 143 |
+
output_per_million=float(row[7] or 0),
|
| 144 |
+
),
|
| 145 |
+
limits=ModelLimits(
|
| 146 |
+
max_context_tokens=row[8] or 0,
|
| 147 |
+
max_output_tokens=row[9] or 0,
|
| 148 |
+
max_images=row[10],
|
| 149 |
+
),
|
| 150 |
+
status=ModelStatus(row[11]) if row[11] else ModelStatus.AVAILABLE,
|
| 151 |
+
tags=row[12] or [],
|
| 152 |
+
metadata=row[13] or {},
|
| 153 |
+
base_url=row[14],
|
| 154 |
+
added_at=row[15],
|
| 155 |
+
updated_at=row[16],
|
| 156 |
+
deprecated_at=row[17],
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
async def list_models(
|
| 160 |
+
self,
|
| 161 |
+
provider: ProviderType | None = None,
|
| 162 |
+
capability: ModelCapability | None = None,
|
| 163 |
+
status: ModelStatus | None = None,
|
| 164 |
+
tags: list[str] | None = None,
|
| 165 |
+
) -> list[ModelInfo]:
|
| 166 |
+
"""List models with optional filters."""
|
| 167 |
+
await self._refresh_cache()
|
| 168 |
+
|
| 169 |
+
results = list(self._cache.values())
|
| 170 |
+
|
| 171 |
+
if provider:
|
| 172 |
+
results = [m for m in results if m.provider == provider]
|
| 173 |
+
if capability:
|
| 174 |
+
results = [m for m in results if capability in m.capabilities]
|
| 175 |
+
if status:
|
| 176 |
+
results = [m for m in results if m.status == status]
|
| 177 |
+
if tags:
|
| 178 |
+
results = [m for m in results if any(t in m.tags for t in tags)]
|
| 179 |
+
|
| 180 |
+
return sorted(results, key=lambda m: m.name)
|
| 181 |
+
|
| 182 |
+
async def get_model(
|
| 183 |
+
self,
|
| 184 |
+
model_id: str,
|
| 185 |
+
) -> ModelInfo | None:
|
| 186 |
+
"""Get a model by ID."""
|
| 187 |
+
await self._refresh_cache()
|
| 188 |
+
|
| 189 |
+
if model_id in self._cache:
|
| 190 |
+
return self._cache[model_id]
|
| 191 |
+
|
| 192 |
+
# Try alias
|
| 193 |
+
resolved = await self.resolve_model_alias(model_id)
|
| 194 |
+
if resolved and resolved in self._cache:
|
| 195 |
+
return self._cache[resolved]
|
| 196 |
+
|
| 197 |
+
return None
|
| 198 |
+
|
| 199 |
+
async def get_model_by_provider_id(
|
| 200 |
+
self,
|
| 201 |
+
provider: ProviderType,
|
| 202 |
+
provider_model_id: str,
|
| 203 |
+
) -> ModelInfo | None:
|
| 204 |
+
"""Get a model by provider ID."""
|
| 205 |
+
await self._refresh_cache()
|
| 206 |
+
|
| 207 |
+
for model in self._cache.values():
|
| 208 |
+
if (
|
| 209 |
+
model.provider == provider
|
| 210 |
+
and model.provider_model_id == provider_model_id
|
| 211 |
+
):
|
| 212 |
+
return model
|
| 213 |
+
return None
|
| 214 |
+
|
| 215 |
+
async def validate_model(
|
| 216 |
+
self,
|
| 217 |
+
model_id: str,
|
| 218 |
+
capability: ModelCapability | None = None,
|
| 219 |
+
) -> ModelValidation:
|
| 220 |
+
"""Validate a model."""
|
| 221 |
+
model = await self.get_model(model_id)
|
| 222 |
+
|
| 223 |
+
if not model:
|
| 224 |
+
suggested = None
|
| 225 |
+
for m in self._cache.values():
|
| 226 |
+
if model_id.lower() in m.model_id.lower():
|
| 227 |
+
suggested = m.model_id
|
| 228 |
+
break
|
| 229 |
+
|
| 230 |
+
return ModelValidation(
|
| 231 |
+
valid=False,
|
| 232 |
+
model_id=model_id,
|
| 233 |
+
reason=f"Model '{model_id}' not found",
|
| 234 |
+
suggested_model=suggested,
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
if model.status == ModelStatus.UNAVAILABLE:
|
| 238 |
+
return ModelValidation(
|
| 239 |
+
valid=False,
|
| 240 |
+
model_id=model_id,
|
| 241 |
+
provider=model.provider,
|
| 242 |
+
reason="Model is currently unavailable",
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
if model.status == ModelStatus.DEPRECATED:
|
| 246 |
+
suggested = model.metadata.get("replacement")
|
| 247 |
+
return ModelValidation(
|
| 248 |
+
valid=True,
|
| 249 |
+
model_id=model_id,
|
| 250 |
+
provider=model.provider,
|
| 251 |
+
reason="Model is deprecated",
|
| 252 |
+
suggested_model=suggested,
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
if capability and capability not in model.capabilities:
|
| 256 |
+
return ModelValidation(
|
| 257 |
+
valid=False,
|
| 258 |
+
model_id=model_id,
|
| 259 |
+
provider=model.provider,
|
| 260 |
+
reason=f"Model does not support capability: {capability.value}",
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
return ModelValidation(
|
| 264 |
+
valid=True,
|
| 265 |
+
model_id=model_id,
|
| 266 |
+
provider=model.provider,
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
async def resolve_model_alias(
|
| 270 |
+
self,
|
| 271 |
+
alias: str,
|
| 272 |
+
) -> str | None:
|
| 273 |
+
"""Resolve a model alias."""
|
| 274 |
+
if alias in self._cache:
|
| 275 |
+
return alias
|
| 276 |
+
return self._aliases.get(alias)
|
| 277 |
+
|
| 278 |
+
async def register_model(
|
| 279 |
+
self,
|
| 280 |
+
model: ModelInfo,
|
| 281 |
+
) -> ModelInfo:
|
| 282 |
+
"""Register a new model."""
|
| 283 |
+
async with await self._get_session() as session:
|
| 284 |
+
await self._ensure_table(session)
|
| 285 |
+
|
| 286 |
+
capabilities = [c.value for c in model.capabilities]
|
| 287 |
+
now = datetime.now()
|
| 288 |
+
|
| 289 |
+
await session.execute(
|
| 290 |
+
text(
|
| 291 |
+
f"""
|
| 292 |
+
INSERT INTO {self._table_name} (
|
| 293 |
+
model_id, name, provider, provider_model_id, description,
|
| 294 |
+
capabilities, input_per_million, output_per_million,
|
| 295 |
+
max_context_tokens, max_output_tokens, max_images,
|
| 296 |
+
status, tags, metadata, base_url, added_at, updated_at
|
| 297 |
+
) VALUES (
|
| 298 |
+
:model_id, :name, :provider, :provider_model_id, :description,
|
| 299 |
+
:capabilities, :input_per_million, :output_per_million,
|
| 300 |
+
:max_context_tokens, :max_output_tokens, :max_images,
|
| 301 |
+
:status, :tags, :metadata, :base_url, :added_at, :updated_at
|
| 302 |
+
)
|
| 303 |
+
ON CONFLICT (model_id) DO UPDATE SET
|
| 304 |
+
name = EXCLUDED.name,
|
| 305 |
+
provider = EXCLUDED.provider,
|
| 306 |
+
provider_model_id = EXCLUDED.provider_model_id,
|
| 307 |
+
description = EXCLUDED.description,
|
| 308 |
+
capabilities = EXCLUDED.capabilities,
|
| 309 |
+
input_per_million = EXCLUDED.input_per_million,
|
| 310 |
+
output_per_million = EXCLUDED.output_per_million,
|
| 311 |
+
max_context_tokens = EXCLUDED.max_context_tokens,
|
| 312 |
+
max_output_tokens = EXCLUDED.max_output_tokens,
|
| 313 |
+
max_images = EXCLUDED.max_images,
|
| 314 |
+
status = EXCLUDED.status,
|
| 315 |
+
tags = EXCLUDED.tags,
|
| 316 |
+
metadata = EXCLUDED.metadata,
|
| 317 |
+
base_url = EXCLUDED.base_url,
|
| 318 |
+
updated_at = EXCLUDED.updated_at
|
| 319 |
+
"""
|
| 320 |
+
),
|
| 321 |
+
{
|
| 322 |
+
"model_id": model.model_id,
|
| 323 |
+
"name": model.name,
|
| 324 |
+
"provider": model.provider.value,
|
| 325 |
+
"provider_model_id": model.provider_model_id,
|
| 326 |
+
"description": model.description,
|
| 327 |
+
"capabilities": capabilities,
|
| 328 |
+
"input_per_million": model.pricing.input_per_million,
|
| 329 |
+
"output_per_million": model.pricing.output_per_million,
|
| 330 |
+
"max_context_tokens": model.limits.max_context_tokens,
|
| 331 |
+
"max_output_tokens": model.limits.max_output_tokens,
|
| 332 |
+
"max_images": model.limits.max_images,
|
| 333 |
+
"status": model.status.value,
|
| 334 |
+
"tags": model.tags,
|
| 335 |
+
"metadata": model.metadata,
|
| 336 |
+
"base_url": model.base_url,
|
| 337 |
+
"added_at": now,
|
| 338 |
+
"updated_at": now,
|
| 339 |
+
},
|
| 340 |
+
)
|
| 341 |
+
await session.commit()
|
| 342 |
+
|
| 343 |
+
# Update cache
|
| 344 |
+
model.added_at = now
|
| 345 |
+
model.updated_at = now
|
| 346 |
+
self._cache[model.model_id] = model
|
| 347 |
+
|
| 348 |
+
return model
|
| 349 |
+
|
| 350 |
+
async def update_model(
|
| 351 |
+
self,
|
| 352 |
+
model_id: str,
|
| 353 |
+
status: ModelStatus | None = None,
|
| 354 |
+
pricing: ModelPricing | None = None,
|
| 355 |
+
limits: ModelLimits | None = None,
|
| 356 |
+
tags: list[str] | None = None,
|
| 357 |
+
) -> ModelInfo:
|
| 358 |
+
"""Update a model."""
|
| 359 |
+
model = await self.get_model(model_id)
|
| 360 |
+
if not model:
|
| 361 |
+
raise ValueError(f"Model {model_id} not found")
|
| 362 |
+
|
| 363 |
+
async with await self._get_session() as session:
|
| 364 |
+
updates = ["updated_at = NOW()"]
|
| 365 |
+
params: dict[str, Any] = {"model_id": model_id}
|
| 366 |
+
|
| 367 |
+
if status:
|
| 368 |
+
updates.append("status = :status")
|
| 369 |
+
params["status"] = status.value
|
| 370 |
+
model.status = status
|
| 371 |
+
|
| 372 |
+
if pricing:
|
| 373 |
+
updates.append("input_per_million = :input_per_million")
|
| 374 |
+
updates.append("output_per_million = :output_per_million")
|
| 375 |
+
params["input_per_million"] = pricing.input_per_million
|
| 376 |
+
params["output_per_million"] = pricing.output_per_million
|
| 377 |
+
model.pricing = pricing
|
| 378 |
+
|
| 379 |
+
if limits:
|
| 380 |
+
updates.append("max_context_tokens = :max_context_tokens")
|
| 381 |
+
updates.append("max_output_tokens = :max_output_tokens")
|
| 382 |
+
updates.append("max_images = :max_images")
|
| 383 |
+
params["max_context_tokens"] = limits.max_context_tokens
|
| 384 |
+
params["max_output_tokens"] = limits.max_output_tokens
|
| 385 |
+
params["max_images"] = limits.max_images
|
| 386 |
+
model.limits = limits
|
| 387 |
+
|
| 388 |
+
if tags:
|
| 389 |
+
updates.append("tags = :tags")
|
| 390 |
+
params["tags"] = tags
|
| 391 |
+
model.tags = tags
|
| 392 |
+
|
| 393 |
+
await session.execute(
|
| 394 |
+
text(
|
| 395 |
+
f"""
|
| 396 |
+
UPDATE {self._table_name}
|
| 397 |
+
SET {", ".join(updates)}
|
| 398 |
+
WHERE model_id = :model_id
|
| 399 |
+
"""
|
| 400 |
+
),
|
| 401 |
+
params,
|
| 402 |
+
)
|
| 403 |
+
await session.commit()
|
| 404 |
+
|
| 405 |
+
model.updated_at = datetime.now()
|
| 406 |
+
self._cache[model_id] = model
|
| 407 |
+
|
| 408 |
+
return model
|
| 409 |
+
|
| 410 |
+
async def deprecate_model(
|
| 411 |
+
self,
|
| 412 |
+
model_id: str,
|
| 413 |
+
suggested_replacement: str | None = None,
|
| 414 |
+
) -> ModelInfo:
|
| 415 |
+
"""Deprecate a model."""
|
| 416 |
+
model = await self.get_model(model_id)
|
| 417 |
+
if not model:
|
| 418 |
+
raise ValueError(f"Model {model_id} not found")
|
| 419 |
+
|
| 420 |
+
now = datetime.now()
|
| 421 |
+
metadata = model.metadata.copy()
|
| 422 |
+
if suggested_replacement:
|
| 423 |
+
metadata["replacement"] = suggested_replacement
|
| 424 |
+
|
| 425 |
+
async with await self._get_session() as session:
|
| 426 |
+
await session.execute(
|
| 427 |
+
text(
|
| 428 |
+
f"""
|
| 429 |
+
UPDATE {self._table_name}
|
| 430 |
+
SET status = 'deprecated',
|
| 431 |
+
deprecated_at = :deprecated_at,
|
| 432 |
+
updated_at = :updated_at,
|
| 433 |
+
metadata = :metadata
|
| 434 |
+
WHERE model_id = :model_id
|
| 435 |
+
"""
|
| 436 |
+
),
|
| 437 |
+
{
|
| 438 |
+
"model_id": model_id,
|
| 439 |
+
"deprecated_at": now,
|
| 440 |
+
"updated_at": now,
|
| 441 |
+
"metadata": metadata,
|
| 442 |
+
},
|
| 443 |
+
)
|
| 444 |
+
await session.commit()
|
| 445 |
+
|
| 446 |
+
model.status = ModelStatus.DEPRECATED
|
| 447 |
+
model.deprecated_at = now
|
| 448 |
+
model.updated_at = now
|
| 449 |
+
model.metadata = metadata
|
| 450 |
+
self._cache[model_id] = model
|
| 451 |
+
|
| 452 |
+
return model
|
| 453 |
+
|
| 454 |
+
async def remove_model(
|
| 455 |
+
self,
|
| 456 |
+
model_id: str,
|
| 457 |
+
) -> bool:
|
| 458 |
+
"""Remove a model."""
|
| 459 |
+
async with await self._get_session() as session:
|
| 460 |
+
result = await session.execute(
|
| 461 |
+
text(
|
| 462 |
+
f"""
|
| 463 |
+
DELETE FROM {self._table_name}
|
| 464 |
+
WHERE model_id = :model_id
|
| 465 |
+
"""
|
| 466 |
+
),
|
| 467 |
+
{"model_id": model_id},
|
| 468 |
+
)
|
| 469 |
+
await session.commit()
|
| 470 |
+
|
| 471 |
+
if result.rowcount > 0:
|
| 472 |
+
self._cache.pop(model_id, None)
|
| 473 |
+
return True
|
| 474 |
+
return False
|
| 475 |
+
|
| 476 |
+
async def discover_local_models(
|
| 477 |
+
self,
|
| 478 |
+
provider: ProviderType,
|
| 479 |
+
base_url: str | None = None,
|
| 480 |
+
) -> list[ModelInfo]:
|
| 481 |
+
"""Discover local models (not supported in PostgreSQL adapter)."""
|
| 482 |
+
# Local discovery is not applicable for database storage
|
| 483 |
+
return []
|
| 484 |
+
|
| 485 |
+
async def sync_provider_models(
|
| 486 |
+
self,
|
| 487 |
+
provider: ProviderType,
|
| 488 |
+
) -> int:
|
| 489 |
+
"""Sync models from a provider (no-op for PostgreSQL)."""
|
| 490 |
+
return 0
|
| 491 |
+
|
| 492 |
+
async def estimate_cost(
|
| 493 |
+
self,
|
| 494 |
+
model_id: str,
|
| 495 |
+
input_tokens: int,
|
| 496 |
+
output_tokens: int,
|
| 497 |
+
) -> float:
|
| 498 |
+
"""Estimate cost for a request."""
|
| 499 |
+
model = await self.get_model(model_id)
|
| 500 |
+
if not model:
|
| 501 |
+
return 0.0
|
| 502 |
+
|
| 503 |
+
input_cost = (input_tokens / 1_000_000) * model.pricing.input_per_million
|
| 504 |
+
output_cost = (output_tokens / 1_000_000) * model.pricing.output_per_million
|
| 505 |
+
|
| 506 |
+
return input_cost + output_cost
|
| 507 |
+
|
| 508 |
+
async def get_pricing(
|
| 509 |
+
self,
|
| 510 |
+
model_id: str,
|
| 511 |
+
) -> ModelPricing | None:
|
| 512 |
+
"""Get pricing for a model."""
|
| 513 |
+
model = await self.get_model(model_id)
|
| 514 |
+
return model.pricing if model else None
|
| 515 |
+
|
| 516 |
+
def add_alias(self, alias: str, model_id: str) -> None:
|
| 517 |
+
"""Add a model alias."""
|
| 518 |
+
self._aliases[alias] = model_id
|
| 519 |
+
|
| 520 |
+
def invalidate_cache(self) -> None:
|
| 521 |
+
"""Invalidate the local cache."""
|
| 522 |
+
self._cache.clear()
|
| 523 |
+
self._cache_time = None
|
backend/adapters/observability/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Observability Adapters.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Implementations du ObservabilityPort.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from backend.adapters.observability.in_memory_adapter import (
|
| 7 |
+
InMemoryObservabilityAdapter,
|
| 8 |
+
)
|
| 9 |
+
from backend.adapters.observability.prometheus_adapter import (
|
| 10 |
+
PrometheusObservabilityAdapter,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
__all__ = [
|
| 14 |
+
"InMemoryObservabilityAdapter",
|
| 15 |
+
"PrometheusObservabilityAdapter",
|
| 16 |
+
]
|
backend/adapters/observability/in_memory_adapter.py
ADDED
|
@@ -0,0 +1,439 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""In-Memory Observability Adapter.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Implementation native du ObservabilityPort
|
| 4 |
+
pour l'observabilite enrichie sans dependance externe.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import uuid
|
| 8 |
+
from datetime import datetime, timedelta
|
| 9 |
+
from dataclasses import dataclass
|
| 10 |
+
|
| 11 |
+
from backend.ports.observability import (
|
| 12 |
+
ObservabilityPort,
|
| 13 |
+
CostFilters,
|
| 14 |
+
CostBreakdown,
|
| 15 |
+
TokenEfficiency,
|
| 16 |
+
Anomaly,
|
| 17 |
+
AnomalyType,
|
| 18 |
+
AnomalySeverity,
|
| 19 |
+
GovernanceKPIs,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@dataclass
|
| 24 |
+
class UsageRecord:
|
| 25 |
+
"""Record of usage for analytics."""
|
| 26 |
+
|
| 27 |
+
timestamp: datetime
|
| 28 |
+
app_id: str
|
| 29 |
+
org_id: str
|
| 30 |
+
model: str
|
| 31 |
+
environment: str
|
| 32 |
+
input_tokens: int
|
| 33 |
+
output_tokens: int
|
| 34 |
+
cost_usd: float
|
| 35 |
+
latency_ms: float
|
| 36 |
+
allowed: bool
|
| 37 |
+
error: bool = False
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class InMemoryObservabilityAdapter(ObservabilityPort):
|
| 41 |
+
"""
|
| 42 |
+
Native implementation of observability.
|
| 43 |
+
|
| 44 |
+
Stores usage data in memory for analytics, cost tracking,
|
| 45 |
+
anomaly detection, and governance KPIs.
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
def __init__(
|
| 49 |
+
self,
|
| 50 |
+
anomaly_threshold_percent: float = 50.0,
|
| 51 |
+
cost_per_1k_input_tokens: float = 0.01,
|
| 52 |
+
cost_per_1k_output_tokens: float = 0.03,
|
| 53 |
+
):
|
| 54 |
+
self._records: list[UsageRecord] = []
|
| 55 |
+
self._anomaly_threshold = anomaly_threshold_percent
|
| 56 |
+
self._cost_per_1k_input = cost_per_1k_input_tokens
|
| 57 |
+
self._cost_per_1k_output = cost_per_1k_output_tokens
|
| 58 |
+
|
| 59 |
+
def record_usage(
|
| 60 |
+
self,
|
| 61 |
+
app_id: str,
|
| 62 |
+
org_id: str,
|
| 63 |
+
model: str,
|
| 64 |
+
environment: str,
|
| 65 |
+
input_tokens: int,
|
| 66 |
+
output_tokens: int,
|
| 67 |
+
latency_ms: float,
|
| 68 |
+
allowed: bool,
|
| 69 |
+
error: bool = False,
|
| 70 |
+
timestamp: datetime | None = None,
|
| 71 |
+
) -> None:
|
| 72 |
+
"""Record a usage event."""
|
| 73 |
+
cost = (input_tokens / 1000) * self._cost_per_1k_input + (
|
| 74 |
+
output_tokens / 1000
|
| 75 |
+
) * self._cost_per_1k_output
|
| 76 |
+
self._records.append(
|
| 77 |
+
UsageRecord(
|
| 78 |
+
timestamp=timestamp or datetime.now(),
|
| 79 |
+
app_id=app_id,
|
| 80 |
+
org_id=org_id,
|
| 81 |
+
model=model,
|
| 82 |
+
environment=environment,
|
| 83 |
+
input_tokens=input_tokens,
|
| 84 |
+
output_tokens=output_tokens,
|
| 85 |
+
cost_usd=cost,
|
| 86 |
+
latency_ms=latency_ms,
|
| 87 |
+
allowed=allowed,
|
| 88 |
+
error=error,
|
| 89 |
+
)
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
async def record_request(
|
| 93 |
+
self,
|
| 94 |
+
app_id: str,
|
| 95 |
+
org_id: str,
|
| 96 |
+
model: str,
|
| 97 |
+
environment: str,
|
| 98 |
+
input_tokens: int,
|
| 99 |
+
output_tokens: int,
|
| 100 |
+
cost_usd: float,
|
| 101 |
+
latency_ms: float,
|
| 102 |
+
outcome: str,
|
| 103 |
+
feature: str | None = None,
|
| 104 |
+
) -> None:
|
| 105 |
+
"""Record request metrics (async wrapper around record_usage)."""
|
| 106 |
+
allowed = outcome == "allowed"
|
| 107 |
+
error = outcome == "error"
|
| 108 |
+
self.record_usage(
|
| 109 |
+
app_id=app_id,
|
| 110 |
+
org_id=org_id,
|
| 111 |
+
model=model,
|
| 112 |
+
environment=environment,
|
| 113 |
+
input_tokens=input_tokens,
|
| 114 |
+
output_tokens=output_tokens,
|
| 115 |
+
latency_ms=latency_ms,
|
| 116 |
+
allowed=allowed,
|
| 117 |
+
error=error,
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
async def get_cost_breakdown(
|
| 121 |
+
self,
|
| 122 |
+
filters: CostFilters,
|
| 123 |
+
) -> CostBreakdown:
|
| 124 |
+
"""Get cost breakdown with filters."""
|
| 125 |
+
filtered = self._apply_filters(filters)
|
| 126 |
+
|
| 127 |
+
by_model: dict[str, float] = {}
|
| 128 |
+
by_app: dict[str, float] = {}
|
| 129 |
+
by_environment: dict[str, float] = {}
|
| 130 |
+
by_day: dict[str, float] = {}
|
| 131 |
+
total = 0.0
|
| 132 |
+
|
| 133 |
+
for record in filtered:
|
| 134 |
+
total += record.cost_usd
|
| 135 |
+
by_model[record.model] = by_model.get(record.model, 0) + record.cost_usd
|
| 136 |
+
by_app[record.app_id] = by_app.get(record.app_id, 0) + record.cost_usd
|
| 137 |
+
by_environment[record.environment] = (
|
| 138 |
+
by_environment.get(record.environment, 0) + record.cost_usd
|
| 139 |
+
)
|
| 140 |
+
day_key = record.timestamp.strftime("%Y-%m-%d")
|
| 141 |
+
by_day[day_key] = by_day.get(day_key, 0) + record.cost_usd
|
| 142 |
+
|
| 143 |
+
return CostBreakdown(
|
| 144 |
+
total_cost_usd=round(total, 4),
|
| 145 |
+
by_model={k: round(v, 4) for k, v in by_model.items()},
|
| 146 |
+
by_app={k: round(v, 4) for k, v in by_app.items()},
|
| 147 |
+
by_environment={k: round(v, 4) for k, v in by_environment.items()},
|
| 148 |
+
by_day={k: round(v, 4) for k, v in by_day.items()},
|
| 149 |
+
period_start=filters.start_date,
|
| 150 |
+
period_end=filters.end_date,
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
async def get_token_efficiency(
|
| 154 |
+
self,
|
| 155 |
+
app_id: str,
|
| 156 |
+
start_date: datetime | None = None,
|
| 157 |
+
end_date: datetime | None = None,
|
| 158 |
+
) -> TokenEfficiency:
|
| 159 |
+
"""Get token efficiency for an app."""
|
| 160 |
+
filtered = [
|
| 161 |
+
r
|
| 162 |
+
for r in self._records
|
| 163 |
+
if r.app_id == app_id
|
| 164 |
+
and (start_date is None or r.timestamp >= start_date)
|
| 165 |
+
and (end_date is None or r.timestamp <= end_date)
|
| 166 |
+
]
|
| 167 |
+
|
| 168 |
+
if not filtered:
|
| 169 |
+
return TokenEfficiency(
|
| 170 |
+
app_id=app_id,
|
| 171 |
+
total_input_tokens=0,
|
| 172 |
+
total_output_tokens=0,
|
| 173 |
+
avg_input_per_request=0.0,
|
| 174 |
+
avg_output_per_request=0.0,
|
| 175 |
+
input_output_ratio=0.0,
|
| 176 |
+
cost_per_1k_tokens=0.0,
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
total_input = sum(r.input_tokens for r in filtered)
|
| 180 |
+
total_output = sum(r.output_tokens for r in filtered)
|
| 181 |
+
total_cost = sum(r.cost_usd for r in filtered)
|
| 182 |
+
count = len(filtered)
|
| 183 |
+
total_tokens = total_input + total_output
|
| 184 |
+
|
| 185 |
+
return TokenEfficiency(
|
| 186 |
+
app_id=app_id,
|
| 187 |
+
total_input_tokens=total_input,
|
| 188 |
+
total_output_tokens=total_output,
|
| 189 |
+
avg_input_per_request=round(total_input / count, 2),
|
| 190 |
+
avg_output_per_request=round(total_output / count, 2),
|
| 191 |
+
input_output_ratio=round(total_input / max(total_output, 1), 2),
|
| 192 |
+
cost_per_1k_tokens=round((total_cost / max(total_tokens, 1)) * 1000, 4),
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
async def detect_anomalies(
|
| 196 |
+
self,
|
| 197 |
+
app_id: str | None = None,
|
| 198 |
+
lookback_hours: int = 24,
|
| 199 |
+
) -> list[Anomaly]:
|
| 200 |
+
"""Detect anomalies in usage patterns."""
|
| 201 |
+
cutoff = datetime.now() - timedelta(hours=lookback_hours)
|
| 202 |
+
recent = [
|
| 203 |
+
r
|
| 204 |
+
for r in self._records
|
| 205 |
+
if r.timestamp >= cutoff and (app_id is None or r.app_id == app_id)
|
| 206 |
+
]
|
| 207 |
+
|
| 208 |
+
if len(recent) < 2:
|
| 209 |
+
return []
|
| 210 |
+
|
| 211 |
+
anomalies: list[Anomaly] = []
|
| 212 |
+
|
| 213 |
+
# Group by hour
|
| 214 |
+
hourly_costs: dict[str, float] = {}
|
| 215 |
+
hourly_tokens: dict[str, int] = {}
|
| 216 |
+
hourly_errors: dict[str, int] = {}
|
| 217 |
+
hourly_latencies: dict[str, list[float]] = {}
|
| 218 |
+
|
| 219 |
+
for record in recent:
|
| 220 |
+
hour_key = record.timestamp.strftime("%Y-%m-%d-%H")
|
| 221 |
+
hourly_costs[hour_key] = hourly_costs.get(hour_key, 0) + record.cost_usd
|
| 222 |
+
hourly_tokens[hour_key] = (
|
| 223 |
+
hourly_tokens.get(hour_key, 0)
|
| 224 |
+
+ record.input_tokens
|
| 225 |
+
+ record.output_tokens
|
| 226 |
+
)
|
| 227 |
+
if record.error:
|
| 228 |
+
hourly_errors[hour_key] = hourly_errors.get(hour_key, 0) + 1
|
| 229 |
+
if hour_key not in hourly_latencies:
|
| 230 |
+
hourly_latencies[hour_key] = []
|
| 231 |
+
hourly_latencies[hour_key].append(record.latency_ms)
|
| 232 |
+
|
| 233 |
+
# Detect cost spikes
|
| 234 |
+
anomalies.extend(
|
| 235 |
+
self._detect_spikes(hourly_costs, AnomalyType.COST_SPIKE, app_id)
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
# Detect token spikes
|
| 239 |
+
anomalies.extend(
|
| 240 |
+
self._detect_spikes(
|
| 241 |
+
{k: float(v) for k, v in hourly_tokens.items()},
|
| 242 |
+
AnomalyType.TOKEN_SPIKE,
|
| 243 |
+
app_id,
|
| 244 |
+
)
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
# Detect error spikes
|
| 248 |
+
if hourly_errors:
|
| 249 |
+
anomalies.extend(
|
| 250 |
+
self._detect_spikes(
|
| 251 |
+
{k: float(v) for k, v in hourly_errors.items()},
|
| 252 |
+
AnomalyType.ERROR_SPIKE,
|
| 253 |
+
app_id,
|
| 254 |
+
)
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
return anomalies
|
| 258 |
+
|
| 259 |
+
async def get_governance_kpis(
|
| 260 |
+
self,
|
| 261 |
+
org_id: str,
|
| 262 |
+
start_date: datetime | None = None,
|
| 263 |
+
end_date: datetime | None = None,
|
| 264 |
+
) -> GovernanceKPIs:
|
| 265 |
+
"""Get governance KPIs for an organization."""
|
| 266 |
+
filtered = [
|
| 267 |
+
r
|
| 268 |
+
for r in self._records
|
| 269 |
+
if r.org_id == org_id
|
| 270 |
+
and (start_date is None or r.timestamp >= start_date)
|
| 271 |
+
and (end_date is None or r.timestamp <= end_date)
|
| 272 |
+
]
|
| 273 |
+
|
| 274 |
+
if not filtered:
|
| 275 |
+
return GovernanceKPIs(
|
| 276 |
+
org_id=org_id,
|
| 277 |
+
total_requests=0,
|
| 278 |
+
allowed_requests=0,
|
| 279 |
+
denied_requests=0,
|
| 280 |
+
approval_rate=0.0,
|
| 281 |
+
total_cost_usd=0.0,
|
| 282 |
+
budget_utilization_percent=0.0,
|
| 283 |
+
avg_latency_ms=0.0,
|
| 284 |
+
error_rate=0.0,
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
total = len(filtered)
|
| 288 |
+
allowed = sum(1 for r in filtered if r.allowed)
|
| 289 |
+
denied = total - allowed
|
| 290 |
+
errors = sum(1 for r in filtered if r.error)
|
| 291 |
+
total_cost = sum(r.cost_usd for r in filtered)
|
| 292 |
+
total_latency = sum(r.latency_ms for r in filtered)
|
| 293 |
+
|
| 294 |
+
# Top models
|
| 295 |
+
model_counts: dict[str, int] = {}
|
| 296 |
+
for r in filtered:
|
| 297 |
+
model_counts[r.model] = model_counts.get(r.model, 0) + 1
|
| 298 |
+
top_models = sorted(model_counts.items(), key=lambda x: x[1], reverse=True)[:5]
|
| 299 |
+
|
| 300 |
+
# Top apps
|
| 301 |
+
app_counts: dict[str, int] = {}
|
| 302 |
+
for r in filtered:
|
| 303 |
+
app_counts[r.app_id] = app_counts.get(r.app_id, 0) + 1
|
| 304 |
+
top_apps = sorted(app_counts.items(), key=lambda x: x[1], reverse=True)[:5]
|
| 305 |
+
|
| 306 |
+
return GovernanceKPIs(
|
| 307 |
+
org_id=org_id,
|
| 308 |
+
total_requests=total,
|
| 309 |
+
allowed_requests=allowed,
|
| 310 |
+
denied_requests=denied,
|
| 311 |
+
approval_rate=round(allowed / total * 100, 2),
|
| 312 |
+
total_cost_usd=round(total_cost, 4),
|
| 313 |
+
budget_utilization_percent=0.0, # Would need budget info
|
| 314 |
+
avg_latency_ms=round(total_latency / total, 2),
|
| 315 |
+
error_rate=round(errors / total * 100, 2),
|
| 316 |
+
top_models=top_models,
|
| 317 |
+
top_apps=top_apps,
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
async def get_usage_trends(
|
| 321 |
+
self,
|
| 322 |
+
app_id: str,
|
| 323 |
+
metric: str,
|
| 324 |
+
granularity: str = "hour",
|
| 325 |
+
lookback_hours: int = 24,
|
| 326 |
+
) -> list[tuple[datetime, float]]:
|
| 327 |
+
"""Get usage trends for an app."""
|
| 328 |
+
cutoff = datetime.now() - timedelta(hours=lookback_hours)
|
| 329 |
+
filtered = [
|
| 330 |
+
r for r in self._records if r.app_id == app_id and r.timestamp >= cutoff
|
| 331 |
+
]
|
| 332 |
+
|
| 333 |
+
if not filtered:
|
| 334 |
+
return []
|
| 335 |
+
|
| 336 |
+
# Format key based on granularity
|
| 337 |
+
if granularity == "minute":
|
| 338 |
+
format_str = "%Y-%m-%d %H:%M"
|
| 339 |
+
elif granularity == "day":
|
| 340 |
+
format_str = "%Y-%m-%d"
|
| 341 |
+
else: # hour
|
| 342 |
+
format_str = "%Y-%m-%d %H:00"
|
| 343 |
+
|
| 344 |
+
buckets: dict[str, float] = {}
|
| 345 |
+
|
| 346 |
+
for record in filtered:
|
| 347 |
+
key = record.timestamp.strftime(format_str)
|
| 348 |
+
|
| 349 |
+
if metric == "requests":
|
| 350 |
+
buckets[key] = buckets.get(key, 0) + 1
|
| 351 |
+
elif metric == "cost":
|
| 352 |
+
buckets[key] = buckets.get(key, 0) + record.cost_usd
|
| 353 |
+
elif metric == "tokens":
|
| 354 |
+
buckets[key] = (
|
| 355 |
+
buckets.get(key, 0) + record.input_tokens + record.output_tokens
|
| 356 |
+
)
|
| 357 |
+
elif metric == "latency":
|
| 358 |
+
if key not in buckets:
|
| 359 |
+
buckets[key] = record.latency_ms
|
| 360 |
+
else:
|
| 361 |
+
# Running average
|
| 362 |
+
buckets[key] = (buckets[key] + record.latency_ms) / 2
|
| 363 |
+
|
| 364 |
+
# Convert to sorted list of tuples
|
| 365 |
+
result: list[tuple[datetime, float]] = []
|
| 366 |
+
for key in sorted(buckets.keys()):
|
| 367 |
+
if granularity == "minute":
|
| 368 |
+
ts = datetime.strptime(key, "%Y-%m-%d %H:%M")
|
| 369 |
+
elif granularity == "day":
|
| 370 |
+
ts = datetime.strptime(key, "%Y-%m-%d")
|
| 371 |
+
else:
|
| 372 |
+
ts = datetime.strptime(key, "%Y-%m-%d %H:00")
|
| 373 |
+
result.append((ts, round(buckets[key], 4)))
|
| 374 |
+
|
| 375 |
+
return result
|
| 376 |
+
|
| 377 |
+
def _apply_filters(self, filters: CostFilters) -> list[UsageRecord]:
|
| 378 |
+
"""Apply filters to records."""
|
| 379 |
+
return [
|
| 380 |
+
r
|
| 381 |
+
for r in self._records
|
| 382 |
+
if (filters.start_date is None or r.timestamp >= filters.start_date)
|
| 383 |
+
and (filters.end_date is None or r.timestamp <= filters.end_date)
|
| 384 |
+
and (filters.app_id is None or r.app_id == filters.app_id)
|
| 385 |
+
and (filters.org_id is None or r.org_id == filters.org_id)
|
| 386 |
+
and (filters.model is None or r.model == filters.model)
|
| 387 |
+
and (filters.environment is None or r.environment == filters.environment)
|
| 388 |
+
]
|
| 389 |
+
|
| 390 |
+
def _detect_spikes(
|
| 391 |
+
self,
|
| 392 |
+
hourly_values: dict[str, float],
|
| 393 |
+
anomaly_type: AnomalyType,
|
| 394 |
+
app_id: str | None,
|
| 395 |
+
) -> list[Anomaly]:
|
| 396 |
+
"""Detect spikes in hourly values."""
|
| 397 |
+
if len(hourly_values) < 2:
|
| 398 |
+
return []
|
| 399 |
+
|
| 400 |
+
values = list(hourly_values.values())
|
| 401 |
+
avg = sum(values) / len(values)
|
| 402 |
+
|
| 403 |
+
if avg == 0:
|
| 404 |
+
return []
|
| 405 |
+
|
| 406 |
+
anomalies: list[Anomaly] = []
|
| 407 |
+
|
| 408 |
+
for hour_key, value in hourly_values.items():
|
| 409 |
+
deviation = ((value - avg) / avg) * 100
|
| 410 |
+
if deviation > self._anomaly_threshold:
|
| 411 |
+
severity = (
|
| 412 |
+
AnomalySeverity.CRITICAL
|
| 413 |
+
if deviation > 200
|
| 414 |
+
else (
|
| 415 |
+
AnomalySeverity.HIGH
|
| 416 |
+
if deviation > 100
|
| 417 |
+
else AnomalySeverity.MEDIUM
|
| 418 |
+
)
|
| 419 |
+
)
|
| 420 |
+
anomalies.append(
|
| 421 |
+
Anomaly(
|
| 422 |
+
anomaly_id=str(uuid.uuid4()),
|
| 423 |
+
anomaly_type=anomaly_type,
|
| 424 |
+
severity=severity,
|
| 425 |
+
app_id=app_id,
|
| 426 |
+
description=f"{anomaly_type.value} detected: {deviation:.1f}% above average",
|
| 427 |
+
detected_at=datetime.now(),
|
| 428 |
+
metric_value=value,
|
| 429 |
+
expected_value=avg,
|
| 430 |
+
deviation_percent=round(deviation, 2),
|
| 431 |
+
metadata={"hour": hour_key},
|
| 432 |
+
)
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
return anomalies
|
| 436 |
+
|
| 437 |
+
def clear(self) -> None:
|
| 438 |
+
"""Clear all records."""
|
| 439 |
+
self._records.clear()
|
backend/adapters/observability/langfuse_adapter.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Langfuse Observability Adapter
|
| 3 |
+
|
| 4 |
+
Sends traces and metrics to Langfuse for LLM observability.
|
| 5 |
+
|
| 6 |
+
Features:
|
| 7 |
+
- Request/response tracing
|
| 8 |
+
- Cost tracking
|
| 9 |
+
- Latency metrics
|
| 10 |
+
- Security findings
|
| 11 |
+
- Token usage
|
| 12 |
+
|
| 13 |
+
Langfuse: https://langfuse.com
|
| 14 |
+
|
| 15 |
+
Usage:
|
| 16 |
+
from backend.adapters.observability.langfuse_adapter import LangfuseAdapter
|
| 17 |
+
|
| 18 |
+
adapter = LangfuseAdapter(
|
| 19 |
+
public_key="pk-...",
|
| 20 |
+
secret_key="sk-...",
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
await adapter.trace_request(
|
| 24 |
+
request_id="req_123",
|
| 25 |
+
request=request_data,
|
| 26 |
+
response=response_data,
|
| 27 |
+
metadata=metadata,
|
| 28 |
+
)
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
import asyncio
|
| 32 |
+
import logging
|
| 33 |
+
from datetime import datetime
|
| 34 |
+
from typing import Optional
|
| 35 |
+
from dataclasses import dataclass
|
| 36 |
+
import httpx
|
| 37 |
+
|
| 38 |
+
logger = logging.getLogger(__name__)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@dataclass
|
| 42 |
+
class LangfuseTrace:
|
| 43 |
+
"""Represents a Langfuse trace."""
|
| 44 |
+
|
| 45 |
+
id: str
|
| 46 |
+
name: str
|
| 47 |
+
input: Optional[dict] = None
|
| 48 |
+
output: Optional[dict] = None
|
| 49 |
+
metadata: Optional[dict] = None
|
| 50 |
+
user_id: Optional[str] = None
|
| 51 |
+
session_id: Optional[str] = None
|
| 52 |
+
tags: Optional[list[str]] = None
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@dataclass
|
| 56 |
+
class LangfuseGeneration:
|
| 57 |
+
"""Represents a Langfuse generation (LLM call)."""
|
| 58 |
+
|
| 59 |
+
trace_id: str
|
| 60 |
+
name: str
|
| 61 |
+
model: str
|
| 62 |
+
input: dict
|
| 63 |
+
output: Optional[str] = None
|
| 64 |
+
usage: Optional[dict] = None
|
| 65 |
+
metadata: Optional[dict] = None
|
| 66 |
+
start_time: Optional[datetime] = None
|
| 67 |
+
end_time: Optional[datetime] = None
|
| 68 |
+
level: str = "DEFAULT" # DEFAULT, DEBUG, WARNING, ERROR
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class LangfuseAdapter:
|
| 72 |
+
"""
|
| 73 |
+
Adapter for sending observability data to Langfuse.
|
| 74 |
+
|
| 75 |
+
Implements async batching for performance.
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
def __init__(
|
| 79 |
+
self,
|
| 80 |
+
public_key: Optional[str] = None,
|
| 81 |
+
secret_key: Optional[str] = None,
|
| 82 |
+
host: str = "https://cloud.langfuse.com",
|
| 83 |
+
enabled: bool = True,
|
| 84 |
+
batch_size: int = 10,
|
| 85 |
+
flush_interval: float = 5.0,
|
| 86 |
+
):
|
| 87 |
+
"""
|
| 88 |
+
Initialize Langfuse adapter.
|
| 89 |
+
|
| 90 |
+
Args:
|
| 91 |
+
public_key: Langfuse public key (or LANGFUSE_PUBLIC_KEY env var)
|
| 92 |
+
secret_key: Langfuse secret key (or LANGFUSE_SECRET_KEY env var)
|
| 93 |
+
host: Langfuse API host
|
| 94 |
+
enabled: Whether to send traces
|
| 95 |
+
batch_size: Number of events to batch before sending
|
| 96 |
+
flush_interval: Seconds between automatic flushes
|
| 97 |
+
"""
|
| 98 |
+
import os
|
| 99 |
+
|
| 100 |
+
self.public_key = public_key or os.getenv("LANGFUSE_PUBLIC_KEY")
|
| 101 |
+
self.secret_key = secret_key or os.getenv("LANGFUSE_SECRET_KEY")
|
| 102 |
+
self.host = host
|
| 103 |
+
self.enabled = enabled and bool(self.public_key and self.secret_key)
|
| 104 |
+
self.batch_size = batch_size
|
| 105 |
+
self.flush_interval = flush_interval
|
| 106 |
+
|
| 107 |
+
self._batch: list[dict] = []
|
| 108 |
+
self._lock = asyncio.Lock()
|
| 109 |
+
self._flush_task: Optional[asyncio.Task] = None
|
| 110 |
+
|
| 111 |
+
if self.enabled:
|
| 112 |
+
logger.info("Langfuse adapter initialized")
|
| 113 |
+
else:
|
| 114 |
+
logger.warning(
|
| 115 |
+
"Langfuse adapter disabled. "
|
| 116 |
+
"Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable."
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
async def start(self) -> None:
|
| 120 |
+
"""Start the background flush task."""
|
| 121 |
+
if self.enabled and self._flush_task is None:
|
| 122 |
+
self._flush_task = asyncio.create_task(self._flush_loop())
|
| 123 |
+
|
| 124 |
+
async def stop(self) -> None:
|
| 125 |
+
"""Stop the background flush task and flush remaining events."""
|
| 126 |
+
if self._flush_task:
|
| 127 |
+
self._flush_task.cancel()
|
| 128 |
+
try:
|
| 129 |
+
await self._flush_task
|
| 130 |
+
except asyncio.CancelledError:
|
| 131 |
+
pass
|
| 132 |
+
await self.flush()
|
| 133 |
+
|
| 134 |
+
async def _flush_loop(self) -> None:
|
| 135 |
+
"""Background loop to flush events periodically."""
|
| 136 |
+
while True:
|
| 137 |
+
await asyncio.sleep(self.flush_interval)
|
| 138 |
+
await self.flush()
|
| 139 |
+
|
| 140 |
+
async def flush(self) -> None:
|
| 141 |
+
"""Flush all pending events to Langfuse."""
|
| 142 |
+
if not self.enabled or not self._batch:
|
| 143 |
+
return
|
| 144 |
+
|
| 145 |
+
async with self._lock:
|
| 146 |
+
events = self._batch.copy()
|
| 147 |
+
self._batch.clear()
|
| 148 |
+
|
| 149 |
+
if not events:
|
| 150 |
+
return
|
| 151 |
+
|
| 152 |
+
try:
|
| 153 |
+
async with httpx.AsyncClient(timeout=10.0) as client:
|
| 154 |
+
response = await client.post(
|
| 155 |
+
f"{self.host}/api/public/ingestion",
|
| 156 |
+
auth=(self.public_key, self.secret_key),
|
| 157 |
+
json={"batch": events},
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
if response.status_code == 207:
|
| 161 |
+
# Partial success
|
| 162 |
+
data = response.json()
|
| 163 |
+
errors = data.get("errors", [])
|
| 164 |
+
if errors:
|
| 165 |
+
logger.warning(f"Langfuse partial errors: {errors}")
|
| 166 |
+
elif response.status_code != 200:
|
| 167 |
+
logger.error(f"Langfuse flush failed: {response.status_code}")
|
| 168 |
+
|
| 169 |
+
except Exception as e:
|
| 170 |
+
logger.error(f"Langfuse flush error: {e}")
|
| 171 |
+
# Put events back in batch for retry
|
| 172 |
+
async with self._lock:
|
| 173 |
+
self._batch = events + self._batch
|
| 174 |
+
|
| 175 |
+
async def _add_event(self, event: dict) -> None:
|
| 176 |
+
"""Add an event to the batch."""
|
| 177 |
+
if not self.enabled:
|
| 178 |
+
return
|
| 179 |
+
|
| 180 |
+
async with self._lock:
|
| 181 |
+
self._batch.append(event)
|
| 182 |
+
|
| 183 |
+
if len(self._batch) >= self.batch_size:
|
| 184 |
+
# Trigger immediate flush
|
| 185 |
+
asyncio.create_task(self.flush())
|
| 186 |
+
|
| 187 |
+
async def trace_request(
|
| 188 |
+
self,
|
| 189 |
+
request_id: str,
|
| 190 |
+
app_id: str,
|
| 191 |
+
model: str,
|
| 192 |
+
messages: list[dict],
|
| 193 |
+
response_content: Optional[str] = None,
|
| 194 |
+
input_tokens: int = 0,
|
| 195 |
+
output_tokens: int = 0,
|
| 196 |
+
cost_usd: float = 0.0,
|
| 197 |
+
latency_ms: int = 0,
|
| 198 |
+
decision: str = "ALLOW",
|
| 199 |
+
security_findings: Optional[list[dict]] = None,
|
| 200 |
+
error: Optional[str] = None,
|
| 201 |
+
metadata: Optional[dict] = None,
|
| 202 |
+
) -> None:
|
| 203 |
+
"""
|
| 204 |
+
Trace an LLM request to Langfuse.
|
| 205 |
+
|
| 206 |
+
Args:
|
| 207 |
+
request_id: Unique request identifier
|
| 208 |
+
app_id: Application ID
|
| 209 |
+
model: LLM model used
|
| 210 |
+
messages: Input messages
|
| 211 |
+
response_content: LLM response content
|
| 212 |
+
input_tokens: Number of input tokens
|
| 213 |
+
output_tokens: Number of output tokens
|
| 214 |
+
cost_usd: Cost in USD
|
| 215 |
+
latency_ms: Latency in milliseconds
|
| 216 |
+
decision: TensorWall decision (ALLOW, WARN, BLOCK)
|
| 217 |
+
security_findings: Security findings if any
|
| 218 |
+
error: Error message if failed
|
| 219 |
+
metadata: Additional metadata
|
| 220 |
+
"""
|
| 221 |
+
# Create trace
|
| 222 |
+
trace_event = {
|
| 223 |
+
"type": "trace-create",
|
| 224 |
+
"body": {
|
| 225 |
+
"id": request_id,
|
| 226 |
+
"name": f"tensorwall-{model}",
|
| 227 |
+
"userId": app_id,
|
| 228 |
+
"metadata": {
|
| 229 |
+
"tensorwall_decision": decision,
|
| 230 |
+
"tensorwall_security_findings": security_findings or [],
|
| 231 |
+
"app_id": app_id,
|
| 232 |
+
**(metadata or {}),
|
| 233 |
+
},
|
| 234 |
+
"tags": [
|
| 235 |
+
f"model:{model}",
|
| 236 |
+
f"decision:{decision}",
|
| 237 |
+
"tensorwall",
|
| 238 |
+
],
|
| 239 |
+
},
|
| 240 |
+
}
|
| 241 |
+
await self._add_event(trace_event)
|
| 242 |
+
|
| 243 |
+
# Create generation (LLM call)
|
| 244 |
+
generation_event = {
|
| 245 |
+
"type": "generation-create",
|
| 246 |
+
"body": {
|
| 247 |
+
"traceId": request_id,
|
| 248 |
+
"name": model,
|
| 249 |
+
"model": model,
|
| 250 |
+
"input": messages,
|
| 251 |
+
"output": response_content,
|
| 252 |
+
"usage": {
|
| 253 |
+
"input": input_tokens,
|
| 254 |
+
"output": output_tokens,
|
| 255 |
+
"total": input_tokens + output_tokens,
|
| 256 |
+
"inputCost": cost_usd
|
| 257 |
+
* (input_tokens / (input_tokens + output_tokens + 0.001)),
|
| 258 |
+
"outputCost": cost_usd
|
| 259 |
+
* (output_tokens / (input_tokens + output_tokens + 0.001)),
|
| 260 |
+
"totalCost": cost_usd,
|
| 261 |
+
},
|
| 262 |
+
"metadata": {
|
| 263 |
+
"latency_ms": latency_ms,
|
| 264 |
+
"decision": decision,
|
| 265 |
+
},
|
| 266 |
+
"level": "ERROR" if error else "DEFAULT",
|
| 267 |
+
"statusMessage": error,
|
| 268 |
+
},
|
| 269 |
+
}
|
| 270 |
+
await self._add_event(generation_event)
|
| 271 |
+
|
| 272 |
+
# Add security span if findings
|
| 273 |
+
if security_findings:
|
| 274 |
+
security_event = {
|
| 275 |
+
"type": "span-create",
|
| 276 |
+
"body": {
|
| 277 |
+
"traceId": request_id,
|
| 278 |
+
"name": "security-check",
|
| 279 |
+
"metadata": {
|
| 280 |
+
"findings_count": len(security_findings),
|
| 281 |
+
"findings": security_findings,
|
| 282 |
+
},
|
| 283 |
+
"level": "WARNING" if security_findings else "DEFAULT",
|
| 284 |
+
},
|
| 285 |
+
}
|
| 286 |
+
await self._add_event(security_event)
|
| 287 |
+
|
| 288 |
+
async def trace_error(
|
| 289 |
+
self,
|
| 290 |
+
request_id: str,
|
| 291 |
+
app_id: str,
|
| 292 |
+
error: str,
|
| 293 |
+
error_code: Optional[str] = None,
|
| 294 |
+
metadata: Optional[dict] = None,
|
| 295 |
+
) -> None:
|
| 296 |
+
"""Trace an error to Langfuse."""
|
| 297 |
+
event = {
|
| 298 |
+
"type": "trace-create",
|
| 299 |
+
"body": {
|
| 300 |
+
"id": request_id,
|
| 301 |
+
"name": "tensorwall-error",
|
| 302 |
+
"userId": app_id,
|
| 303 |
+
"metadata": {
|
| 304 |
+
"error": error,
|
| 305 |
+
"error_code": error_code,
|
| 306 |
+
**(metadata or {}),
|
| 307 |
+
},
|
| 308 |
+
"tags": ["error", "tensorwall"],
|
| 309 |
+
},
|
| 310 |
+
}
|
| 311 |
+
await self._add_event(event)
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
# Default singleton
|
| 315 |
+
langfuse_adapter: Optional[LangfuseAdapter] = None
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def get_langfuse_adapter() -> Optional[LangfuseAdapter]:
|
| 319 |
+
"""Get or create the Langfuse adapter."""
|
| 320 |
+
global langfuse_adapter
|
| 321 |
+
if langfuse_adapter is None:
|
| 322 |
+
langfuse_adapter = LangfuseAdapter()
|
| 323 |
+
return langfuse_adapter if langfuse_adapter.enabled else None
|
backend/adapters/observability/prometheus_adapter.py
ADDED
|
@@ -0,0 +1,475 @@
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Prometheus/Grafana Observability Adapter.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Implémentation production du ObservabilityPort
|
| 4 |
+
utilisant Prometheus pour les métriques et InfluxDB/Grafana pour l'analytics.
|
| 5 |
+
|
| 6 |
+
Ce module fournit:
|
| 7 |
+
- Export métriques vers Prometheus
|
| 8 |
+
- Queries PromQL pour analytics
|
| 9 |
+
- Détection d'anomalies basée sur stddev
|
| 10 |
+
- Agrégation de KPIs
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import uuid
|
| 14 |
+
from datetime import datetime, timedelta
|
| 15 |
+
from typing import Any
|
| 16 |
+
|
| 17 |
+
from backend.ports.observability import (
|
| 18 |
+
ObservabilityPort,
|
| 19 |
+
CostFilters,
|
| 20 |
+
CostBreakdown,
|
| 21 |
+
TokenEfficiency,
|
| 22 |
+
Anomaly,
|
| 23 |
+
AnomalyType,
|
| 24 |
+
AnomalySeverity,
|
| 25 |
+
GovernanceKPIs,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class PrometheusObservabilityAdapter(ObservabilityPort):
|
| 30 |
+
"""
|
| 31 |
+
Prometheus-based observability implementation.
|
| 32 |
+
|
| 33 |
+
Uses prometheus_client for metrics export and PromQL queries
|
| 34 |
+
for analytics. Falls back to in-memory storage for testing.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def __init__(
|
| 38 |
+
self,
|
| 39 |
+
prometheus_url: str | None = None,
|
| 40 |
+
push_gateway_url: str | None = None,
|
| 41 |
+
metrics_prefix: str = "llm_gateway",
|
| 42 |
+
http_client: Any = None,
|
| 43 |
+
):
|
| 44 |
+
"""
|
| 45 |
+
Initialize Prometheus adapter.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
prometheus_url: Prometheus server URL for queries
|
| 49 |
+
push_gateway_url: Push Gateway URL for pushing metrics
|
| 50 |
+
metrics_prefix: Prefix for all metric names
|
| 51 |
+
http_client: Optional HTTP client for API calls
|
| 52 |
+
"""
|
| 53 |
+
self._prometheus_url = prometheus_url or "http://localhost:9090"
|
| 54 |
+
self._push_gateway_url = push_gateway_url
|
| 55 |
+
self._prefix = metrics_prefix
|
| 56 |
+
self._http_client = http_client
|
| 57 |
+
|
| 58 |
+
# In-memory storage for testing/fallback
|
| 59 |
+
self._requests: list[dict] = []
|
| 60 |
+
self._anomalies: list[Anomaly] = []
|
| 61 |
+
|
| 62 |
+
# Prometheus metrics (if prometheus_client available)
|
| 63 |
+
self._metrics_initialized = False
|
| 64 |
+
self._init_prometheus_metrics()
|
| 65 |
+
|
| 66 |
+
def _init_prometheus_metrics(self) -> None:
|
| 67 |
+
"""Initialize Prometheus metrics if library available."""
|
| 68 |
+
try:
|
| 69 |
+
from prometheus_client import Counter, Histogram, Gauge
|
| 70 |
+
|
| 71 |
+
self._request_counter = Counter(
|
| 72 |
+
f"{self._prefix}_requests_total",
|
| 73 |
+
"Total LLM requests",
|
| 74 |
+
["app_id", "model", "environment", "outcome"],
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
self._token_counter = Counter(
|
| 78 |
+
f"{self._prefix}_tokens_total",
|
| 79 |
+
"Total tokens processed",
|
| 80 |
+
["app_id", "model", "direction"], # direction: input/output
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
self._cost_counter = Counter(
|
| 84 |
+
f"{self._prefix}_cost_usd_total",
|
| 85 |
+
"Total cost in USD",
|
| 86 |
+
["app_id", "model", "environment"],
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
self._latency_histogram = Histogram(
|
| 90 |
+
f"{self._prefix}_request_latency_ms",
|
| 91 |
+
"Request latency in milliseconds",
|
| 92 |
+
["app_id", "model"],
|
| 93 |
+
buckets=[50, 100, 250, 500, 1000, 2500, 5000, 10000],
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
self._active_requests = Gauge(
|
| 97 |
+
f"{self._prefix}_active_requests",
|
| 98 |
+
"Currently active requests",
|
| 99 |
+
["app_id"],
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
self._metrics_initialized = True
|
| 103 |
+
|
| 104 |
+
except ImportError:
|
| 105 |
+
# prometheus_client not available, use in-memory only
|
| 106 |
+
pass
|
| 107 |
+
|
| 108 |
+
async def record_request(
|
| 109 |
+
self,
|
| 110 |
+
app_id: str,
|
| 111 |
+
org_id: str,
|
| 112 |
+
model: str,
|
| 113 |
+
environment: str,
|
| 114 |
+
input_tokens: int,
|
| 115 |
+
output_tokens: int,
|
| 116 |
+
cost_usd: float,
|
| 117 |
+
latency_ms: float,
|
| 118 |
+
outcome: str,
|
| 119 |
+
feature: str | None = None,
|
| 120 |
+
) -> None:
|
| 121 |
+
"""Record request metrics to Prometheus and in-memory store."""
|
| 122 |
+
now = datetime.now()
|
| 123 |
+
|
| 124 |
+
# Store in memory for queries
|
| 125 |
+
self._requests.append(
|
| 126 |
+
{
|
| 127 |
+
"timestamp": now,
|
| 128 |
+
"app_id": app_id,
|
| 129 |
+
"org_id": org_id,
|
| 130 |
+
"model": model,
|
| 131 |
+
"environment": environment,
|
| 132 |
+
"input_tokens": input_tokens,
|
| 133 |
+
"output_tokens": output_tokens,
|
| 134 |
+
"cost_usd": cost_usd,
|
| 135 |
+
"latency_ms": latency_ms,
|
| 136 |
+
"outcome": outcome,
|
| 137 |
+
"feature": feature,
|
| 138 |
+
}
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
# Update Prometheus metrics if available
|
| 142 |
+
if self._metrics_initialized:
|
| 143 |
+
self._request_counter.labels(
|
| 144 |
+
app_id=app_id,
|
| 145 |
+
model=model,
|
| 146 |
+
environment=environment,
|
| 147 |
+
outcome=outcome,
|
| 148 |
+
).inc()
|
| 149 |
+
|
| 150 |
+
self._token_counter.labels(
|
| 151 |
+
app_id=app_id,
|
| 152 |
+
model=model,
|
| 153 |
+
direction="input",
|
| 154 |
+
).inc(input_tokens)
|
| 155 |
+
|
| 156 |
+
self._token_counter.labels(
|
| 157 |
+
app_id=app_id,
|
| 158 |
+
model=model,
|
| 159 |
+
direction="output",
|
| 160 |
+
).inc(output_tokens)
|
| 161 |
+
|
| 162 |
+
self._cost_counter.labels(
|
| 163 |
+
app_id=app_id,
|
| 164 |
+
model=model,
|
| 165 |
+
environment=environment,
|
| 166 |
+
).inc(cost_usd)
|
| 167 |
+
|
| 168 |
+
self._latency_histogram.labels(
|
| 169 |
+
app_id=app_id,
|
| 170 |
+
model=model,
|
| 171 |
+
).observe(latency_ms)
|
| 172 |
+
|
| 173 |
+
# Check for anomalies
|
| 174 |
+
await self._check_for_anomalies(app_id, cost_usd, latency_ms)
|
| 175 |
+
|
| 176 |
+
async def get_cost_breakdown(
|
| 177 |
+
self,
|
| 178 |
+
filters: CostFilters,
|
| 179 |
+
) -> CostBreakdown:
|
| 180 |
+
"""Get cost breakdown from stored requests."""
|
| 181 |
+
filtered = self._filter_requests(filters)
|
| 182 |
+
|
| 183 |
+
total_cost = sum(r["cost_usd"] for r in filtered)
|
| 184 |
+
by_model: dict[str, float] = {}
|
| 185 |
+
by_app: dict[str, float] = {}
|
| 186 |
+
by_environment: dict[str, float] = {}
|
| 187 |
+
by_day: dict[str, float] = {}
|
| 188 |
+
|
| 189 |
+
for req in filtered:
|
| 190 |
+
model = req["model"]
|
| 191 |
+
by_model[model] = by_model.get(model, 0) + req["cost_usd"]
|
| 192 |
+
|
| 193 |
+
app = req["app_id"]
|
| 194 |
+
by_app[app] = by_app.get(app, 0) + req["cost_usd"]
|
| 195 |
+
|
| 196 |
+
env = req["environment"]
|
| 197 |
+
by_environment[env] = by_environment.get(env, 0) + req["cost_usd"]
|
| 198 |
+
|
| 199 |
+
day = req["timestamp"].strftime("%Y-%m-%d")
|
| 200 |
+
by_day[day] = by_day.get(day, 0) + req["cost_usd"]
|
| 201 |
+
|
| 202 |
+
return CostBreakdown(
|
| 203 |
+
total_cost_usd=total_cost,
|
| 204 |
+
by_model=by_model,
|
| 205 |
+
by_app=by_app,
|
| 206 |
+
by_environment=by_environment,
|
| 207 |
+
by_day=by_day,
|
| 208 |
+
period_start=filters.start_date,
|
| 209 |
+
period_end=filters.end_date,
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
async def get_token_efficiency(
|
| 213 |
+
self,
|
| 214 |
+
app_id: str,
|
| 215 |
+
start_date: datetime | None = None,
|
| 216 |
+
end_date: datetime | None = None,
|
| 217 |
+
) -> TokenEfficiency:
|
| 218 |
+
"""Calculate token efficiency for an app."""
|
| 219 |
+
filters = CostFilters(
|
| 220 |
+
app_id=app_id,
|
| 221 |
+
start_date=start_date,
|
| 222 |
+
end_date=end_date,
|
| 223 |
+
)
|
| 224 |
+
filtered = self._filter_requests(filters)
|
| 225 |
+
|
| 226 |
+
if not filtered:
|
| 227 |
+
return TokenEfficiency(
|
| 228 |
+
app_id=app_id,
|
| 229 |
+
total_input_tokens=0,
|
| 230 |
+
total_output_tokens=0,
|
| 231 |
+
avg_input_per_request=0,
|
| 232 |
+
avg_output_per_request=0,
|
| 233 |
+
input_output_ratio=0,
|
| 234 |
+
cost_per_1k_tokens=0,
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
total_input = sum(r["input_tokens"] for r in filtered)
|
| 238 |
+
total_output = sum(r["output_tokens"] for r in filtered)
|
| 239 |
+
total_cost = sum(r["cost_usd"] for r in filtered)
|
| 240 |
+
count = len(filtered)
|
| 241 |
+
|
| 242 |
+
total_tokens = total_input + total_output
|
| 243 |
+
|
| 244 |
+
return TokenEfficiency(
|
| 245 |
+
app_id=app_id,
|
| 246 |
+
total_input_tokens=total_input,
|
| 247 |
+
total_output_tokens=total_output,
|
| 248 |
+
avg_input_per_request=total_input / count,
|
| 249 |
+
avg_output_per_request=total_output / count,
|
| 250 |
+
input_output_ratio=total_input / total_output if total_output > 0 else 0,
|
| 251 |
+
cost_per_1k_tokens=(
|
| 252 |
+
(total_cost / total_tokens * 1000) if total_tokens > 0 else 0
|
| 253 |
+
),
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
async def detect_anomalies(
|
| 257 |
+
self,
|
| 258 |
+
app_id: str | None = None,
|
| 259 |
+
lookback_hours: int = 24,
|
| 260 |
+
) -> list[Anomaly]:
|
| 261 |
+
"""Return detected anomalies."""
|
| 262 |
+
cutoff = datetime.now() - timedelta(hours=lookback_hours)
|
| 263 |
+
|
| 264 |
+
anomalies = [
|
| 265 |
+
a
|
| 266 |
+
for a in self._anomalies
|
| 267 |
+
if a.detected_at >= cutoff and (app_id is None or a.app_id == app_id)
|
| 268 |
+
]
|
| 269 |
+
|
| 270 |
+
return sorted(anomalies, key=lambda a: a.detected_at, reverse=True)
|
| 271 |
+
|
| 272 |
+
async def get_governance_kpis(
|
| 273 |
+
self,
|
| 274 |
+
org_id: str,
|
| 275 |
+
start_date: datetime | None = None,
|
| 276 |
+
end_date: datetime | None = None,
|
| 277 |
+
) -> GovernanceKPIs:
|
| 278 |
+
"""Calculate governance KPIs for an org."""
|
| 279 |
+
filters = CostFilters(
|
| 280 |
+
org_id=org_id,
|
| 281 |
+
start_date=start_date,
|
| 282 |
+
end_date=end_date,
|
| 283 |
+
)
|
| 284 |
+
filtered = self._filter_requests(filters)
|
| 285 |
+
|
| 286 |
+
if not filtered:
|
| 287 |
+
return GovernanceKPIs(
|
| 288 |
+
org_id=org_id,
|
| 289 |
+
total_requests=0,
|
| 290 |
+
allowed_requests=0,
|
| 291 |
+
denied_requests=0,
|
| 292 |
+
approval_rate=0,
|
| 293 |
+
total_cost_usd=0,
|
| 294 |
+
budget_utilization_percent=0,
|
| 295 |
+
avg_latency_ms=0,
|
| 296 |
+
error_rate=0,
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
total = len(filtered)
|
| 300 |
+
allowed = sum(1 for r in filtered if r["outcome"] == "allowed")
|
| 301 |
+
denied = sum(1 for r in filtered if r["outcome"].startswith("denied"))
|
| 302 |
+
errors = sum(1 for r in filtered if r["outcome"] == "error")
|
| 303 |
+
|
| 304 |
+
total_cost = sum(r["cost_usd"] for r in filtered)
|
| 305 |
+
total_latency = sum(r["latency_ms"] for r in filtered)
|
| 306 |
+
|
| 307 |
+
# Count by model and app
|
| 308 |
+
model_counts: dict[str, int] = {}
|
| 309 |
+
app_counts: dict[str, int] = {}
|
| 310 |
+
for r in filtered:
|
| 311 |
+
model = r["model"]
|
| 312 |
+
model_counts[model] = model_counts.get(model, 0) + 1
|
| 313 |
+
app = r["app_id"]
|
| 314 |
+
app_counts[app] = app_counts.get(app, 0) + 1
|
| 315 |
+
|
| 316 |
+
top_models = sorted(model_counts.items(), key=lambda x: x[1], reverse=True)[:5]
|
| 317 |
+
top_apps = sorted(app_counts.items(), key=lambda x: x[1], reverse=True)[:5]
|
| 318 |
+
|
| 319 |
+
return GovernanceKPIs(
|
| 320 |
+
org_id=org_id,
|
| 321 |
+
total_requests=total,
|
| 322 |
+
allowed_requests=allowed,
|
| 323 |
+
denied_requests=denied,
|
| 324 |
+
approval_rate=allowed / total if total > 0 else 0,
|
| 325 |
+
total_cost_usd=total_cost,
|
| 326 |
+
budget_utilization_percent=0, # Would need budget info
|
| 327 |
+
avg_latency_ms=total_latency / total if total > 0 else 0,
|
| 328 |
+
error_rate=errors / total if total > 0 else 0,
|
| 329 |
+
top_models=top_models,
|
| 330 |
+
top_apps=top_apps,
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
async def get_usage_trends(
|
| 334 |
+
self,
|
| 335 |
+
app_id: str,
|
| 336 |
+
metric: str,
|
| 337 |
+
granularity: str = "hour",
|
| 338 |
+
lookback_hours: int = 24,
|
| 339 |
+
) -> list[tuple[datetime, float]]:
|
| 340 |
+
"""Get usage trends for a metric."""
|
| 341 |
+
cutoff = datetime.now() - timedelta(hours=lookback_hours)
|
| 342 |
+
filtered = [
|
| 343 |
+
r
|
| 344 |
+
for r in self._requests
|
| 345 |
+
if r["app_id"] == app_id and r["timestamp"] >= cutoff
|
| 346 |
+
]
|
| 347 |
+
|
| 348 |
+
# Group by time bucket
|
| 349 |
+
buckets: dict[str, list[dict]] = {}
|
| 350 |
+
for r in filtered:
|
| 351 |
+
if granularity == "minute":
|
| 352 |
+
key = r["timestamp"].strftime("%Y-%m-%d %H:%M")
|
| 353 |
+
elif granularity == "hour":
|
| 354 |
+
key = r["timestamp"].strftime("%Y-%m-%d %H:00")
|
| 355 |
+
else: # day
|
| 356 |
+
key = r["timestamp"].strftime("%Y-%m-%d")
|
| 357 |
+
|
| 358 |
+
if key not in buckets:
|
| 359 |
+
buckets[key] = []
|
| 360 |
+
buckets[key].append(r)
|
| 361 |
+
|
| 362 |
+
# Calculate metric for each bucket
|
| 363 |
+
results = []
|
| 364 |
+
for key, reqs in sorted(buckets.items()):
|
| 365 |
+
if granularity == "minute":
|
| 366 |
+
ts = datetime.strptime(key, "%Y-%m-%d %H:%M")
|
| 367 |
+
elif granularity == "hour":
|
| 368 |
+
ts = datetime.strptime(key, "%Y-%m-%d %H:00")
|
| 369 |
+
else:
|
| 370 |
+
ts = datetime.strptime(key, "%Y-%m-%d")
|
| 371 |
+
|
| 372 |
+
if metric == "requests":
|
| 373 |
+
value = len(reqs)
|
| 374 |
+
elif metric == "cost":
|
| 375 |
+
value = sum(r["cost_usd"] for r in reqs)
|
| 376 |
+
elif metric == "tokens":
|
| 377 |
+
value = sum(r["input_tokens"] + r["output_tokens"] for r in reqs)
|
| 378 |
+
elif metric == "latency":
|
| 379 |
+
value = sum(r["latency_ms"] for r in reqs) / len(reqs)
|
| 380 |
+
else:
|
| 381 |
+
value = 0
|
| 382 |
+
|
| 383 |
+
results.append((ts, value))
|
| 384 |
+
|
| 385 |
+
return results
|
| 386 |
+
|
| 387 |
+
def _filter_requests(self, filters: CostFilters) -> list[dict]:
|
| 388 |
+
"""Filter requests based on criteria."""
|
| 389 |
+
result = self._requests
|
| 390 |
+
|
| 391 |
+
if filters.start_date:
|
| 392 |
+
result = [r for r in result if r["timestamp"] >= filters.start_date]
|
| 393 |
+
if filters.end_date:
|
| 394 |
+
result = [r for r in result if r["timestamp"] <= filters.end_date]
|
| 395 |
+
if filters.app_id:
|
| 396 |
+
result = [r for r in result if r["app_id"] == filters.app_id]
|
| 397 |
+
if filters.org_id:
|
| 398 |
+
result = [r for r in result if r["org_id"] == filters.org_id]
|
| 399 |
+
if filters.model:
|
| 400 |
+
result = [r for r in result if r["model"] == filters.model]
|
| 401 |
+
if filters.environment:
|
| 402 |
+
result = [r for r in result if r["environment"] == filters.environment]
|
| 403 |
+
|
| 404 |
+
return result
|
| 405 |
+
|
| 406 |
+
async def _check_for_anomalies(
|
| 407 |
+
self,
|
| 408 |
+
app_id: str,
|
| 409 |
+
cost_usd: float,
|
| 410 |
+
latency_ms: float,
|
| 411 |
+
) -> None:
|
| 412 |
+
"""Check if current values are anomalous."""
|
| 413 |
+
# Get recent history for this app
|
| 414 |
+
cutoff = datetime.now() - timedelta(hours=1)
|
| 415 |
+
recent = [
|
| 416 |
+
r
|
| 417 |
+
for r in self._requests
|
| 418 |
+
if r["app_id"] == app_id and r["timestamp"] >= cutoff
|
| 419 |
+
]
|
| 420 |
+
|
| 421 |
+
if len(recent) < 10:
|
| 422 |
+
return # Not enough data
|
| 423 |
+
|
| 424 |
+
# Check cost spike
|
| 425 |
+
avg_cost = sum(r["cost_usd"] for r in recent) / len(recent)
|
| 426 |
+
if avg_cost > 0 and cost_usd > avg_cost * 5:
|
| 427 |
+
self._anomalies.append(
|
| 428 |
+
Anomaly(
|
| 429 |
+
anomaly_id=f"anom_{uuid.uuid4().hex[:8]}",
|
| 430 |
+
anomaly_type=AnomalyType.COST_SPIKE,
|
| 431 |
+
severity=AnomalySeverity.HIGH,
|
| 432 |
+
app_id=app_id,
|
| 433 |
+
description=f"Cost spike: ${cost_usd:.4f} vs avg ${avg_cost:.4f}",
|
| 434 |
+
detected_at=datetime.now(),
|
| 435 |
+
metric_value=cost_usd,
|
| 436 |
+
expected_value=avg_cost,
|
| 437 |
+
deviation_percent=((cost_usd - avg_cost) / avg_cost) * 100,
|
| 438 |
+
)
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
# Check latency spike
|
| 442 |
+
avg_latency = sum(r["latency_ms"] for r in recent) / len(recent)
|
| 443 |
+
if avg_latency > 0 and latency_ms > avg_latency * 3:
|
| 444 |
+
self._anomalies.append(
|
| 445 |
+
Anomaly(
|
| 446 |
+
anomaly_id=f"anom_{uuid.uuid4().hex[:8]}",
|
| 447 |
+
anomaly_type=AnomalyType.LATENCY_SPIKE,
|
| 448 |
+
severity=AnomalySeverity.MEDIUM,
|
| 449 |
+
app_id=app_id,
|
| 450 |
+
description=f"Latency spike: {latency_ms:.0f}ms vs avg {avg_latency:.0f}ms",
|
| 451 |
+
detected_at=datetime.now(),
|
| 452 |
+
metric_value=latency_ms,
|
| 453 |
+
expected_value=avg_latency,
|
| 454 |
+
deviation_percent=((latency_ms - avg_latency) / avg_latency) * 100,
|
| 455 |
+
)
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
async def query_prometheus(self, query: str) -> dict:
|
| 459 |
+
"""Execute a PromQL query against Prometheus."""
|
| 460 |
+
if not self._http_client:
|
| 461 |
+
return {"status": "error", "error": "No HTTP client configured"}
|
| 462 |
+
|
| 463 |
+
try:
|
| 464 |
+
response = await self._http_client.get(
|
| 465 |
+
f"{self._prometheus_url}/api/v1/query",
|
| 466 |
+
params={"query": query},
|
| 467 |
+
)
|
| 468 |
+
return response.json()
|
| 469 |
+
except Exception as e:
|
| 470 |
+
return {"status": "error", "error": str(e)}
|
| 471 |
+
|
| 472 |
+
def clear(self) -> None:
|
| 473 |
+
"""Clear all stored data (for testing)."""
|
| 474 |
+
self._requests.clear()
|
| 475 |
+
self._anomalies.clear()
|
backend/adapters/postgres/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PostgreSQL Adapters - Wrappers autour des repositories legacy.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Ces adapters implémentent les Ports de repository
|
| 4 |
+
en wrappant le code legacy de backend/services/.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from backend.adapters.postgres.policy_repository_adapter import PolicyRepositoryAdapter
|
| 8 |
+
from backend.adapters.postgres.budget_repository_adapter import BudgetRepositoryAdapter
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
__all__ = [
|
| 12 |
+
"PolicyRepositoryAdapter",
|
| 13 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|
| 1 |
+
"""Budget Repository Adapter - Implémentation native SQLAlchemy.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Adapter natif qui implémente directement
|
| 4 |
+
l'interface BudgetRepositoryPort en utilisant SQLAlchemy.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from sqlalchemy import select
|
| 8 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 9 |
+
|
| 10 |
+
from backend.ports.budget_repository import BudgetRepositoryPort
|
| 11 |
+
from backend.domain.models import (
|
| 12 |
+
Budget as DomainBudget,
|
| 13 |
+
BudgetPeriod as DomainBudgetPeriod,
|
| 14 |
+
)
|
| 15 |
+
from backend.db.models import (
|
| 16 |
+
Budget as DBBudget,
|
| 17 |
+
BudgetPeriod as DBBudgetPeriod,
|
| 18 |
+
BudgetScope,
|
| 19 |
+
Application,
|
| 20 |
+
)
|
| 21 |
+
from backend.db.session import get_db_context
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class BudgetRepositoryAdapter(BudgetRepositoryPort):
|
| 25 |
+
"""Adapter natif pour le repository des budgets.
|
| 26 |
+
|
| 27 |
+
Implémente directement l'interface BudgetRepositoryPort en utilisant
|
| 28 |
+
SQLAlchemy pour les opérations de base de données.
|
| 29 |
+
Aucune dépendance au code legacy (services/).
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
def __init__(self, session: AsyncSession | None = None):
|
| 33 |
+
"""Initialise l'adapter.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
session: Session SQLAlchemy optionnelle. Si non fournie,
|
| 37 |
+
une nouvelle session sera créée pour chaque opération.
|
| 38 |
+
"""
|
| 39 |
+
self._session = session
|
| 40 |
+
|
| 41 |
+
def _to_domain(
|
| 42 |
+
self, db_budget: DBBudget, app_id: str | None = None
|
| 43 |
+
) -> DomainBudget:
|
| 44 |
+
"""Convertit un modèle SQLAlchemy vers le domaine.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
db_budget: Modèle SQLAlchemy Budget
|
| 48 |
+
app_id: ID de l'application (optionnel, pour éviter une jointure)
|
| 49 |
+
|
| 50 |
+
Returns:
|
| 51 |
+
Entité domain Budget
|
| 52 |
+
"""
|
| 53 |
+
# Map DB period to domain period
|
| 54 |
+
period_map = {
|
| 55 |
+
DBBudgetPeriod.HOURLY: DomainBudgetPeriod.HOURLY,
|
| 56 |
+
DBBudgetPeriod.DAILY: DomainBudgetPeriod.DAILY,
|
| 57 |
+
DBBudgetPeriod.WEEKLY: DomainBudgetPeriod.WEEKLY,
|
| 58 |
+
DBBudgetPeriod.MONTHLY: DomainBudgetPeriod.MONTHLY,
|
| 59 |
+
}
|
| 60 |
+
period = period_map.get(db_budget.period, DomainBudgetPeriod.MONTHLY)
|
| 61 |
+
|
| 62 |
+
return DomainBudget(
|
| 63 |
+
id=str(db_budget.id),
|
| 64 |
+
app_id=app_id or "",
|
| 65 |
+
limit_usd=db_budget.hard_limit_usd,
|
| 66 |
+
spent_usd=db_budget.current_spend_usd,
|
| 67 |
+
period=period,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
async def get_budgets_for_app(
|
| 71 |
+
self,
|
| 72 |
+
app_id: str,
|
| 73 |
+
org_id: str | None = None,
|
| 74 |
+
) -> list[DomainBudget]:
|
| 75 |
+
"""Récupère les budgets pour une application.
|
| 76 |
+
|
| 77 |
+
Args:
|
| 78 |
+
app_id: Identifiant de l'application
|
| 79 |
+
org_id: Identifiant de l'organisation (optionnel)
|
| 80 |
+
|
| 81 |
+
Returns:
|
| 82 |
+
Liste des budgets applicables
|
| 83 |
+
"""
|
| 84 |
+
async with self._get_session() as session:
|
| 85 |
+
# D'abord trouver l'application
|
| 86 |
+
app_result = await session.execute(
|
| 87 |
+
select(Application).where(Application.app_id == app_id)
|
| 88 |
+
)
|
| 89 |
+
app = app_result.scalar_one_or_none()
|
| 90 |
+
|
| 91 |
+
if not app:
|
| 92 |
+
return []
|
| 93 |
+
|
| 94 |
+
# Construire la requête de base
|
| 95 |
+
query = select(DBBudget).where(
|
| 96 |
+
DBBudget.is_active.is_(True),
|
| 97 |
+
(
|
| 98 |
+
(DBBudget.application_id == app.id)
|
| 99 |
+
| (DBBudget.application_id.is_(None)) # Include global budgets
|
| 100 |
+
),
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
# Filtrer par org_id si fourni
|
| 104 |
+
if org_id:
|
| 105 |
+
query = query.where(
|
| 106 |
+
(DBBudget.org_id == org_id) | (DBBudget.org_id.is_(None))
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
result = await session.execute(query)
|
| 110 |
+
db_budgets = result.scalars().all()
|
| 111 |
+
|
| 112 |
+
return [self._to_domain(b, app_id) for b in db_budgets]
|
| 113 |
+
|
| 114 |
+
async def get_budget_by_id(self, budget_id: str) -> DomainBudget | None:
|
| 115 |
+
"""Récupère un budget par son ID.
|
| 116 |
+
|
| 117 |
+
Args:
|
| 118 |
+
budget_id: Identifiant du budget (string représentant un int)
|
| 119 |
+
|
| 120 |
+
Returns:
|
| 121 |
+
Le budget ou None si non trouvé
|
| 122 |
+
"""
|
| 123 |
+
try:
|
| 124 |
+
bid = int(budget_id)
|
| 125 |
+
except ValueError:
|
| 126 |
+
return None
|
| 127 |
+
|
| 128 |
+
async with self._get_session() as session:
|
| 129 |
+
result = await session.execute(select(DBBudget).where(DBBudget.id == bid))
|
| 130 |
+
db_budget = result.scalar_one_or_none()
|
| 131 |
+
|
| 132 |
+
if not db_budget:
|
| 133 |
+
return None
|
| 134 |
+
|
| 135 |
+
# Récupérer l'app_id si possible
|
| 136 |
+
app_id = ""
|
| 137 |
+
if db_budget.application_id:
|
| 138 |
+
app_result = await session.execute(
|
| 139 |
+
select(Application).where(
|
| 140 |
+
Application.id == db_budget.application_id
|
| 141 |
+
)
|
| 142 |
+
)
|
| 143 |
+
app = app_result.scalar_one_or_none()
|
| 144 |
+
if app:
|
| 145 |
+
app_id = app.app_id
|
| 146 |
+
|
| 147 |
+
return self._to_domain(db_budget, app_id)
|
| 148 |
+
|
| 149 |
+
async def create_budget(self, budget: DomainBudget) -> DomainBudget:
|
| 150 |
+
"""Crée un nouveau budget.
|
| 151 |
+
|
| 152 |
+
Args:
|
| 153 |
+
budget: Le budget à créer
|
| 154 |
+
|
| 155 |
+
Returns:
|
| 156 |
+
Le budget créé avec son ID
|
| 157 |
+
"""
|
| 158 |
+
async with self._get_session() as session:
|
| 159 |
+
# Trouver l'application
|
| 160 |
+
app_result = await session.execute(
|
| 161 |
+
select(Application).where(Application.app_id == budget.app_id)
|
| 162 |
+
)
|
| 163 |
+
app = app_result.scalar_one_or_none()
|
| 164 |
+
|
| 165 |
+
# Map domain period to DB period
|
| 166 |
+
period_map = {
|
| 167 |
+
DomainBudgetPeriod.HOURLY: DBBudgetPeriod.HOURLY,
|
| 168 |
+
DomainBudgetPeriod.DAILY: DBBudgetPeriod.DAILY,
|
| 169 |
+
DomainBudgetPeriod.WEEKLY: DBBudgetPeriod.WEEKLY,
|
| 170 |
+
DomainBudgetPeriod.MONTHLY: DBBudgetPeriod.MONTHLY,
|
| 171 |
+
}
|
| 172 |
+
db_period = period_map.get(budget.period, DBBudgetPeriod.MONTHLY)
|
| 173 |
+
|
| 174 |
+
db_budget = DBBudget(
|
| 175 |
+
scope=BudgetScope.APPLICATION,
|
| 176 |
+
application_id=app.id if app else None,
|
| 177 |
+
soft_limit_usd=budget.limit_usd * 0.8, # 80% pour soft limit
|
| 178 |
+
hard_limit_usd=budget.limit_usd,
|
| 179 |
+
period=db_period,
|
| 180 |
+
current_spend_usd=budget.spent_usd,
|
| 181 |
+
)
|
| 182 |
+
session.add(db_budget)
|
| 183 |
+
await session.flush()
|
| 184 |
+
await session.refresh(db_budget)
|
| 185 |
+
|
| 186 |
+
return self._to_domain(db_budget, budget.app_id)
|
| 187 |
+
|
| 188 |
+
async def update_budget(self, budget: DomainBudget) -> DomainBudget:
|
| 189 |
+
"""Met à jour un budget existant.
|
| 190 |
+
|
| 191 |
+
Args:
|
| 192 |
+
budget: Le budget à mettre à jour
|
| 193 |
+
|
| 194 |
+
Returns:
|
| 195 |
+
Le budget mis à jour
|
| 196 |
+
|
| 197 |
+
Raises:
|
| 198 |
+
ValueError: Si l'ID est invalide ou le budget n'existe pas
|
| 199 |
+
"""
|
| 200 |
+
try:
|
| 201 |
+
bid = int(budget.id)
|
| 202 |
+
except ValueError:
|
| 203 |
+
raise ValueError(f"Invalid budget ID: {budget.id}")
|
| 204 |
+
|
| 205 |
+
async with self._get_session() as session:
|
| 206 |
+
result = await session.execute(select(DBBudget).where(DBBudget.id == bid))
|
| 207 |
+
db_budget = result.scalar_one_or_none()
|
| 208 |
+
|
| 209 |
+
if not db_budget:
|
| 210 |
+
raise ValueError(f"Budget not found: {budget.id}")
|
| 211 |
+
|
| 212 |
+
# Map domain period to DB period
|
| 213 |
+
period_map = {
|
| 214 |
+
DomainBudgetPeriod.HOURLY: DBBudgetPeriod.HOURLY,
|
| 215 |
+
DomainBudgetPeriod.DAILY: DBBudgetPeriod.DAILY,
|
| 216 |
+
DomainBudgetPeriod.WEEKLY: DBBudgetPeriod.WEEKLY,
|
| 217 |
+
DomainBudgetPeriod.MONTHLY: DBBudgetPeriod.MONTHLY,
|
| 218 |
+
}
|
| 219 |
+
db_period = period_map.get(budget.period, DBBudgetPeriod.MONTHLY)
|
| 220 |
+
|
| 221 |
+
# Mettre à jour les champs
|
| 222 |
+
db_budget.hard_limit_usd = budget.limit_usd
|
| 223 |
+
db_budget.soft_limit_usd = budget.limit_usd * 0.8
|
| 224 |
+
db_budget.current_spend_usd = budget.spent_usd
|
| 225 |
+
db_budget.period = db_period
|
| 226 |
+
|
| 227 |
+
await session.flush()
|
| 228 |
+
await session.refresh(db_budget)
|
| 229 |
+
|
| 230 |
+
return self._to_domain(db_budget, budget.app_id)
|
| 231 |
+
|
| 232 |
+
async def record_usage(
|
| 233 |
+
self,
|
| 234 |
+
budget_id: str,
|
| 235 |
+
amount_usd: float,
|
| 236 |
+
) -> DomainBudget:
|
| 237 |
+
"""Enregistre une consommation sur un budget.
|
| 238 |
+
|
| 239 |
+
Args:
|
| 240 |
+
budget_id: Identifiant du budget
|
| 241 |
+
amount_usd: Montant consommé en USD
|
| 242 |
+
|
| 243 |
+
Returns:
|
| 244 |
+
Le budget mis à jour
|
| 245 |
+
|
| 246 |
+
Raises:
|
| 247 |
+
ValueError: Si l'ID est invalide ou le budget n'existe pas
|
| 248 |
+
"""
|
| 249 |
+
try:
|
| 250 |
+
bid = int(budget_id)
|
| 251 |
+
except ValueError:
|
| 252 |
+
raise ValueError(f"Invalid budget ID: {budget_id}")
|
| 253 |
+
|
| 254 |
+
async with self._get_session() as session:
|
| 255 |
+
result = await session.execute(select(DBBudget).where(DBBudget.id == bid))
|
| 256 |
+
db_budget = result.scalar_one_or_none()
|
| 257 |
+
|
| 258 |
+
if not db_budget:
|
| 259 |
+
raise ValueError(f"Budget not found: {budget_id}")
|
| 260 |
+
|
| 261 |
+
# Ajouter la consommation
|
| 262 |
+
db_budget.current_spend_usd += amount_usd
|
| 263 |
+
|
| 264 |
+
await session.flush()
|
| 265 |
+
await session.refresh(db_budget)
|
| 266 |
+
|
| 267 |
+
# Récupérer l'app_id
|
| 268 |
+
app_id = ""
|
| 269 |
+
if db_budget.application_id:
|
| 270 |
+
app_result = await session.execute(
|
| 271 |
+
select(Application).where(
|
| 272 |
+
Application.id == db_budget.application_id
|
| 273 |
+
)
|
| 274 |
+
)
|
| 275 |
+
app = app_result.scalar_one_or_none()
|
| 276 |
+
if app:
|
| 277 |
+
app_id = app.app_id
|
| 278 |
+
|
| 279 |
+
return self._to_domain(db_budget, app_id)
|
| 280 |
+
|
| 281 |
+
async def delete_budget(self, budget_id: str) -> bool:
|
| 282 |
+
"""Supprime un budget.
|
| 283 |
+
|
| 284 |
+
Args:
|
| 285 |
+
budget_id: Identifiant du budget à supprimer
|
| 286 |
+
|
| 287 |
+
Returns:
|
| 288 |
+
True si supprimé, False si non trouvé
|
| 289 |
+
"""
|
| 290 |
+
try:
|
| 291 |
+
bid = int(budget_id)
|
| 292 |
+
except ValueError:
|
| 293 |
+
return False
|
| 294 |
+
|
| 295 |
+
async with self._get_session() as session:
|
| 296 |
+
result = await session.execute(select(DBBudget).where(DBBudget.id == bid))
|
| 297 |
+
db_budget = result.scalar_one_or_none()
|
| 298 |
+
|
| 299 |
+
if not db_budget:
|
| 300 |
+
return False
|
| 301 |
+
|
| 302 |
+
await session.delete(db_budget)
|
| 303 |
+
return True
|
| 304 |
+
|
| 305 |
+
def _get_session(self):
|
| 306 |
+
"""Retourne une session SQLAlchemy (context manager async).
|
| 307 |
+
|
| 308 |
+
Si une session a été fournie au constructeur, l'utilise.
|
| 309 |
+
Sinon, crée une nouvelle session via le context manager.
|
| 310 |
+
"""
|
| 311 |
+
if self._session:
|
| 312 |
+
return _SessionWrapper(self._session)
|
| 313 |
+
else:
|
| 314 |
+
return get_db_context()
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
class _SessionWrapper:
|
| 318 |
+
"""Wrapper pour utiliser une session existante comme context manager."""
|
| 319 |
+
|
| 320 |
+
def __init__(self, session: AsyncSession):
|
| 321 |
+
self._session = session
|
| 322 |
+
|
| 323 |
+
async def __aenter__(self):
|
| 324 |
+
return self._session
|
| 325 |
+
|
| 326 |
+
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
| 327 |
+
pass
|
backend/adapters/postgres/policy_repository_adapter.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Policy Repository Adapter - Implémentation native SQLAlchemy.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Adapter natif qui implémente directement
|
| 4 |
+
l'interface PolicyRepositoryPort en utilisant SQLAlchemy.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from sqlalchemy import select
|
| 8 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 9 |
+
|
| 10 |
+
from backend.ports.policy_repository import PolicyRepositoryPort
|
| 11 |
+
from backend.domain.models import (
|
| 12 |
+
PolicyRule as DomainPolicyRule,
|
| 13 |
+
PolicyAction as DomainPolicyAction,
|
| 14 |
+
)
|
| 15 |
+
from backend.db.models import PolicyRule as DBPolicyRule, PolicyAction as DBPolicyAction
|
| 16 |
+
from backend.db.session import get_db_context
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class PolicyRepositoryAdapter(PolicyRepositoryPort):
|
| 20 |
+
"""Adapter natif pour le repository des policies.
|
| 21 |
+
|
| 22 |
+
Implémente directement l'interface PolicyRepositoryPort en utilisant
|
| 23 |
+
SQLAlchemy pour les opérations de base de données.
|
| 24 |
+
Aucune dépendance au code legacy (services/).
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def __init__(self, session: AsyncSession | None = None):
|
| 28 |
+
"""Initialise l'adapter.
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
session: Session SQLAlchemy optionnelle. Si non fournie,
|
| 32 |
+
une nouvelle session sera créée pour chaque opération.
|
| 33 |
+
"""
|
| 34 |
+
self._session = session
|
| 35 |
+
|
| 36 |
+
def _to_domain(self, db_policy: DBPolicyRule) -> DomainPolicyRule:
|
| 37 |
+
"""Convertit un modèle SQLAlchemy vers le domaine.
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
db_policy: Modèle SQLAlchemy PolicyRule
|
| 41 |
+
|
| 42 |
+
Returns:
|
| 43 |
+
Entité domain PolicyRule
|
| 44 |
+
"""
|
| 45 |
+
return DomainPolicyRule(
|
| 46 |
+
id=str(db_policy.id),
|
| 47 |
+
name=db_policy.name,
|
| 48 |
+
action=DomainPolicyAction(db_policy.action.value),
|
| 49 |
+
priority=db_policy.priority,
|
| 50 |
+
conditions=db_policy.conditions or {},
|
| 51 |
+
enabled=db_policy.is_enabled,
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
def _from_domain(self, rule: DomainPolicyRule) -> dict:
|
| 55 |
+
"""Convertit une entité domain vers les valeurs pour SQLAlchemy.
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
rule: Entité domain PolicyRule
|
| 59 |
+
|
| 60 |
+
Returns:
|
| 61 |
+
Dict des valeurs pour créer/mettre à jour le modèle DB
|
| 62 |
+
"""
|
| 63 |
+
return {
|
| 64 |
+
"name": rule.name,
|
| 65 |
+
"conditions": rule.conditions,
|
| 66 |
+
"action": DBPolicyAction(rule.action.value),
|
| 67 |
+
"priority": rule.priority,
|
| 68 |
+
"is_enabled": rule.enabled,
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
async def get_active_rules(
|
| 72 |
+
self,
|
| 73 |
+
org_id: str | None = None,
|
| 74 |
+
app_id: str | None = None,
|
| 75 |
+
environment: str | None = None,
|
| 76 |
+
) -> list[DomainPolicyRule]:
|
| 77 |
+
"""Récupère les règles actives filtrées.
|
| 78 |
+
|
| 79 |
+
Args:
|
| 80 |
+
org_id: Filtrer par organisation (non implémenté)
|
| 81 |
+
app_id: Filtrer par application
|
| 82 |
+
environment: Filtrer par environnement (via conditions)
|
| 83 |
+
|
| 84 |
+
Returns:
|
| 85 |
+
Liste des règles de policy actives
|
| 86 |
+
"""
|
| 87 |
+
async with self._get_session() as session:
|
| 88 |
+
query = select(DBPolicyRule).where(DBPolicyRule.is_enabled.is_(True))
|
| 89 |
+
|
| 90 |
+
# Filtrer par application si fourni
|
| 91 |
+
if app_id:
|
| 92 |
+
# Joindre avec la table applications pour filtrer par app_id
|
| 93 |
+
from backend.db.models import Application
|
| 94 |
+
|
| 95 |
+
subquery = select(Application.id).where(Application.app_id == app_id)
|
| 96 |
+
query = query.where(
|
| 97 |
+
(DBPolicyRule.application_id.in_(subquery))
|
| 98 |
+
| (DBPolicyRule.application_id.is_(None)) # Include global policies
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
# Trier par priorité décroissante
|
| 102 |
+
query = query.order_by(DBPolicyRule.priority.desc())
|
| 103 |
+
|
| 104 |
+
result = await session.execute(query)
|
| 105 |
+
db_policies = result.scalars().all()
|
| 106 |
+
|
| 107 |
+
# Filtrer par environnement si fourni (dans les conditions)
|
| 108 |
+
domain_rules = []
|
| 109 |
+
for policy in db_policies:
|
| 110 |
+
rule = self._to_domain(policy)
|
| 111 |
+
|
| 112 |
+
# Si environment est spécifié, vérifier si la règle s'applique
|
| 113 |
+
if environment:
|
| 114 |
+
env_conditions = rule.conditions.get("environments", [])
|
| 115 |
+
if env_conditions and environment not in env_conditions:
|
| 116 |
+
continue
|
| 117 |
+
|
| 118 |
+
domain_rules.append(rule)
|
| 119 |
+
|
| 120 |
+
return domain_rules
|
| 121 |
+
|
| 122 |
+
async def get_rule_by_id(self, rule_id: str) -> DomainPolicyRule | None:
|
| 123 |
+
"""Récupère une règle par son ID.
|
| 124 |
+
|
| 125 |
+
Args:
|
| 126 |
+
rule_id: Identifiant de la règle (string représentant un int)
|
| 127 |
+
|
| 128 |
+
Returns:
|
| 129 |
+
La règle ou None si non trouvée
|
| 130 |
+
"""
|
| 131 |
+
try:
|
| 132 |
+
policy_id = int(rule_id)
|
| 133 |
+
except ValueError:
|
| 134 |
+
return None
|
| 135 |
+
|
| 136 |
+
async with self._get_session() as session:
|
| 137 |
+
result = await session.execute(
|
| 138 |
+
select(DBPolicyRule).where(DBPolicyRule.id == policy_id)
|
| 139 |
+
)
|
| 140 |
+
db_policy = result.scalar_one_or_none()
|
| 141 |
+
|
| 142 |
+
if not db_policy:
|
| 143 |
+
return None
|
| 144 |
+
|
| 145 |
+
return self._to_domain(db_policy)
|
| 146 |
+
|
| 147 |
+
async def create_rule(self, rule: DomainPolicyRule) -> DomainPolicyRule:
|
| 148 |
+
"""Crée une nouvelle règle.
|
| 149 |
+
|
| 150 |
+
Args:
|
| 151 |
+
rule: La règle à créer
|
| 152 |
+
|
| 153 |
+
Returns:
|
| 154 |
+
La règle créée avec son ID
|
| 155 |
+
"""
|
| 156 |
+
async with self._get_session() as session:
|
| 157 |
+
values = self._from_domain(rule)
|
| 158 |
+
db_policy = DBPolicyRule(**values)
|
| 159 |
+
session.add(db_policy)
|
| 160 |
+
await session.flush() # Get the ID
|
| 161 |
+
await session.refresh(db_policy)
|
| 162 |
+
|
| 163 |
+
return self._to_domain(db_policy)
|
| 164 |
+
|
| 165 |
+
async def update_rule(self, rule: DomainPolicyRule) -> DomainPolicyRule:
|
| 166 |
+
"""Met à jour une règle existante.
|
| 167 |
+
|
| 168 |
+
Args:
|
| 169 |
+
rule: La règle à mettre à jour
|
| 170 |
+
|
| 171 |
+
Returns:
|
| 172 |
+
La règle mise à jour
|
| 173 |
+
|
| 174 |
+
Raises:
|
| 175 |
+
ValueError: Si l'ID est invalide ou la règle n'existe pas
|
| 176 |
+
"""
|
| 177 |
+
try:
|
| 178 |
+
policy_id = int(rule.id)
|
| 179 |
+
except ValueError:
|
| 180 |
+
raise ValueError(f"Invalid policy ID: {rule.id}")
|
| 181 |
+
|
| 182 |
+
async with self._get_session() as session:
|
| 183 |
+
result = await session.execute(
|
| 184 |
+
select(DBPolicyRule).where(DBPolicyRule.id == policy_id)
|
| 185 |
+
)
|
| 186 |
+
db_policy = result.scalar_one_or_none()
|
| 187 |
+
|
| 188 |
+
if not db_policy:
|
| 189 |
+
raise ValueError(f"Policy not found: {rule.id}")
|
| 190 |
+
|
| 191 |
+
# Mettre à jour les champs
|
| 192 |
+
db_policy.name = rule.name
|
| 193 |
+
db_policy.conditions = rule.conditions
|
| 194 |
+
db_policy.action = DBPolicyAction(rule.action.value)
|
| 195 |
+
db_policy.priority = rule.priority
|
| 196 |
+
db_policy.is_enabled = rule.enabled
|
| 197 |
+
|
| 198 |
+
await session.flush()
|
| 199 |
+
await session.refresh(db_policy)
|
| 200 |
+
|
| 201 |
+
return self._to_domain(db_policy)
|
| 202 |
+
|
| 203 |
+
async def delete_rule(self, rule_id: str) -> bool:
|
| 204 |
+
"""Supprime une règle.
|
| 205 |
+
|
| 206 |
+
Args:
|
| 207 |
+
rule_id: Identifiant de la règle à supprimer
|
| 208 |
+
|
| 209 |
+
Returns:
|
| 210 |
+
True si supprimée, False si non trouvée
|
| 211 |
+
"""
|
| 212 |
+
try:
|
| 213 |
+
policy_id = int(rule_id)
|
| 214 |
+
except ValueError:
|
| 215 |
+
return False
|
| 216 |
+
|
| 217 |
+
async with self._get_session() as session:
|
| 218 |
+
result = await session.execute(
|
| 219 |
+
select(DBPolicyRule).where(DBPolicyRule.id == policy_id)
|
| 220 |
+
)
|
| 221 |
+
db_policy = result.scalar_one_or_none()
|
| 222 |
+
|
| 223 |
+
if not db_policy:
|
| 224 |
+
return False
|
| 225 |
+
|
| 226 |
+
await session.delete(db_policy)
|
| 227 |
+
return True
|
| 228 |
+
|
| 229 |
+
def _get_session(self):
|
| 230 |
+
"""Retourne une session SQLAlchemy (context manager async).
|
| 231 |
+
|
| 232 |
+
Si une session a été fournie au constructeur, l'utilise.
|
| 233 |
+
Sinon, crée une nouvelle session via le context manager.
|
| 234 |
+
"""
|
| 235 |
+
if self._session:
|
| 236 |
+
# Utiliser la session fournie (ne pas la fermer)
|
| 237 |
+
return _SessionWrapper(self._session)
|
| 238 |
+
else:
|
| 239 |
+
# Créer une nouvelle session
|
| 240 |
+
return get_db_context()
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class _SessionWrapper:
|
| 244 |
+
"""Wrapper pour utiliser une session existante comme context manager."""
|
| 245 |
+
|
| 246 |
+
def __init__(self, session: AsyncSession):
|
| 247 |
+
self._session = session
|
| 248 |
+
|
| 249 |
+
async def __aenter__(self):
|
| 250 |
+
return self._session
|
| 251 |
+
|
| 252 |
+
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
| 253 |
+
# Ne pas fermer la session fournie
|
| 254 |
+
pass
|
backend/adapters/prometheus/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Prometheus Adapters - Implémentations natives.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Ces adapters implémentent le Port MetricsPort
|
| 4 |
+
pour exporter les métriques au format Prometheus.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from backend.adapters.prometheus.metrics_adapter import (
|
| 8 |
+
PrometheusMetricsAdapter,
|
| 9 |
+
InMemoryMetricsAdapter,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
__all__ = [
|
| 14 |
+
"PrometheusMetricsAdapter",
|
| 15 |
+
"InMemoryMetricsAdapter",
|
| 16 |
+
]
|
backend/adapters/prometheus/metrics_adapter.py
ADDED
|
@@ -0,0 +1,460 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Prometheus Metrics Adapter - Implémentation native.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Adapter natif qui implémente directement
|
| 4 |
+
l'interface MetricsPort pour exporter les métriques au format Prometheus.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from collections import defaultdict
|
| 8 |
+
|
| 9 |
+
from backend.ports.metrics import (
|
| 10 |
+
MetricsPort,
|
| 11 |
+
RequestMetrics,
|
| 12 |
+
DecisionMetrics,
|
| 13 |
+
BudgetMetrics,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
# =============================================================================
|
| 18 |
+
# Prometheus Metric Types (natifs, sans dépendance)
|
| 19 |
+
# =============================================================================
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class Counter:
|
| 23 |
+
"""Prometheus-style counter metric."""
|
| 24 |
+
|
| 25 |
+
def __init__(self, name: str, description: str, labels: list[str] | None = None):
|
| 26 |
+
self.name = name
|
| 27 |
+
self.description = description
|
| 28 |
+
self.label_names = labels or []
|
| 29 |
+
self.values: dict[tuple, float] = defaultdict(float)
|
| 30 |
+
|
| 31 |
+
def inc(self, value: float = 1, **labels) -> None:
|
| 32 |
+
"""Increment counter."""
|
| 33 |
+
label_key = tuple(labels.get(k, "") for k in self.label_names)
|
| 34 |
+
self.values[label_key] += value
|
| 35 |
+
|
| 36 |
+
def get(self, **labels) -> float:
|
| 37 |
+
"""Get counter value."""
|
| 38 |
+
label_key = tuple(labels.get(k, "") for k in self.label_names)
|
| 39 |
+
return self.values.get(label_key, 0)
|
| 40 |
+
|
| 41 |
+
def export(self) -> str:
|
| 42 |
+
"""Export in Prometheus format."""
|
| 43 |
+
lines = [
|
| 44 |
+
f"# HELP {self.name} {self.description}",
|
| 45 |
+
f"# TYPE {self.name} counter",
|
| 46 |
+
]
|
| 47 |
+
for label_key, value in self.values.items():
|
| 48 |
+
if self.label_names:
|
| 49 |
+
labels_str = ",".join(
|
| 50 |
+
f'{k}="{v}"' for k, v in zip(self.label_names, label_key)
|
| 51 |
+
)
|
| 52 |
+
lines.append(f"{self.name}{{{labels_str}}} {value}")
|
| 53 |
+
else:
|
| 54 |
+
lines.append(f"{self.name} {value}")
|
| 55 |
+
return "\n".join(lines)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class Gauge:
|
| 59 |
+
"""Prometheus-style gauge metric."""
|
| 60 |
+
|
| 61 |
+
def __init__(self, name: str, description: str, labels: list[str] | None = None):
|
| 62 |
+
self.name = name
|
| 63 |
+
self.description = description
|
| 64 |
+
self.label_names = labels or []
|
| 65 |
+
self.values: dict[tuple, float] = {}
|
| 66 |
+
|
| 67 |
+
def set(self, value: float, **labels) -> None:
|
| 68 |
+
"""Set gauge value."""
|
| 69 |
+
label_key = tuple(labels.get(k, "") for k in self.label_names)
|
| 70 |
+
self.values[label_key] = value
|
| 71 |
+
|
| 72 |
+
def inc(self, value: float = 1, **labels) -> None:
|
| 73 |
+
"""Increment gauge."""
|
| 74 |
+
label_key = tuple(labels.get(k, "") for k in self.label_names)
|
| 75 |
+
self.values[label_key] = self.values.get(label_key, 0) + value
|
| 76 |
+
|
| 77 |
+
def dec(self, value: float = 1, **labels) -> None:
|
| 78 |
+
"""Decrement gauge."""
|
| 79 |
+
label_key = tuple(labels.get(k, "") for k in self.label_names)
|
| 80 |
+
self.values[label_key] = self.values.get(label_key, 0) - value
|
| 81 |
+
|
| 82 |
+
def get(self, **labels) -> float:
|
| 83 |
+
"""Get gauge value."""
|
| 84 |
+
label_key = tuple(labels.get(k, "") for k in self.label_names)
|
| 85 |
+
return self.values.get(label_key, 0)
|
| 86 |
+
|
| 87 |
+
def export(self) -> str:
|
| 88 |
+
"""Export in Prometheus format."""
|
| 89 |
+
lines = [
|
| 90 |
+
f"# HELP {self.name} {self.description}",
|
| 91 |
+
f"# TYPE {self.name} gauge",
|
| 92 |
+
]
|
| 93 |
+
for label_key, value in self.values.items():
|
| 94 |
+
if self.label_names:
|
| 95 |
+
labels_str = ",".join(
|
| 96 |
+
f'{k}="{v}"' for k, v in zip(self.label_names, label_key)
|
| 97 |
+
)
|
| 98 |
+
lines.append(f"{self.name}{{{labels_str}}} {value}")
|
| 99 |
+
else:
|
| 100 |
+
lines.append(f"{self.name} {value}")
|
| 101 |
+
return "\n".join(lines)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class Histogram:
|
| 105 |
+
"""Prometheus-style histogram metric."""
|
| 106 |
+
|
| 107 |
+
DEFAULT_BUCKETS = (0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10)
|
| 108 |
+
|
| 109 |
+
def __init__(
|
| 110 |
+
self,
|
| 111 |
+
name: str,
|
| 112 |
+
description: str,
|
| 113 |
+
labels: list[str] | None = None,
|
| 114 |
+
buckets: tuple | None = None,
|
| 115 |
+
):
|
| 116 |
+
self.name = name
|
| 117 |
+
self.description = description
|
| 118 |
+
self.label_names = labels or []
|
| 119 |
+
self.buckets = buckets or self.DEFAULT_BUCKETS
|
| 120 |
+
self.observations: dict[tuple, list[float]] = defaultdict(list)
|
| 121 |
+
|
| 122 |
+
def observe(self, value: float, **labels) -> None:
|
| 123 |
+
"""Observe a value."""
|
| 124 |
+
label_key = tuple(labels.get(k, "") for k in self.label_names)
|
| 125 |
+
self.observations[label_key].append(value)
|
| 126 |
+
|
| 127 |
+
def export(self) -> str:
|
| 128 |
+
"""Export in Prometheus format."""
|
| 129 |
+
lines = [
|
| 130 |
+
f"# HELP {self.name} {self.description}",
|
| 131 |
+
f"# TYPE {self.name} histogram",
|
| 132 |
+
]
|
| 133 |
+
|
| 134 |
+
for label_key, values in self.observations.items():
|
| 135 |
+
labels_str = ""
|
| 136 |
+
if self.label_names:
|
| 137 |
+
labels_str = ",".join(
|
| 138 |
+
f'{k}="{v}"' for k, v in zip(self.label_names, label_key)
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
sorted_values = sorted(values)
|
| 142 |
+
total = len(values)
|
| 143 |
+
sum_val = sum(values)
|
| 144 |
+
|
| 145 |
+
for bucket in self.buckets:
|
| 146 |
+
count = sum(1 for v in sorted_values if v <= bucket)
|
| 147 |
+
if labels_str:
|
| 148 |
+
lines.append(
|
| 149 |
+
f'{self.name}_bucket{{{labels_str},le="{bucket}"}} {count}'
|
| 150 |
+
)
|
| 151 |
+
else:
|
| 152 |
+
lines.append(f'{self.name}_bucket{{le="{bucket}"}} {count}')
|
| 153 |
+
|
| 154 |
+
if labels_str:
|
| 155 |
+
lines.append(f'{self.name}_bucket{{{labels_str},le="+Inf"}} {total}')
|
| 156 |
+
lines.append(f"{self.name}_sum{{{labels_str}}} {sum_val}")
|
| 157 |
+
lines.append(f"{self.name}_count{{{labels_str}}} {total}")
|
| 158 |
+
else:
|
| 159 |
+
lines.append(f'{self.name}_bucket{{le="+Inf"}} {total}')
|
| 160 |
+
lines.append(f"{self.name}_sum {sum_val}")
|
| 161 |
+
lines.append(f"{self.name}_count {total}")
|
| 162 |
+
|
| 163 |
+
return "\n".join(lines)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
# =============================================================================
|
| 167 |
+
# Prometheus Metrics Adapter
|
| 168 |
+
# =============================================================================
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class PrometheusMetricsAdapter(MetricsPort):
|
| 172 |
+
"""Adapter natif pour les métriques Prometheus.
|
| 173 |
+
|
| 174 |
+
Implémente directement l'interface MetricsPort en utilisant
|
| 175 |
+
des structures de données natives pour les métriques Prometheus.
|
| 176 |
+
Aucune dépendance au code legacy (exporters/).
|
| 177 |
+
"""
|
| 178 |
+
|
| 179 |
+
def __init__(self):
|
| 180 |
+
"""Initialise les métriques Prometheus."""
|
| 181 |
+
# Request metrics
|
| 182 |
+
self.requests_total = Counter(
|
| 183 |
+
"llm_gateway_requests_total",
|
| 184 |
+
"Total number of LLM requests",
|
| 185 |
+
["app_id", "feature", "model", "environment", "status"],
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
self.request_latency = Histogram(
|
| 189 |
+
"llm_gateway_request_latency_seconds",
|
| 190 |
+
"Request latency in seconds",
|
| 191 |
+
["app_id", "model"],
|
| 192 |
+
buckets=(0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60),
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
# Token metrics
|
| 196 |
+
self.tokens_total = Counter(
|
| 197 |
+
"llm_gateway_tokens_total",
|
| 198 |
+
"Total tokens processed",
|
| 199 |
+
["app_id", "model", "direction"],
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
# Cost metrics
|
| 203 |
+
self.cost_total = Counter(
|
| 204 |
+
"llm_gateway_cost_usd_total",
|
| 205 |
+
"Total cost in USD",
|
| 206 |
+
["app_id", "feature", "model"],
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
# Budget metrics
|
| 210 |
+
self.budget_usage = Gauge(
|
| 211 |
+
"llm_gateway_budget_usage_ratio",
|
| 212 |
+
"Budget usage ratio (0-1)",
|
| 213 |
+
["app_id", "feature", "environment"],
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
self.budget_remaining = Gauge(
|
| 217 |
+
"llm_gateway_budget_remaining_usd",
|
| 218 |
+
"Remaining budget in USD",
|
| 219 |
+
["app_id", "feature", "environment"],
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
# Decision metrics
|
| 223 |
+
self.decisions_total = Counter(
|
| 224 |
+
"llm_gateway_decisions_total",
|
| 225 |
+
"Total governance decisions",
|
| 226 |
+
["app_id", "decision", "source"],
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
# Security metrics
|
| 230 |
+
self.security_blocks = Counter(
|
| 231 |
+
"llm_gateway_security_blocks_total",
|
| 232 |
+
"Security blocks",
|
| 233 |
+
["app_id", "reason"],
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
# Error metrics
|
| 237 |
+
self.errors_total = Counter(
|
| 238 |
+
"llm_gateway_errors_total",
|
| 239 |
+
"Total errors",
|
| 240 |
+
["app_id", "error_type"],
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
# Active requests gauge
|
| 244 |
+
self.active_requests = Gauge(
|
| 245 |
+
"llm_gateway_active_requests",
|
| 246 |
+
"Currently active requests",
|
| 247 |
+
["app_id"],
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
def record_request(self, metrics: RequestMetrics) -> None:
|
| 251 |
+
"""Enregistre les métriques d'une requête."""
|
| 252 |
+
self.requests_total.inc(
|
| 253 |
+
app_id=metrics.app_id,
|
| 254 |
+
feature=metrics.feature,
|
| 255 |
+
model=metrics.model,
|
| 256 |
+
environment=metrics.environment,
|
| 257 |
+
status=metrics.status,
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
self.request_latency.observe(
|
| 261 |
+
metrics.latency_seconds,
|
| 262 |
+
app_id=metrics.app_id,
|
| 263 |
+
model=metrics.model,
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
if metrics.input_tokens > 0:
|
| 267 |
+
self.tokens_total.inc(
|
| 268 |
+
metrics.input_tokens,
|
| 269 |
+
app_id=metrics.app_id,
|
| 270 |
+
model=metrics.model,
|
| 271 |
+
direction="input",
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
if metrics.output_tokens > 0:
|
| 275 |
+
self.tokens_total.inc(
|
| 276 |
+
metrics.output_tokens,
|
| 277 |
+
app_id=metrics.app_id,
|
| 278 |
+
model=metrics.model,
|
| 279 |
+
direction="output",
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
if metrics.cost_usd > 0:
|
| 283 |
+
self.cost_total.inc(
|
| 284 |
+
metrics.cost_usd,
|
| 285 |
+
app_id=metrics.app_id,
|
| 286 |
+
feature=metrics.feature,
|
| 287 |
+
model=metrics.model,
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
def record_decision(self, metrics: DecisionMetrics) -> None:
|
| 291 |
+
"""Enregistre une décision de gouvernance."""
|
| 292 |
+
self.decisions_total.inc(
|
| 293 |
+
app_id=metrics.app_id,
|
| 294 |
+
decision=metrics.decision,
|
| 295 |
+
source=metrics.source,
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
def record_error(self, app_id: str, error_type: str) -> None:
|
| 299 |
+
"""Enregistre une erreur."""
|
| 300 |
+
self.errors_total.inc(app_id=app_id, error_type=error_type)
|
| 301 |
+
|
| 302 |
+
def record_security_block(self, app_id: str, reason: str) -> None:
|
| 303 |
+
"""Enregistre un blocage de sécurité."""
|
| 304 |
+
self.security_blocks.inc(app_id=app_id, reason=reason)
|
| 305 |
+
|
| 306 |
+
def update_budget(self, metrics: BudgetMetrics) -> None:
|
| 307 |
+
"""Met à jour les métriques de budget."""
|
| 308 |
+
self.budget_usage.set(
|
| 309 |
+
metrics.usage_ratio,
|
| 310 |
+
app_id=metrics.app_id,
|
| 311 |
+
feature=metrics.feature,
|
| 312 |
+
environment=metrics.environment,
|
| 313 |
+
)
|
| 314 |
+
self.budget_remaining.set(
|
| 315 |
+
metrics.remaining_usd,
|
| 316 |
+
app_id=metrics.app_id,
|
| 317 |
+
feature=metrics.feature,
|
| 318 |
+
environment=metrics.environment,
|
| 319 |
+
)
|
| 320 |
+
|
| 321 |
+
def request_started(self, app_id: str) -> None:
|
| 322 |
+
"""Signale le début d'une requête."""
|
| 323 |
+
self.active_requests.inc(app_id=app_id)
|
| 324 |
+
|
| 325 |
+
def request_finished(self, app_id: str) -> None:
|
| 326 |
+
"""Signale la fin d'une requête."""
|
| 327 |
+
self.active_requests.dec(app_id=app_id)
|
| 328 |
+
|
| 329 |
+
def export(self) -> str:
|
| 330 |
+
"""Exporte les métriques au format Prometheus."""
|
| 331 |
+
metrics = [
|
| 332 |
+
self.requests_total,
|
| 333 |
+
self.request_latency,
|
| 334 |
+
self.tokens_total,
|
| 335 |
+
self.cost_total,
|
| 336 |
+
self.budget_usage,
|
| 337 |
+
self.budget_remaining,
|
| 338 |
+
self.decisions_total,
|
| 339 |
+
self.security_blocks,
|
| 340 |
+
self.errors_total,
|
| 341 |
+
self.active_requests,
|
| 342 |
+
]
|
| 343 |
+
|
| 344 |
+
def has_data(m):
|
| 345 |
+
if hasattr(m, "observations"):
|
| 346 |
+
return bool(m.observations)
|
| 347 |
+
if hasattr(m, "values"):
|
| 348 |
+
return bool(m.values)
|
| 349 |
+
return False
|
| 350 |
+
|
| 351 |
+
return "\n\n".join(m.export() for m in metrics if has_data(m))
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
# =============================================================================
|
| 355 |
+
# InMemory Metrics Adapter (pour les tests)
|
| 356 |
+
# =============================================================================
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
class InMemoryMetricsAdapter(MetricsPort):
|
| 360 |
+
"""Adapter en mémoire pour les métriques (pour les tests).
|
| 361 |
+
|
| 362 |
+
Stocke les métriques dans des structures simples pour
|
| 363 |
+
faciliter les assertions dans les tests.
|
| 364 |
+
"""
|
| 365 |
+
|
| 366 |
+
def __init__(self):
|
| 367 |
+
"""Initialise le stockage en mémoire."""
|
| 368 |
+
self.requests: list[RequestMetrics] = []
|
| 369 |
+
self.decisions: list[DecisionMetrics] = []
|
| 370 |
+
self.errors: list[tuple[str, str]] = [] # (app_id, error_type)
|
| 371 |
+
self.security_blocks: list[tuple[str, str]] = [] # (app_id, reason)
|
| 372 |
+
self.budgets: dict[str, BudgetMetrics] = {} # key = f"{app_id}:{feature}:{env}"
|
| 373 |
+
self.active_requests: dict[str, int] = defaultdict(int)
|
| 374 |
+
|
| 375 |
+
def record_request(self, metrics: RequestMetrics) -> None:
|
| 376 |
+
"""Enregistre les métriques d'une requête."""
|
| 377 |
+
self.requests.append(metrics)
|
| 378 |
+
|
| 379 |
+
def record_decision(self, metrics: DecisionMetrics) -> None:
|
| 380 |
+
"""Enregistre une décision de gouvernance."""
|
| 381 |
+
self.decisions.append(metrics)
|
| 382 |
+
|
| 383 |
+
def record_error(self, app_id: str, error_type: str) -> None:
|
| 384 |
+
"""Enregistre une erreur."""
|
| 385 |
+
self.errors.append((app_id, error_type))
|
| 386 |
+
|
| 387 |
+
def record_security_block(self, app_id: str, reason: str) -> None:
|
| 388 |
+
"""Enregistre un blocage de sécurité."""
|
| 389 |
+
self.security_blocks.append((app_id, reason))
|
| 390 |
+
|
| 391 |
+
def update_budget(self, metrics: BudgetMetrics) -> None:
|
| 392 |
+
"""Met à jour les métriques de budget."""
|
| 393 |
+
key = f"{metrics.app_id}:{metrics.feature}:{metrics.environment}"
|
| 394 |
+
self.budgets[key] = metrics
|
| 395 |
+
|
| 396 |
+
def request_started(self, app_id: str) -> None:
|
| 397 |
+
"""Signale le début d'une requête."""
|
| 398 |
+
self.active_requests[app_id] += 1
|
| 399 |
+
|
| 400 |
+
def request_finished(self, app_id: str) -> None:
|
| 401 |
+
"""Signale la fin d'une requête."""
|
| 402 |
+
self.active_requests[app_id] = max(0, self.active_requests[app_id] - 1)
|
| 403 |
+
|
| 404 |
+
def export(self) -> str:
|
| 405 |
+
"""Exporte les métriques (format simplifié pour debug)."""
|
| 406 |
+
lines = [
|
| 407 |
+
f"requests_count: {len(self.requests)}",
|
| 408 |
+
f"decisions_count: {len(self.decisions)}",
|
| 409 |
+
f"errors_count: {len(self.errors)}",
|
| 410 |
+
f"security_blocks_count: {len(self.security_blocks)}",
|
| 411 |
+
f"budgets_count: {len(self.budgets)}",
|
| 412 |
+
f"active_requests: {dict(self.active_requests)}",
|
| 413 |
+
]
|
| 414 |
+
return "\n".join(lines)
|
| 415 |
+
|
| 416 |
+
def clear(self) -> None:
|
| 417 |
+
"""Vide toutes les métriques."""
|
| 418 |
+
self.requests.clear()
|
| 419 |
+
self.decisions.clear()
|
| 420 |
+
self.errors.clear()
|
| 421 |
+
self.security_blocks.clear()
|
| 422 |
+
self.budgets.clear()
|
| 423 |
+
self.active_requests.clear()
|
| 424 |
+
|
| 425 |
+
# Helpers pour les tests
|
| 426 |
+
def get_request_count(
|
| 427 |
+
self, app_id: str | None = None, status: str | None = None
|
| 428 |
+
) -> int:
|
| 429 |
+
"""Compte les requêtes avec filtres optionnels."""
|
| 430 |
+
filtered = self.requests
|
| 431 |
+
if app_id:
|
| 432 |
+
filtered = [r for r in filtered if r.app_id == app_id]
|
| 433 |
+
if status:
|
| 434 |
+
filtered = [r for r in filtered if r.status == status]
|
| 435 |
+
return len(filtered)
|
| 436 |
+
|
| 437 |
+
def get_decision_count(
|
| 438 |
+
self, decision: str | None = None, source: str | None = None
|
| 439 |
+
) -> int:
|
| 440 |
+
"""Compte les décisions avec filtres optionnels."""
|
| 441 |
+
filtered = self.decisions
|
| 442 |
+
if decision:
|
| 443 |
+
filtered = [d for d in filtered if d.decision == decision]
|
| 444 |
+
if source:
|
| 445 |
+
filtered = [d for d in filtered if d.source == source]
|
| 446 |
+
return len(filtered)
|
| 447 |
+
|
| 448 |
+
def get_total_tokens(self, direction: str | None = None) -> int:
|
| 449 |
+
"""Calcule le total des tokens."""
|
| 450 |
+
total = 0
|
| 451 |
+
for r in self.requests:
|
| 452 |
+
if direction == "input" or direction is None:
|
| 453 |
+
total += r.input_tokens
|
| 454 |
+
if direction == "output" or direction is None:
|
| 455 |
+
total += r.output_tokens
|
| 456 |
+
return total
|
| 457 |
+
|
| 458 |
+
def get_total_cost(self) -> float:
|
| 459 |
+
"""Calcule le coût total."""
|
| 460 |
+
return sum(r.cost_usd for r in self.requests)
|
backend/adapters/redis/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Redis Adapters - Implémentations natives.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Ces adapters implémentent les Ports de cache
|
| 4 |
+
en utilisant directement redis.asyncio.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from backend.adapters.redis.cache_adapter import (
|
| 8 |
+
RedisCacheAdapter,
|
| 9 |
+
InMemoryCacheAdapter,
|
| 10 |
+
create_redis_cache_adapter,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
__all__ = [
|
| 15 |
+
"RedisCacheAdapter",
|
| 16 |
+
"InMemoryCacheAdapter",
|
| 17 |
+
"create_redis_cache_adapter",
|
| 18 |
+
]
|
backend/adapters/redis/cache_adapter.py
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Redis Cache Adapter - Implémentation native Redis.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Adapter natif qui implémente directement
|
| 4 |
+
l'interface CachePort en utilisant redis.asyncio.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import json
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
import redis.asyncio as redis
|
| 11 |
+
|
| 12 |
+
from backend.ports.cache import CachePort
|
| 13 |
+
from backend.core.config import settings
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class RedisCacheAdapter(CachePort):
|
| 17 |
+
"""Adapter natif pour le cache Redis.
|
| 18 |
+
|
| 19 |
+
Implémente directement l'interface CachePort en utilisant
|
| 20 |
+
redis.asyncio pour les opérations de cache.
|
| 21 |
+
Aucune dépendance au code legacy (cache/).
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
def __init__(
|
| 25 |
+
self, redis_client: redis.Redis | None = None, redis_url: str | None = None
|
| 26 |
+
):
|
| 27 |
+
"""Initialise l'adapter.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
redis_client: Client Redis optionnel. Si non fourni,
|
| 31 |
+
une nouvelle connexion sera créée.
|
| 32 |
+
redis_url: URL Redis optionnelle (utilisée si redis_client non fourni)
|
| 33 |
+
"""
|
| 34 |
+
self._redis = redis_client
|
| 35 |
+
self._redis_url = redis_url or settings.redis_url
|
| 36 |
+
self._initialized = redis_client is not None
|
| 37 |
+
|
| 38 |
+
async def _ensure_connected(self) -> redis.Redis:
|
| 39 |
+
"""S'assure que la connexion Redis est établie.
|
| 40 |
+
|
| 41 |
+
Returns:
|
| 42 |
+
Client Redis connecté
|
| 43 |
+
"""
|
| 44 |
+
if self._redis is None:
|
| 45 |
+
self._redis = redis.from_url(
|
| 46 |
+
self._redis_url,
|
| 47 |
+
encoding="utf-8",
|
| 48 |
+
decode_responses=True,
|
| 49 |
+
)
|
| 50 |
+
self._initialized = True
|
| 51 |
+
return self._redis
|
| 52 |
+
|
| 53 |
+
async def close(self) -> None:
|
| 54 |
+
"""Ferme la connexion Redis."""
|
| 55 |
+
if self._redis and self._initialized:
|
| 56 |
+
await self._redis.close()
|
| 57 |
+
self._redis = None
|
| 58 |
+
self._initialized = False
|
| 59 |
+
|
| 60 |
+
async def get(self, key: str) -> Any | None:
|
| 61 |
+
"""Récupère une valeur du cache.
|
| 62 |
+
|
| 63 |
+
Args:
|
| 64 |
+
key: Clé de cache
|
| 65 |
+
|
| 66 |
+
Returns:
|
| 67 |
+
La valeur désérialisée ou None si non trouvée
|
| 68 |
+
"""
|
| 69 |
+
client = await self._ensure_connected()
|
| 70 |
+
data = await client.get(key)
|
| 71 |
+
|
| 72 |
+
if data is None:
|
| 73 |
+
return None
|
| 74 |
+
|
| 75 |
+
try:
|
| 76 |
+
return json.loads(data)
|
| 77 |
+
except (json.JSONDecodeError, TypeError):
|
| 78 |
+
# Retourner la valeur brute si ce n'est pas du JSON
|
| 79 |
+
return data
|
| 80 |
+
|
| 81 |
+
async def set(
|
| 82 |
+
self,
|
| 83 |
+
key: str,
|
| 84 |
+
value: Any,
|
| 85 |
+
ttl_seconds: int | None = None,
|
| 86 |
+
) -> bool:
|
| 87 |
+
"""Stocke une valeur dans le cache.
|
| 88 |
+
|
| 89 |
+
Args:
|
| 90 |
+
key: Clé de cache
|
| 91 |
+
value: Valeur à stocker (sera sérialisée en JSON)
|
| 92 |
+
ttl_seconds: Durée de vie en secondes (None = pas d'expiration)
|
| 93 |
+
|
| 94 |
+
Returns:
|
| 95 |
+
True si stocké avec succès
|
| 96 |
+
"""
|
| 97 |
+
client = await self._ensure_connected()
|
| 98 |
+
|
| 99 |
+
try:
|
| 100 |
+
serialized = json.dumps(value)
|
| 101 |
+
|
| 102 |
+
if ttl_seconds:
|
| 103 |
+
await client.setex(key, ttl_seconds, serialized)
|
| 104 |
+
else:
|
| 105 |
+
await client.set(key, serialized)
|
| 106 |
+
|
| 107 |
+
return True
|
| 108 |
+
except Exception:
|
| 109 |
+
return False
|
| 110 |
+
|
| 111 |
+
async def delete(self, key: str) -> bool:
|
| 112 |
+
"""Supprime une valeur du cache.
|
| 113 |
+
|
| 114 |
+
Args:
|
| 115 |
+
key: Clé de cache
|
| 116 |
+
|
| 117 |
+
Returns:
|
| 118 |
+
True si supprimée, False si non trouvée
|
| 119 |
+
"""
|
| 120 |
+
client = await self._ensure_connected()
|
| 121 |
+
|
| 122 |
+
try:
|
| 123 |
+
result = await client.delete(key)
|
| 124 |
+
return result > 0
|
| 125 |
+
except Exception:
|
| 126 |
+
return False
|
| 127 |
+
|
| 128 |
+
async def exists(self, key: str) -> bool:
|
| 129 |
+
"""Vérifie si une clé existe dans le cache.
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
key: Clé de cache
|
| 133 |
+
|
| 134 |
+
Returns:
|
| 135 |
+
True si la clé existe
|
| 136 |
+
"""
|
| 137 |
+
client = await self._ensure_connected()
|
| 138 |
+
return await client.exists(key) > 0
|
| 139 |
+
|
| 140 |
+
async def increment(
|
| 141 |
+
self,
|
| 142 |
+
key: str,
|
| 143 |
+
amount: int = 1,
|
| 144 |
+
) -> int:
|
| 145 |
+
"""Incrémente une valeur numérique.
|
| 146 |
+
|
| 147 |
+
Args:
|
| 148 |
+
key: Clé de cache
|
| 149 |
+
amount: Montant à incrémenter
|
| 150 |
+
|
| 151 |
+
Returns:
|
| 152 |
+
Nouvelle valeur après incrémentation
|
| 153 |
+
"""
|
| 154 |
+
client = await self._ensure_connected()
|
| 155 |
+
result = await client.incrby(key, amount)
|
| 156 |
+
return int(result)
|
| 157 |
+
|
| 158 |
+
async def expire(self, key: str, ttl_seconds: int) -> bool:
|
| 159 |
+
"""Définit un TTL sur une clé existante.
|
| 160 |
+
|
| 161 |
+
Args:
|
| 162 |
+
key: Clé de cache
|
| 163 |
+
ttl_seconds: Durée de vie en secondes
|
| 164 |
+
|
| 165 |
+
Returns:
|
| 166 |
+
True si le TTL a été défini
|
| 167 |
+
"""
|
| 168 |
+
client = await self._ensure_connected()
|
| 169 |
+
|
| 170 |
+
try:
|
| 171 |
+
result = await client.expire(key, ttl_seconds)
|
| 172 |
+
return bool(result)
|
| 173 |
+
except Exception:
|
| 174 |
+
return False
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class InMemoryCacheAdapter(CachePort):
|
| 178 |
+
"""Adapter in-memory pour les tests.
|
| 179 |
+
|
| 180 |
+
Implémente l'interface CachePort sans Redis.
|
| 181 |
+
Utile pour les tests unitaires.
|
| 182 |
+
"""
|
| 183 |
+
|
| 184 |
+
def __init__(self):
|
| 185 |
+
"""Initialise le cache in-memory."""
|
| 186 |
+
self._store: dict[str, tuple[Any, float | None]] = {}
|
| 187 |
+
import time
|
| 188 |
+
|
| 189 |
+
self._time = time
|
| 190 |
+
|
| 191 |
+
async def get(self, key: str) -> Any | None:
|
| 192 |
+
"""Récupère une valeur du cache."""
|
| 193 |
+
if key not in self._store:
|
| 194 |
+
return None
|
| 195 |
+
|
| 196 |
+
value, expires_at = self._store[key]
|
| 197 |
+
|
| 198 |
+
# Vérifier l'expiration
|
| 199 |
+
if expires_at is not None and self._time.time() > expires_at:
|
| 200 |
+
del self._store[key]
|
| 201 |
+
return None
|
| 202 |
+
|
| 203 |
+
return value
|
| 204 |
+
|
| 205 |
+
async def set(
|
| 206 |
+
self,
|
| 207 |
+
key: str,
|
| 208 |
+
value: Any,
|
| 209 |
+
ttl_seconds: int | None = None,
|
| 210 |
+
) -> bool:
|
| 211 |
+
"""Stocke une valeur dans le cache."""
|
| 212 |
+
expires_at = None
|
| 213 |
+
if ttl_seconds:
|
| 214 |
+
expires_at = self._time.time() + ttl_seconds
|
| 215 |
+
|
| 216 |
+
self._store[key] = (value, expires_at)
|
| 217 |
+
return True
|
| 218 |
+
|
| 219 |
+
async def delete(self, key: str) -> bool:
|
| 220 |
+
"""Supprime une valeur du cache."""
|
| 221 |
+
if key in self._store:
|
| 222 |
+
del self._store[key]
|
| 223 |
+
return True
|
| 224 |
+
return False
|
| 225 |
+
|
| 226 |
+
async def exists(self, key: str) -> bool:
|
| 227 |
+
"""Vérifie si une clé existe dans le cache."""
|
| 228 |
+
if key not in self._store:
|
| 229 |
+
return False
|
| 230 |
+
|
| 231 |
+
value, expires_at = self._store[key]
|
| 232 |
+
if expires_at is not None and self._time.time() > expires_at:
|
| 233 |
+
del self._store[key]
|
| 234 |
+
return False
|
| 235 |
+
|
| 236 |
+
return True
|
| 237 |
+
|
| 238 |
+
async def increment(
|
| 239 |
+
self,
|
| 240 |
+
key: str,
|
| 241 |
+
amount: int = 1,
|
| 242 |
+
) -> int:
|
| 243 |
+
"""Incrémente une valeur numérique."""
|
| 244 |
+
current = await self.get(key)
|
| 245 |
+
|
| 246 |
+
if current is None:
|
| 247 |
+
new_value = amount
|
| 248 |
+
else:
|
| 249 |
+
new_value = int(current) + amount
|
| 250 |
+
|
| 251 |
+
await self.set(key, new_value)
|
| 252 |
+
return new_value
|
| 253 |
+
|
| 254 |
+
async def expire(self, key: str, ttl_seconds: int) -> bool:
|
| 255 |
+
"""Définit un TTL sur une clé existante."""
|
| 256 |
+
if key not in self._store:
|
| 257 |
+
return False
|
| 258 |
+
|
| 259 |
+
value, _ = self._store[key]
|
| 260 |
+
expires_at = self._time.time() + ttl_seconds
|
| 261 |
+
self._store[key] = (value, expires_at)
|
| 262 |
+
return True
|
| 263 |
+
|
| 264 |
+
def clear(self) -> None:
|
| 265 |
+
"""Vide le cache (utile pour les tests)."""
|
| 266 |
+
self._store.clear()
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
async def create_redis_cache_adapter(redis_url: str | None = None) -> RedisCacheAdapter:
|
| 270 |
+
"""Factory pour créer un RedisCacheAdapter.
|
| 271 |
+
|
| 272 |
+
Args:
|
| 273 |
+
redis_url: URL Redis optionnelle (utilise settings si non fourni)
|
| 274 |
+
|
| 275 |
+
Returns:
|
| 276 |
+
Instance de RedisCacheAdapter configurée
|
| 277 |
+
"""
|
| 278 |
+
return RedisCacheAdapter(redis_url=redis_url)
|
backend/adapters/tracing/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Request Tracing Adapters.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Implementations du RequestTracingPort.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from backend.adapters.tracing.in_memory_adapter import InMemoryRequestTracingAdapter
|
| 7 |
+
from backend.adapters.tracing.opentelemetry_adapter import OpenTelemetryTracingAdapter
|
| 8 |
+
from backend.adapters.tracing.postgres_adapter import PostgresRequestTracingAdapter
|
| 9 |
+
|
| 10 |
+
__all__ = [
|
| 11 |
+
"InMemoryRequestTracingAdapter",
|
| 12 |
+
"OpenTelemetryTracingAdapter",
|
| 13 |
+
"PostgresRequestTracingAdapter",
|
| 14 |
+
]
|
backend/adapters/tracing/in_memory_adapter.py
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""In-Memory Request Tracing Adapter.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Implementation native du RequestTracingPort
|
| 4 |
+
pour le tracage des requetes.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import uuid
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
|
| 10 |
+
from backend.ports.request_tracing import (
|
| 11 |
+
RequestTracingPort,
|
| 12 |
+
Trace,
|
| 13 |
+
TraceSpan,
|
| 14 |
+
TraceFilters,
|
| 15 |
+
TraceStatus,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class InMemoryRequestTracingAdapter(RequestTracingPort):
|
| 20 |
+
"""
|
| 21 |
+
Native implementation of request tracing.
|
| 22 |
+
|
| 23 |
+
Stores traces in memory for debugging and development.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def __init__(self, max_traces: int = 10000):
|
| 27 |
+
self._traces: dict[str, Trace] = {}
|
| 28 |
+
self._by_request_id: dict[str, str] = {} # request_id -> trace_id
|
| 29 |
+
self._max_traces = max_traces
|
| 30 |
+
|
| 31 |
+
async def create_trace(
|
| 32 |
+
self,
|
| 33 |
+
request_id: str,
|
| 34 |
+
app_id: str,
|
| 35 |
+
org_id: str | None = None,
|
| 36 |
+
model: str | None = None,
|
| 37 |
+
context: dict | None = None,
|
| 38 |
+
) -> Trace:
|
| 39 |
+
"""Create a new trace."""
|
| 40 |
+
trace_id = str(uuid.uuid4())
|
| 41 |
+
|
| 42 |
+
trace = Trace(
|
| 43 |
+
trace_id=trace_id,
|
| 44 |
+
request_id=request_id,
|
| 45 |
+
app_id=app_id,
|
| 46 |
+
org_id=org_id,
|
| 47 |
+
model=model,
|
| 48 |
+
status=TraceStatus.STARTED,
|
| 49 |
+
started_at=datetime.now(),
|
| 50 |
+
context=context or {},
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
self._traces[trace_id] = trace
|
| 54 |
+
self._by_request_id[request_id] = trace_id
|
| 55 |
+
|
| 56 |
+
# Cleanup old traces if needed
|
| 57 |
+
self._cleanup_if_needed()
|
| 58 |
+
|
| 59 |
+
return trace
|
| 60 |
+
|
| 61 |
+
async def start_span(
|
| 62 |
+
self,
|
| 63 |
+
trace_id: str,
|
| 64 |
+
step: str,
|
| 65 |
+
data: dict | None = None,
|
| 66 |
+
) -> TraceSpan:
|
| 67 |
+
"""Start a span in a trace."""
|
| 68 |
+
if trace_id not in self._traces:
|
| 69 |
+
raise ValueError(f"Trace {trace_id} not found")
|
| 70 |
+
|
| 71 |
+
trace = self._traces[trace_id]
|
| 72 |
+
trace.status = TraceStatus.IN_PROGRESS
|
| 73 |
+
|
| 74 |
+
span = TraceSpan(
|
| 75 |
+
step=step,
|
| 76 |
+
started_at=datetime.now(),
|
| 77 |
+
data=data or {},
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
trace.spans.append(span)
|
| 81 |
+
return span
|
| 82 |
+
|
| 83 |
+
async def end_span(
|
| 84 |
+
self,
|
| 85 |
+
trace_id: str,
|
| 86 |
+
step: str,
|
| 87 |
+
status: str = "ok",
|
| 88 |
+
data: dict | None = None,
|
| 89 |
+
error: str | None = None,
|
| 90 |
+
) -> TraceSpan:
|
| 91 |
+
"""End a span in a trace."""
|
| 92 |
+
if trace_id not in self._traces:
|
| 93 |
+
raise ValueError(f"Trace {trace_id} not found")
|
| 94 |
+
|
| 95 |
+
trace = self._traces[trace_id]
|
| 96 |
+
|
| 97 |
+
# Find the span
|
| 98 |
+
span = None
|
| 99 |
+
for s in reversed(trace.spans):
|
| 100 |
+
if s.step == step and s.ended_at is None:
|
| 101 |
+
span = s
|
| 102 |
+
break
|
| 103 |
+
|
| 104 |
+
if span is None:
|
| 105 |
+
# Create a completed span if not found
|
| 106 |
+
span = TraceSpan(
|
| 107 |
+
step=step,
|
| 108 |
+
started_at=datetime.now(),
|
| 109 |
+
)
|
| 110 |
+
trace.spans.append(span)
|
| 111 |
+
|
| 112 |
+
span.ended_at = datetime.now()
|
| 113 |
+
span.status = status
|
| 114 |
+
span.duration_ms = (span.ended_at - span.started_at).total_seconds() * 1000
|
| 115 |
+
if data:
|
| 116 |
+
span.data.update(data)
|
| 117 |
+
if error:
|
| 118 |
+
span.error = error
|
| 119 |
+
|
| 120 |
+
return span
|
| 121 |
+
|
| 122 |
+
async def update_trace(
|
| 123 |
+
self,
|
| 124 |
+
trace_id: str,
|
| 125 |
+
step: str,
|
| 126 |
+
data: dict,
|
| 127 |
+
) -> Trace:
|
| 128 |
+
"""Update a trace with data."""
|
| 129 |
+
if trace_id not in self._traces:
|
| 130 |
+
raise ValueError(f"Trace {trace_id} not found")
|
| 131 |
+
|
| 132 |
+
trace = self._traces[trace_id]
|
| 133 |
+
trace.context.update({step: data})
|
| 134 |
+
|
| 135 |
+
return trace
|
| 136 |
+
|
| 137 |
+
async def complete_trace(
|
| 138 |
+
self,
|
| 139 |
+
trace_id: str,
|
| 140 |
+
outcome: str,
|
| 141 |
+
final_data: dict | None = None,
|
| 142 |
+
) -> Trace:
|
| 143 |
+
"""Complete a trace successfully."""
|
| 144 |
+
if trace_id not in self._traces:
|
| 145 |
+
raise ValueError(f"Trace {trace_id} not found")
|
| 146 |
+
|
| 147 |
+
trace = self._traces[trace_id]
|
| 148 |
+
trace.status = TraceStatus.COMPLETED
|
| 149 |
+
trace.outcome = outcome
|
| 150 |
+
trace.ended_at = datetime.now()
|
| 151 |
+
trace.total_duration_ms = (
|
| 152 |
+
trace.ended_at - trace.started_at
|
| 153 |
+
).total_seconds() * 1000
|
| 154 |
+
|
| 155 |
+
if final_data:
|
| 156 |
+
trace.context.update(final_data)
|
| 157 |
+
|
| 158 |
+
return trace
|
| 159 |
+
|
| 160 |
+
async def fail_trace(
|
| 161 |
+
self,
|
| 162 |
+
trace_id: str,
|
| 163 |
+
error: str,
|
| 164 |
+
step: str | None = None,
|
| 165 |
+
outcome: str | None = None,
|
| 166 |
+
) -> Trace:
|
| 167 |
+
"""Mark a trace as failed."""
|
| 168 |
+
if trace_id not in self._traces:
|
| 169 |
+
raise ValueError(f"Trace {trace_id} not found")
|
| 170 |
+
|
| 171 |
+
trace = self._traces[trace_id]
|
| 172 |
+
trace.status = TraceStatus.FAILED
|
| 173 |
+
trace.error = error
|
| 174 |
+
trace.outcome = outcome or "error"
|
| 175 |
+
trace.ended_at = datetime.now()
|
| 176 |
+
trace.total_duration_ms = (
|
| 177 |
+
trace.ended_at - trace.started_at
|
| 178 |
+
).total_seconds() * 1000
|
| 179 |
+
|
| 180 |
+
if step:
|
| 181 |
+
trace.context["failed_at_step"] = step
|
| 182 |
+
|
| 183 |
+
return trace
|
| 184 |
+
|
| 185 |
+
async def get_trace(
|
| 186 |
+
self,
|
| 187 |
+
trace_id: str,
|
| 188 |
+
) -> Trace | None:
|
| 189 |
+
"""Get a trace by ID."""
|
| 190 |
+
return self._traces.get(trace_id)
|
| 191 |
+
|
| 192 |
+
async def query_traces(
|
| 193 |
+
self,
|
| 194 |
+
filters: TraceFilters,
|
| 195 |
+
limit: int = 100,
|
| 196 |
+
offset: int = 0,
|
| 197 |
+
) -> list[Trace]:
|
| 198 |
+
"""Query traces with filters."""
|
| 199 |
+
results: list[Trace] = []
|
| 200 |
+
|
| 201 |
+
for trace in self._traces.values():
|
| 202 |
+
if not self._matches_filters(trace, filters):
|
| 203 |
+
continue
|
| 204 |
+
results.append(trace)
|
| 205 |
+
|
| 206 |
+
# Sort by started_at (most recent first)
|
| 207 |
+
results.sort(key=lambda t: t.started_at, reverse=True)
|
| 208 |
+
|
| 209 |
+
return results[offset : offset + limit]
|
| 210 |
+
|
| 211 |
+
async def get_trace_by_request_id(
|
| 212 |
+
self,
|
| 213 |
+
request_id: str,
|
| 214 |
+
) -> Trace | None:
|
| 215 |
+
"""Get a trace by request ID."""
|
| 216 |
+
trace_id = self._by_request_id.get(request_id)
|
| 217 |
+
if trace_id:
|
| 218 |
+
return self._traces.get(trace_id)
|
| 219 |
+
return None
|
| 220 |
+
|
| 221 |
+
def _matches_filters(self, trace: Trace, filters: TraceFilters) -> bool:
|
| 222 |
+
"""Check if trace matches filters."""
|
| 223 |
+
if filters.app_id and trace.app_id != filters.app_id:
|
| 224 |
+
return False
|
| 225 |
+
if filters.org_id and trace.org_id != filters.org_id:
|
| 226 |
+
return False
|
| 227 |
+
if filters.status and trace.status != filters.status:
|
| 228 |
+
return False
|
| 229 |
+
if filters.outcome and trace.outcome != filters.outcome:
|
| 230 |
+
return False
|
| 231 |
+
if filters.start_date and trace.started_at < filters.start_date:
|
| 232 |
+
return False
|
| 233 |
+
if filters.end_date and trace.started_at > filters.end_date:
|
| 234 |
+
return False
|
| 235 |
+
if filters.min_duration_ms is not None:
|
| 236 |
+
if (
|
| 237 |
+
trace.total_duration_ms is None
|
| 238 |
+
or trace.total_duration_ms < filters.min_duration_ms
|
| 239 |
+
):
|
| 240 |
+
return False
|
| 241 |
+
if filters.max_duration_ms is not None:
|
| 242 |
+
if (
|
| 243 |
+
trace.total_duration_ms is None
|
| 244 |
+
or trace.total_duration_ms > filters.max_duration_ms
|
| 245 |
+
):
|
| 246 |
+
return False
|
| 247 |
+
if filters.has_error is not None:
|
| 248 |
+
has_error = trace.error is not None
|
| 249 |
+
if filters.has_error != has_error:
|
| 250 |
+
return False
|
| 251 |
+
|
| 252 |
+
return True
|
| 253 |
+
|
| 254 |
+
def _cleanup_if_needed(self) -> None:
|
| 255 |
+
"""Remove old traces if exceeding max."""
|
| 256 |
+
if len(self._traces) > self._max_traces:
|
| 257 |
+
# Sort by started_at and remove oldest
|
| 258 |
+
sorted_traces = sorted(
|
| 259 |
+
self._traces.values(),
|
| 260 |
+
key=lambda t: t.started_at,
|
| 261 |
+
)
|
| 262 |
+
to_remove = len(self._traces) - self._max_traces
|
| 263 |
+
for trace in sorted_traces[:to_remove]:
|
| 264 |
+
del self._traces[trace.trace_id]
|
| 265 |
+
if trace.request_id in self._by_request_id:
|
| 266 |
+
del self._by_request_id[trace.request_id]
|
| 267 |
+
|
| 268 |
+
def clear(self) -> None:
|
| 269 |
+
"""Clear all traces."""
|
| 270 |
+
self._traces.clear()
|
| 271 |
+
self._by_request_id.clear()
|
| 272 |
+
|
| 273 |
+
def get_trace_count(self) -> int:
|
| 274 |
+
"""Get number of traces (for testing)."""
|
| 275 |
+
return len(self._traces)
|
backend/adapters/tracing/opentelemetry_adapter.py
ADDED
|
@@ -0,0 +1,415 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""OpenTelemetry Request Tracing Adapter.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Implémentation production du RequestTracingPort
|
| 4 |
+
utilisant OpenTelemetry pour le traçage distribué.
|
| 5 |
+
|
| 6 |
+
Ce module fournit:
|
| 7 |
+
- Traces OpenTelemetry standards
|
| 8 |
+
- Export vers Jaeger, Zipkin, OTLP
|
| 9 |
+
- Spans avec attributs sémantiques
|
| 10 |
+
- Propagation de contexte
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import uuid
|
| 14 |
+
from datetime import datetime
|
| 15 |
+
from typing import Any
|
| 16 |
+
|
| 17 |
+
from backend.ports.request_tracing import (
|
| 18 |
+
RequestTracingPort,
|
| 19 |
+
Trace,
|
| 20 |
+
TraceSpan,
|
| 21 |
+
TraceFilters,
|
| 22 |
+
TraceStatus,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class OpenTelemetryTracingAdapter(RequestTracingPort):
|
| 27 |
+
"""
|
| 28 |
+
OpenTelemetry-based request tracing implementation.
|
| 29 |
+
|
| 30 |
+
Integrates with OpenTelemetry SDK for distributed tracing.
|
| 31 |
+
Falls back to in-memory storage when OTEL is not available.
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
def __init__(
|
| 35 |
+
self,
|
| 36 |
+
service_name: str = "tensorwall",
|
| 37 |
+
otlp_endpoint: str | None = None,
|
| 38 |
+
jaeger_endpoint: str | None = None,
|
| 39 |
+
enable_console_export: bool = False,
|
| 40 |
+
):
|
| 41 |
+
"""
|
| 42 |
+
Initialize OpenTelemetry adapter.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
service_name: Service name for traces
|
| 46 |
+
otlp_endpoint: OTLP exporter endpoint
|
| 47 |
+
jaeger_endpoint: Jaeger exporter endpoint
|
| 48 |
+
enable_console_export: Enable console span exporter (for debugging)
|
| 49 |
+
"""
|
| 50 |
+
self._service_name = service_name
|
| 51 |
+
self._otlp_endpoint = otlp_endpoint
|
| 52 |
+
self._jaeger_endpoint = jaeger_endpoint
|
| 53 |
+
|
| 54 |
+
# In-memory storage
|
| 55 |
+
self._traces: dict[str, Trace] = {}
|
| 56 |
+
self._spans: dict[str, dict[str, TraceSpan]] = {} # trace_id -> {step: span}
|
| 57 |
+
|
| 58 |
+
# OpenTelemetry tracer
|
| 59 |
+
self._tracer = None
|
| 60 |
+
self._otel_spans: dict[str, Any] = {} # trace_id:step -> otel span
|
| 61 |
+
self._init_opentelemetry(enable_console_export)
|
| 62 |
+
|
| 63 |
+
def _init_opentelemetry(self, console_export: bool) -> None:
|
| 64 |
+
"""Initialize OpenTelemetry if available."""
|
| 65 |
+
try:
|
| 66 |
+
from opentelemetry import trace
|
| 67 |
+
from opentelemetry.sdk.trace import TracerProvider
|
| 68 |
+
from opentelemetry.sdk.resources import Resource
|
| 69 |
+
|
| 70 |
+
# Create resource
|
| 71 |
+
resource = Resource.create(
|
| 72 |
+
{
|
| 73 |
+
"service.name": self._service_name,
|
| 74 |
+
"service.version": "1.0.0",
|
| 75 |
+
}
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
# Create provider
|
| 79 |
+
provider = TracerProvider(resource=resource)
|
| 80 |
+
|
| 81 |
+
# Add exporters
|
| 82 |
+
if self._otlp_endpoint:
|
| 83 |
+
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import (
|
| 84 |
+
OTLPSpanExporter,
|
| 85 |
+
)
|
| 86 |
+
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
| 87 |
+
|
| 88 |
+
otlp_exporter = OTLPSpanExporter(endpoint=self._otlp_endpoint)
|
| 89 |
+
provider.add_span_processor(BatchSpanProcessor(otlp_exporter))
|
| 90 |
+
|
| 91 |
+
if self._jaeger_endpoint:
|
| 92 |
+
from opentelemetry.exporter.jaeger.thrift import JaegerExporter
|
| 93 |
+
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
| 94 |
+
|
| 95 |
+
jaeger_exporter = JaegerExporter(
|
| 96 |
+
agent_host_name=self._jaeger_endpoint.split(":")[0],
|
| 97 |
+
agent_port=(
|
| 98 |
+
int(self._jaeger_endpoint.split(":")[1])
|
| 99 |
+
if ":" in self._jaeger_endpoint
|
| 100 |
+
else 6831
|
| 101 |
+
),
|
| 102 |
+
)
|
| 103 |
+
provider.add_span_processor(BatchSpanProcessor(jaeger_exporter))
|
| 104 |
+
|
| 105 |
+
if console_export:
|
| 106 |
+
from opentelemetry.sdk.trace.export import (
|
| 107 |
+
ConsoleSpanExporter,
|
| 108 |
+
SimpleSpanProcessor,
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
|
| 112 |
+
|
| 113 |
+
# Set global provider
|
| 114 |
+
trace.set_tracer_provider(provider)
|
| 115 |
+
|
| 116 |
+
# Get tracer
|
| 117 |
+
self._tracer = trace.get_tracer(self._service_name)
|
| 118 |
+
|
| 119 |
+
except ImportError:
|
| 120 |
+
# OpenTelemetry not available
|
| 121 |
+
pass
|
| 122 |
+
|
| 123 |
+
async def create_trace(
|
| 124 |
+
self,
|
| 125 |
+
request_id: str,
|
| 126 |
+
app_id: str,
|
| 127 |
+
org_id: str | None = None,
|
| 128 |
+
model: str | None = None,
|
| 129 |
+
context: dict | None = None,
|
| 130 |
+
) -> Trace:
|
| 131 |
+
"""Create a new trace."""
|
| 132 |
+
trace_id = f"trace_{uuid.uuid4().hex[:16]}"
|
| 133 |
+
now = datetime.now()
|
| 134 |
+
|
| 135 |
+
trace = Trace(
|
| 136 |
+
trace_id=trace_id,
|
| 137 |
+
request_id=request_id,
|
| 138 |
+
app_id=app_id,
|
| 139 |
+
org_id=org_id,
|
| 140 |
+
model=model,
|
| 141 |
+
status=TraceStatus.STARTED,
|
| 142 |
+
started_at=now,
|
| 143 |
+
context=context or {},
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
self._traces[trace_id] = trace
|
| 147 |
+
self._spans[trace_id] = {}
|
| 148 |
+
|
| 149 |
+
# Start OpenTelemetry span if available
|
| 150 |
+
if self._tracer:
|
| 151 |
+
from opentelemetry.trace import SpanKind
|
| 152 |
+
|
| 153 |
+
otel_span = self._tracer.start_span(
|
| 154 |
+
"llm_request",
|
| 155 |
+
kind=SpanKind.SERVER,
|
| 156 |
+
)
|
| 157 |
+
otel_span.set_attribute("request.id", request_id)
|
| 158 |
+
otel_span.set_attribute("app.id", app_id)
|
| 159 |
+
if org_id:
|
| 160 |
+
otel_span.set_attribute("org.id", org_id)
|
| 161 |
+
if model:
|
| 162 |
+
otel_span.set_attribute("llm.model", model)
|
| 163 |
+
|
| 164 |
+
self._otel_spans[f"{trace_id}:root"] = otel_span
|
| 165 |
+
|
| 166 |
+
return trace
|
| 167 |
+
|
| 168 |
+
async def start_span(
|
| 169 |
+
self,
|
| 170 |
+
trace_id: str,
|
| 171 |
+
step: str,
|
| 172 |
+
data: dict | None = None,
|
| 173 |
+
) -> TraceSpan:
|
| 174 |
+
"""Start a span within a trace."""
|
| 175 |
+
if trace_id not in self._traces:
|
| 176 |
+
raise ValueError(f"Trace {trace_id} not found")
|
| 177 |
+
|
| 178 |
+
now = datetime.now()
|
| 179 |
+
span = TraceSpan(
|
| 180 |
+
step=step,
|
| 181 |
+
started_at=now,
|
| 182 |
+
data=data or {},
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
self._spans[trace_id][step] = span
|
| 186 |
+
|
| 187 |
+
# Update trace status
|
| 188 |
+
trace = self._traces[trace_id]
|
| 189 |
+
trace.status = TraceStatus.IN_PROGRESS
|
| 190 |
+
|
| 191 |
+
# Start OpenTelemetry span if available
|
| 192 |
+
if self._tracer:
|
| 193 |
+
parent_key = f"{trace_id}:root"
|
| 194 |
+
if parent_key in self._otel_spans:
|
| 195 |
+
from opentelemetry import context as otel_context
|
| 196 |
+
from opentelemetry.trace import set_span_in_context
|
| 197 |
+
|
| 198 |
+
parent_span = self._otel_spans[parent_key]
|
| 199 |
+
ctx = set_span_in_context(parent_span)
|
| 200 |
+
|
| 201 |
+
with otel_context.attach(ctx):
|
| 202 |
+
otel_span = self._tracer.start_span(step)
|
| 203 |
+
if data:
|
| 204 |
+
for key, value in data.items():
|
| 205 |
+
if isinstance(value, (str, int, float, bool)):
|
| 206 |
+
otel_span.set_attribute(f"data.{key}", value)
|
| 207 |
+
|
| 208 |
+
self._otel_spans[f"{trace_id}:{step}"] = otel_span
|
| 209 |
+
|
| 210 |
+
return span
|
| 211 |
+
|
| 212 |
+
async def end_span(
|
| 213 |
+
self,
|
| 214 |
+
trace_id: str,
|
| 215 |
+
step: str,
|
| 216 |
+
status: str = "ok",
|
| 217 |
+
data: dict | None = None,
|
| 218 |
+
error: str | None = None,
|
| 219 |
+
) -> TraceSpan:
|
| 220 |
+
"""End a span."""
|
| 221 |
+
if trace_id not in self._traces:
|
| 222 |
+
raise ValueError(f"Trace {trace_id} not found")
|
| 223 |
+
|
| 224 |
+
if step not in self._spans.get(trace_id, {}):
|
| 225 |
+
raise ValueError(f"Span {step} not found in trace {trace_id}")
|
| 226 |
+
|
| 227 |
+
span = self._spans[trace_id][step]
|
| 228 |
+
span.ended_at = datetime.now()
|
| 229 |
+
span.duration_ms = (span.ended_at - span.started_at).total_seconds() * 1000
|
| 230 |
+
span.status = status
|
| 231 |
+
span.error = error
|
| 232 |
+
if data:
|
| 233 |
+
span.data.update(data)
|
| 234 |
+
|
| 235 |
+
# End OpenTelemetry span if available
|
| 236 |
+
otel_key = f"{trace_id}:{step}"
|
| 237 |
+
if otel_key in self._otel_spans:
|
| 238 |
+
otel_span = self._otel_spans[otel_key]
|
| 239 |
+
if error:
|
| 240 |
+
from opentelemetry.trace import StatusCode
|
| 241 |
+
|
| 242 |
+
otel_span.set_status(StatusCode.ERROR, error)
|
| 243 |
+
if data:
|
| 244 |
+
for key, value in data.items():
|
| 245 |
+
if isinstance(value, (str, int, float, bool)):
|
| 246 |
+
otel_span.set_attribute(f"data.{key}", value)
|
| 247 |
+
otel_span.set_attribute("duration_ms", span.duration_ms)
|
| 248 |
+
otel_span.end()
|
| 249 |
+
|
| 250 |
+
return span
|
| 251 |
+
|
| 252 |
+
async def update_trace(
|
| 253 |
+
self,
|
| 254 |
+
trace_id: str,
|
| 255 |
+
step: str,
|
| 256 |
+
data: dict,
|
| 257 |
+
) -> Trace:
|
| 258 |
+
"""Update trace with additional data."""
|
| 259 |
+
if trace_id not in self._traces:
|
| 260 |
+
raise ValueError(f"Trace {trace_id} not found")
|
| 261 |
+
|
| 262 |
+
trace = self._traces[trace_id]
|
| 263 |
+
trace.context[step] = data
|
| 264 |
+
|
| 265 |
+
return trace
|
| 266 |
+
|
| 267 |
+
async def complete_trace(
|
| 268 |
+
self,
|
| 269 |
+
trace_id: str,
|
| 270 |
+
outcome: str,
|
| 271 |
+
final_data: dict | None = None,
|
| 272 |
+
) -> Trace:
|
| 273 |
+
"""Complete a trace successfully."""
|
| 274 |
+
if trace_id not in self._traces:
|
| 275 |
+
raise ValueError(f"Trace {trace_id} not found")
|
| 276 |
+
|
| 277 |
+
trace = self._traces[trace_id]
|
| 278 |
+
trace.ended_at = datetime.now()
|
| 279 |
+
trace.total_duration_ms = (
|
| 280 |
+
trace.ended_at - trace.started_at
|
| 281 |
+
).total_seconds() * 1000
|
| 282 |
+
trace.status = TraceStatus.COMPLETED
|
| 283 |
+
trace.outcome = outcome
|
| 284 |
+
if final_data:
|
| 285 |
+
trace.context.update(final_data)
|
| 286 |
+
|
| 287 |
+
# Add all spans to trace
|
| 288 |
+
trace.spans = list(self._spans.get(trace_id, {}).values())
|
| 289 |
+
|
| 290 |
+
# End root OpenTelemetry span
|
| 291 |
+
root_key = f"{trace_id}:root"
|
| 292 |
+
if root_key in self._otel_spans:
|
| 293 |
+
otel_span = self._otel_spans[root_key]
|
| 294 |
+
otel_span.set_attribute("outcome", outcome)
|
| 295 |
+
otel_span.set_attribute("duration_ms", trace.total_duration_ms)
|
| 296 |
+
otel_span.end()
|
| 297 |
+
|
| 298 |
+
return trace
|
| 299 |
+
|
| 300 |
+
async def fail_trace(
|
| 301 |
+
self,
|
| 302 |
+
trace_id: str,
|
| 303 |
+
error: str,
|
| 304 |
+
step: str | None = None,
|
| 305 |
+
outcome: str | None = None,
|
| 306 |
+
) -> Trace:
|
| 307 |
+
"""Mark a trace as failed."""
|
| 308 |
+
if trace_id not in self._traces:
|
| 309 |
+
raise ValueError(f"Trace {trace_id} not found")
|
| 310 |
+
|
| 311 |
+
trace = self._traces[trace_id]
|
| 312 |
+
trace.ended_at = datetime.now()
|
| 313 |
+
trace.total_duration_ms = (
|
| 314 |
+
trace.ended_at - trace.started_at
|
| 315 |
+
).total_seconds() * 1000
|
| 316 |
+
trace.status = TraceStatus.FAILED
|
| 317 |
+
trace.error = error
|
| 318 |
+
trace.outcome = outcome or "error"
|
| 319 |
+
if step:
|
| 320 |
+
trace.context["failed_step"] = step
|
| 321 |
+
|
| 322 |
+
# Add all spans to trace
|
| 323 |
+
trace.spans = list(self._spans.get(trace_id, {}).values())
|
| 324 |
+
|
| 325 |
+
# End root OpenTelemetry span with error
|
| 326 |
+
root_key = f"{trace_id}:root"
|
| 327 |
+
if root_key in self._otel_spans:
|
| 328 |
+
from opentelemetry.trace import StatusCode
|
| 329 |
+
|
| 330 |
+
otel_span = self._otel_spans[root_key]
|
| 331 |
+
otel_span.set_status(StatusCode.ERROR, error)
|
| 332 |
+
otel_span.set_attribute("error.message", error)
|
| 333 |
+
if step:
|
| 334 |
+
otel_span.set_attribute("error.step", step)
|
| 335 |
+
otel_span.end()
|
| 336 |
+
|
| 337 |
+
return trace
|
| 338 |
+
|
| 339 |
+
async def get_trace(
|
| 340 |
+
self,
|
| 341 |
+
trace_id: str,
|
| 342 |
+
) -> Trace | None:
|
| 343 |
+
"""Get a trace by ID."""
|
| 344 |
+
trace = self._traces.get(trace_id)
|
| 345 |
+
if trace and trace_id in self._spans:
|
| 346 |
+
trace.spans = list(self._spans[trace_id].values())
|
| 347 |
+
return trace
|
| 348 |
+
|
| 349 |
+
async def query_traces(
|
| 350 |
+
self,
|
| 351 |
+
filters: TraceFilters,
|
| 352 |
+
limit: int = 100,
|
| 353 |
+
offset: int = 0,
|
| 354 |
+
) -> list[Trace]:
|
| 355 |
+
"""Query traces with filters."""
|
| 356 |
+
results = list(self._traces.values())
|
| 357 |
+
|
| 358 |
+
# Apply filters
|
| 359 |
+
if filters.app_id:
|
| 360 |
+
results = [t for t in results if t.app_id == filters.app_id]
|
| 361 |
+
if filters.org_id:
|
| 362 |
+
results = [t for t in results if t.org_id == filters.org_id]
|
| 363 |
+
if filters.status:
|
| 364 |
+
results = [t for t in results if t.status == filters.status]
|
| 365 |
+
if filters.outcome:
|
| 366 |
+
results = [t for t in results if t.outcome == filters.outcome]
|
| 367 |
+
if filters.start_date:
|
| 368 |
+
results = [t for t in results if t.started_at >= filters.start_date]
|
| 369 |
+
if filters.end_date:
|
| 370 |
+
results = [t for t in results if t.started_at <= filters.end_date]
|
| 371 |
+
if filters.min_duration_ms is not None:
|
| 372 |
+
results = [
|
| 373 |
+
t
|
| 374 |
+
for t in results
|
| 375 |
+
if (t.total_duration_ms or 0) >= filters.min_duration_ms
|
| 376 |
+
]
|
| 377 |
+
if filters.max_duration_ms is not None:
|
| 378 |
+
results = [
|
| 379 |
+
t
|
| 380 |
+
for t in results
|
| 381 |
+
if (t.total_duration_ms or 0) <= filters.max_duration_ms
|
| 382 |
+
]
|
| 383 |
+
if filters.has_error is not None:
|
| 384 |
+
if filters.has_error:
|
| 385 |
+
results = [t for t in results if t.error is not None]
|
| 386 |
+
else:
|
| 387 |
+
results = [t for t in results if t.error is None]
|
| 388 |
+
|
| 389 |
+
# Sort by start time descending
|
| 390 |
+
results.sort(key=lambda t: t.started_at, reverse=True)
|
| 391 |
+
|
| 392 |
+
# Add spans to each trace
|
| 393 |
+
for trace in results:
|
| 394 |
+
if trace.trace_id in self._spans:
|
| 395 |
+
trace.spans = list(self._spans[trace.trace_id].values())
|
| 396 |
+
|
| 397 |
+
return results[offset : offset + limit]
|
| 398 |
+
|
| 399 |
+
async def get_trace_by_request_id(
|
| 400 |
+
self,
|
| 401 |
+
request_id: str,
|
| 402 |
+
) -> Trace | None:
|
| 403 |
+
"""Get a trace by request ID."""
|
| 404 |
+
for trace in self._traces.values():
|
| 405 |
+
if trace.request_id == request_id:
|
| 406 |
+
if trace.trace_id in self._spans:
|
| 407 |
+
trace.spans = list(self._spans[trace.trace_id].values())
|
| 408 |
+
return trace
|
| 409 |
+
return None
|
| 410 |
+
|
| 411 |
+
def clear(self) -> None:
|
| 412 |
+
"""Clear all stored data (for testing)."""
|
| 413 |
+
self._traces.clear()
|
| 414 |
+
self._spans.clear()
|
| 415 |
+
self._otel_spans.clear()
|
backend/adapters/tracing/postgres_adapter.py
ADDED
|
@@ -0,0 +1,471 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PostgreSQL Request Tracing Adapter.
|
| 2 |
+
|
| 3 |
+
Architecture Hexagonale: Implémentation du RequestTracingPort
|
| 4 |
+
qui persiste les traces dans la table llm_request_traces.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import uuid
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
|
| 10 |
+
from sqlalchemy import select
|
| 11 |
+
|
| 12 |
+
from backend.ports.request_tracing import (
|
| 13 |
+
RequestTracingPort,
|
| 14 |
+
Trace,
|
| 15 |
+
TraceSpan,
|
| 16 |
+
TraceFilters,
|
| 17 |
+
TraceStatus,
|
| 18 |
+
)
|
| 19 |
+
from backend.db.models import (
|
| 20 |
+
LLMRequestTrace,
|
| 21 |
+
TraceDecision,
|
| 22 |
+
TraceStatus as DBTraceStatus,
|
| 23 |
+
Environment,
|
| 24 |
+
)
|
| 25 |
+
from backend.db.session import get_db_context
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class PostgresRequestTracingAdapter(RequestTracingPort):
|
| 29 |
+
"""
|
| 30 |
+
PostgreSQL implementation of request tracing.
|
| 31 |
+
|
| 32 |
+
Persists all request traces to llm_request_traces table
|
| 33 |
+
for analytics and observability.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
def __init__(self):
|
| 37 |
+
# In-memory cache for active traces
|
| 38 |
+
self._active_traces: dict[str, dict] = {}
|
| 39 |
+
|
| 40 |
+
async def create_trace(
|
| 41 |
+
self,
|
| 42 |
+
request_id: str,
|
| 43 |
+
app_id: str,
|
| 44 |
+
org_id: str | None = None,
|
| 45 |
+
model: str | None = None,
|
| 46 |
+
context: dict | None = None,
|
| 47 |
+
) -> Trace:
|
| 48 |
+
"""Create a new trace."""
|
| 49 |
+
trace_id = str(uuid.uuid4())
|
| 50 |
+
now = datetime.utcnow()
|
| 51 |
+
|
| 52 |
+
trace = Trace(
|
| 53 |
+
trace_id=trace_id,
|
| 54 |
+
request_id=request_id,
|
| 55 |
+
app_id=app_id,
|
| 56 |
+
org_id=org_id,
|
| 57 |
+
model=model,
|
| 58 |
+
status=TraceStatus.STARTED,
|
| 59 |
+
started_at=now,
|
| 60 |
+
context=context or {},
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
# Store in memory for active updates
|
| 64 |
+
self._active_traces[trace_id] = {
|
| 65 |
+
"trace": trace,
|
| 66 |
+
"spans": {},
|
| 67 |
+
"input_tokens": 0,
|
| 68 |
+
"output_tokens": 0,
|
| 69 |
+
"cost_usd": 0.0,
|
| 70 |
+
"decision_reasons": [],
|
| 71 |
+
"risk_categories": [],
|
| 72 |
+
"policies_evaluated": [],
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
return trace
|
| 76 |
+
|
| 77 |
+
async def start_span(
|
| 78 |
+
self,
|
| 79 |
+
trace_id: str,
|
| 80 |
+
step: str,
|
| 81 |
+
data: dict | None = None,
|
| 82 |
+
) -> TraceSpan:
|
| 83 |
+
"""Start a span in a trace."""
|
| 84 |
+
span = TraceSpan(
|
| 85 |
+
step=step,
|
| 86 |
+
started_at=datetime.utcnow(),
|
| 87 |
+
data=data or {},
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
if trace_id in self._active_traces:
|
| 91 |
+
self._active_traces[trace_id]["spans"][step] = span
|
| 92 |
+
|
| 93 |
+
return span
|
| 94 |
+
|
| 95 |
+
async def end_span(
|
| 96 |
+
self,
|
| 97 |
+
trace_id: str,
|
| 98 |
+
step: str,
|
| 99 |
+
status: str = "ok",
|
| 100 |
+
data: dict | None = None,
|
| 101 |
+
error: str | None = None,
|
| 102 |
+
) -> TraceSpan:
|
| 103 |
+
"""End a span."""
|
| 104 |
+
now = datetime.utcnow()
|
| 105 |
+
|
| 106 |
+
if trace_id in self._active_traces:
|
| 107 |
+
spans = self._active_traces[trace_id]["spans"]
|
| 108 |
+
if step in spans:
|
| 109 |
+
span = spans[step]
|
| 110 |
+
span.ended_at = now
|
| 111 |
+
span.status = status
|
| 112 |
+
span.error = error
|
| 113 |
+
if span.started_at:
|
| 114 |
+
span.duration_ms = (now - span.started_at).total_seconds() * 1000
|
| 115 |
+
if data:
|
| 116 |
+
span.data.update(data)
|
| 117 |
+
|
| 118 |
+
# Track tokens from LLM response
|
| 119 |
+
if "input_tokens" in data:
|
| 120 |
+
self._active_traces[trace_id]["input_tokens"] = data[
|
| 121 |
+
"input_tokens"
|
| 122 |
+
]
|
| 123 |
+
if "output_tokens" in data:
|
| 124 |
+
self._active_traces[trace_id]["output_tokens"] = data[
|
| 125 |
+
"output_tokens"
|
| 126 |
+
]
|
| 127 |
+
|
| 128 |
+
return span
|
| 129 |
+
|
| 130 |
+
return TraceSpan(
|
| 131 |
+
step=step, started_at=now, ended_at=now, status=status, error=error
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
async def update_trace(
|
| 135 |
+
self,
|
| 136 |
+
trace_id: str,
|
| 137 |
+
step: str,
|
| 138 |
+
data: dict,
|
| 139 |
+
) -> Trace:
|
| 140 |
+
"""Update a trace with data."""
|
| 141 |
+
if trace_id in self._active_traces:
|
| 142 |
+
trace_data = self._active_traces[trace_id]
|
| 143 |
+
trace_data["trace"].context.update({step: data})
|
| 144 |
+
return trace_data["trace"]
|
| 145 |
+
|
| 146 |
+
return Trace(
|
| 147 |
+
trace_id=trace_id,
|
| 148 |
+
request_id="",
|
| 149 |
+
app_id="",
|
| 150 |
+
org_id=None,
|
| 151 |
+
model=None,
|
| 152 |
+
status=TraceStatus.IN_PROGRESS,
|
| 153 |
+
started_at=datetime.utcnow(),
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
async def complete_trace(
|
| 157 |
+
self,
|
| 158 |
+
trace_id: str,
|
| 159 |
+
outcome: str,
|
| 160 |
+
final_data: dict | None = None,
|
| 161 |
+
) -> Trace:
|
| 162 |
+
"""Complete a trace and persist to database."""
|
| 163 |
+
now = datetime.utcnow()
|
| 164 |
+
|
| 165 |
+
if trace_id not in self._active_traces:
|
| 166 |
+
return Trace(
|
| 167 |
+
trace_id=trace_id,
|
| 168 |
+
request_id="",
|
| 169 |
+
app_id="",
|
| 170 |
+
org_id=None,
|
| 171 |
+
model=None,
|
| 172 |
+
status=TraceStatus.COMPLETED,
|
| 173 |
+
started_at=now,
|
| 174 |
+
ended_at=now,
|
| 175 |
+
outcome=outcome,
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
trace_data = self._active_traces[trace_id]
|
| 179 |
+
trace = trace_data["trace"]
|
| 180 |
+
trace.ended_at = now
|
| 181 |
+
trace.status = TraceStatus.COMPLETED
|
| 182 |
+
trace.outcome = outcome
|
| 183 |
+
trace.total_duration_ms = (now - trace.started_at).total_seconds() * 1000
|
| 184 |
+
|
| 185 |
+
if final_data:
|
| 186 |
+
trace.context.update(final_data)
|
| 187 |
+
if "input_tokens" in final_data:
|
| 188 |
+
trace_data["input_tokens"] = final_data["input_tokens"]
|
| 189 |
+
if "output_tokens" in final_data:
|
| 190 |
+
trace_data["output_tokens"] = final_data["output_tokens"]
|
| 191 |
+
|
| 192 |
+
# Persist to database
|
| 193 |
+
await self._persist_trace(trace_data, outcome)
|
| 194 |
+
|
| 195 |
+
# Clean up
|
| 196 |
+
del self._active_traces[trace_id]
|
| 197 |
+
|
| 198 |
+
return trace
|
| 199 |
+
|
| 200 |
+
async def fail_trace(
|
| 201 |
+
self,
|
| 202 |
+
trace_id: str,
|
| 203 |
+
error: str,
|
| 204 |
+
step: str | None = None,
|
| 205 |
+
outcome: str | None = None,
|
| 206 |
+
) -> Trace:
|
| 207 |
+
"""Mark a trace as failed and persist to database."""
|
| 208 |
+
now = datetime.utcnow()
|
| 209 |
+
|
| 210 |
+
# Use provided outcome or default to "error"
|
| 211 |
+
final_outcome = outcome or "error"
|
| 212 |
+
|
| 213 |
+
if trace_id not in self._active_traces:
|
| 214 |
+
return Trace(
|
| 215 |
+
trace_id=trace_id,
|
| 216 |
+
request_id="",
|
| 217 |
+
app_id="",
|
| 218 |
+
org_id=None,
|
| 219 |
+
model=None,
|
| 220 |
+
status=TraceStatus.FAILED,
|
| 221 |
+
started_at=now,
|
| 222 |
+
ended_at=now,
|
| 223 |
+
error=error,
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
trace_data = self._active_traces[trace_id]
|
| 227 |
+
trace = trace_data["trace"]
|
| 228 |
+
trace.ended_at = now
|
| 229 |
+
trace.status = TraceStatus.FAILED
|
| 230 |
+
trace.outcome = final_outcome
|
| 231 |
+
trace.error = error
|
| 232 |
+
trace.total_duration_ms = (now - trace.started_at).total_seconds() * 1000
|
| 233 |
+
|
| 234 |
+
# Persist to database with correct outcome
|
| 235 |
+
await self._persist_trace(
|
| 236 |
+
trace_data, final_outcome, error=error, blocked_by=step
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
# Clean up
|
| 240 |
+
del self._active_traces[trace_id]
|
| 241 |
+
|
| 242 |
+
return trace
|
| 243 |
+
|
| 244 |
+
async def get_trace(
|
| 245 |
+
self,
|
| 246 |
+
trace_id: str,
|
| 247 |
+
) -> Trace | None:
|
| 248 |
+
"""Get a trace by ID."""
|
| 249 |
+
if trace_id in self._active_traces:
|
| 250 |
+
return self._active_traces[trace_id]["trace"]
|
| 251 |
+
|
| 252 |
+
async with get_db_context() as db:
|
| 253 |
+
stmt = select(LLMRequestTrace).where(LLMRequestTrace.trace_id == trace_id)
|
| 254 |
+
result = await db.execute(stmt)
|
| 255 |
+
db_trace = result.scalar_one_or_none()
|
| 256 |
+
|
| 257 |
+
if db_trace:
|
| 258 |
+
return self._db_trace_to_trace(db_trace)
|
| 259 |
+
|
| 260 |
+
return None
|
| 261 |
+
|
| 262 |
+
async def query_traces(
|
| 263 |
+
self,
|
| 264 |
+
filters: TraceFilters,
|
| 265 |
+
limit: int = 100,
|
| 266 |
+
offset: int = 0,
|
| 267 |
+
) -> list[Trace]:
|
| 268 |
+
"""Query traces with filters."""
|
| 269 |
+
async with get_db_context() as db:
|
| 270 |
+
stmt = select(LLMRequestTrace)
|
| 271 |
+
|
| 272 |
+
if filters.app_id:
|
| 273 |
+
stmt = stmt.where(LLMRequestTrace.app_id == filters.app_id)
|
| 274 |
+
if filters.org_id:
|
| 275 |
+
stmt = stmt.where(LLMRequestTrace.tenant_id == filters.org_id)
|
| 276 |
+
if filters.start_date:
|
| 277 |
+
stmt = stmt.where(LLMRequestTrace.timestamp_start >= filters.start_date)
|
| 278 |
+
if filters.end_date:
|
| 279 |
+
stmt = stmt.where(LLMRequestTrace.timestamp_start <= filters.end_date)
|
| 280 |
+
|
| 281 |
+
stmt = stmt.order_by(LLMRequestTrace.timestamp_start.desc())
|
| 282 |
+
stmt = stmt.limit(limit).offset(offset)
|
| 283 |
+
|
| 284 |
+
result = await db.execute(stmt)
|
| 285 |
+
db_traces = result.scalars().all()
|
| 286 |
+
|
| 287 |
+
return [self._db_trace_to_trace(t) for t in db_traces]
|
| 288 |
+
|
| 289 |
+
async def get_trace_by_request_id(
|
| 290 |
+
self,
|
| 291 |
+
request_id: str,
|
| 292 |
+
) -> Trace | None:
|
| 293 |
+
"""Get a trace by request_id."""
|
| 294 |
+
# Check active traces first
|
| 295 |
+
for trace_data in self._active_traces.values():
|
| 296 |
+
if trace_data["trace"].request_id == request_id:
|
| 297 |
+
return trace_data["trace"]
|
| 298 |
+
|
| 299 |
+
async with get_db_context() as db:
|
| 300 |
+
stmt = select(LLMRequestTrace).where(
|
| 301 |
+
LLMRequestTrace.request_id == request_id
|
| 302 |
+
)
|
| 303 |
+
result = await db.execute(stmt)
|
| 304 |
+
db_trace = result.scalar_one_or_none()
|
| 305 |
+
|
| 306 |
+
if db_trace:
|
| 307 |
+
return self._db_trace_to_trace(db_trace)
|
| 308 |
+
|
| 309 |
+
return None
|
| 310 |
+
|
| 311 |
+
async def _persist_trace(
|
| 312 |
+
self,
|
| 313 |
+
trace_data: dict,
|
| 314 |
+
outcome: str,
|
| 315 |
+
error: str | None = None,
|
| 316 |
+
blocked_by: str | None = None,
|
| 317 |
+
) -> None:
|
| 318 |
+
"""Persist trace to database."""
|
| 319 |
+
trace = trace_data["trace"]
|
| 320 |
+
|
| 321 |
+
# Map outcome to decision
|
| 322 |
+
if outcome == "allowed":
|
| 323 |
+
decision = TraceDecision.ALLOW
|
| 324 |
+
status = DBTraceStatus.SUCCESS
|
| 325 |
+
elif outcome == "warned":
|
| 326 |
+
decision = TraceDecision.WARN
|
| 327 |
+
status = DBTraceStatus.SUCCESS
|
| 328 |
+
elif outcome in (
|
| 329 |
+
"denied_policy",
|
| 330 |
+
"denied_budget",
|
| 331 |
+
"denied_abuse",
|
| 332 |
+
"denied_feature",
|
| 333 |
+
"denied_content",
|
| 334 |
+
"denied_risk",
|
| 335 |
+
):
|
| 336 |
+
decision = TraceDecision.BLOCK
|
| 337 |
+
status = (
|
| 338 |
+
DBTraceStatus.ERROR
|
| 339 |
+
) # Status is technical (error), decision captures policy outcome (block)
|
| 340 |
+
elif outcome == "dry_run":
|
| 341 |
+
decision = TraceDecision.ALLOW
|
| 342 |
+
status = DBTraceStatus.SUCCESS
|
| 343 |
+
else:
|
| 344 |
+
decision = TraceDecision.BLOCK
|
| 345 |
+
status = DBTraceStatus.ERROR
|
| 346 |
+
|
| 347 |
+
# Determine decision reasons
|
| 348 |
+
decision_reasons = trace_data.get("decision_reasons", [])
|
| 349 |
+
if blocked_by and blocked_by not in decision_reasons:
|
| 350 |
+
decision_reasons.append(blocked_by)
|
| 351 |
+
|
| 352 |
+
# Calculate latency
|
| 353 |
+
latency_ms = int(trace.total_duration_ms or 0)
|
| 354 |
+
|
| 355 |
+
# Get environment from context
|
| 356 |
+
env_str = trace.context.get("environment", "development")
|
| 357 |
+
try:
|
| 358 |
+
environment = Environment(env_str)
|
| 359 |
+
except ValueError:
|
| 360 |
+
environment = Environment.DEVELOPMENT
|
| 361 |
+
|
| 362 |
+
# Calculate cost estimate
|
| 363 |
+
input_tokens = trace_data.get("input_tokens", 0)
|
| 364 |
+
output_tokens = trace_data.get("output_tokens", 0)
|
| 365 |
+
cost_usd = self._estimate_cost(trace.model, input_tokens, output_tokens)
|
| 366 |
+
|
| 367 |
+
# Create database record
|
| 368 |
+
db_trace = LLMRequestTrace(
|
| 369 |
+
request_id=trace.request_id,
|
| 370 |
+
trace_id=trace.trace_id,
|
| 371 |
+
tenant_id=trace.org_id,
|
| 372 |
+
app_id=trace.app_id,
|
| 373 |
+
feature=trace.context.get("feature"),
|
| 374 |
+
environment=environment,
|
| 375 |
+
provider=self._get_provider_from_model(trace.model),
|
| 376 |
+
model=trace.model,
|
| 377 |
+
input_tokens=input_tokens,
|
| 378 |
+
output_tokens=output_tokens,
|
| 379 |
+
cost_usd=cost_usd,
|
| 380 |
+
decision=decision,
|
| 381 |
+
decision_reasons=decision_reasons,
|
| 382 |
+
risk_categories=trace_data.get("risk_categories", []),
|
| 383 |
+
policies_evaluated=trace_data.get("policies_evaluated", []),
|
| 384 |
+
estimated_cost_avoided=cost_usd if decision == TraceDecision.BLOCK else 0.0,
|
| 385 |
+
latency_ms=latency_ms,
|
| 386 |
+
status=status,
|
| 387 |
+
error_message=error,
|
| 388 |
+
timestamp_start=trace.started_at,
|
| 389 |
+
timestamp_end=trace.ended_at,
|
| 390 |
+
extra_metadata=trace.context,
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
async with get_db_context() as db:
|
| 394 |
+
db.add(db_trace)
|
| 395 |
+
await db.commit()
|
| 396 |
+
|
| 397 |
+
def _db_trace_to_trace(self, db_trace: LLMRequestTrace) -> Trace:
|
| 398 |
+
"""Convert database trace to domain trace."""
|
| 399 |
+
if db_trace.status == DBTraceStatus.SUCCESS:
|
| 400 |
+
status = TraceStatus.COMPLETED
|
| 401 |
+
elif db_trace.status == DBTraceStatus.ERROR:
|
| 402 |
+
status = TraceStatus.FAILED
|
| 403 |
+
elif db_trace.status == DBTraceStatus.BLOCKED:
|
| 404 |
+
status = TraceStatus.COMPLETED
|
| 405 |
+
else:
|
| 406 |
+
status = TraceStatus.IN_PROGRESS
|
| 407 |
+
|
| 408 |
+
return Trace(
|
| 409 |
+
trace_id=db_trace.trace_id or str(db_trace.id),
|
| 410 |
+
request_id=db_trace.request_id,
|
| 411 |
+
app_id=db_trace.app_id,
|
| 412 |
+
org_id=db_trace.tenant_id,
|
| 413 |
+
model=db_trace.model,
|
| 414 |
+
status=status,
|
| 415 |
+
started_at=db_trace.timestamp_start,
|
| 416 |
+
ended_at=db_trace.timestamp_end,
|
| 417 |
+
total_duration_ms=(
|
| 418 |
+
float(db_trace.latency_ms) if db_trace.latency_ms else None
|
| 419 |
+
),
|
| 420 |
+
outcome=(
|
| 421 |
+
"allowed" if db_trace.decision == TraceDecision.ALLOW else "blocked"
|
| 422 |
+
),
|
| 423 |
+
context=db_trace.extra_metadata or {},
|
| 424 |
+
error=db_trace.error_message,
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
def _estimate_cost(
|
| 428 |
+
self, model: str | None, input_tokens: int, output_tokens: int
|
| 429 |
+
) -> float:
|
| 430 |
+
"""Estimate cost based on model and tokens."""
|
| 431 |
+
if not model:
|
| 432 |
+
return 0.0
|
| 433 |
+
|
| 434 |
+
# Cost per 1K tokens (approximate)
|
| 435 |
+
model_lower = model.lower()
|
| 436 |
+
|
| 437 |
+
if "gpt-4" in model_lower:
|
| 438 |
+
input_cost = 0.03
|
| 439 |
+
output_cost = 0.06
|
| 440 |
+
elif "gpt-3.5" in model_lower:
|
| 441 |
+
input_cost = 0.0015
|
| 442 |
+
output_cost = 0.002
|
| 443 |
+
elif "claude" in model_lower:
|
| 444 |
+
input_cost = 0.015
|
| 445 |
+
output_cost = 0.075
|
| 446 |
+
else:
|
| 447 |
+
# Local models (ollama, lmstudio) - no cost
|
| 448 |
+
input_cost = 0.0
|
| 449 |
+
output_cost = 0.0
|
| 450 |
+
|
| 451 |
+
return (input_tokens / 1000 * input_cost) + (output_tokens / 1000 * output_cost)
|
| 452 |
+
|
| 453 |
+
def _get_provider_from_model(self, model: str | None) -> str | None:
|
| 454 |
+
"""Infer provider from model name."""
|
| 455 |
+
if not model:
|
| 456 |
+
return None
|
| 457 |
+
|
| 458 |
+
model_lower = model.lower()
|
| 459 |
+
|
| 460 |
+
if "gpt" in model_lower or "openai" in model_lower:
|
| 461 |
+
return "openai"
|
| 462 |
+
elif "claude" in model_lower or "anthropic" in model_lower:
|
| 463 |
+
return "anthropic"
|
| 464 |
+
elif (
|
| 465 |
+
"llama" in model_lower or "mistral" in model_lower or "qwen" in model_lower
|
| 466 |
+
):
|
| 467 |
+
return "ollama"
|
| 468 |
+
elif "phi" in model_lower or "local" in model_lower:
|
| 469 |
+
return "lmstudio"
|
| 470 |
+
|
| 471 |
+
return "unknown"
|
backend/alembic.ini
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[alembic]
|
| 2 |
+
script_location = backend/alembic
|
| 3 |
+
prepend_sys_path = .
|
| 4 |
+
|
| 5 |
+
# Database URL (overridden by env.py from settings)
|
| 6 |
+
sqlalchemy.url = postgresql://postgres:postgres@localhost:5432/tensorwall
|
| 7 |
+
|
| 8 |
+
[post_write_hooks]
|
| 9 |
+
|
| 10 |
+
[loggers]
|
| 11 |
+
keys = root,sqlalchemy,alembic
|
| 12 |
+
|
| 13 |
+
[handlers]
|
| 14 |
+
keys = console
|
| 15 |
+
|
| 16 |
+
[formatters]
|
| 17 |
+
keys = generic
|
| 18 |
+
|
| 19 |
+
[logger_root]
|
| 20 |
+
level = WARN
|
| 21 |
+
handlers = console
|
| 22 |
+
qualname =
|
| 23 |
+
|
| 24 |
+
[logger_sqlalchemy]
|
| 25 |
+
level = WARN
|
| 26 |
+
handlers =
|
| 27 |
+
qualname = sqlalchemy.engine
|
| 28 |
+
|
| 29 |
+
[logger_alembic]
|
| 30 |
+
level = INFO
|
| 31 |
+
handlers =
|
| 32 |
+
qualname = alembic
|
| 33 |
+
|
| 34 |
+
[handler_console]
|
| 35 |
+
class = StreamHandler
|
| 36 |
+
args = (sys.stderr,)
|
| 37 |
+
level = NOTSET
|
| 38 |
+
formatter = generic
|
| 39 |
+
|
| 40 |
+
[formatter_generic]
|
| 41 |
+
format = %(levelname)-5.5s [%(name)s] %(message)s
|
| 42 |
+
datefmt = %H:%M:%S
|
backend/alembic/env.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Alembic environment configuration for async SQLAlchemy."""
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
from logging.config import fileConfig
|
| 5 |
+
|
| 6 |
+
from sqlalchemy import pool
|
| 7 |
+
from sqlalchemy.engine import Connection
|
| 8 |
+
from sqlalchemy.ext.asyncio import async_engine_from_config
|
| 9 |
+
|
| 10 |
+
from alembic import context
|
| 11 |
+
|
| 12 |
+
# Import models to ensure they are registered with Base.metadata
|
| 13 |
+
from backend.db.models import Base
|
| 14 |
+
from backend.core.config import settings
|
| 15 |
+
|
| 16 |
+
# Alembic Config object
|
| 17 |
+
config = context.config
|
| 18 |
+
|
| 19 |
+
# Override sqlalchemy.url with our settings
|
| 20 |
+
config.set_main_option(
|
| 21 |
+
"sqlalchemy.url",
|
| 22 |
+
(
|
| 23 |
+
settings.database_url.replace("postgresql://", "postgresql+asyncpg://")
|
| 24 |
+
if settings.database_url.startswith("postgresql://")
|
| 25 |
+
else settings.database_url
|
| 26 |
+
),
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
# Interpret the config file for Python logging
|
| 30 |
+
if config.config_file_name is not None:
|
| 31 |
+
fileConfig(config.config_file_name)
|
| 32 |
+
|
| 33 |
+
# Model's MetaData object for autogenerate
|
| 34 |
+
target_metadata = Base.metadata
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def run_migrations_offline() -> None:
|
| 38 |
+
"""Run migrations in 'offline' mode.
|
| 39 |
+
|
| 40 |
+
This configures the context with just a URL and not an Engine,
|
| 41 |
+
though an Engine is acceptable here as well. By skipping the Engine
|
| 42 |
+
creation we don't even need a DBAPI to be available.
|
| 43 |
+
|
| 44 |
+
Calls to context.execute() here emit the given string to the
|
| 45 |
+
script output.
|
| 46 |
+
"""
|
| 47 |
+
url = config.get_main_option("sqlalchemy.url")
|
| 48 |
+
context.configure(
|
| 49 |
+
url=url,
|
| 50 |
+
target_metadata=target_metadata,
|
| 51 |
+
literal_binds=True,
|
| 52 |
+
dialect_opts={"paramstyle": "named"},
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
with context.begin_transaction():
|
| 56 |
+
context.run_migrations()
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def do_run_migrations(connection: Connection) -> None:
|
| 60 |
+
"""Run migrations with connection."""
|
| 61 |
+
context.configure(connection=connection, target_metadata=target_metadata)
|
| 62 |
+
|
| 63 |
+
with context.begin_transaction():
|
| 64 |
+
context.run_migrations()
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
async def run_async_migrations() -> None:
|
| 68 |
+
"""Run migrations in async mode."""
|
| 69 |
+
connectable = async_engine_from_config(
|
| 70 |
+
config.get_section(config.config_ini_section, {}),
|
| 71 |
+
prefix="sqlalchemy.",
|
| 72 |
+
poolclass=pool.NullPool,
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
async with connectable.connect() as connection:
|
| 76 |
+
await connection.run_sync(do_run_migrations)
|
| 77 |
+
|
| 78 |
+
await connectable.dispose()
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def run_migrations_online() -> None:
|
| 82 |
+
"""Run migrations in 'online' mode."""
|
| 83 |
+
asyncio.run(run_async_migrations())
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
if context.is_offline_mode():
|
| 87 |
+
run_migrations_offline()
|
| 88 |
+
else:
|
| 89 |
+
run_migrations_online()
|
backend/alembic/script.py.mako
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""${message}
|
| 2 |
+
|
| 3 |
+
Revision ID: ${up_revision}
|
| 4 |
+
Revises: ${down_revision | comma,n}
|
| 5 |
+
Create Date: ${create_date}
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
from typing import Sequence, Union
|
| 9 |
+
|
| 10 |
+
from alembic import op
|
| 11 |
+
import sqlalchemy as sa
|
| 12 |
+
${imports if imports else ""}
|
| 13 |
+
|
| 14 |
+
# revision identifiers, used by Alembic.
|
| 15 |
+
revision: str = ${repr(up_revision)}
|
| 16 |
+
down_revision: Union[str, None] = ${repr(down_revision)}
|
| 17 |
+
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
| 18 |
+
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def upgrade() -> None:
|
| 22 |
+
${upgrades if upgrades else "pass"}
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def downgrade() -> None:
|
| 26 |
+
${downgrades if downgrades else "pass"}
|
backend/alembic/versions/001_initial_schema.py
ADDED
|
@@ -0,0 +1,502 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Initial schema
|
| 2 |
+
|
| 3 |
+
Revision ID: 001_initial
|
| 4 |
+
Revises:
|
| 5 |
+
Create Date: 2024-12-29
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from typing import Sequence, Union
|
| 10 |
+
from alembic import op
|
| 11 |
+
import sqlalchemy as sa
|
| 12 |
+
from sqlalchemy.dialects import postgresql
|
| 13 |
+
|
| 14 |
+
# revision identifiers, used by Alembic.
|
| 15 |
+
revision: str = "001_initial"
|
| 16 |
+
down_revision: Union[str, None] = None
|
| 17 |
+
branch_labels: Union[str, Sequence[str], None] = None
|
| 18 |
+
depends_on: Union[str, Sequence[str], None] = None
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def upgrade() -> None:
|
| 22 |
+
# Create enum types
|
| 23 |
+
environment_enum = postgresql.ENUM(
|
| 24 |
+
"development", "staging", "production", name="environment", create_type=False
|
| 25 |
+
)
|
| 26 |
+
environment_enum.create(op.get_bind(), checkfirst=True)
|
| 27 |
+
|
| 28 |
+
budget_period_enum = postgresql.ENUM(
|
| 29 |
+
"hourly", "daily", "weekly", "monthly", name="budgetperiod", create_type=False
|
| 30 |
+
)
|
| 31 |
+
budget_period_enum.create(op.get_bind(), checkfirst=True)
|
| 32 |
+
|
| 33 |
+
budget_scope_enum = postgresql.ENUM(
|
| 34 |
+
"APPLICATION",
|
| 35 |
+
"USER",
|
| 36 |
+
"FEATURE",
|
| 37 |
+
"ORGANIZATION",
|
| 38 |
+
name="budgetscope",
|
| 39 |
+
create_type=False,
|
| 40 |
+
)
|
| 41 |
+
budget_scope_enum.create(op.get_bind(), checkfirst=True)
|
| 42 |
+
|
| 43 |
+
policy_action_enum = postgresql.ENUM(
|
| 44 |
+
"allow", "warn", "deny", name="policyaction", create_type=False
|
| 45 |
+
)
|
| 46 |
+
policy_action_enum.create(op.get_bind(), checkfirst=True)
|
| 47 |
+
|
| 48 |
+
rule_type_enum = postgresql.ENUM(
|
| 49 |
+
"model_restriction",
|
| 50 |
+
"environment_restriction",
|
| 51 |
+
"feature_restriction",
|
| 52 |
+
"token_limit",
|
| 53 |
+
"time_restriction",
|
| 54 |
+
"general",
|
| 55 |
+
name="ruletype",
|
| 56 |
+
create_type=False,
|
| 57 |
+
)
|
| 58 |
+
rule_type_enum.create(op.get_bind(), checkfirst=True)
|
| 59 |
+
|
| 60 |
+
audit_event_enum = postgresql.ENUM(
|
| 61 |
+
"request",
|
| 62 |
+
"response",
|
| 63 |
+
"policy_decision",
|
| 64 |
+
"budget_check",
|
| 65 |
+
"security_check",
|
| 66 |
+
"error",
|
| 67 |
+
name="auditeventtype",
|
| 68 |
+
create_type=False,
|
| 69 |
+
)
|
| 70 |
+
audit_event_enum.create(op.get_bind(), checkfirst=True)
|
| 71 |
+
|
| 72 |
+
trace_decision_enum = postgresql.ENUM(
|
| 73 |
+
"allow", "warn", "block", "degrade", name="tracedecision", create_type=False
|
| 74 |
+
)
|
| 75 |
+
trace_decision_enum.create(op.get_bind(), checkfirst=True)
|
| 76 |
+
|
| 77 |
+
trace_status_enum = postgresql.ENUM(
|
| 78 |
+
"pending",
|
| 79 |
+
"success",
|
| 80 |
+
"blocked",
|
| 81 |
+
"error",
|
| 82 |
+
"timeout",
|
| 83 |
+
name="tracestatus",
|
| 84 |
+
create_type=False,
|
| 85 |
+
)
|
| 86 |
+
trace_status_enum.create(op.get_bind(), checkfirst=True)
|
| 87 |
+
|
| 88 |
+
tenant_status_enum = postgresql.ENUM(
|
| 89 |
+
"ACTIVE", "SUSPENDED", "DELETED", name="tenantstatus", create_type=False
|
| 90 |
+
)
|
| 91 |
+
tenant_status_enum.create(op.get_bind(), checkfirst=True)
|
| 92 |
+
|
| 93 |
+
tenant_tier_enum = postgresql.ENUM(
|
| 94 |
+
"FREE",
|
| 95 |
+
"STARTER",
|
| 96 |
+
"PROFESSIONAL",
|
| 97 |
+
"ENTERPRISE",
|
| 98 |
+
name="tenanttier",
|
| 99 |
+
create_type=False,
|
| 100 |
+
)
|
| 101 |
+
tenant_tier_enum.create(op.get_bind(), checkfirst=True)
|
| 102 |
+
|
| 103 |
+
# Users table
|
| 104 |
+
op.create_table(
|
| 105 |
+
"users",
|
| 106 |
+
sa.Column("id", sa.Integer(), nullable=False),
|
| 107 |
+
sa.Column("uuid", postgresql.UUID(as_uuid=True), nullable=False),
|
| 108 |
+
sa.Column("email", sa.String(length=255), nullable=False),
|
| 109 |
+
sa.Column("password_hash", sa.String(length=255), nullable=False),
|
| 110 |
+
sa.Column("name", sa.String(length=255), nullable=True),
|
| 111 |
+
sa.Column("role", sa.String(length=50), nullable=False, server_default="user"),
|
| 112 |
+
sa.Column("permissions", sa.JSON(), nullable=True),
|
| 113 |
+
sa.Column("is_active", sa.Boolean(), nullable=False, server_default="true"),
|
| 114 |
+
sa.Column("created_at", sa.DateTime(), nullable=False),
|
| 115 |
+
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
| 116 |
+
sa.PrimaryKeyConstraint("id"),
|
| 117 |
+
sa.UniqueConstraint("email"),
|
| 118 |
+
sa.UniqueConstraint("uuid"),
|
| 119 |
+
)
|
| 120 |
+
op.create_index("ix_users_email", "users", ["email"], unique=True)
|
| 121 |
+
|
| 122 |
+
# Organizations table
|
| 123 |
+
op.create_table(
|
| 124 |
+
"organizations",
|
| 125 |
+
sa.Column("id", sa.Integer(), nullable=False),
|
| 126 |
+
sa.Column("org_id", sa.String(length=100), nullable=False),
|
| 127 |
+
sa.Column("name", sa.String(length=255), nullable=False),
|
| 128 |
+
sa.Column("slug", sa.String(length=100), nullable=False),
|
| 129 |
+
sa.Column(
|
| 130 |
+
"status",
|
| 131 |
+
sa.Enum("ACTIVE", "SUSPENDED", "DELETED", name="tenantstatus"),
|
| 132 |
+
nullable=False,
|
| 133 |
+
server_default="ACTIVE",
|
| 134 |
+
),
|
| 135 |
+
sa.Column(
|
| 136 |
+
"tier",
|
| 137 |
+
sa.Enum("FREE", "STARTER", "PROFESSIONAL", "ENTERPRISE", name="tenanttier"),
|
| 138 |
+
nullable=False,
|
| 139 |
+
server_default="FREE",
|
| 140 |
+
),
|
| 141 |
+
sa.Column("owner_email", sa.String(length=255), nullable=True),
|
| 142 |
+
sa.Column("billing_email", sa.String(length=255), nullable=True),
|
| 143 |
+
sa.Column("technical_contact", sa.String(length=255), nullable=True),
|
| 144 |
+
sa.Column("max_applications", sa.Integer(), nullable=False, server_default="5"),
|
| 145 |
+
sa.Column("max_users", sa.Integer(), nullable=False, server_default="10"),
|
| 146 |
+
sa.Column("max_api_keys", sa.Integer(), nullable=False, server_default="20"),
|
| 147 |
+
sa.Column("max_environments", sa.Integer(), nullable=False, server_default="2"),
|
| 148 |
+
sa.Column("custom_domain", sa.String(length=255), nullable=True),
|
| 149 |
+
sa.Column("sso_enabled", sa.Boolean(), nullable=False, server_default="false"),
|
| 150 |
+
sa.Column(
|
| 151 |
+
"audit_retention_days", sa.Integer(), nullable=False, server_default="30"
|
| 152 |
+
),
|
| 153 |
+
sa.Column("created_at", sa.DateTime(), nullable=False),
|
| 154 |
+
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
| 155 |
+
sa.PrimaryKeyConstraint("id"),
|
| 156 |
+
sa.UniqueConstraint("org_id"),
|
| 157 |
+
sa.UniqueConstraint("slug"),
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
# Applications table
|
| 161 |
+
op.create_table(
|
| 162 |
+
"applications",
|
| 163 |
+
sa.Column("id", sa.Integer(), nullable=False),
|
| 164 |
+
sa.Column("uuid", postgresql.UUID(as_uuid=True), nullable=False),
|
| 165 |
+
sa.Column("app_id", sa.String(length=100), nullable=False),
|
| 166 |
+
sa.Column("name", sa.String(length=255), nullable=False),
|
| 167 |
+
sa.Column("owner", sa.String(length=255), nullable=False),
|
| 168 |
+
sa.Column("description", sa.Text(), nullable=True),
|
| 169 |
+
sa.Column("is_active", sa.Boolean(), nullable=False, server_default="true"),
|
| 170 |
+
sa.Column("allowed_providers", sa.JSON(), nullable=True),
|
| 171 |
+
sa.Column("allowed_models", sa.JSON(), nullable=True),
|
| 172 |
+
sa.Column("created_at", sa.DateTime(), nullable=False),
|
| 173 |
+
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
| 174 |
+
sa.PrimaryKeyConstraint("id"),
|
| 175 |
+
sa.UniqueConstraint("app_id"),
|
| 176 |
+
sa.UniqueConstraint("uuid"),
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
# API Keys table
|
| 180 |
+
op.create_table(
|
| 181 |
+
"api_keys",
|
| 182 |
+
sa.Column("id", sa.Integer(), nullable=False),
|
| 183 |
+
sa.Column("key_hash", sa.String(length=255), nullable=False),
|
| 184 |
+
sa.Column("key_prefix", sa.String(length=20), nullable=False),
|
| 185 |
+
sa.Column("name", sa.String(length=255), nullable=False),
|
| 186 |
+
sa.Column("application_id", sa.Integer(), nullable=False),
|
| 187 |
+
sa.Column(
|
| 188 |
+
"environment",
|
| 189 |
+
sa.Enum("development", "staging", "production", name="environment"),
|
| 190 |
+
nullable=False,
|
| 191 |
+
server_default="development",
|
| 192 |
+
),
|
| 193 |
+
sa.Column("llm_api_key_encrypted", sa.Text(), nullable=True),
|
| 194 |
+
sa.Column("is_active", sa.Boolean(), nullable=False, server_default="true"),
|
| 195 |
+
sa.Column("last_used_at", sa.DateTime(), nullable=True),
|
| 196 |
+
sa.Column("expires_at", sa.DateTime(), nullable=True),
|
| 197 |
+
sa.Column("created_at", sa.DateTime(), nullable=False),
|
| 198 |
+
sa.ForeignKeyConstraint(
|
| 199 |
+
["application_id"], ["applications.id"], ondelete="CASCADE"
|
| 200 |
+
),
|
| 201 |
+
sa.PrimaryKeyConstraint("id"),
|
| 202 |
+
sa.UniqueConstraint("key_hash"),
|
| 203 |
+
)
|
| 204 |
+
op.create_index("ix_api_keys_key_hash", "api_keys", ["key_hash"], unique=True)
|
| 205 |
+
op.create_index("ix_api_keys_key_prefix", "api_keys", ["key_prefix"], unique=False)
|
| 206 |
+
|
| 207 |
+
# Policy Rules table
|
| 208 |
+
op.create_table(
|
| 209 |
+
"policy_rules",
|
| 210 |
+
sa.Column("id", sa.Integer(), nullable=False),
|
| 211 |
+
sa.Column("uuid", postgresql.UUID(as_uuid=True), nullable=False),
|
| 212 |
+
sa.Column("name", sa.String(length=255), nullable=False),
|
| 213 |
+
sa.Column("description", sa.Text(), nullable=True),
|
| 214 |
+
sa.Column(
|
| 215 |
+
"rule_type",
|
| 216 |
+
sa.Enum(
|
| 217 |
+
"model_restriction",
|
| 218 |
+
"environment_restriction",
|
| 219 |
+
"feature_restriction",
|
| 220 |
+
"token_limit",
|
| 221 |
+
"time_restriction",
|
| 222 |
+
"general",
|
| 223 |
+
name="ruletype",
|
| 224 |
+
),
|
| 225 |
+
nullable=False,
|
| 226 |
+
),
|
| 227 |
+
sa.Column(
|
| 228 |
+
"action",
|
| 229 |
+
sa.Enum("allow", "warn", "deny", name="policyaction"),
|
| 230 |
+
nullable=False,
|
| 231 |
+
),
|
| 232 |
+
sa.Column("priority", sa.Integer(), nullable=False, server_default="100"),
|
| 233 |
+
sa.Column("conditions", sa.JSON(), nullable=True),
|
| 234 |
+
sa.Column("app_id", sa.String(length=100), nullable=True),
|
| 235 |
+
sa.Column("user_email", sa.String(length=255), nullable=True),
|
| 236 |
+
sa.Column("model_pattern", sa.String(length=255), nullable=True),
|
| 237 |
+
sa.Column("environment", sa.String(length=50), nullable=True),
|
| 238 |
+
sa.Column("feature", sa.String(length=100), nullable=True),
|
| 239 |
+
sa.Column("max_tokens", sa.Integer(), nullable=True),
|
| 240 |
+
sa.Column("is_enabled", sa.Boolean(), nullable=False, server_default="true"),
|
| 241 |
+
sa.Column("created_at", sa.DateTime(), nullable=False),
|
| 242 |
+
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
| 243 |
+
sa.PrimaryKeyConstraint("id"),
|
| 244 |
+
sa.UniqueConstraint("uuid"),
|
| 245 |
+
)
|
| 246 |
+
op.create_index("ix_policy_rules_app_id", "policy_rules", ["app_id"], unique=False)
|
| 247 |
+
op.create_index(
|
| 248 |
+
"ix_policy_rules_user_email", "policy_rules", ["user_email"], unique=False
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
# Budgets table
|
| 252 |
+
op.create_table(
|
| 253 |
+
"budgets",
|
| 254 |
+
sa.Column("id", sa.Integer(), nullable=False),
|
| 255 |
+
sa.Column("uuid", postgresql.UUID(as_uuid=True), nullable=False),
|
| 256 |
+
sa.Column(
|
| 257 |
+
"scope",
|
| 258 |
+
sa.Enum(
|
| 259 |
+
"APPLICATION", "USER", "FEATURE", "ORGANIZATION", name="budgetscope"
|
| 260 |
+
),
|
| 261 |
+
nullable=False,
|
| 262 |
+
),
|
| 263 |
+
sa.Column("application_id", sa.Integer(), nullable=True),
|
| 264 |
+
sa.Column("user_id", sa.Integer(), nullable=True),
|
| 265 |
+
sa.Column("user_email", sa.String(length=255), nullable=True),
|
| 266 |
+
sa.Column("org_id", sa.String(length=100), nullable=True),
|
| 267 |
+
sa.Column("feature", sa.String(length=100), nullable=True),
|
| 268 |
+
sa.Column(
|
| 269 |
+
"environment",
|
| 270 |
+
sa.Enum("development", "staging", "production", name="environment"),
|
| 271 |
+
nullable=True,
|
| 272 |
+
),
|
| 273 |
+
sa.Column("soft_limit_usd", sa.Float(), nullable=False),
|
| 274 |
+
sa.Column("hard_limit_usd", sa.Float(), nullable=False),
|
| 275 |
+
sa.Column(
|
| 276 |
+
"period",
|
| 277 |
+
sa.Enum("hourly", "daily", "weekly", "monthly", name="budgetperiod"),
|
| 278 |
+
nullable=False,
|
| 279 |
+
server_default="monthly",
|
| 280 |
+
),
|
| 281 |
+
sa.Column(
|
| 282 |
+
"current_spend_usd", sa.Float(), nullable=False, server_default="0.0"
|
| 283 |
+
),
|
| 284 |
+
sa.Column("period_start", sa.DateTime(), nullable=False),
|
| 285 |
+
sa.Column("is_active", sa.Boolean(), nullable=False, server_default="true"),
|
| 286 |
+
sa.Column("created_at", sa.DateTime(), nullable=False),
|
| 287 |
+
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
| 288 |
+
sa.ForeignKeyConstraint(
|
| 289 |
+
["application_id"], ["applications.id"], ondelete="CASCADE"
|
| 290 |
+
),
|
| 291 |
+
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
|
| 292 |
+
sa.PrimaryKeyConstraint("id"),
|
| 293 |
+
sa.UniqueConstraint("uuid"),
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
# Audit Logs table
|
| 297 |
+
op.create_table(
|
| 298 |
+
"audit_logs",
|
| 299 |
+
sa.Column("id", sa.Integer(), nullable=False),
|
| 300 |
+
sa.Column("uuid", postgresql.UUID(as_uuid=True), nullable=False),
|
| 301 |
+
sa.Column(
|
| 302 |
+
"event_type",
|
| 303 |
+
sa.Enum(
|
| 304 |
+
"request",
|
| 305 |
+
"response",
|
| 306 |
+
"policy_decision",
|
| 307 |
+
"budget_check",
|
| 308 |
+
"security_check",
|
| 309 |
+
"error",
|
| 310 |
+
name="auditeventtype",
|
| 311 |
+
),
|
| 312 |
+
nullable=False,
|
| 313 |
+
),
|
| 314 |
+
sa.Column("app_id", sa.String(length=100), nullable=True),
|
| 315 |
+
sa.Column("user_email", sa.String(length=255), nullable=True),
|
| 316 |
+
sa.Column("model", sa.String(length=100), nullable=True),
|
| 317 |
+
sa.Column("provider", sa.String(length=50), nullable=True),
|
| 318 |
+
sa.Column("request_id", sa.String(length=100), nullable=True),
|
| 319 |
+
sa.Column("event_data", sa.JSON(), nullable=True),
|
| 320 |
+
sa.Column("created_at", sa.DateTime(), nullable=False),
|
| 321 |
+
sa.PrimaryKeyConstraint("id"),
|
| 322 |
+
sa.UniqueConstraint("uuid"),
|
| 323 |
+
)
|
| 324 |
+
op.create_index("ix_audit_logs_app_id", "audit_logs", ["app_id"], unique=False)
|
| 325 |
+
op.create_index(
|
| 326 |
+
"ix_audit_logs_created_at", "audit_logs", ["created_at"], unique=False
|
| 327 |
+
)
|
| 328 |
+
op.create_index(
|
| 329 |
+
"ix_audit_logs_request_id", "audit_logs", ["request_id"], unique=False
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
# Usage Records table
|
| 333 |
+
op.create_table(
|
| 334 |
+
"usage_records",
|
| 335 |
+
sa.Column("id", sa.Integer(), nullable=False),
|
| 336 |
+
sa.Column("uuid", postgresql.UUID(as_uuid=True), nullable=False),
|
| 337 |
+
sa.Column("application_id", sa.Integer(), nullable=True),
|
| 338 |
+
sa.Column("app_id", sa.String(length=100), nullable=True),
|
| 339 |
+
sa.Column("user_email", sa.String(length=255), nullable=True),
|
| 340 |
+
sa.Column("model", sa.String(length=100), nullable=False),
|
| 341 |
+
sa.Column("provider", sa.String(length=50), nullable=True),
|
| 342 |
+
sa.Column("feature", sa.String(length=100), nullable=True),
|
| 343 |
+
sa.Column("environment", sa.String(length=50), nullable=True),
|
| 344 |
+
sa.Column("input_tokens", sa.Integer(), nullable=False, server_default="0"),
|
| 345 |
+
sa.Column("output_tokens", sa.Integer(), nullable=False, server_default="0"),
|
| 346 |
+
sa.Column("total_tokens", sa.Integer(), nullable=False, server_default="0"),
|
| 347 |
+
sa.Column("cost_usd", sa.Float(), nullable=False, server_default="0.0"),
|
| 348 |
+
sa.Column("latency_ms", sa.Float(), nullable=True),
|
| 349 |
+
sa.Column("request_id", sa.String(length=100), nullable=True),
|
| 350 |
+
sa.Column("created_at", sa.DateTime(), nullable=False),
|
| 351 |
+
sa.ForeignKeyConstraint(
|
| 352 |
+
["application_id"], ["applications.id"], ondelete="SET NULL"
|
| 353 |
+
),
|
| 354 |
+
sa.PrimaryKeyConstraint("id"),
|
| 355 |
+
sa.UniqueConstraint("uuid"),
|
| 356 |
+
)
|
| 357 |
+
op.create_index(
|
| 358 |
+
"ix_usage_records_app_id", "usage_records", ["app_id"], unique=False
|
| 359 |
+
)
|
| 360 |
+
op.create_index(
|
| 361 |
+
"ix_usage_records_created_at", "usage_records", ["created_at"], unique=False
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
# Request Traces table
|
| 365 |
+
op.create_table(
|
| 366 |
+
"request_traces",
|
| 367 |
+
sa.Column("id", sa.Integer(), nullable=False),
|
| 368 |
+
sa.Column("request_id", sa.String(length=100), nullable=False),
|
| 369 |
+
sa.Column("app_id", sa.String(length=100), nullable=True),
|
| 370 |
+
sa.Column("org_id", sa.String(length=100), nullable=True),
|
| 371 |
+
sa.Column("user_email", sa.String(length=255), nullable=True),
|
| 372 |
+
sa.Column("model", sa.String(length=100), nullable=True),
|
| 373 |
+
sa.Column("provider", sa.String(length=50), nullable=True),
|
| 374 |
+
sa.Column("feature", sa.String(length=100), nullable=True),
|
| 375 |
+
sa.Column("environment", sa.String(length=50), nullable=True),
|
| 376 |
+
sa.Column(
|
| 377 |
+
"decision",
|
| 378 |
+
sa.Enum("allow", "warn", "block", "degrade", name="tracedecision"),
|
| 379 |
+
nullable=False,
|
| 380 |
+
),
|
| 381 |
+
sa.Column(
|
| 382 |
+
"status",
|
| 383 |
+
sa.Enum(
|
| 384 |
+
"pending", "success", "blocked", "error", "timeout", name="tracestatus"
|
| 385 |
+
),
|
| 386 |
+
nullable=False,
|
| 387 |
+
),
|
| 388 |
+
sa.Column("input_tokens", sa.Integer(), nullable=True),
|
| 389 |
+
sa.Column("output_tokens", sa.Integer(), nullable=True),
|
| 390 |
+
sa.Column("total_tokens", sa.Integer(), nullable=True),
|
| 391 |
+
sa.Column("cost_usd", sa.Float(), nullable=True),
|
| 392 |
+
sa.Column("latency_ms", sa.Float(), nullable=True),
|
| 393 |
+
sa.Column("gateway_latency_ms", sa.Float(), nullable=True),
|
| 394 |
+
sa.Column("policy_violations", sa.JSON(), nullable=True),
|
| 395 |
+
sa.Column("error_message", sa.Text(), nullable=True),
|
| 396 |
+
sa.Column("prompt_preview", sa.Text(), nullable=True),
|
| 397 |
+
sa.Column("response_preview", sa.Text(), nullable=True),
|
| 398 |
+
sa.Column("metadata", sa.JSON(), nullable=True),
|
| 399 |
+
sa.Column("created_at", sa.DateTime(), nullable=False),
|
| 400 |
+
sa.PrimaryKeyConstraint("id"),
|
| 401 |
+
sa.UniqueConstraint("request_id"),
|
| 402 |
+
)
|
| 403 |
+
op.create_index(
|
| 404 |
+
"ix_request_traces_app_id", "request_traces", ["app_id"], unique=False
|
| 405 |
+
)
|
| 406 |
+
op.create_index(
|
| 407 |
+
"ix_request_traces_created_at", "request_traces", ["created_at"], unique=False
|
| 408 |
+
)
|
| 409 |
+
op.create_index(
|
| 410 |
+
"ix_request_traces_decision", "request_traces", ["decision"], unique=False
|
| 411 |
+
)
|
| 412 |
+
op.create_index(
|
| 413 |
+
"ix_request_traces_model", "request_traces", ["model"], unique=False
|
| 414 |
+
)
|
| 415 |
+
op.create_index(
|
| 416 |
+
"ix_request_traces_status", "request_traces", ["status"], unique=False
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
# Model Registry table
|
| 420 |
+
op.create_table(
|
| 421 |
+
"model_registry",
|
| 422 |
+
sa.Column("id", sa.Integer(), nullable=False),
|
| 423 |
+
sa.Column("model_id", sa.String(length=255), nullable=False),
|
| 424 |
+
sa.Column("provider", sa.String(length=50), nullable=False),
|
| 425 |
+
sa.Column("display_name", sa.String(length=255), nullable=True),
|
| 426 |
+
sa.Column("description", sa.Text(), nullable=True),
|
| 427 |
+
sa.Column("context_window", sa.Integer(), nullable=True),
|
| 428 |
+
sa.Column("max_output_tokens", sa.Integer(), nullable=True),
|
| 429 |
+
sa.Column("input_cost_per_1k", sa.Float(), nullable=True),
|
| 430 |
+
sa.Column("output_cost_per_1k", sa.Float(), nullable=True),
|
| 431 |
+
sa.Column(
|
| 432 |
+
"supports_streaming", sa.Boolean(), nullable=False, server_default="true"
|
| 433 |
+
),
|
| 434 |
+
sa.Column(
|
| 435 |
+
"supports_functions", sa.Boolean(), nullable=False, server_default="false"
|
| 436 |
+
),
|
| 437 |
+
sa.Column(
|
| 438 |
+
"supports_vision", sa.Boolean(), nullable=False, server_default="false"
|
| 439 |
+
),
|
| 440 |
+
sa.Column("is_available", sa.Boolean(), nullable=False, server_default="true"),
|
| 441 |
+
sa.Column("created_at", sa.DateTime(), nullable=False),
|
| 442 |
+
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
| 443 |
+
sa.PrimaryKeyConstraint("id"),
|
| 444 |
+
sa.UniqueConstraint("model_id"),
|
| 445 |
+
)
|
| 446 |
+
|
| 447 |
+
# Features table
|
| 448 |
+
op.create_table(
|
| 449 |
+
"features",
|
| 450 |
+
sa.Column("id", sa.Integer(), nullable=False),
|
| 451 |
+
sa.Column("application_id", sa.Integer(), nullable=False),
|
| 452 |
+
sa.Column("name", sa.String(length=100), nullable=False),
|
| 453 |
+
sa.Column("description", sa.Text(), nullable=True),
|
| 454 |
+
sa.Column("is_active", sa.Boolean(), nullable=False, server_default="true"),
|
| 455 |
+
sa.Column("created_at", sa.DateTime(), nullable=False),
|
| 456 |
+
sa.ForeignKeyConstraint(
|
| 457 |
+
["application_id"], ["applications.id"], ondelete="CASCADE"
|
| 458 |
+
),
|
| 459 |
+
sa.PrimaryKeyConstraint("id"),
|
| 460 |
+
)
|
| 461 |
+
op.create_index(
|
| 462 |
+
"ix_features_app_feature", "features", ["application_id", "name"], unique=True
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
# Setup State table
|
| 466 |
+
op.create_table(
|
| 467 |
+
"setup_state",
|
| 468 |
+
sa.Column("id", sa.Integer(), nullable=False),
|
| 469 |
+
sa.Column("key", sa.String(length=100), nullable=False),
|
| 470 |
+
sa.Column("value", sa.Text(), nullable=True),
|
| 471 |
+
sa.Column("created_at", sa.DateTime(), nullable=False),
|
| 472 |
+
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
| 473 |
+
sa.PrimaryKeyConstraint("id"),
|
| 474 |
+
sa.UniqueConstraint("key"),
|
| 475 |
+
)
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
def downgrade() -> None:
|
| 479 |
+
op.drop_table("setup_state")
|
| 480 |
+
op.drop_table("features")
|
| 481 |
+
op.drop_table("model_registry")
|
| 482 |
+
op.drop_table("request_traces")
|
| 483 |
+
op.drop_table("usage_records")
|
| 484 |
+
op.drop_table("audit_logs")
|
| 485 |
+
op.drop_table("budgets")
|
| 486 |
+
op.drop_table("policy_rules")
|
| 487 |
+
op.drop_table("api_keys")
|
| 488 |
+
op.drop_table("applications")
|
| 489 |
+
op.drop_table("organizations")
|
| 490 |
+
op.drop_table("users")
|
| 491 |
+
|
| 492 |
+
# Drop enum types
|
| 493 |
+
op.execute("DROP TYPE IF EXISTS tenanttier")
|
| 494 |
+
op.execute("DROP TYPE IF EXISTS tenantstatus")
|
| 495 |
+
op.execute("DROP TYPE IF EXISTS tracestatus")
|
| 496 |
+
op.execute("DROP TYPE IF EXISTS tracedecision")
|
| 497 |
+
op.execute("DROP TYPE IF EXISTS auditeventtype")
|
| 498 |
+
op.execute("DROP TYPE IF EXISTS ruletype")
|
| 499 |
+
op.execute("DROP TYPE IF EXISTS policyaction")
|
| 500 |
+
op.execute("DROP TYPE IF EXISTS budgetscope")
|
| 501 |
+
op.execute("DROP TYPE IF EXISTS budgetperiod")
|
| 502 |
+
op.execute("DROP TYPE IF EXISTS environment")
|
backend/api/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from backend.api import health
|
| 2 |
+
|
| 3 |
+
__all__ = ["health"]
|
backend/api/admin/__init__.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Admin API endpoints for TensorWall."""
|
| 2 |
+
|
| 3 |
+
from backend.api.admin import (
|
| 4 |
+
applications,
|
| 5 |
+
policies,
|
| 6 |
+
features,
|
| 7 |
+
models,
|
| 8 |
+
requests,
|
| 9 |
+
users,
|
| 10 |
+
settings,
|
| 11 |
+
security,
|
| 12 |
+
budgets,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
__all__ = [
|
| 16 |
+
"applications",
|
| 17 |
+
"policies",
|
| 18 |
+
"features",
|
| 19 |
+
"models",
|
| 20 |
+
"requests",
|
| 21 |
+
"budgets",
|
| 22 |
+
"users",
|
| 23 |
+
"settings",
|
| 24 |
+
"security",
|
| 25 |
+
]
|