Skip to main content

rig_core/providers/voyageai/
wire.rs

1//! Voyage AI configuration and embedding and reranking endpoint wires.
2//!
3//! ```no_run
4//! use rig_core::providers::voyageai::{VoyageAi, VOYAGE_3_5};
5//! let wire = VoyageAi::from_env()?.embedding(VOYAGE_3_5, None);
6//! # Ok::<(), Box<dyn std::error::Error>>(())
7//! ```
8
9use crate::client::env::{self, EnvError};
10use crate::error::EncodeError;
11use crate::error::ProviderError;
12use crate::operation::{Embedding, Rerank as RerankOp, RerankRequest};
13use crate::providers::internal::{credential_header, set_fields};
14use crate::rerank::{RerankResponse, RerankResult};
15use crate::wire::{
16    Body, Capabilities, Descriptor, DocumentDecoder, Encoded, Framing, Mode, Secret, Wire,
17};
18use serde::{Deserialize, Serialize};
19
20use super::{
21    EmbeddingResponse as VoyageEmbeddingResponse, RerankApiResponse, VOYAGEAI_API_BASE_URL,
22    model_dimensions_from_identifier,
23};
24
25/// The provider descriptor name, as records and telemetry spell it.
26const PROVIDER_NAME: &str = "voyageai";
27
28/// The environment variable carrying the API key.
29const API_KEY_ENV: &str = "VOYAGE_API_KEY";
30
31/// The most texts `POST /embeddings` accepts in one call.
32const MAX_DOCUMENTS: usize = 1024;
33
34/// The most documents `POST /rerank` orders in one call.
35const MAX_RERANK_DOCUMENTS: usize = 1000;
36
37/// The settings of a Voyage AI provider: serializable, and the credential
38/// is never serialized. [`connect`](Self::connect) puts it on a transport as
39/// a [`VoyageAi`](super::VoyageAi) client.
40#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
41pub struct VoyageAiConfig {
42    /// The API key, sent as `Authorization: Bearer`.
43    pub api_key: Secret,
44    /// The API root, without a trailing slash.
45    pub base_url: String,
46}
47
48impl VoyageAiConfig {
49    /// Voyage AI with default settings.
50    pub fn new(api_key: impl Into<Secret>) -> Self {
51        Self {
52            api_key: api_key.into(),
53            base_url: VOYAGEAI_API_BASE_URL.to_owned(),
54        }
55    }
56
57    /// Voyage AI from `VOYAGE_API_KEY`.
58    pub fn from_env() -> Result<Self, EnvError> {
59        Ok(Self::new(env::required(API_KEY_ENV)?))
60    }
61
62    /// Point the wires at another API root.
63    pub fn with_base_url(mut self, base_url: impl AsRef<str>) -> Self {
64        self.base_url = base_url.as_ref().trim_end_matches('/').to_owned();
65        self
66    }
67
68    /// Build an embedding wire reporting `ndims`, or the known model width,
69    /// or zero if unknown. This does not send an output-dimension override;
70    /// use [`Embeddings::with_output_dimension`] for that.
71    pub(crate) fn embedding(&self, model: impl Into<String>, ndims: Option<usize>) -> Embeddings {
72        let model = model.into();
73        let ndims = ndims
74            .or_else(|| model_dimensions_from_identifier(&model))
75            .unwrap_or_default();
76        Embeddings {
77            provider: self.clone(),
78            model,
79            ndims,
80            input_type: None,
81            truncation: None,
82            output_dimension: None,
83        }
84    }
85
86    /// The rerank wire for `model`.
87    pub(crate) fn rerank(&self, model: impl Into<String>) -> Rerank {
88        Rerank {
89            provider: self.clone(),
90            model: model.into(),
91            top_k: None,
92            return_documents: false,
93            truncation: None,
94        }
95    }
96
97    /// One request, authenticated and typed as JSON.
98    fn post(&self, path: &str) -> http::request::Builder {
99        credential_header(
100            http::Request::post(format!("{}{path}", self.base_url))
101                .header(http::header::CONTENT_TYPE, "application/json"),
102            "authorization",
103            &format!("Bearer {}", self.api_key.expose()),
104        )
105    }
106}
107
108/// The embedding wire: `POST /embeddings`.
109///
110/// Every option defaults to `None`, which is Voyage's own server default:
111/// no retrieval prompt, truncation enabled, and the model's default output
112/// dimension.
113#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
114pub struct Embeddings {
115    /// The provider this wire speaks to.
116    pub provider: VoyageAiConfig,
117    /// The model to address.
118    pub model: String,
119    /// The width this wire reports, from the caller or the model's published
120    /// dimensions. `0` means neither named one.
121    pub ndims: usize,
122    /// Prepends a retrieval prompt to the input text: `"document"` when
123    /// embedding stored chunks, `"query"` when embedding search queries.
124    /// Embeddings produced with and without it are compatible.
125    pub input_type: Option<String>,
126    /// Whether to truncate inputs longer than the model's context. Voyage's
127    /// server default is `true`.
128    pub truncation: Option<bool>,
129    /// Dimensionality of the returned vectors, when overriding the model's
130    /// default output dimension.
131    pub output_dimension: Option<usize>,
132}
133
134impl Embeddings {
135    /// Prepend Voyage's retrieval prompt for this input's role.
136    pub fn with_input_type(mut self, input_type: impl Into<String>) -> Self {
137        self.input_type = Some(input_type.into());
138        self
139    }
140
141    /// Set whether overlong inputs are truncated (`true`) or rejected (`false`).
142    pub fn with_truncation(mut self, truncation: bool) -> Self {
143        self.truncation = Some(truncation);
144        self
145    }
146
147    /// Ask Voyage for vectors of this width.
148    ///
149    /// This is the width the request carries; [`Self::ndims`] is the width
150    /// the wire reports to a vector store, so they are set together.
151    pub fn with_output_dimension(mut self, output_dimension: usize) -> Self {
152        self.output_dimension = Some(output_dimension);
153        self.ndims = output_dimension;
154        self
155    }
156}
157
158impl Wire for Embeddings {
159    type Op = Embedding;
160    type Payload = crate::wire::Encoded;
161    type Frame = crate::wire::WireFrame;
162    type Event = VoyageEmbeddingResponse;
163    type Decoder<'id> = DocumentDecoder<Embedding, Self::Event>;
164    type Reassembler = crate::wire::document::Unreassembled;
165
166    fn describe(&self) -> Descriptor<'_> {
167        Descriptor::new(PROVIDER_NAME)
168            .model(self.model.as_str())
169            .capabilities(Capabilities::embedding(MAX_DOCUMENTS, self.ndims))
170    }
171
172    fn encode(&self, texts: Vec<String>, _mode: Mode) -> Result<Encoded, EncodeError> {
173        let body = set_fields([
174            ("model", Some(serde_json::json!(self.model))),
175            ("input", Some(serde_json::Value::from(texts))),
176            (
177                "input_type",
178                self.input_type.as_ref().map(|v| serde_json::json!(v)),
179            ),
180            ("truncation", self.truncation.map(serde_json::Value::from)),
181            (
182                "output_dimension",
183                self.output_dimension.map(|v| serde_json::json!(v)),
184            ),
185        ]);
186        let request = self
187            .provider
188            .post("/embeddings")
189            .body(Body::Bytes(serde_json::to_vec(&body)?))?;
190        Ok(Encoded::new(request, Framing::Whole))
191    }
192
193    /// Decodes one `/embeddings` reply.
194    fn decoder<'id>(&self) -> Self::Decoder<'id> {
195        DocumentDecoder::new(
196            |body| crate::providers::internal::wire::classify_marker_keyed_frame(body, &["data"]),
197            |reply| {
198                let usage = input_usage(reply.usage.total_tokens);
199                let vectors = reply.data.into_iter().map(|embedding| embedding.embedding);
200                Ok(crate::embeddings::EmbeddingResponse {
201                    model: Some(reply.model),
202                    usage,
203                    ..crate::embeddings::EmbeddingResponse::from_vectors(vectors)
204                })
205            },
206        )
207    }
208}
209
210/// The rerank wire: `POST /rerank`.
211#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
212pub struct Rerank {
213    /// The provider this wire speaks to.
214    pub provider: VoyageAiConfig,
215    /// The model to address.
216    pub model: String,
217    /// Return only the `top_k` most relevant documents. `None` returns them
218    /// all.
219    pub top_k: Option<usize>,
220    /// Whether the reply echoes each document's text back.
221    pub return_documents: bool,
222    /// Whether to truncate documents longer than the model's context.
223    /// Voyage's server default is `true`.
224    pub truncation: Option<bool>,
225}
226
227impl Rerank {
228    /// Set whether overlong documents are truncated (`true`) or rejected (`false`).
229    pub fn with_truncation(mut self, truncation: bool) -> Self {
230        self.truncation = Some(truncation);
231        self
232    }
233}
234
235impl Wire for Rerank {
236    type Op = RerankOp;
237    type Payload = crate::wire::Encoded;
238    type Frame = crate::wire::WireFrame;
239    type Event = Result<RerankApiResponse, String>;
240    type Decoder<'id> = DocumentDecoder<RerankOp, Self::Event>;
241    type Reassembler = crate::wire::document::Unreassembled;
242
243    fn describe(&self) -> Descriptor<'_> {
244        Descriptor::new(PROVIDER_NAME)
245            .model(self.model.as_str())
246            .capabilities(Capabilities::rerank(MAX_RERANK_DOCUMENTS))
247    }
248
249    fn encode(&self, request: RerankRequest, _mode: Mode) -> Result<Encoded, EncodeError> {
250        let body = set_fields([
251            ("query", Some(serde_json::Value::from(request.query))),
252            (
253                "documents",
254                Some(serde_json::Value::from(request.documents)),
255            ),
256            ("model", Some(serde_json::json!(self.model))),
257            ("top_k", self.top_k.map(serde_json::Value::from)),
258            (
259                "return_documents",
260                Some(serde_json::Value::from(self.return_documents)),
261            ),
262            ("truncation", self.truncation.map(serde_json::Value::from)),
263        ]);
264        let request = self
265            .provider
266            .post("/rerank")
267            .body(Body::Bytes(serde_json::to_vec(&body)?))?;
268        Ok(Encoded::new(request, Framing::Whole))
269    }
270
271    /// Decodes one `/rerank` reply.
272    /// The ordering, or the error envelope Voyage can answer a **200** with.
273    fn decoder<'id>(&self) -> Self::Decoder<'id> {
274        DocumentDecoder::new(
275            |body| {
276                crate::providers::internal::wire::classify_reply_or_message_envelope(body, "data")
277            },
278            |reply| {
279                let reply = reply.map_err(ProviderError::from_provider_body)?;
280                let usage = input_usage(reply.usage.total_tokens);
281                let results = reply
282                    .data
283                    .into_iter()
284                    .map(|result| RerankResult {
285                        index: result.index,
286                        document: result.document,
287                        relevance_score: result.relevance_score,
288                    })
289                    .collect();
290                Ok(RerankResponse {
291                    model: Some(reply.model),
292                    usage,
293                    ..RerankResponse::new(results)
294                })
295            },
296        )
297    }
298}
299
300/// Voyage reports one count, and every token of an embedding or a rerank
301/// is input.
302fn input_usage(total_tokens: usize) -> crate::completion::Usage {
303    crate::completion::Usage {
304        input_tokens: Some(total_tokens as u64),
305        total_tokens: Some(total_tokens as u64),
306        ..Default::default()
307    }
308}
309
310#[cfg(test)]
311mod tests;