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.
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.
| Provider | Key Variables | Tier Variable |
|---|---|---|
| OpenRouter | OPENROUTER_API_KEY / FREELM_OPENROUTER_KEYS | FREELM_OPENROUTER_TIER (free | credit) |
| Google AI Studio | GEMINI_API_KEY / GOOGLE_API_KEY / FREELM_GOOGLE_KEYS | FREELM_GOOGLE_TIER (free | tier1) |
| NVIDIA NIM | NVIDIA_API_KEY / NIM_API_KEY / FREELM_NIM_KEYS | FREELM_NIM_TIER (free) |
| Groq | GROQ_API_KEY / FREELM_GROQ_KEYS | FREELM_GROQ_TIER (free) |
| Mistral | MISTRAL_API_KEY / FREELM_MISTRAL_KEYS | FREELM_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_KEYS | free GLM Flash models only (paid GLM ids refused) |
| Cohere (beta) | COHERE_API_KEY / CO_API_KEY / FREELM_COHERE_KEYS | trial key: free, non-commercial |
| Kilo Gateway | KILO_API_KEY / FREELM_KILO_KEYS (optional: free routes work keyless) | FREELM_KILO_TIER (free) |
| OVHcloud AI Endpoints | none: anonymous tier only (keyless mode) | n/a |
| Cerebras | CEREBRAS_API_KEY / FREELM_CEREBRAS_KEYS | trial 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
import freelm
llm = freelm.FreeLLM.from_env()
print(llm.text("Explain black holes in one sentence."))Node.js / 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:
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)
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)
llm = freelm.FreeLLM.from_env()
for chunk in llm.stream("Write a haiku about failover."):
print(chunk, end="", flush=True)Python (async)
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
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.
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/freelmfrom 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){
"$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.
$ 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: googleNo 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.
pip install freelm && freelm chat "hello" # works with no keysDrop-in OpenAI Shim
Change one import line. Your existing OpenAI SDK code works unchanged — backed by free providers instead of a paid API.
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
// 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.
| Alias | Meaning |
|---|---|
| auto / chat | Any available chat model (registry order) |
| chat:large / large | A larger, stronger model |
| chat:fast / fast | A fast, cheap model (e.g. Gemini Flash-Lite or Groq) |
| chat:small / small | The smallest available model |
| chat:tools / vision | Only models that support function calling / images |
| vendor/model-id | Exactly 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.
smartThe 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.
priorityProviders tried in ascending priority integer. Deterministic and predictable.
round_robinRotates which provider goes first each call, spreading load evenly across all keys.
quota_awareRanks by remaining quota headroom. Keys nearing daily limits score lower.
latencyPrefers 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 provider | 0.4.0 | 0.5.0, first call | 0.5.0, next call |
|---|---|---|---|
| Rate limit (429) or server error (500) | 0.3 s | 0.3 s | 0.3 s |
| Provider hangs | failed after 60 s | 6.3 s | 0.3 s |
| Unroutable host | failed after 60 s | 6.3 s | 0.3 s |
| Slow provider (8 s) | 8.0 s every call | 6.3 s | 0.3 s |
| Stream stalls before the first token | failed after 60 s | 3.3 s | 0.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.
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 timeError 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.
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 rejectedHealth & Introspection
Call llm.health() at any time to inspect the live state of every key in the pool.
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 creditsEach response object also exposes: r.text, r.provider, r.model, r.usage, r.latency_ms, and r.raw.