llmrouter
One chat interface, eight LLM backends – plus text embeddings – with automatic provider detection, thread-safe and async.
llmrouter gives Python programs a single, small API (create_chat() → chat() / chat_stream() / achat()) on top
of Claude (Agent SDK or API), Gemini (Antigravity CLI), OpenAI Codex, Ollama and llama.cpp. If you do not choose a provider, it probes all of them in a fixed priority order and uses the first one that works.
from llmrouter import create_chat
chat = create_chat() # no provider set → auto-detect
print(chat.chat("Name three primary colours."))
Machine-readable docs for LLMs and agents:
llms.txt,llms-full.txt,docs/providers.json,AGENTS.md, or runllmrouter describe.
Contents
- Why · 2. Install · 3. Quick start ·
- How a provider is chosen · 5. Provider guides ·
- Python API · Embeddings · 7. Concurrency, async and robustness ·
- Command line · 9. Environment variables · 10. Recipes ·
- Errors and resilience · 12. Troubleshooting ·
- Using llmrouter in another project · 14. Development ·
- Verification status
Why
- One API. The same
chat()/chat_stream()/achat()/ history calls work everywhere. - Bring whatever you have. A Claude subscription token or login, an API key, a Google AI Pro/Ultra plan through the Antigravity CLI, a ChatGPT plan through Codex, a local Ollama or llama.cpp – whichever is available gets used.
- Deterministic auto-detection, only when you did not pick a provider (see below).
- Thread-safe and async. A chat can be shared between threads and tasks (turns are serialised, history never
interleaves);
achat_streamnever blocks the event loop and cancels cleanly. - Robust. Timeouts everywhere, bounded retries for transient failures (only before any output, so text is never duplicated), input validation, and rollback of failed or aborted turns.
- Chat and embeddings through the same selection rules. Gemini, Ollama and llama.cpp can embed text; the rest of the providers fail with a clear message instead of silently falling back.
- Tiny core. The only hard dependency is
httpx; every provider SDK is an optional extra, imported lazily. - Never mistakes an error for an answer. Every failure is an
LLMError. - LLM friendly.
llms.txt,llms-full.txt,AGENTS.md, JSON provider catalogue, exhaustive docstrings.
Install
llmrouter is installed from GitHub.
# everything (all provider SDKs)
uv add "pyllmrouter[all] @ git+https://github.com/fortalbrz/llmrouter.git"
# or with pip
pip install "pyllmrouter[all] @ git+https://github.com/fortalbrz/llmrouter.git"
# only what you use
pip install "pyllmrouter[ollama] @ git+https://github.com/fortalbrz/llmrouter.git"
| Extra | Installs | Needed by provider |
|---|---|---|
claude-agent |
claude-agent-sdk |
claude-agent-token, claude-agent-login |
anthropic |
anthropic |
anthropic |
gemini |
google-genai |
gemini |
codex |
openai-codex (official Codex Python SDK, import openai_codex) |
codex (optional: the Codex CLI also works) |
ollama |
ollama |
ollama |
| (none) | – | antigravity (external agy binary), llamacpp (only needs httpx) |
all |
all of the above | everything |
Requires Python ≥ 3.10.
Quick start
from llmrouter import create_chat
# 1. Automatic: first working provider in priority order.
chat = create_chat()
# 2. Explicit provider (and model).
chat = create_chat("ollama", "qwen3:8b")
# 3. Conversation with a system prompt.
chat.set_system_message("You answer in one sentence.")
print(chat.chat("What is a fugue?"))
print(chat.chat("And a canon?")) # remembers the previous turn
# 4. Streaming.
for token in chat.chat_stream("Write a haiku about rain."):
print(token, end="", flush=True)
# 5. Async (never blocks the event loop).
reply = await chat.achat("hello")
async for token in chat.achat_stream("hello again"):
print(token, end="")
# 6. One-shot helpers (sync and async).
from llmrouter import complete, acomplete
print(complete("Translate 'bom dia' to English", provider="claude"))
How a provider is chosen
Provider selection has exactly two modes:
- A provider is set – by the
providerargument,--provider, or theLLMROUTER_PROVIDERenvironment variable (argument wins over variable). That provider is used. No probing happens. If it is unusable you get a precise error (missing credential, missing SDK, …). An unknown name is an error, never a silent fallback. - No provider is set (
None,""or"auto") – auto-detection walks all eight providers in this order and uses the first whose cheap probe succeeds:
| # | Provider id | Backend | "Available" means |
|---|---|---|---|
| 1 | claude-agent-token |
Claude Agent SDK + CLAUDE_CODE_OAUTH_TOKEN |
token variable set and claude-agent-sdk installed |
| 2 | claude-agent-login |
Claude Agent SDK + interactive CLI login | SDK installed and claude auth status reports loggedIn |
| 3 | anthropic |
Anthropic API (ANTHROPIC_API_KEY) |
key set and anthropic installed |
| 4 | gemini |
google-genai (GEMINI_API_KEY) |
key set and google-genai installed |
| 5 | antigravity |
Antigravity CLI agy via subprocess (Google account OAuth) |
agy found and its state directory ~/.gemini/antigravity-cli exists |
| 6 | codex |
OpenAI Codex: official Python SDK or CLI (ChatGPT sign-in) | SDK or codex CLI installed and codex login status succeeds |
| 7 | ollama |
Ollama server | ollama installed and GET /api/tags answers |
| 8 | llamacpp |
llama.cpp llama-server |
GET /health answers 200 |
Probes are cheap and side-effect free: no tokens are spent. If none works, NoProviderAvailableError lists the
reason for every provider. The choice is logged at INFO (logger llmrouter.registry).
llmrouter providers # probe all eight and show why each is (un)available
llmrouter detect # print the provider auto-detection would pick
Accepted spellings (case-insensitive, _/space ≡ -): the canonical ids above, plus aliases such as claude
(= anthropic, backward compatible), claude-oauth, claude-login, claude-agent, google, google-genai,
agy, antigravity-cli, openai-codex, codex-sdk, llama.cpp, llama-server. Full list: llmrouter describe.
gemini-cliwas removed. Google ended "Sign in with Google" for individual accounts in the legacy Gemini CLI, so the id now resolves (with a deprecation warning) toantigravity. See provider 5.
Note on the default. Because auto-detection prefers Claude, a machine that has
ANTHROPIC_API_KEYset will use it when you give no provider. To stay local, setLLMROUTER_PROVIDER=ollama.
Provider guides
Every provider honours model= (or its own environment variable); a blank model means "provider default".
1. claude-agent-token – Claude Agent SDK with an OAuth token
Uses your Claude subscription through the official Claude Agent SDK.
pip install "pyllmrouter[claude-agent] @ git+https://github.com/fortalbrz/llmrouter.git"
claude setup-token # one-off: creates a long-lived OAuth token (valid for 1 year)
export CLAUDE_CODE_OAUTH_TOKEN=... # PowerShell: $env:CLAUDE_CODE_OAUTH_TOKEN = "..."
llmrouter ask -p claude-agent-token "hello"
claude setup-token prints the token once (the screenshot below has it redacted) and tells you how to use it:
Store the token securely (a secret manager or your shell profile) – it cannot be shown again.
- Model:
CLAUDE_AGENT_MODEL/CLAUDE_MODELormodel=(alias such assonnet, or a full id). Blank = CLI default. - The SDK is used as plain chat: all built-in tools are disabled, one turn, no project settings loaded.
temperatureandmax_tokensare not supported by the Agent SDK and are ignored (debug-logged).ANTHROPIC_API_KEY/ANTHROPIC_AUTH_TOKENare blanked for the child process so they cannot override the token.
2. claude-agent-login – Claude Agent SDK with the interactive CLI login
Same engine, but authenticated by the stored claude CLI login.
claude auth login # one-off, interactive (opens a browser)
llmrouter ask -p claude-agent-login "hello"
- Detection runs
claude auth statuswith credential variables blanked, so an exported API key can never be mistaken for a login. If the CLI cannot be run,~/.claude/.credentials.jsonis used as evidence. CLAUDE_CLI_PATHpoints at a specificclaudebinary (the SDK's bundled binary is the last fallback).- All other behaviour and limits are identical to provider 1.
3. anthropic – Claude API key
pip install "pyllmrouter[anthropic] @ git+https://github.com/fortalbrz/llmrouter.git"
export ANTHROPIC_API_KEY=sk-ant-... # legacy name CLAUDE_TOKEN is also read
llmrouter ask -p anthropic "hello"
- Default model
claude-opus-5-5; override withmodel=,CLAUDE_MODELorANTHROPIC_MODEL. - Streams through the official SDK with a 10-minute timeout.
max_tokensdefaults to 16000 (the API requires one). temperatureis intentionally never sent: current Claude models and API versions reject sampling parameters. It is accepted by the common API and ignored here.- For models that support it, the server-side refusal fallback is enabled (
AnthropicChat(fallbacks=False)opts out). Arefusalstop reason raisesLLMError; truncation atmax_tokensis logged as a warning.
4. gemini – Gemini API key (google-genai)
pip install "pyllmrouter[gemini] @ git+https://github.com/fortalbrz/llmrouter.git"
export GEMINI_API_KEY=... # GOOGLE_API_KEY also accepted
llmrouter ask -p gemini "hello"
- Default model
gemini-3.5-flash; override withmodel=orGEMINI_MODEL. - Supports
temperatureandmax_tokens(max_output_tokens) and a real system instruction. - HTTP 429/5xx are retried; other API errors fail immediately.
5. antigravity – Antigravity CLI (agy)
Background. On 2026-06-18 Google ended "Sign in with Google" (OAuth) in the legacy Gemini CLI
(@google/gemini-cli) for individual accounts – Free, Google AI Pro and Google AI Ultra. The legacy CLI now only
works with Enterprise licences or a paid / AI Studio API key. Individual users were moved to the Antigravity CLI
(binary name agy), a standalone binary (no Node.js required) that uses your Google AI Pro/Ultra quota.
llmrouter therefore drives agy in headless mode through subprocess; if you have a Gemini API key instead, use
provider 4 (gemini).
Install – pick your platform, then check it:
# Windows PowerShell
irm https://antigravity.google/cli/install.ps1 | iex
# (long form of the same command)
Invoke-RestMethod https://antigravity.google/cli/install.ps1 | Invoke-Expression
# Linux, macOS and WSL
curl -fsSL https://antigravity.google/cli/install.sh | bash
agy --version # verify the installation (open a new terminal if the command is not found)
agy # first run: sign in with your Google account
The installer puts the binary in %LOCALAPPDATA%\agy\bin (Windows) or ~/.local/bin (Linux/macOS/WSL); llmrouter also
looks there if PATH was not updated yet. Running agy once starts the OAuth sign-in: your browser opens
automatically, or – over SSH/WSL without a browser – the terminal prints a URL and waits for the authorization code:
After signing in, use it from Python or the shell:
agy -p "In one sentence, what is a git rebase?" # what llmrouter runs under the hood (headless)
llmrouter ask -p antigravity "hello"
from llmrouter import create_chat
chat = create_chat("antigravity", "gemini-3.8-flash-medium") # slugs: run `agy models`
Optional – the Python SDK. pip install google-antigravity installs Google's Antigravity SDK for building your
own agents in Python (async Agent, preview; it authenticates with a Gemini API key). It is a separate product and is
not needed by llmrouter, which uses the CLI.
- How it runs:
agy -p "<prompt>" --output-format stream-json --disable-slash-commands [--model slug] [--mode mode], in an empty temporary directory (the agent has no project files), with stdin closed. The answer streams fromagent_responsetext_deltaevents and is reconciled with the finalresult.response, so nothing is duplicated or lost. - The prompt is one command-line argument: llmrouter refuses prompts over 30 000 characters on Windows (120 000 elsewhere) with a clear error – use another provider for those.
- Env:
AGY_CLI_PATH(binary),AGY_CLI_TIMEOUT(default 600 s),AGY_CLI_MODEL,AGY_CLI_MODE(accept-edits|auto|plan; unset = CLI default). - Availability is a heuristic.
agyhas no "am I signed in?" command and keeps the sign-in in the OS keyring, so the free probe combines three signals: the binary exists,~/.gemini/antigravity-cliexists (created by the first run), and the tail of the CLI's owncli.logdoes not containYou are not logged into Antigravity(whichagylogs whenever it runs unauthenticated). If the probe is wrong, the first request fails with a clear "runagyonce and finish the browser sign-in" error (the OAuth URL thatagyprints is never echoed). - Heads-up: run headless while not signed in,
agystarts its interactive OAuth flow (it tries to open your browser) and exits with status 1. Sign in once withagybefore using the provider. --disable-slash-commandsis always passed, so a prompt that starts with/can never run a CLI command.temperatureandmax_tokensare not exposed by the CLI and are ignored. A.cmd/.batwrapper is rejected (use the native binary).
6. codex – OpenAI Codex (official Python SDK + CLI)
OpenAI includes Codex usage in ChatGPT Plus, Pro and Business plans, so you can use your subscription instead of an API key.
# Windows PowerShell (or any shell with Node.js)
npm install -g @openai/codex
codex # first run: choose "Sign in with ChatGPT" to authenticate via OAuth on your subscription
Run codex and choose Sign in with ChatGPT (instead of an API key): a browser flow authenticates you and the
credentials are cached in ~/.codex/auth.json. Check it any time with codex login status.
Standalone installers (no npm) also exist: Windows
powershell -ExecutionPolicy ByPass -c "irm https://chatgpt.com/codex/install.ps1 | iex", macOS/Linux
curl -fsSL https://chatgpt.com/codex/install.sh | sh.
Then add the official Python SDK (recommended – it streams token deltas and ships its own pinned runtime, so the CLI is optional):
pip install "pyllmrouter[codex] @ git+https://github.com/fortalbrz/llmrouter.git" # installs openai-codex (import openai_codex)
llmrouter ask -p codex "hello"
from llmrouter import create_chat
chat = create_chat("codex") # SDK when installed, else the CLI
chat = create_chat("codex", backend="cli") # force `codex exec` (also "sdk" / "auto")
- Transports (
backend=):sdk–openai_codexstarts a pinnedcodex app-serverand streamsitem/agentMessage/deltanotifications;cli–codex exec --skip-git-repo-check -s read-only -with the prompt on stdin;auto(default) – SDK if installed, otherwise CLI. - Both run as plain chat: read-only sandbox, approvals denied (SDK
ApprovalMode.deny_all) / never asked (exec), an empty temporary working directory, no stored session. The system prompt becomes the SDK's developer instructions (a<system>block for the CLI). - Model:
model=,CODEX_MODEL, else the account's Codex default. Env:CODEX_CLI_PATH,CODEX_HOME(default~/.codex),CODEX_TIMEOUT(default 600 s). - The probe runs
codex login status(exit 0 = credentials present) and never echoes its output (it can contain a masked key). It cannot validate the credential: an expired or revoked key surfaces on the first request as a clear "not authenticated: runcodexand choose Sign in with ChatGPT" error. Note: ifcodex login statussays "API key", usage is billed at API rates, not on your ChatGPT plan – sign in with ChatGPT to use the plan. temperatureandmax_tokensare not supported by Codex and are ignored. Server-busy errors are retried.
7. ollama – Ollama server
pip install "pyllmrouter[ollama] @ git+https://github.com/fortalbrz/llmrouter.git"
ollama serve & ollama pull qwen3:8b
llmrouter ask -p ollama -m qwen3:8b "hello"
- URL:
base_url=, elseOLLAMA_SERVER/OLLAMA_HOST, elsehttp://localhost:11434. - Model:
model=, elseOLLAMA_MODEL, elseqwen3:8b. Surrounding whitespace is stripped. - Supports
temperatureandmax_tokens(num_predict). Connection failures and HTTP 429/5xx are retried.
8. llamacpp – llama.cpp llama-server
Talks to the server's OpenAI-compatible /v1/chat/completions endpoint. Start the server with the --jinja
option so the model's own chat template is used:
llama-server -m model.gguf --port 8080 --jinja
llmrouter ask -p llamacpp "hello"
- URL:
base_url=/LLAMACPP_SERVER(defaulthttp://localhost:8080); bearer token fromLLAMACPP_API_KEYwhen the server uses--api-key. chat_template_kwargs={"enable_thinking": False}forwards Jinja template variables.- Connection failures and HTTP 429/5xx are retried before any output.
- Let Python run the server for you (it waits for
/health, stops on exit, and is safe to start from several threads):
from llmrouter import LlamaCppChat, LlamaCppServer
with LlamaCppServer("model.gguf", port=8080, extra_args=("-c", "8192", "-ngl", "99")) as server:
chat = LlamaCppChat(base_url=server.base_url)
print(chat.chat("hello"))
LlamaCppServer passes --jinja by default and finds the binary via LLAMACPP_CLI_PATH or PATH.
Recent llama.cpp builds enable Jinja by default; add --no-jinja to extra_args (and jinja=False) to disable it.
Capability matrix
| Provider | System prompt | temperature |
max_tokens |
Streaming | Retries (transient) | Network |
|---|---|---|---|---|---|---|
claude-agent-token |
yes | ignored | ignored | yes | – | yes |
claude-agent-login |
yes | ignored | ignored | yes | – | yes |
anthropic |
yes | never sent | yes | yes | SDK-internal | yes |
gemini |
yes | yes | yes | yes | 429/5xx | yes |
antigravity |
yes (prefixed) | ignored | ignored | yes | – | yes |
codex |
yes | ignored | ignored | yes (SDK) / final message (CLI) | server busy | yes |
ollama |
yes | yes | yes | yes | connection, 429/5xx | local |
llamacpp |
yes | yes | yes | yes | connection, 429/5xx | local |
Using a Claude, Google or ChatGPT subscription login from scripts is meant for your own local automation. Check the current terms of the respective service before using it in anything shared or commercial.
Python API
from llmrouter import (
create_chat,
complete, # factory + one-shot
acreate_chat,
acomplete, # async versions
create_embedder,
embed,
BaseEmbedder, # embeddings (aembed / acreate_embedder are async)
detect_provider,
resolve_provider, # selection (adetect_provider is the async one)
probe_provider,
probe_providers, # diagnostics (never raise; aprobe_providers is async)
normalize_provider,
provider_names,
describe,
Provider,
PROVIDER_ORDER,
BaseChat,
LLMError,
ProviderUnavailableError,
NoProviderAvailableError,
UnknownProviderError,
InvalidRequestError,
ChatBusyError,
TransientLLMError,
# concrete classes: AnthropicChat, ClaudeAgentTokenChat, ClaudeAgentLoginChat, GeminiChat,
# AntigravityChat, CodexChat, OllamaChat, LlamaCppChat, LlamaCppServer
)
create_chat(provider=None, model=None, *, models=None, default_models=None, **kwargs) -> BaseChat
| Argument | Meaning |
|---|---|
provider |
name/alias/Provider. None, "", "auto" → LLMROUTER_PROVIDER, then auto-detection |
model |
model for the selected provider (blank → env var → provider default) |
models |
{provider: model} map – use it with auto-detection, where the winner is unknown in advance; wins over model |
default_models |
{provider: model} application defaults; lowest precedence (below the provider's env var) |
**kwargs |
provider options: base_url, timeout, backend, mode, fallbacks, chat_template_kwargs, … (bad options → LLMError) |
chat = create_chat(
models={
"anthropic": "claude-sonnet-5-5",
"gemini": "gemini-3.5-flash",
"ollama": "qwen3:8b",
}
) # whichever provider wins gets its own model
Model precedence (highest first): models[provider] → model → the provider's environment variable
(OLLAMA_MODEL, CLAUDE_MODEL, …) → default_models[provider] (your application's defaults) → the library default.
BaseChat
| Member | Description |
|---|---|
chat(msg, temperature=0.7, max_tokens=None) -> str |
complete reply |
chat_stream(msg, temperature=0.7, max_tokens=None) |
generator of text chunks |
await achat(msg, ...) / async for … in achat_stream(msg, ...) |
async versions (never block the event loop) |
set_system_message(text) |
set/replace the system prompt (first history entry) |
get_history() / reset_conversation() |
history copy / clear all |
verify_connection() -> bool |
live check (a tiny request; Ollama/llama.cpp only hit a health endpoint) |
check_available() (classmethod) |
free probe → ProviderStatus(provider, available, detail) |
max_retries (2), retry_backoff (0.5 s) |
transient-failure retry policy (settable per instance) |
model, provider, conversation_history |
attributes |
History rules: a turn is committed only if the whole reply arrived. If the backend fails, the reply is empty, you stop iterating a stream early, or the task is cancelled, the user message is rolled back.
Diagnostics
from llmrouter import probe_providers
for s in probe_providers(): # all eight, probed concurrently
print(s.provider, s.available, s.detail)
Embeddings
Text embeddings (for semantic search, RAG, clustering) use the same provider model as chat – explicit provider, then an environment variable, then auto-detection – but only providers with an embeddings API take part:
| Provider | Embeddings | Default embedding model | Env |
|---|---|---|---|
gemini |
yes (google-genai) |
gemini-embedding-001 |
GEMINI_EMBED_MODEL |
ollama |
yes | nomic-embed-text |
OLLAMA_EMBED_MODEL |
llamacpp |
yes (/v1/embeddings; start the server with --embeddings) |
the loaded model | LLAMACPP_EMBED_MODEL, LLAMACPP_EMBED_SERVER |
claude-agent-*, anthropic, antigravity, codex |
no (no embeddings API) | – | – |
from llmrouter import create_embedder, embed
embedder = create_embedder() # auto-detect: gemini > ollama > llamacpp, first usable one
embedder = create_embedder("ollama", "qwen3-embedding:4b")
vectors = embedder.embed(["first text", "second text"]) # list[list[float]], one per text
vector = embedder.embed_one("a single text")
print(embedder.signature) # "ollama:qwen3-embedding:4b"
vectors = await embedder.aembed(texts) # async, never blocks the event loop
vectors = embed(["quick one-shot"], provider="gemini")
- Selection.
create_embedder(provider, model, models=, default_models=)mirrorscreate_chat: an explicit provider (orLLMROUTER_EMBEDDING_PROVIDER) is used without probing; otherwise the first embedding-capable provider whose probe succeeds wins. The probe checks that the model exists (Ollama:ollama pull <model>hint). Model precedence is the same as for chat (models>model>*_EMBED_MODELenv var >default_models> library default). Asking for the embeddings ofanthropic,codex, … raisesProviderUnavailableErrorlisting the capable providers. - Batching and validation. Inputs are split into backend-sized requests (
batch_size, Gemini max 100). Blank or non-string texts raiseInvalidRequestErrorbefore any request; the answer is checked (count, non-empty, finite, consistent dimension) so a malformed reply never reaches your index. - Retries and threads. Connection failures and HTTP 429/5xx are retried (
embedder.max_retries, default 2). An embedder is stateless: one instance can be shared by many threads/tasks and calls run in parallel. - Never mix embedding spaces. Vectors from different providers/models have different dimensions and meaning (e.g.
Ollama
qwen3-embedding:4b= 2560, Geminigemini-embedding-001= 3072). Storeembedder.signaturenext to persisted vectors and re-index when it changes.
llmrouter providers --embeddings # probe the embedding backends
llmrouter embed -p ollama -m qwen3-embedding:4b --summary "hello" # {"signature": ..., "dimensions": 2560}
Concurrency, async and robustness
Thread safety
- A chat instance may be shared between threads and tasks. Turns on one chat are serialised by a per-instance lock:
other callers wait, the backend never sees two overlapping turns, and each turn sees all previous ones – history
can never interleave.
get_history()never blocks. - For throughput use one instance per worker. Different instances run fully in parallel (nothing is shared: clients, temporary directories and subprocesses are per call).
- No deadlocks. The lock is not re-entrant: if the same thread starts or modifies a turn while one of its own
streams is still open,
ChatBusyErroris raised instead of hanging. Finish orclose()the open stream first. - Abandoned streams clean up. Breaking out of a
for, calling.close(), or dropping the generator rolls the turn back and releases the lock. - Registry functions, provider metadata and the probes hold no mutable shared state (
probe_providersruns them concurrently);LlamaCppServer.start()/stop()are lock-protected.
from concurrent.futures import ThreadPoolExecutor
from llmrouter import create_chat
shared = create_chat("ollama") # one chat shared by all threads: turns are queued
with ThreadPoolExecutor(8) as pool:
answers = list(pool.map(shared.chat, ["q1", "q2", "q3"]))
# independent conversations in parallel: one chat per worker
with ThreadPoolExecutor(8) as pool:
answers = list(pool.map(lambda q: create_chat("ollama").chat(q), ["q1", "q2", "q3"]))
Async
Every backend is implemented synchronously and exposed to asyncio through a dedicated daemon thread per call, so the event loop is never blocked and slow streams cannot starve its executor.
import asyncio
from llmrouter import acreate_chat
async def main() -> None:
chat = await acreate_chat() # auto-detection probes run off the loop
print(await chat.achat("hello"))
async for token in chat.achat_stream("tell me a story"):
print(token, end="", flush=True)
replies = await asyncio.gather(*(acreate_chat("ollama") for _ in range(4))) # parallel chats
asyncio.run(main())
- Cancellation is clean. Cancelling the task,
aclose()-ing the generator, leaving anasync forearly, or shutting the loop down stops the worker, closes the stream, rolls the turn back and releases the lock before the cancellation completes – the next call on that chat is safe. A cancelled task that was still queued behind another turn never sends its request. - Concurrent
achatcalls on the same chat are serialised (like threads); on different chats they run in parallel. - A blocked network read cannot be interrupted from outside: cancellation takes effect at the next chunk or at the provider's timeout (all backends have one).
Retries and timeouts
- A provider raises
TransientLLMErrorfor failures worth retrying (connection refused, HTTP 429/5xx, "server busy"). The turn is retried up tochat.max_retriestimes (default 2) with exponential backoff (retry_backoff * 2**attempt+ jitter) only if no output chunk was produced yet – a retry can therefore never duplicate text. After the last retry theTransientLLMErroris raised. Setchat.max_retries = 0to disable. - Every backend has a timeout: Anthropic 10 min, Gemini 10 min, Ollama/llama.cpp 20 min per request (
timeout=), Antigravity/Codex 10 min per turn (AGY_CLI_TIMEOUT,CODEX_TIMEOUT); subprocesses are killed on timeout, on early close and on error.
Input validation
InvalidRequestError (a ValueError and an LLMError) is raised before any state is touched for: a non-string or blank
message, a non-finite or non-numeric temperature, and a non-positive or non-integer max_tokens.
Command line
llmrouter providers [--json] [--embeddings] probe every provider (or the embedding backends)
llmrouter detect print the auto-detected provider (exit 1 if none)
llmrouter describe provider catalogue as JSON
llmrouter ask [PROMPT] [-p PROVIDER] [-m MODEL] [-s SYSTEM] [-t TEMP] [--max-tokens N] [--no-stream]
llmrouter embed [TEXT...] [-p PROVIDER] [-m MODEL] [--summary] embeddings as JSON (texts or stdin lines)
llmrouter -v ... debug logging on stderr (shows the selection)
python -m llmrouter ... same thing
echo "Summarise this in one line" | llmrouter ask -p gemini
git diff | llmrouter ask -s "You are a code reviewer" -p claude-agent-login
Exit codes: 0 ok · 1 runtime failure (no provider, LLMError) · 2 usage error (e.g. empty prompt).
Environment variables
| Variable | Used by | Purpose |
|---|---|---|
LLMROUTER_PROVIDER |
selection | provider to use when none is passed (auto = detect) |
LLMROUTER_EMBEDDING_PROVIDER |
embeddings | embedding provider to use when none is passed (auto = detect) |
OLLAMA_EMBED_MODEL, GEMINI_EMBED_MODEL, LLAMACPP_EMBED_MODEL, LLAMACPP_EMBED_SERVER |
embeddings | embedding model per provider, and the llama-server used for embeddings |
CLAUDE_CODE_OAUTH_TOKEN |
claude-agent-token | OAuth token from claude setup-token |
CLAUDE_CLI_PATH |
claude-agent-* | path of the claude binary |
CLAUDE_AGENT_MODEL, CLAUDE_MODEL |
claude-agent-*, anthropic | default model |
ANTHROPIC_API_KEY (CLAUDE_TOKEN) |
anthropic | API key |
ANTHROPIC_MODEL |
anthropic | default model |
GEMINI_API_KEY (GOOGLE_API_KEY) |
gemini | API key |
GEMINI_MODEL |
gemini | default model |
AGY_CLI_PATH, AGY_CLI_TIMEOUT, AGY_CLI_MODEL, AGY_CLI_MODE |
antigravity | agy executable, timeout (s), model slug, --mode |
CODEX_CLI_PATH, CODEX_MODEL, CODEX_HOME, CODEX_TIMEOUT |
codex | codex executable, model, state dir, timeout (s) |
OLLAMA_SERVER (OLLAMA_HOST), OLLAMA_MODEL |
ollama | server URL, default model |
LLAMACPP_SERVER, LLAMACPP_MODEL, LLAMACPP_API_KEY, LLAMACPP_CLI_PATH |
llamacpp | server URL, model, bearer token, binary |
Recipes
Prefer local, fall back to cloud. Auto-detection prefers cloud; pass an explicit order instead:
from llmrouter import create_chat, detect_provider
chat = create_chat(detect_provider(["ollama", "llamacpp", "codex", "anthropic", "gemini"]))
Choose the provider from your own CLI – pass None when the user did not choose:
import argparse
from llmrouter import create_chat
ap = argparse.ArgumentParser()
ap.add_argument("--provider")
ap.add_argument("--model")
args = ap.parse_args()
chat = create_chat(args.provider, args.model) # provider None → auto-detect
A web endpoint (FastAPI-style) with streaming and disconnect handling:
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from llmrouter import create_chat
app = FastAPI()
@app.get("/ask")
async def ask(q: str):
chat = create_chat("ollama") # per-request conversation
return StreamingResponse(chat.achat_stream(q), media_type="text/plain") # a client disconnect cancels cleanly
Resilient batch – log and continue instead of aborting:
import logging
from llmrouter import LLMError, complete
log = logging.getLogger(__name__)
def safe(prompt: str) -> str | None:
try:
return complete(prompt)
except LLMError:
log.exception("LLM call failed for %r", prompt[:40])
return None
Unit-test code that uses llmrouter – subclass BaseChat:
from llmrouter import BaseChat, Provider, ProviderStatus
class FakeChat(BaseChat):
provider = Provider.OLLAMA
@classmethod
def check_available(cls):
return ProviderStatus(cls.provider, True, "fake")
def _stream(self, messages, temperature, max_tokens):
yield "canned reply"
Add your own provider. Subclass BaseChat, implement check_available() and _stream() (re-entrant: no per-call
state on self); locking, retries, validation, history and async come for free. Use it directly
(auto-detection only knows the eight built-ins). Embedding backends subclass BaseEmbedder the same way.
Errors and resilience
LLMError base of everything raised by llmrouter
├── TransientLLMError retryable (connection, 429/5xx, busy) – retried before the first chunk
├── InvalidRequestError (+ValueError) bad argument
├── ChatBusyError same thread re-entered its own open turn
├── ProviderUnavailableError missing SDK / credential / binary / server
│ └── NoProviderAvailableError auto-detection found nothing (.statuses has every reason)
└── UnknownProviderError (+ValueError) name matches no provider or alias
- Backend exceptions are wrapped in
LLMErrorwith the original as__cause__. - An empty reply is an error (so a blocked or failed generation is never returned as
""). - Probes (
probe_provider,check_available) never raise; they returnavailable=Falseplus the reason.
Troubleshooting
| Symptom | Fix |
|---|---|
NoProviderAvailableError |
run llmrouter providers; each line says what is missing |
| auto-detect picks a paid provider you did not want | set LLMROUTER_PROVIDER=ollama (or pass provider=) |
claude-agent-login says "not logged in" though claude works |
an exported ANTHROPIC_API_KEY is not a login; run claude auth login |
agy: command not found / not recognised |
open a new terminal; add %LOCALAPPDATA%\agy\bin (Windows) or ~/.local/bin to PATH, or set AGY_CLI_PATH |
| antigravity: "not signed in (authentication required)" | run agy once and finish the browser sign-in |
gemini-cli deprecation warning |
the legacy Gemini CLI lost Google sign-in for individuals; use antigravity (or gemini with an API key) |
codex: "not authenticated" / 401 invalid_api_key |
run codex, choose Sign in with ChatGPT (an old API key stored by codex login is rejected by OpenAI) |
ProviderUnavailableError … pip install 'pyllmrouter[…]' |
install the named extra |
| Ollama "not reachable" | ollama serve; check OLLAMA_SERVER |
| llama.cpp "still loading the model" | wait – /health returns 503 until the model is loaded |
ChatBusyError |
you called the chat again from the same thread while a stream of it was still open; finish/close it first |
Anthropic 400 … temperature |
not applicable – llmrouter never sends it |
Using llmrouter in another project
Depend on it straight from GitHub (pin a tag/commit for reproducibility):
# pyproject.toml
dependencies = [
"pyllmrouter[all] @ git+https://github.com/fortalbrz/llmrouter.git@main",
]
Pattern used by the reference consumer (Apex Music Machine): keep one thin module that turns your CLI
--provider/--model options into create_chat(provider or None, model or None, default_models={...}), and never branch
on provider names in application code.
Development
uv sync --all-extras # runtime extras + dev tools
uv run ruff format .
uv run ruff check . --fix
uv run pyrefly check
uv run pytest # coverage gate: 90 %
Layout: base.py (contract, locking, retries, async) · registry.py (names, order, probing, factory) · providers/
(one module per backend) · bridge.py (sync↔async) · _process.py (CLI runner) · cli.py. See
AGENTS.md for contribution rules.
Verification status
The 480-test suite exercises every provider against fakes (no network, no credentials) and real child processes for the
CLI runner and both CLI backends; the concurrency and async properties above (serialisation, parallelism, re-entry,
cancellation, loop shutdown) each have a dedicated test, and a mutation check (disabling the turn lock) fails six of
them. Live-verified on a development machine: provider probing, an end-to-end Ollama chat, and the Codex SDK and CLI
transports up to authentication (the stored API key on that machine was rejected by OpenAI with 401, which surfaced as the
documented error and left the history clean).
Not live-verified (needs your own account): successful answers from the Claude Agent SDK tiers, the Anthropic API
(incl. refusal fallback), google-genai, Codex with a valid login, a running llama-server, and the Antigravity CLI –
agy was not installed on the development machine, so its stream-json handling is implemented from Google's
documentation and tested with scripted child processes. Please open an issue if one misbehaves.
Autor
- Jorge Albuquerque, Ph.D. [LinkedIn] [X]
- GitHub: fortalbrz/llmopenfinance
License
MIT.
Metadata
Release files for pyllmrouter 0.4.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| pyllmrouter-0.4.1.tar.gz | 3.5 MB | Without provenance | Details for pyllmrouter-0.4.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pyllmrouter-0.4.1-py3-none-any.whl | Python 3 | none | any | Details for pyllmrouter-0.4.1-py3-none-any.whl |
Total release size: 3.5 MB
Release files / pyllmrouter-0.4.1.tar.gz
| Download URL | pyllmrouter-0.4.1.tar.gz |
|---|---|
| Size | 3.5 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
02d87c5e1ba92c6e830a9647bfac0303063418c8cf62174c08aa45d4e6430eba
|
|
BLAKE2b-256 checksum How to use checksums |
f062e0b5c9a213625eb2533ffb905f8f2883036af955f7ffe73d2c641a0be1b1
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.11.21 {"installer":{"name":"uv","version":"0.11.21","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Release files / pyllmrouter-0.4.1-py3-none-any.whl
| Download URL | pyllmrouter-0.4.1-py3-none-any.whl |
|---|---|
| Size | 70.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
09a3dd9e1842c79f53f8cb0fa51653d80cd01f6416b2a90bc41431115151ef98
|
|
BLAKE2b-256 checksum How to use checksums |
dabc3b78d07baae07e3e6d8653a99574f09b2360fba8a0857eb4c1cfc8350d02
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.11.21 {"installer":{"name":"uv","version":"0.11.21","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Security for pyllmrouter 0.4.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.