rig_core/providers/cohere/
embeddings.rs1use 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
21pub const EMBED_V4: &str = "embed-v4.0";
23pub const EMBED_ENGLISH_V3: &str = "embed-english-v3.0";
25pub const EMBED_ENGLISH_LIGHT_V3: &str = "embed-english-light-v3.0";
27pub const EMBED_MULTILINGUAL_V3: &str = "embed-multilingual-v3.0";
29pub 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 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 pub(crate) fn image_embedding(&self) -> ImageEmbeddings {
62 ImageEmbeddings {
63 provider: self.clone(),
64 }
65 }
66
67 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
78const DEFAULT_INPUT_TYPE: &str = "search_document";
80
81const MAX_DOCUMENTS: usize = 96;
83
84const IMAGE_NDIMS: usize = 1_024;
86
87#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
89pub struct Embeddings {
90 pub provider: CohereConfig,
92 pub model: String,
94 pub ndims: usize,
97 pub input_type: String,
100}
101
102impl Embeddings {
103 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 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 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
159pub struct ImageEmbeddings {
160 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 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 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 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 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
228fn usage_of(meta: Option<&Meta>) -> crate::completion::Usage {
230 meta.map(|meta| meta.billed_units.to_usage())
231 .unwrap_or_default()
232}
233
234#[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#[derive(Debug, Clone, Serialize, Deserialize)]
244pub struct Meta {
245 #[serde(default)]
246 pub billed_units: BilledUnits,
247}
248
249#[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#[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 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
309pub(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;