use anyhow::Result;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::time::Duration;
pub mod anthropic;
pub mod deepseek;
pub mod ollama;
pub mod openai;
pub use anthropic::AnthropicProvider;
pub use deepseek::DeepSeekProvider;
pub use ollama::OllamaProvider;
pub use openai::OpenAIProvider;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GenerationOptions {
pub max_tokens: Option<u32>,
pub temperature: Option<f32>,
pub timeout: Option<Duration>,
}
impl Default for GenerationOptions {
fn default() -> Self {
Self {
max_tokens: Some(4000),
temperature: Some(0.7),
timeout: Some(Duration::from_secs(60)),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProviderHealthStatus {
pub provider: String,
pub healthy: bool,
pub connection: ConnectionStatus,
pub authentication: AuthStatus,
pub response_time_ms: Option<u64>,
pub models_available: Option<usize>,
pub models: Vec<ModelInfo>,
pub messages: Vec<String>,
pub metadata: std::collections::HashMap<String, String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ConnectionStatus {
Connected,
Failed,
Untested,
}
impl ConnectionStatus {
pub fn is_ok(&self) -> bool {
matches!(self, Self::Connected)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AuthStatus {
Authenticated,
Failed,
NotRequired,
NotConfigured,
Untested,
}
impl AuthStatus {
pub fn is_ok(&self) -> bool {
matches!(self, Self::Authenticated | Self::NotRequired)
}
}
impl ProviderHealthStatus {
pub fn new(provider: impl Into<String>) -> Self {
Self {
provider: provider.into(),
healthy: false,
connection: ConnectionStatus::Untested,
authentication: AuthStatus::Untested,
response_time_ms: None,
models_available: None,
models: Vec::new(),
messages: Vec::new(),
metadata: std::collections::HashMap::new(),
}
}
pub fn update_health(&mut self) {
self.healthy = self.connection.is_ok() && self.authentication.is_ok();
}
pub fn add_message(&mut self, message: impl Into<String>) {
self.messages.push(message.into());
}
pub fn add_metadata(&mut self, key: impl Into<String>, value: impl Into<String>) {
self.metadata.insert(key.into(), value.into());
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelInfo {
pub id: String,
pub name: String,
pub provider: String,
pub size: Option<u64>,
#[serde(default)]
pub capabilities: Vec<String>,
pub context_window: Option<u32>,
}
impl ModelInfo {
pub fn new(id: String, name: String, provider: String) -> Self {
Self {
id,
name,
provider,
size: None,
capabilities: Vec::new(),
context_window: None,
}
}
pub fn with_size(mut self, size: u64) -> Self {
self.size = Some(size);
self
}
pub fn with_context_window(mut self, tokens: u32) -> Self {
self.context_window = Some(tokens);
self
}
pub fn with_capability(mut self, capability: impl Into<String>) -> Self {
self.capabilities.push(capability.into());
self
}
pub fn size_human_readable(&self) -> String {
match self.size {
None => "Unknown".to_string(),
Some(bytes) => {
const GB: u64 = 1_073_741_824;
const MB: u64 = 1_048_576;
const KB: u64 = 1_024;
if bytes >= GB {
format!("{:.2} GB", bytes as f64 / GB as f64)
} else if bytes >= MB {
format!("{:.2} MB", bytes as f64 / MB as f64)
} else if bytes >= KB {
format!("{:.2} KB", bytes as f64 / KB as f64)
} else {
format!("{} B", bytes)
}
}
}
}
}
#[async_trait]
pub trait LLMProvider: Send + Sync {
fn name(&self) -> &str;
fn is_available(&self) -> bool;
async fn generate(&self, prompt: &str, options: GenerationOptions) -> Result<String>;
async fn list_models(&self) -> Result<Vec<ModelInfo>>;
fn estimate_cost(&self, _prompt: &str) -> Option<f64> {
None }
async fn health_check(&self) -> Result<ProviderHealthStatus>;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_generation_options_default() {
let options = GenerationOptions::default();
assert_eq!(options.max_tokens, Some(4000));
assert_eq!(options.temperature, Some(0.7));
assert!(options.timeout.is_some());
}
#[test]
fn test_model_info_builder() {
let model = ModelInfo::new(
"test-model".to_string(),
"Test Model".to_string(),
"test-provider".to_string(),
)
.with_size(1_073_741_824) .with_context_window(8192)
.with_capability("code-generation")
.with_capability("chat");
assert_eq!(model.id, "test-model");
assert_eq!(model.name, "Test Model");
assert_eq!(model.provider, "test-provider");
assert_eq!(model.size, Some(1_073_741_824));
assert_eq!(model.context_window, Some(8192));
assert_eq!(model.capabilities.len(), 2);
}
#[test]
fn test_model_info_size_formatting() {
let model_gb = ModelInfo::new("test".to_string(), "Test".to_string(), "test".to_string())
.with_size(5_368_709_120); assert_eq!(model_gb.size_human_readable(), "5.00 GB");
let model_mb = ModelInfo::new("test".to_string(), "Test".to_string(), "test".to_string())
.with_size(157_286_400); assert_eq!(model_mb.size_human_readable(), "150.00 MB");
let model_kb = ModelInfo::new("test".to_string(), "Test".to_string(), "test".to_string())
.with_size(10_240); assert_eq!(model_kb.size_human_readable(), "10.00 KB");
let model_none = ModelInfo::new("test".to_string(), "Test".to_string(), "test".to_string());
assert_eq!(model_none.size_human_readable(), "Unknown");
}
#[test]
fn test_generation_options_serialization() {
let options = GenerationOptions {
max_tokens: Some(2000),
temperature: Some(0.5),
timeout: Some(Duration::from_secs(30)),
};
let json = serde_json::to_string(&options).unwrap();
let deserialized: GenerationOptions = serde_json::from_str(&json).unwrap();
assert_eq!(deserialized.max_tokens, Some(2000));
assert_eq!(deserialized.temperature, Some(0.5));
}
}