offgrid: embeddable offline AI
offgrid is a small native library that adds local, offline AI to an application: chat, tool calling, structured JSON output, embeddings, image and audio input, and image generation. You link a library, ship a GGUF model next to your app, and that's it. No daemon, no Docker, no cloud, and no network access at runtime.
It is written in Rust on top of llama.cpp. It runs on any GPU through Vulkan, falls back to the CPU automatically, and is packaged for Linux and Windows.
flowchart TD
subgraph app["Your app"]
direction LR
rust["Rust / Tauri"]
capps["C · C++ · Python · Go · C#"]
deno["Deno"]
http["Any HTTP client"]
end
abi["C ABI · liboffgrid"]
server["offgrid-server · OpenAI API"]
core["offgrid · Rust core"]
sys["offgrid-sys · llama.cpp"]
gpu["Vulkan · CPU · CUDA"]
rust --> core
capps --> abi
deno --> abi
http --> server
abi --> core
server --> core
core --> sys --> gpu
What it does
| Capability | Details |
|---|---|
| Chat | Streaming generation with stop strings, token limits, sampling options and seeds. Requests follow the OpenAI format and are stateless; the session reuses the matching prefix of its KV cache, so follow-up turns only process new tokens. Hybrid models (Qwen3.5 and later), whose recurrent layers can't drop the end of their state, keep checkpoints every 4096 tokens: a new conversation with the same system prompt restarts from the last one instead of from zero. |
| Chat templates | Each model's own Jinja template (stored in the GGUF) is rendered with minijinja the way Hugging Face does it. 69 of the 72 real-world templates in llama.cpp's test corpus render; the other 3 refuse by design (for example, Gemma 2 has no system role). If a template can't be used, llama.cpp's built-in formats are the fallback. |
| Structured output | OpenAI response_format (json_object or json_schema) is compiled into a llama.cpp grammar, so the output is valid by construction. The converter handles objects, arrays, enums, anyOf / oneOf / allOf, $ref / $defs, and string formats, patterns and lengths. Properties are generated in the order they are declared. |
| Tool calling | OpenAI tools, tool_choice and parallel_tool_calls. Tool calls are parsed from the model's native format: Hermes/Qwen, Llama 3.x, Mistral, Qwen3-Coder XML, Gemma 4, or generic JSON. If a model's template ignores tools (Gemma 3, for example), the tools and the call format are described in the system message instead, and earlier calls and results are written into the conversation as text. A grammar keeps the arguments valid against each tool's schema. Loop helpers (run_tools, runTools) handle the call, execute and feed-back cycle. |
| Reasoning | Thinking models' <think> blocks are separated into reasoning_content and streamed as their own events. |
| Vision and audio | Images (PNG, JPEG, …) and audio (WAV, MP3, FLAC) are sent as OpenAI content parts. Several items per message and mixed image and audio both work. Encoded media is reused across turns from the KV cache and is not decoded again. |
| Code completion | Fill-in-the-middle for code models with FIM tokens (Qwen2.5-Coder, ...), laid out like llama.cpp's /infill: extra context from other files, the code before and after the cursor, and stops at a time limit or at a less-indented line. llama.cpp's infill sampler (on by default) ends a completion once the model is unsure how to go on, which keeps suggestions short and fast. Completions that share a prefix reuse the KV cache, and chunks that moved up (an editor's window sliding down a file) are shifted into place instead of evaluated again (cache_reuse, as llama.cpp's --cache-reuse). |
| Memory and large models | KV cache in 8 or 4 bits (cache_type: a 32k context in half the memory), and Mixture-of-Experts models larger than the GPU with their expert weights in RAM (n_cpu_moe, as llama.cpp's --n-cpu-moe), which keeps them fast at long contexts. |
| Embeddings | Batched and L2-normalized, with float or base64 output. |
| Image generation | Text-to-image and image-to-image through stable-diffusion.cpp (Z-Image, FLUX, SD 1.x/2.x/XL, ...), built on the same ggml as llama.cpp. Progress (loading, sampling, decoding) and cancellation; PNG or RGB output. Runs alongside chat in the same process. Feature image; included in the release packages. |
| Cancellation | Requests can be cancelled from any thread. Cancellation is scoped to one request and never affects a later one. |
| Server | offgrid-server: OpenAI-compatible HTTP with SSE streaming, llama.cpp's /infill for editor plugins, a session pool, cancellation when the client disconnects, an optional API key, and graceful shutdown. |
Using it
Rust (or Tauri)
cargo add offgrid (builds llama.cpp from source: CMake, a C/C++ compiler and, for the default
vulkan feature, the Vulkan headers and glslc; default-features = false for CPU only).
use offgrid::*;
let model = Model::load("qwen3-4b.gguf", &ModelParams::default())?;
let mut chat = ChatSession::new(model, &SessionParams::default())?;
let req = ChatRequest::new(vec![ChatMessage::user("Name three rivers.")]);
let resp = chat.complete(&req, |piece| { print!("{piece}"); true })?; // return false to cancel
println!("\n{:?} {:?}", resp.finish_reason, resp.usage);
Images or audio need the model's projector:
let model = Model::load("qwen2.5-vl-3b.gguf", &ModelParams { mmproj: Some("mmproj.gguf".into()), ..Default::default() })?;
let msg = ChatMessage::user_with_media("What's in this picture?", vec![Media::from_path("photo.jpg")?]);
Image generation (feature image, which needs offgrid from git: stable-diffusion.cpp's sources
are too large for crates.io):
let mut images = ImageModel::load(&ImageModelParams {
diffusion_model: Some("z_image_turbo-Q4_K.gguf".into()),
text_encoder: Some("qwen3-4b.gguf".into()),
vae: Some("ae-f16.gguf".into()),
..Default::default()
})?;
let req = ImageRequest { prompt: "A lighthouse at dusk".into(), width: 768, height: 512, steps: Some(8), cfg_scale: Some(1.0), ..Default::default() };
let png = images.generate(&req, |progress| { println!("{progress:?}"); true })?.to_png();
The main entry points are ChatSession::complete_stream (content, reasoning and tool-call
events), run_tools (the tool loop), ChatSession::infill (code completion), Embedder::embed
and ImageModel::generate. Memory is set per model and session: ModelParams::n_cpu_moe (MoE
experts in RAM), SessionParams::cache_type (q8_0 halves the KV cache) and
SessionParams::cache_reuse (reuse cached text that moved up); the C ABI and Deno take the same
fields in their JSON params. See crates/offgrid/examples/, and
examples/tauri/ for a desktop chat app that embeds the crate.
C / C++ (and anything with a C FFI)
include/offgrid.h exposes 26 functions (including image generation: offgrid_image_model_load,
offgrid_image_generate returning PNG bytes). Requests and results are JSON in the OpenAI format,
so new features don't change the ABI.
char *err = NULL;
offgrid_model *m = offgrid_model_load("qwen3-4b.gguf", NULL, &err);
offgrid_chat *c = offgrid_chat_new(m, NULL, &err);
char *resp = offgrid_chat_complete(c,
"{\"messages\":[{\"role\":\"user\",\"content\":\"Hi!\"}],\"max_tokens\":100}",
on_token, NULL, &err); /* bool on_token(const char *piece, size_t len, void *user) */
/* ... */
offgrid_string_free(resp); offgrid_chat_free(c); offgrid_model_free(m);
Conventions:
- Fallible functions take a trailing
char **error_out. - Returned strings belong to the caller and are freed with
offgrid_string_free. - Panics never cross the FFI boundary.
offgrid_chat_cancelandoffgrid_chat_cancel_requestare safe to call from any thread.
ABI version: offgrid_abi_version() (currently 1). Examples are in examples/c/.
Deno
import { Offgrid, imagePart } from "jsr:@pinta365/offgrid";
using core = await Offgrid.load(); // $OFFGRID_LIB, the cache, or a one-time verified download of the release package
using model = await core.loadModel("qwen3-4b.gguf");
using chat = await model.createChat();
const res = await chat.complete(
{ messages: [{ role: "user", content: "Hi!" }] },
{ onToken: (t) => Deno.stdout.writeSync(new TextEncoder().encode(t)), signal: AbortSignal.timeout(30_000) },
);
Calls are nonblocking, so the event loop keeps running. The binding also offers:
- streaming through
onTokenandonReasoning, or as an async iterator withchat.stream() - the tool loop
chat.runTools(request, handlers) imagePart()andaudioPart()helpers- image generation:
core.loadImageModel(...), thenmodel.generate(request, { onProgress, signal })returns PNG bytes Disposablehandles that guard against freeing while a call is in flight
Offgrid.load() downloads this version's prebuilt package from the GitHub release on first use, checks its
SHA-256 and caches it; Offgrid.open() and OFFGRID_LIB never touch the network. See the
package README for the details and permissions. Examples are in examples/deno/.
HTTP (any language): offgrid-server
bin/offgrid-server --model qwen3-4b.gguf [--embedding-model embed.gguf] [--mmproj mmproj.gguf] \
[--fim-model qwen2.5-coder-1.5b.gguf] \
[--image-diffusion-model z_image_turbo.gguf --image-text-encoder qwen3-4b.gguf --image-vae ae.gguf] \
[--port 8080] [--parallel 2] [--ctx 8192] [--api-key KEY]
offgrid-server --help lists every option.
Point any OpenAI client at http://127.0.0.1:8080/v1. The server provides:
POST /v1/chat/completions, with or without SSE streaming, includingdelta.reasoning_contentanddelta.tool_callsPOST /v1/completions: a raw text prompt, or fill-in-the-middle whensuffixis setPOST /infill: llama.cpp's code-completion endpoint (input_prefix,input_suffix,input_extra,n_indent,t_max_predict_ms), so editor plugins such as llama.vscode workPOST /v1/embeddingsPOST /v1/images/generations(b64_json, plussteps,cfg_scale,seed,negative_promptandinit_image/strengthfor image-to-image)GET /v1/modelsandGET /health
Code completion uses --fim-model if given, else the chat model (which then needs FIM tokens);
a request can pick either by its model id. /infill requests with the same id_slot (one
editor) replace each other: a newer one cancels the running one and skips queued ones.
Options for memory and speed:
| Option | Default | |
|---|---|---|
--cache-type f16|q8_0|q4_0 |
f16 |
KV cache storage. q8_0 halves it (a 32k context for Qwen3-4B: 4.6 GB -> 2.4 GB) for 10-17% slower prompts and generation, with the same output in our tests; q4_0 quarters it but changes the output |
--cache-reuse N |
0 |
Shift cached chunks of at least N tokens into place when text before them was removed (an editor's window sliding down a file). Off as in llama-server; llama.vscode recommends 256 |
--n-cpu-moe N |
0 |
Keep the expert weights of the first N layers of a MoE model in RAM, attention on the GPU (llama.cpp's --n-cpu-moe). Unlike --gpu-layers, it stays fast at long contexts |
--batch N |
512 |
Prompt tokens per decode call. With --n-cpu-moe, 2048 more than doubles prompt speed |
--fim-ctx N |
--ctx |
A separate, usually smaller, context for the FIM model |
--exit-on-stdin-close |
off | Exit when stdin closes: an extension that keeps a pipe open takes the server down with it, even if it crashes |
Compatibility has been checked with the official openai npm SDK (scripts/openai-compat.ts).
The server binds to localhost by default; use --api-key before exposing it.
Tested models
Every model below was exercised end to end by the test suites on an RX 9070 XT (Vulkan).
| Model | Used for | Notes |
|---|---|---|
| Qwen3-4B-Instruct-2507 Q4_K_M | Chat, JSON schema, tools, server | Reference model; all tool-calling scenarios pass |
| Llama-3.2-3B-Instruct Q4_K_M | Llama 3 tool format | Formats calls correctly but judges poorly when to call tools (llama-server behaves the same) |
| Qwen3-0.6B Q8_0 | Reasoning streaming | Use temperature 0.6 in thinking mode; greedy decoding loops |
| Qwen3-Embedding-0.6B Q8_0 | Embeddings | |
| Qwen2.5-Coder-1.5B Q8_0 | Code completion (FIM) | Repo-level format with extra files; ~200 tokens/s on the RX 9070 XT |
| Qwen3.5 0.8B / 2B / 4B / 9B | Chat, tools (hybrid: context checkpoints) | 4/5 on an agent benchmark from 2B up (Qwen3 1.7B: 0/5) with a smaller KV cache than Qwen3: 3.9 GB for 2B with a 32k q8_0 context and a code model |
| Gemma 4 E4B / 12B Q4_K_M | Tools (Gemma 4 format), agent use | 4/5 on the agent benchmark, no bad calls for E4B; E4B ~92 tokens/s, 6.7 GB with a 32k q8_0 context and a code model |
| Qwen3.6-35B-A3B UD-Q4_K_M | Tools, agent use (hybrid MoE) | 22 GB: on a 16 GB GPU with --n-cpu-moe 28 --batch 2048, ~37 tokens/s at a 26k context; 5/5 on the agent benchmark |
| Qwen3-Coder-30B-A3B-Instruct Q4_K_M | Tools (Qwen3-Coder XML), agent use | 18.6 GB: on a 16 GB GPU with --n-cpu-moe 24 --batch 2048, ~35 tokens/s at a 26k context. Sometimes leaves out <tool_call> around a call; that is parsed too |
| Qwen2.5-VL-3B + mmproj | Vision (M-RoPE) | Colors, counting, OCR, JPEG, multiple images |
| Gemma 3 4B + mmproj | Vision, tools without template support | Template ignores tools; uses the system-message fallback |
| Qwen2.5-Omni-3B + mmproj | Audio and vision | Word-perfect transcription from WAV, MP3 and FLAC |
| Ultravox 0.5 (Llama 3.2 1B) + mmproj | Audio | Understands speech; unreliable at verbatim transcription |
| Z-Image-Turbo Q4_K + Qwen3-4B text encoder + VAE | Image generation | 8 steps, cfg_scale 1.0: 768×512 in ~5 s on the RX 9070 XT, 512×512 in ~2m45s on the CPU. Uses ~6.2 GB of GPU memory. Next to a chat model, vae_tiling keeps the weights resident between images; on small GPUs add text_encoder_on_cpu (saves 2.4 GB) or max_vram_gib |
Performance with Qwen3-4B Q4_K_M:
| Hardware | Prompt processing | Generation |
|---|---|---|
| RX 9070 XT (Vulkan) | ~5,000 tokens/s | ~150–175 tokens/s |
| Ryzen 7 9800X3D (CPU) | ~300 tokens/s | ~21 tokens/s |
Platforms and packaging
| Platform | Status | Package |
|---|---|---|
| Linux x86_64 | Tested | scripts/package-linux.sh → offgrid-<ver>-linux-x86_64.tar.gz (~38 MB) |
| Windows x86_64 | Tested on Windows 11: package (RTX 3060 Laptop via Vulkan, and CPU), native MSVC build with the full test suite | scripts/package-windows.sh → .zip (~45 MB) |
| macOS, ARM | Not attempted yet |
A package is a relocatable folder: lib/ or bin/ with liboffgrid, llama.cpp/ggml/mtmd,
stable-diffusion.cpp and the backends, plus include/offgrid.h and offgrid-server. Keep the folder together.
- Runs on any x86_64 CPU. It ships 14 CPU variants (from baseline x64 up to zen4 and sapphirerapids), and the best one for the machine is chosen at load time.
- The GPU is optional. Vulkan is a plugin module. Without a GPU, without a Vulkan driver, or with the module deleted, the library falls back to the CPU.
- Linux: glibc 2.28. That covers Ubuntu 20.04+, Debian 10+ and RHEL 8+. The build uses zig
(
cargo-zigbuild) with a static C++ runtime. The only runtime dependencies are glibc and libm, plus libvulkan for the GPU module.$ORIGINRPATHs make the folder relocatable. - Windows is built from Linux with llvm-mingw.
- It depends only on Windows system DLLs, plus
vulkan-1.dllfrom the GPU driver. offgrid.dlldelay-loads its dependencies from its own folder, so hosts such as Deno, Python or C# can load it by path from anywhere.- Import libraries are included for both MSVC and MinGW.
- AMD's switchable-graphics Vulkan layer, which hangs Vulkan start-up on laptops with an AMD
iGPU plus another GPU, is turned off for the process (
DISABLE_LAYER_AMD_SWITCHABLE_GRAPHICS_1).
- It depends only on Windows system DLLs, plus
scripts/check-portable.sh and scripts/check-windows.sh verify each package: dependencies
resolve from inside it, a relocated copy runs, and the CPU fallback works.
Pushing a tag that matches the crate version (v0.1.0) runs the release workflow: it builds and
checks both packages and creates a draft GitHub release with them attached.
Windows: unsigned binaries
The Windows binaries are not code-signed yet. Most machines run them without complaint, but Windows 11's Smart App Control blocks unsigned programs when it is turned on (the default on clean installs), with "part of this app has been blocked". It has no per-app exceptions: to run offgrid on such a machine, turn it off under Windows Security → App & browser control → Smart App Control settings. Since the April 2026 Windows update it can be turned back on later without reinstalling Windows. SmartScreen is not involved for packages you unzip yourself or that the VS Code extension unpacks.
Signing is planned. The SignPath Foundation's free certificate for open-source projects requires more public adoption than this young project has yet, so it's on hold until then; a paid certificate is the other route.
If and when releases are signed, this is how it will work:
- What will be signed: the Windows release packages (
offgrid-<version>-windows-x86_64.zipand.tar.gz):offgrid-server.exe,offgrid.dll, and the llama.cpp, ggml, mtmd and stable-diffusion.cpp DLLs next to them, each carrying version information for offgrid. Every file is built from this repository's tagged sources by the release workflow on GitHub Actions; llama.cpp and stable-diffusion.cpp are compiled from the pinned submodules, not taken as prebuilt binaries. - Team roles: committer, reviewer and approver of each signing request: Pinta365.
- Privacy: this program will not transfer any information to other networked systems unless
specifically requested by the user or the person installing or operating it. The library and
offgrid-servermake no outbound connections: models load from local files, images and audio are never fetched from URLs, and the server only answers requests on the address it is told to listen on (localhost by default). The only download in the project is the Deno binding'sOffgrid.load(), which fetches the release package from GitHub when called (Offgrid.open()never does).
Building from source
Requirements:
- Rust 1.88+
- cmake, ninja and a C/C++ compiler
- Vulkan headers and
glslc, for exampleomarchy pkg add cmake ninja vulkan-headers spirv-headers shadercon Arch/Omarchy
git submodule update --init
cargo build --release -p offgrid-ffi # liboffgrid.{so,a} (static llama.cpp, dev build)
cargo run --release -p offgrid --example chat -- model.gguf
Features:
--no-default-features: CPU only--features cuda: CUDA backend--features dynamic-backends: the portable runtime-loaded layout used by the packages--features image: image generation through stable-diffusion.cpp (onoffgrid,offgrid-ffiandoffgrid-server)
Cross-compiling for Windows needs llvm-mingw in
~/.local/share and rustup target add x86_64-pc-windows-gnullvm. The Linux package uses zig
(mise install zig@0.16.0) and cargo install cargo-zigbuild when they are available.
Building natively on Windows (MSVC) needs Visual Studio Build Tools with the C++ workload, CMake and the [Vulkan SDK](https://vul