Skip to main content

rig_llama_cpp/
client.rs

1use std::sync::Arc;
2use std::sync::atomic::{AtomicBool, Ordering};
3use std::thread;
4
5use tokio::sync::mpsc;
6
7use crate::error::LoadError;
8use crate::types::{
9    CheckpointParams, FitParams, InferenceCommand, KvCacheParams, ReloadRequest, SamplingParams,
10};
11use crate::wire::{CompletionWire, Model, Runtime};
12use crate::worker::{WorkerInit, inference_worker};
13
14/// Default context window used by [`ClientBuilder`] when `n_ctx` is not set.
15const DEFAULT_N_CTX: u32 = 4096;
16
17/// Capacity of the inference command channel. Bounded to apply backpressure
18/// to misbehaving callers (a flood of requests can't grow the worker's queue
19/// without limit). Eight is generous for a single-worker llama.cpp client —
20/// generation is the bottleneck, not enqueueing — and leaves headroom for
21/// `Reload` / `Shutdown` to slip in alongside in-flight `Request`s.
22const COMMAND_CHANNEL_CAPACITY: usize = 8;
23
24/// Builder for [`Client`].
25///
26/// Construct one with [`Client::builder`], then chain optional setters and
27/// finish with [`ClientBuilder::build`]. Every field except `model_path`
28/// has a sensible default, so the minimal usage is:
29///
30/// ```rust,no_run
31/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
32/// let client = rig_llama_cpp::Client::builder("path/to/model.gguf").build()?;
33/// # let _ = client;
34/// # Ok(())
35/// # }
36/// ```
37///
38/// The builder shape is forward-compatible: new optional knobs can be added
39/// without breaking existing call sites.
40#[must_use]
41pub struct ClientBuilder {
42    model_path: String,
43    #[cfg(feature = "mtmd")]
44    mmproj_path: Option<String>,
45    n_ctx: u32,
46    sampling: SamplingParams,
47    fit: FitParams,
48    kv_cache: KvCacheParams,
49    checkpoint: CheckpointParams,
50}
51
52impl ClientBuilder {
53    fn new(model_path: impl Into<String>) -> Self {
54        Self {
55            model_path: model_path.into(),
56            #[cfg(feature = "mtmd")]
57            mmproj_path: None,
58            n_ctx: DEFAULT_N_CTX,
59            sampling: SamplingParams::default(),
60            fit: FitParams::default(),
61            kv_cache: KvCacheParams::default(),
62            checkpoint: CheckpointParams::default(),
63        }
64    }
65
66    /// Desired context window size in tokens. Defaults to `4096`.
67    pub fn n_ctx(mut self, n_ctx: u32) -> Self {
68        self.n_ctx = n_ctx;
69        self
70    }
71
72    /// Token sampling parameters.
73    pub fn sampling(mut self, sampling: SamplingParams) -> Self {
74        self.sampling = sampling;
75        self
76    }
77
78    /// Automatic-fit parameters (per-device memory margins, minimum context).
79    pub fn fit(mut self, fit: FitParams) -> Self {
80        self.fit = fit;
81        self
82    }
83
84    /// KV cache data-type configuration. Defaults to F16 / F16.
85    pub fn kv_cache(mut self, kv_cache: KvCacheParams) -> Self {
86        self.kv_cache = kv_cache;
87        self
88    }
89
90    /// In-memory state-checkpoint cache tunables (used by hybrid/recurrent
91    /// models to preserve KV state across turns).
92    pub fn checkpoints(mut self, checkpoint: CheckpointParams) -> Self {
93        self.checkpoint = checkpoint;
94        self
95    }
96
97    /// Path to a multimodal projector (`mmproj`) GGUF file. Setting this
98    /// switches the resulting [`Client`] into vision mode. Only available
99    /// when the `mtmd` feature is enabled.
100    #[cfg(feature = "mtmd")]
101    pub fn mmproj(mut self, mmproj_path: impl Into<String>) -> Self {
102        self.mmproj_path = Some(mmproj_path.into());
103        self
104    }
105
106    /// Spawn the inference worker thread, load the model, and return a
107    /// ready-to-use [`Client`].
108    ///
109    /// # Errors
110    ///
111    /// Returns a [`LoadError`] if the backend fails to initialise, automatic
112    /// fitting fails, the GGUF file cannot be loaded, or — when `mmproj` was
113    /// set — the multimodal projector cannot be initialised.
114    pub fn build(self) -> Result<Client, LoadError> {
115        #[cfg(feature = "mtmd")]
116        let mmproj_path = self.mmproj_path;
117        #[cfg(not(feature = "mtmd"))]
118        let mmproj_path: Option<String> = None;
119
120        Client::spawn(
121            self.model_path,
122            mmproj_path,
123            self.n_ctx,
124            self.sampling,
125            self.fit,
126            self.kv_cache,
127            self.checkpoint,
128        )
129    }
130}
131
132/// The llama.cpp completion client.
133///
134/// `Client` loads a GGUF model on a dedicated inference thread and exposes it
135/// to Rig as a completion [`Model`] (see [`Client::completion_model`]).
136/// Construct one with
137/// [`Client::builder`], or — for backward-compatible positional construction —
138/// [`Client::from_gguf`].
139///
140/// # Lifecycle
141///
142/// The worker thread owns the `LlamaModel`, `LlamaContext`, and (when the
143/// `mtmd` feature is on) the multimodal projector. It only releases that
144/// memory when it exits, which happens in two cases:
145///
146/// - On [`Client::reload`], the worker drops the old model and loads the new
147///   one in place — the `Client` itself is **not** dropped, and the worker
148///   thread is reused. Caller blocks on the reload result.
149/// - On [`Client::drop`], the worker thread is signalled and joined. See
150///   [`impl Drop for Client`](Client#impl-Drop-for-Client) for the exact
151///   semantics — including how a long in-flight generation is cancelled so
152///   the dropping thread doesn't have to wait for it to finish naturally.
153pub struct Client {
154    request_tx: mpsc::Sender<InferenceCommand>,
155    /// Shared shutdown flag. Set by [`Client::drop`] so the worker's prompt
156    /// prefill and sampling loops short-circuit at their next polling point.
157    /// Cloned into the worker via [`WorkerInit::cancel`].
158    cancel: Arc<AtomicBool>,
159    sampling_params: std::sync::RwLock<SamplingParams>,
160    worker_handle: Option<thread::JoinHandle<()>>,
161}
162
163impl Client {
164    /// Start a [`ClientBuilder`] for a GGUF model at `model_path`.
165    pub fn builder(model_path: impl Into<String>) -> ClientBuilder {
166        ClientBuilder::new(model_path)
167    }
168
169    /// Load a GGUF model with automatic GPU/CPU layer fitting and start the inference worker thread.
170    ///
171    /// llama.cpp will probe available device memory and determine the optimal layer
172    /// distribution automatically.
173    ///
174    /// Prefer [`Client::builder`] for new code — this constructor is kept for
175    /// backward compatibility with the positional 0.1.x API and forwards
176    /// directly to the builder.
177    ///
178    /// # Arguments
179    ///
180    /// * `model_path` — Path to a `.gguf` model file.
181    /// * `n_ctx` — Desired context window size in tokens.
182    /// * `sampling_params` — Sampling parameters for token generation.
183    /// * `fit_params` — Configuration for the fitting algorithm.
184    /// * `kv_cache_params` — KV cache data-type configuration (defaults to F16/F16).
185    /// * `checkpoint_params` — Tunables for the in-memory state-checkpoint cache
186    ///   used to preserve KV/recurrent state across chat turns for hybrid models.
187    ///
188    /// # Errors
189    ///
190    /// Returns a [`LoadError`] if the backend fails to initialise, automatic
191    /// fitting fails, or the model cannot be loaded.
192    pub fn from_gguf(
193        model_path: impl Into<String>,
194        n_ctx: u32,
195        sampling_params: SamplingParams,
196        fit_params: FitParams,
197        kv_cache_params: KvCacheParams,
198        checkpoint_params: CheckpointParams,
199    ) -> Result<Self, LoadError> {
200        Self::spawn(
201            model_path.into(),
202            None,
203            n_ctx,
204            sampling_params,
205            fit_params,
206            kv_cache_params,
207            checkpoint_params,
208        )
209    }
210
211    /// Load a GGUF vision model with a multimodal projector and automatic GPU/CPU layer fitting.
212    ///
213    /// This constructor enables multimodal (vision) inference. The `mmproj_path` should point
214    /// to a GGUF multimodal projector file (mmproj) that corresponds to the vision model.
215    ///
216    /// Prefer [`Client::builder`] with [`ClientBuilder::mmproj`] for new code.
217    ///
218    /// # Arguments
219    ///
220    /// * `model_path` — Path to a `.gguf` vision model file.
221    /// * `mmproj_path` — Path to the corresponding multimodal projector `.gguf` file.
222    /// * `n_ctx` — Desired context window size in tokens.
223    /// * `sampling_params` — Sampling parameters for token generation.
224    /// * `fit_params` — Configuration for the fitting algorithm.
225    /// * `kv_cache_params` — KV cache data-type configuration (defaults to F16/F16).
226    ///
227    /// # Errors
228    ///
229    /// Returns a [`LoadError`] if the backend fails to initialise, the model
230    /// cannot be loaded, or the multimodal projector cannot be initialised.
231    #[cfg(feature = "mtmd")]
232    pub fn from_gguf_with_mmproj(
233        model_path: impl Into<String>,
234        mmproj_path: impl Into<String>,
235        n_ctx: u32,
236        sampling_params: SamplingParams,
237        fit_params: FitParams,
238        kv_cache_params: KvCacheParams,
239        checkpoint_params: CheckpointParams,
240    ) -> Result<Self, LoadError> {
241        Self::spawn(
242            model_path.into(),
243            Some(mmproj_path.into()),
244            n_ctx,
245            sampling_params,
246            fit_params,
247            kv_cache_params,
248            checkpoint_params,
249        )
250    }
251
252    /// Shared spawn path used by the builder and by the positional constructors.
253    /// `mmproj_path` is only consulted when the `mtmd` feature is enabled; with
254    /// the feature off, callers always pass `None` and the worker thread
255    /// silently ignores any value.
256    fn spawn(
257        model_path: String,
258        mmproj_path: Option<String>,
259        n_ctx: u32,
260        sampling_params: SamplingParams,
261        fit_params: FitParams,
262        kv_cache_params: KvCacheParams,
263        checkpoint_params: CheckpointParams,
264    ) -> Result<Self, LoadError> {
265        let (request_tx, mut request_rx) =
266            mpsc::channel::<InferenceCommand>(COMMAND_CHANNEL_CAPACITY);
267        let (init_tx, init_rx) = std::sync::mpsc::channel::<Result<(), LoadError>>();
268        let cancel = Arc::new(AtomicBool::new(false));
269        let worker_cancel = Arc::clone(&cancel);
270
271        let worker_handle = thread::spawn(move || {
272            let init = WorkerInit {
273                model_path: &model_path,
274                mmproj_path: mmproj_path.as_deref(),
275                n_ctx,
276                fit_params: &fit_params,
277                kv_cache_params: &kv_cache_params,
278                checkpoint_params,
279                cancel: worker_cancel,
280            };
281            inference_worker(init, init_tx, &mut request_rx);
282        });
283
284        init_rx
285            .recv()
286            .map_err(|_| LoadError::WorkerInitDisconnected)??;
287
288        Ok(Self {
289            request_tx,
290            cancel,
291            sampling_params: std::sync::RwLock::new(sampling_params),
292            worker_handle: Some(worker_handle),
293        })
294    }
295
296    /// A Rig completion model backed by this client's loaded model.
297    ///
298    /// `model` is the id the model reports to Rig (in telemetry and in the
299    /// origin of the turns it produces); it does not select a file. The
300    /// handle snapshots the client's current [`SamplingParams`], so take a
301    /// fresh one after [`Client::reload`] changes them.
302    ///
303    /// ```rust,no_run
304    /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
305    /// let client = rig_llama_cpp::Client::builder("path/to/model.gguf").build()?;
306    /// let model = client.completion_model("local");
307    /// let response = model.call("Hello!").await?;
308    /// println!("{:?}", response.choice);
309    /// # Ok(())
310    /// # }
311    /// ```
312    pub fn completion_model(&self, model: impl Into<String>) -> Model {
313        // See the matching `unwrap_or_else` in `reload`: SamplingParams is
314        // `Copy`, so a poisoned lock still holds valid data.
315        let sampling = *self
316            .sampling_params
317            .read()
318            .unwrap_or_else(|p| p.into_inner());
319        rig_core::Model::new(
320            CompletionWire::new(model),
321            Runtime::new(self.request_tx.clone(), sampling),
322        )
323    }
324
325    /// Reload the worker thread with a new model without destroying the backend.
326    ///
327    /// This swaps the model in-place on the existing inference thread, avoiding the
328    /// `LlamaBackend` singleton re-initialization race that occurs when dropping and
329    /// recreating a `Client`.
330    ///
331    /// # Errors
332    ///
333    /// Returns [`LoadError::WorkerNotRunning`] if the inference worker is no
334    /// longer accepting commands, or any of the load-stage variants if the
335    /// new model fails to come up.
336    // The positional signature is part of the 0.1.x public API. A future minor
337    // release can introduce a `ReloadOptions`/`reload_builder` shape; until
338    // then, the eight params (self + 7 fields) intentionally stay positional.
339    #[allow(clippy::too_many_arguments)]
340    pub fn reload(
341        &self,
342        model_path: String,
343        mmproj_path: Option<String>,
344        n_ctx: u32,
345        sampling: SamplingParams,
346        fit_params: FitParams,
347        kv_cache_params: KvCacheParams,
348        checkpoint_params: CheckpointParams,
349    ) -> Result<(), LoadError> {
350        let (result_tx, result_rx) = std::sync::mpsc::channel();
351        // `blocking_send` is the right call here: `reload` is a sync API and
352        // is documented to be invoked from a `spawn_blocking` task (or any
353        // non-async thread) when used from a tokio context. Backpressure on a
354        // full command queue is fine — reload is itself a blocking operation.
355        self.request_tx
356            .blocking_send(InferenceCommand::Reload(ReloadRequest {
357                model_path,
358                mmproj_path,
359                n_ctx,
360                fit_params,
361                kv_cache_params,
362                checkpoint_params,
363                result_tx,
364            }))
365            .map_err(|_| LoadError::WorkerNotRunning)?;
366        let result = result_rx
367            .recv()
368            .map_err(|_| LoadError::WorkerInitDisconnected)?;
369        if result.is_ok() {
370            // SamplingParams is `Copy` (just numeric scalars) — a poisoned
371            // lock can't represent torn or invalid data, so recover the
372            // guard rather than propagate a panic.
373            let mut guard = self
374                .sampling_params
375                .write()
376                .unwrap_or_else(|p| p.into_inner());
377            *guard = sampling;
378        }
379        result
380    }
381}
382
383impl Drop for Client {
384    /// Tear down the worker thread synchronously.
385    ///
386    /// `Drop` blocks until the worker thread has fully exited and the
387    /// `LlamaModel` / `LlamaContext` (and `LlamaBackend` device handles, plus
388    /// the multimodal projector when the `mtmd` feature is on) are released.
389    /// This is intentional: the caller almost always wants to allocate a
390    /// replacement `Client` immediately after dropping this one, and a
391    /// non-blocking drop would briefly hold 2× the model's RAM/VRAM and risk
392    /// OOM. [`Client::reload`] reuses the same worker and avoids this whole
393    /// path; prefer it over drop-and-recreate when you can.
394    ///
395    /// To keep the wait short even when a long generation is mid-flight,
396    /// `Drop` flips the shared cancel flag before signalling shutdown. The
397    /// worker polls the flag at every prompt-prefill chunk boundary and
398    /// every sampled token, so an in-flight `Request` returns within a
399    /// single decode step. The pessimal wait is therefore one decode step,
400    /// not the rest of the generation.
401    ///
402    /// `try_send(Shutdown)` is best-effort: if the bounded command queue is
403    /// full at this instant, the `Shutdown` command isn't enqueued — but the
404    /// in-flight request still bails on the cancel flag, and the worker's
405    /// per-iteration cancel check at the top of its command loop also exits
406    /// the thread before pulling more queued commands.
407    ///
408    /// `Model` clones outliving the `Client` keep the channel sender count
409    /// above zero; their `send` calls naturally fail with `SendError` once
410    /// the receiver is dropped on worker exit, so they don't prevent
411    /// shutdown.
412    fn drop(&mut self) {
413        self.cancel.store(true, Ordering::Relaxed);
414        let _ = self.request_tx.try_send(InferenceCommand::Shutdown);
415
416        if let Some(worker_handle) = self.worker_handle.take() {
417            let _ = worker_handle.join();
418        }
419    }
420}