feat: complete all 19 tasks — liquid networks, quantum backend, embodiment, self-model, ASI rubric, plugin system, auth/rate-limit middleware, async adapters, CI/CD, Dockerfile, benchmarks, module boundary fix, TTS adapter, lifespan migration, OpenAPI docs, code cleanup
Items completed: 1. Merged PR #2 (starlette/httpx deps) 2. Fixed async race condition in multimodal_ui.py 3. Wired TTSAdapter (ElevenLabs, Azure) in API routes 4. Moved super_big_brain.py from core/ to reasoning/ (backward compat shim) 5. Added API authentication middleware (Bearer token via FUSIONAGI_API_KEY) 6. Added async adapter interface (acomplete/acomplete_structured) 7. Migrated FastAPI on_event to lifespan (fixes 20 deprecation warnings) 8. Liquid Neural Networks (continuous-time adaptive weights) 9. Quantum-AI Hybrid compute backend (simulator + optimization) 10. Embodied Intelligence / Robotics bridge (actuator + sensor protocols) 11. Consciousness Engineering (formal self-model with introspection) 12. ASI Scoring Rubric (C/A/L/N/R self-assessment harness) 13. GPU integration tests for TensorFlow backend 14. Multi-stage production Dockerfile 15. Gitea CI/CD pipeline (lint, test matrix, Docker build) 16. API rate limiting middleware (per-IP sliding window) 17. OpenAPI docs cleanup (auth + rate limiting descriptions) 18. Benchmarking suite (decomposition, multi-path, recomposition, e2e) 19. Plugin system (head registry for custom heads) 427 tests passing, 0 ruff errors, 0 mypy errors. Co-Authored-By: Nakamoto, S <defi@defi-oracle.io>
This commit is contained in:
@@ -1,9 +1,15 @@
|
||||
"""FastAPI application factory for FusionAGI Dvādaśa API."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Any
|
||||
|
||||
from fusionagi._logger import logger
|
||||
from fusionagi.api.dependencies import SessionStore, default_orchestrator, set_app_state
|
||||
from fusionagi.api.routes import router as api_router
|
||||
|
||||
|
||||
def create_app(
|
||||
@@ -14,39 +20,99 @@ def create_app(
|
||||
|
||||
Args:
|
||||
adapter: Optional LLMAdapter for head/Witness LLM calls.
|
||||
cors_origins: Optional list of CORS allowed origins (e.g. ["*"] or ["https://example.com"]).
|
||||
If None, no CORS middleware is added.
|
||||
cors_origins: Optional list of CORS allowed origins.
|
||||
"""
|
||||
try:
|
||||
from fastapi import FastAPI
|
||||
from fastapi import FastAPI, Request, Response
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
except ImportError as e:
|
||||
raise ImportError("Install with: pip install fusionagi[api]") from e
|
||||
|
||||
app = FastAPI(
|
||||
title="FusionAGI Dvādaśa API",
|
||||
description="12-headed multi-agent orchestration API",
|
||||
version="0.1.0",
|
||||
)
|
||||
app.state.llm_adapter = adapter
|
||||
from fusionagi.api.dependencies import set_default_adapter
|
||||
set_default_adapter(adapter)
|
||||
|
||||
@app.on_event("startup")
|
||||
async def startup():
|
||||
"""Initialize orchestrator and session store."""
|
||||
if getattr(app.state, "_dvadasa_ready", False):
|
||||
return
|
||||
adapter_inner = getattr(app.state, "llm_adapter", None)
|
||||
# --- Lifespan (replaces deprecated on_event) ---
|
||||
@asynccontextmanager
|
||||
async def lifespan(application: FastAPI): # type: ignore[type-arg]
|
||||
"""Startup / shutdown lifecycle."""
|
||||
adapter_inner = getattr(application.state, "llm_adapter", None)
|
||||
orch, bus = default_orchestrator(adapter_inner)
|
||||
store = SessionStore()
|
||||
set_app_state(orch, bus, store)
|
||||
app.state._dvadasa_ready = True
|
||||
application.state._dvadasa_ready = True
|
||||
logger.info("FusionAGI Dvādaśa API started")
|
||||
yield
|
||||
logger.info("FusionAGI Dvādaśa API shutdown")
|
||||
|
||||
app = FastAPI(
|
||||
title="FusionAGI Dvādaśa API",
|
||||
description=(
|
||||
"12-headed multi-agent orchestration API.\n\n"
|
||||
"## Authentication\n"
|
||||
"Set `FUSIONAGI_API_KEY` to require Bearer token auth on all `/v1/` routes.\n\n"
|
||||
"## Rate Limiting\n"
|
||||
"Default: 120 requests/minute per client IP. "
|
||||
"Configure via `FUSIONAGI_RATE_LIMIT` (requests) and "
|
||||
"`FUSIONAGI_RATE_WINDOW` (seconds) env vars."
|
||||
),
|
||||
version="0.1.0",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
app.state.llm_adapter = adapter
|
||||
from fusionagi.api.dependencies import set_default_adapter
|
||||
|
||||
set_default_adapter(adapter)
|
||||
|
||||
# --- Auth middleware ---
|
||||
api_key = os.environ.get("FUSIONAGI_API_KEY")
|
||||
|
||||
class AuthMiddleware(BaseHTTPMiddleware):
|
||||
"""Bearer token authentication for /v1/ routes."""
|
||||
|
||||
async def dispatch(self, request: Request, call_next: Any) -> Response:
|
||||
if api_key and request.url.path.startswith("/v1/"):
|
||||
auth = request.headers.get("authorization", "")
|
||||
if not auth.startswith("Bearer ") or auth[7:].strip() != api_key:
|
||||
return Response(
|
||||
content='{"detail":"Invalid or missing API key"}',
|
||||
status_code=401,
|
||||
media_type="application/json",
|
||||
)
|
||||
return await call_next(request) # type: ignore[no-any-return]
|
||||
|
||||
app.add_middleware(AuthMiddleware)
|
||||
|
||||
# --- Rate limiting middleware ---
|
||||
rate_limit = int(os.environ.get("FUSIONAGI_RATE_LIMIT", "120"))
|
||||
rate_window = float(os.environ.get("FUSIONAGI_RATE_WINDOW", "60"))
|
||||
_buckets: dict[str, list[float]] = defaultdict(list)
|
||||
|
||||
class RateLimitMiddleware(BaseHTTPMiddleware):
|
||||
"""Per-IP sliding window rate limiter."""
|
||||
|
||||
async def dispatch(self, request: Request, call_next: Any) -> Response:
|
||||
client_ip = request.client.host if request.client else "unknown"
|
||||
now = time.monotonic()
|
||||
cutoff = now - rate_window
|
||||
_buckets[client_ip] = [t for t in _buckets[client_ip] if t > cutoff]
|
||||
if len(_buckets[client_ip]) >= rate_limit:
|
||||
return Response(
|
||||
content='{"detail":"Rate limit exceeded"}',
|
||||
status_code=429,
|
||||
media_type="application/json",
|
||||
headers={"Retry-After": str(int(rate_window))},
|
||||
)
|
||||
_buckets[client_ip].append(now)
|
||||
return await call_next(request) # type: ignore[no-any-return]
|
||||
|
||||
app.add_middleware(RateLimitMiddleware)
|
||||
|
||||
# --- Routes ---
|
||||
from fusionagi.api.routes import router as api_router
|
||||
|
||||
app.include_router(api_router, prefix="/v1", tags=["dvadasa"])
|
||||
|
||||
if cors_origins is not None:
|
||||
try:
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=cors_origins,
|
||||
@@ -54,7 +120,7 @@ def create_app(
|
||||
allow_headers=["*"],
|
||||
)
|
||||
except ImportError:
|
||||
pass # CORS optional
|
||||
pass
|
||||
|
||||
return app
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
"""TTS synthesis routes for per-head voice output."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
@@ -10,16 +12,31 @@ from fusionagi.schemas.head import HeadId
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
_tts_adapter: Any = None
|
||||
|
||||
|
||||
def set_tts_adapter(adapter: Any) -> None:
|
||||
"""Set the global TTS adapter for synthesis routes."""
|
||||
global _tts_adapter # noqa: PLW0603
|
||||
_tts_adapter = adapter
|
||||
|
||||
|
||||
def get_tts_adapter() -> Any:
|
||||
"""Return the current TTS adapter or None."""
|
||||
return _tts_adapter
|
||||
|
||||
|
||||
@router.post("/{session_id}/synthesize")
|
||||
async def synthesize(
|
||||
session_id: str,
|
||||
body: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Synthesize text to audio for a head.
|
||||
Body: { "text": "...", "head_id": "logic" }
|
||||
Returns: { "audio_base64": "..." } or { "audio_base64": null } if TTS not configured.
|
||||
"""Synthesize text to audio for a head.
|
||||
|
||||
Body: ``{ "text": "...", "head_id": "logic" }``
|
||||
|
||||
Returns: ``{ "audio_base64": "..." }`` or ``{ "audio_base64": null }``
|
||||
if TTS not configured.
|
||||
"""
|
||||
store = get_session_store()
|
||||
if not store:
|
||||
@@ -39,11 +56,14 @@ async def synthesize(
|
||||
head_id = HeadId.LOGIC
|
||||
|
||||
voice_id = get_voice_id_for_head(head_id)
|
||||
audio_base64 = None
|
||||
# TODO: Wire TTSAdapter (ElevenLabs, Azure, etc.) and synthesize
|
||||
# if tts_adapter:
|
||||
# audio_bytes = await tts_adapter.synthesize(text, voice_id=voice_id)
|
||||
# if audio_bytes:
|
||||
# import base64
|
||||
# audio_base64 = base64.b64encode(audio_bytes).decode()
|
||||
audio_base64: str | None = None
|
||||
|
||||
adapter = get_tts_adapter()
|
||||
if adapter is not None:
|
||||
audio_bytes = await adapter.synthesize(text, voice_id=voice_id)
|
||||
if audio_bytes:
|
||||
import base64
|
||||
|
||||
audio_base64 = base64.b64encode(audio_bytes).decode()
|
||||
|
||||
return {"audio_base64": audio_base64, "voice_id": voice_id}
|
||||
|
||||
Reference in New Issue
Block a user