Skip to main content

llama_cpp_2/
model.rs

1//! A safe wrapper around `llama_model`.
2use std::ffi::{c_char, CStr, CString};
3use std::num::NonZeroU16;
4use std::os::raw::c_int;
5use std::path::Path;
6use std::ptr::{self, NonNull};
7use std::slice;
8use std::str::Utf8Error;
9
10use crate::context::params::LlamaContextParams;
11use crate::context::LlamaContext;
12use crate::llama_backend::LlamaBackend;
13use crate::model::params::LlamaModelParams;
14use crate::sampling::LlamaSampler;
15use crate::token::LlamaToken;
16use crate::token_type::{LlamaTokenAttr, LlamaTokenAttrs};
17use crate::{
18    ApplyChatTemplateError, ChatTemplateError, LlamaContextLoadError, LlamaLoraAdapterInitError,
19    LlamaModelLoadError, MetaValError, NewLlamaChatMessageError, StringToTokenError,
20    TokenToStringError,
21};
22
23pub mod params;
24
25/// A safe wrapper around `llama_model`.
26#[derive(Debug)]
27#[repr(transparent)]
28#[allow(clippy::module_name_repetitions)]
29pub struct LlamaModel {
30    pub(crate) model: NonNull<llama_cpp_sys_2::llama_model>,
31}
32
33/// A safe wrapper around `llama_lora_adapter`.
34#[derive(Debug)]
35#[repr(transparent)]
36#[allow(clippy::module_name_repetitions)]
37pub struct LlamaLoraAdapter {
38    pub(crate) lora_adapter: NonNull<llama_cpp_sys_2::llama_adapter_lora>,
39}
40
41/// A performance-friendly wrapper around [`LlamaModel::chat_template`] which is then
42/// fed into [`LlamaModel::apply_chat_template`] to convert a list of messages into an LLM
43/// prompt. Internally the template is stored as a `CString` to avoid round-trip conversions
44/// within the FFI.
45#[derive(Eq, PartialEq, Clone, PartialOrd, Ord, Hash)]
46pub struct LlamaChatTemplate(CString);
47
48impl LlamaChatTemplate {
49    /// Create a new template from a string. This can either be the name of a llama.cpp [chat template](https://github.com/ggerganov/llama.cpp/blob/8a8c4ceb6050bd9392609114ca56ae6d26f5b8f5/src/llama-chat.cpp#L27-L61)
50    /// like "chatml" or "llama3" or an actual Jinja template for llama.cpp to interpret.
51    pub fn new(template: &str) -> Result<Self, std::ffi::NulError> {
52        Ok(Self(CString::new(template)?))
53    }
54
55    /// Accesses the template as a c string reference.
56    pub fn as_c_str(&self) -> &CStr {
57        &self.0
58    }
59
60    /// Attempts to convert the `CString` into a Rust str reference.
61    pub fn to_str(&self) -> Result<&str, Utf8Error> {
62        self.0.to_str()
63    }
64
65    /// Convenience method to create an owned String.
66    pub fn to_string(&self) -> Result<String, Utf8Error> {
67        self.to_str().map(str::to_string)
68    }
69}
70
71impl std::fmt::Debug for LlamaChatTemplate {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        self.0.fmt(f)
74    }
75}
76
77/// A Safe wrapper around `llama_chat_message`
78#[derive(Debug, Eq, PartialEq, Clone)]
79pub struct LlamaChatMessage {
80    role: CString,
81    content: CString,
82}
83
84impl LlamaChatMessage {
85    /// Create a new `LlamaChatMessage`
86    ///
87    /// # Errors
88    /// If either of ``role`` or ``content`` contain null bytes.
89    pub fn new(role: String, content: String) -> Result<Self, NewLlamaChatMessageError> {
90        Ok(Self {
91            role: CString::new(role)?,
92            content: CString::new(content)?,
93        })
94    }
95}
96
97/// The Rope type that's used within the model.
98#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99pub enum RopeType {
100    Norm,
101    NeoX,
102    MRope,
103    Vision,
104}
105
106/// How to determine if we should prepend a bos token to tokens
107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108pub enum AddBos {
109    /// Add the beginning of stream token to the start of the string.
110    Always,
111    /// Do not add the beginning of stream token to the start of the string.
112    Never,
113}
114
115/// How to determine if we should tokenize special tokens
116#[deprecated(
117    since = "0.1.0",
118    note = "This enum is a mixture of options for llama cpp providing less flexibility it only used with deprecated methods and will be removed in the future."
119)]
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub enum Special {
122    /// Allow tokenizing special and/or control tokens which otherwise are not exposed and treated as plaintext. Does not insert a leading space.
123    Tokenize,
124    /// Treat special and/or control tokens as plaintext.
125    Plaintext,
126}
127
128unsafe impl Send for LlamaModel {}
129
130unsafe impl Sync for LlamaModel {}
131
132impl LlamaModel {
133    pub(crate) fn vocab_ptr(&self) -> *const llama_cpp_sys_2::llama_vocab {
134        unsafe { llama_cpp_sys_2::llama_model_get_vocab(self.model.as_ptr()) }
135    }
136
137    /// get the number of tokens the model was trained on
138    ///
139    /// # Panics
140    ///
141    /// If the number of tokens the model was trained on does not fit into an `u32`. This should be impossible on most
142    /// platforms due to llama.cpp returning a `c_int` (i32 on most platforms) which is almost certainly positive.
143    #[must_use]
144    pub fn n_ctx_train(&self) -> u32 {
145        let n_ctx_train = unsafe { llama_cpp_sys_2::llama_n_ctx_train(self.model.as_ptr()) };
146        u32::try_from(n_ctx_train).expect("n_ctx_train fits into an u32")
147    }
148
149    /// Get all tokens in the model.
150    pub fn tokens(
151        &self,
152        decode_special: bool,
153    ) -> impl Iterator<Item = (LlamaToken, Result<String, TokenToStringError>)> + '_ {
154        (0..self.n_vocab())
155            .map(LlamaToken::new)
156            .map(move |llama_token| {
157                let mut decoder = encoding_rs::UTF_8.new_decoder();
158                (
159                    llama_token,
160                    self.token_to_piece(llama_token, &mut decoder, decode_special, None),
161                )
162            })
163    }
164
165    /// Get the beginning of stream token.
166    #[must_use]
167    pub fn token_bos(&self) -> LlamaToken {
168        let token = unsafe { llama_cpp_sys_2::llama_token_bos(self.vocab_ptr()) };
169        LlamaToken(token)
170    }
171
172    /// Get the end of stream token.
173    #[must_use]
174    pub fn token_eos(&self) -> LlamaToken {
175        let token = unsafe { llama_cpp_sys_2::llama_token_eos(self.vocab_ptr()) };
176        LlamaToken(token)
177    }
178
179    /// Get the newline token.
180    #[must_use]
181    pub fn token_nl(&self) -> LlamaToken {
182        let token = unsafe { llama_cpp_sys_2::llama_token_nl(self.vocab_ptr()) };
183        LlamaToken(token)
184    }
185
186    /// Check if a token represents the end of generation (end of turn, end of sequence, etc.)
187    #[must_use]
188    pub fn is_eog_token(&self, token: LlamaToken) -> bool {
189        unsafe { llama_cpp_sys_2::llama_token_is_eog(self.vocab_ptr(), token.0) }
190    }
191
192    /// Get the decoder start token.
193    #[must_use]
194    pub fn decode_start_token(&self) -> LlamaToken {
195        let token =
196            unsafe { llama_cpp_sys_2::llama_model_decoder_start_token(self.model.as_ptr()) };
197        LlamaToken(token)
198    }
199
200    /// Get the separator token (SEP).
201    #[must_use]
202    pub fn token_sep(&self) -> LlamaToken {
203        let token = unsafe { llama_cpp_sys_2::llama_vocab_sep(self.vocab_ptr()) };
204        LlamaToken(token)
205    }
206
207    /// Convert single token to a string.
208    ///
209    /// # Errors
210    ///
211    /// See [`TokenToStringError`] for more information.
212    #[deprecated(since = "0.1.0", note = "Use `token_to_piece` instead")]
213    pub fn token_to_str(
214        &self,
215        token: LlamaToken,
216        special: Special,
217    ) -> Result<String, TokenToStringError> {
218        // TODO lsptrip None is acutally not quite the origignal behavior of this function,
219        let mut decoder = encoding_rs::UTF_8.new_decoder();
220        self.token_to_piece(
221            token,
222            &mut decoder,
223            matches!(special, Special::Tokenize),
224            None,
225        )
226    }
227
228    /// Convert single token to bytes.
229    ///
230    /// # Errors
231    /// See [`TokenToStringError`] for more information.
232    ///
233    /// # Panics
234    /// If a [`TokenToStringError::InsufficientBufferSpace`] error returned by
235    /// [`Self::token_to_bytes_with_size`] contains a positive nonzero value. This should never
236    /// happen.
237    #[deprecated(since = "0.1.0", note = "Use `token_to_piece_bytes` instead")]
238    pub fn token_to_bytes(
239        &self,
240        token: LlamaToken,
241        special: Special,
242    ) -> Result<Vec<u8>, TokenToStringError> {
243        // TODO lsptrip None is acutally not quite the origignal behavior of this function,
244        match self.token_to_piece_bytes(token, 8, matches!(special, Special::Tokenize), None) {
245            Err(TokenToStringError::InsufficientBufferSpace(i)) => self.token_to_piece_bytes(
246                token,
247                (-i).try_into().expect("Error buffer size is positive"),
248                matches!(special, Special::Tokenize),
249                None,
250            ),
251            x => x,
252        }
253    }
254
255    /// Convert a vector of tokens to a single string.
256    ///
257    /// # Errors
258    ///
259    /// See [`TokenToStringError`] for more information.
260    #[deprecated(
261        since = "0.1.0",
262        note = "Use `token_to_piece` for each token individually instead"
263    )]
264    pub fn tokens_to_str(
265        &self,
266        tokens: &[LlamaToken],
267        special: Special,
268    ) -> Result<String, TokenToStringError> {
269        let mut builder: Vec<u8> = Vec::with_capacity(tokens.len() * 4);
270        for piece in tokens
271            .iter()
272            .copied()
273            .map(|t| self.token_to_piece_bytes(t, 8, matches!(special, Special::Tokenize), None))
274        {
275            builder.extend_from_slice(&piece?);
276        }
277        Ok(String::from_utf8(builder)?)
278    }
279
280    /// Convert a string to a Vector of tokens.
281    ///
282    /// # Errors
283    ///
284    /// - if [`str`] contains a null byte.
285    ///
286    /// # Panics
287    ///
288    /// - if there is more than [`usize::MAX`] [`LlamaToken`]s in [`str`].
289    ///
290    ///
291    /// ```no_run
292    /// use llama_cpp_2::model::LlamaModel;
293    ///
294    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
295    /// use std::path::Path;
296    /// use llama_cpp_2::model::AddBos;
297    /// let backend = llama_cpp_2::llama_backend::LlamaBackend::init()?;
298    /// let model = LlamaModel::load_from_file(&backend, Path::new("path/to/model"), &Default::default())?;
299    /// let tokens = model.str_to_token("Hello, World!", AddBos::Always)?;
300    /// # Ok(())
301    /// # }
302    pub fn str_to_token(
303        &self,
304        str: &str,
305        add_bos: AddBos,
306    ) -> Result<Vec<LlamaToken>, StringToTokenError> {
307        let add_bos = match add_bos {
308            AddBos::Always => true,
309            AddBos::Never => false,
310        };
311
312        let tokens_estimation = std::cmp::max(8, (str.len() / 2) + usize::from(add_bos));
313        let mut buffer: Vec<LlamaToken> = Vec::with_capacity(tokens_estimation);
314
315        let c_string = CString::new(str)?;
316        let buffer_capacity =
317            c_int::try_from(buffer.capacity()).expect("buffer capacity should fit into a c_int");
318
319        let size = unsafe {
320            llama_cpp_sys_2::llama_tokenize(
321                self.vocab_ptr(),
322                c_string.as_ptr(),
323                c_int::try_from(c_string.as_bytes().len())?,
324                buffer.as_mut_ptr().cast::<llama_cpp_sys_2::llama_token>(),
325                buffer_capacity,
326                add_bos,
327                true,
328            )
329        };
330
331        // if we fail the first time we can resize the vector to the correct size and try again. This should never fail.
332        // as a result - size is guaranteed to be positive here.
333        let size = if size.is_negative() {
334            buffer.reserve_exact(usize::try_from(-size).expect("usize's are larger "));
335            unsafe {
336                llama_cpp_sys_2::llama_tokenize(
337                    self.vocab_ptr(),
338                    c_string.as_ptr(),
339                    c_int::try_from(c_string.as_bytes().len())?,
340                    buffer.as_mut_ptr().cast::<llama_cpp_sys_2::llama_token>(),
341                    -size,
342                    add_bos,
343                    true,
344                )
345            }
346        } else {
347            size
348        };
349
350        let size = usize::try_from(size).expect("size is positive and usize ");
351
352        // Safety: `size` < `capacity` and llama-cpp has initialized elements up to `size`
353        unsafe { buffer.set_len(size) }
354        Ok(buffer)
355    }
356
357    /// Get the type of a token.
358    ///
359    /// # Panics
360    ///
361    /// If the token type is not known to this library.
362    #[must_use]
363    pub fn token_attr(&self, LlamaToken(id): LlamaToken) -> LlamaTokenAttrs {
364        let token_type = unsafe { llama_cpp_sys_2::llama_token_get_attr(self.vocab_ptr(), id) };
365        LlamaTokenAttrs::try_from(token_type).expect("token type is valid")
366    }
367
368    /// Convert a token to a string using the underlying llama.cpp `llama_token_to_piece` function.
369    ///
370    /// This is the new default function for token decoding and provides direct access to
371    /// the llama.cpp token decoding functionality without any special logic or filtering.
372    ///
373    /// Decoding raw string requires using an decoder, tokens from language models may not always map
374    /// to full characters depending on the encoding so stateful decoding is required, otherwise partial strings may be lost!
375    /// Invalid characters are mapped to REPLACEMENT CHARACTER making the method safe to use even if the model inherently produces
376    /// garbage.
377    ///
378    /// # Errors
379    ///
380    /// - if the token type is unknown
381    ///
382    /// # Panics
383    ///
384    /// - if the returned size from llama-cpp does not fit into a [`usize`]. (this should never happen)
385    pub fn token_to_piece(
386        &self,
387        token: LlamaToken,
388        decoder: &mut encoding_rs::Decoder,
389        special: bool,
390        lstrip: Option<NonZeroU16>,
391    ) -> Result<String, TokenToStringError> {
392        let bytes = match self.token_to_piece_bytes(token, 8, special, lstrip) {
393            // when there is insufficient space `token_to_piece` will return a negative number with the size that would have been returned
394            // https://github.com/abetlen/llama-cpp-python/blob/c37132bac860fcc333255c36313f89c4f49d4c8d/llama_cpp/llama_cpp.py#L3461
395            Err(TokenToStringError::InsufficientBufferSpace(i)) => self.token_to_piece_bytes(
396                token,
397                (-i).try_into().expect("Error buffer size is positive"),
398                special,
399                lstrip,
400            ),
401            x => x,
402        }?;
403        // here the assumption is that each byte from the output may map to at most one output charakter
404        let mut output_piece = String::with_capacity(bytes.len());
405        // _result only tells if there is nothing more in the input, or if the output was full
406        // but further decoding will happen on the next interation anyway
407        let (_result, _somesize, _truthy) =
408            decoder.decode_to_string(&bytes, &mut output_piece, false);
409        Ok(output_piece)
410    }
411
412    /// Raw token decoding to bytes, use if you want to handle the decoding model output yourself
413    ///
414    /// Convert a token to bytes using the underlying llama.cpp `llama_token_to_piece` function. This is mostly
415    /// a thin wrapper around `llama_token_to_piece` function, that handles rust <-> c type conversions while
416    /// letting the caller handle errors. For a safer inteface returing rust strings directly use `token_to_piece` instead!
417    ///
418    /// # Errors
419    ///
420    /// - if the token type is unknown
421    /// - the resultant token is larger than `buffer_size`.
422    ///
423    /// # Panics
424    ///
425    /// - if `buffer_size` does not fit into a [`c_int`].
426    /// - if the returned size from llama-cpp does not fit into a [`usize`]. (this should never happen)
427    pub fn token_to_piece_bytes(
428        &self,
429        token: LlamaToken,
430        buffer_size: usize,
431        special: bool,
432        lstrip: Option<NonZeroU16>,
433    ) -> Result<Vec<u8>, TokenToStringError> {
434        let string = CString::new(vec![b'*'; buffer_size]).expect("no null");
435        let len = string.as_bytes().len();
436        let len = c_int::try_from(len).expect("length fits into c_int");
437        let buf = string.into_raw();
438        let lstrip = lstrip.map_or(0, |it| i32::from(it.get()));
439        let size = unsafe {
440            llama_cpp_sys_2::llama_token_to_piece(
441                self.vocab_ptr(),
442                token.0,
443                buf,
444                len,
445                lstrip,
446                special,
447            )
448        };
449
450        match size {
451            0 => Err(TokenToStringError::UnknownTokenType),
452            i if i.is_negative() => Err(TokenToStringError::InsufficientBufferSpace(i)),
453            size => {
454                let string = unsafe { CString::from_raw(buf) };
455                let mut bytes = string.into_bytes();
456                let len = usize::try_from(size).expect("size is positive and fits into usize");
457                bytes.truncate(len);
458                Ok(bytes)
459            }
460        }
461    }
462
463    /// Convert a token to a string with a specified buffer size.
464    ///
465    /// Generally you should use [`LlamaModel::token_to_str`] as it is able to decode tokens with
466    /// any length.
467    ///
468    /// # Errors
469    ///
470    /// - if the token type is unknown
471    /// - the resultant token is larger than `buffer_size`.
472    /// - the string returend by llama-cpp is not valid utf8.
473    ///
474    /// # Panics
475    ///
476    /// - if `buffer_size` does not fit into a [`c_int`].
477    /// - if the returned size from llama-cpp does not fit into a [`usize`]. (this should never happen)
478    #[deprecated(since = "0.1.0", note = "Use `token_to_piece` instead")]
479    pub fn token_to_str_with_size(
480        &self,
481        token: LlamaToken,
482        buffer_size: usize,
483        special: Special,
484    ) -> Result<String, TokenToStringError> {
485        let bytes = self.token_to_piece_bytes(
486            token,
487            buffer_size,
488            matches!(special, Special::Tokenize),
489            None,
490        )?;
491        Ok(String::from_utf8(bytes)?)
492    }
493
494    /// Convert a token to bytes with a specified buffer size.
495    ///
496    /// Generally you should use [`LlamaModel::token_to_bytes`] as it is able to handle tokens of
497    /// any length.
498    ///
499    /// # Errors
500    ///
501    /// - if the token type is unknown
502    /// - the resultant token is larger than `buffer_size`.
503    ///
504    /// # Panics
505    ///
506    /// - if `buffer_size` does not fit into a [`c_int`].
507    /// - if the returned size from llama-cpp does not fit into a [`usize`]. (this should never happen)
508    #[deprecated(since = "0.1.0", note = "Use `token_to_piece_bytes` instead")]
509    pub fn token_to_bytes_with_size(
510        &self,
511        token: LlamaToken,
512        buffer_size: usize,
513        special: Special,
514        lstrip: Option<NonZeroU16>,
515    ) -> Result<Vec<u8>, TokenToStringError> {
516        if token == self.token_nl() {
517            return Ok(b"\n".to_vec());
518        }
519
520        // unsure what to do with this in the face of the 'special' arg + attr changes
521        let attrs = self.token_attr(token);
522        if attrs.is_empty()
523            || attrs
524                .intersects(LlamaTokenAttr::Unknown | LlamaTokenAttr::Byte | LlamaTokenAttr::Unused)
525            || attrs.contains(LlamaTokenAttr::Control)
526                && (token == self.token_bos() || token == self.token_eos())
527        {
528            return Ok(Vec::new());
529        }
530
531        let special = match special {
532            Special::Tokenize => true,
533            Special::Plaintext => false,
534        };
535
536        let string = CString::new(vec![b'*'; buffer_size]).expect("no null");
537        let len = string.as_bytes().len();
538        let len = c_int::try_from(len).expect("length fits into c_int");
539        let buf = string.into_raw();
540        let lstrip = lstrip.map_or(0, |it| i32::from(it.get()));
541        let size = unsafe {
542            llama_cpp_sys_2::llama_token_to_piece(
543                self.vocab_ptr(),
544                token.0,
545                buf,
546                len,
547                lstrip,
548                special,
549            )
550        };
551
552        match size {
553            0 => Err(TokenToStringError::UnknownTokenType),
554            i if i.is_negative() => Err(TokenToStringError::InsufficientBufferSpace(i)),
555            size => {
556                let string = unsafe { CString::from_raw(buf) };
557                let mut bytes = string.into_bytes();
558                let len = usize::try_from(size).expect("size is positive and fits into usize");
559                bytes.truncate(len);
560                Ok(bytes)
561            }
562        }
563    }
564    /// The number of tokens the model was trained on.
565    ///
566    /// This returns a `c_int` for maximum compatibility. Most of the time it can be cast to an i32
567    /// without issue.
568    #[must_use]
569    pub fn n_vocab(&self) -> i32 {
570        unsafe { llama_cpp_sys_2::llama_n_vocab(self.vocab_ptr()) }
571    }
572
573    /// The type of vocab the model was trained on.
574    ///
575    /// # Panics
576    ///
577    /// If llama-cpp emits a vocab type that is not known to this library.
578    #[must_use]
579    pub fn vocab_type(&self) -> VocabType {
580        // llama_cpp_sys_2::llama_model_get_vocab
581        let vocab_type = unsafe { llama_cpp_sys_2::llama_vocab_type(self.vocab_ptr()) };
582        VocabType::try_from(vocab_type).expect("invalid vocab type")
583    }
584
585    /// This returns a `c_int` for maximum compatibility. Most of the time it can be cast to an i32
586    /// without issue.
587    #[must_use]
588    pub fn n_embd(&self) -> c_int {
589        unsafe { llama_cpp_sys_2::llama_n_embd(self.model.as_ptr()) }
590    }
591
592    /// Returns the total size of all the tensors in the model in bytes.
593    pub fn size(&self) -> u64 {
594        unsafe { llama_cpp_sys_2::llama_model_size(self.model.as_ptr()) }
595    }
596
597    /// Returns the number of parameters in the model.
598    pub fn n_params(&self) -> u64 {
599        unsafe { llama_cpp_sys_2::llama_model_n_params(self.model.as_ptr()) }
600    }
601
602    /// Returns whether the model is a recurrent network (Mamba, RWKV, etc)
603    pub fn is_recurrent(&self) -> bool {
604        unsafe { llama_cpp_sys_2::llama_model_is_recurrent(self.model.as_ptr()) }
605    }
606
607    /// Returns whether the model is a hybrid network (Jamba, Granite, Qwen3xx, etc)
608    ///
609    /// Hybrid models have both attention layers and recurrent/SSM layers.
610    /// They require special handling for state checkpointing.
611    pub fn is_hybrid(&self) -> bool {
612        unsafe { llama_cpp_sys_2::llama_model_is_hybrid(self.model.as_ptr()) }
613    }
614
615    /// Returns the number of layers within the model.
616    pub fn n_layer(&self) -> u32 {
617        // It's never possible for this to panic because while the API interface is defined as an int32_t,
618        // the field it's accessing is a uint32_t.
619        u32::try_from(unsafe { llama_cpp_sys_2::llama_model_n_layer(self.model.as_ptr()) }).unwrap()
620    }
621
622    /// Returns the number of attention heads within the model.
623    pub fn n_head(&self) -> u32 {
624        // It's never possible for this to panic because while the API interface is defined as an int32_t,
625        // the field it's accessing is a uint32_t.
626        u32::try_from(unsafe { llama_cpp_sys_2::llama_model_n_head(self.model.as_ptr()) }).unwrap()
627    }
628
629    /// Returns the number of KV attention heads.
630    pub fn n_head_kv(&self) -> u32 {
631        // It's never possible for this to panic because while the API interface is defined as an int32_t,
632        // the field it's accessing is a uint32_t.
633        u32::try_from(unsafe { llama_cpp_sys_2::llama_model_n_head_kv(self.model.as_ptr()) })
634            .unwrap()
635    }
636
637    /// Get metadata value as a string by key name
638    pub fn meta_val_str(&self, key: &str) -> Result<String, MetaValError> {
639        let key_cstring = CString::new(key)?;
640        let key_ptr = key_cstring.as_ptr();
641
642        extract_meta_string(
643            |buf_ptr, buf_len| unsafe {
644                llama_cpp_sys_2::llama_model_meta_val_str(
645                    self.model.as_ptr(),
646                    key_ptr,
647                    buf_ptr,
648                    buf_len,
649                )
650            },
651            256,
652        )
653    }
654
655    /// Get the number of metadata key/value pairs
656    pub fn meta_count(&self) -> i32 {
657        unsafe { llama_cpp_sys_2::llama_model_meta_count(self.model.as_ptr()) }
658    }
659
660    /// Get metadata key name by index
661    pub fn meta_key_by_index(&self, index: i32) -> Result<String, MetaValError> {
662        extract_meta_string(
663            |buf_ptr, buf_len| unsafe {
664                llama_cpp_sys_2::llama_model_meta_key_by_index(
665                    self.model.as_ptr(),
666                    index,
667                    buf_ptr,
668                    buf_len,
669                )
670            },
671            256,
672        )
673    }
674
675    /// Get metadata value as a string by index
676    pub fn meta_val_str_by_index(&self, index: i32) -> Result<String, MetaValError> {
677        extract_meta_string(
678            |buf_ptr, buf_len| unsafe {
679                llama_cpp_sys_2::llama_model_meta_val_str_by_index(
680                    self.model.as_ptr(),
681                    index,
682                    buf_ptr,
683                    buf_len,
684                )
685            },
686            256,
687        )
688    }
689
690    /// Returns the rope type of the model.
691    pub fn rope_type(&self) -> Option<RopeType> {
692        match unsafe { llama_cpp_sys_2::llama_model_rope_type(self.model.as_ptr()) } {
693            llama_cpp_sys_2::LLAMA_ROPE_TYPE_NONE => None,
694            llama_cpp_sys_2::LLAMA_ROPE_TYPE_NORM => Some(RopeType::Norm),
695            llama_cpp_sys_2::LLAMA_ROPE_TYPE_NEOX => Some(RopeType::NeoX),
696            llama_cpp_sys_2::LLAMA_ROPE_TYPE_MROPE => Some(RopeType::MRope),
697            llama_cpp_sys_2::LLAMA_ROPE_TYPE_VISION => Some(RopeType::Vision),
698            rope_type => {
699                tracing::error!(rope_type = rope_type, "Unexpected rope type from llama.cpp");
700                None
701            }
702        }
703    }
704
705    /// Get chat template from model by name. If the name parameter is None, the default chat template will be returned.
706    ///
707    /// You supply this into [`Self::apply_chat_template`] to get back a string with the appropriate template
708    /// substitution applied to convert a list of messages into a prompt the LLM can use to complete
709    /// the chat.
710    ///
711    /// You could also use an external jinja parser, like [minijinja](https://github.com/mitsuhiko/minijinja),
712    /// to parse jinja templates not supported by the llama.cpp template engine.
713    ///
714    /// # Errors
715    ///
716    /// * If the model has no chat template by that name
717    /// * If the chat template is not a valid [`CString`].
718    pub fn chat_template(
719        &self,
720        name: Option<&str>,
721    ) -> Result<LlamaChatTemplate, ChatTemplateError> {
722        let name_cstr = name.map(CString::new);
723        let name_ptr = match name_cstr {
724            Some(Ok(name)) => name.as_ptr(),
725            _ => std::ptr::null(),
726        };
727        let result =
728            unsafe { llama_cpp_sys_2::llama_model_chat_template(self.model.as_ptr(), name_ptr) };
729
730        // Convert result to Rust String if not null
731        if result.is_null() {
732            Err(ChatTemplateError::MissingTemplate)
733        } else {
734            let chat_template_cstr = unsafe { CStr::from_ptr(result) };
735            let chat_template = CString::new(chat_template_cstr.to_bytes())?;
736            Ok(LlamaChatTemplate(chat_template))
737        }
738    }
739
740    /// Loads a model from a file.
741    ///
742    /// # Errors
743    ///
744    /// See [`LlamaModelLoadError`] for more information.
745    #[tracing::instrument(skip_all, fields(params))]
746    pub fn load_from_file(
747        _: &LlamaBackend,
748        path: impl AsRef<Path>,
749        params: &LlamaModelParams,
750    ) -> Result<Self, LlamaModelLoadError> {
751        let path = path.as_ref();
752        debug_assert!(Path::new(path).exists(), "{path:?} does not exist");
753        let path = path
754            .to_str()
755            .ok_or(LlamaModelLoadError::PathToStrError(path.to_path_buf()))?;
756
757        let cstr = CString::new(path)?;
758        let llama_model =
759            unsafe { llama_cpp_sys_2::llama_load_model_from_file(cstr.as_ptr(), params.params) };
760
761        let model = NonNull::new(llama_model).ok_or(LlamaModelLoadError::NullResult)?;
762
763        tracing::debug!(?path, "Loaded model");
764        Ok(LlamaModel { model })
765    }
766
767    /// Initializes a lora adapter from a file.
768    ///
769    /// # Errors
770    ///
771    /// See [`LlamaLoraAdapterInitError`] for more information.
772    pub fn lora_adapter_init(
773        &self,
774        path: impl AsRef<Path>,
775    ) -> Result<LlamaLoraAdapter, LlamaLoraAdapterInitError> {
776        let path = path.as_ref();
777        debug_assert!(Path::new(path).exists(), "{path:?} does not exist");
778
779        let path = path
780            .to_str()
781            .ok_or(LlamaLoraAdapterInitError::PathToStrError(
782                path.to_path_buf(),
783            ))?;
784
785        let cstr = CString::new(path)?;
786        let adapter =
787            unsafe { llama_cpp_sys_2::llama_adapter_lora_init(self.model.as_ptr(), cstr.as_ptr()) };
788
789        let adapter = NonNull::new(adapter).ok_or(LlamaLoraAdapterInitError::NullResult)?;
790
791        tracing::debug!(?path, "Initialized lora adapter");
792        Ok(LlamaLoraAdapter {
793            lora_adapter: adapter,
794        })
795    }
796
797    /// Create a new context from this model.
798    ///
799    /// # Errors
800    ///
801    /// There is many ways this can fail. See [`LlamaContextLoadError`] for more information.
802    // we intentionally do not derive Copy on `LlamaContextParams` to allow llama.cpp to change the type to be non-trivially copyable.
803    #[allow(clippy::needless_pass_by_value)]
804    pub fn new_context<'a>(
805        &'a self,
806        _: &LlamaBackend,
807        params: LlamaContextParams,
808    ) -> Result<LlamaContext<'a>, LlamaContextLoadError> {
809        let context_params = params.context_params;
810        let context = unsafe {
811            llama_cpp_sys_2::llama_new_context_with_model(self.model.as_ptr(), context_params)
812        };
813        let context = NonNull::new(context).ok_or(LlamaContextLoadError::NullReturn)?;
814
815        Ok(LlamaContext::new(self, context, params.embeddings()))
816    }
817
818    /// Create a new context bound to another context via llama.cpp's `ctx_other` field.
819    ///
820    /// This is required for MTP speculative decoding when the target model's
821    /// architecture uses `LLM_ARCH_GEMMA4_ASSISTANT`, which asserts that the draft
822    /// context references the target context so KV state can be shared.
823    ///
824    /// # Errors
825    ///
826    /// See [`LlamaContextLoadError`].
827    #[allow(clippy::needless_pass_by_value)]
828    pub fn new_context_with_ctx_other<'a>(
829        &'a self,
830        _: &LlamaBackend,
831        params: LlamaContextParams,
832        ctx_other: &LlamaContext<'_>,
833    ) -> Result<LlamaContext<'a>, LlamaContextLoadError> {
834        let mut context_params = params.context_params;
835        context_params.ctx_other = ctx_other.context.as_ptr();
836        let context = unsafe {
837            llama_cpp_sys_2::llama_new_context_with_model(self.model.as_ptr(), context_params)
838        };
839        let context = NonNull::new(context).ok_or(LlamaContextLoadError::NullReturn)?;
840
841        Ok(LlamaContext::new(self, context, params.embeddings()))
842    }
843
844    /// Creates a new context with backend samplers attached for specific sequences.
845    ///
846    /// Ownership of the samplers is transferred to the context, ensuring they remain
847    /// alive for the context's lifetime. Only samplers that support backend execution
848    /// (greedy, dist, temp, top_k, top_p, min_p, logit_bias) will run on the backend.
849    ///
850    /// # Arguments
851    ///
852    /// * `params` - Context parameters
853    /// * `samplers` - Iterator of `(seq_id, sampler)` pairs where sampler must be a chain
854    ///
855    /// # Example
856    ///
857    /// ```rust,ignore
858    /// let sampler = LlamaSampler::chain([
859    ///     LlamaSampler::min_p(0.01, 64),
860    ///     LlamaSampler::temp(0.1),
861    ///     LlamaSampler::dist(42),
862    /// ], false);
863    ///
864    /// let ctx = model.new_context_with_samplers(
865    ///     &backend,
866    ///     ctx_params,
867    ///     [(0, sampler)],
868    /// )?;
869    /// ```
870    #[allow(clippy::needless_pass_by_value)]
871    pub fn new_context_with_samplers<'a>(
872        &'a self,
873        _: &LlamaBackend,
874        params: LlamaContextParams,
875        samplers: impl IntoIterator<Item = (i32, LlamaSampler)>,
876    ) -> Result<LlamaContext<'a>, LlamaContextLoadError> {
877        let samplers: Vec<_> = samplers.into_iter().collect();
878        let mut context_params = params.context_params;
879
880        let mut sampler_configs: Vec<llama_cpp_sys_2::llama_sampler_seq_config> = samplers
881            .iter()
882            .map(|(seq_id, sampler)| llama_cpp_sys_2::llama_sampler_seq_config {
883                seq_id: *seq_id,
884                sampler: sampler.sampler,
885            })
886            .collect();
887
888        if !sampler_configs.is_empty() {
889            context_params.samplers = sampler_configs.as_mut_ptr();
890            context_params.n_samplers = sampler_configs.len();
891        }
892
893        let context = unsafe {
894            llama_cpp_sys_2::llama_new_context_with_model(self.model.as_ptr(), context_params)
895        };
896        let context = NonNull::new(context).ok_or(LlamaContextLoadError::NullReturn)?;
897
898        Ok(LlamaContext::with_samplers(self, context, params.embeddings(), samplers))
899    }
900
901    /// Apply the models chat template to some messages.
902    /// See <https://github.com/ggerganov/llama.cpp/wiki/Templates-supported-by-llama_chat_apply_template>
903    ///
904    /// Unlike the llama.cpp `apply_chat_template` which just randomly uses the ChatML template when given
905    /// a null pointer for the template, this requires an explicit template to be specified. If you want to
906    /// use "chatml", then just do `LlamaChatTemplate::new("chatml")` or any other model name or template
907    /// string.
908    ///
909    /// Use [`Self::chat_template`] to retrieve the template baked into the model (this is the preferred
910    /// mechanism as using the wrong chat template can result in really unexpected responses from the LLM).
911    ///
912    /// You probably want to set `add_ass` to true so that the generated template string ends with a the
913    /// opening tag of the assistant. If you fail to leave a hanging chat tag, the model will likely generate
914    /// one into the output and the output may also have unexpected output aside from that.
915    ///
916    /// # Errors
917    /// There are many ways this can fail. See [`ApplyChatTemplateError`] for more information.
918    #[tracing::instrument(skip_all)]
919    pub fn apply_chat_template(
920        &self,
921        tmpl: &LlamaChatTemplate,
922        chat: &[LlamaChatMessage],
923        add_ass: bool,
924    ) -> Result<String, ApplyChatTemplateError> {
925        // Buffer is twice the length of messages per their recommendation
926        let message_length = chat.iter().fold(0, |acc, c| {
927            acc + c.role.to_bytes().len() + c.content.to_bytes().len()
928        });
929        let mut buff: Vec<u8> = vec![0; message_length * 2];
930
931        // Build our llama_cpp_sys_2 chat messages
932        let chat: Vec<llama_cpp_sys_2::llama_chat_message> = chat
933            .iter()
934            .map(|c| llama_cpp_sys_2::llama_chat_message {
935                role: c.role.as_ptr(),
936                content: c.content.as_ptr(),
937            })
938            .collect();
939
940        let tmpl_ptr = tmpl.0.as_ptr();
941
942        let res = unsafe {
943            llama_cpp_sys_2::llama_chat_apply_template(
944                tmpl_ptr,
945                chat.as_ptr(),
946                chat.len(),
947                add_ass,
948                buff.as_mut_ptr().cast::<c_char>(),
949                buff.len().try_into().expect("Buffer size exceeds i32::MAX"),
950            )
951        };
952
953        if res < 0 {
954            return Err(ApplyChatTemplateError::FfiError(res));
955        }
956
957        if res > buff.len().try_into().expect("Buffer size exceeds i32::MAX") {
958            buff.resize(res.try_into().expect("res is negative"), 0);
959
960            let res = unsafe {
961                llama_cpp_sys_2::llama_chat_apply_template(
962                    tmpl_ptr,
963                    chat.as_ptr(),
964                    chat.len(),
965                    add_ass,
966                    buff.as_mut_ptr().cast::<c_char>(),
967                    buff.len().try_into().expect("Buffer size exceeds i32::MAX"),
968                )
969            };
970            if res < 0 {
971                return Err(ApplyChatTemplateError::FfiError(res));
972            }
973            assert_eq!(Ok(res), buff.len().try_into());
974        }
975        buff.truncate(res.try_into().expect("res is negative"));
976        Ok(String::from_utf8(buff)?)
977    }
978}
979
980/// Generic helper function for extracting string values from the C API
981/// This are specifically useful for the the metadata functions, where we pass in a buffer
982/// to be populated by a string, not yet knowing if the buffer is large enough.
983/// If the buffer was not large enough, we get the correct length back, which can be used to
984/// construct a buffer of appropriate size.
985fn extract_meta_string<F>(c_function: F, capacity: usize) -> Result<String, MetaValError>
986where
987    F: Fn(*mut c_char, usize) -> i32,
988{
989    let mut buffer = vec![0u8; capacity];
990
991    // call the foreign function
992    let result = c_function(buffer.as_mut_ptr().cast::<c_char>(), buffer.len());
993    if result < 0 {
994        return Err(MetaValError::NegativeReturn(result));
995    }
996
997    // check if the response fit in our buffer
998    let returned_len = result as usize;
999    if returned_len >= capacity {
1000        // buffer wasn't large enough, try again with the correct capacity.
1001        return extract_meta_string(c_function, returned_len + 1);
1002    }
1003
1004    // verify null termination
1005    debug_assert_eq!(
1006        buffer.get(returned_len),
1007        Some(&0),
1008        "should end with null byte"
1009    );
1010
1011    // resize, convert, and return
1012    buffer.truncate(returned_len);
1013    Ok(String::from_utf8(buffer)?)
1014}
1015
1016impl Drop for LlamaModel {
1017    fn drop(&mut self) {
1018        unsafe { llama_cpp_sys_2::llama_free_model(self.model.as_ptr()) }
1019    }
1020}
1021
1022/// a rusty equivalent of `llama_vocab_type`
1023#[repr(u32)]
1024#[derive(Debug, Eq, Copy, Clone, PartialEq)]
1025pub enum VocabType {
1026    /// Byte Pair Encoding
1027    BPE = llama_cpp_sys_2::LLAMA_VOCAB_TYPE_BPE as _,
1028    /// Sentence Piece Tokenizer
1029    SPM = llama_cpp_sys_2::LLAMA_VOCAB_TYPE_SPM as _,
1030}
1031
1032/// There was an error converting a `llama_vocab_type` to a `VocabType`.
1033#[derive(thiserror::Error, Debug, Eq, PartialEq)]
1034pub enum LlamaTokenTypeFromIntError {
1035    /// The value is not a valid `llama_token_type`. Contains the int value that was invalid.
1036    #[error("Unknown Value {0}")]
1037    UnknownValue(llama_cpp_sys_2::llama_vocab_type),
1038}
1039
1040impl TryFrom<llama_cpp_sys_2::llama_vocab_type> for VocabType {
1041    type Error = LlamaTokenTypeFromIntError;
1042
1043    fn try_from(value: llama_cpp_sys_2::llama_vocab_type) -> Result<Self, Self::Error> {
1044        match value {
1045            llama_cpp_sys_2::LLAMA_VOCAB_TYPE_BPE => Ok(VocabType::BPE),
1046            llama_cpp_sys_2::LLAMA_VOCAB_TYPE_SPM => Ok(VocabType::SPM),
1047            unknown => Err(LlamaTokenTypeFromIntError::UnknownValue(unknown)),
1048        }
1049    }
1050}