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 AI21Provider {
base: BaseProvider,
pricing_cache: HashMap<String, ModelPricing>,
}
impl AI21Provider {
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.ai21.com".to_string());
let provider = Self {
base: BaseProvider { base_url, ..base },
pricing_cache: Self::initialize_pricing_cache(),
};
info!("AI21 provider '{}' initialized successfully", config.name);
Ok(provider)
}
fn initialize_pricing_cache() -> HashMap<String, ModelPricing> {
let mut cache = HashMap::new();
cache.insert(
"j2-ultra".to_string(),
ModelPricing {
model: "j2-ultra".to_string(),
input_cost_per_1k: 0.015,
output_cost_per_1k: 0.015,
currency: "USD".to_string(),
updated_at: chrono::Utc::now(),
},
);
cache.insert(
"j2-mid".to_string(),
ModelPricing {
model: "j2-mid".to_string(),
input_cost_per_1k: 0.01,
output_cost_per_1k: 0.01,
currency: "USD".to_string(),
updated_at: chrono::Utc::now(),
},
);
cache.insert(
"j2-light".to_string(),
ModelPricing {
model: "j2-light".to_string(),
input_cost_per_1k: 0.003,
output_cost_per_1k: 0.003,
currency: "USD".to_string(),
updated_at: chrono::Utc::now(),
},
);
cache.insert(
"jamba-instruct".to_string(),
ModelPricing {
model: "jamba-instruct".to_string(),
input_cost_per_1k: 0.0005,
output_cost_per_1k: 0.0007,
currency: "USD".to_string(),
updated_at: chrono::Utc::now(),
},
);
cache
}
fn convert_messages_to_ai21(&self, messages: &[ChatMessage]) -> String {
messages
.iter()
.map(|msg| {
let role = match msg.role {
MessageRole::System => "System",
MessageRole::User => "Human",
MessageRole::Assistant => "Assistant",
MessageRole::Tool => "Tool",
MessageRole::Function => "Function",
};
let content = match &msg.content {
Some(MessageContent::Text(text)) => text.clone(),
Some(MessageContent::Parts(parts)) => parts
.iter()
.filter_map(|part| match part {
ContentPart::Text { text } => Some(text.clone()),
_ => None,
})
.collect::<Vec<String>>()
.join(" "),
None => String::new(),
};
format!("{}: {}", role, content)
})
.collect::<Vec<String>>()
.join("\n\n")
}
fn convert_ai21_response_to_openai(
&self,
ai21_response: serde_json::Value,
model: &str,
) -> Result<ChatCompletionResponse> {
let completions = ai21_response
.get("completions")
.and_then(|c| c.as_array())
.ok_or_else(|| ProviderError::Parsing("No completions in response".to_string()))?;
let choices: Vec<ChatCompletionChoice> = completions
.iter()
.enumerate()
.map(|(index, completion)| {
let text = completion
.get("data")
.and_then(|d| d.get("text"))
.and_then(|t| t.as_str())
.unwrap_or("")
.to_string();
let finish_reason = completion
.get("finishReason")
.and_then(|fr| fr.get("reason"))
.and_then(|r| r.as_str())
.map(|r| match r {
"stop" => "stop",
"length" => "length",
_ => "stop",
})
.unwrap_or("stop")
.to_string();
ChatCompletionChoice {
index: index as u32,
message: ChatMessage {
role: MessageRole::Assistant,
content: Some(MessageContent::Text(text)),
name: None,
function_call: None,
tool_calls: None,
tool_call_id: None,
audio: None,
},
finish_reason: Some(finish_reason),
logprobs: None,
}
})
.collect();
let usage = Usage {
prompt_tokens: 0, completion_tokens: 0,
total_tokens: 0,
prompt_tokens_details: None,
completion_tokens_details: None,
};
Ok(ChatCompletionResponse {
id: format!("chatcmpl-ai21-{}", uuid::Uuid::new_v4()),
object: "chat.completion".to_string(),
created: chrono::Utc::now().timestamp() as u64,
model: model.to_string(),
choices: choices
.into_iter()
.map(|choice| ChatChoice {
index: choice.index,
message: choice.message,
logprobs: choice.logprobs.map(|_| Logprobs { content: None }),
finish_reason: choice.finish_reason,
})
.collect(),
usage: Some(usage),
system_fingerprint: None,
})
}
}
#[async_trait]
impl Provider for AI21Provider {
fn name(&self) -> &str {
&self.base.name
}
fn provider_type(&self) -> ProviderType {
ProviderType::Custom("ai21".to_string())
}
async fn supports_model(&self, model: &str) -> bool {
self.base.is_model_supported(model) || model.starts_with("j2-") || model.contains("jamba")
}
async fn supports_images(&self) -> bool {
false
}
async fn supports_embeddings(&self) -> bool {
false
}
async fn supports_streaming(&self) -> bool {
false }
async fn list_models(&self) -> Result<Vec<Model>> {
let known_models = vec!["j2-ultra", "j2-mid", "j2-light", "jamba-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: "ai21".to_string(),
})
.collect();
Ok(models)
}
async fn health_check(&self) -> Result<()> {
debug!("Performing AI21 health check");
Ok(()) }
async fn chat_completion(
&self,
request: ChatCompletionRequest,
_context: RequestContext,
) -> Result<ChatCompletionResponse> {
debug!("AI21 chat completion for model: {}", request.model);
let prompt = self.convert_messages_to_ai21(&request.messages);
let mut body = json!({
"prompt": prompt
});
if let Some(max_tokens) = request.max_tokens {
body["maxTokens"] = json!(max_tokens);
}
if let Some(temperature) = request.temperature {
body["temperature"] = json!(temperature);
}
if let Some(top_p) = request.top_p {
body["topP"] = json!(top_p);
}
let url = format!(
"{}/studio/v1/{}/complete",
self.base.base_url, request.model
);
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 ai21_response: serde_json::Value = self.base.parse_json_response(response).await?;
self.convert_ai21_response_to_openai(ai21_response, &request.model)
}
async fn completion(
&self,
request: CompletionRequest,
_context: RequestContext,
) -> Result<CompletionResponse> {
debug!("AI21 completion for model: {}", request.model);
let mut body = json!({
"prompt": request.prompt
});
if let Some(max_tokens) = request.max_tokens {
body["maxTokens"] = json!(max_tokens);
}
if let Some(temperature) = request.temperature {
body["temperature"] = json!(temperature);
}
if let Some(top_p) = request.top_p {
body["topP"] = json!(top_p);
}
let url = format!(
"{}/studio/v1/{}/complete",
self.base.base_url, request.model
);
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 ai21_response: serde_json::Value = self.base.parse_json_response(response).await?;
let empty_vec = vec![];
let completions = ai21_response
.get("completions")
.and_then(|c| c.as_array())
.unwrap_or(&empty_vec);
let choices: Vec<CompletionChoice> = completions
.iter()
.enumerate()
.map(|(index, completion)| {
let text = completion
.get("data")
.and_then(|d| d.get("text"))
.and_then(|t| t.as_str())
.unwrap_or("")
.to_string();
let finish_reason = completion
.get("finishReason")
.and_then(|fr| fr.get("reason"))
.and_then(|r| r.as_str())
.map(|r| match r {
"stop" => "stop",
"length" => "length",
_ => "stop",
})
.unwrap_or("stop")
.to_string();
CompletionChoice {
text,
index: index as u32,
logprobs: None,
finish_reason: Some(finish_reason),
}
})
.collect();
Ok(CompletionResponse {
id: format!("cmpl-ai21-{}", uuid::Uuid::new_v4()),
object: "text_completion".to_string(),
created: chrono::Utc::now().timestamp() as u64,
model: request.model,
choices,
usage: Some(Usage::default()),
})
}
async fn embedding(
&self,
_request: EmbeddingRequest,
_context: RequestContext,
) -> Result<EmbeddingResponse> {
Err(ProviderError::InvalidRequest("Embeddings not supported by AI21".to_string()).into())
}
async fn image_generation(
&self,
_request: ImageGenerationRequest,
_context: RequestContext,
) -> Result<ImageGenerationResponse> {
Err(
ProviderError::InvalidRequest("Image generation not supported by AI21".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.01,
output_cost_per_1k: 0.01,
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;
let output_cost = (output_tokens as f64 / 1000.0) * pricing.output_cost_per_1k;
Ok(input_cost + output_cost)
}
}