OptimaAI Logo

Overview

Setup and configuration of the FastAPI backend

Backend Overview

The OptimaAi backend is a FastAPI application written in Python. It exposes a RESTful API consumed by the frontend dashboard, handles ML inference, orchestrates LLM calls, manages a Redis cache, and persists data to PostgreSQL.

Setup

Prerequisites

  • Python 3.10+
  • PostgreSQL 14+
  • Redis 6+

Installation

git clone https://github.com/your-org/optimaai-backend.git
cd optimaai-backend
 
python -m venv venv
source venv/bin/activate        # Windows: venv\Scripts\activate
 
pip install -r requirements.txt

Environment Variables

Create a .env file at the project root:

# PostgreSQL
DATABASE_URL=postgresql://optimaai:optimaai123@localhost:5432/optimaai_db

# Redis
REDIS_URL=redis://localhost:6379/0

# LLM via OpenRouter
OPENROUTER_API_KEY=your_key_here

# ChromaDB (Knowledge Base)
CHROMA_DIR=knowledge_base/chroma

Database Initialisation

The tables are created automatically on first startup. To trigger it manually:

from app.database import init_db
init_db()

Or add it to your main.py startup event:

from fastapi import FastAPI
from app.database import init_db
 
app = FastAPI()
 
@app.on_event("startup")
def startup():
    init_db()

Run the Server

uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

Interactive API docs: http://localhost:8000/docs

Project Layout

app/
├── api.py                   ← All core prediction + KPI + LLM routes
├── database.py              ← SQLAlchemy models and session factory
├── cache.py                 ← Redis helper functions
├── routes/
│   ├── datasets_routes.py   ← File upload + preprocessing endpoints
│   └── kb_routes.py         ← Knowledge base ingestion + query
└── services/
    ├── inference_service.py
    ├── recommendation_service.py
    ├── bmc_service.py
    ├── ml_bridge.py
    ├── knowledge_base.py
    └── improved_prompts.py

⚠️ Warning: The prediction endpoints will return a 500 error until you have run python ml/train.py at least once to generate model artefacts.

Health Check

GET /api/v1/health
{
  "status": "ok",
  "service": "OptimaAi API",
  "timestamp": "2026-05-11T10:00:00"
}

On this page