use super::{BaseProvider, ModelPricing, Provider, ProviderError, ProviderType};
use crate::config::ProviderConfig;
use crate::core::models::{RequestContext, openai::*};
use crate::utils::error::Result;
use async_trait::async_trait;
use serde_json::json;
use std::collections::HashMap;
use tracing::{debug, info};
#[derive(Debug, Clone)]
pub struct VoyageProvider {
base: BaseProvider,
pricing_cache: HashMap<String, ModelPricing>,
}
impl VoyageProvider {
pub async fn new(config: &ProviderConfig) -> Result<Self> {
let base = BaseProvider::new(config)?;
let base_url = config
.base_url
.clone()
.unwrap_or_else(|| "https://api.voyageai.com".to_string());
let provider = Self {
base: BaseProvider { base_url, ..base },
pricing_cache: Self::initialize_pricing_cache(),
};
info!(
"Voyage AI provider '{}' initialized successfully",
config.name
);
Ok(provider)
}
fn initialize_pricing_cache() -> HashMap<String, ModelPricing> {
let mut cache = HashMap::new();
cache.insert(
"voyage-large-2".to_string(),
ModelPricing {
model: "voyage-large-2".to_string(),
input_cost_per_1k: 0.00012,
output_cost_per_1k: 0.0,
currency: "USD".to_string(),
updated_at: chrono::Utc::now(),
},
);
cache.insert(
"voyage-code-2".to_string(),
ModelPricing {
model: "voyage-code-2".to_string(),
input_cost_per_1k: 0.00012,
output_cost_per_1k: 0.0,
currency: "USD".to_string(),
updated_at: chrono::Utc::now(),
},
);
cache.insert(
"voyage-2".to_string(),
ModelPricing {
model: "voyage-2".to_string(),
input_cost_per_1k: 0.0001,
output_cost_per_1k: 0.0,
currency: "USD".to_string(),
updated_at: chrono::Utc::now(),
},
);
cache.insert(
"voyage-lite-02-instruct".to_string(),
ModelPricing {
model: "voyage-lite-02-instruct".to_string(),
input_cost_per_1k: 0.00001,
output_cost_per_1k: 0.0,
currency: "USD".to_string(),
updated_at: chrono::Utc::now(),
},
);
cache
}
}
#[async_trait]
impl Provider for VoyageProvider {
fn name(&self) -> &str {
&self.base.name
}
fn provider_type(&self) -> ProviderType {
ProviderType::Custom("voyage".to_string())
}
async fn supports_model(&self, model: &str) -> bool {
self.base.is_model_supported(model) || model.starts_with("voyage")
}
async fn supports_images(&self) -> bool {
false
}
async fn supports_embeddings(&self) -> bool {
true }
async fn supports_streaming(&self) -> bool {
false
}
async fn list_models(&self) -> Result<Vec<Model>> {
let known_models = vec![
"voyage-large-2",
"voyage-code-2",
"voyage-2",
"voyage-lite-02-instruct",
];
let models = known_models
.into_iter()
.map(|model| Model {
id: model.to_string(),
object: "model".to_string(),
created: chrono::Utc::now().timestamp() as u64,
owned_by: "voyage".to_string(),
})
.collect();
Ok(models)
}
async fn health_check(&self) -> Result<()> {
debug!("Performing Voyage AI health check");
Ok(())
}
async fn chat_completion(
&self,
_request: ChatCompletionRequest,
_context: RequestContext,
) -> Result<ChatCompletionResponse> {
Err(
ProviderError::InvalidRequest("Chat completion not supported by Voyage AI".to_string())
.into(),
)
}
async fn completion(
&self,
_request: CompletionRequest,
_context: RequestContext,
) -> Result<CompletionResponse> {
Err(
ProviderError::InvalidRequest("Text completion not supported by Voyage AI".to_string())
.into(),
)
}
async fn embedding(
&self,
request: EmbeddingRequest,
_context: RequestContext,
) -> Result<EmbeddingResponse> {
debug!("Voyage AI embedding for model: {}", request.model);
let body = json!({
"model": request.model,
"input": request.input
});
let url = format!("{}/v1/embeddings", self.base.base_url);
let response = self
.base
.client
.post(&url)
.header("Authorization", format!("Bearer {}", self.base.api_key))
.header("Content-Type", "application/json")
.json(&body)
.send()
.await
.map_err(|e| ProviderError::Network(e.to_string()))?;
if !response.status().is_success() {
let status = response.status();
let error_text = response.text().await.unwrap_or_default();
return Err(match status.as_u16() {
401 => ProviderError::Authentication(error_text),
429 => ProviderError::RateLimit(error_text),
404 => ProviderError::ModelNotFound(error_text),
400 => ProviderError::InvalidRequest(error_text),
_ => ProviderError::Unknown(format!("HTTP {}: {}", status, error_text)),
}
.into());
}
let response_json: EmbeddingResponse = self.base.parse_json_response(response).await?;
Ok(response_json)
}
async fn image_generation(
&self,
_request: ImageGenerationRequest,
_context: RequestContext,
) -> Result<ImageGenerationResponse> {
Err(ProviderError::InvalidRequest(
"Image generation not supported by Voyage AI".to_string(),
)
.into())
}
async fn get_model_pricing(&self, model: &str) -> Result<ModelPricing> {
if let Some(pricing) = self.pricing_cache.get(model) {
Ok(pricing.clone())
} else {
Ok(ModelPricing {
model: model.to_string(),
input_cost_per_1k: 0.0001,
output_cost_per_1k: 0.0,
currency: "USD".to_string(),
updated_at: chrono::Utc::now(),
})
}
}
async fn calculate_cost(
&self,
model: &str,
input_tokens: u32,
_output_tokens: u32,
) -> Result<f64> {
let pricing = self.get_model_pricing(model).await?;
let input_cost = (input_tokens as f64 / 1000.0) * pricing.input_cost_per_1k;
Ok(input_cost)
}
}