Skip to main content

rig_llama_cpp/
lib.rs

1//! # rig-llama-cpp
2//!
3//! A [Rig](https://docs.rs/rig-core) provider that runs GGUF models locally
4//! via [llama.cpp](https://github.com/ggml-org/llama.cpp), with optional Vulkan GPU acceleration.
5//!
6//! A loaded model is a Rig [`Model`](rig_core::Model) — a completion wire bound to an
7//! in-process runtime — so any GGUF model can stand in for a cloud provider wherever Rig
8//! takes a model (`DynModel`, `rig_agent::AgentBuilder`, …). It supports:
9//!
10//! - **Completion and streaming** — both one-shot and token-by-token responses.
11//! - **Tool calling** — models with OpenAI-compatible chat templates can invoke tools.
12//! - **Reasoning / thinking** — extended thinking output is forwarded when the model supports it.
13//! - **Configurable sampling** — top-p, top-k, min-p, temperature, presence and repetition penalties.
14//! - **Embeddings** — generate text embeddings using GGUF embedding models.
15//!
16//! # Feature flags
17//!
18//! There is **no default GPU backend** — pick exactly the one that matches
19//! your hardware. With no feature enabled the build is CPU-only.
20//!
21//! GPU backends (forwarded to `llama-cpp-2`):
22//!
23//! - `vulkan` — cross-vendor GPU (recommended on Linux/Windows when CUDA/ROCm aren't set up).
24//! - `cuda` — NVIDIA GPUs with the CUDA toolkit installed.
25//! - `metal` — Apple Silicon / macOS.
26//! - `rocm` — AMD GPUs on Linux with the ROCm toolchain.
27//!
28//! Other:
29//!
30//! - `openmp` — OpenMP CPU threading; orthogonal to the GPU backends and may be combined with any of them.
31//! - `mtmd` — multimodal (vision) inference; required for `Client::from_gguf_with_mmproj` and `ClientBuilder::mmproj`.
32//!
33//! Examples:
34//!
35//! ```text
36//! cargo build --features vulkan
37//! cargo build --features cuda
38//! cargo build --features "vulkan,mtmd"
39//! ```
40//!
41//! Backend support depends on the corresponding `llama-cpp-2` feature and any required
42//! native toolchain or system libraries being available on the host machine.
43//!
44//! # Quick start
45//!
46//! Agents come from the [`rig-agent`](https://docs.rs/rig-agent) crate:
47//!
48//! ```rust,no_run
49//! use rig_agent::AgentBuilder;
50//!
51//! # #[tokio::main]
52//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
53//! let client = rig_llama_cpp::Client::builder("path/to/model.gguf")
54//!     .n_ctx(8192)
55//!     .build()?;
56//!
57//! let agent = AgentBuilder::new(client.completion_model("local"))
58//!     .preamble("You are a helpful assistant.")
59//!     .max_tokens(512)
60//!     .build();
61//!
62//! let response = agent.prompt("Hello!").await?;
63//! println!("{}", response.output());
64//! # Ok(())
65//! # }
66//! ```
67
68mod checkpoint;
69mod client;
70mod embedding;
71mod error;
72#[cfg(feature = "mtmd")]
73mod image;
74mod jinja;
75mod loader;
76mod parsing;
77mod prompt;
78mod request;
79mod sampling;
80mod slot;
81mod types;
82mod wire;
83mod worker;
84
85pub use client::{Client, ClientBuilder};
86pub use embedding::{EmbeddingClient, EmbeddingModelHandle, EmbeddingRuntime};
87pub use error::LoadError;
88pub use types::{
89    CheckpointParams, FitParams, Frame, KvCacheParams, KvCacheType, RawResponse, SamplingParams,
90};
91pub use wire::{CompletionWire, FrameDecoder, Model, RawDocument, Runtime};
92
93/// The provider name this crate's models report to Rig.
94pub(crate) const PROVIDER: &str = "llama.cpp";
95
96fn env_flag_enabled(name: &str) -> bool {
97    match std::env::var(name) {
98        Ok(value) => matches!(
99            value.trim().to_ascii_lowercase().as_str(),
100            "1" | "true" | "yes" | "on"
101        ),
102        Err(_) => false,
103    }
104}
105
106/// Whether to forward llama.cpp's *C-side* logging to stderr.
107///
108/// This only controls log lines that originate inside the `llama-cpp-2` /
109/// `llama-cpp-sys-2` C++ code (via `printf`-style writes that bypass Rust's
110/// `log` facade). Library-level diagnostics from `rig-llama-cpp` itself go
111/// through the [`log`] crate and are controlled by the consumer's logger
112/// configuration (e.g. `RUST_LOG=rig_llama_cpp=debug`), not this env var.
113fn llama_logs_enabled() -> bool {
114    env_flag_enabled("RIG_LLAMA_CPP_LOGS")
115}
116
117/// Process-wide [`LlamaBackend`] initialised on first use and shared by every
118/// worker (chat + embedding). The underlying llama.cpp backend is a global
119/// singleton — calling `LlamaBackend::init()` twice in the same process
120/// returns `BackendAlreadyInitialized`. Routing all callers through this
121/// helper means a chat client and an embedding client can coexist without
122/// racing on the C-side init flag.
123///
124/// Returns `Ok(&'static LlamaBackend)` once the backend is up; subsequent
125/// calls are cheap (single `OnceLock::get`). On platforms where init can
126/// fail (e.g. no Vulkan device) the error is sticky for the lifetime of
127/// the process — there's no recovering anyway.
128pub(crate) fn shared_backend() -> Result<&'static llama_cpp_2::llama_backend::LlamaBackend, String>
129{
130    use llama_cpp_2::llama_backend::LlamaBackend;
131    use std::sync::{Mutex, OnceLock};
132
133    static BACKEND: OnceLock<LlamaBackend> = OnceLock::new();
134    static INIT_LOCK: Mutex<()> = Mutex::new(());
135
136    if let Some(b) = BACKEND.get() {
137        return Ok(b);
138    }
139    // Serialise concurrent first-time initialisations. The C-side init flag
140    // is process-global so multiple threads racing on `LlamaBackend::init`
141    // will produce `BackendAlreadyInitialized` for the loser even though
142    // they all want the same handle.
143    let _guard = INIT_LOCK.lock().map_err(|e| e.to_string())?;
144    if let Some(b) = BACKEND.get() {
145        return Ok(b);
146    }
147
148    let mut backend = LlamaBackend::init().map_err(|e| format!("Backend init failed: {e}"))?;
149    if !llama_logs_enabled() {
150        backend.void_logs();
151        // NOTE: upstream llama-cpp-2 0.1.146 does not yet expose a way to
152        // silence mtmd's own log stream — when the `mtmd` feature is on,
153        // mmproj init may print to stderr. Track upstream for an mtmd
154        // log-silencing API and re-enable suppression here.
155    }
156    let _ = BACKEND.set(backend);
157    // INVARIANT: we hold `INIT_LOCK` for the duration of this function and
158    // just called `BACKEND.set(backend)`. Any concurrent caller that
159    // reached the second `BACKEND.get().is_some()` check above already
160    // returned, so reaching this line means we are the unique writer and
161    // `BACKEND` is now `Some`. Even if `set()` raced (`Err`-returning),
162    // the "loser" still observes the state filled by the winner — `get()`
163    // is guaranteed to return `Some`.
164    Ok(BACKEND.get().expect("BACKEND set above under INIT_LOCK"))
165}