flutter_llm_router 1.2.1
flutter_llm_router: ^1.2.1 copied to clipboard
Production reliability layer for LLMs in Flutter AI Toolkit: multi-provider failover, retries, circuit breaking, budgets, attachments, cost tracking, and live observability.
Changelog #
All notable changes to this project are documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
1.2.1 - 2026-11-24 #
Added #
- Added live cost tracking and
RouterInspectordebug widget. - Added demo example application in
example/.
Changed #
- Updated Material UI imports and dependencies to
package:material_ui/material_ui.dartfor Flutter 3.50+ compatibility.
Fixed #
- The package is now WASM-compatible, which restores the full platform score on pub.dev. It imports only the
flutter_ai_toolkitprovider interfaces instead of the toolkit's public library. That library also exportsFirebaseProvider, which reachesdart:iothroughfirebase_aiandweb_socket_channel. The public API is unchanged.
1.2.0 - 2026-11-04 #
1.2.0 is the first release since 1.1.0. It combines four milestones: failover that covers every failure class, real chat features, opt-in reliability policies, and tool calling with structured output. Every new feature is opt-in, but some failures now fail over where they used to stop the chain.
Upgrade notes #
- HTTP 401, 402, 403, and 404, empty replies, and any
Exceptionfrom an adapter now fail over instead of stopping the chain or escaping. See Failover correctness. - Attachments are now sent to providers as real images, PDFs, and text, instead of
toString()notes in the prompt. See Chat features. AdapterChunkhas two new subtypes,AdapterFinishandAdapterToolCall. Code that switches exhaustively overAdapterChunkmust handle both.- The minimum versions are now Dart
^3.8.0and Flutter>=3.32.0. getDocumentEmbeddingandgetQueryEmbeddingare deprecated and will be removed in 2.0.0.
Failover correctness #
Failover now covers the failures that used to stop the chain or hang it.
Changed
- HTTP 401, 402, 403, and 404 now fail over to the next provider instead of stopping the chain. They throw the new
ProviderUnavailableLlmException, which extendsRetryableLlmException. Gemini's HTTP 400API_KEY_INVALIDand Anthropic's HTTP 400 for low credit balance are treated the same way. Code that caughtTerminalLlmExceptionfor a bad key now getsAllProvidersFailedExceptionwhen every provider fails. - A stream that ends without text is now a failure that fails over, instead of an empty success. Empty text chunks no longer block failover.
- Any
Exceptionfrom an adapter, such as a TLS failure or a custom adapter's own error, now fails over and is logged, instead of escaping the router. - Usage is now recorded for cancelled replies, replies that fail after text arrived, and failed attempts where the provider reported token counts. Gemini thinking tokens count as output tokens.
RouterLlmProviderthrowsArgumentErrorfor an emptyproviderslist in every build mode, instead of asserting only in debug builds.HttpConnectivityCheckertreats a probe timeout as online, and the default probe falls back tohttps://cp.cloudflare.com/generate_204when Google cannot be reached. A local or privatebaseUrlno longer triggers the probe.- OpenAI requests to
api.openai.comsendmax_completion_tokensinstead ofmax_tokens, which newer models require. - Raised the minimum versions to Dart
^3.8.0and Flutter>=3.32.0.flutter_lints ^6.0.0needs Dart 3.8, and the previous Flutter floor did not match the Dart floor.
Fixed
- A stream that stalled after the response headers could hang forever.
ProviderConfig.idleTimeout(default 60 seconds) andProviderConfig.deadlinenow bound it, and an error response body is bounded bytimeout. - Error events inside a 200 stream (OpenAI and OpenRouter
errorchunks, Anthropicerrorevents such asoverloaded_error, Geminierrorobjects and blocked prompts) were treated as success. They now fail over. - Cancelling a reply did not stop the chain, and timed-out requests kept running. Cancelling or timing out now aborts the HTTP request, and no later provider is called.
- Disposing the router during a stream could throw.
disposenow cancels active requests and can be called more than once. - A failed send was resent with the next prompt. Failed and cancelled sends stay in
historyfor display but are no longer sent upstream. - A slower earlier call could overwrite
lastAttemptLogsfrom a newer one. - Anthropic requests from web builds were blocked by CORS. The adapter now sends
anthropic-dangerous-direct-browser-accesson web.
Added
ProviderUnavailableLlmExceptionandAssumeOnlineConnectivityChecker.ProviderConfig.idleTimeout,deadline,requestStreamUsage, andheaders.headerssupports backend proxies and can replace built-in headers such asauthorization.RouterLlmProvider.attemptLogs, aValueListenableof the latest attempt logs.BaseLlmAdapter.isProviderScopedFailureandthrowStreamErrorfor custom adapters.postSsetakes optionalidleTimeoutanddeadline.- CI, tag-based publishing, Dependabot, and issue and pull request templates.
CONTRIBUTING.md,SECURITY.md, andCODE_OF_CONDUCT.md.- API key guidance in the README and quickstart.
- macOS runner for the example app.
Documentation
- README attempt-log snippet used
AttemptLogfields that do not exist. - Example and quickstart docs described an OpenRouter setup the example no longer uses.
Removed
- Unused example files:
view_model/chat_router_view_model.dart,widgets/api_keys_dialog.dart, andwidgets/attempt_logs_sheet.dart.
Chat features #
Attachments are now sent for real. This part also adds request settings and provider presets, and reports why a provider stopped.
Changed
- Attachments are sent to providers as images, PDFs, and text instead of being appended to the prompt as
toString()notes, which sent the file name and size but not the content.ChatTurn.textnow holds only the message text. AdapterChunkhas a new subtype,AdapterFinish. Code that switches exhaustively overAdapterChunkmust add a case for it.- An HTTP 400 on a request with image, PDF, audio, or video attachments now fails over, because the model may not accept that media. Without such attachments, HTTP 400 still stops the chain.
- Gemini thought-summary parts are no longer shown as reply text. Their tokens are still billed as output.
Added
ChatTurn.attachments, withTurnAttachment,FileTurnAttachment,LinkTurnAttachment, andAttachmentKind. Each adapter maps them to its vendor format: OpenAIimage_urlandfileparts, Anthropicimageanddocumentblocks, GeminiinlineData. Text files are inlined as text for every vendor. Non-image links are sent as text references.ChatTurn.toAnthropicMessage.ProviderCapabilitiesandProviderConfig.capabilities, plusBaseLlmAdapter.capabilities. The router skips a provider that cannot take the conversation's attachments and logs the reason, instead of sending a request that would fail or drop the file.GenerationSettingswithsystemPrompt,temperature,topP, andstopSequences. Set defaults onRouterLlmProvider.settingsand override per provider withProviderConfig.settings.FinishReasonandAdapterFinish.AttemptLog.finishReasonshows a reply cut off atmaxOutputTokens(FinishReason.length) or stopped by a content filter. A filtered reply with no text fails over.- Provider presets:
ProviderConfig.ollama,lmStudio,groq,mistral,deepSeek, andazureOpenAi. AzureOpenAiAdapter, used with theazure-openaiadapter key.ProviderConfig.adapter, which picks the built-in adapter sonamecan be any display label.ProviderConfig.idandisFree.OpenAiAdapter.chatUrl,authHeaders, andmaxTokensField, for adapters that target other OpenAI-compatible hosts.- Groq usage reported under
x_groq.usageis read.
Deprecated
RouterLlmProvider.getDocumentEmbeddingandgetQueryEmbedding. They always threw and will be removed in 2.0.0.
Reliability policies #
This part adds production reliability controls: same-provider retries, a circuit breaker, routing strategies, budgets, an event stream, a debug panel, and a response cache. Every feature is opt-in. With the defaults, routing behaves as it did without them.
Added
RetryPolicyandRouterLlmProvider.retryPolicy. Retries the same provider with exponential backoff and jitter before failing over. Only transient failures are retried: HTTP 408, 429, 5xx, timeouts, and dropped connections. ARetry-Afterlonger thanmaxDelayskips the retry and fails over. The default,RetryPolicy.none, does not retry.RetryableLlmException.retryAfter, read from theretry-after-msheader or aRetry-Afterheader in seconds.- Anthropic's in-stream
overloaded_errornow carries status 529, so it can be retried. CircuitBreakerPolicyandRouterLlmProvider.circuitBreaker. AfterfailureThresholdconsecutive failed requests, a provider is skipped forcooldown, then one trial request decides whether it comes back. If every circuit is open, the router tries the providers anyway.RouterLlmProvider.providerHealthexposesProviderHealth(circuit state, success and failure counts, average time to first token) keyed byProviderConfig.id.resetCircuitscloses every circuit.RoutingStrategyandRouterLlmProvider.routingStrategy, withPriorityRoutingStrategy(default),CheapestFirstRoutingStrategy,LowestLatencyRoutingStrategy, andWeightedRoutingStrategy.BudgetPolicyandRouterLlmProvider.budget. A provider over its entry inproviderLimitsUsdis skipped. OversessionLimitUsd, only free providers are called. When nothing within budget remains, the router throws the newBudgetExceededExceptionwithout calling a provider.CostTracker.usageByProvider,costFor, andtotalCachedInputTokens, plus theProviderUsagetype.- Cached-token pricing:
ProviderConfig.pricePerCachedInputToken,AdapterUsage.cachedInputTokens, and acachedInputTokensargument oncalculateCostandrecordUsage. OpenAI, DeepSeek, Anthropic, and Gemini cache counts are read from the stream. RouterLlmProvider.events, a broadcast stream ofRouterEvent:RequestStarted,AttemptStarted,AttemptFinished,RetryScheduled,CircuitStateChanged,UsageRecorded, andRequestFinished.RouterLlmProvider.redactEventErrors, true by default, andLlmRouterException.redactedMessage. Events leave provider response bodies out of error messages, because they can echo the prompt.lastAttemptLogsand thrown exceptions keep the full message.RouterInspector, a widget that shows spend, provider health, and the attempts of the latest request live.ResponseCache,InMemoryResponseCache,CachedResponse, andRouterLlmProvider.responseCache. Only complete, successful replies are stored. Cache errors never fail a request.AttemptLog.timeToFirstTokenMs,retry,skipReason,isSkipped, andfromCache. Skipped providers and cache hits now appear inlastAttemptLogs.- API key pools.
ProviderConfig.apiKeysadds keys toapiKey(ProviderConfig.allKeyslists them all), andKeyPoolPolicywithRouterLlmProvider.keyPoolsetsKeyRotation.roundRobin(default) orKeyRotation.priority. A key that fails with HTTP 429 rests for itsRetry-After, orrateLimitCooldown(60 seconds); a key that fails with 401, 402, or 403 rests forinvalidKeyCooldown(10 minutes). The router retries the same provider with the next key before it fails over, which matters when no other provider can do the job, such as image generation. When every key of a provider is resting, the provider is skipped with askipReason.AttemptLog.keyIndexshows which key an attempt used; the key itself is never logged. A provider with a single key behaves as before.
Tools and structured output #
This part adds tool calling and structured output. Both are opt-in. Read Changed if you wrote a custom adapter or switch over AdapterChunk.
Added
- Tool calling. Pass
RouterTools toRouterLlmProvider.tools. When a model calls one, the router runs itsToolHandler, sends theToolResultback to the same provider, and streams the final reply.maxToolRounds(default 8) caps the rounds; going past it throwsTerminalLlmException.- New types:
ToolDefinition,RouterTool,ToolHandler,ToolCall,ToolResult. - Tools in one round run concurrently. Results go back in call order. A handler that throws an
Exception, an unknown tool name, or a result that can't be encoded as JSON becomes an error result, so the model can recover. ChatTurn.toolCallsandChatTurn.toolResults, andChatTurn.toOpenAiMessages, which yields onetoolmessage per result.AdapterToolCall, yielded once per complete call. OpenAI streamedtool_callsfragments and Anthropicinput_json_deltablocks are assembled by the adapters. GeminifunctionCallparts are read whole.- Gemini's
thoughtSignatureis kept inToolCall.providerDataand sent back with the call, as Gemini requires. ToolCallFinishedevent, with tool name, call id, duration, and whether it failed.ProviderCapabilities.tools. When tools are set, providers withtools: falseare skipped and the reason is logged.BaseLlmAdapter.decodeToolArgumentsfor custom adapters. Malformed arguments are retryable.
- New types:
- Structured output.
RouterLlmProvider.generateObjectasks for a reply that matches aResponseSchemaand returns it decoded.- Every provider gets the schema in its system prompt. OpenAI-compatible APIs also get
response_formatwithjson_schema. Gemini switches to JSON mode withresponseMimeType. - The reply is parsed as JSON (a surrounding code fence is tolerated) and passed to your
decodefunction. If either step fails, the attempt fails with the newInvalidStructuredOutputExceptionand the router fails over.
- Every provider gets the schema in its system prompt. OpenAI-compatible APIs also get
GenerationSettings.toolsandGenerationSettings.responseSchema. The router fills them fromtoolsandgenerateObject.- The live contract tests now cover a tool round-trip and structured output for each vendor.
- A seeded chaos benchmark (
test/chaos) that injects eight failure classes and checks that every failure is classified and none hangs. Results are indoc/11-reliability-benchmark.md. - Example app: a keyless demo mode that streams simulated replies, and a workflow that publishes the example to GitHub Pages as a live web demo.
Changed
AdapterChunkhas a new subtype,AdapterToolCall. Code that switches exhaustively overAdapterChunkmust add a case.- Failover stops once a tool has run in a request. A later failure is rethrown, so a tool never runs twice because a provider failed.
RetryPolicystill retries the same provider, which is safe because the tool results are already in the conversation. Failover before the first tool call works as before. generateObjectbuffers the reply and emits it only after it validates, so an invalid reply can still fail over.- The response cache key now includes the tools and the schema. Cached
generateStreamreplies don't answergenerateObject, and the reverse.
1.1.0 - 2026-10-17 #
- Added connectivity-aware failover. When a provider fails with a connection error or timeout,
RouterLlmProvidersilently probes the internet once per request. If the device is offline, it throws the newNoInternetConnectionExceptioninstead of trying every provider. If the device is online, it fails over as before. - Added
ConnectivityCheckerandHttpConnectivityChecker. The default probe ishttps://www.google.com/generate_204with a 3-second timeout, usingHEADon native platforms and ano-corsfetchon web. Configure it throughRouterLlmProvider(connectivityChecker: ...). - Example app: added a "Simulate OpenAI network failure" switch and an offline SnackBar through
LlmChatView.onErrorCallback.
1.0.4 - 2026-10-11 #
- Added screenshots to the pub.dev listing: failover, cost tracking, and quickstart.
1.0.3 - 2026-10-10 #
- Added explicit Windows and Linux (full cross-platform) support declarations in
pubspec.yaml. - Added native Windows (
example/windows/) and Linux (example/linux/) desktop runner scaffolding to enable running the example app natively on both desktop platforms. - Updated
httpdependency constraint to^1.6.0. - Updated documentation with Windows and Linux desktop setup instructions and synchronized dependency version requirements.
1.0.2 - 2026-10-06 #
- Upgraded
flutter_ai_toolkitconstraint to^1.0.0andflutter_lintsto^6.0.0. - Removed discontinued
firebase_vertexaidependency. - Updated
RouterLlmProviderembedding methods and documentation forflutter_ai_toolkit 1.0.0.
1.0.1 - 2026-10-04 #
- Added direct multi-provider configurations for OpenAI, Google Gemini, and Anthropic Claude.
- Refactored example app with MVVM state management (
ChatRouterViewModel). - Added compile-time
--dart-definekey configuration support. - Exported adapters and model types in public library exports.
- Updated repository and issue tracker URLs to open-source-collabs.
1.0.0 - 2026-10-01 #
First release of the local package. It is not published to pub.dev.
Added #
- Package layout for
flutter_llm_router: publiclib/exports,test/,doc/, andexample/, with MIT license and strict analyzer options. ProviderConfigfor a named upstream model, API key, per-token USD prices, optionalbaseUrl, and a 30-second defaulttimeout. IncludescopyWithandcalculateCost.AttemptLogfor one provider try: name, model, timestamp, latency, success, error text, and HTTP status.CostTrackerwithtotalCostNotifier(ValueListenable<double>), token counters,recordUsage,recordCost,reset, anddispose.LlmRouterException,RetryableLlmException,TerminalLlmException, andAllProvidersFailedException.- SSE adapters for OpenAI chat completions, Anthropic
content_block_delta, GeministreamGenerateContent?alt=sse, and OpenRouter chat completions athttps://openrouter.ai/api/v1. HTTP 429, 408, and 5xx, plus timeouts and socket drops, are retryable. HTTP 400, 401, and 403 are terminal. The adapters usepackage:httpand do not importdart:io. RouterLlmProvider, anLlmProviderthat walks providers in order. A retryable failure before the first token fails over. A terminal failure is logged and rethrown. If every provider fails, the router throwsAllProvidersFailedException. Successful streams record estimated token cost.lastAttemptLogsexposes the latest attempt list. Built-in names areopenai,anthropic,gemini, andopenrouter.customAdaptersoverrides that lookup.- Example chat app on
LlmChatViewthat sends one OpenRouter key throughopenai/gpt-4o-mini, thengoogle/gemini-2.5-flash, thenanthropic/claude-haiku-4.5. A switch simulates HTTP 429. The app bar shows live spend, and a sheet lists attempt logs. The example Android manifest allows internet access.
Notes #
- Token counts are
(text.length + 3) ~/ 4, not the provider's billed tokenizer. getDocumentEmbeddingandgetQueryEmbeddingare unimplemented.flutter_ai_toolkit0.5.0 is pinned, andfirebase_vertexaiis constrained to>=1.0.1 <1.5.0because later releases removedTaskType.
