AI Routes (Chat & Intelligence)

Documentation for AI chat routes and all backend services within the unified backend architecture

Created: 1/19/2026

Unified Backend Routes

The unified backend (apps/ai) serves as the central hub for all backend functionality. While this section focuses on AI chat capabilities, the backend encompasses multiple route modules providing comprehensive application services.

Architecture Overview

graph TD
    Client[Native/Web Apps] --> Backend[Unified Backend apps/ai]
    Backend --> AI[AI Routes /api/ai]
    Backend --> Move[Move Routes /api/move]
    Backend --> IPFS[IPFS Routes /api/ipfs]
    Backend --> DB[Database Routes /api/database]
    Backend --> Notif[Notifications Routes /api/notifications]
    Backend --> Auth[Auth Routes /api/auth]
    Backend --> HB[Heartbeat /api/heartbeat]

    AI --> OpenAI[OpenAI GPT-4o-mini]
    Move --> MovementNetwork[Movement Testnet]
    IPFS --> Helia[Helia IPFS Node]
    DB --> PostgreSQL[PostgreSQL Database]
    Notif --> Expo[Expo Push Service]
    Auth --> Privy[Privy Auth]

Core Features

  • Unified Authentication: Privy-based authentication across all services
  • Performance Tracking: Built-in timing middleware for all operations
  • Database Integration: PostgreSQL with Drizzle ORM and Row Level Security
  • Activity Monitoring: Automatic cleanup of stale sessions and devices
  • Cross-Service Integration: Services can share data and coordinate through the database

AI Chat Routes (/api/ai)

POST /api/chat

Handles streaming AI conversations using OpenAI GPT-4o-mini.

Authentication: Required (Privy token)

Request Body:

{
  "messages": [
    { "role": "user", "content": "Hello, how can I help you?" }
  ]
}

Response: Server-sent events stream with AI responses

Message Mapping: The backend transforms UI messages with parts into AI SDK format:

const mapMessages = (messages: any[]): CoreMessage[] => {
    return messages.map(m => ({
        role: m.role,
        content: m.content || m.parts?.map((p: any) => p.text || '').join('') || ''
    }));
};

Database Routes (/api/database)

GET /api/database/entries

Fetch user entries with optional timestamp filtering.

Authentication: Required (Privy token)

Query Parameters:

  • since: ISO timestamp for incremental sync

Response:

[
  {
    "id": "uuid",
    "userId": "uuid",
    "content": "Entry content",
    "createdAt": "2026-01-29T...",
    "updatedAt": "2026-01-29T..."
  }
]

POST /api/database/entries

Create or update entries (upsert operation).

Authentication: Required (Privy token)

Request Body:

{
  "id": "optional-uuid",
  "content": "Entry content",
  "created_at": "optional-iso-timestamp",
  "updated_at": "optional-iso-timestamp",
  "deleted": false
}

Notifications Routes (/api/notifications)

POST /api/notifications/devices/register

Register device push token for notifications.

Authentication: Required (Privy token)

Request Body:

{
  "pushToken": "ExponentPushToken[...]",
  "platform": "ios" // or "android"
}

DELETE /api/notifications/devices/:tokenId

Deactivate a device token (soft delete).

Authentication: Required (Privy token)

GET /api/notifications/devices

List all active devices for the authenticated user.

Authentication: Required (Privy token)

POST /api/notifications/send

Send push notifications to multiple users.

Authentication: Required (Privy token)

Request Body:

{
  "userIds": ["user-uuid-1", "user-uuid-2"],
  "title": "Notification Title",
  "body": "Notification message",
  "data": { "customData": "value" },
  "priority": "default"
}

Authentication Routes (/api/auth)

POST /api/auth/register

Register new user with device information.

Authentication: Privy token required

Request Body:

{
  "deviceInfo": {
    "name": "iPhone 15",
    "model": "iPhone15,2",
    "platform": "ios",
    "appVersion": "1.0.0"
  }
}

POST /api/auth/logout

Deactivate all user devices and tokens.

Authentication: Required (Privy token)

Heartbeat Route (/api/heartbeat)

POST /api/heartbeat

Update user activity status and refresh device sessions.

Authentication: Required (Privy token)

Database Schema

The unified backend uses PostgreSQL with the following key tables:

Users

CREATE TABLE users (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  privyUserId TEXT UNIQUE NOT NULL,
  createdAt TIMESTAMP DEFAULT NOW()
);

Devices

CREATE TABLE devices (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  userId UUID REFERENCES users(id),
  deviceName TEXT,
  deviceModel TEXT,
  platform TEXT CHECK (platform IN ('ios', 'android')),
  appVersion TEXT,
  isActive BOOLEAN DEFAULT true
);

Device Tokens

CREATE TABLE deviceTokens (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  deviceId UUID REFERENCES devices(id),
  userId UUID REFERENCES users(id),
  pushToken TEXT UNIQUE NOT NULL,
  isActive BOOLEAN DEFAULT true
);

Entries

CREATE TABLE entries (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  userId UUID REFERENCES users(id),
  content TEXT NOT NULL,
  createdAt TIMESTAMP DEFAULT NOW(),
  updatedAt TIMESTAMP DEFAULT NOW(),
  deleted BOOLEAN DEFAULT false
);

Activity Service

The backend includes an activity monitoring service that:

  • Tracks user sessions and device activity
  • Automatically cleans up inactive devices
  • Manages push token lifecycle
  • Runs cleanup operations on a schedule

Installation & Setup

Located in apps/ai, the unified backend runs on port 3005 by default.

Environment Variables

# OpenAI (required)
OPENAI_API_KEY=your_openai_key

# Privy (required)
PRIVY_APP_ID=your_privy_app_id
PRIVY_APP_SECRET=your_privy_app_secret

# Database (required)
DATABASE_URL=postgresql://user:pass@localhost:5432/db

# Server (optional)
PORT=3005
HOST=localhost
NODE_ENV=development

Running Locally

# Start unified backend
pnpm start:ai

# Or from project root
pnpm dev

Integration with Apps

Native App Configuration

# apps/native/.env
EXPO_PUBLIC_AI_BACKEND_URL="http://localhost:3005"

Web App Configuration

# apps/web/.env.local
NEXT_PUBLIC_API_URL="http://localhost:3005"

Security Features

  • Privy Authentication: All routes validate access tokens
  • Row Level Security: Database queries are automatically scoped to authenticated users
  • API Key Protection: IPFS operations require additional API keys
  • Activity Monitoring: Automatic cleanup prevents token abuse
  • Rate Limiting: Recommended for production deployments