briga-core-api / app /middleware /token_tracker.py
yabeskn's picture
feat: sync briga-backend — 2026 fallback chain (Gemini->OpenRouter :free->Groq), per-agent tier override, supabase JWT auth, agents router, retry columns
3a006a3 verified
Raw History Blame Contribute Delete
1.28 kB
"""Token Tracker Middleware — Monitors AI quota consumption across all requests."""
import time
from typing import Callable
from fastapi import Request, Response
from loguru import logger
from starlette.middleware.base import BaseHTTPMiddleware
from app.database import AsyncSessionLocal
from app.models.system import APIMonitoring
class TokenTrackerMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next: Callable) -> Response:
start_time = time.time()
# Process the request
response = await call_next(request)
# Post-process: Check if this was an AI-related request
# In a real scenario, we could look for custom headers like 'X-AI-Tokens'
# injected by the services, or just monitor endpoint patterns.
# For Antigravity, the service itself handles DB logging.
# This middleware can serve as a secondary observer or for non-Antigravity AI calls.
duration = time.time() - start_time
if response.status_code >= 400:
logger.warning(f"[Monitor] Request {request.method} {request.url.path} failed ({response.status_code}) in {duration:.2f}s")
return response