rig_core/providers/voyageai/
wire.rs1use 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
25const PROVIDER_NAME: &str = "voyageai";
27
28const API_KEY_ENV: &str = "VOYAGE_API_KEY";
30
31const MAX_DOCUMENTS: usize = 1024;
33
34const MAX_RERANK_DOCUMENTS: usize = 1000;
36
37#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
41pub struct VoyageAiConfig {
42 pub api_key: Secret,
44 pub base_url: String,
46}
47
48impl VoyageAiConfig {
49 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 pub fn from_env() -> Result<Self, EnvError> {
59 Ok(Self::new(env::required(API_KEY_ENV)?))
60 }
61
62 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 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 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 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
114pub struct Embeddings {
115 pub provider: VoyageAiConfig,
117 pub model: String,
119 pub ndims: usize,
122 pub input_type: Option<String>,
126 pub truncation: Option<bool>,
129 pub output_dimension: Option<usize>,
132}
133
134impl Embeddings {
135 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 pub fn with_truncation(mut self, truncation: bool) -> Self {
143 self.truncation = Some(truncation);
144 self
145 }
146
147 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 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
212pub struct Rerank {
213 pub provider: VoyageAiConfig,
215 pub model: String,
217 pub top_k: Option<usize>,
220 pub return_documents: bool,
222 pub truncation: Option<bool>,
225}
226
227impl Rerank {
228 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 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
300fn 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;