Skip to main content

rig_core/providers/cohere/
embeddings.rs

1//! Cohere's text-embedding and image-embedding wires (`POST /v1/embed`),
2//! their reply types, and image-input validation.
3//!
4//! ```
5//! use rig_core::providers::cohere::embeddings::FloatEmbeddings;
6//! let vectors: FloatEmbeddings = serde_json::from_str(r#"{"float": [[0.5]]}"#)?;
7//! assert_eq!(vectors.values.len(), 1);
8//! # Ok::<(), serde_json::Error>(())
9//! ```
10
11use crate::error::{EncodeError, ProviderError};
12use crate::operation::{Embedding, ImageEmbedding};
13use crate::providers::internal::credential_header;
14use crate::providers::internal::wire::classify_reply_or_message_envelope;
15use crate::wire::{Body, Capabilities, Descriptor, DocumentDecoder, Encoded, Framing, Mode, Wire};
16use base64::{Engine as _, engine::general_purpose::STANDARD};
17use serde::{Deserialize, Serialize};
18
19use super::{CohereConfig, PROVIDER_NAME};
20
21/// `embed-v4.0` embedding model
22pub const EMBED_V4: &str = "embed-v4.0";
23/// `embed-english-v3.0` embedding model
24pub const EMBED_ENGLISH_V3: &str = "embed-english-v3.0";
25/// `embed-english-light-v3.0` embedding model
26pub const EMBED_ENGLISH_LIGHT_V3: &str = "embed-english-light-v3.0";
27/// `embed-multilingual-v3.0` embedding model
28pub const EMBED_MULTILINGUAL_V3: &str = "embed-multilingual-v3.0";
29/// `embed-multilingual-light-v3.0` embedding model
30pub const EMBED_MULTILINGUAL_LIGHT_V3: &str = "embed-multilingual-light-v3.0";
31
32pub(crate) fn model_dimensions_from_identifier(identifier: &str) -> Option<usize> {
33    match identifier {
34        EMBED_V4 => Some(1_536),
35        EMBED_ENGLISH_V3 | EMBED_MULTILINGUAL_V3 => Some(1_024),
36        EMBED_ENGLISH_LIGHT_V3 | EMBED_MULTILINGUAL_LIGHT_V3 => Some(384),
37        _ => None,
38    }
39}
40
41impl CohereConfig {
42    /// Build a text-embedding wire reporting the supplied or known model width,
43    /// or zero if unknown. This width is metadata, not a request parameter.
44    pub(crate) fn embedding(&self, model: impl Into<String>, ndims: Option<usize>) -> Embeddings {
45        let model = model.into();
46        let ndims = ndims
47            .or_else(|| model_dimensions_from_identifier(&model))
48            .unwrap_or_default();
49        Embeddings {
50            provider: self.clone(),
51            model,
52            ndims,
53            input_type: DEFAULT_INPUT_TYPE.to_owned(),
54        }
55    }
56
57    /// The image-embedding wire.
58    ///
59    /// Cohere Embed v3 embeds images with one fixed model, so this wire
60    /// names no model.
61    pub(crate) fn image_embedding(&self) -> ImageEmbeddings {
62        ImageEmbeddings {
63            provider: self.clone(),
64        }
65    }
66
67    /// One request, authenticated and typed as JSON.
68    pub(super) fn post(&self, path: &str) -> http::request::Builder {
69        credential_header(
70            http::Request::post(format!("{}{path}", self.base_url))
71                .header(http::header::CONTENT_TYPE, "application/json"),
72            "authorization",
73            &format!("Bearer {}", self.api_key.expose()),
74        )
75    }
76}
77
78/// Default retrieval role for embeddings of stored document chunks.
79const DEFAULT_INPUT_TYPE: &str = "search_document";
80
81/// The most texts Cohere embeds in one `/v1/embed` call.
82const MAX_DOCUMENTS: usize = 96;
83
84/// The width Cohere's image embeddings come back at.
85const IMAGE_NDIMS: usize = 1_024;
86
87/// The text-embedding wire: `POST /v1/embed`.
88#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
89pub struct Embeddings {
90    /// The provider this wire speaks to.
91    pub provider: CohereConfig,
92    /// The model to address.
93    pub model: String,
94    /// The width this wire reports, from the caller or the model's published
95    /// dimensions. `0` means neither named one.
96    pub ndims: usize,
97    /// Cohere's retrieval prompt: `search_document` for stored chunks,
98    /// `search_query` for queries, `classification`, `clustering`.
99    pub input_type: String,
100}
101
102impl Embeddings {
103    /// Embed for a different purpose than storing chunks.
104    pub fn with_input_type(mut self, input_type: impl Into<String>) -> Self {
105        self.input_type = input_type.into();
106        self
107    }
108}
109
110impl Wire for Embeddings {
111    type Op = Embedding;
112    type Payload = crate::wire::Encoded;
113    type Frame = crate::wire::WireFrame;
114    type Event = Result<EmbeddingResponse, String>;
115    type Decoder<'id> = DocumentDecoder<Embedding, Self::Event>;
116    type Reassembler = crate::wire::document::Unreassembled;
117
118    fn describe(&self) -> Descriptor<'_> {
119        Descriptor::new(PROVIDER_NAME)
120            .model(self.model.as_str())
121            .capabilities(Capabilities::embedding(MAX_DOCUMENTS, self.ndims))
122    }
123
124    fn encode(&self, texts: Vec<String>, _mode: Mode) -> Result<Encoded, EncodeError> {
125        let body = crate::providers::internal::object! {
126            "model": self.model.as_str(),
127            "texts": texts,
128            "input_type": self.input_type.as_str(),
129        };
130        let request = self
131            .provider
132            .post("/v1/embed")
133            .body(Body::Bytes(serde_json::to_vec(&body)?))?;
134        Ok(Encoded::new(request, Framing::Whole))
135    }
136
137    /// The vectors, or the error envelope Cohere can answer a **200** with.
138    fn decoder<'id>(&self) -> Self::Decoder<'id> {
139        DocumentDecoder::new(
140            |body| classify_reply_or_message_envelope(body, "embeddings"),
141            |reply| {
142                let reply = reply.map_err(ProviderError::from_provider_body)?;
143                // Cohere's `/v1/embed` reply names no model.
144                Ok(crate::embeddings::EmbeddingResponse {
145                    response_id: Some(reply.id),
146                    usage: usage_of(reply.meta.as_ref()),
147                    ..crate::embeddings::EmbeddingResponse::from_vectors(reply.embeddings)
148                })
149            },
150        )
151    }
152}
153
154/// The image-embedding wire: `POST /v1/embed`, one image per request.
155///
156/// Cohere Embed v3 accepts a single image per call, so the wire's batch limit
157/// is one image.
158#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
159pub struct ImageEmbeddings {
160    /// The provider this wire speaks to.
161    pub provider: CohereConfig,
162}
163
164impl Wire for ImageEmbeddings {
165    type Op = ImageEmbedding;
166    type Payload = crate::wire::Encoded;
167    type Frame = crate::wire::WireFrame;
168    type Event = Result<ImageEmbeddingResponse, String>;
169    type Decoder<'id> = DocumentDecoder<ImageEmbedding, Self::Event>;
170    type Reassembler = crate::wire::document::Unreassembled;
171
172    fn describe(&self) -> Descriptor<'_> {
173        Descriptor::new(PROVIDER_NAME)
174            .model(EMBED_ENGLISH_V3)
175            .capabilities(Capabilities::embedding(1, IMAGE_NDIMS))
176    }
177
178    fn encode(&self, images: Vec<Vec<u8>>, _mode: Mode) -> Result<Encoded, EncodeError> {
179        // The wire's batch limit is one image: a caller splits larger
180        // batches into one call per image.
181        let [image] = images.as_slice() else {
182            return Err(EncodeError::request(format!(
183                "Cohere embeds one image per request, not {}",
184                images.len()
185            )));
186        };
187        let media_type = validate_image(image)?;
188        let body = serde_json::json!({
189            "model": EMBED_ENGLISH_V3,
190            "images": [image_data_url(image, media_type)],
191            "input_type": "image",
192            "embedding_types": ["float"],
193        });
194        let request = self
195            .provider
196            .post("/v1/embed")
197            .body(Body::Bytes(serde_json::to_vec(&body)?))?;
198        Ok(Encoded::new(request, Framing::Whole))
199    }
200
201    /// The vector, or the error envelope Cohere can answer a **200** with.
202    fn decoder<'id>(&self) -> Self::Decoder<'id> {
203        DocumentDecoder::new(
204            |body| classify_reply_or_message_envelope(body, "embeddings"),
205            |reply| {
206                let reply = reply.map_err(ProviderError::from_provider_body)?;
207                // Each request carries one image, so any other vector count is invalid.
208                let [vector] = reply.embeddings.values.as_slice() else {
209                    return Err(ProviderError::Response(format!(
210                        "Expected 1 image embedding, got {}",
211                        reply.embeddings.values.len()
212                    )));
213                };
214                // The fold names the input: an image has no text, and its bytes
215                // must never travel back in a response.
216                Ok(crate::embeddings::EmbeddingResponse {
217                    usage: usage_of(reply.meta.as_ref()),
218                    response_id: reply.id,
219                    ..crate::embeddings::EmbeddingResponse::from_vectors([vector.clone()])
220                })
221            },
222        )
223    }
224}
225
226const MAX_IMAGE_BYTES: usize = 5_000_000;
227
228/// The usage a reply's `meta` bills, or none.
229fn usage_of(meta: Option<&Meta>) -> crate::completion::Usage {
230    meta.map(|meta| meta.billed_units.to_usage())
231        .unwrap_or_default()
232}
233
234/// One `/v1/embed` reply, as far as rig reads it.
235#[derive(Debug, Clone, Serialize, Deserialize)]
236pub struct EmbeddingResponse {
237    pub id: String,
238    pub embeddings: Vec<Vec<f64>>,
239    pub meta: Option<Meta>,
240}
241
242/// A reply's `meta`: what the call billed.
243#[derive(Debug, Clone, Serialize, Deserialize)]
244pub struct Meta {
245    #[serde(default)]
246    pub billed_units: BilledUnits,
247}
248
249/// Cohere's `meta.billed_units`. Token counters are absent when the request
250/// was not billed in tokens (image embeds bill `images`), so they are
251/// `Option`; the non-token counters default to zero.
252#[derive(Debug, Clone, Default, Serialize, Deserialize)]
253pub struct BilledUnits {
254    #[serde(skip_serializing_if = "Option::is_none")]
255    pub input_tokens: Option<u32>,
256    #[serde(skip_serializing_if = "Option::is_none")]
257    pub output_tokens: Option<u32>,
258    #[serde(default)]
259    pub search_units: u32,
260    #[serde(default)]
261    pub classifications: u32,
262    #[serde(default)]
263    pub images: u32,
264}
265
266/// One Cohere `/v1/embed` answer for a single image, one per input image:
267/// Cohere Embed v3 accepts a single image per call.
268#[derive(Debug, Clone, Serialize, Deserialize)]
269pub struct ImageEmbeddingResponse {
270    pub id: Option<String>,
271    pub embeddings: FloatEmbeddings,
272    pub meta: Option<Meta>,
273}
274
275#[derive(Debug, Clone, Serialize, Deserialize)]
276pub struct FloatEmbeddings {
277    #[serde(rename = "float")]
278    pub values: Vec<Vec<f64>>,
279}
280
281impl BilledUnits {
282    /// Maps the billed token counters straight through; `total_tokens` is
283    /// the sum of whichever counters Cohere sent (an embed bills input only,
284    /// so it reports `input_tokens` and `total_tokens`, no `output_tokens`).
285    pub(super) fn to_usage(&self) -> crate::completion::Usage {
286        let input_tokens = self.input_tokens.map(u64::from);
287        let output_tokens = self.output_tokens.map(u64::from);
288        let total_tokens = match (input_tokens, output_tokens) {
289            (None, None) => None,
290            (input, output) => Some(input.unwrap_or(0) + output.unwrap_or(0)),
291        };
292        crate::completion::Usage {
293            input_tokens,
294            output_tokens,
295            total_tokens,
296            ..Default::default()
297        }
298    }
299}
300
301#[derive(Debug, thiserror::Error)]
302pub(super) enum ImageInputError {
303    #[error("Cohere image embeddings support PNG, JPEG, WebP, or GIF file bytes")]
304    UnsupportedFormat,
305    #[error("Cohere image embeddings accept at most 5 MB per image; received {actual_bytes} bytes")]
306    TooLarge { actual_bytes: usize },
307}
308
309/// Detect an accepted image media type. Returns a document error for unsupported
310/// formats or inputs exceeding 5,000,000 bytes.
311pub(super) fn validate_image(bytes: &[u8]) -> Result<&'static str, EncodeError> {
312    if bytes.len() > MAX_IMAGE_BYTES {
313        return Err(EncodeError::request(ImageInputError::TooLarge {
314            actual_bytes: bytes.len(),
315        }));
316    }
317
318    crate::embeddings::image_media_type(bytes)
319        .ok_or_else(|| EncodeError::request(ImageInputError::UnsupportedFormat))
320}
321
322pub(super) fn image_data_url(bytes: &[u8], media_type: &str) -> String {
323    format!("data:{media_type};base64,{}", STANDARD.encode(bytes))
324}
325
326#[cfg(test)]
327mod tests;