Skip to main content

rig_llama_cpp/
wire.rs

1//! The Rig side of a loaded model: the completion wire that describes it to
2//! Rig and decodes its replies, and the runtime that carries each request to
3//! the inference worker.
4//!
5//! Rig drives a [`Model`] as a [`CompletionWire`] bound to a [`Runtime`]
6//! transport. The wire's payload is the prepared [`CompletionRequest`]
7//! itself; the runtime hands it to the worker thread, whose [`Frame`]s the
8//! wire's decoder writes into Rig's completion turn.
9
10use rig_core::completion::options::{Mapping, OptionFields, OptionMap};
11use rig_core::completion::{Accepts, CompletionRequest, LaterSystem, Media, ReplayTarget, Usage};
12use rig_core::driver::{Exchange, Opened, Opening, Transport};
13use rig_core::error::{EncodeError, ProviderError};
14use rig_core::message::{Api, DocumentSourceKind};
15use rig_core::operation::{Block, CallFragment, Completion, Finish};
16use rig_core::wire::document::{Reassemble, Serves};
17use rig_core::wire::{Decoder, Descriptor, Flow, Mode, Out, Wire, WireEvent};
18use tokio::sync::{mpsc, oneshot};
19use tokio_stream::wrappers::UnboundedReceiverStream;
20
21use crate::request::prepare_request;
22use crate::types::{
23    Done, Frame, FrameKind, InferenceCommand, InferenceParams, InferenceRequest, OutputPart,
24    RawResponse, ResponseChannel, SamplingParams,
25};
26
27/// The wire format this crate's turns record as their origin.
28const API: Api = Api::from_static("llama.cpp.chat-template");
29
30/// `max_tokens` when the request names none.
31const DEFAULT_MAX_TOKENS: u32 = 512;
32
33/// `temperature` when the request names none.
34const DEFAULT_TEMPERATURE: f32 = 0.7;
35
36/// Seed of the final sampler when the request names none.
37const DEFAULT_SEED: u32 = 42;
38
39/// A loaded model as Rig drives it: [`CompletionWire`] over [`Runtime`].
40///
41/// Obtained via [`Client::completion_model`](crate::Client::completion_model).
42/// Call it directly (`model.call(request)`, `model.stream(request)`), or hand
43/// it to anything that takes `impl Into<DynModel<Completion>>`, such as
44/// `rig_agent::AgentBuilder::new`. Clones share the loaded model.
45pub type Model = rig_core::Model<CompletionWire, Runtime>;
46
47/// The completion wire of a local llama.cpp model.
48///
49/// Its payload is the request as Rig prepared it, and its replies are the
50/// inference worker's [`Frame`]s.
51#[derive(Clone, Debug, PartialEq, Eq)]
52pub struct CompletionWire {
53    model: String,
54}
55
56impl CompletionWire {
57    pub(crate) fn new(model: impl Into<String>) -> Self {
58        Self {
59            model: model.into(),
60        }
61    }
62}
63
64impl ReplayTarget for CompletionWire {
65    fn api(&self) -> Api {
66        API
67    }
68
69    fn provider(&self) -> &str {
70        crate::PROVIDER
71    }
72
73    fn model(&self) -> &str {
74        &self.model
75    }
76
77    /// Images reach the model only through a multimodal projector, so a build
78    /// without `mtmd` reads text and tools alone. Assistant images are never
79    /// rendered into the prompt.
80    fn accepts(&self, _model: &str) -> Accepts {
81        if cfg!(feature = "mtmd") {
82            Accepts {
83                assistant_images: false,
84                ..Accepts::ALL
85            }
86        } else {
87            Accepts::TEXT
88        }
89    }
90
91    /// Images must carry their bytes: there is no network access to fetch a
92    /// URL or a provider file id, so those become placeholders instead.
93    fn encodes(&self, _model: &str, media: Media<'_>) -> bool {
94        match media {
95            Media::Image(image, _) => matches!(
96                image.data,
97                DocumentSourceKind::Raw(_) | DocumentSourceKind::Base64(_)
98            ),
99            _ => true,
100        }
101    }
102
103    fn map_options(&self, _request: &CompletionRequest, fields: OptionFields<'_>) -> OptionMap {
104        let OptionFields {
105            reasoning,
106            cache,
107            service_tier,
108            verbosity,
109            parallel_tool_calls,
110            top_p,
111            seed,
112            stop,
113        } = fields;
114        OptionMap {
115            reasoning: Mapping::of(reasoning, |_| {
116                Mapping::Omit("passed to the chat template as `enable_thinking`")
117            }),
118            cache: Mapping::of(
119                cache,
120                refuse("the persistent KV cache is configured on the client"),
121            ),
122            service_tier: Mapping::of(service_tier, refuse("a local model has no tiers")),
123            verbosity: Mapping::of(verbosity, refuse("no verbosity control")),
124            parallel_tool_calls: Mapping::of(
125                parallel_tool_calls,
126                refuse("tool calls are parsed from free-form output"),
127            ),
128            top_p: Mapping::of(top_p, |_| Mapping::Omit("applied by the local sampler")),
129            seed: Mapping::of(seed, |_| Mapping::Omit("seeds the local sampler")),
130            stop: Mapping::of_stop(stop, |_| Mapping::unsupported("no stop sequences")),
131        }
132    }
133
134    /// Generation ends at an end-of-generation token or the token budget;
135    /// neither is reported as a finish reason.
136    fn states_finish_reason(&self) -> bool {
137        false
138    }
139
140    /// Chat templates commonly accept a system message only at the start.
141    fn later_system(&self, _model: &str) -> LaterSystem {
142        LaterSystem::Leading
143    }
144}
145
146/// The answer for an option this wire cannot honour.
147fn refuse<T>(reason: &'static str) -> impl FnOnce(T) -> Mapping {
148    move |_| Mapping::unsupported(reason)
149}
150
151impl Wire for CompletionWire {
152    type Op = Completion;
153    type Payload = CompletionRequest;
154    type Frame = Frame;
155    type Decoder<'id> = FrameDecoder<'id>;
156    type Reassembler = RawDocument;
157
158    fn describe(&self) -> Descriptor<'_> {
159        Descriptor::new(crate::PROVIDER)
160            .model(Some(self.model.as_str()))
161            .replay(self)
162    }
163
164    fn encode(
165        &self,
166        request: CompletionRequest,
167        _mode: Mode,
168    ) -> Result<Self::Payload, EncodeError> {
169        Ok(request)
170    }
171
172    fn decoder<'id>(&self) -> FrameDecoder<'id> {
173        FrameDecoder::default()
174    }
175}
176
177/// The decoder of [`CompletionWire`]: writes each worker [`Frame`] into the
178/// reply.
179#[derive(Default)]
180pub struct FrameDecoder<'id> {
181    brand: std::marker::PhantomData<fn(&'id ()) -> &'id ()>,
182}
183
184impl<'id> Decoder<'id, Completion, Frame> for FrameDecoder<'id> {
185    type Event = Frame;
186
187    fn classify(&self, frame: Frame) -> WireEvent<Frame> {
188        WireEvent::Known(frame)
189    }
190
191    fn decode(
192        &mut self,
193        frame: Frame,
194        mut out: Out<'id, Completion>,
195    ) -> Result<Flow, ProviderError> {
196        match frame.0 {
197            // Streamed text arrives one token piece at a time; consecutive
198            // pieces extend one text block.
199            FrameKind::Part(OutputPart::Text(text)) => {
200                if !text.is_empty() {
201                    out.run(Block::Text, &text)?;
202                }
203            }
204            FrameKind::Part(OutputPart::Reasoning(text)) => {
205                out.end_run()?;
206                let index = out.fresh_index();
207                out.whole(
208                    index,
209                    Block::Reasoning { redacted: false },
210                    serde_json::Value::Null,
211                    &text,
212                )?;
213            }
214            FrameKind::Part(OutputPart::ToolCall { name, arguments }) => {
215                out.end_run()?;
216                // The model issues no call ids, so Rig mints one per call.
217                let index = out.fresh_index();
218                let arguments = match arguments {
219                    serde_json::Value::String(text) => text,
220                    other => other.to_string(),
221                };
222                out.fragment(
223                    Some(index),
224                    CallFragment {
225                        id: None,
226                        name: Some(&name),
227                        arguments: Some(&arguments),
228                    },
229                )?;
230                out.finish(index)?;
231            }
232            FrameKind::End(done) => {
233                out.end_run()?;
234                return Ok(out.end(Finish {
235                    usage: usage(&done),
236                    ..Finish::default()
237                }));
238            }
239        }
240        Ok(Flow::More)
241    }
242}
243
244fn usage(done: &Done) -> Usage {
245    Usage::new()
246        .input_tokens(done.prompt_tokens)
247        .output_tokens(done.completion_tokens)
248        .total_tokens(done.prompt_tokens + done.completion_tokens)
249        .cached_input_tokens(done.cached_input_tokens)
250}
251
252/// Rebuilds a reply's provider document — a serialized [`RawResponse`] —
253/// from the worker's end frame.
254#[derive(Debug, Default)]
255pub struct RawDocument {
256    document: Option<serde_json::Value>,
257}
258
259impl Serves<Completion> for RawDocument {}
260
261impl Reassemble<Frame> for RawDocument {
262    fn absorb(&mut self, frame: &Frame) {
263        if let FrameKind::End(done) = &frame.0 {
264            self.document = serde_json::to_value(RawResponse {
265                text: done.text.clone(),
266            })
267            .ok();
268        }
269    }
270
271    fn finish(self) -> serde_json::Value {
272        self.document.unwrap_or(serde_json::Value::Null)
273    }
274}
275
276/// The transport of a [`Model`]: carries each request to the inference
277/// worker thread and delivers its reply as [`Frame`]s.
278#[derive(Clone)]
279pub struct Runtime {
280    request_tx: mpsc::Sender<InferenceCommand>,
281    sampling: SamplingParams,
282}
283
284impl Runtime {
285    pub(crate) fn new(
286        request_tx: mpsc::Sender<InferenceCommand>,
287        sampling: SamplingParams,
288    ) -> Self {
289        Self {
290            request_tx,
291            sampling,
292        }
293    }
294
295    /// The worker's parameters for `request`, or why it cannot be rendered.
296    fn params(&self, request: &CompletionRequest) -> Result<InferenceParams, String> {
297        let prepared_request = prepare_request(request)?;
298        let options = &request.options;
299        Ok(InferenceParams {
300            prepared_request,
301            max_tokens: request.max_tokens.map_or(DEFAULT_MAX_TOKENS, |max| {
302                u32::try_from(max).unwrap_or(u32::MAX)
303            }),
304            temperature: request
305                .temperature
306                .map_or(DEFAULT_TEMPERATURE, |temperature| temperature as f32),
307            top_p: options
308                .top_p
309                .map_or(self.sampling.top_p, |top_p| top_p as f32),
310            top_k: self.sampling.top_k,
311            min_p: self.sampling.min_p,
312            presence_penalty: self.sampling.presence_penalty,
313            repetition_penalty: self.sampling.repetition_penalty,
314            // llama.cpp seeds take 32 bits; a wider seed keeps its low half.
315            seed: options.seed.map_or(DEFAULT_SEED, |seed| seed as u32),
316        })
317    }
318
319    async fn submit(
320        &self,
321        params: InferenceParams,
322        response_channel: ResponseChannel,
323    ) -> Result<(), ProviderError> {
324        self.request_tx
325            .send(InferenceCommand::Request(InferenceRequest {
326                params,
327                response_channel,
328            }))
329            .await
330            .map_err(|_| ProviderError::Provider("Inference thread shut down".into()))
331    }
332
333    async fn open(
334        self,
335        request: CompletionRequest,
336        mode: Mode,
337    ) -> Result<Opened<Frame>, ProviderError> {
338        let params = self.params(&request).map_err(ProviderError::request)?;
339        match mode {
340            Mode::Unary => {
341                let (response_tx, response_rx) = oneshot::channel();
342                self.submit(params, ResponseChannel::Completion(response_tx))
343                    .await?;
344                let result = response_rx
345                    .await
346                    .map_err(|_| ProviderError::Provider("Response channel closed".into()))?
347                    .map_err(ProviderError::Provider)?;
348                let frames: Vec<Result<Frame, ProviderError>> = result
349                    .parts
350                    .into_iter()
351                    .map(Frame::part)
352                    .chain([Frame::end(result.done)])
353                    .map(Ok)
354                    .collect();
355                Ok(Opened::new(tokio_stream::iter(frames)))
356            }
357            // Dropping the stream closes the channel, which stops generation
358            // at the next sampled token.
359            Mode::Streaming => {
360                let (stream_tx, stream_rx) = mpsc::unbounded_channel();
361                self.submit(params, ResponseChannel::Streaming(stream_tx))
362                    .await?;
363                Ok(Opened::new(UnboundedReceiverStream::new(stream_rx)))
364            }
365        }
366    }
367}
368
369impl Transport<CompletionWire> for Runtime {
370    fn send(&self, request: CompletionRequest, exchange: Exchange) -> Opening<Frame> {
371        Opening::new(self.clone().open(request, exchange.mode))
372    }
373}
374
375#[cfg(test)]
376mod tests {
377    use rig_core::completion::{CompletionRequest, Effort};
378    use rig_core::driver::{Exchange, Opened, Opening, Transport};
379    use rig_core::message::AssistantContent;
380    use rig_core::streaming::{Item, StreamEvent};
381    use serde_json::json;
382    use tokio_stream::StreamExt;
383
384    use super::CompletionWire;
385    use crate::types::{Done, Frame, OutputPart, RawResponse};
386
387    /// A runtime that answers every request with the same frames.
388    #[derive(Clone)]
389    struct Scripted(Vec<Frame>);
390
391    impl Transport<CompletionWire> for Scripted {
392        fn send(&self, _request: CompletionRequest, _exchange: Exchange) -> Opening<Frame> {
393            let frames: Vec<_> = self.0.iter().cloned().map(Ok).collect();
394            Opening::ready(Opened::new(tokio_stream::iter(frames)))
395        }
396    }
397
398    fn model(parts: Vec<OutputPart>) -> rig_core::Model<CompletionWire, Scripted> {
399        let mut frames: Vec<Frame> = parts.into_iter().map(Frame::part).collect();
400        frames.push(Frame::end(Done {
401            text: "the raw output".to_string(),
402            prompt_tokens: 12,
403            completion_tokens: 5,
404            cached_input_tokens: 4,
405        }));
406        rig_core::Model::new(CompletionWire::new("test"), Scripted(frames))
407    }
408
409    fn turn() -> Vec<OutputPart> {
410        vec![
411            OutputPart::Reasoning("weigh it".to_string()),
412            OutputPart::Text("Hello ".to_string()),
413            OutputPart::Text("world".to_string()),
414            OutputPart::ToolCall {
415                name: "get_time".to_string(),
416                arguments: json!({"zone": "UTC"}),
417            },
418        ]
419    }
420
421    #[tokio::test]
422    async fn a_turn_assembles_its_blocks_usage_and_raw_text() {
423        let response = model(turn()).call("hi").await.unwrap();
424
425        let [
426            AssistantContent::Reasoning(reasoning),
427            AssistantContent::Text(text),
428            AssistantContent::ToolCall(call),
429        ] = response.choice.as_slice()
430        else {
431            panic!("unexpected blocks: {:?}", response.choice);
432        };
433        assert_eq!(reasoning.text, "weigh it");
434        assert_eq!(text.text, "Hello world");
435        assert_eq!(call.function.name.as_str(), "get_time");
436        assert_eq!(call.function.arguments["zone"], "UTC");
437
438        assert_eq!(response.usage.input_tokens, Some(12));
439        assert_eq!(response.usage.output_tokens, Some(5));
440        assert_eq!(response.usage.total_tokens, Some(17));
441        assert_eq!(response.usage.cached_input_tokens, Some(4));
442
443        let raw: RawResponse = serde_json::from_value(response.raw).unwrap();
444        assert_eq!(raw.text, "the raw output");
445    }
446
447    #[tokio::test]
448    async fn every_tool_call_gets_its_own_id() {
449        let call = OutputPart::ToolCall {
450            name: "get_time".to_string(),
451            arguments: json!({}),
452        };
453        let response = model(vec![call.clone(), call]).call("hi").await.unwrap();
454        let ids: Vec<_> = response
455            .choice
456            .iter()
457            .filter_map(|block| match block {
458                AssistantContent::ToolCall(call) => Some(call.id.clone()),
459                _ => None,
460            })
461            .collect();
462        assert_eq!(ids.len(), 2);
463        assert_ne!(ids[0], ids[1]);
464    }
465
466    #[tokio::test]
467    async fn arguments_given_as_json_text_are_parsed() {
468        let call = OutputPart::ToolCall {
469            name: "search".to_string(),
470            arguments: json!("{\"q\": 1}"),
471        };
472        let response = model(vec![call]).call("hi").await.unwrap();
473        let AssistantContent::ToolCall(call) = &response.choice[0] else {
474            panic!("expected a tool call, got {:?}", response.choice);
475        };
476        assert_eq!(call.function.arguments["q"], 1);
477    }
478
479    #[tokio::test]
480    async fn a_stream_delivers_text_deltas_and_folds_into_the_same_response() {
481        let mut stream = model(turn()).stream("hi").unwrap();
482        let mut text = String::new();
483        while let Some(item) = stream.next().await {
484            if let Item::Event(StreamEvent::Text { text: delta, .. }) = item.unwrap() {
485                text.push_str(&delta);
486            }
487        }
488        assert_eq!(text, "Hello world");
489
490        let response = stream.finish().await.unwrap();
491        assert_eq!(response.choice.len(), 3);
492        assert_eq!(response.usage.output_tokens, Some(5));
493    }
494
495    #[tokio::test]
496    async fn sampler_options_are_accepted() {
497        let request = CompletionRequest::new("hi")
498            .reasoning(Effort::Low)
499            .top_p(0.5)
500            .seed(7);
501        assert!(model(turn()).call(request).await.is_ok());
502    }
503
504    #[tokio::test]
505    async fn an_option_the_runtime_cannot_honour_is_refused() {
506        let request = CompletionRequest::new("hi").stop(["END"]);
507        let error = model(turn()).call(request).await.unwrap_err();
508        assert!(
509            matches!(error, rig_core::ProviderError::UnsupportedOption(_)),
510            "got {error:?}"
511        );
512    }
513}