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?
Request Flow#
When your application makes a request through Layers Gateway, here's what happens:
Authorization: Bearer lyr_live_xxx
- • Validate API key format (lyr_live_* or lyr_test_*)
- • Look up key in database
- • Return 401 if invalid/expired/revoked
- • Check requests/minute by subscription tier
- • Free: 10/min, Starter: 60, Pro: 300, Team: 1000
- • Return 429 if exceeded
- • Estimate cost based on model + max_tokens
- • Check user balance
- • Return 402 if insufficient credits
- • Route request to Hustle Together AI SDK
- • SDK handles model lookup and provider routing
- • 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
- • 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.
Request Flow: Your App → AI Gateway → AI Provider
- • Direct provider calls
- • No usage tracking
- • Good for development/testing
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:
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
}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:
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);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.
| Feature | Direct API | Layers Gateway |
|---|---|---|
| Tool call arguments | Passed through | Passed through |
| Perplexity sources/citations | Passed through | Passed through |
| Extended thinking | Passed through | Passed through |
| Token counts | Passed through | Passed through + credits |
| Provider metadata | Passed through | Passed through |
Key Implementation Files#
| File | Purpose |
|---|---|
lib/gateway/client.ts | AI SDK wrapper, provider routing, response transformation |
lib/middleware/auth.ts | API key validation, user authentication |
lib/middleware/credits.ts | Credit calculation, deduction, usage logging |
lib/middleware/rate-limit.ts | Tier-based rate limiting |
lib/pricing/sync.ts | Pricing sync from Hustle Together AI |
lib/models/registry.ts | Model 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