llamadart library
High-performance Dart and Flutter plugin for local LLM inference.
llamadart allows you to run Large Language Models (LLMs) locally with
GGUF models through llama.cpp and .litertlm bundles through LiteRT-LM
across native and web platforms.
Core Components
- LlamaEngine: The stateless engine for model loading, tokenization, and generation.
- ChatSession: A high-level, stateful interface for chat-based interactions. It automatically manages conversation history and context window limits.
- LlamaBackend: The platform-agnostic interface for inference.
Custom backends and their test fakes also import
package:llamadart/backend.dart. The raw llama.cpp FFI is in
package:llamadart/llama_cpp_bindings.dart, outside semantic versioning.
Simple Example
final engine = LlamaEngine(LlamaBackend());
await engine.loadModel('path/to/model.gguf'); // or model.litertlm
final session = ChatSession(engine);
await for (final chunk in session.create([LlamaTextContent('Hello!')])) {
stdout.write(chunk.text);
}
final reply = await session.send('Say that again, shorter.');
print(reply.text);
await engine.dispose();
Classes
- BackendPerfContextData
- Native performance timings reported by llama.cpp for the active context.
- ChatParseResult
- The result of parsing raw LLM output into structured components.
- ChatSession
- Convenience wrapper for multi-turn chat with automatic history management.
- ChatTemplateEngine
- Orchestrates chat template detection, rendering, and output parsing.
- ChatTemplateHandler
- Abstract base class for per-format chat template handlers.
- ChoiceAnswer
- Pick-one answer to a ChoiceQuestion: the chosen label and the probability of each.
-
ChoiceKey<
T extends Object?> -
Key of a pick-one question (ChoiceQuestion) whose options stand for
values of type
T. -
ChoiceOf<
T extends Object?> -
A ChoiceAnswer read through a ChoiceKey, with option values of type
T. - ChoiceQuestion
- A pick-one question: the answer is the most probable label of criteria.
- DecisionAnswer
- The model's answer to one DecisionQuestion.
- DecisionCapabilities
- Decision-model support of a LlamaEngine, or of a loaded DecisionEngine.
- DecisionEngine
- Answers typed questions about a state with a Laya-style decision model.
-
DecisionKey<
R extends Object?> -
A question with its id, typed by what reading its answer gives:
R. - DecisionModel
- A Laya-style decision model: an encoder GGUF, a decision head and, for heads without embedded config, the head's config file.
- DecisionModelInfo
- Sequence limits of a loaded decision model and the device its head runs on.
- DecisionModelParams
-
Runtime settings of a decision model:
params:ofDecisionEngine.load. - DecisionQuestion
-
A question with a typed answer (pick one, rate, or yes/no), asked about
a state, in Laya's
system_oneformat. - DecisionRequest
- The input to judge (the "state") and the questions to answer about it.
- DecisionResult
- Answers to the questions of one DecisionRequest, by question id.
- DecisionUsage
- Token usage of a decision call.
- DefaultModelDownloadManager
- Non-IO placeholder for the package-managed model download manager.
- DefaultModelResolver
- Minimal default resolver for Task 1-3 API foundation.
- EngineCapabilities
- What an engine reports about its support: whether it can run, why not, and the backend it runs on.
- GeneratedImage
- A generated image with 8-bit interleaved channels.
- GenerationGrammarTrigger
- Lazy grammar activation trigger.
- GenerationParams
- Parameters controlling the token sampling and generation process.
- GpuDeviceInfo
-
One inference-capable GPU-class device, as returned by
listGpuDevices. - GrammarTrigger
- A trigger that activates grammar constraints.
- ImageGenerationCapabilities
-
Image-generation support of the runtime, from
ImageGenerationEngine.checkRuntime, and of a loaded engine, fromImageGenerationEngine.capabilities. - ImageGenerationCompletion
- Terminal details of an image-generation task.
- ImageGenerationEngine
- Experimental on-device text-to-image generation through the opt-in stable_diffusion runtime (stable-diffusion.cpp).
- ImageGenerationEvent
- Base class for image-generation events.
- ImageGenerationFinalEvent
- Final event carrying the generated images.
- ImageGenerationModel
- An image-generation model: a main file and the other files it needs.
- ImageGenerationProgressEvent
- Progress emitted before the final images are available.
- ImageGenerationRequest
- A request to generate one or more images from a text prompt.
- ImageGenerationResult
- The images of one completed generation.
- ImageGenerationTask
- A cancellable image generation.
- ImageModelComponent
- A file of an image model besides its main file.
- ImageModelParams
-
Runtime settings of an image-generation engine:
params:ofImageGenerationEngine.load. - LiteRtLmAsrAdapter
-
Dedicated LiteRT-LM ASR: a
.tflitespeech model and its tokenizer run natively in a worker isolate, with incremental PCM input and partial transcripts. - LiteRtLmAsrRuntimeConfig
- Configuration for a dedicated LiteRT-LM ASR session.
- LlamaAudioContent
- A part of a message containing generic multimodal audio input.
- LlamaBackend
- Platform-agnostic interface for local model inference.
- LlamaChatMessage
- A message in a chat conversation history.
- LlamaChatOperation
-
A chat completion:
LlamaEngine.create,createStructuredJsonorChatSession.create. - LlamaChatTemplateResult
- The result of applying a chat template to a conversation history.
- LlamaCompletion
- A chat completion collected from a stream of LlamaCompletionChunks.
- LlamaCompletionChunk
-
Represents a streaming chunk of a chat completion.
Aligns with OpenAI's
ChatCompletionChunk. - LlamaCompletionChunkChoice
- Represents a choice in a completion chunk.
- LlamaCompletionChunkDelta
- Represents a delta in a completion choice.
- LlamaCompletionChunkFunction
- Represents a function call within a tool call.
- LlamaCompletionChunkToolCall
-
A tool call in a completion chunk, shaped like OpenAI's streaming
ToolCall. - LlamaContentPart
- Base class for all content types in a message.
- LlamaEmbeddingCapabilities
- Embedding modalities available on the loaded model and runtime.
- LlamaEmbeddingInput
- One embedding request: ordered, interleaved text, image and audio parts.
- LlamaEmbeddingsOperation
- A text or content embeddings request.
- LlamaEngine
- Stateless chat completions engine (like OpenAI's Chat Completions API).
- LlamaEngineCapabilities
-
What a
LlamaEngineand its loaded model support, as the loaded model's runtime reports it. - LlamaEngineObserver
-
Observes the operations of a
LlamaEngine, for tracing, metrics or logging. - LlamaGenerationUsage
- Token counts and timings of one generation request.
- LlamaImageContent
- A part of a message containing image data for vision models.
- LlamaLogger
- A lightweight singleton logger for the llama_dart library.
- LlamaLogging
- Library-wide logging configuration for Dart-side records and native runtime output.
- LlamaLogRecord
- A log record containing level, message, time, and optional error info.
- LlamaModel
-
The files of a model that
LlamaEngineruns. - LlamaModelLoadOperation
-
A model load: a whole
LlamaEngine.loadorsetModelcall, with its downloads and its projector, or the deprecatedloadModelandloadModelFromUrl, including the load thatloadModelSourceperforms after resolving its source. - LlamaNextTokenScores
-
Log-probabilities of the token that would follow a prompt, from
LlamaEngine.scoreNextToken. - LlamaOperation
-
An operation of a
LlamaEngine. - LlamaOperationObserver
- Observes one LlamaOperation after LlamaEngineObserver.onStart.
- LlamaOperationResult
- How a LlamaOperation ended.
-
LlamaStructuredOutput<
T> - Describes a strict structured JSON response and final-output decoder.
- LlamaTextCompletionOperation
-
A raw-prompt text completion:
LlamaEngine.generate. - LlamaTextContent
- A part of a message containing plain text.
- LlamaThinkingContent
- A part of a message containing the model's Chain-of-Thought (reasoning).
- LlamaTokenLogprob
- One token and its log-probability.
- LlamaToolCallContent
- A part of a message containing a tool call solicitation from the model.
- LlamaToolLoopResult
-
The outcome of
ChatSession.sendWithTools. - LlamaToolResultContent
- A part of a message containing the result of a tool execution.
- LlamaVideoContent
- A part of a message containing encoded video input.
- LocalModelFile
- A resolved local model file path.
- LoraAdapterConfig
- Configuration for a LoRA (Low-Rank Adaptation) adapter.
- ModelCacheEntry
- Metadata describing a package-managed cached model file.
- ModelDownloadCancelToken
- Cooperative cancellation token for model downloads and resolution.
- ModelDownloadController
- Small, dependency-free controller for app model download/cache UX.
- ModelDownloadManager
- Public API for package-managed model cache/download implementations.
- ModelDownloadProgress
- Progress information for a package-managed model download.
- ModelDownloadTaskSnapshot
- Immutable app-facing state for a ModelDownloadController.
- ModelFileStore
-
Where an engine finds and keeps model files: the resolver that maps a
ModelSourceto a load target, and the download manager that fetches and caches remote files. - ModelFileType
- Model file type and quantization metadata for a loaded model.
- ModelLoadOptions
- Options used when resolving and loading model sources.
- ModelLoadTarget
- Concrete model target after source resolution.
- ModelParams
- Configuration parameters for loading a Llama model.
- ModelResolver
- Resolves a ModelSource to a concrete load target for the engine.
- ModelResolveRequest
- Request data passed to a ModelResolver.
- ModelSource
- Describes where a model file can be loaded from.
- NoulAnswer
- Yes/no answer to a NoulQuestion: the probability that its statement is true.
- NoulKey
- Key of a yes/no question (NoulQuestion); reading it gives the NoulAnswer.
- NoulQuestion
- A yes/no question, Jev's "noul": the answer is the probability that the statement in instructions is true.
- Qwen3AsrAdapter
- Qwen3-ASR on llama.cpp, with its audio projector.
- Qwen3TtsAdapter
- Qwen3-TTS on llama.cpp, with its audio-generation projector.
- RemoteModelUrl
- A resolved remote model URL.
- ScoreAnswer
- Rating answer to a ScoreQuestion: the expected level and the probability of each.
- ScoreKey
- Key of a rating question (ScoreQuestion); reading it gives the ScoreAnswer.
- ScoreQuestion
- A rating question: the answer places the state on ordered levels.
- SpeculativeDecodingConfig
- Backend-neutral speculative decoding configuration.
- SpeechAudioBytesInput
- Encoded audio held in memory.
- SpeechAudioFileInput
- A local encoded audio file.
- SpeechAudioFormat
- Audio metadata supplied with speech input.
- SpeechAudioInput
- Base class for audio accepted by SpeechToTextEngine.
- SpeechAudioPcmInput
- Mono float PCM held in memory.
- SpeechToTextAdapter
-
Model-specific knowledge
SpeechToTextEngineneeds to run a speech-recognition model. - SpeechToTextCapabilities
- Runtime speech-to-text capabilities for the loaded engine.
- SpeechToTextCompletion
- Terminal details for a speech recognition task.
- SpeechToTextEngine
- Typed speech-to-text API for prompt-adapted and dedicated ASR runtimes.
- SpeechToTextEvent
- Base class for streamed speech recognition events.
- SpeechToTextFinalEvent
- The final transcript event for a task.
- SpeechToTextModel
- A speech-recognition model: its files and the adapter that drives it.
- SpeechToTextPartialEvent
- A replaceable, non-final transcript update.
- SpeechToTextPromptAdapter
-
Recognizes speech with a multimodal chat model on
LlamaEngine, by sending the audio with an instruction and parsing the generated text. - SpeechToTextRequest
- A request to recognize speech from one complete audio input.
- SpeechToTextResult
- Final speech recognition result.
- SpeechToTextStreamingSession
- An active incremental speech-recognition session.
- SpeechToTextTask
- A cancellable speech recognition operation.
- SpeechToTextTranscript
- Transcript text and language that a SpeechToTextPromptAdapter parsed from a model's output.
- StateLoadResult
- Result of BackendStatePersistence.stateLoadFile. Contains the token sequence saved alongside the native KV-cache state.
- TemplateToolCallSerialization
- Tool-call serialization policy for template render contexts.
- TextToSpeechAdapter
-
Model-specific knowledge
TextToSpeechEngineneeds to run a text-to-speech model. - TextToSpeechCapabilities
- Runtime text-to-speech capabilities for the loaded engine.
- TextToSpeechCompletion
- Terminal details for a synthesis task.
- TextToSpeechEngine
- Typed text-to-speech API backed by a LlamaEngine.
- TextToSpeechEvent
- Base class for synthesis events.
- TextToSpeechFinalEvent
- Final PCM event emitted after generation completes.
- TextToSpeechModel
- A text-to-speech model: its files and the adapter that drives it.
- TextToSpeechProgressEvent
- Progress emitted before the final PCM becomes available.
- TextToSpeechRequest
- A request to synthesize one complete utterance.
- TextToSpeechResult
- Complete synthesized PCM audio.
- TextToSpeechTask
- A cancellable text-to-speech operation.
- ThinkingBudget
- Limits the generated tokens within a model's reasoning block.
- ThrowingModelDownloadManager
- Base implementation for download managers that do not implement IO yet.
- ToolDefinition
- Defines a tool that the LLM can invoke.
- ToolParam
- Represents a single parameter in a tool's input schema.
- ToolParams
- Provides type-safe access to tool call arguments.
- TranscriptSegment
- A recognized transcript segment.
- TranscriptWord
- A recognized word with optional backend-provided metadata.
Enums
- BackendTextToSpeechModel
- Model family reported by a backend text-to-speech implementation.
- ChatFormat
- Identifies the chat format detected from a model's template source.
- ComputeDevice
-
Device an engine runs a model on:
ModelParams.device,ImageModelParams.deviceandDecisionModelParams.device. - DecisionQuestionType
- Kind of a DecisionQuestion: pick one, rate on a scale, or yes/no.
- FlashAttention
-
Selects llama.cpp's
flash_attn_type. Required when KvCacheType is not KvCacheType.f16 — llama.cpp refuses non-F16 KV cache without it. - GpuBackend
- GPU backend selection for runtime device preference.
- GpuDeviceType
- The kind of compute device a backend enumerated.
- GrammarTriggerType
- How a GenerationGrammarTrigger activates a lazy grammar.
- ImageGenerationCompletionState
- Terminal state of an image-generation task.
- ImageGenerationPhase
- Stage of an image generation.
- ImageGenerationSampler
- Sampling method of a generation.
- ImageGenerationScheduler
- Noise schedule of a generation.
- ImageModelRole
- Runtime role of an image-model file.
- KvCacheType
-
KV-cache data type for
llama_context_params.type_k/type_v. q8_0 ≈ 0.5× the KV memory of f16; q4_0 ≈ 0.25×. Both require flash attention to be enabled (see FlashAttention). - LiteRtLmActivationDataType
-
LiteRT-LM activation data type override for native
.litertlmengines. - LiteRtLmAsrBackend
- LiteRT accelerator used for a dedicated ASR model.
- LiteRtLmAsrModelPreset
- LiteRT-LM ASR model families whose runtime metadata is versioned by the native bridge.
- LiteRtLmBackendPreference
-
Preferred LiteRT-LM runtime backend for
.litertlmmodels. - LlamaChatRole
- Role of a message sender in a chat conversation.
- LlamaEmbeddingModality
- A modality accepted by the embedding input contract.
- LlamaFinishReason
-
Why a completion stopped, typed from the
finish_reasonwire value of a LlamaCompletionChunkChoice. - LlamaLogLevel
- Log level for the selected native inference backend.
- LlamaRuntime
- The inference runtime that runs a loaded model.
- LlamaSpeechTranscriptLimit
- Token limit that stopped speech recognition before the transcript ended.
- LlamaToolLoopStopReason
-
Why
ChatSession.sendWithToolsstopped. - ModelCachePlatform
- Operating-system families relevant to model cache directory selection.
- ModelCachePolicy
- Controls how model source resolution should interact with caches.
- ModelDownloadTaskStage
- High-level lifecycle stage for an app-facing model download task.
- ModelFormat
- The container format of a model file, which selects the runtime that loads it.
- ModelSourceKind
- The kind of model source represented by a ModelSource.
- ModelSplitMode
- Strategy for distributing model tensors across GPU devices.
- SpeculativeDecodingStrategy
- Backend-neutral speculative decoding strategy.
- SpeechAudioInputKind
- The kind of audio input accepted by a speech recognizer.
- SpeechToTextCompletionState
- Terminal state of a speech recognition task.
- SpeechToTextImplementation
- How the active backend implements speech recognition.
- SpeechToTextModelProfile
- Model-specific adapter used by SpeechToTextEngine.
- TextToSpeechCompletionState
- Terminal state of a synthesis task.
- TextToSpeechImplementation
- How the active backend implements text-to-speech.
- TextToSpeechModelProfile
- Model-specific adapter selected by TextToSpeechEngine.
- TextToSpeechProgressPhase
- Current stage of a synthesis task.
- ToolChoice
- Controls which tool(s) the model should call.
Extensions
- ChatSessionCompletionExtension on ChatSession
- One-shot replies for ChatSession.
- ChatSessionToolLoopExtension on ChatSession
- Tool-calling loops for ChatSession.
- DecisionResultKeys on DecisionResult
- Typed reads of a DecisionResult through DecisionKeys.
- LlamaCompletionChunkExtension on LlamaCompletionChunk
- Shortcuts for the first choice of a LlamaCompletionChunk.
-
LlamaCompletionStreamExtension
on Stream<
LlamaCompletionChunk> -
Text and collection helpers for a chat-completion stream, such as the
one
LlamaEngine.createorChatSession.createreturns. - LlamaEngineCompletionExtension on LlamaEngine
- One-shot completions for LlamaEngine.
-
LlamaStructuredOutputStreamExtension
on Stream<
LlamaCompletionChunk> - Collects streamed chat-completion content and parses it as structured JSON.
Properties
- liteRtLmQwen3ChatTemplate → String
-
The current canonical Qwen3 text template for
ModelParams.chatTemplate.no setter
Functions
-
hasPersistentCacheSensitiveUrlParts(
String value) → bool -
Returns whether
valuecontains URL parts that should not be persisted as browser cache keys. -
resolveModelContextBatchSizes(
ModelParams modelParams, int contextSize, {bool useFullContextDefaults = false}) → ({int batchSize, int microBatchSize}) - Resolves llama.cpp-compatible context batch parameters.
Typedefs
-
LlamaJsonObjectDecoder<
T> = T Function(Map< String, dynamic> json) - Converts a decoded JSON object into an application-specific value.
-
LlamaJsonValueDecoder<
T> = T Function(Object? value) - Converts any decoded JSON value into an application-specific value.
- LlamaLogHandler = void Function(LlamaLogRecord record)
- Type definition for custom log handlers.
-
LlamaToolCallCallback
= FutureOr<
Object?> Function(LlamaToolCallContent call) -
Runs a tool call that has no ToolDefinition.handler, or that names a
tool missing from the
toolslist, and returns its result. -
LlamaToolErrorCallback
= FutureOr<
Object?> Function(LlamaToolCallContent call, Object error, StackTrace stackTrace) -
Turns an error thrown while running
callinto the tool result the model sees, or rethrows it to stop the tool loop. - ModelDownloadProgressCallback = void Function(ModelDownloadProgress progress)
- Callback invoked with model download progress.
-
ToolHandler
= Future<
Object?> Function(ToolParams params) - Signature for a tool handler function.
Exceptions / Errors
- LlamaArgumentException
-
Exception thrown when an argument or a combination of parameters is
invalid, such as by
ModelParams.validate. - LlamaAudioFormatException
- Exception thrown when speech audio does not satisfy an input contract.
- LlamaBackendInitializationException
- Exception thrown when a backend cannot initialize its runtime.
- LlamaContextException
- Exception thrown when a context operation fails.
- LlamaDecisionException
- Exception thrown when a decision-model request is invalid or cannot be answered.
- LlamaEmbeddingInputTooLongException
- An embedding input exceeds the loaded context or single-pass budget.
- LlamaException
- Base class for all Llama-related exceptions.
- LlamaImageGenerationException
- Exception thrown when an image-generation request or image buffer is invalid.
- LlamaInferenceException
- Exception thrown during text generation or tokenization.
- LlamaModelException
- Exception thrown when a model fails to load.
- LlamaModelFormatException
-
Exception thrown when a model file's content is in one format but its file
extension or an explicit
format:names another. - LlamaSpeechException
- Exception thrown when speech recognition fails.
- LlamaSpeechTranscriptTruncatedException
- Exception thrown when speech recognition stops at a token limit before the transcript ends.
- LlamaStateException
- Exception thrown when the engine is in an invalid state.
- LlamaTextToSpeechException
- Exception thrown when text-to-speech synthesis fails.
- LlamaUnsupportedException
- Exception thrown when an operation is not supported on the current platform.