Commercial Large Language Model (LLM) labs and cloud platform providers regularly offer complimentary access tiers to developers. These free tiers allow a few requests per minute or a few million tokens per month per provider. In isolation, any individual free tier acts as a constrained sandbox. However, aggregated across the AI landscape, these tiers constitute roughly 7.4 billion tokens per month of available inference capacity across 34 providers and 635 free model endpoints.
┌─────────────────────────────────────────────────────────────────────────────────────────┐
│ SYSTEM BOUNDARY: FreeLLMAPI │
│ │
│ ┌───────────────────────┐ ┌────────────────────────────────────────────────┐ │
│ │ Client Layer │ │ FreeLLMAPI Gateway Core │ │
│ │ │ │ │ │
│ │ • Claude Code │ │ ┌──────────────────────────────────────────┐ │ │
│ │ • Codex CLI │ │ │ Express Proxy (:3001) │ │ │
│ │ • Aider / Cursor │ Bearer │ │ • /v1/chat/completions │ │ │
│ │ • DeepSeek Harness │ ───────> │ │ • /v1/messages, /v1beta, /api/* │ │ │
│ │ • Custom Apps / SDKs │ │ └───────────────────┬──────────────────────┘ │ │
│ └───────────────────────┘ │ │ │ │
│ │ ▼ │ │
│ │ ┌──────────────────────────────────────────┐ │ │
│ │ │ Router & Policy Engine │ │ │
│ │ │ • Thompson-Sampling Bandit │ │ │
│ │ │ • Per-Key Rate Ledger (SQLite/Memory) │ │ │
│ │ │ • Failover & Cooldown Pipeline │ │ │
│ │ │ • Prompt Compression Pipeline │ │ │
│ │ └───────────────────┬──────────────────────┘ │ │
│ └──────────────────────┼─────────────────────────┘ │
└────────────────────────────────────────────────────────────┼────────────────────────────┘
│
Outbound TLS / SOCKS / Relay │
▼
┌─────────────────────────────────────────┐
│ External Provider Fleet │
│ │
│ Google AI Studio │ Groq │ Cerebras │
│ Cloudflare │ Z.ai │ OpenRouter │
│ HuggingFace │ NVIDIA NIM │ ... │
└─────────────────────────────────────────┘
Managing this distributed network manually introduces significant complexity: developers must maintain distinct SDKs, handle incompatible authentication protocols, track heterogeneous rate limits (requests/tokens per minute/day), and manage provider outages. FreeLLMAPI solves this by operating as a local-first, single-user, self-hosted gateway proxy that encapsulates these providers behind a unified OpenAI-compatible /v1 protocol surface.
System Scope and Explicit Boundaries
- In-Scope : Local-first request routing, protocol translation (OpenAI, Anthropic, Gemini, Ollama), rate-limit tracking, Thompson-sampling candidate selection, transparent retries/failover, AES-256-GCM encrypted credential storage, prompt compression, and client setup automation.
- Out-of-Scope (Documented Non-Support): Multi-tenant user management, native user-level billing, content moderation endpoints (/v1/moderations), and multiple completions per request ((n > 1)).
Global Architecture & Component Decomposition
FreeLLMAPI is structured as a TypeScript monorepo. It runs as an Express-based Node.js server paired with a React/Vite/shadcn management dashboard and an optional Electron desktop app.
┌────────────────────────────────────────────────────────────────────────────────────────┐
│ FreeLLMAPI Monorepo │
│ │
│ ┌───────────────────────────┐ ┌──────────────────────────┐ ┌─────────────────┐ │
│ │ server/ │ │ client/ │ │ desktop/ │ │
│ │ • Express HTTP Router │ │ • React + Vite Admin UI │ │ • Electron App │ │
│ │ • Provider Adapters │ │ • 60-Locale i18n System │ │ • Tray Popover │ │
│ │ • SQLite Storage Engine │ │ • Analytics & Playground│ │ • Local Auto-Auth │
│ └─────────────┬─────────────┘ └────────────┬─────────────┘ └────────┬────────┘ │
│ │ │ │ │
│ └──────────────────────┬────────┴───────────────────────────┘ │
│ ▼ │
│ ┌──────────────────────────────────────────────────────────────────────────────────┐ │
│ │ shared/ & cli/ │ │
│ │ • Schema definitions, IPC types, setup generators (`setup-claude`, etc.) │ │
│ └──────────────────────────────────────────────────────────────────────────────────┘ │
└────────────────────────────────────────────────────────────────────────────────────────┘
Core Components Walkthrough
1. Express Gateway Proxy (server/src/index.ts)
- Purpose : Ingress controller for incoming client requests, handling protocol routing, authentication, and HTTP response streaming.
- Inputs : Client HTTP requests containing standard Bearer tokens (freellmapi-...), custom headers (X-FreeLLM-Compress, X-FreeLLM-Task-Type), or Anthropic/Gemini headers.
- Outputs : Server-Sent Events (SSE) stream, JSON completions, binary media streams (MP4, WAV, PNG), or protocol error objects.
- Dependencies : better-sqlite3, Express router, provider adapters, compression service, rate-limit ledger.
- Callers : Standard AI SDKs, coding agents (Claude Code, Cursor, Aider, DeepSeek Harness), HTTP clients.
- Downstream Consumers : Upstream cloud providers (Groq, Google, Cerebras, etc.).
- State : Stateless worker thread delegating state access to SQLite and in-memory ledgers.
- Configuration : .env (PORT, HOST_BIND, TRUST_PROXY), FREEAPI_CONFIG_PATH.
- Protocol : HTTP/1.1, HTTP/2, SSE, NDJSON.
- Failure Behavior : Converts internal routing failures to standard OpenAI JSON errors (502 Bad Gateway, 429 Too Many Requests, or 400 Bad Request).
- Security : Validates incoming Bearer tokens against SQLite hashes; strips internal keys before outbound transit.
- Observability : Emits X-Routed-Via, X-Fallback-Attempts, X-Fallback-Trail, and optional X-Fallback-Detail headers.
- Extension Points : Middleware pipeline hooks for new route registrations.
2. Thompson-Sampling Bandit Router (server/src/services/router.ts)
- Purpose : Selects the optimal model/provider endpoint for each request based on real-time health, performance statistics, and user strategy preferences.
- Inputs : Target model identifier (auto, auto:smart, gemini-2.5-flash), key availability, rate-limit status, request task-type hint.
- Outputs : Ranked candidate chain specifying (platform, modelId, keyId, providerAdapter).
- Dependencies : Rate-limit ledger, SQLite database, Health service.
- Callers : Express ingress routes.
- Downstream Consumers : Provider Adapters (server/src/providers/*.ts).
- State : Reads rolling execution statistics (latency p50/p95, success rate) stored in memory and SQLite.
- Configuration : Active fallback chain, routing strategy (balanced, smart, fast, reliable, cheap), profile overrides.
- Protocol : Internal TypeScript async calls.
- Failure Behavior : If no candidate satisfies the criteria, it triggers a chain rejection (400 or 429).
- Security : Evaluates permission scopes attached to individual keys.
- Observability : Records candidate evaluation timings and logs routing choices to request analytics.
- Extension Points : Custom strategy functions registered in the routing table.
3. Per-Key Rate-Limit Ledger (server/src/services/ratelimit.ts)
- Purpose : Tracks real-time API key quotas across RPM/RPD and TPM/TPD limits to prevent upstream HTTP 429 rate-limit errors.
- Inputs : Request token estimates, provider response headers, HTTP 429 status signals.
- Outputs : Boolean readiness flag (ready, exhausted, needsKey) and minimum cooldown delay.
- Dependencies : better-sqlite3.
- Callers : Bandit Router.
- Downstream Consumers : SQLite database table api_keys.
- State : Dual state — in-memory atomic counters backed by durable SQLite transaction logs.
- Configuration : monthlyRequestCap, monthlyTokenCap, provider-declared rate limit parameters.
- Protocol : Internal TS calls.
- Failure Behavior : Fails conservative (blocks candidate selection) when usage reaches 100% of reported ceiling.
- Security : Enforces isolation between distinct provider credentials.
- Observability : Exposes real-time key utilization via GET /api/free-tier.
- Extension Points : Custom quota window calculators per provider.
Core Routing Mechanics & State Management
Thompson-Sampling Bandit Router & Steering Strategies
The core routing engine optimizes candidate selection across heterogeneous, non-stationary provider free tiers. It maintains dynamic probability distributions for each model endpoint based on observed performance metrics.
- GitHub - tashfeenahmed/freellmapi: 7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
- Free LLM API model catalog · FreeLLMAPI
Incoming Request
│
▼
Inspect Target Model Suffix
│
┌─────────────────────┼─────────────────────┐
▼ ▼ ▼
`auto` `auto:<profile>` `model-id`
(Active Chain) (Named Profile) (Direct Lookup)
│ │ │
└─────────────────────┼─────────────────────┘
│
▼
Filter Eligible Candidate Pool
• Key Enabled & Probed Healthy
• Current Usage < Rate Caps
• Task Type Matching (Vision/Code)
│
▼
Execute Thompson Sampling
Probability Score = f(R, S, I, W)
R: Live Reliability (Success %)
S: Throughput & TTFB Metrics
I: Model Intelligence Benchmark
W: Strategy Bias Weighting
│
▼
Sorted Fallback Priority Chain
Routing Strategies (auto:*)
Users steer candidate ranking on a per-request basis by appending a suffix to the auto model string:
- auto / auto:balanced : Default blend balancing reliability first, splitting remaining weight between speed and intelligence.
- auto:smart / auto:smartest : Biases weights toward model capability and intelligence scores.
- auto:fast / auto:fastest : Biases weights toward measured throughput and time-to-first-byte (TTFB).
- auto:reliable : Biases candidate selection toward recent request success rates.
- auto:cheap / auto:budget : Selection tuned for zero cost impact.
- auto: : Routes through a named fallback-chain profile configured in the dashboard (e.g., auto:coding).
Task-Type Routing Biasing (X-FreeLLM-Task-Type)
The proxy supports request-level task classification:
- Headers set to code, chat, or auto adjust strategy weights.
- A code hint shifts candidate ranking weights by 30% toward intelligence at the cost of speed, as inaccurate code generation carries a higher penalty than higher latency.
- The task weight fraction is operator-configurable via PUT /api/settings/task-weight-share ({"share": 0.0 - 1.0}, default 0.3).
- Automatic task detection scans prompts for explicit code markers (fenced code blocks, function signatures, stack frames, file/line references such as file.ts:214) or active tool calls.
Per-Key Rate-Limit Ledger & UTC Resets
To operate within provider free tiers, FreeLLMAPI tracks usage across four dimensions per key: RPM, RPD, TPM, and TPD.
Incoming Completion Request
│
▼
Estimate Token Overhead (chars / 4)
│
▼
Check In-Memory Ledger State
│
┌──────────────┴──────────────┐
▼ ▼
Quota Available Quota Exhausted
│ │
▼ ▼
Reserve Capacity Allowance Cool Down Key
│ Mark State: `exhausted`
▼ │
Execute Outbound Call ▼
│ Try Next Candidate
┌─────────┴─────────┐
▼ ▼
Success (200) Error (429)
│ │
▼ ▼
Reconcile Actual Release Reservation
Token Usage & Trigger Cooldown Period
Commit Ledger (Exponent Backoff)
- Reservation Phase : Before dispatching a request, the router estimates token overhead ((\approx \text{characters} / 4)) and reserves capacity in the ledger.
- Reconciliation Phase : Upon request completion, actual token counts reported by the provider update the ledger. If actual tokens exceed reservations, the ledger records the overflow and updates the remaining quota balance.
- UTC Reset Protocol : Most cloud providers reset daily quotas at 00:00 UTC. At UTC midnight, the ledger clears daily accumulated RPD/TPD counters, restoring top-tier model endpoints to ready state.
Failover Engine & Degraded Mode Operations
When a provider request fails due to rate limits (HTTP 429), server errors (HTTP 5xx), or network timeouts, the failover engine executes up to 20 retries within the request's wall-clock budget.
Client Request
│
▼
┌─────────────────┐ Success (HTTP 200)
│ Attempt Hop N ├──────────────────────────────┐
└────────┬────────┘ │
│ Failure (HTTP 429 / 5xx / Timeout) │
▼ ▼
┌─────────────────┐ Return Response
│ Cool Down Key │ Append Trail
└────────┬────────┘ Headers
│ ▲
▼ │
┌─────────────────┐ │
│ Select Hop N+1 │ │
└────────┬────────┘ │
│ │
├─ Attempt < 20 ──> Retry Loop ─────────┘
│
└─ Attempt == 20 ─> Return HTTP 429/502 Error
Failover Lifecycle
- The failed key is assigned a cooldown period based on the provider’s Retry-After header or an exponential backoff baseline.
- The request is dispatched to the next candidate model in the fallback chain.
- The response is updated with diagnostic fallback headers:
- X-Routed-Via: Identifies the final serving endpoint (platform/model).
- X-Fallback-Attempts: Counts total failed attempts.
- X-Fallback-Trail: Summarizes failure reasons per hop (e.g., groq/llama-3.3-70b key1=rate_limited; google/gemini-2.5-flash key2=timeout).
- X-Fallback-Detail (enabled via FALLBACK_DETAIL_HEADER=1): Appends hop offsets and execution durations (t=0+39000ms msg=Groq API error 429).
Degraded Mode
As daily allowances for top-tier models exhaust over the course of a day, the candidate pool gracefully degrades to smaller models (e.g., falling back from frontier reasoning models to lighter models) until quotas reset at UTC midnight.
Model Catalog Synchronization & Signed Feed
FreeLLMAPI dynamically updates its model definitions, quota limits, and provider quirks without requiring full application updates.
freellmapi.co Catalog Server
│
│ Signed JSON Feed
│ (Ed25519 Signature)
▼
Local FreeLLMAPI Server
│
▼
Verify Signature against Pinned Key
│
┌─────────────┴─────────────┐
▼ ▼
Valid Signature Invalid Signature
│ │
▼ ▼
Apply Updates to SQLite Abort Sync Operation
(Preserve User Tweaks) Log Security Alert
- Signature Verification : Catalog feeds are signed with an Ed25519 key. Updates are verified before applying changes to freeapi.db.
- User Customization Protection : User settings (enabled status, custom provider definitions, profile chains) are preserved during catalog updates.
- Tier Distribution :
- Free Snapshot : Updated monthly; new models appear 30 days after release.
- Premium Live Feed ($19/yr or $49 lifetime): Syncs twice daily to deliver same-day model additions and quota adjustments.
End-to-End Request Lifecycle & Protocol Translation
Step-by-Step Request Processing Lifecycle
[Client App] [Express Gateway] [Router / Ledger] [Provider Adapter] [Upstream API]
│ │ │ │ │
│ 1. POST /v1/chat/compl │ │ │ │
─────────────────────────>│ │ │ │
│ │ 2. Validate Bearer Token │ │ │
│ │ 3. Run Compression │ │ │
│ │─────────────────────────>│ │ │
│ │ │ 4. Select Candidate │ │
│ │ │ 5. Reserve Token Cap │ │
│ │ │──────────────────────>│ │
│ │ │ │ 6. Decrypt API Key │
│ │ │ │ 7. Format Payload │
│ │ │ │────────────────────>│
│ │ │ │ │ 8. Process
│ │ │ │<────────────────────│
│ │ │ │ 9. Parse Response │
│ │ │<──────────────────────│ │
│ │ │ 10. Reconcile Tokens │ │
│ │<─────────────────────────│ │ │
│ │ 11. Inject Headers │ │ │
│<────────────────────────│ │ │ │
│ 12. Stream HTTP 200 OK │ │ │ │
- Client Ingress : Client sends HTTP request to /v1/chat/completions containing Bearer auth token, payload parameters, and optional control headers.
- Authentication & Validation : server/src/index.ts validates the Bearer token against stored API key hashes.
- Context Optimization : If enabled, prompt compression runs to eliminate redundant content before token estimation.
- Candidate Selection : The Thompson-sampling router identifies candidate models and selects an available key based on ledger status.
- Key Decryption : The provider adapter decrypts the target API key in memory using AES-256-GCM.
- Payload Translation : Request parameters are translated to the target provider’s native format (e.g., converting OpenAI tool calls to Gemini functionDeclarations).
- Outbound Execution : Request is dispatched to the upstream API using configured proxy transports.
- Response Processing : Streamed or unary response tokens are parsed and converted back to OpenAI or Anthropic format.
- Ledger Reconciliation : Observed token usage updates the rate-limit ledger.
- Egress Delivery : Response streams to the client with X-Routed-Via and diagnostic fallback headers attached.
Protocol Adapters Specification
Client Wire Formats
┌──────────────────┬──────────────────┬──────────────────┐
▼ ▼ ▼ ▼
OpenAI `/v1` Anthropic `/v1` Gemini `/v1beta` Ollama `/api`
│ │ │ │
└──────────────────┼──────────────────┴──────────────────┘
│
▼
Unified Ingress Normaliser
│
▼
Internal Canonical Request
│
▼
Provider Wire Translation Engine
│
┌──────────────────┼──────────────────┬──────────────────┐
▼ ▼ ▼ ▼
OpenAI Format Anthropic Format Gemini JSON Format Custom HTTP
(Groq, OpenRouter) (Claude Native) (Google AI Studio) (Ollama/vLLM)
1. OpenAI /v1 Compatibility Engine
Provides support for standard chat completions (/v1/chat/completions), completion autocomplete (/v1/completions), models listing (/v1/models), and responses (/v1/responses).
2. Anthropic Messages Surface (/v1/messages)
Allows tools like Claude Code and the Anthropic SDK to interface with the gateway.
- Client requests point to root origin http://localhost:3001.
- Authentication uses x-api-key or Authorization: Bearer.
- Model mappings on the Keys → Anthropic dashboard tab route requests to default or pinned models.
- Implements token counting (POST /v1/messages/count_tokens) and Anthropic-formatted model lists.
# Illustrative: Direct Anthropic Protocol Ingress Call
curl http://localhost:3001/v1/messages \
-H "x-api-key: freellmapi-your-unified-key" \
-H "anthropic-version: 2023-06-01" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-sonnet-4-5",
"max_tokens": 256,
"messages": [{"role": "user", "content": "Analyze system load"}]
}'
3. Native Gemini Wire Protocol (/v1beta)
Provides direct compatibility for Google Gemini SDKs and the Gemini CLI:
- Endpoints: POST /v1beta/models/{model}:generateContent, streamGenerateContent, and countTokens.
- Accepts authentication via x-goog-api-key, Authorization: Bearer, or URL parameter ?key=.
- Translates native contents, parts, inlineData, functionDeclarations, and thinking budget parameters.
4. Ollama Emulation Engine (/api/*)
Enables local development tools (e.g., Zed, JetBrains AI Assistant) to connect without modifying underlying client integrations:
- Endpoints: /api/tags, /api/chat, /api/generate, /api/show, /api/version, /api/embed, and /api/embeddings.
- Data Format: Uses NDJSON (Newline Delimited JSON) streaming.
- Security Modes: open-loopback (restricts access to 127.0.0.1 / ::1) or key-required (Authorization: Bearer).
Multimodal, Media & Vector Processing Pipeline
Vision Input Normalization
Requests containing image content blocks (image_url with data:image/...;base64 or HTTP URLs) are processed through vision-capable endpoints:
Input Request with Image Data
│
▼
Inspect Payload for `image_url` Blocks
│
▼
Filter Candidate Pool: Retain Only Models with Vision Badge
(Gemini 2.5/3.x, Llama 4 Scout/Maverick, GLM-4.6V, etc.)
│
┌─────────┴─────────┐
▼ ▼
Vision Models No Vision Models
Available Available
│ │
▼ ▼
Route to Model Return HTTP 422
`code: "no_vision_model"`
If no vision-enabled models are active in the chain, the gateway returns HTTP 422 (code: "no_vision_model") to avoid stripping image context.
Media Generation Pipeline
- Endpoints : /v1/images/generations, /v1/videos/generations, and /v1/audio/speech.
- Video Workflow : Video generation jobs (served by HuggingFace/fal-ai queue or Pollinations) are bounded to a 5-minute timeout (VIDEO_FETCH_TIMEOUT_MS).
- Socket Disconnect Handling : If a client disconnects mid-generation, socket close events trigger job cancellation to prevent wasted upstream polling.
- Binary Stream Return : Completed jobs return raw MP4/WAV/PNG binary streams with X-Provider and X-Model tracking headers.
Vector Embeddings Isolation Engine (/v1/embeddings)
Vector embeddings enforce strict model isolation to prevent index corruption:
Incoming Embedding Request
│
▼
Identify Specified Vector Family
(e.g., `bge-m3`, `gemini-embedding-001`)
│
▼
Filter Candidate Providers
Must Support EXACT Family & Dims
│
┌───────────────────────────┴───────────────────────────┐
▼ ▼
Candidate 1 Fails (429) Candidate 2 Succeeds
Fall over to Candidate 2 Generate Vectors & Return
(SAME Family & Dimensions) (Zero Dimensional Drift)
To prevent corrupting vector indices, failover for /v1/embeddings never switches across different model families. Failovers are restricted to providers serving the identical model family and dimensionality.
Tool Calling, Tool-Call Rescue & Gemini Grounding
Tool-Call Rescue Engine (server/src/lib/tool-call-rescue.ts)
When models output tool calls as unformatted plain text instead of structured JSON, the rescue engine parses the response and converts it into valid OpenAI-style tool_calls objects. Tool-bearing requests are restricted to endpoints with verified tool-use support.
Gemini Google Search Grounding Translation
When clients request a tool named google_search via the OpenAI API interface, FreeLLMAPI translates it into Gemini's native web search grounding protocol:
# Illustrative: Triggering Gemini Web Search Grounding via OpenAI SDK
from openai import OpenAI
client = OpenAI(
base_url="http://localhost:3001/v1",
api_key="freellmapi-your-unified-key",
)
response = client.chat.completions.create(
model="gemini-2.5-flash",
messages=[{"role": "user", "content": "What were today's top tech releases?"}],
tools=[{"type": "function", "function": {"name": "google_search", "parameters": {}}}],
)
print(response.choices.message.content)
Prompt Compression Pipeline
The prompt compression pipeline reduces context size for long-running agent sessions before token estimation and routing, expanding eligibility for smaller-context models. Provider responses are left uncompressed.
Incoming Request Payload
│
▼
Evaluate Compression Mode
(Env / Dashboard / Header Override)
│
┌───────────────┬────────────┴────────────┬───────────────┐
▼ ▼ ▼ ▼
Mode: `off` Mode: `lossless` Mode: `standard` Mode: `aggressive`
No-op • Block Deduplication • Lossless • Standard
• Whitespace Clean • Tool Output • Turn Condensation
• Reversible JSON Filtering • Lexical Filtering
Tables • Stale Read • Hard Token Target
Supersession
│ │ │ │
└───────────────┼─────────────────────────┴───────────────┘
│
▼
Run Fail-Open Fidelity Gate Check
1. All numbers & diff hunks present?
2. Security/constraint text 100% intact?
3. >= 90% JSON keys preserved?
4. >= 95% protected spans intact?
│
┌─────────┴─────────┐
▼ ▼
Gate Passed Gate Failed
│ │
▼ ▼
Apply Compressed Discard Draft
Payload Context Fall back to Original
Four Compression Tiers
- off : Bypasses request transformation.
- lossless : Executes repeated-block deduplication, whitespace normalization, and reversible homogeneous JSON table encoding.
- standard : Includes lossless transformations plus command-aware tool-output filtering and stale file-read supersession.
- aggressive : Includes standard transformations plus turn condensation, lexical relevance filtering, and target token truncation.
Fail-Open Fidelity Gate & Protected Spans
The pipeline is designed to fail open. If an engine throws an exception, expands payload size, or fails the fidelity gate, its draft is discarded and the system falls back to the uncompressed context.
Validation Gate Rules
To pass validation, compressed output must meet the following criteria:
- 100% preservation of distinct numeric literals and git diff hunks.
- 100% preservation of security instructions, explicit constraints, and error messages.
- (\ge) 90% preservation of JSON object keys.
- (\ge) 95% preservation of protected spans (code fences, file paths, URLs, stack traces, key/value pairs, tool metadata).
- 100% structural validity of tool-call and tool-result JSON envelopes.
Custom JSON Filters & Project Trust Mechanics
Custom tool-output filters can be loaded from two filesystem locations:
- User Filters : ~/.freellmapi/filters/*.json (always trusted).
- Project Filters : .freellmapi/filters.json (disabled by default; requires enabling Trust project filter files in the admin dashboard).
Security, Storage & Key Management
AES-256-GCM Envelope Encryption & Storage Schema
Provider credentials and security tokens stored in SQLite (freeapi.db) are encrypted at rest using AES-256-GCM envelope encryption.
┌─────────────────────────────────────────────────────────────────────────────────┐
│ SQLite Database (`freeapi.db`) │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ Table: `api_keys` │ │
│ │ │ │
│ │ • `id` : INTEGER PRIMARY KEY │ │
│ │ • `platform` : TEXT (e.g., 'groq', 'google') │ │
│ │ • `encrypted_key` : BLOB (AES-256-GCM Ciphertext) │ │
│ │ • `iv` : BLOB (Initialization Vector) │ │
│ │ • `auth_tag` : BLOB (GCM Authentication Tag) │ │
│ │ • `label` : TEXT │ │
│ │ • `monthly_req_cap` : INTEGER DEFAULT 0 │ │
│ │ • `monthly_tok_cap` : INTEGER DEFAULT 0 │ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘
▲
│ Decrypted in-memory per request
│ Key: ENCRYPTION_KEY (.env)
▼
┌───────────────────────────┐
│ Node.js Application RAM │
│ (Plaintext Key Ephemeral) │
└───────────────────────────┘
OS Storage Paths (freeapi.db, config.json, logs/freeapi.log)
- Windows : %APPDATA%\FreeLLMAPI.
- macOS : ~/Library/Application Support/FreeLLMAPI/.
- Linux : ~/.config/FreeLLMAPI/.
- Docker / Linux Server : /app/server/data/freeapi.db (override via FREEAPI_DB_PATH).
Key Rotation Protocol & Backup Recovery
Key Rotation Script
Changing ENCRYPTION_KEY requires re-encrypting stored database secrets with the old key before applying the new key:
# 1. Stop the running FreeLLMAPI instance
docker compose down
# 2. Generate a new 32-byte hex encryption key
NEW_KEY="$(node -e 'console.log(require("crypto").randomBytes(32).toString("hex"))')"
# 3. Perform a dry-run re-encryption check
cd server
ENCRYPTION_KEY=<old_key> npm run rotate-encryption-key -- --new-key "$NEW_KEY" --dry-run
# 4. Execute key re-encryption
ENCRYPTION_KEY=<old_key> npm run rotate-encryption-key -- --new-key "$NEW_KEY"
# 5. Update .env with ENCRYPTION_KEY=$NEW_KEY and restart
docker compose up -d
Database Backups (/api/backups)
The backup system creates encrypted SQL dumps (DUMP_FORMAT = 1) that include a SHA-256 fingerprint of the encryption key in their header. Restoring a backup requires an exact match between the active ENCRYPTION_KEY fingerprint and the dump header; mismatched keys trigger an HTTP 409 error.
Authentication, Authorization & URL Tokens
Ingress Authentication
- Server Dashboard : Authenticated via email/password sessions. If credentials are lost, requesting a password reset prints a 10-character single-use code to the server logs (valid for 15 minutes).
- Desktop Application : Uses a zero-password model, auto-authenticating the dashboard with an internal local account.
- API Ingress : Authenticated using a single unified Bearer token (freellmapi-...).
Revocable URL Tokens (/v1/t/{token}/*)
For clients that cannot supply custom HTTP authorization headers, FreeLLMAPI provides tokenized URL routing:
- Endpoints: /v1/t//chat/completions, /v1/t//models, /v1/t//responses.
- Security Model: Tokens are stored as SHA-256 hashes in SQLite and can be revoked individually from the dashboard.
Network Transports & Proxy Infrastructure
Forward Proxy Chain & System Auto-Detection
Outbound provider traffic supports HTTP, HTTPS, SOCKS4, SOCKS4a, SOCKS5, and SOCKS5h proxies via PROXY_URL. SOCKS5h/4a resolve DNS remotely on the proxy server.
Outbound Request Dispatcher
│
▼
Is `PROXY_URL` Explicitly Set?
│
┌──────────────┴──────────────┐
▼ ▼
YES NO
│ │
▼ ▼
Route via Specified Inspect Environment:
SOCKS/HTTP Proxy `ALL_PROXY` -> `HTTPS_PROXY` -> `HTTP_PROXY`
│
┌──────────┴──────────┐
▼ ▼
FOUND NOT FOUND
│ │
▼ ▼
Route via Env Run Native OS System
Proxy Auto-Detection Fallback
(scutil / WinReg / gsettings)
Resolution Chain
- Explicit PROXY_URL defined in .env or Key settings.
- Environment variables: ALL_PROXY (\rightarrow) HTTPS_PROXY (\rightarrow) HTTP_PROXY.
- Native OS Auto-Detection Fallback (detectSystemProxy in server/src/lib/proxy.ts):
- macOS : Parses scutil --proxy.
- Windows : Reads ProxyEnable and ProxyServer from the System Registry.
- Linux : Queries gsettings for GNOME proxy configurations.
Fetch Relay Transport (PROXY_MODE=fetch-relay)
Fetch Relay enables routing outbound requests through custom edge workers (e.g., Cloudflare Workers) to bypass regional IP restrictions.
[FreeLLMAPI Gateway] ──> [Fetch Relay (Cloudflare Worker)] ──> [Upstream Provider]
Headers: Headers: Direct HTTPS
• Fetch-Relay-Target • Strips Fetch-Relay-*
• Fetch-Relay-Auth • Applies Upstream Auth Key
- Configuration : PROXY_MODE=fetch-relay, PROXY_URL=, FETCH_RELAY_TOKEN=.
- Hop Headers : Requests pass Fetch-Relay-Target (upstream target URL) and Fetch-Relay-Authorization (Bearer ) headers.
- Security Controls : The relay worker strips Fetch-Relay-* hop headers before forwarding requests upstream, blocks loopback/metadata targets, and streams responses without buffering.
Inbound Trust Proxy (TRUST_PROXY)
Inbound IP evaluation for rate limiting (PROXY_RATE_LIMIT_RPM, ADMIN_RATE_LIMIT_RPM) is managed via TRUST_PROXY:
- false (default): Ignores X-Forwarded-For headers.
- true: Trusts all upstream proxies.
- : Trusts a specific number of proxy hops from the socket peer.
- : Restricts trust to specific IP addresses or subnet ranges.
Developer Workflows, Agent Integrations & CLI Generators
Automated Setup CLI Architecture
FreeLLMAPI provides automated setup generators (npx freellmapi setup-) that configure third-party developer tools.
Execute `npx freellmapi setup-<agent>`
│
▼
Fetch Live Catalog from Server (`/v1/models`)
│
▼
Inspect Target Agent Configuration File
│
▼
Create Timestamped Backup of Existing Config
│
▼
Perform Non-Destructive Structural Merge
(Preserve Custom Keys, Comments & Profiles)
│
▼
Write Updated Config File (Permissions 0600)
CLI Command Matrix
Detailed Agent Configuration Walkthroughs
1. Claude Code Launcher (Zero-Persistence Mode)
Launches Claude Code without storing credentials in setting files on disk:
# macOS / Linux (Bash)
export ANTHROPIC_BASE_URL=http://localhost:3001
export ANTHROPIC_AUTH_TOKEN=freellmapi-your-unified-key # Must use AUTH_TOKEN, NOT API_KEY
claude
Note: ANTHROPIC_AUTH_TOKEN must be used instead of ANTHROPIC_API_KEY. Setting ANTHROPIC_API_KEY causes Claude Code to treat the connection as a direct first-party Anthropic endpoint, leading to authentication conflicts.
2. DeepSeek Harness Integration (setup-dsh)
- Config Path : $DSH_HOME/settings.yaml (default ~/.dsh/settings.yaml).
- Credentials Path : $DSH_HOME/.env (FREELLMAPI_API_KEY, file mode 0600).
- Structure : Adds a route under llm-pi-ai.providers configured with api: openai-completions and /v1 endpoint routing.
# Illustrative: Merged DSH settings.yaml structure
llm-pi-ai:
providers:
freellmapi:
api: openai-completions
baseUrl: "http://localhost:3001/v1"
models:
- id: "auto"
displayName: "FreeLLMAPI Auto Router"
contextWindow: 131072
3. OpenClaw Setup (setup-openclaw)
- Config Path : ~/.openclaw/openclaw.json (JSON5 format).
- Credentials Path : ~/.openclaw/.env (FREELLMAPI_API_KEY, file mode 0600).
- Structure : Injects a freellmapi provider block into models.providers referencing ${FREELLMAPI_API_KEY} and sets default routing under agents.defaults.model.primary to freellmapi/auto. Includes a static header User-Agent: openclaw.
Context Handoff Protocol
When a failover occurs mid-conversation, the replacement model may lack prior context state. Enabling FREELLMAPI_CONTEXT_HANDOFF=on_model_switch injects a system note into the payload to preserve conversation continuity:
FreeLLMAPI context handoff:
You are taking over an ongoing conversation from another model (groq:llama-3 -> google:gemini-flash).
Continue the user's task using the conversation context already provided in this request.
Do not restart the task, re-ask already answered setup questions, or discard prior tool results.
Respect the user's latest message as the highest-priority instruction.
Recent session summary:
User: ...
Assistant: ...
- Session Tracking : Tracks active conversation sessions in memory using an LRU cache (3-hour TTL) keyed by X-Session-Id or a SHA-1 hash of the initial user prompt.
- Injection Conditions : Appended only when a failover switches models mid-conversation. Skipped for first-turn requests or same-model continuations.
Model Context Protocol (MCP) Integration
FreeLLMAPI includes a built-in Model Context Protocol (MCP) server running at /mcp, allowing coding agents to inspect gateway state during execution.
┌────────────────────────┐ JSON-RPC over Streamable HTTP ┌────────────────────────┐
│ Coding Agent │ ─────────────────────────────────────> │ FreeLLMAPI MCP Server │
│ (Claude Code / Cursor)│ <───────────────────────────────────── │ Path: `/mcp` │
└────────────────────────┘ └───────────┬────────────┘
│
▼
┌────────────────────────┐
│ Exposed MCP Tools │
│ • `get_usable_models` │
│ • `get_health_status` │
│ • `compression_stats` │
└────────────────────────┘
MCP Server Architecture & Activation
- Endpoint : POST /mcp (using JSON-RPC 2.0 over Streamable HTTP).
- Authentication : Requires Authorization: Bearer freellmapi-....
- Activation Switch : Disabled by default on new installs. Toggled via dashboard under Agent compatibility or via API (PUT /api/settings/enable-mcp, {"enabled": true}). When disabled, /mcp endpoints return HTTP 403 with a JSON-RPC error payload.
# Registering the FreeLLMAPI MCP Server with Claude Code
claude mcp add --transport http freellmapi http://localhost:3001/mcp \
--header "Authorization: Bearer freellmapi-your-unified-key"
Introspection Tools
Agents can invoke MCP tools to inspect gateway capabilities mid-session:
- get_usable_models: Returns currently available models, context lengths, and tool/vision flags.
- get_health_status: Returns live provider latency, success rates, and rate-limit cooldown states.
- compression_stats: Returns rolling metrics from the prompt compression engine (tokens saved, gate discards).
Operational Deployment, Configuration & Observability
Environment Variables Surface
Declarative Startup Configuration (freellmapi.config.json)
For automated server deployments, FreeLLMAPI can apply a declarative configuration on startup via FREEAPI_CONFIG_PATH:
{
"keys": [
{ "platform": "groq", "key": "gsk_example_key_string", "label": "primary-groq" },
{ "platform": "google", "key": "AIzaSy_example_key_string", "enabled": true }
],
"customProviders": [
{
"baseUrl": "http://host.docker.internal:11434/v1",
"label": "Local Ollama Endpoint",
"models": [
{ "model": "llama3.1:8b", "displayName": "Llama 3.1 8B Local", "supportsTools": true }
]
}
],
"routing": {
"strategy": "balanced"
}
}
Failure Modes, Edge Cases & Mitigation Matrix
Architectural Trade-offs, Performance Analysis & Limitations
Trade-off Matrix
┌───────────────────────────────────────────────┬───────────────────────────────────────────────┐
│ Design Advantage │ Architectural Trade-off │
├───────────────────────────────────────────────┼───────────────────────────────────────────────┤
│ Zero Cost Inference: Aggregates free tiers │ No SLA / Variable Latency: Dependent on │
│ into ~7.4B tokens/month. │ provider load and queue depth. │
├───────────────────────────────────────────────┼───────────────────────────────────────────────┤
│ Universal Wire Protocol: Supports OpenAI, │ Single-User Focus: No native multi-tenant │
│ Anthropic, Gemini, and Ollama APIs. │ authentication or user isolation. │
├───────────────────────────────────────────────┼───────────────────────────────────────────────┤
│ Self-Updating Catalog: Ed25519-signed updates │ UTC Quality Degradation: Daily quotas for │
│ adjust limits dynamically. │ top models exhaust late in the day.│
└───────────────────────────────────────────────┴───────────────────────────────────────────────┘
System Limitations
- Intra-Day Quality Variations : Top-ranked model endpoints (e.g., Gemini 3.6 Flash, DeepSeek V4) have lower daily allowances. As these models exhaust their daily quotas, the gateway degrades to secondary candidates until quotas reset at UTC midnight.
- Variable Latency : Latency varies significantly across providers (e.g., high-speed providers like Groq/Cerebras versus slower community endpoints).
- No Service Level Agreement (SLA): Free tier allowances remain subject to unannounced provider adjustments, rate limit changes, or endpoint retirements.
FreeLLMAPI is optimized for personal experimentation and rapid prototyping. As projects transition to production-grade requirements, the system is designed to be easily swapped for a direct paid API to ensure Service Level Agreements (SLAs) and consistent access to frontier models.
FreeLLMAPI stands as the definitive infrastructure layer for the democratisation of LLM access, turning fragmented free resources into a unified, high-capacity inference engine.
Need High-Impact Technical Content for Your Engineering Team?
I partner with developer-tooling startups, SaaS platforms, and engineering teams to translate complex infrastructure, agentic systems, and backend architecture into publication-grade technical writing.
Whether you need deep-dive architecture essays, hands-on developer tutorials, or technical counter-narratives:
- 📩 Email: abhishekninja2018@gmail.com
- 💼 LinkedIn: linkedin.com/in/abhishekninja
- 🐦 X (Twitter): x.com/AvishekBanzzov
- 🛠️ Capabilities: Long-form Technical Essays | Hands-On Tutorials | Developer Tooling Deep-Dives | Technical Counter-Narratives





Top comments (0)