FastAPI Route Structure in AI Hedge Fund: Modular Router Architecture Guide
The AI Hedge Fund backend implements a hierarchical FastAPI route structure where domain-specific sub-routers for health, hedge-fund execution, flows, and Ollama management are aggregated into a single api_router in app/backend/routes/__init__.py and mounted by the root application in app/backend/main.py.
The virattt/ai-hedge-fund repository demonstrates production-grade FastAPI patterns by separating HTTP concerns into discrete router modules. This FastAPI route structure enables independent domain testing, clean URL organization, and straightforward feature expansion across the AI-powered hedge fund platform.
Three-Tier Router Architecture
The application organizes its HTTP endpoints using a three-layer hierarchy:
- Root FastAPI instance – Creates the application, configures CORS, and mounts the aggregated router
- API router aggregator – Collects all sub-routers with logical tags in a central
__init__.py - Domain-specific sub-routers – Define endpoints for individual concerns (health, execution, model management)
Each sub-router declares its own URL prefix (e.g., APIRouter(prefix="/hedge-fund")). When aggregated, the final URL pattern becomes <root>/<prefix>/<path>, producing clean, version-agnostic endpoints.
Root Application Configuration
The entry point at app/backend/main.py instantiates the FastAPI application and includes the consolidated router:
# app/backend/main.py
app = FastAPI(...)
app.include_router(api_router) # mounts everything at the root URL
This file also handles database table creation and CORS configuration, keeping the routing logic separate from infrastructure setup.
The Aggregation Pattern
The app/backend/routes/__init__.py file serves as the central registry, importing individual routers and tagging them for OpenAPI documentation:
# app/backend/routes/__init__.py
api_router = APIRouter()
api_router.include_router(health_router, tags=["health"])
api_router.include_router(hedge_fund_router, tags=["hedge-fund"])
api_router.include_router(storage_router, tags=["storage"])
api_router.include_router(flows_router, tags=["flows"])
api_router.include_router(flow_runs_router, tags=["flow-runs"])
api_router.include_router(ollama_router, tags=["ollama"])
api_router.include_router(language_models_router, tags=["language-models"])
api_router.include_router(api_keys_router, tags=["api-keys"])
This pattern allows developers to add new functional areas by creating a sub-router and registering it in this single location, without touching the root application file.
Domain-Specific Route Modules
Health Monitoring Endpoints
The app/backend/routes/health.py module provides simple liveness checks and Server-Sent Events (SSE) demonstrations:
GET /– Returns a welcome message for API status verificationGET /ping– Streams five SSE messages demonstrating real-time communication capabilities used by the frontend
Hedge Fund Execution Engine
The core functionality resides in app/backend/routes/hedge_fund.py, implementing streaming endpoints for AI-driven trading decisions:
POST /hedge-fund/run– Executes a live hedge-fund decision flow, streamingStartEvent,ProgressUpdateEvent, andCompleteEventpayloads via SSEPOST /hedge-fund/backtest– Runs historical back-tests of trading strategies with similar streaming semanticsGET /hedge-fund/agents– Returns a list of available AI agents configured in the system
Workflow and Flow Management
React-Flow graph persistence is handled by two complementary modules:
Flows Router (app/backend/routes/flows.py):
POST /flows/– Create new workflow definitionsGET /flows/– List saved flowsGET /flows/{id}– Retrieve specific flow configurationPUT /flows/{id}– Update existing flow graphsDELETE /flows/{id}– Remove workflow definitions
Flow Runs Router (app/backend/routes/flow_runs.py):
Tracks execution metadata and historic runs of workflow instances, providing audit trails for hedge-fund decisions.
Ollama Model Management
The app/backend/routes/ollama.py module manages local LLM infrastructure:
GET /ollama/status– Check if the Ollama server is runningPOST /ollama/start– Initialize the local Ollama servicePOST /ollama/models/download– Trigger model downloadsGET /ollama/models/download/progress/{model}– Stream download progress events
Language Model Registry
The app/backend/routes/language_models.py router merges cloud-based LLM configurations from src.llm.models with locally available Ollama models:
GET /language-models/– Returns unified list of all available models (OpenAI, Anthropic, Ollama)GET /language-models/providers– Groups models by their provider for UI organization
Configuration and Storage
Additional routers follow the same pattern:
app/backend/routes/storage.py– Handles file uploads and downloads for portfolio data and graph definitionsapp/backend/routes/api_keys.py– Provides CRUD operations for third-party API credentials (Alpha Vantage, Polygon)
Practical API Usage Examples
Health Verification
curl -s http://localhost:8000/health/
# => {"message":"Welcome to AI Hedge Fund API"}
SSE Streaming Test
curl -N http://localhost:8000/health/ping
# Receives 5 JSON lines:
# data: {"ping":"ping 1/5","timestamp":1}
Execute Trading Flow
Stream live hedge-fund decisions using the -N flag to disable buffering:
curl -X POST http://localhost:8000/hedge-fund/run \
-H "Content-Type: application/json" \
-d @request.json \
-N
Run Historical Backtest
curl -X POST http://localhost:8000/hedge-fund/backtest \
-H "Content-Type: application/json" \
-d @backtest_request.json \
-N
Manage Local Models
# Check Ollama server status
curl http://localhost:8000/ollama/status
# Start the service
curl -X POST http://localhost:8000/ollama/start
# Download with progress streaming
curl -X POST http://localhost:8000/ollama/models/download/progress \
-H "Content-Type: application/json" \
-d '{"model_name":"llama3"}' \
-N
Query Available Models
curl http://localhost:8000/language-models/
# Returns combined cloud and local model configurations
Summary
- The FastAPI route structure in virattt/ai-hedge-fund uses a hierarchical aggregation pattern where sub-routers are collected in
app/backend/routes/__init__.pybefore mounting inapp/backend/main.py. - Domain separation enables independent testing and maintenance of health checks, hedge-fund execution, workflow management, and Ollama integration.
- URL prefixes defined in individual routers (e.g.,
/hedge-fund,/flows) combine with the root mount to produce clean, predictable endpoint paths. - Streaming endpoints throughout the hedge-fund and Ollama routes use Server-Sent Events for real-time progress updates during AI execution and model downloads.
Frequently Asked Questions
How are routes organized in the AI Hedge Fund FastAPI application?
Routes are organized using FastAPI's APIRouter hierarchy. Individual domain routers (health, hedge-fund, flows) are defined in separate files under app/backend/routes/, then imported and tagged in app/backend/routes/__init__.py within a consolidated api_router. Finally, app/backend/main.py mounts this single aggregator, exposing all endpoints under the root URL path.
What is the purpose of the api_router in routes/__init__.py?
The api_router serves as a central registry that combines all domain-specific sub-routers into one cohesive API surface. It applies logical OpenAPI tags (e.g., tags=["hedge-fund"]) to group endpoints in the interactive documentation and ensures that URL prefixes defined in sub-routers are properly preserved when mounted to the root application.
How does the hedge-fund endpoint handle streaming responses?
The POST /hedge-fund/run and POST /hedge-fund/backtest endpoints in app/backend/routes/hedge_fund.py implement Server-Sent Events (SSE). They stream StartEvent notifications at initiation, multiple ProgressUpdateEvent objects during AI agent execution, and a final CompleteEvent containing the trading decision payload. Clients must use non-buffered HTTP requests (e.g., curl -N) to receive events in real time.
Can new domain routers be added without modifying main.py?
Yes. New functional domains require only two steps: create a new router file in app/backend/routes/ (e.g., analytics.py), then import and include it in app/backend/routes/__init__.py using api_router.include_router(new_router, tags=["analytics"]). The root main.py file remains unchanged because it only mounts the aggregated api_router.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →