Metadata-Version: 2.5
Name: pyllmrouter
Version: 0.4.1
Summary: One chat interface, eight LLM backends: Claude Agent SDK, Anthropic API, Gemini API, Antigravity CLI, Codex, Ollama and llama.cpp, with automatic provider detection.
Project-URL: Homepage, https://github.com/fortalbrz/llmrouter
Project-URL: Issues, https://github.com/fortalbrz/llmrouter/issues
Author: Jorge Albuquerque
License: MIT License
        
        Copyright (c) 2026 Jorge Albuquerque
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: anthropic,antigravity,chat,claude,claude-agent-sdk,codex,gemini,llama.cpp,llm,ollama,router
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx>=0.27
Provides-Extra: all
Requires-Dist: anthropic>=0.40.0; extra == 'all'
Requires-Dist: claude-agent-sdk>=0.1.0; extra == 'all'
Requires-Dist: google-genai>=1.0.0; extra == 'all'
Requires-Dist: ollama>=0.6.0; extra == 'all'
Requires-Dist: openai-codex>=0.144; extra == 'all'
Provides-Extra: anthropic
Requires-Dist: anthropic>=0.40.0; extra == 'anthropic'
Provides-Extra: claude-agent
Requires-Dist: claude-agent-sdk>=0.1.0; extra == 'claude-agent'
Provides-Extra: codex
Requires-Dist: openai-codex>=0.144; extra == 'codex'
Provides-Extra: gemini
Requires-Dist: google-genai>=1.0.0; extra == 'gemini'
Provides-Extra: ollama
Requires-Dist: ollama>=0.6.0; extra == 'ollama'
Description-Content-Type: text/markdown

# llmrouter

**One chat interface, eight LLM backends – plus text embeddings – with automatic provider detection, thread-safe and async.**

![llm router logo](docs/img/logo.jpg)

`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.

```python
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.txt), [`llms-full.txt`](llms-full.txt),
> [`docs/providers.json`](docs/providers.json), [`AGENTS.md`](AGENTS.md), or run `llmrouter describe`.

---

## Contents

1. [Why](#why) · 2. [Install](#install) · 3. [Quick start](#quick-start) ·
4. [How a provider is chosen](#how-a-provider-is-chosen) · 5. [Provider guides](#provider-guides) ·
6. [Python API](#python-api) · [Embeddings](#embeddings) · 7. [Concurrency, async and robustness](#concurrency-async-and-robustness) ·
8. [Command line](#command-line) · 9. [Environment variables](#environment-variables) · 10. [Recipes](#recipes) ·
11. [Errors and resilience](#errors-and-resilience) · 12. [Troubleshooting](#troubleshooting) ·
13. [Using llmrouter in another project](#using-llmrouter-in-another-project) · 14. [Development](#development) ·
15. [Verification status](#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](#how-a-provider-is-chosen)).
* **Thread-safe and async.** A chat can be shared between threads and tasks (turns are serialised, history never
  interleaves); `achat_stream` never 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.

```bash
# 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

```python
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:

1. **A provider is set** – by the `provider` argument, `--provider`, or the `LLMROUTER_PROVIDER` environment
   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.
2. **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`).

```bash
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-cli` was removed.** Google ended "Sign in with Google" for individual accounts in the legacy Gemini CLI,
> so the id now resolves (with a deprecation warning) to `antigravity`. See [provider 5](#5-antigravity--antigravity-cli-agy).

> **Note on the default.** Because auto-detection prefers Claude, a machine that has `ANTHROPIC_API_KEY` set will use it
> when you give no provider. To stay local, set `LLMROUTER_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].

```bash
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:

![claude setup-token creating a long-lived authentication token](docs/img/img_claude_oath_001.png)

Store the token securely (a secret manager or your shell profile) – it cannot be shown again.

* Model: `CLAUDE_AGENT_MODEL` / `CLAUDE_MODEL` or `model=` (alias such as `sonnet`, 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.
* `temperature` and `max_tokens` are **not supported** by the Agent SDK and are ignored (debug-logged).
* `ANTHROPIC_API_KEY` / `ANTHROPIC_AUTH_TOKEN` are 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.

```bash
claude auth login        # one-off, interactive (opens a browser)
llmrouter ask -p claude-agent-login "hello"
```

* Detection runs `claude auth status` with credential variables blanked, so an exported API key can never be
  mistaken for a login. If the CLI cannot be run, `~/.claude/.credentials.json` is used as evidence.
* `CLAUDE_CLI_PATH` points at a specific `claude` binary (the SDK's bundled binary is the last fallback).
* All other behaviour and limits are identical to provider 1.

### 3. `anthropic` – Claude API key

```bash
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 with `model=`, `CLAUDE_MODEL` or `ANTHROPIC_MODEL`.
* Streams through the official SDK with a 10-minute timeout. `max_tokens` defaults to 16000 (the API requires one).
* **`temperature` is 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). A `refusal` stop reason raises `LLMError`; truncation at `max_tokens` is logged as a warning.

### 4. `gemini` – Gemini API key (`google-genai`)

```bash
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 with `model=` or `GEMINI_MODEL`.
* Supports `temperature` and `max_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:

```powershell
# 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
```

```bash
# Linux, macOS and WSL
curl -fsSL https://antigravity.google/cli/install.sh | bash
```

```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:

![agy first run: browser sign-in and authorization-code prompt in Windows PowerShell](docs/img/img_antigravity_oath_001.png)

After signing in, use it from Python or the shell:

```bash
agy -p "In one sentence, what is a git rebase?"     # what llmrouter runs under the hood (headless)
llmrouter ask -p antigravity "hello"
```

```python
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 from `agent_response`
  `text_delta` events and is reconciled with the final `result.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.** `agy` has 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-cli` exists (created by the first run), and
  the tail of the CLI's own `cli.log` does not contain `You are not logged into Antigravity` (which `agy` logs whenever it
  runs unauthenticated). If the probe is wrong, the first request fails with a clear "run `agy` once and finish the
  browser sign-in" error (the OAuth URL that `agy` prints is never echoed).
* **Heads-up:** run headless while *not* signed in, `agy` starts its interactive OAuth flow (it tries to open your browser)
  and exits with status 1. Sign in once with `agy` before using the provider.
* `--disable-slash-commands` is always passed, so a prompt that starts with `/` can never run a CLI command.
* `temperature` and `max_tokens` are not exposed by the CLI and are ignored. A `.cmd`/`.bat` wrapper 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.

```powershell
# 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):

```bash
pip install "pyllmrouter[codex] @ git+https://github.com/fortalbrz/llmrouter.git"   # installs openai-codex (import openai_codex)
llmrouter ask -p codex "hello"
```

```python
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_codex` starts a pinned `codex app-server` and streams
  `item/agentMessage/delta` notifications; **`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: run `codex` and choose Sign in with ChatGPT" error. *Note:* if `codex login status` says "API key",
  usage is billed at API rates, not on your ChatGPT plan – sign in with ChatGPT to use the plan.
* `temperature` and `max_tokens` are not supported by Codex and are ignored. Server-busy errors are retried.

### 7. `ollama` – Ollama server

```bash
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=`, else `OLLAMA_SERVER` / `OLLAMA_HOST`, else `http://localhost:11434`.
* Model: `model=`, else `OLLAMA_MODEL`, else `qwen3:8b`. Surrounding whitespace is stripped.
* Supports `temperature` and `max_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:

```bash
llama-server -m model.gguf --port 8080 --jinja
llmrouter ask -p llamacpp "hello"
```

* URL: `base_url=` / `LLAMACPP_SERVER` (default `http://localhost:8080`); bearer token from `LLAMACPP_API_KEY` when
  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):

```python
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

```python
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`) |

```python
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

```python
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) | – | – |

```python
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=)` mirrors `create_chat`: an explicit provider (or
  `LLMROUTER_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_MODEL` env var > `default_models` > library default). Asking for the embeddings
  of `anthropic`, `codex`, … raises `ProviderUnavailableError` listing the capable providers.
* **Batching and validation.** Inputs are split into backend-sized requests (`batch_size`, Gemini max 100). Blank or
  non-string texts raise `InvalidRequestError` before 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, Gemini `gemini-embedding-001` = 3072). Store `embedder.signature` next to persisted
  vectors and re-index when it changes.

```bash
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, `ChatBusyError` is raised instead of hanging. Finish or `close()` 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_providers` runs them
  concurrently); `LlamaCppServer.start()/stop()` are lock-protected.

```python
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.

```python
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 an `async for` early, 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 `achat` calls 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 `TransientLLMError` for failures worth retrying (connection refused, HTTP 429/5xx, "server busy").
  The turn is retried up to `chat.max_retries` times (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 the `TransientLLMError` is raised. Set `chat.max_retries = 0` to 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

```text
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
```

```bash
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:

```python
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:

```python
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:**

```python
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:

```python
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`:

```python
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

```text
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 `LLMError` with 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 return `available=False` plus 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):

```toml
# 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

```bash
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`](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](mailto:quantamentalguy@gmail.com)**, Ph.D. [[LinkedIn](https://www.linkedin.com/in/jorgealbuquerque)] [[X](https://x.com/quantamentalguy)]
- GitHub: [fortalbrz/llmopenfinance](https://github.com/fortalbrz/llmrouter)

## License

[`MIT`](LICENSE).

[Claude Agent SDK]: https://code.claude.com/docs/en/agent-sdk/python
[Codex Agent SDK]: https://learn.chatgpt.com/docs/codex-sdk
[Antigravity SDK]:https://antigravity.google/product/antigravity-sdk/
