leehack/llamadart
Acerca de
Cross-platform on-device LLM inference for Dart & Flutter: GGUF via llama.cpp and LiteRT-LM on Android, iOS, macOS, Windows, Linux and web.
Desarrollo web y de aplicacionesCrecimiento de estrellas medido
- in 24h
- +1
- in 7 days
- +1
- in 15 days
- +2
- in 1 month
- Recopilando historial
Cambios netos en períodos que se solapan, no totales diarios. Los datos no disponibles se dejan en blanco. Las estrellas indican interés, no calidad.
README.md
Originalllamadart
llamadart is a Dart package for on-device inference. It runs GGUF models
through llama.cpp and .litertlm bundles through LiteRT-LM, on Android, iOS,
macOS, Linux, Windows and the web, behind one Dart API. Web support is
experimental. Native targets need no network once the model is on the device.
- Streaming chat and text generation, with structured JSON output and cancellable task handles.
- Tool calling driven by the model's chat template, with image tool results on native llama.cpp for Hermes-style, Qwen XML and Gemma 4 templates.
- Embeddings, reranking, and image and audio input with multimodal models.
- Speech to text (including incremental live PCM streaming on native
llama.cppviaLlamaCppLiveAsrAdapterfor Voxtral Realtime and LFM3-Audio, opt-in bounded windowed live PCM viaQwen3WindowedAsrAdapterfor Qwen3-ASR, and on native LiteRT-LM), text to speech (Qwen3-TTS; LFM3-Audio, Soprano, Chatterbox and Pocket TTS on native; experimental PCM streaming for Qwen3-TTS, LFM3-Audio and Pocket TTS), and decision models with cooperative task cancellation. - Image generation from text prompts on native platforms (Preview).
- Runtime LoRA adapters for llama.cpp, observability hooks and typed capability checks.
Native llama.cpp can keep generating past end-of-generation tokens with
GenerationParams(ignoreEos: true), as the --ignore-eos CLI option does,
for benchmarks that need a fixed token count; it rejects a non-empty grammar,
and the other runtimes reject it. See runtime parameters.
Native llama.cpp also supports per-occurrence frequencyPenalty, a
penaltyLastN history window and token-level logitBias. Check
(await engine.capabilities).samplerControls before using these options. It
also supports typicalP, topNSigma, XTC (xtcProbability,
xtcThreshold), dynamic temperature (dynatempRange, dynatempExponent)
and Mirostat (mirostat, mirostatTau, mirostatEta), plus DRY repetition
penalties (dryMultiplier, dryBase, dryAllowedLength, dryPenaltyLastN,
drySequenceBreakers). DRY settings that can exhaust the candidates left by
token bans or runtime suppression throw LlamaArgumentException. To disable
XTC, dynamic temperature or Mirostat, set xtcProbability, dynatempRange
or mirostat to zero and reset its tuning fields to their defaults.
Native llama.cpp can report the log-probability of every generated token, with
the most probable alternatives, on streamed chat completions and raw generation:
set GenerationParams(topLogprobs: 5) after checking
(await engine.capabilities).supportsTokenLogprobs. The values come from the
model's raw distribution, before sampling settings. See
runtime parameters.
Use engine.generateFromTokens(ids) with a native llama.cpp decoder-only GGUF
when the prompt must contain exactly the supplied token IDs. For prefill timing,
set maxTokens: 0 and reusePromptPrefix: false to evaluate every ID without
sampling. See the exact-token guide.
Use engine.generateInfill(prefix: ..., suffix: ...) with a native llama.cpp
decoder-only FIM GGUF after checking (await engine.capabilities).supportsInfill
for fill-in-the-middle code completion with literal tokenization, optional
extraContext chunks, and LlamaInfillPattern ordering. See the
infill guide.
Choose direct llamadart, Genkit, or Flutter Edge AI for your application. The separate genkit_llamadart 3.15.0 package supports llamadart 0.25.0. The Flutter Edge AI connector is owned upstream and pins its own llamadart version.
All five engine types implement LlamadartEngine<C extends EngineCapabilities>
for shared capability inspection and disposal. Keep loading and requests on the
concrete engine; see shared lifecycle ownership.
LFM2 Python-style tool calls use declared argument types and preserve copied string backslashes; see tool calling. The automatic grammar preserves copied singleton string spellings and can use an existing Python arguments wrapper for unambiguous JSON-escaped string values. Foreign XML closing tags remain raw diagnostics with no executable calls.
Native llama.cpp applies schema-directed lazy grammar to LFM2 automatic Python tool calls. Web additionally requires bridge assets v0.1.82+ with a loaded-core prompt-penalty capability; older runtimes reject before inference.
Tools can return images with a compatible chat template and vision projector, or audio on native llama.cpp with an audio projector. Web image results require non-empty bytes and bridge assets v0.1.75+ reporting lazyGrammar. See tool-result media.
Native LiteRT-LM enforces strict JSON Schema output for Qwen3 and Gemma 4 on the macOS arm64 CPU and GPU, the iOS arm64 CPU, the Android arm64 CPU and GPU, the Linux x64 and Windows x64 GPU and CPU, and the Linux arm64 CPU, and for Qwen3 on the iOS arm64 GPU (Gemma 4 cannot create a GPU engine there; per-host model evidence in the structured-output guide), for the schemas llama.cpp's GBNF converter also enforces; see structured output and the support matrix.
LFM2 replies cut off at a reported length limit expose raw partialToolCalls diagnostics separately from executable calls and history. LFM2 tool markers inside reasoning stay in reasoning and produce no executable calls. Explicit parallel-tool requests reach supported Dart tool grammars even when template probes do not recognize parallel history.
Install
dependencies:
llamadart: ^0.25.0
dart pub get
# or
flutter pub get
Requirements: Dart SDK >=3.10.7; for Flutter apps, Flutter SDK >=3.38.6,
iOS deployment target 16.4 and macOS deployment target 14.0 or newer.
Consumers need no local C++ toolchain: the package build hook resolves native
runtime archives on first build or run. Windows and other per-platform notes:
Installation.
Flutter iOS and macOS apps that link the Apple XCFrameworks through Swift
Package Manager add the companion packages for the runtimes they use. A
companion shares its core's MAJOR.MINOR and constrains llamadart to it.
dependencies:
llamadart: ^0.25.0
llamadart_llama_cpp_flutter: ^0.25.0 # GGUF / llama.cpp
llamadart_litert_lm_flutter: ^0.25.0 # Apple .litertlm / LiteRT-LM targets
llamadart_stable_diffusion_flutter: ^0.25.0 # Apple image generation, opt-in
Pairing rules, the SwiftPM bootstrap and the privacy manifest are in
Installation and
Apple setup.
Web apps run dart run llamadart:web_setup once; see the
WebGPU bridge.
Pages with neither cross-origin isolation nor usable SharedArrayBuffer
automatically use the single-threaded GGUF core with bridge assets v0.1.93+.
It uses one CPU
thread and supports WebGPU offload. Serve COOP/COEP headers to enable shared
memory for the threaded core and fetch-backed model loading. Set
window.__llamadartBridgeAllowSingleThreadCore = false before the first model
load to require the threaded core. Lazy tool-call grammars and
custom grammar roots follow the loaded core's lazyGrammar capability.
With bridge assets v0.1.93+, Chromium automatically uses JavaScript-backed
GGUF and projector staging on confirmed memory64 cores when modelBytesHint
is at most 4 GiB. On confirmed wasm32 single-thread cores, the automatic policy
uses JavaScript-backed staging for hints above 960 MiB through 3.75 GiB and
rejects larger hints before downloading. Other loads follow the bridge's
browser policy.
Set ModelParams.jsBackedModelStaging: false to disable staging or true to
require it with staging-capable v0.1.92+ assets. Pass
ModelLoadOptions(cancelToken: token) to stop a streamed Web GGUF load.
Wait for the load to throw LlamaStateException before loading again.
llamadart also ships agent skills that teach coding agents its APIs. Install them from your app's root:
dart run skills@ get
To check a desktop setup without a model, run dart run llamadart:doctor; see
setup report scope.
For Dart Web and Flutter Web, call collectLlamaWebSetupReport() in the
browser.
Hosts bundling a Linux Vulkan runtime can preflight the system loader with
probeLinuxVulkanUnavailableReason() from package:llamadart/backend.dart;
see API levels.
Native llama.cpp automatically skips unavailable Vulkan initialization on Linux
under GpuBackend.auto, retaining the other bundled backends. An explicit
GpuBackend.vulkan load reports LlamaUnsupportedException with a remedy.
First generation
import 'package:llamadart/llamadart.dart';
Future<void> main() async {
final engine = await LlamaEngine.load(
LlamaModel(
ModelSource.parse(
'hf://unsloth/SmolLM2-135M-Instruct-GGUF/'
'SmolLM2-135M-Instruct-Q2_K.gguf',
),
),
);
try {
final reply = await engine.create(
const [
LlamaChatMessage.fromText(
role: LlamaChatRole.user,
text: 'Explain local inference in one sentence.',
),
],
params: const GenerationParams(maxTokens: 48),
).text();
print(reply);
} finally {
await engine.dispose();
}
}
Dispose every engine before a native host calls C exit(); see
Model lifecycle. For multi-turn chat, wrap the
engine in ChatSession:
First chat session.
A native model file the app can open but not name by path, such as an Android document grant or a file the user picked, loads without a copy through its descriptor with engine.setModelFromFileDescriptor; see
Load from a file descriptor.
Runtimes and platforms
LlamaBackend() routes by model file type. After a model loads,
engine.runtime names the runtime and await engine.capabilities reports what
it supports, so branch on those instead of the file extension. Unsupported
runtime and option combinations are rejected with LlamaUnsupportedException
instead of silently degrading.
| Model format | Typical use | Runtime |
|---|---|---|
| GGUF | Broad llama.cpp compatibility, Metal/Vulkan/CUDA/CPU, WebGPU bridge | llama.cpp |
.litertlm |
LiteRT-LM deployments, Android GPU/NPU-oriented bundles, Gemma-family LiteRT packages | LiteRT-LM |
llama.cpp uses Metal on Apple platforms, Vulkan on Linux and Windows, and WebGPU in the browser. Android Vulkan is experimental and opt-in. llama.cpp refuses GPU loads when Android registers a Qualcomm or Imagination (PowerVR) proprietary Vulkan device. Automatic selection falls back to CPU with a warning.
After loading on native llama.cpp or LiteRT-LM, use
await engine.getLoadReport() for the selected device, configuration, and
typed fallback reasons. LiteRT-LM reports a provisional selection until the
deferred engine initializes. Web backends return null.
A llama.cpp runtime older than ggml 0.28.0 (llamadart-native v0.8.0)
limits native Qwen3.5 on Android Vulkan to ordinary text on some GPUs; the
bundled runtime does not. See Android Vulkan.
LiteRT-LM can also use GPU. On Android arm64, ComputeDevice.npu discovers
the LiteRT-LM vendor dispatcher in the app's extracted native library directory. Call
probeLiteRtLmNpuDispatch() to check the dispatcher and NPU placement ABI 1
before downloading a compatible compiled bundle. The pinned litert-lm-native
runtime provides this ABI. Inspect
getLoadReport().liteRtLmNpuPlacement for partition admission and the latest
turn's observed participation. The bundled runtime streams explicit NPU output
once it observes participation and still verifies placement at completion.
Runtimes without progress ABI 1 hold output until completion. For GGUF on Android
arm64, experimental Qualcomm Hexagon HTP ships as an opt-in sidecar in
llamadart-native v1.1.0-6. Select
hexagon in llamadart_native_backends, then use
ComputeDevice.npu with extracted DSP skeletons and hexagon-assets.json passed
via ModelParams.hexagonAssetsDir. probeLlamaCppHexagon() verifies the
extracted host libraries before loading libggml-hexagon.so from beside
libllamadart.so. ComputeDevice.auto excludes HTP. A
release Flutter APK ran Qwen3-0.6B Q4_0 on Galaxy S24 (SM8650/v75) and S25 Ultra (SM8750/v79).
Await cooperative disposal before shutdown. Forced native process exit
can still produce fatal signals. See Enable the Android NPU in your app
for Tensor G6 and Qualcomm packaging and verification.
The experimental Studio app recommends Qwen3 0.6B (Q4_0) for verified Hexagon hosts and Gemma 4 E2B for verified Tensor G6 hosts. Studio also guides MT6989 users through local import of the publisher's compiled LiteRT-LM model. See the Studio Android NPU preview.
On Linux x64, opt into the experimental Intel OpenVINO NPU sidecar in the
build hook.
Call probeLlamaCppOpenVino(), then use ComputeDevice.npu with optional
ModelParams.openVinoCacheDir. Redistribute the Intel OpenVINO license and
oneTBB notices with the sidecar. Intel hardware qualification and Windows
publication remain open in #2554.
On native LiteRT-LM, numberOfThreads applies only to CPU, including a CPU
retry under automatic device selection.
Android 12+ apps targeting API 31+ must request the optional vendor OpenCL
library in their manifest; see Android LiteRT-LM setup.
The opt-in llama.cpp opencl module on Android needs the same declaration;
without it the module cannot load, ComputeDevice.auto runs elsewhere and
ComputeDevice.gpu with GpuBackend.opencl throws. ggml-opencl admits only
Adreno (and Intel) GPUs.
GPU support still depends on the device, driver and model. If GPU engine
creation fails, ComputeDevice.auto retries on the CPU with a warning;
ComputeDevice.gpu fails instead.
Image generation is not available on the web. The Windows x64 image
runtime bundles its Visual C++ runtime DLLs. On iOS, use
ImageModelPlacement(vaeOnCpu: true) for CPU VAE decoding with Metal
diffusion, or choose CPU generation. The pinned v0.4.0 runtime splits Metal graphs, so a full VAE
is admitted on iOS Metal. Device qualification for v0.4.0 is pending.
SD v0.3.0-6 passed four full-VAE load/dispose cycles and eight decodes per device on iPhone 16 Pro (iOS 18.3.2) and iPhone 17 Pro (iOS 26.5.1), tested at 6b191b28. Small nonzero residual memory remains; this single session is not proof of zero leaks (#2004).
Use estimateImageGenerationMemoryBytes to plan an image model download.
If the load-time memory check refuses the model, catch
LlamaImageMemoryException to read the estimate and the available budget.
See Image generation memory and limits.
Per-target support, device limitations and runtime options:
- Platform and backend support matrix, including known limitations
- Backend selection
- Runtime parameters
- Native runtime configuration
Current default runtime pins:
| Runtime | Pin |
|---|---|
| Native llama.cpp / GGUF | leehack/[email protected] |
Native LiteRT-LM / .litertlm |
leehack/[email protected] |
| Web llama.cpp / GGUF | leehack/[email protected] |
Web LiteRT-LM / .litertlm |
@litert-lm/[email protected] |
The Web backend reuses cached HTTP(S) projectors through the pinned bridge.
If a direct WebAssembly core abort unloads the model, catch
LlamaModelUnloadedException and reload it before retrying.
On thinking-capable Qwen3-Coder XML templates, a generated <tool_call>
ends the thinking budget and generation continues into the call. This needs
llamadart-native v1.0.0-4 or a WebGPU bridge core reporting
thinkingBudgetMultiEnd (assets v0.1.87+). An explicit
ThinkingBudget.endTag selects a single delimiter.
Native LiteRT-LM uses a lazy ABI-aware client for direct calls, services and
speech. The public selector admits legacy runtimes and C API 1.0.x and 1.1.x.
It refuses unknown or future versions before engine calls. The pin is published native
v0.20.0-2
(owner c30a2423 / upstream 95df4c2a). It uses C API 1.1.0
and links LiteRT and the GPU accelerators into the runtime. The selected loader
requires macOS 14+ before owned library loads, including legacy libraries and
custom paths. Web LiteRT-LM uses @litert-lm/[email protected]; through
LlamaBackend.withTextHistory() it forwards chat history, supports tool
calling and reports replies cut off at a token limit. Web apps that preload
window.LiteRtLmEngine must also expose window.LiteRtLmBackendEnum = module.Backend
from the same package for CPU inference. On WebGPU, a drafter-bearing bundle
can use MTP with loadMtp: true and a per-request speculation flag. See the
LiteRT-LM Web MTP guide.
Native overrides accept stable vMAJOR.MINOR.PATCH releases and explicit
historical or nightly bNNNN artifacts. New nightly wrapper rebuilds use
bNNNN-N; existing bNNNN-llamadart.N artifacts stay valid as
consumption-only overrides. Nightly cores use canonical decimal spelling, and
rebuild counters start at 1 without leading zeros. Build-hook overrides must
always name an explicit tag; latest is limited to maintainer synchronization
and header/binding regeneration. On Windows, runtime environment directory
overrides select backend modules; use llamadart_native_path to replace the
complete runtime. The full override rules are in Native runtime configuration.
Await engine disposal before host shutdown. Forced worker cleanup during
native creation uses owner API v1 in the pinned v1.1.0-6 runtime. Raw
allocation-to-registration gaps remain; see the
shutdown contract.
Guides
| Task | Docs |
|---|---|
| Resolve local paths, URLs, and Hugging Face sources | Finding models |
| Stream text and collect output | Generation and streaming |
| Generate typed JSON | Structured output |
| Use tool calling | Tool calling |
| Use images, audio, or projectors | Multimodal |
| Transcribe speech on device | Speech to text |
| Synthesize speech on device | Text to speech |
| Generate images on device (Preview) | Image generation |
| Answer typed questions with a decision model | Decision models |
| Generate embeddings and rerank | Embeddings |
| Load LoRA adapters | LoRA adapters |
| Save and restore KV state, write a custom backend | API levels |
| Trace and measure requests | Observability |
| Run Flutter Web / WebGPU | WebGPU bridge |
| Tune performance | Performance tuning |
| Upgrade from 0.16.x | 0.17 migration guide |
Examples
Run the Flutter chat app from a repository checkout, try the hosted chat app, or chat with GGUF models (SmolLM2 135M, Qwen3.5 0.8B, or desktop Chrome Gemma 4 E2B) on preview.dartpad.dev.
- Basic Dart CLI
- Flutter chat app
- Experimental Studio app and reusable core, with Chat, Notes, Coding (including app-owned local workspaces on iOS/Android), model management, speech, images, and runtime exploration
- Laya Tetris, a Flutter game played by a decision model
- HTTP server example
- TUI coding agent example
Contributing
Repository checks, validation commands, and PR expectations are in AGENTS.md and the maintainer docs.
License
MIT. See LICENSE.
Explorar proyectos relacionados
Cargando…