Skip to main content

rig_core/providers/ollama/
embedding.rs

1//! Ollama's embedding wire, `POST /api/embed`, and its embedding models.
2//!
3//! ```
4//! use rig_core::providers::ollama::{ALL_MINILM, OllamaConfig};
5//! let model = OllamaConfig::new().client().embedding(ALL_MINILM, None);
6//! assert_eq!(model.wire.ndims, 384);
7//! ```
8
9use crate::error::EncodeError;
10use crate::operation::Embedding;
11use crate::wire::{Body, Capabilities, Descriptor, DocumentDecoder, Encoded, Framing, Mode, Wire};
12use serde::{Deserialize, Serialize};
13
14use super::{OllamaConfig, PROVIDER_NAME};
15
16/// The `all-minilm` embedding model.
17pub const ALL_MINILM: &str = "all-minilm";
18/// The `nomic-embed-text` embedding model.
19pub const NOMIC_EMBED_TEXT: &str = "nomic-embed-text";
20/// The `mxbai-embed-large` embedding model.
21pub const MXBAI_EMBED_LARGE: &str = "mxbai-embed-large";
22/// The `bge-m3` multilingual embedding model.
23pub const BGE_M3: &str = "bge-m3";
24/// The `embeddinggemma` embedding model.
25pub const EMBEDDINGGEMMA: &str = "embeddinggemma";
26/// The `qwen3-embedding` embedding model family; dimensions vary by size, so pass them explicitly.
27pub const QWEN3_EMBEDDING: &str = "qwen3-embedding";
28
29fn model_dimensions_from_identifier(identifier: &str) -> Option<usize> {
30    match identifier {
31        ALL_MINILM => Some(384),
32        NOMIC_EMBED_TEXT => Some(768),
33        MXBAI_EMBED_LARGE => Some(1024),
34        BGE_M3 => Some(1024),
35        EMBEDDINGGEMMA => Some(768),
36        _ => None,
37    }
38}
39
40#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct EmbeddingResponse {
42    pub model: String,
43    pub embeddings: Vec<Vec<f64>>,
44    pub total_duration: Option<u64>,
45    pub load_duration: Option<u64>,
46    pub prompt_eval_count: Option<u64>,
47}
48
49/// The most texts `POST /api/embed` accepts in one call.
50const MAX_DOCUMENTS: usize = 1024;
51
52impl OllamaConfig {
53    /// Build an embedding wire reporting the supplied width, known model width,
54    /// or zero if unknown. The width is metadata and is not sent to the daemon.
55    pub(crate) fn embedding(&self, model: impl Into<String>, ndims: Option<usize>) -> Embeddings {
56        let model = model.into();
57        let ndims = ndims
58            .or_else(|| model_dimensions_from_identifier(&model))
59            .unwrap_or_default();
60        Embeddings {
61            provider: self.clone(),
62            model,
63            ndims,
64        }
65    }
66}
67
68/// The embedding wire: `POST /api/embed`.
69#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
70pub struct Embeddings {
71    /// The daemon this wire speaks to.
72    pub provider: OllamaConfig,
73    /// The model to address.
74    pub model: String,
75    /// The width this wire reports, from the caller or the model's published
76    /// dimensions. `0` means neither named one.
77    pub ndims: usize,
78}
79
80impl Wire for Embeddings {
81    type Op = Embedding;
82    type Payload = crate::wire::Encoded;
83    type Frame = crate::wire::WireFrame;
84    type Event = EmbeddingResponse;
85    type Decoder<'id> = DocumentDecoder<Embedding, Self::Event>;
86    type Reassembler = crate::wire::document::Unreassembled;
87
88    fn describe(&self) -> Descriptor<'_> {
89        Descriptor::new(PROVIDER_NAME)
90            .model(self.model.as_str())
91            .capabilities(Capabilities::embedding(MAX_DOCUMENTS, self.ndims))
92    }
93
94    fn encode(&self, texts: Vec<String>, _mode: Mode) -> Result<Encoded, EncodeError> {
95        let body = serde_json::json!({ "model": self.model, "input": texts });
96        let request = self
97            .provider
98            .request(http::Method::POST, "/api/embed")
99            .body(Body::Bytes(serde_json::to_vec(&body)?))?;
100        Ok(Encoded::new(request, Framing::Whole))
101    }
102
103    /// Decodes one `/api/embed` reply.
104    fn decoder<'id>(&self) -> Self::Decoder<'id> {
105        DocumentDecoder::new(
106            |body| {
107                crate::providers::internal::wire::classify_marker_keyed_frame(body, &["embeddings"])
108            },
109            |reply| {
110                // Ollama counts the prompt it embedded and nothing else: every token
111                // of an embedding is input.
112                let usage = crate::completion::Usage {
113                    input_tokens: reply.prompt_eval_count,
114                    total_tokens: reply.prompt_eval_count,
115                    ..Default::default()
116                };
117                Ok(crate::embeddings::EmbeddingResponse {
118                    model: Some(reply.model),
119                    usage,
120                    ..crate::embeddings::EmbeddingResponse::from_vectors(reply.embeddings)
121                })
122            },
123        )
124    }
125}
126
127#[cfg(test)]
128mod tests;