Eve library

Psyche Domain: Developer Guide

Guide

Revision 1

On this page

This guide provides comprehensive instructions for setting up a local development environment and working with the Psyche (Serwaa) AI Virtual Assistant Platform.

Table of Contents#

  1. Prerequisites
  2. Quick Start
  3. Development Environment Setup
  4. Project Structure
  5. Python Development Workflow
  6. TypeScript Development Workflow
  7. GPU Development
  8. Running Services Locally
  9. Testing
  10. Debugging
  11. Common Tasks
  12. Troubleshooting

Prerequisites#

Required Software#

Software Minimum Version Recommended Purpose
Python 3.11 3.11.x Backend services
Node.js 22.0 22.x LTS TypeScript libraries
pnpm 10.0 10.x Node.js package manager
Poetry 1.7 1.8.x Python package manager
Docker 24.0 25.x Container runtime
Docker Compose 2.20 2.24+ Multi-container orchestration
Git 2.40 2.43+ Version control

For GPU Development (Required for Avatar/Voice)#

Component Minimum Recommended Notes
GPU NVIDIA RTX 3080 NVIDIA A100 10GB+ VRAM required
CUDA 11.8 12.1+ Must match PyTorch version
cuDNN 8.6 8.9+ For optimized inference
NVIDIA Driver 525.x 545.x+ Check with nvidia-smi
TensorRT 8.5 8.6+ Optional, for optimization

Operating System#

  • Recommended: Ubuntu 22.04 LTS or macOS 14+ (Apple Silicon with Rosetta)
  • Windows: Use WSL2 with Ubuntu 22.04

Quick Start#

Get up and running in 5 minutes:

bash
# 1. Clone the repository
git clone git@github.com:GreyChimp/oshun.git
cd oshun

# 2. Install dependencies
pnpm install                    # Node.js dependencies
cd serwaa && poetry install     # Python dependencies
cd ..

# 3. Set up environment
cp serwaa/.env.example serwaa/.env
# Edit .env with your API keys

# 4. Start infrastructure
docker compose -f serwaa/infrastructure/docker/docker-compose.dev.yml up -d

# 5. Run database migrations
cd serwaa && poetry run alembic upgrade head && cd ..

# 6. Start a service
cd serwaa && poetry run uvicorn services.api_gateway.main:app --reload --port 8000

Development Environment Setup#

Step 1: Install System Dependencies#

Ubuntu/Debian:

bash
# Update system
sudo apt update && sudo apt upgrade -y

# Install Python build dependencies
sudo apt install -y \
  build-essential \
  libssl-dev \
  zlib1g-dev \
  libbz2-dev \
  libreadline-dev \
  libsqlite3-dev \
  libncursesw5-dev \
  libxml2-dev \
  libxmlsec1-dev \
  libffi-dev \
  liblzma-dev \
  tk-dev \
  git \
  curl \
  wget

# Install Python 3.11 via pyenv (recommended)
curl https://pyenv.run | bash
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(pyenv init -)"' >> ~/.bashrc
source ~/.bashrc
pyenv install 3.11.7
pyenv global 3.11.7

# Install Poetry
curl -sSL https://install.python-poetry.org | python3 -
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc

# Install Node.js via nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install 22
nvm use 22
nvm alias default 22

# Install pnpm
corepack enable
corepack prepare pnpm@latest --activate

# Install Docker
curl -fsSL https://get.docker.com | sh
sudo usermod -aG docker $USER
# Log out and back in for group changes to take effect

macOS:

bash
# Install Homebrew if not present
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# Install dependencies
brew install python@3.11 node@22 pnpm poetry git

# Docker Desktop
brew install --cask docker
# Start Docker Desktop from Applications

Step 2: Clone and Initialize Repository#

bash
# Clone repository
git clone git@github.com:GreyChimp/oshun.git
cd oshun

# Initialize submodules (if any)
git submodule update --init --recursive

# Install root-level Node dependencies
pnpm install

# Navigate to Serwaa and install Python dependencies
cd serwaa
poetry install --with dev,ml,api
cd ..

Step 3: Configure Environment#

bash
# Create environment file from template
cp serwaa/.env.example serwaa/.env

Edit serwaa/.env with your credentials:

bash
# Required API Keys (obtain from providers)
ANTHROPIC_API_KEY=sk-ant-xxxxxxxxxxxxx
OPENAI_API_KEY=sk-xxxxxxxxxxxxx
ELEVENLABS_API_KEY=xxxxxxxxxxxxx

# Optional: Zoom integration
ZOOM_CLIENT_ID=your_client_id
ZOOM_CLIENT_SECRET=your_client_secret

# Leave these as defaults for local development
DATABASE_URL=postgresql://serwaa:serwaa_dev@localhost:5432/serwaa
REDIS_URL=redis://localhost:6379/0
QDRANT_URL=http://localhost:6333
S3_ENDPOINT=http://localhost:9000

Step 4: Start Infrastructure Services#

bash
# Start all development infrastructure
docker compose -f serwaa/infrastructure/docker/docker-compose.dev.yml up -d

# Verify all services are running
docker compose -f serwaa/infrastructure/docker/docker-compose.dev.yml ps

# Expected output:
# NAME                 STATUS    PORTS
# serwaa-postgres      healthy   5432
# serwaa-redis         healthy   6379
# serwaa-qdrant        healthy   6333, 6334
# serwaa-minio         healthy   9000, 9001
# serwaa-mailpit       running   1025, 8025
# serwaa-jaeger        running   16686
# serwaa-prometheus    running   9090
# serwaa-grafana       running   3001

Step 5: Initialize Database#

bash
cd serwaa

# Run database migrations
poetry run alembic upgrade head

# Verify database is ready
poetry run python -c "
from sqlalchemy import create_engine
engine = create_engine('postgresql://serwaa:serwaa_dev@localhost:5432/serwaa')
with engine.connect() as conn:
    result = conn.execute('SELECT 1')
    print('Database connection successful!')
"

Project Structure#

Root Directory Layout#

text
oshun/
├── libs/                        # Shared libraries (Nx workspace)
│   ├── psyche/                  # Psyche domain TypeScript libraries
│   │   ├── avatar-core/         # 3DGS avatar rendering types
│   │   ├── voice-synthesis/     # TTS integration
│   │   ├── memory-core/         # Memory abstractions
│   │   └── ...                  # 60+ packages
│   ├── shared/                  # Cross-domain utilities
│   └── proto/                   # gRPC/Protobuf definitions
├── serwaa/                      # Psyche Python services (source)
│   ├── services/                # Microservices
│   │   ├── api-gateway/         # REST/WebSocket API
│   │   ├── avatar-engine/       # Avatar rendering (GPU)
│   │   ├── voice-engine/        # TTS/STT (GPU)
│   │   └── ...                  # 12+ services
│   ├── packages/                # Shared Python packages
│   ├── infrastructure/          # Docker, K8s, Terraform
│   ├── pyproject.toml           # Root Poetry configuration
│   └── .env                     # Environment variables
├── docs/                        # Documentation
├── nx.json                      # Nx workspace configuration
├── pnpm-workspace.yaml          # pnpm workspace definition
└── tsconfig.base.json           # TypeScript base config

Serwaa Services Directory#

text
serwaa/services/
├── api-gateway/                 # Port 8000 - REST/WebSocket API
│   ├── src/api_gateway/
│   │   ├── main.py              # FastAPI app entry
│   │   ├── routers/             # API route handlers
│   │   ├── models/              # Pydantic schemas
│   │   └── websocket/           # WebSocket handlers
│   ├── tests/
│   └── pyproject.toml
├── avatar-engine/               # Port 8001 - GPU-accelerated
│   ├── src/avatar_engine/
│   │   ├── main.py
│   │   ├── models/              # ML model wrappers
│   │   ├── rendering/           # 3DGS rasterization
│   │   └── face/                # FLAME integration
│   ├── tests/
│   └── pyproject.toml
├── voice-engine/                # Port 8002 - GPU-accelerated
├── behavior-engine/             # Port 8003 - CPU
├── perception-engine/           # Port 8004 - GPU-accelerated
├── computer-use/                # Port 8005 - CPU
├── conferencing/                # Port 8006 - CPU
├── orchestrator/                # Port 8007 - CPU
├── knowledge-base/              # Port 8008 - CPU
├── persona-service/             # Port 8009 - CPU
└── admin-dashboard/             # Port 3000 - Next.js

TypeScript Libraries (libs/psyche/)#

text
libs/psyche/
├── avatar-*/                    # Avatar rendering & animation
│   ├── avatar-core/             # Core types and interfaces
│   ├── avatar-expressions/      # FACS expression system
│   ├── avatar-lipsync/          # Viseme-to-mouth mapping
│   └── ...
├── voice-*/                     # Voice processing
│   ├── voice-synthesis/         # TTS provider integration
│   ├── speech-recognition/      # STT integration
│   └── ...
├── memory-*/                    # Memory systems
│   ├── memory-core/             # Core abstractions
│   ├── memory-embeddings/       # Vector operations
│   └── ...
├── *-integration/               # Platform integrations
│   ├── zoom-integration/
│   ├── teams-integration/
│   └── ...
└── e2e-tests/                   # End-to-end tests

Python Development Workflow#

Virtual Environment#

Poetry manages virtual environments automatically:

bash
cd serwaa

# Activate virtual environment
poetry shell

# Or run commands within the environment
poetry run python script.py
poetry run pytest

Installing Dependencies#

bash
# Install all dependencies
poetry install

# Install specific groups
poetry install --with dev          # Development tools
poetry install --with ml           # Machine learning (PyTorch, etc.)
poetry install --with api          # FastAPI and web dependencies

# Add a new dependency
poetry add httpx
poetry add --group dev pytest-benchmark

Code Quality#

bash
cd serwaa

# Format code
poetry run black .
poetry run isort .

# Lint code
poetry run ruff check .
poetry run ruff check . --fix     # Auto-fix issues

# Type checking
poetry run mypy services/

# Security scanning
poetry run bandit -r services/

# All quality checks (pre-commit)
poetry run pre-commit run --all-files

Running a Python Service#

bash
cd serwaa

# Development mode with auto-reload
poetry run uvicorn services.api_gateway.main:app --reload --port 8000

# With custom settings
poetry run uvicorn services.api_gateway.main:app \
  --reload \
  --host 0.0.0.0 \
  --port 8000 \
  --log-level debug

# Multiple workers (production-like)
poetry run uvicorn services.api_gateway.main:app \
  --workers 4 \
  --port 8000

Database Migrations#

bash
cd serwaa

# Create a new migration
poetry run alembic revision --autogenerate -m "Add user preferences table"

# Apply migrations
poetry run alembic upgrade head

# Rollback one migration
poetry run alembic downgrade -1

# View migration history
poetry run alembic history

# Check current revision
poetry run alembic current

TypeScript Development Workflow#

Package Management#

bash
# From repository root
pnpm install                     # Install all dependencies

# Add dependency to specific package
pnpm --filter @psyche/avatar-core add zod

# Add dev dependency
pnpm --filter @psyche/avatar-core add -D vitest

# Update dependencies
pnpm update
pnpm update --latest             # Update to latest versions

Building Libraries#

bash
# Build all Psyche libraries
pnpm nx run-many --target=build --projects=tag:psyche

# Build specific library
pnpm nx build @psyche/avatar-core

# Build with dependencies
pnpm nx build @psyche/avatar-core --with-deps

# Watch mode for development
pnpm nx build @psyche/avatar-core --watch

Running Tests#

bash
# Test all Psyche libraries
pnpm nx run-many --target=test --projects=tag:psyche

# Test specific library
pnpm nx test @psyche/avatar-core

# Watch mode
pnpm nx test @psyche/avatar-core --watch

# Coverage
pnpm nx test @psyche/avatar-core --coverage

Linting and Type Checking#

bash
# Lint all
pnpm nx run-many --target=lint --projects=tag:psyche

# Lint specific
pnpm nx lint @psyche/avatar-core
pnpm nx lint @psyche/avatar-core --fix

# Type check
pnpm nx typecheck @psyche/avatar-core

Creating a New Library#

bash
# Generate new library using Nx
pnpm nx g @nx/js:library my-new-lib \
  --directory=libs/psyche/my-new-lib \
  --importPath=@psyche/my-new-lib \
  --bundler=tsup \
  --unitTestRunner=vitest

# Or manually create:
mkdir -p libs/psyche/my-new-lib/src
cd libs/psyche/my-new-lib

# Create package.json
cat > package.json << 'EOF'
{
  "name": "@psyche/my-new-lib",
  "version": "0.1.0",
  "type": "module",
  "main": "./dist/index.cjs",
  "module": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "scripts": {
    "build": "tsup",
    "test": "vitest run",
    "lint": "eslint src",
    "typecheck": "tsc --noEmit"
  }
}
EOF

# Create tsconfig.json
cat > tsconfig.json << 'EOF'
{
  "extends": "../../../tsconfig.base.json",
  "compilerOptions": {
    "outDir": "./dist"
  },
  "include": ["src/**/*"]
}
EOF

GPU Development#

Verifying GPU Setup#

bash
# Check NVIDIA driver
nvidia-smi

# Expected output shows:
# - Driver Version (e.g., 545.23.08)
# - CUDA Version (e.g., 12.3)
# - GPU name and memory

# Check PyTorch CUDA
cd serwaa
poetry run python -c "
import torch
print(f'PyTorch version: {torch.__version__}')
print(f'CUDA available: {torch.cuda.is_available()}')
print(f'CUDA version: {torch.version.cuda}')
print(f'GPU count: {torch.cuda.device_count()}')
if torch.cuda.is_available():
    print(f'GPU name: {torch.cuda.get_device_name(0)}')
    print(f'GPU memory: {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB')
"

# Check cuDNN
poetry run python -c "
import torch
print(f'cuDNN version: {torch.backends.cudnn.version()}')
print(f'cuDNN enabled: {torch.backends.cudnn.enabled}')
"

GPU Docker Development#

bash
# Start GPU-enabled infrastructure
docker compose -f serwaa/infrastructure/docker/docker-compose.gpu.yml up -d

# Verify GPU in Docker
docker run --rm --gpus all nvidia/cuda:12.1.1-base-ubuntu22.04 nvidia-smi

# Run GPU service in Docker
docker compose -f serwaa/infrastructure/docker/docker-compose.services.yml \
  up -d avatar-engine

GPU Memory Management#

python
# In your Python code
import torch
import gc

def clear_gpu_memory():
    """Force GPU memory cleanup."""
    gc.collect()
    torch.cuda.empty_cache()
    torch.cuda.synchronize()

def get_gpu_memory_usage():
    """Get current GPU memory usage in GB."""
    if torch.cuda.is_available():
        return torch.cuda.memory_allocated() / 1e9
    return 0

def get_gpu_memory_available():
    """Get available GPU memory in GB."""
    if torch.cuda.is_available():
        total = torch.cuda.get_device_properties(0).total_memory
        used = torch.cuda.memory_allocated()
        return (total - used) / 1e9
    return 0

# Use context manager for memory-efficient inference
@torch.inference_mode()
def run_inference(model, inputs):
    with torch.cuda.amp.autocast():  # Mixed precision
        return model(inputs)

GPU Profiling#

bash
# Profile CUDA operations
cd serwaa
poetry run python -c "
import torch
from torch.profiler import profile, record_function, ProfilerActivity

with profile(
    activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
    record_shapes=True,
    profile_memory=True,
) as prof:
    # Your inference code here
    x = torch.randn(1000, 1000).cuda()
    y = x @ x.T

print(prof.key_averages().table(sort_by='cuda_time_total', row_limit=10))
"

# Use NVIDIA Nsight Systems
nsys profile --stats=true poetry run python your_script.py

Model Loading Best Practices#

python
import torch
from pathlib import Path

class ModelLoader:
    """Efficient model loading with caching."""

    def __init__(self, cache_dir: Path, device: str = "cuda"):
        self.cache_dir = cache_dir
        self.device = device
        self._models = {}

    def load_model(self, name: str, model_class, checkpoint_path: Path):
        """Load model with memory-efficient settings."""
        if name in self._models:
            return self._models[name]

        # Load on CPU first, then move to GPU
        model = model_class()
        checkpoint = torch.load(
            checkpoint_path,
            map_location="cpu",
            weights_only=True  # Security: prevent arbitrary code execution
        )
        model.load_state_dict(checkpoint)

        # Move to GPU with optimization
        model = model.to(self.device)
        model = model.eval()

        # Enable optimizations
        if hasattr(torch, 'compile'):
            model = torch.compile(model, mode="reduce-overhead")

        self._models[name] = model
        return model

    def unload_model(self, name: str):
        """Unload model and free memory."""
        if name in self._models:
            del self._models[name]
            torch.cuda.empty_cache()

Running Services Locally#

Single Service#

bash
cd serwaa

# API Gateway
poetry run uvicorn services.api_gateway.main:app --reload --port 8000

# Avatar Engine (requires GPU)
poetry run uvicorn services.avatar_engine.main:app --reload --port 8001

# Voice Engine (requires GPU)
poetry run uvicorn services.voice_engine.main:app --reload --port 8002

# Orchestrator
poetry run uvicorn services.orchestrator.main:app --reload --port 8007

Multiple Services (using scripts)#

Create a helper script scripts/run-services.sh:

bash
#!/bin/bash
set -e

# Start services in background
poetry run uvicorn services.api_gateway.main:app --port 8000 &
poetry run uvicorn services.orchestrator.main:app --port 8007 &
poetry run uvicorn services.persona_service.main:app --port 8009 &

# Wait for all background processes
wait

Using Docker Compose#

bash
# Start all services
docker compose -f serwaa/infrastructure/docker/docker-compose.services.yml up -d

# Start specific services
docker compose -f serwaa/infrastructure/docker/docker-compose.services.yml \
  up -d api-gateway orchestrator

# View logs
docker compose -f serwaa/infrastructure/docker/docker-compose.services.yml \
  logs -f api-gateway

# Stop services
docker compose -f serwaa/infrastructure/docker/docker-compose.services.yml down

Admin Dashboard (Next.js)#

bash
cd serwaa/services/admin-dashboard

# Install dependencies
pnpm install

# Development mode
pnpm dev

# Build for production
pnpm build
pnpm start

Testing#

Python Tests#

bash
cd serwaa

# Run all tests
poetry run pytest

# Run with verbose output
poetry run pytest -v

# Run specific test file
poetry run pytest services/api_gateway/tests/test_sessions.py

# Run specific test function
poetry run pytest services/api_gateway/tests/test_sessions.py::test_create_session

# Run with coverage
poetry run pytest --cov=services --cov-report=html
open htmlcov/index.html

# Run in parallel
poetry run pytest -n auto

# Run only fast tests (exclude slow/gpu)
poetry run pytest -m "not slow and not gpu"

# Run GPU tests only
poetry run pytest -m gpu

TypeScript Tests#

bash
# All Psyche tests
pnpm nx run-many --target=test --projects=tag:psyche

# Specific library
pnpm nx test @psyche/avatar-core

# Watch mode
pnpm nx test @psyche/avatar-core --watch

# With coverage
pnpm nx test @psyche/avatar-core --coverage

Integration Tests#

bash
cd serwaa

# Ensure infrastructure is running
docker compose -f infrastructure/docker/docker-compose.dev.yml up -d

# Run integration tests
poetry run pytest tests/integration/ -v

# Run E2E tests
poetry run pytest tests/e2e/ -v --slow

Test Fixtures#

python
# conftest.py example
import pytest
import asyncio
from httpx import AsyncClient
from services.api_gateway.main import app

@pytest.fixture(scope="session")
def event_loop():
    """Create event loop for async tests."""
    loop = asyncio.get_event_loop_policy().new_event_loop()
    yield loop
    loop.close()

@pytest.fixture
async def client():
    """Create async HTTP client."""
    async with AsyncClient(app=app, base_url="http://test") as client:
        yield client

@pytest.fixture
def sample_persona():
    """Sample persona for testing."""
    return {
        "name": "test-assistant",
        "display_name": "Test Assistant",
        "personality": {
            "formality": 0.5,
            "friendliness": 0.8
        }
    }

Debugging#

VS Code Configuration#

Create .vscode/launch.json:

json
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Python: API Gateway",
      "type": "debugpy",
      "request": "launch",
      "module": "uvicorn",
      "args": ["services.api_gateway.main:app", "--reload", "--port", "8000"],
      "cwd": "${workspaceFolder}/serwaa",
      "envFile": "${workspaceFolder}/serwaa/.env",
      "jinja": true
    },
    {
      "name": "Python: Avatar Engine",
      "type": "debugpy",
      "request": "launch",
      "module": "uvicorn",
      "args": ["services.avatar_engine.main:app", "--reload", "--port", "8001"],
      "cwd": "${workspaceFolder}/serwaa",
      "envFile": "${workspaceFolder}/serwaa/.env"
    },
    {
      "name": "Python: Current File",
      "type": "debugpy",
      "request": "launch",
      "program": "${file}",
      "cwd": "${workspaceFolder}/serwaa",
      "envFile": "${workspaceFolder}/serwaa/.env"
    },
    {
      "name": "TypeScript: Debug Vitest",
      "type": "node",
      "request": "launch",
      "runtimeExecutable": "pnpm",
      "args": ["nx", "test", "@psyche/avatar-core", "--", "--run"],
      "cwd": "${workspaceFolder}",
      "skipFiles": ["<node_internals>/**"]
    }
  ]
}

Python Debugging Tips#

python
# Interactive debugging
import pdb; pdb.set_trace()  # Traditional
breakpoint()                  # Python 3.7+ (preferred)

# IPython debugging (richer experience)
from IPython import embed; embed()

# Rich debugging with stack traces
from rich.traceback import install
install(show_locals=True)

# Logging for async code
import structlog
log = structlog.get_logger()
log.debug("Processing request", request_id=request.id, user_id=user.id)

Database Debugging#

bash
# Connect to PostgreSQL
docker exec -it serwaa-postgres psql -U serwaa -d serwaa

# Useful queries
\dt                          # List tables
\d+ sessions                 # Describe table
SELECT * FROM sessions LIMIT 5;
EXPLAIN ANALYZE SELECT * FROM sessions WHERE status = 'active';

# Check connection pool
SELECT count(*) FROM pg_stat_activity WHERE datname = 'serwaa';

Redis Debugging#

bash
# Connect to Redis
docker exec -it serwaa-redis redis-cli

# Useful commands
KEYS session:*               # List session keys
GET session:123              # Get specific key
TTL session:123              # Check TTL
INFO memory                  # Memory stats
MONITOR                      # Watch all commands (careful in production!)

Common Tasks#

Creating a New Service#

  1. Create service directory:
bash
mkdir -p serwaa/services/my-new-service/src/my_new_service
mkdir -p serwaa/services/my-new-service/tests
  1. Create pyproject.toml:
toml
[tool.poetry]
name = "my-new-service"
version = "0.1.0"
description = "Description of my new service"

[tool.poetry.dependencies]
python = "^3.11"
fastapi = "^0.109.0"
uvicorn = {extras = ["standard"], version = "^0.27.0"}
pydantic = "^2.5.0"

[tool.poetry.group.dev.dependencies]
pytest = "^8.0.0"
pytest-asyncio = "^0.23.0"
  1. Create main.py:
python
from fastapi import FastAPI
from contextlib import asynccontextmanager

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup
    print("Starting service...")
    yield
    # Shutdown
    print("Shutting down...")

app = FastAPI(
    title="My New Service",
    version="0.1.0",
    lifespan=lifespan
)

@app.get("/health")
async def health():
    return {"status": "healthy"}
  1. Add Dockerfile and update docker-compose.

Adding API Endpoints#

python
# routers/items.py
from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel
from typing import List

router = APIRouter(prefix="/items", tags=["items"])

class ItemCreate(BaseModel):
    name: str
    description: str | None = None

class ItemResponse(BaseModel):
    id: str
    name: str
    description: str | None

@router.post("/", response_model=ItemResponse, status_code=201)
async def create_item(item: ItemCreate):
    """Create a new item."""
    # Implementation
    pass

@router.get("/{item_id}", response_model=ItemResponse)
async def get_item(item_id: str):
    """Get item by ID."""
    # Implementation
    pass

Working with WebSockets#

python
from fastapi import WebSocket, WebSocketDisconnect
from typing import Set

class ConnectionManager:
    def __init__(self):
        self.active_connections: Set[WebSocket] = set()

    async def connect(self, websocket: WebSocket):
        await websocket.accept()
        self.active_connections.add(websocket)

    def disconnect(self, websocket: WebSocket):
        self.active_connections.discard(websocket)

    async def broadcast(self, message: dict):
        for connection in self.active_connections:
            await connection.send_json(message)

manager = ConnectionManager()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await manager.connect(websocket)
    try:
        while True:
            data = await websocket.receive_json()
            await manager.broadcast({"type": "message", "data": data})
    except WebSocketDisconnect:
        manager.disconnect(websocket)

Troubleshooting#

Common Issues#

1. Poetry Install Fails#

bash
# Clear cache
poetry cache clear pypi --all

# Update Poetry
poetry self update

# Use specific Python version
poetry env use python3.11
poetry install

2. Docker Compose Fails#

bash
# Check Docker daemon
systemctl status docker
sudo systemctl start docker

# Clean up
docker system prune -a
docker volume prune

# Rebuild
docker compose -f serwaa/infrastructure/docker/docker-compose.dev.yml up -d --build

3. Database Connection Failed#

bash
# Check PostgreSQL is running
docker compose -f serwaa/infrastructure/docker/docker-compose.dev.yml ps postgres

# Check logs
docker compose -f serwaa/infrastructure/docker/docker-compose.dev.yml logs postgres

# Restart
docker compose -f serwaa/infrastructure/docker/docker-compose.dev.yml restart postgres

4. GPU Not Available in Docker#

bash
# Install NVIDIA Container Toolkit
distribution=$(. /etc/os-release;echo $ID$VERSION_ID)
curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | sudo apt-key add -
curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | sudo tee /etc/apt/sources.list.d/nvidia-docker.list
sudo apt update
sudo apt install -y nvidia-container-toolkit
sudo systemctl restart docker

# Verify
docker run --rm --gpus all nvidia/cuda:12.1.1-base-ubuntu22.04 nvidia-smi

5. Import Errors#

bash
# Ensure you're in the right directory
cd serwaa

# Activate virtual environment
poetry shell

# Check PYTHONPATH
export PYTHONPATH="${PYTHONPATH}:$(pwd)"

6. Port Already in Use#

bash
# Find process using port
lsof -i :8000

# Kill process
kill -9 <PID>

# Or use different port
poetry run uvicorn services.api_gateway.main:app --port 8001

Getting Help#



Revision History#

Version Date Author Changes
1.0.0 2026-01-31 Claude Opus Initial developer guide