The freelm field guide.

freelm is an open-source LLM client for Python and Node.js/TypeScript. It pools the free tiers of Google AI Studio (Gemini), Groq, OpenRouter, Cloudflare Workers AI, Mistral, NVIDIA NIM, Z.ai, Cohere and Kilo behind one OpenAI-compatible call, or a local OpenAI-compatible endpoint, with automatic key rotation, failover that races slow providers, circuit breaking, and live model discovery. This guide covers version 0.5.


Installation

Install freelm from the package manager for your language. Python 3.9+ and Node.js 20+ are supported. The Node.js package has zero runtime dependencies and uses the built-in fetch API.

Python (3.9+)

bash
pip install freelm
View on PyPI

Node.js / TypeScript (20+)

bash
npm install freelm
View on npm

Environment Variables

Set whichever keys you have. freelm auto-detects them. Supply multiple keys per provider by comma-separating them — they are round-robined within that provider for additional rate limit headroom.

ProviderKey VariablesTier Variable
OpenRouterOPENROUTER_API_KEY / FREELM_OPENROUTER_KEYSFREELM_OPENROUTER_TIER (free | credit)
Google AI StudioGEMINI_API_KEY / GOOGLE_API_KEY / FREELM_GOOGLE_KEYSFREELM_GOOGLE_TIER (free | tier1)
NVIDIA NIMNVIDIA_API_KEY / NIM_API_KEY / FREELM_NIM_KEYSFREELM_NIM_TIER (free)
GroqGROQ_API_KEY / FREELM_GROQ_KEYSFREELM_GROQ_TIER (free)
MistralMISTRAL_API_KEY / FREELM_MISTRAL_KEYSFREELM_MISTRAL_TIER (free)
Cloudflare Workers AI (beta)CLOUDFLARE_API_TOKEN / FREELM_CLOUDFLARE_KEYS + CLOUDFLARE_ACCOUNT_ID (required)10,000 Neurons/day free (Workers Paid bills past it)
Z.ai (beta)ZAI_API_KEY / FREELM_ZAI_KEYSfree GLM Flash models only (paid GLM ids refused)
Cohere (beta)COHERE_API_KEY / CO_API_KEY / FREELM_COHERE_KEYStrial key: free, non-commercial
Kilo GatewayKILO_API_KEY / FREELM_KILO_KEYS (optional: free routes work keyless)FREELM_KILO_TIER (free)
OVHcloud AI Endpointsnone: anonymous tier only (keyless mode)n/a
CerebrasCEREBRAS_API_KEY / FREELM_CEREBRAS_KEYStrial credits only (no longer free)

Quick Start

The fastest path: call from_env() / fromEnv(). It reads all supported keys from your environment and builds the provider pool automatically.

Python

Python
import freelm

llm = freelm.FreeLLM.from_env()
print(llm.text("Explain black holes in one sentence."))

Node.js / TypeScript

TypeScript
import { FreeLLM } from "freelm";

const llm = FreeLLM.fromEnv();
console.log(await llm.text("Explain black holes in one sentence."));

Explicit provider config (Python)

For full control over which providers are used, their priority, and routing strategy:

Python
from freelm import FreeLLM, GoogleAIStudio, Groq, Mistral, NIM, OpenRouter

llm = FreeLLM(
    providers=[
        GoogleAIStudio("AIza...", priority=0),     # tried first
        Groq("gsk_...", priority=1),
        OpenRouter("sk-or-...", priority=2),
        Mistral("...", priority=3),
        NIM("nvapi-...", priority=4),
    ],
    strategy="quota_aware",   # priority | round_robin | quota_aware | latency
)

resp = llm.chat(
    [{"role": "user", "content": "Write a haiku about failover."}],
    model="chat:fast",
)
print(resp.text, "via", resp.provider)

Explicit provider config (Node.js)

TypeScript
import { FreeLLM, GoogleAIStudio, Groq, Mistral, NIM, OpenRouter } from "freelm";

const llm = new FreeLLM(
  [
    new GoogleAIStudio("AIza..."),
    new Groq("gsk_..."),
    new OpenRouter("sk-or-..."),
    new Mistral("..."),
    new NIM("nvapi-..."),
  ],
  { strategy: "quota_aware" }
);

const r = await llm.chat(
  [{ role: "user", content: "Write a haiku about failover." }],
  { model: "chat:fast" }
);
console.log(r.text, "via", r.provider);

Streaming

Token streaming works across all providers through the same failover mechanism. freelm fails over between providers before the first token. Once tokens start flowing, it stays on that provider for the rest of the response — no mid-stream switching.

Python (sync)

Python
llm = freelm.FreeLLM.from_env()
for chunk in llm.stream("Write a haiku about failover."):
    print(chunk, end="", flush=True)

Python (async)

Python
from freelm import AsyncFreeLLM

async with AsyncFreeLLM.from_env() as llm:
    async for chunk in llm.astream("Stream me some tokens"):
        print(chunk, end="", flush=True)

Node.js

TypeScript
for await (const chunk of llm.stream("Stream me some tokens")) {
  process.stdout.write(chunk);
}

Local OpenAI-compatible endpoint

freelm serve runs the same router as a local API, with /v1/chat/completions (including streaming and tool calls), /v1/models and /health. Point OpenCode, OpenClaw, Hermes Agent, Cline, Continue, Aider, Open WebUI, n8n, LangChain or the Vercel AI SDK at http://127.0.0.1:4000/v1 with model auto. It binds to localhost; set --api-key before exposing it.

bash
freelm serve                 # or: npx freelm serve
# Docker:
docker run --rm -p 4000:4000 -e GEMINI_API_KEY=... -e FREELM_SERVER_KEY=change-me \
  ghcr.io/shihabshahrier/freelm
Python
from openai import OpenAI   # the real OpenAI SDK, pointed at freelm

client = OpenAI(base_url="http://127.0.0.1:4000/v1", api_key="freelm")
r = client.chat.completions.create(model="auto", messages=[{"role": "user", "content": "hi"}])
print(r.choices[0].message.content)
opencode.json (OpenCode)
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "freelm": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "freelm",
      "options": { "baseURL": "http://127.0.0.1:4000/v1" },
      "models": { "auto": { "name": "freelm auto" } }
    }
  }
}

OpenClaw: add a provider under models.providers with baseUrl: "http://127.0.0.1:4000/v1", api: "openai-completions" and a model auto, then allow freelm/auto in agents.defaults.models. Hermes Agent: run hermes model, pick Custom endpoint, and enter the same base URL with model auto (agents want a long-context model, so pin large or a concrete id if answers get cut off).

Check your keys

Free keys expire and get revoked quietly. freelm doctor sends one tiny request per key and tells you which ones work, why the others fail, and where to get a new free key. Add --json for scripts and CI.

bash
$ freelm doctor
  openrouter  sk-or-...a1b2    FAIL  key rejected (401): User not found. — get a new free key: https://openrouter.ai/keys
  google      AIzaSy...x9yz    OK    gemini-2.5-flash-lite · 1131 ms

1 of 2 key(s) working — ready: google

No keys yet?

With no keys configured, the CLI (freelm chat, freelm serve) falls back to documented keyless endpoints, Kilo Gateway's free routes and OVHcloud AI Endpoints' anonymous tier, and says so. Limits are low and free routes may log prompts. In code, keyless mode is opt-in: FreeLLM.from_env(keyless=True) or FREELM_KEYLESS=1, so an app with a missing key never sends prompts there silently.

bash
pip install freelm && freelm chat "hello"   # works with no keys

Drop-in OpenAI Shim

Change one import line. Your existing OpenAI SDK code works unchanged — backed by free providers instead of a paid API.

Python

Python
# Before:  from openai import OpenAI
# After:
from freelm.compat import OpenAI

client = OpenAI()   # backed by FreeLLM.from_env()
r = client.chat.completions.create(
    model="auto",   # virtual model: picks best available
    messages=[{"role": "user", "content": "hi"}],
)
print(r.choices[0].message.content)

Node.js / TypeScript

TypeScript
// Before:  import OpenAI from "openai";
// After:
import { OpenAI } from "freelm/compat";

const client = new OpenAI();   // backed by FreeLLM.fromEnv()
const r = await client.chat.completions.create({
  model: "auto",
  messages: [{ role: "user", content: "hi" }],
});
console.log(r.choices[0].message.content);

Virtual Models

Model names differ across providers. Use intent-based aliases and freelm resolves each to a concrete model. Free model IDs change constantly, so freelm discovers them live from each provider's /models endpoint and caches results to ~/.cache/freelm.

AliasMeaning
auto / chatAny available chat model (registry order)
chat:large / largeA larger, stronger model
chat:fast / fastA fast, cheap model (e.g. Gemini Flash-Lite or Groq)
chat:small / smallThe smallest available model
chat:tools / visionOnly models that support function calling / images
vendor/model-idExactly this model, routed only to providers that list it
["vendor/id", "chat:fast"]An ordered per-call fallback chain

List currently available free models

Python

from freelm import list_free_models

for m in list_free_models()[:5]:
    print(m.id, m.tags, m.ctx)

Node.js

import { listFreeModels } from "freelm";

const models = await listFreeModels();
for (const m of models.slice(0, 5)) {
    console.log(m.id, m.tags);
}

Routing Strategies

Set the strategy param when constructing FreeLLM. The default is smart. Regardless of strategy, failover is always interleaved across providers so no single provider monopolizes retries.

smart

The default since 0.5. Priority tiers first, then the fastest measured provider. A provider with no fresh sample counts as typical (2 s), so new ones get tried; samples expire after 10 minutes, so a provider that was slow once is reconsidered.

priority

Providers tried in ascending priority integer. Deterministic and predictable.

round_robin

Rotates which provider goes first each call, spreading load evenly across all keys.

quota_aware

Ranks by remaining quota headroom. Keys nearing daily limits score lower.

latency

Prefers the provider with the lowest observed EWMA round-trip latency.

How fast is failover?

An error (429, 5xx, bad key, retired model) moves to the next provider at the cost of one round trip. A provider that hangs, or a stream that never starts, is raced: once the attempt has run for three times that provider's usual latency (clamped: 1.5 to 6 s for a stream's first token, 4 to 12 s for a whole answer), the next provider starts in parallel and the first answer wins. The slow attempt is cancelled and ranked lower, so the next call goes straight to the fast provider.

Failure in front of a healthy provider0.4.00.5.0, first call0.5.0, next call
Rate limit (429) or server error (500)0.3 s0.3 s0.3 s
Provider hangsfailed after 60 s6.3 s0.3 s
Unroutable hostfailed after 60 s6.3 s0.3 s
Slow provider (8 s)8.0 s every call6.3 s0.3 s
Stream stalls before the first tokenfailed after 60 s3.3 s0.3 s

Simulation run on 2026-10-10 with fake providers on localhost over real HTTP (the healthy one answers in 0.3 s), default settings and a 60 s deadline; Python and Node gave the same times. Reproduce it with benchmarks/failover.py.

Python
FreeLLM.from_env(hedge=True)    # default: adaptive race delay
FreeLLM.from_env(hedge=2.0)     # fixed: race after 2 s
FreeLLM.from_env(hedge=False)   # one attempt at a time

Error Handling (Python)

Seeing a specific provider error? The free LLM API error reference has one guide per common error, with the exact body, causes and fix: Gemini 429 RESOURCE_EXHAUSTED and "User location is not supported", OpenRouter free-models-per-day and "No endpoints found that support tool use", Groq, Mistral and Z.ai rate limits, and empty replies from thinking models.

No single provider error ends a call: auth and quota failures disable that key, retired models (404/410) are set aside, and a request one provider rejects is tried on the next. Retryable errors (RateLimited, Transient) are handled internally and only surface inside NoProvidersAvailable when all providers are exhausted; its message explains each provider's state and points to freelm doctor. A request that two providers reject (or the only provider) surfaces as BadRequest, because then it is the request itself.

Python
from freelm import BadRequest, NoProvidersAvailable

try:
    resp = llm.chat("hi")
except NoProvidersAvailable as e:
    print(e)          # one line per provider: disabled / cooling / no usable model
    print(e.attempts) # [(candidate, exception), ...]
except BadRequest as e:
    print(e.provider, e.status)   # the request itself was rejected

Health & Introspection

Call llm.health() at any time to inspect the live state of every key in the pool.

Python
for row in llm.health():
    print(row)
# → provider, key (masked), ready, breaker state, rpd_used, last_error, ewma_latency_ms

llm.reset_keys()   # fresh start after fixing a key or topping up credits

Each response object also exposes: r.text, r.provider, r.model, r.usage, r.latency_ms, and r.raw.

GitHub Repository PyPI Package npm Package
Shihab portraying Goku in an anime-inspired costume, keeping his own facial identity
The other lives of Shihab

01/ 08

The pursuit of better.

Goku / Dragon Ball

A training arc never really ends.

Personal cosplay artwork. Same face. A different world.Enter the six-form training arc ↗
A little energy from the whole world.
1 of 8