codive-core 0.1.0

Core types, traits, and utilities for Codive
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
//! Provider trait and types for LLM integrations
//!
//! This module defines the abstraction layer for LLM providers (Anthropic, OpenAI, etc.).
//! The key design principle is **streaming-first**: all completions return a stream of events.
//!
//! # Architecture
//!
//! ```text
//! CompletionRequest
//!        │
//!        ▼
//! ┌─────────────┐
//! │  Provider   │  (Anthropic, OpenAI, etc.)
//! └─────────────┘
//!        │
//!        ▼
//! CompletionStream (StreamEvent, StreamEvent, ...)
//! ```
//!
//! # Example
//!
//! ```rust,ignore
//! use codive_core::provider::{Provider, CompletionRequest};
//! use tokio_stream::StreamExt;
//!
//! async fn chat(provider: &dyn Provider) {
//!     let request = CompletionRequest::new("You are a helpful assistant")
//!         .with_message(Message::user("Hello!"));
//!
//!     let mut stream = provider.complete(request).await?;
//!     while let Some(event) = stream.next().await {
//!         match event {
//!             StreamEvent::TextDelta { text } => print!("{}", text),
//!             StreamEvent::Done { .. } => break,
//!             _ => {}
//!         }
//!     }
//! }
//! ```

use crate::message::Message;
use crate::tool::ToolInfo;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::pin::Pin;

// ============================================================================
// CompletionRequest
// ============================================================================

/// A request to complete a conversation
///
/// This struct contains everything needed to make a completion request:
/// - System prompt (instructions for the model)
/// - Messages (the conversation history)
/// - Available tools
/// - Model parameters (temperature, max tokens, etc.)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompletionRequest {
    /// System prompt - instructions for how the model should behave
    pub system: String,

    /// The conversation messages
    pub messages: Vec<Message>,

    /// Tools available for the model to use
    #[serde(default)]
    pub tools: Vec<ToolInfo>,

    /// Maximum tokens to generate
    #[serde(default)]
    pub max_tokens: Option<u32>,

    /// Temperature for sampling (0.0 = deterministic, 1.0 = creative)
    #[serde(default)]
    pub temperature: Option<f32>,

    /// Stop sequences - generation stops if any of these are produced
    #[serde(default)]
    pub stop_sequences: Vec<String>,
}

impl CompletionRequest {
    /// Create a new completion request with a system prompt
    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(),
        }
    }

    /// Add a message to the conversation
    pub fn with_message(mut self, message: Message) -> Self {
        self.messages.push(message);
        self
    }

    /// Add multiple messages to the conversation
    pub fn with_messages(mut self, messages: impl IntoIterator<Item = Message>) -> Self {
        self.messages.extend(messages);
        self
    }

    /// Set the available tools
    pub fn with_tools(mut self, tools: Vec<ToolInfo>) -> Self {
        self.tools = tools;
        self
    }

    /// Set the maximum tokens to generate
    pub fn with_max_tokens(mut self, max_tokens: u32) -> Self {
        self.max_tokens = Some(max_tokens);
        self
    }

    /// Set the temperature
    pub fn with_temperature(mut self, temperature: f32) -> Self {
        self.temperature = Some(temperature);
        self
    }

    /// Add stop sequences
    pub fn with_stop_sequences(mut self, sequences: Vec<String>) -> Self {
        self.stop_sequences = sequences;
        self
    }
}

// ============================================================================
// StreamEvent
// ============================================================================

/// Events emitted by a completion stream
///
/// The stream produces a sequence of these events as the model generates
/// its response. Consumers should handle each event type appropriately.
///
/// # Event Flow
///
/// A typical stream might look like:
/// 1. `MessageStart` - Begin of response
/// 2. `TextDelta` (multiple) - Text being generated
/// 3. `ToolCallStart` - Beginning of a tool call
/// 4. `ToolCallDelta` - Tool call arguments streaming
/// 5. `ToolCallEnd` - Tool call complete
/// 6. `MessageEnd` - Response finished
///
/// Or in error case:
/// 1. `MessageStart`
/// 2. `Error` - Something went wrong
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum StreamEvent {
    /// The message has started
    MessageStart {
        /// Unique ID for this message (from provider)
        message_id: String,
    },

    /// A chunk of text content
    TextDelta {
        /// The text fragment
        text: String,
    },

    /// A tool call is starting
    ToolCallStart {
        /// Index of this tool call (for parallel calls)
        index: usize,
        /// ID for this tool call
        id: String,
        /// Name of the tool being called
        name: String,
    },

    /// Arguments for a tool call (streamed)
    ToolCallDelta {
        /// Index of this tool call
        index: usize,
        /// JSON fragment of arguments
        arguments_delta: String,
    },

    /// A tool call has completed
    ToolCallEnd {
        /// Index of this tool call
        index: usize,
    },

    /// The message has ended
    MessageEnd {
        /// Reason the message ended
        stop_reason: StopReason,
        /// Token usage statistics
        usage: Option<Usage>,
    },

    /// An error occurred during streaming
    Error {
        /// Error message
        message: String,
        /// Error code (provider-specific)
        code: Option<String>,
    },
}

impl StreamEvent {
    /// Create a text delta event
    pub fn text_delta(text: impl Into<String>) -> Self {
        Self::TextDelta { text: text.into() }
    }

    /// Create a message start event
    pub fn message_start(message_id: impl Into<String>) -> Self {
        Self::MessageStart {
            message_id: message_id.into(),
        }
    }

    /// Create a message end event
    pub fn message_end(stop_reason: StopReason) -> Self {
        Self::MessageEnd {
            stop_reason,
            usage: None,
        }
    }

    /// Create an error event
    pub fn error(message: impl Into<String>) -> Self {
        Self::Error {
            message: message.into(),
            code: None,
        }
    }

    /// Check if this is a text delta
    pub fn is_text_delta(&self) -> bool {
        matches!(self, StreamEvent::TextDelta { .. })
    }

    /// Check if this signals the end of the message
    pub fn is_end(&self) -> bool {
        matches!(self, StreamEvent::MessageEnd { .. })
    }

    /// Check if this is an error
    pub fn is_error(&self) -> bool {
        matches!(self, StreamEvent::Error { .. })
    }

    /// Extract text if this is a text delta
    pub fn as_text(&self) -> Option<&str> {
        match self {
            StreamEvent::TextDelta { text } => Some(text),
            _ => None,
        }
    }
}

// ============================================================================
// StopReason
// ============================================================================

/// Why the model stopped generating
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StopReason {
    /// Natural end of response
    EndTurn,
    /// Hit maximum token limit
    MaxTokens,
    /// Hit a stop sequence
    StopSequence,
    /// Model wants to use tools
    ToolUse,
}

// ============================================================================
// Usage
// ============================================================================

/// Token usage statistics
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Usage {
    /// Tokens in the input (prompt)
    pub input_tokens: u32,
    /// Tokens in the output (completion)
    pub output_tokens: u32,
}

impl Usage {
    /// Create new usage stats
    pub fn new(input_tokens: u32, output_tokens: u32) -> Self {
        Self {
            input_tokens,
            output_tokens,
        }
    }

    /// Total tokens used
    pub fn total_tokens(&self) -> u32 {
        self.input_tokens + self.output_tokens
    }
}

// ============================================================================
// CompletionStream
// ============================================================================

/// A stream of completion events
///
/// This is a boxed, pinned stream that yields `StreamEvent`s.
/// We use this type alias to avoid repeating the complex type.
///
/// # Why Pin<Box<...>>?
///
/// Async streams in Rust need to be pinned because they may contain
/// self-referential data (the async state machine). `Pin` guarantees
/// the stream won't be moved in memory, which is required for safety.
///
/// # Why dyn Stream?
///
/// Using a trait object allows different provider implementations
/// to return different concrete stream types without exposing them.
pub type CompletionStream = Pin<Box<dyn futures_core::Stream<Item = StreamEvent> + Send + 'static>>;

// ============================================================================
// Provider Trait
// ============================================================================

/// An LLM provider that can complete conversations
///
/// This trait abstracts over different LLM providers (Anthropic, OpenAI, etc.)
/// allowing the agent to work with any provider implementation.
///
/// # Streaming
///
/// All completions are streaming. For non-streaming responses, the
/// implementation should return a stream that yields a single event.
///
/// # Thread Safety
///
/// Providers must be `Send + Sync` to allow concurrent use from
/// different async tasks.
#[async_trait]
pub trait Provider: Send + Sync {
    /// The name of this provider (e.g., "anthropic", "openai")
    fn name(&self) -> &str;

    /// The model being used (e.g., "claude-3-opus", "gpt-4")
    fn model(&self) -> &str;

    /// Complete a conversation
    ///
    /// Returns a stream of events as the model generates its response.
    /// The stream ends with either `MessageEnd` or `Error`.
    async fn complete(&self, request: CompletionRequest)
        -> Result<CompletionStream, ProviderError>;
}

// ============================================================================
// ProviderError
// ============================================================================

/// Errors that can occur when using a provider
#[derive(Debug, Clone, thiserror::Error)]
pub enum ProviderError {
    /// Authentication failed (invalid API key, etc.)
    #[error("Authentication failed: {message}")]
    Authentication { message: String },

    /// Rate limit exceeded
    #[error("Rate limit exceeded: {message}")]
    RateLimit { message: String },

    /// Invalid request (bad parameters, etc.)
    #[error("Invalid request: {message}")]
    InvalidRequest { message: String },

    /// Model not available or doesn't exist
    #[error("Model not found: {model}")]
    ModelNotFound { model: String },

    /// Network/connection error
    #[error("Connection error: {message}")]
    Connection { message: String },

    /// Provider returned an error
    #[error("Provider error: {message}")]
    ProviderError { message: String },

    /// Unexpected error
    #[error("Unexpected error: {message}")]
    Unexpected { message: String },
}

impl ProviderError {
    /// Create an authentication error
    pub fn authentication(message: impl Into<String>) -> Self {
        Self::Authentication {
            message: message.into(),
        }
    }

    /// Create a rate limit error
    pub fn rate_limit(message: impl Into<String>) -> Self {
        Self::RateLimit {
            message: message.into(),
        }
    }

    /// Create an invalid request error
    pub fn invalid_request(message: impl Into<String>) -> Self {
        Self::InvalidRequest {
            message: message.into(),
        }
    }

    /// Create a connection error
    pub fn connection(message: impl Into<String>) -> Self {
        Self::Connection {
            message: message.into(),
        }
    }

    /// Check if this error is retryable
    pub fn is_retryable(&self) -> bool {
        matches!(self, Self::RateLimit { .. } | Self::Connection { .. })
    }
}

// ============================================================================
// RUST CONCEPTS EXPLAINED (for learning)
// ============================================================================
//
// 1. `Pin<Box<dyn Stream<...>>>`
//    - `Pin` - Guarantees the value won't move in memory
//    - `Box` - Heap allocation, allows different sizes
//    - `dyn Stream` - Trait object for dynamic dispatch
//    - Together: a heap-allocated, pinned stream of any type
//
// 2. `futures_core::Stream`
//    - The async iterator trait (like Iterator but async)
//    - `Item` associated type defines what the stream yields
//    - Use `tokio_stream::StreamExt` for convenient methods
//
// 3. `+ Send + 'static` bounds
//    - `Send` - Can be sent between threads
//    - `'static` - Contains no borrowed references (owns all data)
//    - Required for async streams used across await points
//
// 4. Builder pattern in `CompletionRequest`
//    - Methods return `self` allowing chaining
//    - `mut self` - takes ownership, modifies, returns
//    - Clean, readable API for constructing complex objects
//
// 5. Tagged enums with serde
//    - `#[serde(tag = "type")]` - Adds "type" field in JSON
//    - `#[serde(rename_all = "snake_case")]` - Converts variants
//    - Result: `{"type": "text_delta", "text": "..."}`
//
// 6. Error types with thiserror
//    - Each variant has its own message template
//    - `is_retryable()` - encode error semantics in types
//    - Constructors for common error patterns
//
// **📚 Read:**
// - [Async Book - Streams](https://rust-lang.github.io/async-book/05_streams/01_chapter.html)
// - [Pin documentation](https://doc.rust-lang.org/std/pin/)

// ============================================================================
// Tests
// ============================================================================

#[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() {
        // Verify we can create a stream from a vec
        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); // MessageStart
        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!");
    }
}