Skip to main content

codive_core/
provider.rs

1//! Provider trait and types for LLM integrations
2//!
3//! This module defines the abstraction layer for LLM providers (Anthropic, OpenAI, etc.).
4//! The key design principle is **streaming-first**: all completions return a stream of events.
5//!
6//! # Architecture
7//!
8//! ```text
9//! CompletionRequest
10//!        │
11//!        ▼
12//! ┌─────────────┐
13//! │  Provider   │  (Anthropic, OpenAI, etc.)
14//! └─────────────┘
15//!        │
16//!        ▼
17//! CompletionStream (StreamEvent, StreamEvent, ...)
18//! ```
19//!
20//! # Example
21//!
22//! ```rust,ignore
23//! use codive_core::provider::{Provider, CompletionRequest};
24//! use tokio_stream::StreamExt;
25//!
26//! async fn chat(provider: &dyn Provider) {
27//!     let request = CompletionRequest::new("You are a helpful assistant")
28//!         .with_message(Message::user("Hello!"));
29//!
30//!     let mut stream = provider.complete(request).await?;
31//!     while let Some(event) = stream.next().await {
32//!         match event {
33//!             StreamEvent::TextDelta { text } => print!("{}", text),
34//!             StreamEvent::Done { .. } => break,
35//!             _ => {}
36//!         }
37//!     }
38//! }
39//! ```
40
41use crate::message::Message;
42use crate::tool::ToolInfo;
43use async_trait::async_trait;
44use serde::{Deserialize, Serialize};
45use std::pin::Pin;
46
47// ============================================================================
48// CompletionRequest
49// ============================================================================
50
51/// A request to complete a conversation
52///
53/// This struct contains everything needed to make a completion request:
54/// - System prompt (instructions for the model)
55/// - Messages (the conversation history)
56/// - Available tools
57/// - Model parameters (temperature, max tokens, etc.)
58#[derive(Debug, Clone, Serialize, Deserialize)]
59pub struct CompletionRequest {
60    /// System prompt - instructions for how the model should behave
61    pub system: String,
62
63    /// The conversation messages
64    pub messages: Vec<Message>,
65
66    /// Tools available for the model to use
67    #[serde(default)]
68    pub tools: Vec<ToolInfo>,
69
70    /// Maximum tokens to generate
71    #[serde(default)]
72    pub max_tokens: Option<u32>,
73
74    /// Temperature for sampling (0.0 = deterministic, 1.0 = creative)
75    #[serde(default)]
76    pub temperature: Option<f32>,
77
78    /// Stop sequences - generation stops if any of these are produced
79    #[serde(default)]
80    pub stop_sequences: Vec<String>,
81}
82
83impl CompletionRequest {
84    /// Create a new completion request with a system prompt
85    pub fn new(system: impl Into<String>) -> Self {
86        Self {
87            system: system.into(),
88            messages: Vec::new(),
89            tools: Vec::new(),
90            max_tokens: None,
91            temperature: None,
92            stop_sequences: Vec::new(),
93        }
94    }
95
96    /// Add a message to the conversation
97    pub fn with_message(mut self, message: Message) -> Self {
98        self.messages.push(message);
99        self
100    }
101
102    /// Add multiple messages to the conversation
103    pub fn with_messages(mut self, messages: impl IntoIterator<Item = Message>) -> Self {
104        self.messages.extend(messages);
105        self
106    }
107
108    /// Set the available tools
109    pub fn with_tools(mut self, tools: Vec<ToolInfo>) -> Self {
110        self.tools = tools;
111        self
112    }
113
114    /// Set the maximum tokens to generate
115    pub fn with_max_tokens(mut self, max_tokens: u32) -> Self {
116        self.max_tokens = Some(max_tokens);
117        self
118    }
119
120    /// Set the temperature
121    pub fn with_temperature(mut self, temperature: f32) -> Self {
122        self.temperature = Some(temperature);
123        self
124    }
125
126    /// Add stop sequences
127    pub fn with_stop_sequences(mut self, sequences: Vec<String>) -> Self {
128        self.stop_sequences = sequences;
129        self
130    }
131}
132
133// ============================================================================
134// StreamEvent
135// ============================================================================
136
137/// Events emitted by a completion stream
138///
139/// The stream produces a sequence of these events as the model generates
140/// its response. Consumers should handle each event type appropriately.
141///
142/// # Event Flow
143///
144/// A typical stream might look like:
145/// 1. `MessageStart` - Begin of response
146/// 2. `TextDelta` (multiple) - Text being generated
147/// 3. `ToolCallStart` - Beginning of a tool call
148/// 4. `ToolCallDelta` - Tool call arguments streaming
149/// 5. `ToolCallEnd` - Tool call complete
150/// 6. `MessageEnd` - Response finished
151///
152/// Or in error case:
153/// 1. `MessageStart`
154/// 2. `Error` - Something went wrong
155#[derive(Debug, Clone, Serialize, Deserialize)]
156#[serde(tag = "type", rename_all = "snake_case")]
157pub enum StreamEvent {
158    /// The message has started
159    MessageStart {
160        /// Unique ID for this message (from provider)
161        message_id: String,
162    },
163
164    /// A chunk of text content
165    TextDelta {
166        /// The text fragment
167        text: String,
168    },
169
170    /// A tool call is starting
171    ToolCallStart {
172        /// Index of this tool call (for parallel calls)
173        index: usize,
174        /// ID for this tool call
175        id: String,
176        /// Name of the tool being called
177        name: String,
178    },
179
180    /// Arguments for a tool call (streamed)
181    ToolCallDelta {
182        /// Index of this tool call
183        index: usize,
184        /// JSON fragment of arguments
185        arguments_delta: String,
186    },
187
188    /// A tool call has completed
189    ToolCallEnd {
190        /// Index of this tool call
191        index: usize,
192    },
193
194    /// The message has ended
195    MessageEnd {
196        /// Reason the message ended
197        stop_reason: StopReason,
198        /// Token usage statistics
199        usage: Option<Usage>,
200    },
201
202    /// An error occurred during streaming
203    Error {
204        /// Error message
205        message: String,
206        /// Error code (provider-specific)
207        code: Option<String>,
208    },
209}
210
211impl StreamEvent {
212    /// Create a text delta event
213    pub fn text_delta(text: impl Into<String>) -> Self {
214        Self::TextDelta { text: text.into() }
215    }
216
217    /// Create a message start event
218    pub fn message_start(message_id: impl Into<String>) -> Self {
219        Self::MessageStart {
220            message_id: message_id.into(),
221        }
222    }
223
224    /// Create a message end event
225    pub fn message_end(stop_reason: StopReason) -> Self {
226        Self::MessageEnd {
227            stop_reason,
228            usage: None,
229        }
230    }
231
232    /// Create an error event
233    pub fn error(message: impl Into<String>) -> Self {
234        Self::Error {
235            message: message.into(),
236            code: None,
237        }
238    }
239
240    /// Check if this is a text delta
241    pub fn is_text_delta(&self) -> bool {
242        matches!(self, StreamEvent::TextDelta { .. })
243    }
244
245    /// Check if this signals the end of the message
246    pub fn is_end(&self) -> bool {
247        matches!(self, StreamEvent::MessageEnd { .. })
248    }
249
250    /// Check if this is an error
251    pub fn is_error(&self) -> bool {
252        matches!(self, StreamEvent::Error { .. })
253    }
254
255    /// Extract text if this is a text delta
256    pub fn as_text(&self) -> Option<&str> {
257        match self {
258            StreamEvent::TextDelta { text } => Some(text),
259            _ => None,
260        }
261    }
262}
263
264// ============================================================================
265// StopReason
266// ============================================================================
267
268/// Why the model stopped generating
269#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
270#[serde(rename_all = "snake_case")]
271pub enum StopReason {
272    /// Natural end of response
273    EndTurn,
274    /// Hit maximum token limit
275    MaxTokens,
276    /// Hit a stop sequence
277    StopSequence,
278    /// Model wants to use tools
279    ToolUse,
280}
281
282// ============================================================================
283// Usage
284// ============================================================================
285
286/// Token usage statistics
287#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
288pub struct Usage {
289    /// Tokens in the input (prompt)
290    pub input_tokens: u32,
291    /// Tokens in the output (completion)
292    pub output_tokens: u32,
293}
294
295impl Usage {
296    /// Create new usage stats
297    pub fn new(input_tokens: u32, output_tokens: u32) -> Self {
298        Self {
299            input_tokens,
300            output_tokens,
301        }
302    }
303
304    /// Total tokens used
305    pub fn total_tokens(&self) -> u32 {
306        self.input_tokens + self.output_tokens
307    }
308}
309
310// ============================================================================
311// CompletionStream
312// ============================================================================
313
314/// A stream of completion events
315///
316/// This is a boxed, pinned stream that yields `StreamEvent`s.
317/// We use this type alias to avoid repeating the complex type.
318///
319/// # Why Pin<Box<...>>?
320///
321/// Async streams in Rust need to be pinned because they may contain
322/// self-referential data (the async state machine). `Pin` guarantees
323/// the stream won't be moved in memory, which is required for safety.
324///
325/// # Why dyn Stream?
326///
327/// Using a trait object allows different provider implementations
328/// to return different concrete stream types without exposing them.
329pub type CompletionStream = Pin<Box<dyn futures_core::Stream<Item = StreamEvent> + Send + 'static>>;
330
331// ============================================================================
332// Provider Trait
333// ============================================================================
334
335/// An LLM provider that can complete conversations
336///
337/// This trait abstracts over different LLM providers (Anthropic, OpenAI, etc.)
338/// allowing the agent to work with any provider implementation.
339///
340/// # Streaming
341///
342/// All completions are streaming. For non-streaming responses, the
343/// implementation should return a stream that yields a single event.
344///
345/// # Thread Safety
346///
347/// Providers must be `Send + Sync` to allow concurrent use from
348/// different async tasks.
349#[async_trait]
350pub trait Provider: Send + Sync {
351    /// The name of this provider (e.g., "anthropic", "openai")
352    fn name(&self) -> &str;
353
354    /// The model being used (e.g., "claude-3-opus", "gpt-4")
355    fn model(&self) -> &str;
356
357    /// Complete a conversation
358    ///
359    /// Returns a stream of events as the model generates its response.
360    /// The stream ends with either `MessageEnd` or `Error`.
361    async fn complete(&self, request: CompletionRequest)
362        -> Result<CompletionStream, ProviderError>;
363}
364
365// ============================================================================
366// ProviderError
367// ============================================================================
368
369/// Errors that can occur when using a provider
370#[derive(Debug, Clone, thiserror::Error)]
371pub enum ProviderError {
372    /// Authentication failed (invalid API key, etc.)
373    #[error("Authentication failed: {message}")]
374    Authentication { message: String },
375
376    /// Rate limit exceeded
377    #[error("Rate limit exceeded: {message}")]
378    RateLimit { message: String },
379
380    /// Invalid request (bad parameters, etc.)
381    #[error("Invalid request: {message}")]
382    InvalidRequest { message: String },
383
384    /// Model not available or doesn't exist
385    #[error("Model not found: {model}")]
386    ModelNotFound { model: String },
387
388    /// Network/connection error
389    #[error("Connection error: {message}")]
390    Connection { message: String },
391
392    /// Provider returned an error
393    #[error("Provider error: {message}")]
394    ProviderError { message: String },
395
396    /// Unexpected error
397    #[error("Unexpected error: {message}")]
398    Unexpected { message: String },
399}
400
401impl ProviderError {
402    /// Create an authentication error
403    pub fn authentication(message: impl Into<String>) -> Self {
404        Self::Authentication {
405            message: message.into(),
406        }
407    }
408
409    /// Create a rate limit error
410    pub fn rate_limit(message: impl Into<String>) -> Self {
411        Self::RateLimit {
412            message: message.into(),
413        }
414    }
415
416    /// Create an invalid request error
417    pub fn invalid_request(message: impl Into<String>) -> Self {
418        Self::InvalidRequest {
419            message: message.into(),
420        }
421    }
422
423    /// Create a connection error
424    pub fn connection(message: impl Into<String>) -> Self {
425        Self::Connection {
426            message: message.into(),
427        }
428    }
429
430    /// Check if this error is retryable
431    pub fn is_retryable(&self) -> bool {
432        matches!(self, Self::RateLimit { .. } | Self::Connection { .. })
433    }
434}
435
436// ============================================================================
437// RUST CONCEPTS EXPLAINED (for learning)
438// ============================================================================
439//
440// 1. `Pin<Box<dyn Stream<...>>>`
441//    - `Pin` - Guarantees the value won't move in memory
442//    - `Box` - Heap allocation, allows different sizes
443//    - `dyn Stream` - Trait object for dynamic dispatch
444//    - Together: a heap-allocated, pinned stream of any type
445//
446// 2. `futures_core::Stream`
447//    - The async iterator trait (like Iterator but async)
448//    - `Item` associated type defines what the stream yields
449//    - Use `tokio_stream::StreamExt` for convenient methods
450//
451// 3. `+ Send + 'static` bounds
452//    - `Send` - Can be sent between threads
453//    - `'static` - Contains no borrowed references (owns all data)
454//    - Required for async streams used across await points
455//
456// 4. Builder pattern in `CompletionRequest`
457//    - Methods return `self` allowing chaining
458//    - `mut self` - takes ownership, modifies, returns
459//    - Clean, readable API for constructing complex objects
460//
461// 5. Tagged enums with serde
462//    - `#[serde(tag = "type")]` - Adds "type" field in JSON
463//    - `#[serde(rename_all = "snake_case")]` - Converts variants
464//    - Result: `{"type": "text_delta", "text": "..."}`
465//
466// 6. Error types with thiserror
467//    - Each variant has its own message template
468//    - `is_retryable()` - encode error semantics in types
469//    - Constructors for common error patterns
470//
471// **📚 Read:**
472// - [Async Book - Streams](https://rust-lang.github.io/async-book/05_streams/01_chapter.html)
473// - [Pin documentation](https://doc.rust-lang.org/std/pin/)
474
475// ============================================================================
476// Tests
477// ============================================================================
478
479#[cfg(test)]
480mod tests {
481    use super::*;
482    use tokio_stream::StreamExt;
483
484    #[test]
485    fn test_completion_request_builder() {
486        let request = CompletionRequest::new("You are a helpful assistant")
487            .with_max_tokens(1000)
488            .with_temperature(0.7)
489            .with_message(Message::user("Hello"));
490
491        assert_eq!(request.system, "You are a helpful assistant");
492        assert_eq!(request.max_tokens, Some(1000));
493        assert_eq!(request.temperature, Some(0.7));
494        assert_eq!(request.messages.len(), 1);
495    }
496
497    #[test]
498    fn test_completion_request_with_messages() {
499        let messages = vec![
500            Message::user("Hello"),
501            Message::assistant_text("Hi there!"),
502            Message::user("How are you?"),
503        ];
504
505        let request = CompletionRequest::new("System").with_messages(messages);
506        assert_eq!(request.messages.len(), 3);
507    }
508
509    #[test]
510    fn test_stream_event_text_delta() {
511        let event = StreamEvent::text_delta("Hello");
512        assert!(event.is_text_delta());
513        assert!(!event.is_end());
514        assert_eq!(event.as_text(), Some("Hello"));
515    }
516
517    #[test]
518    fn test_stream_event_message_end() {
519        let event = StreamEvent::message_end(StopReason::EndTurn);
520        assert!(event.is_end());
521        assert!(!event.is_text_delta());
522    }
523
524    #[test]
525    fn test_stream_event_error() {
526        let event = StreamEvent::error("Something went wrong");
527        assert!(event.is_error());
528        assert!(!event.is_end());
529    }
530
531    #[test]
532    fn test_stream_event_serialization() {
533        let event = StreamEvent::text_delta("Hello");
534        let json = serde_json::to_string(&event).unwrap();
535        assert!(json.contains("\"type\":\"text_delta\""));
536        assert!(json.contains("\"text\":\"Hello\""));
537
538        let restored: StreamEvent = serde_json::from_str(&json).unwrap();
539        assert!(restored.is_text_delta());
540    }
541
542    #[test]
543    fn test_stop_reason_serialization() {
544        assert_eq!(
545            serde_json::to_string(&StopReason::EndTurn).unwrap(),
546            "\"end_turn\""
547        );
548        assert_eq!(
549            serde_json::to_string(&StopReason::ToolUse).unwrap(),
550            "\"tool_use\""
551        );
552    }
553
554    #[test]
555    fn test_usage_total() {
556        let usage = Usage::new(100, 50);
557        assert_eq!(usage.total_tokens(), 150);
558    }
559
560    #[test]
561    fn test_provider_error_retryable() {
562        assert!(ProviderError::rate_limit("try again").is_retryable());
563        assert!(ProviderError::connection("timeout").is_retryable());
564        assert!(!ProviderError::authentication("bad key").is_retryable());
565        assert!(!ProviderError::invalid_request("bad params").is_retryable());
566    }
567
568    #[tokio::test]
569    async fn test_completion_stream_type() {
570        // Verify we can create a stream from a vec
571        let events = vec![
572            StreamEvent::message_start("msg_1"),
573            StreamEvent::text_delta("Hello, "),
574            StreamEvent::text_delta("world!"),
575            StreamEvent::message_end(StopReason::EndTurn),
576        ];
577
578        let stream: CompletionStream = Box::pin(tokio_stream::iter(events));
579        let collected: Vec<_> = stream.collect().await;
580
581        assert_eq!(collected.len(), 4);
582        assert!(collected[0].is_text_delta() == false); // MessageStart
583        assert!(collected[1].is_text_delta());
584        assert!(collected[2].is_text_delta());
585        assert!(collected[3].is_end());
586    }
587
588    #[tokio::test]
589    async fn test_stream_collect_text() {
590        let events = vec![
591            StreamEvent::message_start("msg_1"),
592            StreamEvent::text_delta("Hello, "),
593            StreamEvent::text_delta("world!"),
594            StreamEvent::message_end(StopReason::EndTurn),
595        ];
596
597        let stream = tokio_stream::iter(events);
598        let text: String = stream
599            .filter_map(|e| e.as_text().map(|s| s.to_string()))
600            .collect()
601            .await;
602
603        assert_eq!(text, "Hello, world!");
604    }
605}