Skip to main content

rig_core/providers/gemini/
embedding.rs

1//! Batch text embeddings through the [Gemini API](https://ai.google.dev/api/embeddings).
2//!
3//! ```no_run
4//! use rig_core::providers::gemini::{Gemini, embedding::EMBEDDING_001};
5//!
6//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
7//! let model = Gemini::from_env()?.embedding(EMBEDDING_001, None);
8//! # Ok(())
9//! # }
10//! ```
11
12use serde_json::{Map, Value, json};
13
14use crate::embeddings;
15use crate::error::EncodeError;
16use crate::providers::internal::wire::classify_marker_keyed_frame;
17use crate::wire::{Body, Capabilities, Descriptor, DocumentDecoder, Encoded, Framing, Mode, Wire};
18
19/// `gemini-embedding-001` embedding model (3072 dimensions by default)
20pub const EMBEDDING_001: &str = "gemini-embedding-001";
21/// `text-embedding-004` embedding model (768 dimensions by default)
22pub const EMBEDDING_004: &str = "text-embedding-004";
23
24/// The width the Gemini API embeds `model` at when no width is asked for:
25/// 3072 for [`EMBEDDING_001`], and 768 for [`EMBEDDING_004`] and any model
26/// rig does not know. Every Gemini embedding wire defaults to it.
27///
28/// See <https://ai.google.dev/gemini-api/docs/models#gemini-embedding>
29pub fn default_ndims(model: &str) -> usize {
30    match model {
31        EMBEDDING_001 => 3072,
32        _ => 768,
33    }
34}
35
36/// Gemini's batch embedding endpoint.
37///
38/// `POST /v1beta/models/{model}:batchEmbedContents`.
39#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
40pub struct Embeddings {
41    /// The provider this wire speaks to.
42    pub provider: super::GeminiConfig,
43    /// The embedding model, as the path names it.
44    pub model: String,
45    /// The `output_dimensionality` every document in the batch asks for.
46    pub ndims: usize,
47}
48
49impl Embeddings {
50    /// Build a wire for `model` with the requested output dimensions, or
51    /// else [`default_ndims`].
52    pub fn new(
53        provider: super::GeminiConfig,
54        model: impl Into<String>,
55        ndims: Option<usize>,
56    ) -> Self {
57        let model = model.into();
58        let ndims = ndims.unwrap_or_else(|| default_ndims(&model));
59        Self {
60            provider,
61            model,
62            ndims,
63        }
64    }
65}
66
67impl Wire for Embeddings {
68    type Op = crate::operation::Embedding;
69    type Payload = crate::wire::Encoded;
70    type Frame = crate::wire::WireFrame;
71    type Event = gemini_api_types::EmbeddingResponse;
72    type Decoder<'id> = DocumentDecoder<Self::Op, Self::Event>;
73    type Reassembler = crate::wire::document::Unreassembled;
74
75    fn describe(&self) -> Descriptor<'_> {
76        Descriptor::new(super::PROVIDER_NAME)
77            .model(self.model.as_str())
78            // `batchEmbedContents` refuses more than 100 requests.
79            .capabilities(Capabilities::embedding(100, self.ndims))
80    }
81
82    fn encode(&self, request: Vec<String>, _mode: Mode) -> Result<Encoded, EncodeError> {
83        let model = format!("models/{}", self.model);
84        let requests = request.iter().map(|doc| {
85            json!({
86                "model": model,
87                "content": { "parts": [{ "text": doc }] },
88                "output_dimensionality": self.ndims,
89            })
90        });
91        let body = Value::Object(Map::from_iter([(
92            "requests".to_owned(),
93            Value::Array(requests.collect()),
94        )]));
95
96        // Avoid allocating formatted batch JSON unless tracing consumes it.
97        if tracing::enabled!(target: "rig::embedding", tracing::Level::TRACE)
98            && let Ok(pretty_body) = serde_json::to_string_pretty(&body)
99        {
100            tracing::trace!(
101                target: "rig::embedding",
102                "Sending embedding request to Gemini API {pretty_body}"
103            );
104        }
105
106        let path = format!("/v1beta/models/{}:batchEmbedContents", self.model);
107        let request = self
108            .provider
109            .post_json(&path, Body::Bytes(serde_json::to_vec(&body)?))?;
110        // `batchEmbedContents` has no streaming variant, so a streamed call
111        // sends the same bytes and reads the same whole reply.
112        Ok(Encoded::new(request, Framing::Whole))
113    }
114
115    fn decoder<'id>(&self) -> Self::Decoder<'id> {
116        DocumentDecoder::new(
117            |body| classify_marker_keyed_frame(body, &["embeddings"]),
118            |reply| {
119                let vectors = reply
120                    .embeddings
121                    .into_iter()
122                    .map(|embedding| embedding.values);
123                // Gemini supplies no usage or response id; the driver attaches the raw body.
124                Ok(embeddings::EmbeddingResponse::from_vectors(vectors))
125            },
126        )
127    }
128}
129
130/// Request and response types for [Gemini embeddings](https://ai.google.dev/api/embeddings).
131///
132/// ```
133/// use rig_core::providers::gemini::embedding::gemini_api_types::EmbeddingValues;
134///
135/// let vector = EmbeddingValues { values: vec![1.into(), 2.into()] };
136/// ```
137pub mod gemini_api_types {
138    use serde::{Deserialize, Serialize};
139
140    #[derive(Debug, Clone, Serialize, Deserialize)]
141    pub struct EmbeddingResponse {
142        pub embeddings: Vec<EmbeddingValues>,
143    }
144
145    #[derive(Debug, Clone, Serialize, Deserialize)]
146    pub struct EmbeddingValues {
147        #[serde(default)]
148        pub values: Vec<f64>,
149    }
150}
151
152impl super::GeminiConfig {
153    /// The `batchEmbedContents` embedding wire. `ndims` defaults from the
154    /// model identifier.
155    pub(crate) fn embedding(&self, model: impl Into<String>, ndims: Option<usize>) -> Embeddings {
156        Embeddings::new(self.clone(), model, ndims)
157    }
158}
159
160#[cfg(test)]
161mod tests;