rig_core/providers/ollama/
embedding.rs1use 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
16pub const ALL_MINILM: &str = "all-minilm";
18pub const NOMIC_EMBED_TEXT: &str = "nomic-embed-text";
20pub const MXBAI_EMBED_LARGE: &str = "mxbai-embed-large";
22pub const BGE_M3: &str = "bge-m3";
24pub const EMBEDDINGGEMMA: &str = "embeddinggemma";
26pub 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
49const MAX_DOCUMENTS: usize = 1024;
51
52impl OllamaConfig {
53 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
70pub struct Embeddings {
71 pub provider: OllamaConfig,
73 pub model: String,
75 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 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 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;