Skip to content

core

robotsix_llmio.core

Provider-agnostic LLM I/O base.

All submodule imports are deferred via PEP 562 __getattr__ so that importing lightweight helpers (e.g. core.retry) does not eagerly pull in pydantic-ai or OpenTelemetry at module load time.

TierConfigLoadError

Bases: RobotsixLLMIOError

Raised when tier configuration cannot be loaded.

This wraps underlying pydantic :class:~pydantic.ValidationError(s) as __cause__ so the original details are always available.

FailoverConfig

Bases: BaseModel

Automatic provider-failover policy.

After :attr:failure_threshold consecutive provider-shaped failures on the default slot (a provider-wide exhaustion arms failover immediately), calls route to the fallback slot for :attr:window_seconds, then automatically return to default. See :mod:robotsix_llmio.core.failover.

ProviderSlotConfig

Bases: BaseModel

One provider slot's binding of all three capability levels.

A slot is a role (a position in :attr:TierConfig.chain), not a provider name: each level entry carries its own combined provider-model identifier, so a slot can technically mix backends. The baked configuration keeps each slot on one provider — that is what makes provider-level failover meaningful.

for_level

for_level(level)

Return the :class:TierLevelConfig for integer level (1, 2, or 3).

Raises:

Type Description
ValueError

If level is not 1, 2, or 3.

TierConfig

Bases: BaseModel

Ordered N-slot, three-level provider+model configuration.

:attr:chain is an ordered sequence of :class:ProviderSlotConfig entries: position 0 is the provider used in normal operation, and each later position is the next provider to cascade to while failover is active. Any number of slots (>= 1) is supported.

All fields are optional: the baked chain is Anthropic via the direct Messages API (position 0), Anthropic via the Claude SDK (position 1), then DeepSeek via OpenRouter (position 2), so TierConfig() yields the fully baked configuration.

The legacy two-slot shape (top-level default / fallback keys) is still accepted and migrated onto the chain — default becomes position 0 and fallback position 1 of a two-slot chain; an omitted legacy key keeps its baked slot (Claude SDK / OpenRouter respectively). Example YAML/JSON (legacy shape)::

{"default": {"level1": {...}, "level2": {...}, "level3": {...}}}

or the chain shape::

{"chain": [{"level1": {...}, ...}, {...}, {...}]}

Use :meth:for_level to resolve an integer level to the corresponding :class:TierLevelConfig; by default it resolves against the slot the failover tracker currently designates as active.

default property

default

Legacy alias for chain position 0 (the normal-operation slot).

fallback property

fallback

Legacy alias for chain position 1 (the first failover slot).

Raises:

Type Description
ValueError

If the chain holds a single slot.

slot_index

slot_index(name)

Return the zero-based chain position designated by name.

Parameters:

Name Type Description Default
name ProviderSlotName

A chain index (0 <= name < len(chain)) or a legacy slot-name alias ("default" = 0, "fallback" = 1).

required

Raises:

Type Description
ValueError

If name is not a valid chain index or alias.

slot

slot(name)

Return the :class:ProviderSlotConfig at chain position name.

Parameters:

Name Type Description Default
name ProviderSlotName

A chain index or a legacy slot-name alias — see :meth:slot_index.

required

Raises:

Type Description
ValueError

If name is not a valid chain index or alias.

for_level

for_level(level, slot=None)

Resolve integer level (1, 2, or 3) to a :class:TierLevelConfig.

Parameters:

Name Type Description Default
level int

Capability level — 1, 2, or 3.

required
slot ProviderSlotName | None

Which provider slot to resolve against — a zero-based chain index or a legacy alias ("default" / "fallback"). None (the default) resolves against the slot the process-wide failover tracker currently designates as active. Pass an explicit slot for pure config access (e.g. to display every binding in a UI).

None

Raises:

Type Description
ValueError

If level is not 1, 2, or 3, or slot is not a valid chain position.

TierLevel

Bases: StrEnum

Three-level capability selector.

Member Value Purpose
LEVEL1 level1 Cheap, frequent: monitors, classifiers, summaries
LEVEL2 level2 Workhorse: implementing code, main assistant turns
LEVEL3 level3 Frontier: hardest reasoning and long-horizon work

Collapsed from five levels on 2026-09-01: equivalent-capability models on other providers are no longer separate levels — they live in the fallback provider slot of :class:TierConfig at the same level.

TierLevelConfig

Bases: BaseModel

A single level's provider-model binding.

Describes which combined provider-model identifier to use for a given :class:TierLevel. The identifier is <provider>-<model-name>: the provider prefix (before the first hyphen) and the concrete model name — e.g. "claudeSDK-opus" or "openrouter-deepseek/deepseek-v4-flash-20260731".

A :func:~pydantic.model_validator parses the identifier and confirms the provider prefix is a known backend; the concrete model name is the backend's concern (no upfront registry check).

provider property

provider

Provider prefix parsed from the identifier.

model_name property

model_name

Concrete model name parsed from the identifier.

AgentHandle

Wraps a pydantic-ai Agent with its HTTP (httpx2) client so callers can deterministically close the client after use. Delegates attribute access to the underlying agent so existing call sites (and test mocks) work unchanged.

close

close()

Close the HTTP client. Idempotent.

aclose async

aclose()

Close the HTTP client from an async context. Idempotent.

CostLogSource

Bases: Protocol

Backend-neutral read interface for logged cost.

A backend adapter implements this single method to expose logged cost over a time window. Consumers depend on this protocol, not on any concrete backend.

fetch_logged_cost

fetch_logged_cost(window)

Return the logged cost recorded over window.

CostRecord dataclass

One logged unit of cost (one trace).

session_id and name are populated when the backend exposes them.

CostWindow dataclass

A time window to query logged cost for.

start is treated as inclusive and end as exclusive; adapters serialize these as ISO-8601 timestamps for the backend.

LoggedCost dataclass

Aggregate result of a logged-cost query.

records is the per-call/per-trace breakdown backing total_cost.

FailoverStatus

Bases: BaseModel

Snapshot of the failover tracker, shaped for consumer status APIs.

Consumers expose this (e.g. .model_dump(mode="json")) from their own status endpoints so their UIs can show which provider slot is serving calls and, during failover, when the default slot returns.

ProviderFailoverTracker

Track per-slot health and route calls down the provider chain.

Every slot of the ordered chain (see :attr:TierConfig.chain) has its own failure streak and failover window. New calls resolve against the first slot whose window is not armed, so failures cascade down the chain — position 0, then 1, then 2, … — and calls climb back up as each earlier slot's window expires (the next call then probes it). The last slot never arms: there is nothing further to cascade to, so its failures only update the last-failure status fields.

With a two-slot chain this is exactly the historic default / fallback behaviour.

Thread-safe: consumers run agents from worker threads and event loops concurrently, and status reads come from web handlers.

configure

configure(config, chain_length=None)

Adopt config as the active threshold + window policy.

chain_length, when given, is the number of slots in the routed chain: it bounds :meth:active_slot and decides which slot is last (and therefore never arms).

active_index

active_index(now=None, chain_length=None)

Return the zero-based chain position new calls should start on.

chain_length clamps the result to the last slot of the routed chain (defaults to the length adopted via :meth:configure).

active_slot

active_slot(now=None, chain_length=None)

Return the slot new calls should resolve against.

Positions 0 and 1 are reported by their legacy names ("default" / "fallback"), deeper positions by their integer index.

record_failure

record_failure(slot, exc, now=None, wall_now=None)

Record a provider-shaped failure on slot.

Exhaustion arms that slot's failover window immediately, other failures arm it once failure_threshold consecutive ones accumulate; while armed, calls cascade to the next slot. Failures on the last slot of the chain update the last-failure fields for status display only — there is nowhere further to cascade, and the earlier slots' windows govern the climb back up the chain.

record_success

record_success(slot)

Record a success on slot.

A success clears that slot's failure streak and any armed window (the provider is demonstrably healthy again) and forgets its backoff escalation. Other slots are untouched — an earlier slot's window alone decides when calls climb back to it.

status

status(now=None)

Return a :class:FailoverStatus snapshot.

failover_until / seconds_remaining name the earliest moment calls climb back up the chain (the soonest-expiring window among the armed slots ahead of the active one).

reset

reset()

Clear all state (useful for tests).

MalformedIdentifierError

Bases: RobotsixLLMIOError

Raised when a provider-model identifier string is malformed.

ParsedIdentifier

Bases: NamedTuple

Result of :func:parse_model_identifier.

Attributes:

Name Type Description
provider str

The provider prefix before the first hyphen (e.g. "claudeSDK" or "openrouter").

model_name str

Everything after the first hyphen — the concrete model name fed to the backend. May contain hyphens and slashes (e.g. "deepseek/deepseek-v4-flash-latest").

AsyncLangfuseReadClient

Bases: _LangfuseReadClientBase

Async variant of :class:LangfuseReadClient.

Owns the same reusable kernel — auth header, base-URL resolution, and pagination — but uses httpx.AsyncClient so it is safe to call from within an event loop.

Credentials are always passed in explicitly; the client reads no LANGFUSE_* env vars.

aiter_pages async

aiter_pages(url, params=None, *, error_label='request')

Paginate url (1-based page), yielding each page's data.

Owns the httpx.AsyncClient, the page loop, the Basic auth header, the non-2xx LangfuseClientError (labelled with error_label), the empty-data break, and the meta.totalPages termination. url may be an absolute URL or a path relative to :attr:base_url.

fetch_traces_window async

fetch_traces_window(hours)

Yield individual traces created in the last hours hours.

Convenience wrapper that computes fromTimestamp and flattens the paginated pages into a stream of individual trace dicts.

fetch_trace_detail async

fetch_trace_detail(trace_id)

Fetch a single trace by its Langfuse trace ID.

parse_timestamp staticmethod

parse_timestamp(value)

Parse an ISO-8601 timestamp (tolerating a trailing Z).

observation_provider staticmethod

observation_provider(obs)

Pull the provider tag out of an observation's metadata.

observation_cost staticmethod

observation_cost(obs)

USD cost of one Langfuse observation.

LangfuseClientError

Bases: RobotsixLLMIOError

Error from the Langfuse API client (HTTP, auth, iteration limit).

LangfuseReadClient

Bases: _LangfuseReadClientBase

Speak the Langfuse REST read protocol.

Owns the reusable kernel — auth header, base-URL resolution, and 1-based pagination over the public endpoints — so adapters need not re-derive it. Credentials are always passed in explicitly; the client reads no LANGFUSE_* env vars (env defaulting, if any, belongs to the consumer).

iter_pages

iter_pages(url, params=None, *, error_label='request')

Paginate url (1-based page), yielding each page's data.

Owns the httpx.Client, the page loop, the Basic auth header, the non-2xx LangfuseClientError (labelled with error_label), the empty-data break, and the meta.totalPages termination. url may be an absolute URL or a path relative to :attr:base_url.

parse_timestamp staticmethod

parse_timestamp(value)

Parse an ISO-8601 timestamp (tolerating a trailing Z).

observation_provider staticmethod

observation_provider(obs)

Pull the provider tag out of an observation's metadata.

observation_cost staticmethod

observation_cost(obs)

USD cost of one Langfuse observation.

LangfuseCostLogSource

Read logged cost back from Langfuse via its public REST API.

Implements :class:~robotsix_llmio.core.cost_log.CostLogSource. Credentials are always passed in explicitly — the adapter reads no LANGFUSE_* env vars (env defaulting, if any, belongs to the consumer). The Langfuse REST kernel (auth, base-URL, pagination) is delegated to :class:~robotsix_llmio.core.langfuse_client.LangfuseReadClient.

fetch_logged_cost

fetch_logged_cost(window)

Fetch and aggregate logged trace cost over window.

Pages through the public traces endpoint (1-based page + limit) until a page returns no data (or the response's meta.totalPages is reached), then sums trace-level totalCost and builds a :class:CostRecord per trace. Raises LangfuseClientError on any non-2xx response rather than silently returning zero.

fetch_logged_cost_by_provider

fetch_logged_cost_by_provider(window, provider)

Fetch logged GENERATION cost over window, summing only the slice whose observation metadata provider equals provider.

The write path stamps langfuse.observation.metadata.provider (e.g. "openrouter" / "claude-sdk") so cost can be reconciled PER PROVIDER — an OpenRouter key only bills the OpenRouter slice, so a claude_sdk fleet (no independent billing API) reconciles 0-vs-0 instead of false-flagging all Claude spend. The public observations endpoint has no server-side metadata filter, so paginate type=GENERATION over the window and filter client-side. Raises LangfuseClientError on non-2xx.

prune_before

prune_before(cutoff)

Delete logged traces older than cutoff (timestamp < cutoff).

Time-based retention — keeps the cost log bounded while guaranteeing any window at/after cutoff stays fully reconcilable (the consumer reconciles only windows inside this horizon). Lists the oldest traces up to cutoff (toTimestamp + timestamp.asc) and bulk-deletes them in pages until none remain. Returns the count deleted; raises LangfuseClientError on any non-2xx response.

LLMProvider

Bases: ABC

Base for every provider. A derived provider implements :meth:new_model (and optionally :meth:_is_transient); the generic build_agent / call_with_retry are inherited.

new_model abstractmethod

new_model(*, model=None, level=0)

Return (model, http_client) — a fully configured pydantic-ai model (provider/auth/cost/quirks baked in) plus the http client to close when done.

Parameters

model: The concrete model name (e.g. "deepseek/deepseek-v4-flash-latest"). level: Capability level (1, 2, or 3) for per-level policy hooks. 0 is the sentinel for "unknown / direct new_model() call" — providers should apply a safe default.

build_agent

build_agent(
    *,
    level=1,
    tier_config=None,
    model=None,
    system_prompt,
    tools=None,
    output_type=str,
    name=None,
    retries=2,
    builtin_tools=True,
    web_tools=False,
    images=None,
    vision_api_key=None,
)

Build a ready-to-run agent for the requested capability level.

builtin_tools is honored only by the claude-sdk provider (whose SDK ships a built-in toolset); set it False to restrict that agent to only the explicitly provided tools. Other providers expose no built-in tools and accept it as a no-op.

Parameters

level: Integer 1-3 selecting the capability level:

- ``1`` — cheap, frequent: monitors, classifiers, summaries
- ``2`` — workhorse: implementing code, main assistant turns
- ``3`` — frontier: hardest reasoning and long-horizon work
tier_config

When provided, resolution is::

tlc = tier_config.for_level(level)
new_model(model=tlc.model_name)

When None, a default :class:~robotsix_llmio.config.tier.TierConfig is built via the no-arg constructor, which produces independent deep copies of the baked defaults.

Ignored when model is provided (see below).

model: Optional explicit bare model name override (not a full provider-model identifier). When provided, this is passed directly to :meth:new_model, bypassing tier_config resolution entirely. The caller is responsible for providing a valid model name for the provider. When None (default), the model is resolved from tier_config as usual. system_prompt: Final system prompt for the agent (domain concern). tools: Optional list of Python functions the agent may call. output_type: Expected return type; defaults to :class:str. At level >= 2 a raw structured type (pydantic model, dataclass, etc.) is automatically wrapped in :class:~pydantic_ai.PromptedOutput to avoid the forced tool_choice / thinking-mode conflict. Pass an explicit :class:~pydantic_ai.ToolOutput, :class:~pydantic_ai.NativeOutput, or :class:~pydantic_ai.PromptedOutput to opt out of the auto-wrap. name: Optional name for the agent (used in traces). retries: Maximum retry attempts for the underlying pydantic-ai agent (default 2). builtin_tools: When True (default), allows the provider to expose its built-in toolset (only honored by the claude-sdk provider). Set False to restrict the agent to only the explicitly provided tools. web_tools: Grants WebFetch / WebSearch even when builtin_tools is False. They read nothing local and mutate nothing, so an agent restricted from the filesystem and shell can still look something up. Default False — an agent that never needs the web should not carry the capability. Also only honored by the claude-sdk provider. images: Attached images as (media_type, bytes) pairs. Transport- dependent: the Claude SDK provider overrides this to deliver them NATIVELY (Claude models read images). Here — the generic path serving OpenRouter's text-only models — the agent instead gets an ask_image tool answered by the tier config's vision binding, plus a system-prompt note pointing at it. Either way the caller's prompt stays TEXT-ONLY: do not embed BinaryContent when passing images=. vision_api_key: API key for the vision binding's provider. Precedence: this argument, else the provider's own OpenRouter key (when this IS an OpenRouter-family provider), else the vision provider's environment fallback (OPENROUTER_API_KEY).

Returns

AgentHandle A ready-to-run agent handle wrapping a pydantic-ai Agent and its httpx2 client. Call .close() when done.

call_with_retry

call_with_retry(
    fn, *, what="model call", sleep=sleep, fallback_fn=None
)

Run fn with bounded transient/rate-limit retry, using this provider's transient signatures.

Discrepancy dataclass

Outcome of reconciling logged cost against provider-billed cost.

ProviderCost dataclass

Provider-billed cost for a window.

breakdown maps a provider-defined label (e.g. model id) to its cost; request_count is the provider's own request tally when exposed (0 when not). total_cost is authoritative — breakdown is for diagnostics.

ProviderCostSource

Bases: Protocol

Backend-neutral read interface for provider-billed cost over a window.

fetch_provider_cost

fetch_provider_cost(window)

Return the provider-billed cost over window.

TraceSpan

Handle to a root span: set trace-level input/output, read the trace id.

trace_id property

trace_id

The 32-hex-char trace id of the root span, or None when there is no active span.

set_input

set_input(value)

Record value as the trace-level input (no-op when not recording).

set_output

set_output(value)

Record value as the trace-level output (no-op when not recording).

create_model

create_model(
    *,
    level=1,
    tier_config=None,
    slot=None,
    **provider_kwargs,
)

Create a provider instance for the given capability level.

The provider is derived from the combined provider-model identifier on the tier config — the identifier's prefix drives lazy backend import via :func:~robotsix_llmio.core.factory.get_provider_for_identifier.

Parameters:

Name Type Description Default
level int

Capability level (1, 2, or 3). Level 1 is the cheap frequent tier, level 2 the workhorse, level 3 the frontier (claudeSDK-claude-fable-5 by default). Resolution honours the provider slot the failover tracker currently designates as active (see :mod:robotsix_llmio.core.failover).

1
tier_config TierConfig | None

Optional :class:~.tier.TierConfig to resolve the provider + model. When None, a default TierConfig() is built; its default_factory lambdas produce independent deep copies of the baked defaults.

None
slot ProviderSlotName | None

Explicit provider slot ("default" or "fallback") to resolve against; None follows the failover tracker's active slot.

None
**provider_kwargs Any

Forwarded to the provider constructor (e.g. api_key=... for the OpenRouter provider). These override any provider_kwargs from the tier config.

{}

Returns:

Name Type Description
LLMProvider LLMProvider

A fully-instantiated provider ready for :meth:~LLMProvider.build_agent or :meth:~LLMProvider.new_model calls.

Raises:

Type Description
ValueError

If level is not 1, 2, or 3.

ImportError

If the provider's optional extra is not installed.

Example:

.. code-block:: python

from robotsix_llmio.config import create_model

# Level 2 → Claude SDK by default (identifier "claudeSDK-opus").
provider = create_model(level=2)
agent = provider.build_agent(
    level=2,
    system_prompt="You are a helpful assistant.",
)

load_tier_config

load_tier_config(config_dict=None)

Load a validated :class:TierConfig, merging config_dict over the baked defaults.

Parameters:

Name Type Description Default
config_dict dict[str, Any] | None

Optional dict in the :class:TierConfig shape (see the module docstring). Per-level dicts merge field-by-field over the baked default for that slot+level; the failover dict merges field-by-field over the default policy. None (or {}) yields the fully baked configuration.

None

Returns:

Name Type Description
TierConfig TierConfig

A fully-validated configuration — the baked three-slot

TierConfig

chain, or a two-slot (Claude SDK / OpenRouter) chain when the legacy

TierConfig

default / fallback keys are supplied.

Raises:

Type Description
TierConfigLoadError

If the merged configuration fails validation — an unknown provider prefix in a supplied model, an unknown key anywhere in the shape, or a slot/level value that is not a dict or pydantic model.

build_agent

build_agent(
    model,
    http_client,
    *,
    system_prompt,
    tools=None,
    output_type=str,
    name=None,
    retries=2,
)

Assemble a pydantic-ai Agent from an already-configured model and wrap it (with http_client) in an :class:AgentHandle.

Provider-agnostic: the model carries provider/pin/reasoning/cost; this function only does the generic Agent wiring. The system prompt, tools, and output_type are supplied verbatim by the caller (the consumer owns prompt composition and tool selection).

flush_current_provider

flush_current_provider()

Best-effort force-flush of the active OTel TracerProvider.

Called around retry backoffs so spans export before a long sleep. No-op when OTel is absent or the provider can't flush.

record_cost

record_cost(response, get_cost, *, provider=None)

Pull the USD cost out of response via get_cost and stamp it onto the current span using gen_ai semantic-convention attributes.

provider (e.g. "openrouter" / "claude-sdk") is stamped as langfuse.observation.metadata.provider — Langfuse indexes it onto the observation's metadata, so a consumer can sum logged cost PER PROVIDER (e.g. reconcile only the OpenRouter slice against an OpenRouter key). Harmless on backends that ignore it.

build_agent_for_level

build_agent_for_level(
    level,
    *,
    tier_config=None,
    slot=None,
    model=None,
    provider_kwargs=None,
    **build_kwargs,
)

Build an agent on the provider+model bound to a capability level.

This is the single entry point a consumer needs: pick a level and get a ready-to-run agent on that level's default provider and model — no provider knowledge required. Resolution is:

  1. resolve the level's :class:~robotsix_llmio.config.tier.TierLevelConfig from tier_config (or :func:default_tier_config when None);
  2. lazy-import the provider via :func:get_provider_for_identifier, passing provider_kwargs (falling back to the level's provider_kwargs) to its constructor;
  3. call provider.build_agent(level=level, model=..., **build_kwargs).

With everything left at its default a consumer calls build_agent_for_level(1, system_prompt=..., output_type=str, name=...) for a cheap Claude-haiku agent, build_agent_for_level(2, system_prompt=..., tools=..., output_type=str, name=...) for a Claude-opus workhorse agent, and build_agent_for_level(3, system_prompt=..., name=...) for a Claude-Fable-5 frontier agent — or the DeepSeek equivalents while provider failover is active.

Parameters:

Name Type Description Default
level int

Capability level — 1 (cheap/frequent), 2 (workhorse), or 3 (frontier).

required
tier_config TierConfig | None

Per-level (provider, model) binding to resolve against. When None, the baked defaults from :func:default_tier_config are used (i.e. omitting everything uses the baked defaults).

None
slot ProviderSlotName | None

Explicit provider slot ("default" or "fallback") to resolve against; None follows the failover tracker's active slot.

None
model str | None

Optional bare model-name override. It overrides only the model name; the provider stays the one bound to level. When None (default), the level's baked model name is used.

None
provider_kwargs dict[str, Any] | None

Keyword arguments for the provider constructor. When None, the level's provider_kwargs are used.

None
**build_kwargs Any

Forwarded verbatim to provider.build_agent (e.g. system_prompt, tools, output_type, name, retries, builtin_tools).

{}

Returns:

Name Type Description
AgentHandle Any

A ready-to-run agent handle. Call .close() when done.

Raises:

Type Description
ValueError

If level is not 1, 2, or 3 (via :meth:TierConfig.for_level), or if the level's identifier names an unknown provider prefix.

MalformedIdentifierError

If the level's identifier cannot be parsed.

ImportError

If the resolved provider's optional extra is not installed (the default slot's levels require the claude_sdk extra).

default_tier_config

default_tier_config()

Return a :class:TierConfig built from the baked defaults.

The baked binding is two provider slots of three levels each:

  • default (Anthropic via the Claude SDK): level 1 → claudeSDK-haiku, level 2 → claudeSDK-opus, level 3 → claudeSDK-claude-fable-5.
  • fallback (DeepSeek via OpenRouter): levels 1 and 2 → flash (level 2 with xhigh reasoning), level 3 → pro.

The no-arg TierConfig() constructor uses default_factory functions that produce independent deep copies of the baked defaults, so each call returns a fresh config that aliases nothing.

Returns:

Name Type Description
TierConfig TierConfig

A config holding fresh copies of the baked defaults.

get_provider_for_identifier

get_provider_for_identifier(identifier, **kwargs)

Resolve and instantiate a provider from a combined tier identifier.

The identifier is parsed via :func:~.identifier.parse_model_identifier, the provider prefix looked up in :data:_PROVIDER_PREFIX_MAP, and the backend is lazy-imported. **kwargs are forwarded to the provider constructor.

Parameters:

Name Type Description Default
identifier str

Combined provider-model identifier — e.g. "claudeSDK-opus" or "openrouter-deepseek/deepseek-v4-flash-latest".

required
**kwargs Any

Forwarded to the resolved provider class constructor.

{}

Returns:

Name Type Description
LLMProvider LLMProvider

A fully-instantiated provider.

Raises:

Type Description
MalformedIdentifierError

If identifier cannot be parsed.

ValueError

If the parsed provider prefix is not in :data:_PROVIDER_PREFIX_MAP.

ImportError

If the provider's optional extra is not installed.

get_provider_for_level

get_provider_for_level(
    level, *, tier_config=None, slot=None, **kwargs
)

Resolve and instantiate the provider bound to a capability level.

The (provider, model) binding for level is read from tier_config (or :func:default_tier_config when None), resolved against the provider slot the failover tracker currently designates as active; the level's combined identifier drives the provider lazy-import, exactly as :func:get_provider_for_identifier. The tier level's provider_kwargs are merged with **kwargs (caller **kwargs win on conflict) and forwarded to the provider constructor.

Parameters:

Name Type Description Default
level int

Capability level — 1 (cheap/frequent), 2 (workhorse), or 3 (frontier).

required
tier_config TierConfig | None

Per-level (provider, model) binding to resolve against. When None, the baked defaults from :func:default_tier_config are used.

None
slot ProviderSlotName | None

Explicit provider slot ("default" or "fallback") to resolve against. None (the default) follows the failover tracker's active slot. Pass an explicit slot to build a provider for the other slot — e.g. a failover loop's cross-slot attempt, or a status UI showing both bindings.

None
**kwargs Any

Forwarded to the resolved provider class constructor, merged over the tier level's provider_kwargs (caller values win).

{}

Returns:

Name Type Description
LLMProvider LLMProvider

A fully-instantiated provider for the level's bound backend.

Raises:

Type Description
ValueError

If level is not 1, 2, or 3 (via :meth:TierConfig.for_level), or if the level's identifier names an unknown provider prefix.

MalformedIdentifierError

If the level's identifier cannot be parsed.

ImportError

If the resolved provider's optional extra is not installed (claude_sdk for the default slot's levels).

acall_with_failover async

acall_with_failover(
    fn_factory,
    *,
    tier_config,
    level,
    failover_enabled=True,
    what="model call",
)

Async mirror of :func:call_with_failover.

Identical semantics except fn_factory returns an awaitable-producing callable and the callable is awaited.

call_with_failover

call_with_failover(
    fn_factory,
    *,
    tier_config,
    level,
    failover_enabled=True,
    what="model call",
)

Run fn_factory-produced callables with provider failover.

Parameters:

Name Type Description Default
fn_factory Callable[[TierLevelConfig], Callable[[], T]]

Called with the :class:TierLevelConfig resolved for the attempted provider slot; must return a zero-argument callable that performs the actual work (typically a model call with provider-specific retry). Called fresh per slot attempted.

required
tier_config TierConfig

A validated :class:TierConfig; its failover policy is adopted by the process-wide tracker.

required
level int

Capability level (1, 2, or 3). The level never changes across attempts — only the provider slot does.

required
failover_enabled bool

When True (the default), a provider-shaped failure on the active slot retries the same level on the next slot of the chain, cascading until one succeeds or the chain is exhausted. Pass False where a caller depends on one specific provider's behaviour rather than on getting an answer.

True
what str

Human-readable label for log messages.

'model call'

get_failover_status

get_failover_status()

Snapshot the process-wide failover state — the consumer-UI surface.

get_failover_tracker

get_failover_tracker()

Return the process-wide :class:ProviderFailoverTracker singleton.

is_provider_shaped

is_provider_shaped(exc)

True when exc points at the provider rather than the task.

A provider-shaped failure is one where running the same request on a different provider can plausibly succeed: transient transport errors that outlived their retries, rate limits, usage exhaustion, and provider-wide exhaustion (:class:ProviderExhaustedError). Task-shaped failures — a turn-limit blowout, a validation error in the caller's own output type — raise straight through: re-running a doomed task on the other provider would only spend money twice.

reset_failover_tracker

reset_failover_tracker()

Reset the process-wide singleton (for test teardown).

timeout_http_client

timeout_http_client()

A fresh httpx2.AsyncClient with a hard per-request timeout, so a hung/glacial provider connection raises instead of blocking forever. Pass to the provider as its http_client.

httpx2 is pydantic-ai 2.x's HTTP layer: a legacy httpx.AsyncClient handed to a 2.x provider emits PydanticAIDeprecationWarning (and is slated for removal in v3), so the provider-facing client is built on the fork.

parse_model_identifier

parse_model_identifier(identifier)

Parse a combined provider-model tier identifier.

Grammar::

<provider>-<model-name>

where <provider> is everything before the first hyphen and <model-name> is everything after it (the model name may itself contain hyphens and slashes).

Parameters:

Name Type Description Default
identifier str

The combined identifier string — e.g. "claudeSDK-opus" or "openrouter-deepseek/deepseek-v4-flash-latest".

required

Returns:

Name Type Description
ParsedIdentifier ParsedIdentifier

Parsed components.

Raises:

Type Description
MalformedIdentifierError

If the identifier has no hyphen-delimited model part, or an empty provider or model name.

build_image_question_tool

build_image_question_tool(
    images, *, tier_config=None, api_key=None
)

Build the ask_image tool over images.

Parameters:

Name Type Description Default
images Sequence[tuple[str, bytes]]

The attached images as (media_type, data) pairs, e.g. [("image/png", b"...")]. Captured immutably at build time.

required
tier_config TierConfig | None

Supplies the :attr:~robotsix_llmio.config.tier.TierConfig.vision binding that answers the questions. None uses the baked defaults.

None
api_key str | None

API key for the vision provider (OpenRouter). None falls back to the provider's own resolution (OPENROUTER_API_KEY).

None

Returns:

Type Description
Callable[[int, str], Coroutine[Any, Any, str]]

An async ask_image(image_index, question) -> str function ready

Callable[[int, str], Coroutine[Any, Any, str]]

to be passed as a pydantic-ai tool or through the Claude SDK MCP

Callable[[int, str], Coroutine[Any, Any, str]]

bridge.

reconcile

reconcile(logged, provider, *, tolerance=DEFAULT_TOLERANCE)

Compare logged (what we recorded) against provider (what was billed).

Pure window-total reconciliation: the absolute delta of the two totals, flagged within_tolerance when delta <= tolerance. Per-generation alignment is intentionally out of scope until the cost recorder captures provider generation ids (today CostRecord.id is the log backend's trace id, which doesn't map to a provider line-item).

The caller owns the retention guard: only reconcile windows still inside the log backend's retention horizon — a window older than retention reads back as ~0 logged cost (pruned) and would look like a huge false gap.

acall_with_retry async

acall_with_retry(
    fn,
    *,
    what="model call",
    sleep=sleep,
    fallback_fn=None,
    is_transient_fn=is_transient,
)

Async mirror of :func:call_with_retry.

Identical retry/backoff/classification/one-shot-fallback semantics, except fn/fallback_fn are awaited and sleep defaults to :func:asyncio.sleep (kept injectable so tests can pass a no-op).

acall_with_retry_and_fallback async

acall_with_retry_and_fallback(
    primary,
    fallback,
    *,
    what="model call",
    sleep=sleep,
    is_transient_primary=is_transient,
    is_transient_fallback=is_transient,
    should_fallback=lambda _e: True,
)

Async mirror of :func:call_with_retry_and_fallback.

Retries primary locally through :func:acall_with_retry, then falls back to fallback only when that whole session fails AND should_fallback of the error is true. Same "retry locally first, fall back only when local retries failed" semantics, including raise fallback_exc from primary_exc chaining when the fallback also fails.

call_with_retry

call_with_retry(
    fn,
    *,
    what="model call",
    sleep=sleep,
    fallback_fn=None,
    is_transient_fn=is_transient,
)

Run fn and retry it on transient failures only.

Transient failures use a short exponential backoff (baked base/cap). UsageLimitExceeded is never retried: if a fallback_fn is provided it is tried exactly once, else the exception re-raises immediately. Non-transient errors re-raise immediately; the last error re-raises once retries are exhausted.

Fallback activation does not consume a transient-retry slot — the fallback gets the same full retry budget as the primary, regardless of how many transient retries the primary consumed before hitting the rate limit.

is_transient_fn lets a provider layer widen the transient set (e.g. the OpenRouter upstream-error or DeepSeek reasoning-400 signatures).

call_with_retry_and_fallback

call_with_retry_and_fallback(
    primary,
    fallback,
    *,
    what="model call",
    sleep=sleep,
    is_transient_primary=is_transient,
    is_transient_fallback=is_transient,
    should_fallback=lambda _e: True,
)

Retry primary locally, then fall back to a different model.

primary runs through :func:call_with_retry — its own bounded transient retries. Only when that whole session fails (retries exhausted, or a non-transient/terminal error) AND fallback is provided AND should_fallback of the error is true is fallback run, itself through a fresh :func:call_with_retry session.

This is "retry locally first, fall back only when local retries failed": the fallback model is never tried instead of the primary's retries, only after they are exhausted. is_transient_primary/is_transient_fallback let each model retry on its own provider's transient signatures.

is_rate_limited

is_rate_limited(exc)

True only for UsageLimitExceeded (the pydantic-ai budget-cap exception). Walks the cause/context chain.

is_usage_exhausted

is_usage_exhausted(exc)

True when exc reports that a model's usage capacity is exhausted.

Matches either shape llmio surfaces:

  • pydantic-ai UsageLimitExceeded — a per-run request/token budget cap; or
  • ClaudeSDKUsageExhaustedError — the Claude subscription tier is out of usage credits.

Both are non-transient (re-running the SAME model cannot help) but ARE fallback-eligible: the request should be retried on a DIFFERENT model. Pass this as should_fallback to :func:call_with_retry_and_fallback / :func:acall_with_retry_and_fallback (or :func:~robotsix_llmio.core.run.run_agent / :func:~robotsix_llmio.core.run.arun_agent) so a run degrades to the fallback model on exhaustion while still failing loudly on genuine errors. Walks the cause/context chain. The Claude-SDK error is matched by class name to keep this module free of an import cycle with :mod:robotsix_llmio.claude_sdk.

arun_agent async

arun_agent(
    handle,
    run,
    *,
    label,
    session_id=None,
    project=None,
    fallback=None,
    what="model call",
    trace_input=None,
    sleep=sleep,
    is_transient_fn=is_transient,
    should_fallback=lambda _e: True,
)

Async mirror of :func:run_agent.

Same composition, except run/fallback are awaited and the retry uses :func:acall_with_retry / :func:acall_with_retry_and_fallback with sleep defaulting to :func:asyncio.sleep. handle.aclose() is awaited in the finally block to close the HTTP client in the caller's running event loop. should_fallback gates fallback exactly as in :func:run_agent (default: fall back on any error; pass :func:~robotsix_llmio.core.retry.is_usage_exhausted to fall back only on usage exhaustion).

run_agent

run_agent(
    handle,
    run,
    *,
    label,
    session_id=None,
    project=None,
    fallback=None,
    what="model call",
    trace_input=None,
    sleep=sleep,
    is_transient_fn=is_transient,
    should_fallback=lambda _e: True,
)

Run run under a trace span and bounded retry, always closing handle.

Opens a root trace span named label (optionally grouped under session_id and routed to project). When trace_input is not None it is recorded as the span input. run is executed under :func:acall_with_retry (or :func:acall_with_retry_and_fallback when fallback is given); on success the result is recorded as the span output and returned. handle.close() runs in a finally — even when run raises after retries are exhausted.

should_fallback gates when fallback is used: it is only invoked when the primary fails its whole retry session AND should_fallback(exc) is true. The default falls back on any error; pass :func:~robotsix_llmio.core.retry.is_usage_exhausted to degrade to the fallback model only when the primary's usage is exhausted (out of credits / budget cap) while still failing loudly on genuine errors.

add_column_if_missing

add_column_if_missing(conn, table, column_ddl)

Add column_ddl to table when the column is not already present.

Returns True when the column was newly created, False when it already existed.

run_additive_migrations

run_additive_migrations(conn, table, column_ddls)

Apply every DDL in column_ddls to table.

Returns a list[bool] parallel to column_ddls: True when the column was newly added, False when it already existed.

run_multi_table_migrations

run_multi_table_migrations(conn, migrations)

Apply additive column migrations across multiple tables.

migrations maps each table name to its sequence of column DDL strings. Returns a dict mapping each table name to its per-column list[bool] result (same semantics as :func:run_additive_migrations).

html_to_text

html_to_text(html_text)

Strip HTML markup down to whitespace-collapsed plaintext.

This is a dependency-free helper (stdlib :mod:re + :mod:html only) that performs, in order:

  1. Remove <script>, <style>, <noscript>, and <svg> blocks including their inner content (case-insensitive, dot matches newline).
  2. Strip all remaining tags.
  3. html.unescape(...) the result to decode entities (e.g. &amp;, &nbsp;).
  4. Collapse all runs of whitespace to a single space and .strip() the ends.

Parameters:

Name Type Description Default
html_text str

The HTML markup to convert.

required

Returns:

Type Description
str

The whitespace-collapsed plaintext rendering of html_text.

active_routing_key

active_routing_key()

The active Langfuse public key from the current context, or None.

Unlike the internal _active_public_key, this does not fall back to the default project — it only returns what was set via :func:langfuse_project. Use this to introspect which project the current context routes to without triggering the silent default.

current_session

current_session()

The session id active in the current context, or None.

flush_tracing

flush_tracing(timeout_millis=10000)

Force-flush pending spans so they ship before the process exits (or so a test can read them back). No-op without OTel / a flushable provider.

get_recording_span

get_recording_span()

Return the current OTel span if recording, else None. No-op without OTel.

get_tracer

get_tracer(name)

Return an OTel tracer for name, or None when OpenTelemetry is not installed. The tracer late-binds to whatever provider is active when a span is started, so it's safe to fetch before tracing is configured.

install_signal_handlers

install_signal_handlers()

Flush pending traces on SIGTERM / SIGINT before the process exits.

Installs handlers that flush once and then SystemExit(0). No-op when not on the main thread (where signal handlers can't be installed). Call from your process entry point if you run long-lived workers.

langfuse_project

langfuse_project(public_key)

Route spans produced in this block to the registered Langfuse project with public_key (multi-tenant). Spans whose project isn't registered are silently dropped by the filtered exporters.

langfuse_session

langfuse_session(session_id)

Group all spans produced in this block under session_id in Langfuse.

langfuse_trace_url

langfuse_trace_url(trace_id, *, public_key=None)

Build the Langfuse web-UI URL for trace_id, or None when the project's id isn't known. Uses public_key's project, or the active/default one. A project id is only available when it was passed to :func:setup_langfuse_tracing (or set via LANGFUSE_PROJECT_ID).

make_session_id

make_session_id(kind)

A unique session id of the form <kind>-<hex> for :func:langfuse_session.

setup_langfuse_tracing

setup_langfuse_tracing(
    *,
    public_key=None,
    secret_key=None,
    base_url=None,
    project_id=None,
    service_name="robotsix-llmio",
    on_export_result=None,
)

Register a Langfuse project for trace export and start instrumentation.

Call once for single-tenant (credentials default to the LANGFUSE_* env vars), or once per project for multi-tenant routing (then use :func:langfuse_project). project_id (or LANGFUSE_PROJECT_ID) is optional and only used to build web-UI links via :func:langfuse_trace_url. Idempotent per public key. Returns True when the project is registered, False when credentials are absent (no-op).

on_export_result is an optional health hook: when provided, every span export attempt for THIS project invokes it as on_export_result(public_key, ok, error) — ok=False with an error string on an exception or a non-success OTLP result, ok=True with None on success. Consumers use it to surface "Langfuse export broken" in their own UI and to auto-clear the flag once exports recover. The hook must not raise; exceptions from it are swallowed so it can never break the export path.

start_span

start_span(tracer, name, attributes=None)

Start a current span on tracer, set attributes (skipping None values), and yield it. A no-op yielding None when tracer is None (OTel absent); a non-recording span when no SDK provider is configured.

start_trace

start_trace(name, *, session_id=None, project=None)

Open a root span name (the trace), optionally grouped under session_id and routed to project (a registered Langfuse public key). Use the yielded :class:TraceSpan to set trace-level input/output. Lets you group arbitrary work — multiple agent runs and non-agent steps — under one trace.