Skip to main content
Every function on this page is importable from the top-level routehub package unless noted. import routehub loads nothing until you first use a name, so importing is cheap.

completion

Call any supported chat model with OpenAI-style arguments.

Returns

openai.types.chat.ChatCompletion
The OpenAI SDK’s own response type, for every provider. With stream=True, a ChatStream that yields openai.types.chat.ChatCompletionChunk objects and works as a context manager.

Request parameters

str
required
Provider-prefixed or bare model name, such as "gpt-5.4", "claude-sonnet-4-6" or "groq/llama-3.3-70b-versatile". See Providers.
list[dict]
required
OpenAI-format chat messages. Content can be a string or a list of content blocks (text, images, files, cache_control markers). An empty list raises BadRequestError.
bool
Stream the reply as ChatCompletionChunk objects. Pair with stream_options={"include_usage": True} to get usage on the final chunk.
list[dict]
Tool definitions in the OpenAI format. Translated for Claude. Use tool_choice and parallel_tool_calls to control selection.
dict | type
A pydantic model class for strict JSON-schema output, or a dict such as {"type": "json_object"}, sent as given.
str
One of "none", "minimal", "low", "medium", "high" or "xhigh". Mapped to a thinking budget or adaptive thinking on Claude. See Reasoning.
dict
Claude’s thinking configuration, such as {"type": "enabled", "budget_tokens": 2048}. Wins over reasoning_effort.
int
Output token cap. Sent as max_completion_tokens to OpenAI. Claude gets 4,096 when neither this nor max_completion_tokens is set.
temperature, top_p, n, stream_options, stop, max_completion_tokens, modalities, prediction, audio, presence_penalty, frequency_penalty, logit_bias, user, verbosity, seed, tool_choice, logprobs, top_logprobs, parallel_tool_calls, web_search_options, functions and function_call work as in the OpenAI chat API.Any other keyword argument, such as prompt_cache_key, is sent in the request body unless drop_params=True. litellm-only arguments such as metadata, caching and fallbacks are accepted and ignored.

Gateway options

str
API key. Defaults to the provider’s environment variable, read on each call.
str
Base URL override for a proxy, private endpoint or self-hosted server. base_url is an alias.
int
default:"2"
Retries on rate limits, server errors, timeouts and connection failures, with backoff that honours retry-after.
bool
default:"False"
Drop parameters the model rejects instead of raising UnsupportedParamsError.
float
Request timeout in seconds. Overrides request_timeout (default 600.0).
str | Exception
Return this text, or raise this exception, without calling a provider.
OpenAI | AsyncOpenAI | httpx.Client
Your own preconfigured client. OpenAI SDK clients for OpenAI-compatible providers, httpx clients for Claude.
api_version (Azure), custom_llm_provider, extra_headers, extra_body (always sent), ssl_verify (default True, or a CA bundle path), keepalive_expiry (default 60.0), gzip (Claude request bodies; None reads ROUTEHUB_GZIP_ON), set_verbose (default False) and request_timeout (default 600.0). See Configuration.

Examples


acompletion

Async form of completion. It takes exactly the same arguments and returns the same types.
openai.types.chat.ChatCompletion
The response. With stream=True, an AsyncChatStream of ChatCompletionChunk objects, used with async for and async with.
HTTP clients are cached per event loop, so concurrent calls reuse pooled connections.

embedding

Embed text with any OpenAI-compatible embeddings model.
str
required
Embedding model, such as "text-embedding-3-small" or "gemini/gemini-embedding-001".
str | list[str]
required
Text or texts to embed.
int
Output dimensions, where the model supports it.
str
"float" or "base64".
Also takes api_key, api_base, base_url, api_version, custom_llm_provider, extra_headers, extra_body, num_retries, ssl_verify, keepalive_expiry, request_timeout, timeout and client. There is no mock_response; pass a fake OpenAI client as client= in tests.
openai.types.CreateEmbeddingResponse
data[i].embedding holds each vector, in input order. usage.prompt_tokens holds the token count.
aembedding is the async form, with the same arguments. Claude models raise BadRequestError, because Anthropic has no embeddings API.

responses

Call a model through the OpenAI Responses API.
str
required
Provider-prefixed or bare model name for a provider that serves the Responses API, such as OpenAI.
Any
Any Responses API parameter (input, instructions, tools, reasoning, stream and so on), plus completion’s gateway options except mock_response.
openai.types.responses.Response
The SDK’s own Response, or its event stream when stream=True.

batched_completions

Run many chat requests through OpenAI’s Batch API, Groq’s Batch API or Anthropic’s Message Batches API, at about half the price of regular calls.
str
required
An OpenAI, Groq or Claude model, such as "gpt-5.4-mini", "groq/llama-3.1-8b-instant" or "claude-sonnet-4-6". Other providers raise BadRequestError.
list[dict]
required
completion arguments for each request, such as messages and max_tokens. Cannot be empty.
bool
default:"True"
Poll until the batch finishes and return its results. When False, return a BatchJob at once.
float
default:"30"
Seconds between status checks.
float
default:"86400"
Seconds to wait before raising Timeout. The batch keeps running and BatchJob can still collect it.
Any
completion arguments shared by every request, such as api_key, temperature or client.
list
One ChatCompletion per request in request order, or the RouteHub exception for a request that failed. A BatchJob when wait=False.
abatched_completions takes the same arguments and keeps the event loop free while the batch runs.

BatchJob

A submitted batch, rebuildable from its provider and ID in any process.

get_llm_provider

Resolve a model string to its provider, API key and base URL without sending a request.
tuple
The bare model name, provider, API key and base URL. Raises BadRequestError when no provider can be determined.

PROVIDERS

A dict of every provider name to its Provider record: name, base_url, key_env, base_env, native, default_key and base_suffix.

get_model_info

Return the metadata for a model from the live OpenRouter catalog, the built-in embedding table, or your registered models.
str
required
A bare or provider-prefixed model name. Anthropic-style names, dated names and serving-provider IDs such as groq/llama-3.3-70b-versatile are matched to the vendor’s entry.
str
Explicit provider, reported back as provider.
dict
Raises ModelNotMappedError when the model is unknown.
The catalog is fetched on first use and cached for five minutes. The last good copy is kept on disk at ROUTEHUB_CACHE_DIR for offline runs. See Model catalog.

get_max_tokens

Returns the model’s output token limit. Raises ModelNotMappedError for unknown models.

supports_* checks

Each takes (model: str, custom_llm_provider: str | None = None) and returns bool. Unknown models return False.

register_model

Add or override models in litellm’s model-info shape. Registered entries take priority over catalog data and never expire.
dict | str
required
A dict of model name to info, or a path to a JSON file of it. Fields merge into an earlier registration of the same name.
dict
All registered models.

model_list, model_cost and clear_model_cache

Both model_list and model_cost refresh with the catalog, so read them from routehub each time rather than binding them once.

get_all_models

List models from each provider’s own models API, concurrently, in one consistent shape. Import these from routehub.get_all_models.
Iterable[str]
Providers to list. Every supported source with a key configured, plus OpenRouter, when omitted.
float
default:"10"
Per-request timeout in seconds.
bool
default:"False"
Ignore the five-minute cache and fetch again.
list[dict]
Entries grouped by provider. A provider that fails or has no key contributes nothing.

token_counter

Count the tokens in a text or a chat message list.
str
Model whose tokenizer to use. Models tiktoken doesn’t know use o200k_base, so counts for non-OpenAI models are estimates.
str
A plain string to count.
list[dict]
Chat messages to count, including message overhead.

encode and decode

When no tokenizer can be loaded, for example offline before tiktoken has cached its files, counts fall back to four bytes per token.

get_reasoning_efforts

Returns the values reasoning_effort accepts: ("none", "minimal", "low", "medium", "high", "xhigh").

Exceptions

Every provider failure is raised as one of these, importable from routehub or routehub.exceptions. Each subclasses the matching OpenAI SDK exception and carries status_code, llm_provider, model and message. BadRequestError, UnsupportedParamsError, ContextWindowExceededError, ContentPolicyViolationError, AuthenticationError, PermissionDeniedError, NotFoundError, UnprocessableEntityError, RateLimitError, ServiceUnavailableError, InternalServerError, APIError, APIConnectionError, Timeout, OpenAIError and ModelNotMappedError.
See Error handling for when each one is raised.