Skip to main content

aither_llama/
client.rs

1use crate::error::LlamaError;
2use aither_core::{
3    EmbeddingModel, LanguageModel,
4    llm::{
5        Event, LLMRequest, Message, Role, ToolCall,
6        model::{Ability, Parameters, Profile, ToolChoice},
7        tool::ToolDefinition,
8    },
9};
10use futures_core::Stream;
11use llama_cpp_2::{
12    LlamaCppError,
13    context::params::{LlamaContextParams, LlamaPoolingType},
14    llama_backend::LlamaBackend,
15    llama_batch::LlamaBatch,
16    model::{AddBos, LlamaChatTemplate, LlamaModel, params::LlamaModelParams},
17    openai::OpenAIChatTemplateParams,
18    sampling::LlamaSampler,
19};
20use serde::Serialize;
21use serde_json::{Value, json};
22use std::{
23    num::NonZeroU32,
24    path::{Path, PathBuf},
25    sync::Arc,
26    thread,
27    time::{SystemTime, UNIX_EPOCH},
28};
29
30fn init_backend() -> Result<LlamaBackend, LlamaError> {
31    match LlamaBackend::init() {
32        Ok(backend) => Ok(backend),
33        Err(LlamaCppError::BackendAlreadyInitialized) => Ok(LlamaBackend {}),
34        Err(err) => Err(LlamaError::Model(err.to_string())),
35    }
36}
37
38/// Local llama.cpp model wrapper implementing aither traits.
39#[derive(Debug, Clone)]
40pub struct Llama {
41    inner: Arc<LlamaConfig>,
42    model: Arc<LlamaModel>,
43    backend: Arc<LlamaBackend>,
44}
45
46impl Llama {
47    /// Load a GGUF model from disk.
48    ///
49    /// # Errors
50    ///
51    /// Returns an error if the backend cannot start or the model cannot be
52    /// loaded from `model_path`.
53    pub fn from_file(model_path: impl AsRef<Path>) -> Result<Self, LlamaError> {
54        Self::builder(model_path).build()
55    }
56
57    /// Start building a llama backend with custom options.
58    #[must_use]
59    pub fn builder(model_path: impl AsRef<Path>) -> Builder {
60        Builder::new(model_path)
61    }
62
63    /// Override chat template name or full template string.
64    #[must_use]
65    pub fn with_chat_template(mut self, template: impl Into<String>) -> Self {
66        Arc::make_mut(&mut self.inner).chat_template = Some(template.into());
67        self
68    }
69
70    /// Override generation context size.
71    #[must_use]
72    pub fn with_n_ctx(mut self, n_ctx: u32) -> Self {
73        Arc::make_mut(&mut self.inner).n_ctx = n_ctx;
74        self
75    }
76}
77
78impl LanguageModel for Llama {
79    type Error = LlamaError;
80
81    fn respond(
82        &self,
83        request: LLMRequest,
84    ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
85        response_stream(
86            self.model.clone(),
87            self.backend.clone(),
88            self.inner.clone(),
89            request,
90        )
91    }
92
93    fn profile(&self) -> impl std::future::Future<Output = Result<Profile, Self::Error>> + Send {
94        let cfg = self.inner.clone();
95        let context_length = cfg.n_ctx;
96        async move {
97            let model_name = cfg
98                .model_path
99                .file_name()
100                .and_then(|s| s.to_str())
101                .unwrap_or("llama-local")
102                .to_string();
103            Ok(Profile::new(
104                model_name.clone(),
105                "llama.cpp",
106                model_name,
107                "Local llama.cpp GGUF model",
108                context_length,
109            )
110            .with_abilities([Ability::ToolUse, Ability::Reasoning]))
111        }
112    }
113}
114
115impl EmbeddingModel for Llama {
116    fn dim(&self) -> usize {
117        usize::try_from(self.model.n_embd())
118            .expect("llama embedding dimension must be non-negative")
119    }
120
121    fn embed(
122        &self,
123        text: &str,
124    ) -> impl std::future::Future<Output = aither_core::Result<Vec<f32>>> + Send {
125        let model = self.model.clone();
126        let cfg = self.inner.clone();
127        let input = text.to_owned();
128
129        async move {
130            let mut context = create_context(&model, &self.backend, &cfg, true)?;
131
132            let tokens = model
133                .str_to_token(&input, AddBos::Never)
134                .map_err(|err| LlamaError::Token(err.to_string()))?;
135            if tokens.is_empty() {
136                return Err(LlamaError::Unsupported(
137                    "cannot embed empty token sequence".to_string(),
138                )
139                .into());
140            }
141
142            let mut batch = LlamaBatch::new(tokens.len(), 1);
143            batch
144                .add_sequence(&tokens, 0, true)
145                .map_err(|err| LlamaError::Decode(err.to_string()))?;
146            context
147                .decode(&mut batch)
148                .map_err(|err| LlamaError::Decode(err.to_string()))?;
149
150            if let Ok(embedding) = context.embeddings_seq_ith(0) {
151                return Ok(embedding.to_vec());
152            }
153
154            let last_index = i32::try_from(tokens.len() - 1)
155                .map_err(|_| LlamaError::Unsupported("token sequence is too long".to_string()))?;
156            let embedding = context
157                .embeddings_ith(last_index)
158                .map_err(|err| LlamaError::Decode(err.to_string()))?;
159            Ok(embedding.to_vec())
160        }
161    }
162}
163
164#[derive(Debug, Clone)]
165struct LlamaConfig {
166    model_path: PathBuf,
167    chat_template: Option<String>,
168    /// The context size contexts are created with and the profile reports.
169    n_ctx: u32,
170    n_threads: i32,
171    n_threads_batch: i32,
172}
173
174/// Builder for local llama.cpp model configuration.
175#[derive(Debug, Clone)]
176pub struct Builder {
177    model_path: PathBuf,
178    n_gpu_layers: u32,
179    use_mlock: bool,
180    n_ctx: Option<u32>,
181    chat_template: Option<String>,
182    n_threads: i32,
183    n_threads_batch: i32,
184    backend: Option<Arc<LlamaBackend>>,
185}
186
187impl Builder {
188    fn new(model_path: impl AsRef<Path>) -> Self {
189        Self {
190            model_path: model_path.as_ref().to_path_buf(),
191            n_gpu_layers: 0,
192            use_mlock: false,
193            n_ctx: None,
194            chat_template: None,
195            n_threads: 4,
196            n_threads_batch: 4,
197            backend: None,
198        }
199    }
200
201    /// Number of layers offloaded to GPU.
202    #[must_use]
203    pub const fn n_gpu_layers(mut self, n_gpu_layers: u32) -> Self {
204        self.n_gpu_layers = n_gpu_layers;
205        self
206    }
207
208    /// Keep model pages in RAM when possible.
209    #[must_use]
210    pub const fn use_mlock(mut self, use_mlock: bool) -> Self {
211        self.use_mlock = use_mlock;
212        self
213    }
214
215    /// Generation/embedding context size.
216    #[must_use]
217    pub const fn n_ctx(mut self, n_ctx: u32) -> Self {
218        self.n_ctx = Some(n_ctx);
219        self
220    }
221
222    /// Override model chat template name/content.
223    #[must_use]
224    pub fn chat_template(mut self, template: impl Into<String>) -> Self {
225        self.chat_template = Some(template.into());
226        self
227    }
228
229    /// Number of decode threads.
230    #[must_use]
231    pub const fn n_threads(mut self, n_threads: i32) -> Self {
232        self.n_threads = n_threads;
233        self
234    }
235
236    /// Number of batch decode threads.
237    #[must_use]
238    pub const fn n_threads_batch(mut self, n_threads_batch: i32) -> Self {
239        self.n_threads_batch = n_threads_batch;
240        self
241    }
242
243    /// Build the local llama provider.
244    ///
245    /// # Errors
246    ///
247    /// Returns an error if the backend cannot start or the model file cannot be
248    /// loaded.
249    pub fn build(self) -> Result<Llama, LlamaError> {
250        let model_params = LlamaModelParams::default()
251            .with_n_gpu_layers(self.n_gpu_layers)
252            .with_use_mlock(self.use_mlock);
253        let backend = if let Some(backend) = self.backend {
254            backend
255        } else {
256            Arc::new(init_backend()?)
257        };
258        let model = LlamaModel::load_from_file(backend.as_ref(), &self.model_path, &model_params)
259            .map_err(|err| LlamaError::Model(err.to_string()))?;
260
261        Ok(Llama {
262            inner: Arc::new(LlamaConfig {
263                model_path: self.model_path,
264                chat_template: self.chat_template,
265                n_ctx: resolve_n_ctx(self.n_ctx, model.n_ctx_train()),
266                n_threads: self.n_threads,
267                n_threads_batch: self.n_threads_batch,
268            }),
269            model: Arc::new(model),
270            backend,
271        })
272    }
273}
274
275fn response_stream(
276    model: Arc<LlamaModel>,
277    backend: Arc<LlamaBackend>,
278    cfg: Arc<LlamaConfig>,
279    request: LLMRequest,
280) -> impl Stream<Item = Result<Event, LlamaError>> + Send {
281    let (sender, receiver) = async_channel::unbounded();
282    let worker_sender = sender.clone();
283    match thread::Builder::new()
284        .name("aither-llama-respond".to_string())
285        .spawn(move || {
286            if let Err(err) = run_response_generation(
287                model.as_ref(),
288                backend.as_ref(),
289                cfg.as_ref(),
290                request,
291                &worker_sender,
292            ) {
293                let _ = worker_sender.send_blocking(Err(err));
294            }
295        }) {
296        Ok(_handle) => receiver,
297        Err(err) => {
298            let _ = sender.try_send(Err(LlamaError::Model(format!(
299                "failed to spawn llama response thread: {err}"
300            ))));
301            drop(sender);
302            receiver
303        }
304    }
305}
306
307fn run_response_generation(
308    model: &LlamaModel,
309    backend: &LlamaBackend,
310    cfg: &LlamaConfig,
311    request: LLMRequest,
312    sender: &async_channel::Sender<Result<Event, LlamaError>>,
313) -> Result<(), LlamaError> {
314    let (messages, parameters, tool_defs) = request.into_parts();
315
316    if messages.iter().any(|msg| !msg.attachments().is_empty()) {
317        return Err(LlamaError::Unsupported(
318            "attachments are not supported by aither-llama".to_string(),
319        ));
320    }
321    if messages.iter().any(|msg| msg.role() == Role::Configuration) {
322        return Err(LlamaError::Unsupported(
323            "per-message effort updates are not supported by aither-llama".to_string(),
324        ));
325    }
326
327    let tool_defs = filter_tool_definitions(tool_defs, &parameters.tool_choice);
328    let template = resolve_chat_template(model, cfg)?;
329    let prompt = build_prompt(model, &template, &messages, &parameters, &tool_defs)?;
330
331    let mut context = create_context(model, backend, cfg, false)?;
332    let prompt_tokens = model
333        .str_to_token(&prompt.template_result.prompt, AddBos::Never)
334        .map_err(|err| LlamaError::Token(err.to_string()))?;
335
336    if prompt_tokens.is_empty() {
337        return Err(LlamaError::Unsupported(
338            "empty prompt after template rendering".to_string(),
339        ));
340    }
341
342    let mut init_batch = LlamaBatch::new(prompt_tokens.len(), 1);
343    init_batch
344        .add_sequence(&prompt_tokens, 0, false)
345        .map_err(|err| LlamaError::Decode(err.to_string()))?;
346    context
347        .decode(&mut init_batch)
348        .map_err(|err| LlamaError::Decode(err.to_string()))?;
349
350    let mut sampler = build_sampler(&parameters);
351    sampler.accept_many(prompt_tokens.iter());
352
353    let mut generated = String::new();
354    let mut decoder = encoding_rs::UTF_8.new_decoder();
355    let start_pos = i32::try_from(prompt_tokens.len())
356        .map_err(|_| LlamaError::Unsupported("prompt is too long".to_string()))?;
357    let max_tokens = parameters.max_tokens.unwrap_or(512);
358
359    for pos in (start_pos..).take(usize::try_from(max_tokens).unwrap_or(usize::MAX)) {
360        let token = sampler.sample(&context, -1);
361        sampler.accept(token);
362
363        if model.is_eog_token(token) {
364            break;
365        }
366
367        let piece = model
368            .token_to_piece(token, &mut decoder, true, None)
369            .map_err(|err| LlamaError::Token(err.to_string()))?;
370        if !piece.is_empty() {
371            generated.push_str(&piece);
372            if sender.send_blocking(Ok(Event::Text(piece))).is_err() {
373                return Ok(());
374            }
375        }
376
377        let mut step_batch = LlamaBatch::new(1, 1);
378        step_batch
379            .add(token, pos, &[0], true)
380            .map_err(|err| LlamaError::Decode(err.to_string()))?;
381        context
382            .decode(&mut step_batch)
383            .map_err(|err| LlamaError::Decode(err.to_string()))?;
384    }
385
386    if let Ok(parsed) = prompt
387        .template_result
388        .parse_response_oaicompat(&generated, false)
389    {
390        for call in parse_openai_message(&parsed)? {
391            if sender.send_blocking(Ok(Event::ToolCall(call))).is_err() {
392                return Ok(());
393            }
394        }
395    }
396
397    Ok(())
398}
399
400/// The smallest context a model is run with, whatever its training window.
401const MIN_N_CTX: u32 = 512;
402
403/// The context size the model runs with: the configured one, else its
404/// training window. The session's context and the profile both use it.
405fn resolve_n_ctx(configured: Option<u32>, trained: u32) -> u32 {
406    configured.unwrap_or_else(|| trained.max(MIN_N_CTX))
407}
408
409fn context_params(cfg: &LlamaConfig, embeddings: bool) -> LlamaContextParams {
410    let mut params = LlamaContextParams::default()
411        .with_n_ctx(NonZeroU32::new(cfg.n_ctx))
412        .with_n_threads(cfg.n_threads)
413        .with_n_threads_batch(cfg.n_threads_batch);
414
415    if embeddings {
416        params = params.with_embeddings(true);
417        params = params.with_pooling_type(LlamaPoolingType::Last);
418    }
419    params
420}
421
422fn create_context<'a>(
423    model: &'a LlamaModel,
424    backend: &LlamaBackend,
425    cfg: &LlamaConfig,
426    embeddings: bool,
427) -> Result<llama_cpp_2::context::LlamaContext<'a>, LlamaError> {
428    model
429        .new_context(backend, context_params(cfg, embeddings))
430        .map_err(|err| LlamaError::Context(err.to_string()))
431}
432
433fn resolve_chat_template(
434    model: &LlamaModel,
435    cfg: &LlamaConfig,
436) -> Result<LlamaChatTemplate, LlamaError> {
437    if let Some(template) = &cfg.chat_template {
438        return LlamaChatTemplate::new(template).map_err(|err| LlamaError::Model(err.to_string()));
439    }
440    // Fall back to ChatML when the model carries no template of its own.
441    model.chat_template(None).map_or_else(
442        |_| LlamaChatTemplate::new("chatml").map_err(|err| LlamaError::Model(err.to_string())),
443        Ok,
444    )
445}
446
447struct Prompt {
448    template_result: llama_cpp_2::model::ChatTemplateResult,
449}
450
451fn build_prompt(
452    model: &LlamaModel,
453    template: &LlamaChatTemplate,
454    messages: &[Message],
455    parameters: &Parameters,
456    tool_defs: &[ToolDefinition],
457) -> Result<Prompt, LlamaError> {
458    let messages_json = serde_json::to_string(&messages_to_openai(messages))?;
459    let tools_json = tools_to_openai_json(tool_defs);
460
461    let template_result = model
462        .apply_chat_template_oaicompat(
463            template,
464            &OpenAIChatTemplateParams {
465                messages_json: &messages_json,
466                tools_json: tools_json.as_deref(),
467                tool_choice: None,
468                json_schema: None,
469                grammar: None,
470                reasoning_format: None,
471                chat_template_kwargs: None,
472                add_generation_prompt: true,
473                use_jinja: true,
474                parallel_tool_calls: true,
475                enable_thinking: parameters.include_reasoning,
476                add_bos: false,
477                add_eos: false,
478                parse_tool_calls: !tool_defs.is_empty(),
479            },
480        )
481        .map_err(|err| LlamaError::Model(err.to_string()))?;
482
483    Ok(Prompt { template_result })
484}
485
486fn filter_tool_definitions(
487    tool_defs: Vec<ToolDefinition>,
488    tool_choice: &ToolChoice,
489) -> Vec<ToolDefinition> {
490    match tool_choice {
491        ToolChoice::None => Vec::new(),
492        ToolChoice::Exact(name) => tool_defs
493            .into_iter()
494            .filter(|tool| tool.name() == name)
495            .collect(),
496        ToolChoice::Auto | ToolChoice::Required => tool_defs,
497    }
498}
499
500#[derive(Serialize)]
501struct OpenAIMessage {
502    role: String,
503    content: String,
504    #[serde(skip_serializing_if = "Option::is_none")]
505    tool_calls: Option<Vec<OpenAIToolCall>>,
506    #[serde(skip_serializing_if = "Option::is_none")]
507    tool_call_id: Option<String>,
508}
509
510#[derive(Serialize)]
511struct OpenAIToolCall {
512    id: String,
513    #[serde(rename = "type")]
514    kind: &'static str,
515    function: OpenAIToolFunction,
516}
517
518#[derive(Serialize)]
519struct OpenAIToolFunction {
520    name: String,
521    arguments: String,
522}
523
524fn messages_to_openai(messages: &[Message]) -> Vec<OpenAIMessage> {
525    messages
526        .iter()
527        .map(|msg| {
528            let role = match msg.role() {
529                Role::User => "user",
530                Role::Assistant => "assistant",
531                Role::System => "system",
532                Role::Tool => "tool",
533                Role::Configuration => {
534                    unreachable!("run_response_generation rejects configuration updates")
535                }
536            };
537
538            let tool_calls = if msg.tool_calls().is_empty() {
539                None
540            } else {
541                Some(
542                    msg.tool_calls()
543                        .iter()
544                        .map(|call| OpenAIToolCall {
545                            id: call.id.clone(),
546                            kind: "function",
547                            function: OpenAIToolFunction {
548                                name: call.name.clone(),
549                                arguments: call.arguments.to_string(),
550                            },
551                        })
552                        .collect(),
553                )
554            };
555
556            OpenAIMessage {
557                role: role.to_string(),
558                content: msg.content().to_string(),
559                tool_calls,
560                tool_call_id: msg.tool_call_id().map(ToString::to_string),
561            }
562        })
563        .collect()
564}
565
566fn tools_to_openai_json(tool_defs: &[ToolDefinition]) -> Option<String> {
567    if tool_defs.is_empty() {
568        return None;
569    }
570
571    let tools: Vec<Value> = tool_defs
572        .iter()
573        .map(|tool| {
574            json!({
575                "type": "function",
576                "function": {
577                    "name": tool.name(),
578                    "description": tool.description(),
579                    "parameters": tool.arguments_openai_schema(),
580                }
581            })
582        })
583        .collect();
584
585    serde_json::to_string(&tools).ok()
586}
587
588fn build_sampler(parameters: &Parameters) -> LlamaSampler {
589    let mut samplers = Vec::new();
590
591    if parameters.repetition_penalty.is_some()
592        || parameters.frequency_penalty.is_some()
593        || parameters.presence_penalty.is_some()
594    {
595        samplers.push(LlamaSampler::penalties(
596            64,
597            parameters.repetition_penalty.unwrap_or(1.0),
598            parameters.frequency_penalty.unwrap_or(0.0),
599            parameters.presence_penalty.unwrap_or(0.0),
600        ));
601    }
602
603    if let Some(top_k) = parameters.top_k {
604        samplers.push(LlamaSampler::top_k(top_k.cast_signed()));
605    }
606    if let Some(top_p) = parameters.top_p {
607        samplers.push(LlamaSampler::top_p(top_p, 1));
608    }
609    if let Some(min_p) = parameters.min_p {
610        samplers.push(LlamaSampler::min_p(min_p, 1));
611    }
612
613    if parameters.temperature.unwrap_or(0.8) <= 0.0 {
614        samplers.push(LlamaSampler::greedy());
615    } else {
616        samplers.push(LlamaSampler::temp(parameters.temperature.unwrap_or(0.8)));
617        samplers.push(LlamaSampler::dist(sampling_seed(parameters.seed)));
618    }
619
620    if samplers.is_empty() {
621        samplers.push(LlamaSampler::dist(sampling_seed(parameters.seed)));
622    }
623
624    LlamaSampler::chain_simple(samplers)
625}
626
627fn sampling_seed(seed: Option<u32>) -> u32 {
628    if let Some(seed) = seed {
629        return seed;
630    }
631    let now = SystemTime::now()
632        .duration_since(UNIX_EPOCH)
633        .map_or(1, |value| {
634            u64::try_from(value.as_nanos()).unwrap_or(u64::MAX)
635        });
636    let mixed = now ^ (now >> 32);
637    u32::try_from(mixed & u64::from(u32::MAX)).expect("masked seed fits in u32")
638}
639
640fn parse_openai_message(json_text: &str) -> Result<Vec<ToolCall>, LlamaError> {
641    let value: Value = serde_json::from_str(json_text)?;
642
643    let tool_calls = value
644        .get("tool_calls")
645        .and_then(Value::as_array)
646        .cloned()
647        .or_else(|| {
648            value
649                .get("choices")
650                .and_then(Value::as_array)
651                .and_then(|choices| choices.first())
652                .and_then(|choice| choice.get("message"))
653                .and_then(|message| message.get("tool_calls"))
654                .and_then(Value::as_array)
655                .cloned()
656        })
657        .unwrap_or_default();
658
659    let mut calls = Vec::new();
660    for call in &tool_calls {
661        let id = call
662            .get("id")
663            .and_then(Value::as_str)
664            .unwrap_or("llama_tool_call")
665            .to_string();
666        let function = call.get("function").unwrap_or(&Value::Null);
667        let name = function
668            .get("name")
669            .and_then(Value::as_str)
670            .unwrap_or("unknown")
671            .to_string();
672        let arguments = function
673            .get("arguments")
674            .and_then(Value::as_str)
675            .map_or_else(
676                || Value::Object(serde_json::Map::new()),
677                |raw| {
678                    serde_json::from_str::<Value>(raw)
679                        .unwrap_or_else(|_| Value::String(raw.to_string()))
680                },
681            );
682
683        calls.push(ToolCall::new(id, name, arguments));
684    }
685
686    Ok(calls)
687}
688
689#[cfg(test)]
690mod tests {
691    use super::*;
692
693    #[test]
694    fn an_unset_context_size_is_the_training_window() {
695        assert_eq!(resolve_n_ctx(None, 32_768), 32_768);
696    }
697
698    #[test]
699    fn a_tiny_training_window_is_raised_to_the_floor() {
700        assert_eq!(resolve_n_ctx(None, 128), 512);
701    }
702
703    #[test]
704    fn a_configured_context_size_wins() {
705        assert_eq!(resolve_n_ctx(Some(2048), 32_768), 2048);
706    }
707
708    #[test]
709    fn the_context_a_session_creates_is_the_size_the_profile_reports() {
710        let params = context_params(&config_with(resolve_n_ctx(None, 8192)), false);
711        assert_eq!(params.n_ctx(), NonZeroU32::new(8192));
712    }
713
714    fn config_with(n_ctx: u32) -> LlamaConfig {
715        LlamaConfig {
716            model_path: PathBuf::from("model.gguf"),
717            chat_template: None,
718            n_ctx,
719            n_threads: 4,
720            n_threads_batch: 4,
721        }
722    }
723}