Skip to content

MorpheusAIs/Morpheus-Marketplace-API

Repository files navigation

Morpheus API Gateway - FastAPI Implementation

A robust API Gateway connecting Web2 clients to the Morpheus-Lumerin AI Marketplace using FastAPI, PostgreSQL, and secure key management practices.

Overview

This project migrates the existing Morpheus API Gateway functionality from Node.js/Express to Python/FastAPI, incorporating robust authentication, persistent storage, secure key management, and best practices for API development and deployment using Docker.

The gateway provides OpenAI-compatible endpoints that connect to the Morpheus blockchain, allowing users to access AI models in a familiar way while leveraging blockchain technology behind the scenes.

Technology Stack

  • Web Framework: FastAPI
  • Data Validation: Pydantic
  • Database ORM: SQLAlchemy with Alembic for migrations
  • Database: PostgreSQL
  • Caching: In-memory with DirectModelService
  • Asynchronous HTTP Client: httpx (for communicating with the proxy-router)
  • JWT Handling: python-jose
  • Password Hashing: passlib[bcrypt]
  • Cryptography: cryptography for private key encryption
  • KMS Integration: AWS KMS for secure key management
  • Containerization: Docker, Docker Compose

Project Structure

morpheus_api_python/
β”œβ”€β”€ alembic/                  # Database migrations
β”œβ”€β”€ alembic.ini
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ api/                  # FastAPI routers/endpoints
β”‚   β”‚   β”œβ”€β”€ v1/
β”‚   β”‚   β”‚   β”œβ”€β”€ auth.py       # User registration, login, API keys, private key mgmt
β”‚   β”‚   β”‚   β”œβ”€β”€ models.py     # OpenAI compatible models endpoint
β”‚   β”‚   β”‚   β”œβ”€β”€ chat.py       # OpenAI compatible chat completions
β”‚   β”‚   β”‚   β”œβ”€β”€ chat_history.py # Chat history management
β”‚   β”‚   β”‚   β”œβ”€β”€ session.py    # Session management
β”‚   β”‚   β”‚   └── automation.py # Automation settings
β”‚   β”‚   └── __init__.py
β”‚   β”œβ”€β”€ core/                 # Core logic, configuration, security
β”‚   β”‚   β”œβ”€β”€ config.py         # Pydantic settings
β”‚   β”‚   β”œβ”€β”€ security.py       # JWT generation/validation, password hashing, API key handling
β”‚   β”‚   β”œβ”€β”€ key_vault.py      # Private key encryption/decryption, KMS interaction
β”‚   β”‚   β”œβ”€β”€ direct_model_service.py # Direct model fetching with in-memory cache
β”‚   β”‚   β”œβ”€β”€ model_routing.py  # Model name to blockchain ID routing
β”‚   β”‚   β”œβ”€β”€ local_testing.py  # Local testing mode and authentication bypass
β”‚   β”‚   └── __init__.py
β”‚   β”œβ”€β”€ crud/                 # Database interaction functions
β”‚   β”‚   β”œβ”€β”€ user.py
β”‚   β”‚   β”œβ”€β”€ api_key.py
β”‚   β”‚   β”œβ”€β”€ private_key.py
β”‚   β”‚   β”œβ”€β”€ chat.py           # Chat and message CRUD operations
β”‚   β”‚   β”œβ”€β”€ session.py        # Session CRUD operations
β”‚   β”‚   └── __init__.py
β”‚   β”œβ”€β”€ db/                   # Database session management, base model
β”‚   β”‚   β”œβ”€β”€ database.py
β”‚   β”‚   β”œβ”€β”€ models.py         # SQLAlchemy models (includes Chat, Message)
β”‚   β”‚   └── __init__.py
β”‚   β”œβ”€β”€ schemas/              # Pydantic schemas for request/response validation
β”‚   β”‚   β”œβ”€β”€ user.py
β”‚   β”‚   β”œβ”€β”€ token.py
β”‚   β”‚   β”œβ”€β”€ api_key.py
β”‚   β”‚   β”œβ”€β”€ private_key.py
β”‚   β”‚   β”œβ”€β”€ openai.py         # Schemas for OpenAI compatibility
β”‚   β”‚   └── __init__.py
β”‚   β”œβ”€β”€ services/             # Business logic layer
β”‚   β”‚   β”œβ”€β”€ cognito_service.py    # Cognito integration
β”‚   β”‚   β”œβ”€β”€ session_service.py    # Session management logic
β”‚   β”‚   β”œβ”€β”€ proxy_router.py       # Proxy router communication
β”‚   β”‚   └── __init__.py
β”‚   β”œβ”€β”€ dependencies.py       # FastAPI dependency injection functions
β”‚   └── main.py               # FastAPI application instance and root setup
β”œβ”€β”€ ai-docs/                  # Documentation and guides
β”‚   β”œβ”€β”€ DOCKER_TESTING.md     # Local testing guide
β”‚   β”œβ”€β”€ SELF_CONTAINED_LOCAL_TESTING.md # Detailed local setup
β”‚   └── ...                   # Other documentation files
β”œβ”€β”€ scripts/                  # Development and deployment scripts
β”‚   β”œβ”€β”€ test_local.sh         # Self-contained local testing
β”‚   β”œβ”€β”€ start_local_dev.sh    # Container startup with auto-migration
β”‚   └── ...                   # Other utility scripts
β”œβ”€β”€ tests/                    # Test files
β”‚   β”œβ”€β”€ api/                  # API integration tests
β”‚   └── unit/                 # Unit tests
β”œβ”€β”€ .env.example              # Production environment template
β”œβ”€β”€ env.local.example         # Local testing environment template
β”œβ”€β”€ .gitignore                # Git ignore file
β”œβ”€β”€ Dockerfile                # Docker build configuration
β”œβ”€β”€ docker-compose.local.yml  # Local development container setup
β”œβ”€β”€ pyproject.toml            # Python project dependencies
└── README.md                 # This file

Getting Started

πŸš€ Quick Start - Local Development (Recommended)

No external dependencies needed! For rapid development and testing:

# One-time setup
cp env.local.example .env.local

# Start local development environment
./scripts/test_local.sh

What this gives you:

  • βœ… No Authentication Required - All endpoints work without tokens/keys
  • βœ… Fresh Database - PostgreSQL with auto-migrations on every start
  • βœ… Hot Reload - Code changes apply instantly
  • βœ… Complete API Testing - Test all endpoints via Swagger UI
  • βœ… Ephemeral Environment - Clean state every restart

Access your local environment:

πŸ“š For detailed testing instructions, see Docker Testing Guide

Prerequisites (Production Setup)

  • Python 3.11+
  • Docker and Docker Compose
  • PostgreSQL (if running locally without Docker)
  • AWS Account with KMS access (for production)

Production Installation

  1. Clone the repository:

    git clone https://github.com/yourusername/morpheus-api-python.git
    cd morpheus-api-python
  2. Create a virtual environment:

    python -m venv venv
    source venv/bin/activate  # On Windows: venv\Scripts\activate
  3. Install dependencies:

    pip install poetry
    poetry install
  4. Configure environment variables:

    cp .env.example .env

    Edit the .env file with your specific settings

Environment Configuration

Configure the following key environment variables:

# Database
POSTGRES_USER=morpheus_user
POSTGRES_PASSWORD=secure_password_here
POSTGRES_DB=morpheus_db
DATABASE_URL=postgresql+asyncpg://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:5432/${POSTGRES_DB}

# Model Service (uses in-memory caching)
ACTIVE_MODELS_URL=https://active.dev.mor.org/active_models.json

# JWT
JWT_SECRET_KEY=generate_this_with_openssl_rand_-hex_32
ACCESS_TOKEN_EXPIRE_MINUTES=30
REFRESH_TOKEN_EXPIRE_DAYS=7

# AWS KMS (for production)
KMS_PROVIDER=aws
KMS_MASTER_KEY_ID=your_kms_key_id_or_arn
AWS_REGION=us-east-1
# AWS_ACCESS_KEY_ID=your_access_key_id         # If not using IAM roles
# AWS_SECRET_ACCESS_KEY=your_secret_access_key # If not using IAM roles

# Development mode local encryption (not for production)
MASTER_ENCRYPTION_KEY=generate_this_with_openssl_rand_-hex_32

# Proxy Router
PROXY_ROUTER_URL=http://localhost:8545  # URL of the Morpheus-Lumerin Node proxy-router

Database Setup

Local Development Database

Using Local Testing Environment (Recommended):

  • Database setup is automatic when using ./scripts/test_local.sh
  • PostgreSQL starts in Docker with auto-migrations
  • No manual database setup required!

Manual Database Setup (Production)

  1. Start PostgreSQL:

    docker run --name morpheus-postgres -e POSTGRES_USER=morpheus_user -e POSTGRES_PASSWORD=morpheus_password -e POSTGRES_DB=morpheus_db -p 5432:5432 -d postgres:15-alpine
  2. Run migrations:

    alembic upgrade head

Database Migrations

Local Development:

  • Migrations run automatically on container startup
  • Always uses the latest schema
  • Fresh database on every restart

Production/Manual:

Generate a new migration after model changes:

alembic revision --autogenerate -m "Description of changes"

Apply migrations:

alembic upgrade head

Roll back migrations:

alembic downgrade -1  # Roll back one migration

Model Service

The API uses an in-memory caching system for model data fetched from CloudFront. No external caching service is required.

AWS KMS Setup (Production)

  1. Create a KMS key in the AWS console or using AWS CLI
  2. Note the key ARN or ID
  3. Configure IAM permissions for your service principal
  4. Update environment variables with key details

Running the Application

πŸš€ Local Development (Recommended)

One command starts everything:

./scripts/test_local.sh

Features:

  • βœ… PostgreSQL database with auto-migrations
  • βœ… API with hot reload
  • βœ… Authentication bypass for easy testing
  • βœ… All endpoints accessible via Swagger UI

Monitor your environment:

# View logs
docker compose -f docker-compose.local.yml logs -f api-local

# Check status
docker compose -f docker-compose.local.yml ps

# Stop environment
docker compose -f docker-compose.local.yml down

Production Docker Setup

  1. Build and start containers:

    docker-compose up -d
  2. Check container status:

    docker-compose ps
  3. View logs:

    docker-compose logs -f api

Manual Local Development

  1. Start PostgreSQL (see Database Setup above)

  2. Run the FastAPI application:

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

Testing the API

πŸ§ͺ Local Development Testing

Using Local Environment (No Authentication Required):

# Start environment
./scripts/test_local.sh

# Access Swagger UI - all endpoints work without authentication!
# http://localhost:8000/docs

Test any endpoint directly:

  • No Bearer tokens needed
  • No API keys required
  • Click "Try it out" and execute immediately
  • Test user automatically created: [email protected]

API Documentation

FastAPI automatically generates interactive API documentation:

πŸ“š For comprehensive testing instructions, see Docker Testing Guide

Core Endpoints

Authentication

  • POST /api/v1/auth/register - Create a new user
  • POST /api/v1/auth/login - Log in and get JWT tokens
  • POST /api/v1/auth/refresh - Refresh access token

API Key Management

  • POST /api/v1/auth/keys - Create a new API key
  • GET /api/v1/auth/keys - List your API keys
  • DELETE /api/v1/auth/keys/{key_id} - Delete an API key

Private Key Management

  • POST /api/v1/auth/private-key - Store your blockchain private key
  • GET /api/v1/auth/private-key/status - Check if you have a stored private key
  • DELETE /api/v1/auth/private-key - Delete your stored private key

OpenAI-Compatible Endpoints

  • GET /api/v1/models - List available models
  • GET /api/v1/models/{model_id} - Get model details
  • POST /api/v1/chat/completions - Create a chat completion

Example: Testing Chat Completion

πŸš€ Local Development (No Authentication)

# Start local environment
./scripts/test_local.sh

# Test chat completion directly (no auth needed!)
curl -X POST http://localhost:8000/api/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-3.5-turbo",
    "messages": [
      {"role": "user", "content": "Hello, how are you?"}
    ]
  }'

# Test chat history
curl -X POST http://localhost:8000/api/v1/chat-history/chats \
  -H "Content-Type: application/json" \
  -d '{"title": "Test Chat"}'

# List available models
curl http://localhost:8000/api/v1/models

🏭 Production (Full Authentication Flow)

  1. Register a user:

    curl -X POST http://localhost:8000/api/v1/auth/register \
      -H "Content-Type: application/json" \
      -d '{"name": "Test User", "email": "[email protected]", "password": "securepassword"}'
  2. Login to get tokens:

    curl -X POST http://localhost:8000/api/v1/auth/login \
      -H "Content-Type: application/json" \
      -d '{"email": "[email protected]", "password": "securepassword"}'
  3. Create an API key (using JWT from login):

    curl -X POST http://localhost:8000/api/v1/auth/keys \
      -H "Authorization: Bearer YOUR_JWT_TOKEN" \
      -H "Content-Type: application/json" \
      -d '{"name": "My API Key"}'
  4. Store a private key:

    curl -X POST http://localhost:8000/api/v1/auth/private-key \
      -H "Authorization: Bearer YOUR_JWT_TOKEN" \
      -H "Content-Type: application/json" \
      -d '{"private_key": "YOUR_BLOCKCHAIN_PRIVATE_KEY"}'
  5. Create a chat completion using the API key:

    curl -X POST http://localhost:8000/api/v1/chat/completions \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "model": "gpt-3.5-turbo",
        "messages": [
          {"role": "user", "content": "Hello, how are you?"}
        ]
      }'

Health Checks

  • GET /health - Check API and model service health
  • GET / - Basic API information

Open Questions and TODOs

This implementation is based on the FastAPI Implementation Plan and has the following open questions:

  1. Proxy-Router API Specifics: The exact API contract of the morpheus-lumerin-node proxy-router needs clarification.
  2. Model Mapping Source: The source of mapping between OpenAI model names and blockchain model IDs needs to be determined.
  3. Token Spending Approval: The mechanism for the /auth/approve-spending endpoint needs specification.
  4. Private Key Scope: Confirm if a single private key per user is sufficient.
  5. Rate Limiting: Determine rate-limiting requirements and implement if needed.
  6. Security Requirements: Confirm if there are any specific compliance or advanced security requirements.

The current implementation uses placeholder/mock data for model information and chat completions until the proxy-router integration is finalized.

πŸ”„ Development Workflow

Daily Development

# Start local environment (one-time per session)
./scripts/test_local.sh

# Make code changes (hot reload active - changes apply instantly!)
# Test in Swagger UI: http://localhost:8000/docs

# Stop environment when done
# Ctrl+C or: docker compose -f docker-compose.local.yml down

Key Features for Development

  • βœ… Hot Reload - Code changes apply instantly
  • βœ… No Authentication - Test all endpoints immediately
  • βœ… Fresh Database - Clean state every restart
  • βœ… Auto-Migration - Database schema always current
  • βœ… Comprehensive Testing - All endpoints accessible via Swagger UI

Testing Different Scenarios

# Test chat functionality
curl -X POST http://localhost:8000/api/v1/chat-history/chats \
  -H "Content-Type: application/json" \
  -d '{"title": "Development Test"}'

# Test model service
curl http://localhost:8000/api/v1/models

# Test health checks
curl http://localhost:8000/health

Development and Contributing

  • Format code with ruff format
  • Run linting with ruff check
  • Run type checking with mypy
  • Run tests with pytest

License

MIT License

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Packages

 
 
 

Contributors 5

Languages