Layers

Gateway Architecture

Layers is an AI Gateway built on top of the Hustle Together AI SDK. It sits between your applications and AI providers, providing unified access, automatic billing, and usage tracking.

Powered by Hustle Together AI SDK - The Hustle Together AI SDK provides the model registry (40 models: 19 language, 21 image/multimodal from 6 providers), real-time pricing data synced daily from all providers, and Vercel AI Gateway integration. Layers wraps this with authentication, credit management, rate limiting, and Stripe billing.

What is Layers Gateway?#

Think of Layers as "npm for AI models" - one unified interface for all providers. Instead of managing separate API keys and tracking usage manually across Anthropic, OpenAI, Google, etc., Layers handles everything automatically.

Unified API Key

One key for all providers - no more juggling multiple credentials.

Automatic Tracking

Every API call logs tokens, costs, and credits automatically.

Credit System

Transparent pricing - 1 credit = $0.01 USD across all providers.

Centralized Enforcement

Rate limits, quotas, and billing enforced at the gateway level.

Multi-App Platform Architecture#

Layers is designed for building a multi-application AI platform where users have one account across all your apps, with a single shared credit balance.

Multiple Apps

Build 3-4+ AI-powered apps

Single Account

Users log in once

Shared Balance

Credits work everywhere

Central Billing

One place for limits

Why Gateway Architecture?

The gateway pattern provides centralized enforcement. When a user hits their credit limit, ALL apps are blocked immediately. With client-side tracking, apps could bypass limits. The gateway ensures complete control and security.

Request Flow#

When your application makes a request through Layers Gateway, here's what happens:

YOUR APPLICATION
POST /api/v1/chat
Authorization: Bearer lyr_live_xxx
LAYERS GATEWAY
layers.hustletogether.com
1. AUTH MIDDLEWARE
  • • Validate API key format (lyr_live_* or lyr_test_*)
  • • Look up key in database
  • • Return 401 if invalid/expired/revoked
2. RATE LIMIT MIDDLEWARE
  • • Check requests/minute by subscription tier
  • • Free: 10/min, Starter: 60, Pro: 300, Team: 1000
  • • Return 429 if exceeded
3. CREDIT PRE-CHECK
  • • Estimate cost based on model + max_tokens
  • • Check user balance
  • • Return 402 if insufficient credits
4. FORWARD TO HUSTLE TOGETHER AI SDK
  • • Route request to Hustle Together AI SDK
  • • SDK handles model lookup and provider routing
HUSTLE TOGETHER AI SDK
  • • Look up model in registry (40 models)
  • • Get pricing data (synced daily)
  • • Route via Vercel AI Gateway to provider:
  • • anthropic/* → Anthropic API
  • • openai/* → OpenAI API
  • • google/* → Google AI API
  • • perplexity/* → Perplexity API
  • • morph/* → Morph API
  • • bfl/* → Black Forest Labs (Flux)
  • • recraft/* → Recraft API
AI PROVIDERS (6 Total)
Anthropic, OpenAI, Google, Perplexity, Morph, BFL, Recraft
5. POST-PROCESSING (Layers)
  • • Calculate actual credits used (via SDK pricing)
  • • Deduct from user balance
  • • Log usage to database
  • • Return OpenAI-compatible response

The Layers Toggle#

In Hustle Together AI (and other apps), you'll see a "Use Layers Gateway" toggle. This controls whether requests route through Layers or directly to providers.

Toggle OFF

Request Flow: Your App → AI Gateway → AI Provider

  • • Direct provider calls
  • • No usage tracking
  • • Good for development/testing
Toggle ON

Request Flow: Your App → Layers → AI Provider

  • • Automatic usage tracking
  • • Credit billing
  • • Centralized enforcement
  • • Your brand visible to users

Technical Implementation#

Provider Selection#

When the toggle is ON, the app uses getProvider() to route requests through Layers:

lib/models/get-provider.tstypescript
import { createOpenAI } from '@ai-sdk/openai';

// Layers provider instance
const layers = createOpenAI({
  baseURL: 'https://layers.hustletogether.com/api/v1',
  apiKey: process.env.LAYERS_API_KEY,
});

export function getProvider(modelId: string, useLayers: boolean) {
  if (useLayers) {
    return layers.chat(modelId);  // → layers.hustletogether.com
  }
  return modelId;  // → Direct AI Gateway
}
app/api/chat/route.tstypescript
import { generateText } from 'ai';
import { getProvider } from '@/lib/models/get-provider';

export async function POST(req: Request) {
  const { model, prompt, useLayers } = await req.json();

  const result = await generateText({
    model: getProvider(model, useLayers),
    prompt,
  });

  return Response.json({ text: result.text });
}

Gateway Internals#

Inside Layers Gateway, requests are processed through middleware and routed to providers:

Layers Gateway: app/api/v1/chat/route.tstypescript
export async function POST(req: Request) {
  const body = await req.json();
  const apiKey = req.headers.get('Authorization');

  // 1. Authenticate
  const user = await validateApiKey(apiKey);

  // 2. Check rate limits
  const rateLimit = checkRateLimit(user.id, user.tier);
  if (!rateLimit.allowed) return rateLimit.response;

  // 3. Pre-check credits
  const estimated = estimateCredits(body.model, body.max_tokens);
  if (user.balance < estimated) return insufficientCredits();

  // 4. Call AI provider via SDK
  const result = await generateText({
    model: gateway(body.model),  // Routes based on prefix
    ...body
  });

  // 5. Calculate actual credits and deduct
  const { credits, breakdown } = calculateCreditsWithBreakdown(
    body.model,
    result.usage.promptTokens,
    result.usage.completionTokens
  );
  await deductCredits(user.id, credits);
  await logUsage({ user, model: body.model, credits, breakdown });

  // 6. Return response with Layers metadata
  return Response.json({
    ...result,
    layers: { credits_used: credits, cost_breakdown: breakdown }
  });
}

Pricing Sync#

Layers automatically syncs pricing from Hustle Together AI to ensure accurate cost calculations:

// Pricing is synced from Hustle Together AI
// Source: https://ai.hustletogether.com/api/pricing
// Frequency: Every 24 hours (cached)

// When calculating credits:
const syncedPricing = getSyncedModelPricing(model);
const baseCost = (inputTokens / 1000) * syncedPricing.input
               + (outputTokens / 1000) * syncedPricing.output;
const credits = (baseCost / 0.01) * (1 + marginPercent / 100);
See Billing & Credits for full pricing documentation.

Transparent Pass-Through#

Layers Gateway preserves all provider-specific response fields. This means features like Perplexity sources, Claude thinking blocks, and tool call arguments work identically whether you use Layers or direct provider calls.

FeatureDirect APILayers Gateway
Tool call argumentsPassed throughPassed through
Perplexity sources/citationsPassed throughPassed through
Extended thinkingPassed throughPassed through
Token countsPassed throughPassed through + credits
Provider metadataPassed throughPassed through

Key Implementation Files#

FilePurpose
lib/gateway/client.tsAI SDK wrapper, provider routing, response transformation
lib/middleware/auth.tsAPI key validation, user authentication
lib/middleware/credits.tsCredit calculation, deduction, usage logging
lib/middleware/rate-limit.tsTier-based rate limiting
lib/pricing/sync.tsPricing sync from Hustle Together AI
lib/models/registry.tsModel definitions with capabilities and pricing

Your Brand, Your Infrastructure#

When using Layers Gateway, all AI requests flow through layers.hustletogether.com. This is YOUR infrastructure, YOUR brand.

  • Your API - Apps integrate with layers.hustletogether.com
  • Your Relationship - You own the customer relationship
  • Your Features - Add caching, fallbacks, rate limiting
  • Your Pricing - Set margins, offer volume discounts
  • Your Control - Swap providers without apps knowing

Next Steps#