use crate::message::Message;
use crate::tool::ToolInfo;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::pin::Pin;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompletionRequest {
pub system: String,
pub messages: Vec<Message>,
#[serde(default)]
pub tools: Vec<ToolInfo>,
#[serde(default)]
pub max_tokens: Option<u32>,
#[serde(default)]
pub temperature: Option<f32>,
#[serde(default)]
pub stop_sequences: Vec<String>,
}
impl CompletionRequest {
pub fn new(system: impl Into<String>) -> Self {
Self {
system: system.into(),
messages: Vec::new(),
tools: Vec::new(),
max_tokens: None,
temperature: None,
stop_sequences: Vec::new(),
}
}
pub fn with_message(mut self, message: Message) -> Self {
self.messages.push(message);
self
}
pub fn with_messages(mut self, messages: impl IntoIterator<Item = Message>) -> Self {
self.messages.extend(messages);
self
}
pub fn with_tools(mut self, tools: Vec<ToolInfo>) -> Self {
self.tools = tools;
self
}
pub fn with_max_tokens(mut self, max_tokens: u32) -> Self {
self.max_tokens = Some(max_tokens);
self
}
pub fn with_temperature(mut self, temperature: f32) -> Self {
self.temperature = Some(temperature);
self
}
pub fn with_stop_sequences(mut self, sequences: Vec<String>) -> Self {
self.stop_sequences = sequences;
self
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum StreamEvent {
MessageStart {
message_id: String,
},
TextDelta {
text: String,
},
ToolCallStart {
index: usize,
id: String,
name: String,
},
ToolCallDelta {
index: usize,
arguments_delta: String,
},
ToolCallEnd {
index: usize,
},
MessageEnd {
stop_reason: StopReason,
usage: Option<Usage>,
},
Error {
message: String,
code: Option<String>,
},
}
impl StreamEvent {
pub fn text_delta(text: impl Into<String>) -> Self {
Self::TextDelta { text: text.into() }
}
pub fn message_start(message_id: impl Into<String>) -> Self {
Self::MessageStart {
message_id: message_id.into(),
}
}
pub fn message_end(stop_reason: StopReason) -> Self {
Self::MessageEnd {
stop_reason,
usage: None,
}
}
pub fn error(message: impl Into<String>) -> Self {
Self::Error {
message: message.into(),
code: None,
}
}
pub fn is_text_delta(&self) -> bool {
matches!(self, StreamEvent::TextDelta { .. })
}
pub fn is_end(&self) -> bool {
matches!(self, StreamEvent::MessageEnd { .. })
}
pub fn is_error(&self) -> bool {
matches!(self, StreamEvent::Error { .. })
}
pub fn as_text(&self) -> Option<&str> {
match self {
StreamEvent::TextDelta { text } => Some(text),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StopReason {
EndTurn,
MaxTokens,
StopSequence,
ToolUse,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Usage {
pub input_tokens: u32,
pub output_tokens: u32,
}
impl Usage {
pub fn new(input_tokens: u32, output_tokens: u32) -> Self {
Self {
input_tokens,
output_tokens,
}
}
pub fn total_tokens(&self) -> u32 {
self.input_tokens + self.output_tokens
}
}
pub type CompletionStream = Pin<Box<dyn futures_core::Stream<Item = StreamEvent> + Send + 'static>>;
#[async_trait]
pub trait Provider: Send + Sync {
fn name(&self) -> &str;
fn model(&self) -> &str;
async fn complete(&self, request: CompletionRequest)
-> Result<CompletionStream, ProviderError>;
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum ProviderError {
#[error("Authentication failed: {message}")]
Authentication { message: String },
#[error("Rate limit exceeded: {message}")]
RateLimit { message: String },
#[error("Invalid request: {message}")]
InvalidRequest { message: String },
#[error("Model not found: {model}")]
ModelNotFound { model: String },
#[error("Connection error: {message}")]
Connection { message: String },
#[error("Provider error: {message}")]
ProviderError { message: String },
#[error("Unexpected error: {message}")]
Unexpected { message: String },
}
impl ProviderError {
pub fn authentication(message: impl Into<String>) -> Self {
Self::Authentication {
message: message.into(),
}
}
pub fn rate_limit(message: impl Into<String>) -> Self {
Self::RateLimit {
message: message.into(),
}
}
pub fn invalid_request(message: impl Into<String>) -> Self {
Self::InvalidRequest {
message: message.into(),
}
}
pub fn connection(message: impl Into<String>) -> Self {
Self::Connection {
message: message.into(),
}
}
pub fn is_retryable(&self) -> bool {
matches!(self, Self::RateLimit { .. } | Self::Connection { .. })
}
}
#[cfg(test)]
mod tests {
use super::*;
use tokio_stream::StreamExt;
#[test]
fn test_completion_request_builder() {
let request = CompletionRequest::new("You are a helpful assistant")
.with_max_tokens(1000)
.with_temperature(0.7)
.with_message(Message::user("Hello"));
assert_eq!(request.system, "You are a helpful assistant");
assert_eq!(request.max_tokens, Some(1000));
assert_eq!(request.temperature, Some(0.7));
assert_eq!(request.messages.len(), 1);
}
#[test]
fn test_completion_request_with_messages() {
let messages = vec![
Message::user("Hello"),
Message::assistant_text("Hi there!"),
Message::user("How are you?"),
];
let request = CompletionRequest::new("System").with_messages(messages);
assert_eq!(request.messages.len(), 3);
}
#[test]
fn test_stream_event_text_delta() {
let event = StreamEvent::text_delta("Hello");
assert!(event.is_text_delta());
assert!(!event.is_end());
assert_eq!(event.as_text(), Some("Hello"));
}
#[test]
fn test_stream_event_message_end() {
let event = StreamEvent::message_end(StopReason::EndTurn);
assert!(event.is_end());
assert!(!event.is_text_delta());
}
#[test]
fn test_stream_event_error() {
let event = StreamEvent::error("Something went wrong");
assert!(event.is_error());
assert!(!event.is_end());
}
#[test]
fn test_stream_event_serialization() {
let event = StreamEvent::text_delta("Hello");
let json = serde_json::to_string(&event).unwrap();
assert!(json.contains("\"type\":\"text_delta\""));
assert!(json.contains("\"text\":\"Hello\""));
let restored: StreamEvent = serde_json::from_str(&json).unwrap();
assert!(restored.is_text_delta());
}
#[test]
fn test_stop_reason_serialization() {
assert_eq!(
serde_json::to_string(&StopReason::EndTurn).unwrap(),
"\"end_turn\""
);
assert_eq!(
serde_json::to_string(&StopReason::ToolUse).unwrap(),
"\"tool_use\""
);
}
#[test]
fn test_usage_total() {
let usage = Usage::new(100, 50);
assert_eq!(usage.total_tokens(), 150);
}
#[test]
fn test_provider_error_retryable() {
assert!(ProviderError::rate_limit("try again").is_retryable());
assert!(ProviderError::connection("timeout").is_retryable());
assert!(!ProviderError::authentication("bad key").is_retryable());
assert!(!ProviderError::invalid_request("bad params").is_retryable());
}
#[tokio::test]
async fn test_completion_stream_type() {
let events = vec![
StreamEvent::message_start("msg_1"),
StreamEvent::text_delta("Hello, "),
StreamEvent::text_delta("world!"),
StreamEvent::message_end(StopReason::EndTurn),
];
let stream: CompletionStream = Box::pin(tokio_stream::iter(events));
let collected: Vec<_> = stream.collect().await;
assert_eq!(collected.len(), 4);
assert!(collected[0].is_text_delta() == false); assert!(collected[1].is_text_delta());
assert!(collected[2].is_text_delta());
assert!(collected[3].is_end());
}
#[tokio::test]
async fn test_stream_collect_text() {
let events = vec![
StreamEvent::message_start("msg_1"),
StreamEvent::text_delta("Hello, "),
StreamEvent::text_delta("world!"),
StreamEvent::message_end(StopReason::EndTurn),
];
let stream = tokio_stream::iter(events);
let text: String = stream
.filter_map(|e| e.as_text().map(|s| s.to_string()))
.collect()
.await;
assert_eq!(text, "Hello, world!");
}
}