Files
2026-02-25 01:41:28 +01:00

15 KiB
Raw Permalink Blame History

CLAUDE.md — Multi‑Provider OpenAI‑Compatible API SaaS

1. Mission & elevator pitch

Build a SaaS that exposes a single OpenAI‑compatible API (base URL + API key) which fans out to multiple LLM providers (OpenAI, Anthropic, Grok, DeepSeek, Perplexity, etc.).
Users get:

  • One base URL and one key.
  • Access to many models across providers.
  • Centralized billing, limits, and analytics.
  • A clean Next.js web app (dashboard + admin).

This repo should be structured so that adding a new AI provider requires only a new adapter module and configuration, not touching core routing logic.


2. High‑level requirements

Core product

  • OpenAI‑compatible API:
    • POST /v1/chat/completions
    • POST /v1/completions
    • POST /v1/embeddings
    • GET /v1/models
    • (Optional later) POST /v1/moderations, file endpoints, etc.
  • Single base URL and single API key per user (with ability for users to create multiple keys for their account, each with its own limits and metadata).
  • Multi‑provider support from day one:
    • OpenAI, Anthropic, Grok, DeepSeek, Perplexity.
    • Additional providers must be pluggable via a standard adapter interface.

Admin features

  • Web admin panel with full CRUD for:
    • Users and their status (active, banned, trial, etc.).
    • Subscription plans, pricing, and usage limits per plan.
    • Provider API keys (add/remove/enable/disable).
  • Provider key ingestion system:
    • Upload .txt with one raw key per line.
    • System automatically:
      • Detects which provider each key belongs to.
      • Validates key via a lightweight test call or pattern.
      • Fetches / stores basic metadata (rate limits, model access, etc.) where possible.
  • Advanced usage stats panel:
    • Per provider.
    • Per provider API key.
    • Per user and per user‑API‑key.
    • Time‑series charts (e.g. daily/weekly usage) and breakdown by model.

User features

  • Authenticated user dashboard where users can:
    • View and regenerate their own API keys (for this SaaS).
    • Create multiple API keys with:
      • Custom per‑key limits (requests/day, tokens/day, cost/day).
      • Optional tags/labels (e.g. "staging", "prod‑service‑A").
    • See usage statistics:
      • Requests and tokens over time.
      • By model, provider, and user key.
    • View API request logs:
      • Timestamp, model, provider, latency, tokens, cost, status (success/error).
      • (Configurable) truncated prompt/response previews or hash IDs (for privacy).
    • Delete logs for privacy/GDPR purposes (soft delete + optional hard delete jobs).
  • Account billing section:
    • Current plan, remaining quota.
    • Upgrade/downgrade plan.
    • Invoices and payment history.

3. Tech stack & major dependencies

Frontend & backend framework

  • Next.js (App Router, latest stable).
  • TypeScript everywhere.
  • React Server Components where suitable; client components only where needed.

UI

  • Tailwind CSS.
  • shadcn/ui (or similar) for composable, good‑looking components.
  • A design system matching a custom SaaS look (no raw boilerplate UI).

Backend inside Next.js

  • Next.js Route Handlers for JSON API endpoints.
  • Optionally a thin internal service layer (folder like src/server/) for domain logic.

Database & data access

  • MongoDB

Caching, rate limiting, queues

  • Redis:
    • Per‑user/per‑key rate limiting counters.
    • Short‑term request metadata caching as needed.
  • Background work:
    • Either:
      • Next.js + cron jobs (e.g. Vercel Cron, or node‑cron in a long‑running environment), or
      • A small worker process using BullMQ/Node + Redis.

Auth

  • Auth.js (NextAuth) or similar:
    • Email/password and OAuth (GitHub/Google) as nice‑to‑have.
    • JWT sessions or database‑backed sessions.

Billing

  • Stripe subscriptions:
    • Plans aligned with DB SubscriptionPlan model.
    • Webhooks to update user plan & limits.

Logging & monitoring

  • Application logs via a standard logger (e.g. pino).
  • Request/usage logs written to PostgreSQL (aggregations created via scheduled jobs).

4. Architecture overview

Core components

  1. API Gateway Layer (OpenAI‑compatible)

    • Receives requests on /v1/*.
    • Authenticates using the user’s SaaS API key.
    • Normalizes input into an internal UnifiedRequest format.
    • Selects provider + provider key based on model mapping and routing policies.
    • Forwards the request to the appropriate provider adapter.
    • Normalizes provider responses to UnifiedResponse matching OpenAI format.
  2. Provider Adapter Layer

    • Each provider gets its own module that implements a common interface, e.g.:

      interface ProviderAdapter {
        id: 'openai' | 'anthropic' | 'grok' | 'deepseek' | 'perplexity' | string;
        // Used during ingestion to guess provider from raw key
        matchesApiKeyPattern(key: string): boolean;
        // Validate key and optionally fetch metadata
        validateApiKey(key: string): Promise<ProviderKeyMetadata>;
        // Core operations
        chatCompletion(req: UnifiedChatRequest, ctx: ProviderKeyContext): Promise<UnifiedChatResponse>;
        completion?(req: UnifiedCompletionRequest, ctx: ProviderKeyContext): Promise<UnifiedCompletionResponse>;
        embeddings?(req: UnifiedEmbeddingRequest, ctx: ProviderKeyContext): Promise<UnifiedEmbeddingResponse>;
        listModels?(ctx: ProviderKeyContext): Promise<ProviderModelInfo[]>;
      }
      
    • A registry maps provider IDs to adapters.

    • Adding a new provider = new adapter file + config entry.

  3. Routing & Key Selection

    • Model map:
      • Internal model names exactly match OpenAI naming where possible.
      • Mapping table: logical_model_id → {provider_id, provider_model_id} or list for fallbacks.
    • Provider key pool:
      • Each provider has many keys, each with:
        • Status (active/disabled).
        • Remaining quota or soft usage limits.
        • Health status (recent errors, last validated time).
    • Routing policies:
      • Default: round‑robin or least‑used key among active keys for chosen provider/model.
      • Fallback:
        • If provider returns rate‑limit/5xx, optionally try another provider/model in the mapping chain.
      • Future: policies like “cheapest”, “fastest”, etc.
  4. Usage Logging & Analytics Pipeline

    • For each request:
      • Synchronous write of a minimal log row (user_id, api_key_id, provider_id, model, tokens_in, tokens_out, success/error, latency).
      • Async enrichment:
        • Cost calculation from pricing table (per model).
        • Aggregation into daily/weekly rollups by:
          • User, API key, provider, model, plan.
    • Dashboards query rollup tables for performance.
  5. Admin & User Web Apps

    • Same Next.js project, separated by route groups:
      • /dashboard/* for users.
      • /admin/* for admins (with role‑based access control).

5. Data model (high‑level)

Use MongoDB to define schemas similar to:

  • User
    • id, email, name, role (user, admin), createdAt, etc.
  • SubscriptionPlan
    • id, name, monthlyPrice, requestLimitPerMonth, tokenLimitPerMonth, overagePricePer1kTokens, features JSON, etc.
  • Subscription
    • id, userId, planId, status, currentPeriodStart, currentPeriodEnd, usage counters.
  • UserApiKey
    • id, userId, hashedKey, label, status, dailyRequestLimit, dailyTokenLimit, softCostLimit, createdAt, lastUsedAt.
  • Provider
    • id (openai, anthropic, grok, deepseek, perplexity, etc.), displayName, baseUrl, enabled, config JSON.
  • ProviderApiKey
    • id, providerId, encryptedKey, label, status, lastValidatedAt, errorCount, metadata JSON (rate limits, models, notes).
  • ModelMapping
    • id, logicalModelId (e.g. gpt-4.1-mini), providerId, providerModelId, priority, enabled.
  • RequestLog
    • id, userId, userApiKeyId, providerId, providerApiKeyId, logicalModelId, providerModelId, statusCode, errorCode, tokensIn, tokensOut, cost, latencyMs, createdAt.
    • Optional fields for truncated prompt/response or hashes.
  • UsageAggregateDaily
    • date, userId, userApiKeyId, providerId, logicalModelId, totalRequests, totalTokensIn, totalTokensOut, totalCost.
  • IngestionBatch
    • id, providerId (optional at upload), status, totalKeys, successfulKeys, failedKeys, createdAt.

6. API surface (OpenAI‑compatible)

Authentication

  • Header: Authorization: Bearer <user_api_key> for this SaaS (not provider keys).
  • Optional X-Request-Id header for correlation.

Endpoints

  1. POST /v1/chat/completions

    • Accepts standard OpenAI chat schema: model, messages, stream, temperature, etc.
    • model resolves through ModelMapping.
    • Supports streaming responses with SSE (compatible with OpenAI clients).
  2. POST /v1/completions

    • Legacy support where needed.
  3. POST /v1/embeddings

    • Accepts OpenAI embeddings schema.
    • Routes to providers that support embeddings.
  4. GET /v1/models

    • Returns merged set of logical models with metadata:
      • id, owned_by (this SaaS), provider hints, capabilities.
  5. (Later phases) POST /v1/moderations, image/audio endpoints as providers allow.

Error format

  • Mirror OpenAI’s error structure closely:
    • {"error": {"message": "...", "type": "...", "code": "...", ...}}
  • Include provider error info where safe, but never leak provider keys.

7. Provider key ingestion & management

Ingestion flow

  • Admin uploads a .txt file via /admin/providers/ingest:
    • One raw API key per line.
    • Optional prefix line for metadata, or UI‑provided providerId if known.
  • Backend logic:
    • For each line:
      • Trim and ignore empty lines/comments.
      • Run through adapter matchesApiKeyPattern.
      • If ambiguous or none match:
        • Try calling a lightweight “who am I” endpoint for providers (if such endpoints exist) or a low‑cost list‑models/completions test.
      • Store as ProviderApiKey with:
        • providerId.
        • encryptedKey (use environment key).
        • initial status (active or pending).
        • metadata JSON with detection results and basic limits.
  • Provide ingestion status UI showing:
    • Total keys, success count, error reasons, and affected providers.

Key lifecycle

  • Admin can:
    • Enable/disable keys.
    • Tag keys (e.g. "low‑latency‑region‑EU", "backup").
    • See basic health metrics per key: recent errors, last used, estimated remaining quota (where derivable).

8. Usage statistics & analytics

Per provider and provider key

  • Metrics:
    • Requests, tokens, cost, errors, latency distribution.
  • Views:
    • Time series graphs (per day/week).
    • Breakdowns by model.

Per user and per user API key

  • Metrics:
    • Same as above, plus:
      • % of plan used (requests, tokens, cost).
  • Views:
    • For users:
      • Simple charts and tables.
    • For admins:
      • Global views, filters by plan, heavy users, etc.

Data pipeline

  • Real‑time counters in Redis can back UI for “today’s usage”.
  • Nightly job aggregates logs into UsageAggregateDaily.

9. User dashboard

Overview page

  • Current plan and remaining quota.
  • Sparkline or chart of recent usage (requests/tokens per day).
  • Quick links to create API keys and view logs.

API key management

  • List of keys with:
    • Label, createdAt, lastUsedAt, status.
    • Daily limits and soft cost limits.
  • Actions:
    • Create new key.
    • Regenerate key (invalidates old one).
    • Edit limits and labels.
    • Disable/enable key.
    • Delete key (with confirmation).

Request logs

  • Paginated table:
    • Time, model, provider, latency, tokens, cost, status.
  • Filters:
    • Date range, model, provider, status, API key.
  • Log deletion:
    • Single log or bulk within date range.
    • UI warns about permanent deletion (or marks soft deletion with background purge).

Billing

  • Show:
    • Current subscription plan and renewal date.
    • Usage vs plan limits.
    • Invoices & payment method.
  • Actions:
    • Upgrade/downgrade via Stripe Checkout/Customer Portal.

10. Admin panel

Users

  • Table of users:
    • Email, role, plan, status, usage summary.
  • Detail view:
    • Reset password/email link.
    • Force plan change.
    • Suspend user.
    • View user’s API keys and usage metrics.

Subscription plans

  • CRUD for plans:
    • Name, description, price, limits, flags (e.g. “allow BYOK”, “priority routing”).
  • Mark certain plans as public/hidden.

Providers & keys

  • Providers list:
    • Enable/disable provider globally.
    • Adjust base URLs, timeouts.
  • Provider keys:
    • List with status and usage.
    • Ingestion batches management.
    • Buttons to test a key and refresh metadata.

System metrics

  • Global charts:
    • Requests/day across all users.
    • Cost vs revenue estimation.
    • Error rate and provider health.

11. Security, privacy & compliance

  • Encrypt provider keys at rest with strong symmetric encryption (e.g. AES‑256‑GCM).
  • Never log provider keys or user API keys in plain text.
  • Allow users to:
    • Opt out of prompt/response logging (store only metadata).
    • Delete logs (with real deletion within a defined time frame).
  • Rate limiting per user key to mitigate abuse.
  • Store minimal PII; consider GDPR requirements for EU users.

12. Modularity & future providers

Design goal: zero core changes to add a provider.

  • Provider adapter interface is the only place provider‑specific logic lives.
  • Model mapping table decides which adapter is hit.
  • Pricing, limits, and metadata are stored in DB, not hard‑coded.
  • For future providers (e.g. local models, self‑hosted):
    • Implement same adapter interface.
    • Add models to ModelMapping.

13. Implementation phases

✅ Phase 1 — Functional MVP

  • Implement:
    • Core DB schema.
    • User auth and basic dashboard.
    • Single provider (e.g. OpenAI) through adapter.
    • /v1/chat/completions + /v1/models only.
    • Basic logs and per‑user API keys.
    • Minimal admin UI for users and provider keys.

✅ Phase 2 — Multi‑provider & analytics

  • Add:
    • Anthropic, DeepSeek, Perplexity, Grok adapters.
    • ModelMapping‑based routing.
    • Provider key ingestion from .txt files.
    • Full usage logging + daily aggregates.
    • User dashboard charts and filters.

✅ Phase 3 — Competitive features

  • Implement:
    • Auto fallback routing, routing policies.
    • Advanced plan system + Stripe billing.
    • Fine‑grained per‑key limits & cost caps.
    • Better admin dashboards and global analytics.
    • Optional prompt/response logging controls.

14. Developer experience & quality

  • Use strict TypeScript and ESLint + Prettier.
  • Organize code by domain:
    • src/app (Next routes).
    • src/server (services, adapters, routing logic).
    • src/lib (shared helpers).
    • src/components (UI building blocks).
  • Provide seed script to create:
    • Default admin user.
    • Example subscription plans.
    • Example provider and model mappings.
  • Include unit tests for:
    • Provider adapters (mocking HTTP).
    • Routing logic.
    • Usage aggregation logic.
  • Include end‑to‑end tests for:
    • Basic API flow (chat completion).
    • Dashboard and admin flows (Playwright or similar).