FreeLLMAPI

repository·main·Indexed 11 days ago

https://github.com/tashfeenahmed/freellmapi

An OpenAI-compatible API gateway that aggregates free-tier LLM endpoints from multiple providers. It features intelligent routing, automatic quota management, and a live-updating model catalog. Includes a CLI for configuring coding agents like Claude Code, Aider, and Cursor, as well as a desktop Electron application and Docker Compose deployment options.

Tokens
48.2K
Snippets
135
Records
195
Agent score
97%

What's inside FreeLLMAPI

  1. Overview of FreeLLMAPI

    main

    FreeLLMAPI is an aggregator that combines free tiers from dozens of LLM providers into a single, OpenAI-compatible /v1 endpoint. It provides access to approximately 4 billion tokens per month across 251 model families and 358 provider endpoints.

    Key Capabilities:

    • Unified API: Collapses multiple SDKs and rate limits into one OpenAI-compatible interface.
    • Intelligent Routing: A router selects the best available model and automatically falls back to the next provider if one is rate-limited.
    • Quota Management: Tracks per-key usage to ensure you stay within the free-tier limits of each provider.
    • Automatic Updates: The router pulls a signed model catalog from freellmapi.co to update model availability, quotas, and compatibility without requiring a manual code update or git pull.
  2. Usage Disclaimer and Production Warning

    main

    FreeLLMAPI is intended for personal experimentation and learning only. It is not suitable for production use.

    Because the project relies on free tiers of various providers, it does not offer a stable or supported inference substrate. If you transition from prototyping to a production environment, you should replace FreeLLMAPI with a paid API.

    Users are responsible for complying with the Terms of Service (ToS) of each upstream provider. Traffic proxied through this project is still subject to the terms accepted when creating accounts with those providers.

  3. Configure routing strategies and fallback chains

    main

    The router uses a fallback chain to ensure high availability. You can rank this chain using one of six selectable strategies via the Dashboard:

    • priority: Uses your manually defined order.
    • balanced: A mix of speed and reliability.
    • smartest: Prioritizes model capability.
    • fastest: Prioritizes low latency.
    • reliable: Prioritizes providers with the highest uptime/health.
    • custom: Allows for your own specific weight mix.

    Key Routing Features:

    • Automatic Fallover: If a provider fails (429, 5xx, or timeout), the router skips it, applies a cooldown, and retries (up to 20 attempts within a wall-clock budget).
    • Unified Models: Multiple providers serving the same logical model (e.g., GLM-4.7 on Cloudflare and Z.ai) are collapsed into a single entry in /v1/models for seamless in-group failover.
    • Model Profiles: You can save and switch between different fallback-chain configurations (e.g., a coding chain, a long-context chain, or a vision chain) from the dashboard.
    • Sticky Sessions: To prevent hallucinations caused by mid-conversation model switches, the router attempts to keep a conversation talking to the same model for 30 minutes.
  4. How the FreeLLMAPI routing mechanism works

    main

    FreeLLMAPI acts as a smart router for free LLM providers. When a request is received, the router selects the highest-priority model that satisfies three conditions: it has a healthy API key, it is currently under its rate limits, and it is available.

    Key operational behaviors include:

    • Key Management: API keys are decrypted in memory only when needed to call the provider.
    • Error Handling & Fallback: If a provider returns a 429 (Too Many Requests) or 5xx (Server Error), the router automatically puts that specific key into a 'cooldown' state and retries the request using the next available model in your configured fallback chain.
    • Tracking: The system maintains live scores, cooldowns, and quota tracking to optimize model selection.

    For deep technical details on routing internals and component walkthroughs, refer to docs/architecture.md.

  5. Understand the limitations of stacking free tiers

    main

    Using FreeLLMAPI involves trade-offs inherent to using free-tier models. Before deploying to production, consider the following limitations:

    • Model Capability: You will not have access to frontier models (e.g., GPT-4o, Claude 3.5 Sonnet).
    • Performance: Expect variable latency and no Service Level Agreement (SLA).
    • Intelligence Fluctuations: The effective intelligence of the endpoint may decrease late in the day as top-tier free models hit their daily usage caps.
    • Reset Cycle: Usage quotas and caps typically reset at UTC midnight.

    For a comprehensive list of constraints, consult docs/architecture.md#limitations.

  6. Fidelity and Cache Safety Guarantees

    main

    The compression pipeline is fail-open: if an engine increases request size, throws an exception, or fails a fidelity gate, its output is discarded.

    Fidelity Gates: To pass, the compressed output must satisfy:

    • All distinct numeric literals and diff hunks must survive.
    • Every explicit constraint, security instruction, and error line must survive.
    • At least 90% of JSON keys must survive.
    • At least 95% of other protected spans must survive.
    • Tool-call and tool-result envelopes must remain valid.

    Protected Spans include: code fences, URLs, file paths, stack traces, explicit constraints, error lines, key/value pairs, and structured tool metadata.

    Cache Safety: Compression configuration is included in the response-cache fingerprint to prevent different compression modes from sharing the same stale cache entry.

  7. Understand Adaptive Compression

    main
    If autoTriggerEstTokens is configured, the pipeline may automatically switch to aggressive engines for uncompressed requests that exceed that token estimate. The compression process will continue until the targetTokens threshold is reached. An explicit request header that lowers the permitted mode will still override this adaptive behavior.
  8. Use Routing Strategies with `auto:*` prefixes

    main

    Instead of using a specific model name, you can use the auto prefix to let the router select a model based on specific performance profiles. This allows you to steer requests without changing dashboard settings.

    Available Profiles:

    • auto:smart: Favors highest-intelligence models.
    • auto:fast: Favors throughput and low time-to-first-byte.
    • auto:cheap: Budget-leaning (currently uses the balanced blend).
    • auto:reliable: Favors models with recent high success rates.
    • auto:balanced: The default (reliability first, then split between speed and intelligence).

    Note: Profiles are case-insensitive and support common synonyms (e.g., auto:fastest, auto:smartest, auto:budget).

    Named Profiles: You can route through a specific named fallback chain created in your dashboard using auto:<profile-name>. If the profile name is unknown, the API returns a 400 error.

    # Example using the 'fast' profile
    curl http://localhost:3001/v1/chat/completions \
      -H "Authorization: Bearer freellmapi-your-unified-key" \
      -H "Content-Type: application/json" \
      -d '{
        "model": "auto:fast",
        "messages": [{"role": "user", "content": "hi"}]
      }'
  9. How the Premium live catalog works

    main

    The Premium service provides a live, signed model catalog that keeps your local router up-to-date with the latest providers, model families, and quota changes.

    Key Features:

    • Automatic Updates: The router pulls a signed catalog from freellmapi.co twice daily, applying updates to your local database without touching your custom providers or enable/disable choices.
    • Security: Every download is verified against a pinned Ed25519 key before application.
    • Coverage: Tracks approximately 29 providers, 251 model families, and 358 provider/model endpoints.
    • Unified Access: A single fla_ key covers all your running routers (Desktop, Homelab, Raspberry Pi, etc.).

    Activation and Management:

    • Activate via the Premium section in the dashboard.
    • Manage or cancel billing at freellmapi.co/manage.
    • The router software remains MIT-licensed and free; Premium only covers the live catalog feed.
  10. Enable Context Handoff for model switches

    main

    When FreeLLMAPI switches models mid-conversation (due to quota, rate limits, or cooldowns), it can inject a system message to inform the new model that it is taking over an ongoing task. This helps maintain continuity.

    Enable via .env:

    FREELLMAPI_CONTEXT_HANDOFF=on_model_switch

    How it works:

    • Trigger: Injected only when the selected model changes for a given session key.
    • Session Identification: Uses the X-Session-Id header if present; otherwise, it uses a SHA-1 hash of the first user message.
    • Storage: Session messages are stored in-memory with a 3-hour TTL. Nothing is written to disk or logged.
    • Limitations: It cannot recover provider-internal hidden state or messages that were never sent to the proxy.
    FREELLMAPI_CONTEXT_HANDOFF=on_model_switch
  11. How the FreeLLMAPI router works

    main

    FreeLLMAPI acts as an OpenAI-compatible proxy that routes requests to various free-tier LLM providers (e.g., Google, Groq, Cerebras, OpenRouter, HF).

    The Request Flow:

    1. Client Request: An OpenAI SDK, curl, or any OpenAI-compatible client sends a request to the Express proxy (default port :3001) using a freellmapi-... bearer token.
    2. Routing Logic: The Router selects the highest-priority model that satisfies two conditions:
      • It has a healthy API key.
      • It is currently under its rate limits (RPM/RPD/TPM/TPD).
    3. Execution: The router decrypts the provider key, calls the provider's SDK, and streams tokens back to the client.
    4. Error Handling: If a provider returns a 429 (Rate Limit) or 5xx (Server Error), the router puts that key on cooldown and automatically retries the request using the next model in the fallback chain.

    Core Components:

    • Router: Manages model selection per request.
    • Rate-limit ledger: Tracks in-memory counters (RPM, RPD, TPM, TPD) backed by SQLite.
    • Provider adapters: Implement the Provider base class for chatCompletion() and streamChatCompletion().
    • Health service: Periodically probes keys to ensure they are valid and active.
    • Storage: Uses SQLite with AES-256-GCM encryption for API keys.
    ┌──────────────────┐   Bearer freellmapi-…   ┌─────────────────────────┐
    │  OpenAI SDK /    │ ──────────────────────▶ │  Express proxy (:3001)  │
    │  curl / any      │ ◀────────────────────── │  /v1/chat/completions   │
    │  OpenAI client   │      streamed tokens    └────────────┬────────────┘
    └──────────────────┘                                      │
                                                              ▼
                                 ┌────────────────────────────────────────────────┐
                                 │  Router                                        │
                                 │   1. Pick highest-priority model that          │
                                 │      (a) has a healthy key and                 │
                                 │      (b) is under all its rate limits.         │
                                 │   2. Decrypt key, call provider SDK.           │
                                 │   3. On 429/5xx → cooldown + retry next model. │
                                 └────────────────────────────────────────────────┘