models library

Large language model adapters, registries, routing, and request/response types.

Provides BaseLlm, Gemini, Claude, LiteLlm, RoutedLlm, LlmRequest, LlmResponse, and toGenerateContentBody.

import 'package:adk_dart/models.dart';

final model = Gemini(model: 'gemini-2.5-flash');

Classes

AnthropicGcsObject
Metadata and raw bytes downloaded from a gs:// object for Claude.
AnthropicGenerateContentConfig
Specialized generation configuration for Anthropic Claude models.
AnthropicLlm
Anthropic Claude adapter for ADK model requests.
AnthropicRestHttpTransport
Default HTTP-backed transport for the Anthropic Messages API.
AnthropicRestTransport
Transport abstraction for Anthropic Messages API calls.
ApigeeCompletionsClient
Client contract for Apigee chat-completions calls.
ApigeeLlm
Apigee model adapter that supports both GenAI and chat-completions flows.
AutomaticFunctionCallingConfig
Configuration for SDK-managed automatic function calling.
BaseLlm
Base interface for model adapters used by the runner.
BaseLlmConnection
Bidirectional connection contract for realtime model sessions.
CacheMetadata
Metadata describing a cached prompt/context entry.
ChatCompletionsHttpClient
Production HTTP client for OpenAI-compatible chat-completions endpoints.
FallbackModel
Tries a sequence of models in order, moving on when one fails.
FunctionCallingConfig
Function-calling configuration attached to tool settings.
FunctionDeclaration
Function-calling declaration exposed to the model.
Gemini
Google Gemini model adapter with REST, interactions, and live support.
GeminiCacheClient
Client contract for Gemini context cache operations.
GeminiContextCacheManager
Manages cache metadata and cache lifecycle for Gemini requests.
GeminiCreatedCache
Result returned by cache creation calls.
GeminiLiveSession
Runtime contract for Gemini live session transports.
GeminiLiveSessionMessage
Message envelope emitted by Gemini live sessions.
GeminiLlmConnection
BaseLlmConnection implementation backed by Gemini live/fallback flows.
GeminiServerContentPayload
Server-content payload emitted by Gemini live sessions.
GeminiToolCallPayload
Tool-call payload emitted by Gemini live sessions.
GeminiTranscriptionEvent
Transcription delta emitted by Gemini live sessions.
GeminiUsageMetadata
Usage metadata payload emitted by Gemini live sessions.
Gemma
Integration for Gemma 3 models exposed via the Gemini API.
Gemma3Ollama
Integration for Gemma 3 models running locally via Ollama.
GemmaFunctionCallModel
Parsed inline Gemma function call payload.
GenerateContentConfig
Generation configuration for text/content model calls.
HttpOptions
HTTP configuration for model API requests.
HttpRetryOptions
Retry policy for HTTP model requests.
InteractionsStreamState
State accumulator across Gemini Interactions API streaming events.
LiteLlm
OpenAI-compatible adapter that targets LiteLLM providers.
LiveConnectConfig
Realtime connection configuration for live model sessions.
LlmCapabilities
Resolved capabilities for an LLM instance.
LLMRegistry
Registry that maps model patterns to concrete LLM adapters.
LlmRequest
Full model request payload used by LLM adapters.
LlmResponse
Normalized model response emitted by LLM adapters.
LlmToolConfig
Tool-level configuration wrapper for model requests.
RealtimeBlob
Binary payload sent over realtime model transports.
RoutedLlm
A BaseLlm implementation that delegates to one of multiple models based on an LlmRouter function.
RoutedLlmErrorContext
Error context passed to an LlmRouter when a candidate model fails before yielding any responses.
ToolDeclaration
Tool declaration payload sent to model backends.

Enums

ApiType
Apigee backend protocol families supported by this adapter.
FunctionCallingConfigMode
Function-calling modes recognized by model providers.

Mixins

GemmaFunctionCallingMixin
Mixin providing function calling support for Gemma 3 models.

Extensions

GeminiHttpOptionsBaseUrl on HttpOptions
Extension providing client-level base URL metadata on HttpOptions.

Constants

geminiDefaultApiVersion → const String
Default API version used for the Gemini Developer API when none is explicitly configured.

Properties

anthropicGcsDownloaderForTest ↔ AnthropicGcsDownloader?
Optional process-wide GCS downloader override used by static helpers/tests.
getter/setter pair
anthropicSdkMajorVersionForTest ↔ int?
Optional Anthropic SDK major version override used by tests.
getter/setter pair
anthropicWarningHandlerForTest ↔ AnthropicWarningHandler?
Optional process-wide warning handler override used by tests.
getter/setter pair
declaredInteractionsSamplingParams ↔ Set<String>
Sampling knobs declared by the active client configuration.
getter/setter pair
interactionsLogHandlerForTest ↔ InteractionsLogHandler?
Test hook to intercept log warnings.
getter/setter pair

Functions

annotateValueError(ArgumentError exc, {required bool vertexai}) → ArgumentError
Annotates a backend-compatibility exc with its LlmRequest.config field path and target vertexai backend.
buildAdkHttpOptions({Map<String, Object?>? clientKwargs, Map<String, String>? defaultHeaders, HttpRetryOptions? retryOptions, String? apiVersion, String? baseUrl, bool excludeRuntimeTag = false, Map<String, String>? environment}) → HttpOptions
Builds HttpOptions by merging caller clientKwargs http_options with ADK defaults and tracking headers.
buildGenerationConfig(GenerateContentConfig config, {Set<String>? declaredSamplingParams}) → Map<String, Object?>
Builds interactions generation config from config.
clearExplicitCachingRefusalCacheForTest() → void
Clears the in-memory set of (scope, model) entries that reported explicit context caching as unsupported. Intended for test isolation.
convertContentsToTurns(List<Content> contents) → List<Map<String, Object?>>
Converts conversation contents into interactions API turns.
convertContentToTurn(Content content) → Map<String, Object?>
Converts one Content turn into interactions API turn format.
convertInteractionEventToLlmResponse(Map<String, Object?> event, List<Part> aggregatedParts, {required String? interactionId, String? fallbackModelVersion, Map<int, Part>? fcPartsByIndex, InteractionsStreamState? streamState}) → LlmResponse?
Converts one interactions streaming event into an LlmResponse.
convertInteractionOutputToPart(Map<String, Object?> output) → Part?
Converts one interactions output row into a Part.
convertInteractionOutputToParts(Map<String, Object?> output) → List<Part>
Converts one interactions output/step row into zero or more Part objects.
convertInteractionToLlmResponse(Map<String, Object?> interaction, {String? fallbackModelVersion}) → LlmResponse
Converts a full interactions API object into an LlmResponse.
convertPartToInteractionContent(Part part) → Map<String, Object?>?
Converts one Part into interactions API content format.
convertToolsConfigToInteractionsFormat(GenerateContentConfig config) → List<Map<String, Object?>>
Converts tool declarations in config to interactions API tool entries.
copyRequestScopedFields(GenerateContentConfig config) → GenerateContentConfig
Copies request-scoped mutable containers on config so per-request assembly or callbacks do not mutate the source configuration.
extractSystemInstruction(GenerateContentConfig config) → String?
Returns a normalized system instruction string from config.
filterMediaHistory(List<Content> history) → List<Content>
Filters media parts out of a list of history Content items, omitting entries whose parts are all removed.
generateContentViaInteractions({required LlmRequest llmRequest, required bool stream, Stream<LlmResponse> invoker(LlmRequest request, {required bool stream})?, GeminiRestTransport? restTransport, String? apiKey, String? baseUrl, String apiVersion = 'v1beta', Map<String, String>? headers, HttpRetryOptions? retryOptions, bool excludeRuntimeTag = false, Map<String, String>? environment}) → Stream<LlmResponse>
Generates model responses through the Gemini interactions API pathway.
getLatestUserContents(List<Content> contents) → List<Content>
Returns the latest user segment from contents.
isTransientUserContent(LlmRequest llmRequest, Content content) → bool
Returns whether ADK inserted content as transient user context on llmRequest rather than the user.
lastNonTransientContent(LlmRequest llmRequest) → Content?
Returns the last content in llmRequest not inserted as transient ADK context, or null if none exists.
parseToolCallArguments(Object? arguments, {String? functionName}) → Object?
Parses tool call arguments into a JSON-encodable object, throwing FormatException when the arguments cannot be parsed or encoded.
parseToolCallsFromText(String? textBlock, {bool allowBareJson = true}) → (List<Map<String, Object?>>, String?)
Extracts inline JSON tool calls from LiteLLM text responses while ignoring tool calls quoted inside Markdown code spans/fences, <think> blocks, or bare JSON following prose.
redactFileUriForLog(String fileUri, {String? displayName}) → String
Returns a privacy-preserving identifier for logs and error messages.
resetWarnedSamplingParamsForTest() → void
Test hook to clear warned sampling parameters.
runWithRouting<T, C, TYield>(Map<String, T> items, C context, FutureOr<String?> router(Map<String, T> items, C context, {RoutedLlmErrorContext? errorContext}), Stream<TYield> runFn(T item)) → Stream<TYield>
Runs runFn against items selected by router, failing over if an item throws before emitting its first value.
toGenerateContentBody(LlmRequest llmRequest, {bool? vertexai, Object? apiClient, Map<String, String>? environment}) → Map<String, dynamic>
Converts llmRequest into a generateContent JSON request body.
withAdkHttpOptions({Map<String, Object?>? clientKwargs, Map<String, String>? defaultHeaders, HttpRetryOptions? retryOptions, String? apiVersion, String? baseUrl, bool excludeRuntimeTag = false, Map<String, String>? environment}) → Map<String, Object?>
Returns a copy of clientKwargs with ADK HTTP options and tracking headers merged into http_options.

Typedefs

AnthropicApiInvoker = Future<List<Map<String, Object?>>> Function({required Map<String, Object?> request, required bool stream})
Callback that invokes Anthropic message APIs and returns raw responses.
AnthropicGcsDownloader = AnthropicGcsObject Function(String bucketName, String blobName)
Callback that downloads a GCS object for gs://bucket/blob URIs.
AnthropicGenerateHook = Stream<LlmResponse> Function(LlmRequest request, bool stream)
Hook for overriding Anthropic generation behavior.
AnthropicStreamInvoker = Stream<Map<String, Object?>> Function({required Map<String, Object?> request})
Callback that streams raw Anthropic SSE event payloads.
AnthropicWarningHandler = void Function(String message)
Callback to intercept warnings emitted by AnthropicLlm (for testing).
Claude = AnthropicLlm
Backward-compatible alias for AnthropicLlm.
GeminiGenerateHook = Stream<LlmResponse> Function(LlmRequest request, bool stream)
Hook for overriding Gemini generation behavior.
GeminiInteractionsInvoker = Stream<LlmResponse> Function(LlmRequest request, {required bool stream})
Invoker hook for Gemini interactions API generation.
GeminiLiveSessionFactory = GeminiLiveSession Function(LlmRequest request)
Factory that creates live Gemini session transports.
GemmaLlm = Gemma
Backwards-compatible alias for Gemma.
GoogleLlm = Gemini
Backward-compatible alias for Gemini.
InteractionsLogHandler = void Function(String message, {int level, String name})
Optional callback to intercept warnings emitted by interactions utils (for testing).
LiteLlmCompletionsInvoker = Future<List<Map<String, Object?>>> Function({required Map<String, Object?> payload, required bool stream})
Callback that invokes a LiteLLM-compatible completions endpoint.
LiteLlmGenerateHook = Stream<LlmResponse> Function(LlmRequest request, bool stream)
Hook for overriding LiteLLM generation behavior.
LlmFactory = BaseLlm Function(String model)
Factory function that creates an LLM adapter for a model string.
LlmRouter = FutureOr<String?> Function(Map<String, BaseLlm> models, LlmRequest request, {RoutedLlmErrorContext? errorContext})
Function that selects a model key from models for request.

Exceptions / Errors

AnthropicApiException
Anthropic API exception with HTTP and body context.
ChatCompletionsHttpException
HTTP exception thrown by ChatCompletionsHttpClient.
LiteLlmException
Exception thrown when a LiteLLM/Ollama HTTP request fails.
MalformedFunctionCallException
Exception thrown when the model returned a malformed function call.
RecoverableLiveConnectionException
Recoverable failure raised by live connections when reconnection is possible.
ResourceExhaustedModelException
Exception thrown when model capacity is exhausted.