robotsix_llmio core
Provider-agnostic LLM I/O base: agent assembly, retry, cost recording, provider-cost reconciliation, tracing, and Langfuse integration.
Exports
Provider ABC & agent assembly
LLMProvider— abstract base for every LLM provider; subclasses implementnew_model(*, model=None, level=0)AgentHandle— wraps a pydantic-ai Agent with its httpx2 client, exposingclose()for cleanupbuild_agent— assembles a pydantic-ai Agent from model, http_client, system_prompt, tools, and output_type; on the provider the public entry-point isLLMProvider.build_agent(level=..., system_prompt=...)wherelevelis an integer 1–3
Config-tier re-exports
ANTHROPIC_LEVEL1..3— bakedTierLevelConfigper level of chain position 0 (direct Anthropic API: claude-haiku-5-5 / claude-opus-5-5 / claude-fable-5)DEFAULT_LEVEL1..3— bakedTierLevelConfigper level of chain position 1 (Claude SDK: haiku / opus / claude-fable-5)FALLBACK_LEVEL1..3— bakedTierLevelConfigper level of chain position 2 (OpenRouter DeepSeek: flash / flash / pro)TierConfig— pydantic model holding an ordered provider-slotchain(baked: direct Anthropic API → Claude SDK → OpenRouter; the legacydefault/fallbackkeys still load) plus thefailoverpolicyProviderSlotConfig— one slot's binding of all three levelsFailoverConfig— provider-failover policy (failure_threshold,window_seconds)TierConfigLoadError— raised when tier configuration cannot be loadedTierLevel—StrEnumwithLEVEL1(→level=1),LEVEL2(→level=2),LEVEL3(→level=3) selector valuesTierLevelConfig— pydantic model binding a single level's transport and modelcreate_model— consumer-facing factory returning a configuredLLMProviderload_tier_config— merges an explicit dict over the baked defaults into a validatedTierConfig
Agent runners
run_agent— runs anAgentHandleunder a trace span with bounded retry, always closing the handlearun_agent— async mirror ofrun_agent
Identifier parsing
MalformedIdentifierError— raised when a provider-model identifier string is malformed (e.g. unbalanced brackets, missing model part)ParsedIdentifier—NamedTupleholding the parsed components of a provider-model identifier:providerandmodel_nameparse_model_identifier— parses a combined provider-model identifier (e.g.claudeSDK-opusoropenrouter-deepseek/deepseek-v4-flash-latest) into aParsedIdentifier
Factory
create_model— preferred entry point: resolves a provider from level + transport + tier config, returns a configuredLLMProviderget_provider_for_identifier— resolves and instantiates a provider from a combined provider-model identifier string (parsed viaparse_model_identifier)
Retry & transient errors
call_with_retry— bounded retry on transient/rate-limit errors with optional fallbackcall_with_retry_and_fallback— retries locally then activates a fallback model on failureis_rate_limited— detects pydantic-aiUsageLimitExceeded(budget cap) exceptionsis_transient— detects retryable infrastructure failures (httpx timeouts, 429/5xx, transport errors)acall_with_retry— async mirror ofcall_with_retryacall_with_retry_and_fallback— async mirror ofcall_with_retry_and_fallback
Image questions
build_image_question_tool— builds the asyncask_image(image_index, question)tool over attached(media_type, bytes)images, answered by the tier config'svisionbinding; wired automatically bybuild_agent(images=...)on the OpenRouter (text-only) path; the Claude SDK transport serves images natively instead
Provider failover
call_with_failover— runs a callable at a fixed capability level with automatic failover down the orderedTierConfig.chain: a provider-shaped failure on the active slot retries the SAME level on the next slot, trying each slot at most once per request; afterfailure_thresholdconsecutive failures on a slot (exhaustion immediately) that slot is skipped forwindow_seconds(exponentially backed off on repeated re-arms) and calls route to the next healthy slot; the optional per-request cost guards (max_request_cost_usd,cost_ratio_threshold) can refuse a switch withFailoverCostGuardError. See Config — failover down the chainacall_with_failover— async mirror ofcall_with_failoverProviderFailoverTracker— process-wide tracker holding failover state (singleton viaget_failover_tracker)get_failover_status/FailoverStatus— snapshot of the failover state, shaped for consumer status endpoints and UIsis_provider_shaped— classifies whether an exception points at the provider (failover-eligible) or the taskreset_failover_tracker— resets the singleton (test teardown)
See the Failover cost-reduction operational runbook for configuring, monitoring, and troubleshooting the slot-switch cap, retry-cap + backoff, and per-request cost guard, and Failover cost-reduction validation for the repeatable before/after-deploy procedure that proves failover churn cost dropped without regressing the request completion rate.
Cost recording
CostLogSource— protocol for reading logged cost; single methodfetch_logged_cost(window) -> LoggedCostCostRecord— dataclass for one logged cost unit:id,cost,timestamp, optionalsession_idandnameCostWindow— dataclass withstart/enddatetimes bounding a cost query (start inclusive, end exclusive)LoggedCost— dataclass aggregating a logged-cost query:total_cost,record_count,records
Provider cost reconciliation
DEFAULT_TOLERANCE— default tolerance (1.0) for cost reconciliationDiscrepancy— dataclass with logged vs. provider totals, delta, andwithin_toleranceflagProviderCost— dataclass for provider-billed cost:total_cost,breakdown,request_countProviderCostSource— protocol for reading provider-billed cost;fetch_provider_cost(window) -> ProviderCostreconcile— compares logged vs. provider-billed cost, returning aDiscrepancy
Tracing & Langfuse
TraceSpan— handle to a root span withtrace_id,set_input(),set_output()active_routing_key— returns the active Langfuse public key from context, orNonecurrent_session— returns the session id active in the current context, orNoneflush_tracing— force-flushes pending OTel spans; no-op without OTelget_recording_span— returns the current OTel span if recording, elseNoneget_tracer— returns an OTel tracer, orNonewhen OpenTelemetry is not installedinstall_signal_handlers— installs SIGTERM/SIGINT handlers that flush tracing then exitlangfuse_project— context manager routing spans to a registered Langfuse project (multi-tenant)langfuse_session— context manager grouping spans under asession_idin Langfuselangfuse_trace_url— builds the Langfuse web-UI URL for a trace IDmake_session_id— returns a unique session id (<kind>-<hex>) for use withlangfuse_sessionsetup_langfuse_tracing— registers a Langfuse project and starts OTel instrumentationstart_span— context manager starting a named span; yieldsNonewhen OTel is absentstart_trace— context manager opening a root span (trace), optionally under a session and project
Langfuse cost log
LangfuseCostLogSource— concreteCostLogSourcefetching logged cost from Langfuse's REST APILangfuseReadClient— low-level Langfuse REST client for reading trace and session data
HTTP
timeout_http_client— returns a freshhttpx.AsyncClientwith a hard per-request timeout
Text utilities
html_to_text— strips HTML markup down to whitespace-collapsed plaintext