rrag 0.1.0-alpha.2

High-performance Rust framework for Retrieval-Augmented Generation with pluggable components, async-first design, and comprehensive observability
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
//! # RRAG Streaming System
//!
//! Real-time streaming responses using Rust's async ecosystem.
//! Leverages tokio-stream and futures for efficient token streaming.

use crate::{RragError, RragResult};
use futures::{Stream, StreamExt};
use serde::{Deserialize, Serialize};
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::sync::mpsc;
use tokio_stream::wrappers::UnboundedReceiverStream;

/// Streaming response token
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StreamToken {
    /// Token content
    pub content: String,

    /// Token type (text, tool_call, metadata, etc.)
    pub token_type: TokenType,

    /// Position in the stream
    pub position: usize,

    /// Whether this is the final token
    pub is_final: bool,

    /// Token metadata
    pub metadata: Option<serde_json::Value>,
}

impl StreamToken {
    pub fn text(content: impl Into<String>, position: usize) -> Self {
        Self {
            content: content.into(),
            token_type: TokenType::Text,
            position,
            is_final: false,
            metadata: None,
        }
    }

    pub fn tool_call(content: impl Into<String>, position: usize) -> Self {
        Self {
            content: content.into(),
            token_type: TokenType::ToolCall,
            position,
            is_final: false,
            metadata: None,
        }
    }

    pub fn final_token(position: usize) -> Self {
        Self {
            content: String::new(),
            token_type: TokenType::End,
            position,
            is_final: true,
            metadata: None,
        }
    }

    pub fn with_metadata(mut self, metadata: serde_json::Value) -> Self {
        self.metadata = Some(metadata);
        self
    }
}

/// Token types for different streaming content
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum TokenType {
    /// Regular text content
    Text,

    /// Tool call information
    ToolCall,

    /// Tool result
    ToolResult,

    /// Metadata/system information
    Metadata,

    /// Stream end marker
    End,

    /// Error token
    Error,
}

/// Streaming response wrapper
pub struct StreamingResponse {
    stream: Pin<Box<dyn Stream<Item = RragResult<StreamToken>> + Send>>,
}

impl StreamingResponse {
    /// Create from a text string by splitting into tokens
    pub fn from_text(text: impl Into<String>) -> Self {
        let text = text.into();
        let tokens: Vec<_> = text
            .split_whitespace()
            .enumerate()
            .map(|(i, word)| Ok(StreamToken::text(format!("{} ", word), i)))
            .collect();

        // Add final token
        let mut tokens = tokens;
        let final_pos = tokens.len();
        tokens.push(Ok(StreamToken::final_token(final_pos)));

        let stream = futures::stream::iter(tokens);

        Self {
            stream: Box::pin(stream),
        }
    }

    /// Create from a token stream
    pub fn from_stream<S>(stream: S) -> Self
    where
        S: Stream<Item = RragResult<StreamToken>> + Send + 'static,
    {
        Self {
            stream: Box::pin(stream),
        }
    }

    /// Create from an async channel
    pub fn from_channel(receiver: mpsc::UnboundedReceiver<RragResult<StreamToken>>) -> Self {
        let stream = UnboundedReceiverStream::new(receiver);
        Self::from_stream(stream)
    }

    /// Collect all tokens into a single string
    pub async fn collect_text(mut self) -> RragResult<String> {
        let mut result = String::new();

        while let Some(token_result) = self.stream.next().await {
            match token_result? {
                token if token.token_type == TokenType::Text => {
                    result.push_str(&token.content);
                }
                token if token.is_final => break,
                _ => {} // Skip non-text tokens
            }
        }

        Ok(result.trim().to_string())
    }

    /// Filter tokens by type
    pub fn filter_by_type(self, token_type: TokenType) -> FilteredStream {
        FilteredStream {
            stream: self.stream,
            filter_type: token_type,
        }
    }

    /// Map tokens to a different type
    pub fn map_tokens<F, T>(self, f: F) -> MappedStream<T>
    where
        F: Fn(StreamToken) -> T + Send + 'static,
        T: Send + 'static,
    {
        let mapped_stream = self.stream.map(move |result| result.map(&f));

        MappedStream {
            stream: Box::pin(mapped_stream),
        }
    }
}

impl Stream for StreamingResponse {
    type Item = RragResult<StreamToken>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.stream.as_mut().poll_next(cx)
    }
}

/// Filtered stream that only yields specific token types
pub struct FilteredStream {
    stream: Pin<Box<dyn Stream<Item = RragResult<StreamToken>> + Send>>,
    filter_type: TokenType,
}

impl Stream for FilteredStream {
    type Item = RragResult<StreamToken>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        loop {
            match self.stream.as_mut().poll_next(cx) {
                Poll::Ready(Some(Ok(token))) => {
                    if token.token_type == self.filter_type || token.is_final {
                        return Poll::Ready(Some(Ok(token)));
                    }
                    // Continue polling for matching tokens
                }
                Poll::Ready(Some(Err(e))) => return Poll::Ready(Some(Err(e))),
                Poll::Ready(None) => return Poll::Ready(None),
                Poll::Pending => return Poll::Pending,
            }
        }
    }
}

/// Mapped stream that transforms tokens
pub struct MappedStream<T> {
    stream: Pin<Box<dyn Stream<Item = RragResult<T>> + Send>>,
}

impl<T> Stream for MappedStream<T> {
    type Item = RragResult<T>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.stream.as_mut().poll_next(cx)
    }
}

/// Token stream builder for creating custom streams
pub struct TokenStreamBuilder {
    sender: mpsc::UnboundedSender<RragResult<StreamToken>>,
    position: usize,
}

impl TokenStreamBuilder {
    /// Create a new token stream builder
    pub fn new() -> (Self, mpsc::UnboundedReceiver<RragResult<StreamToken>>) {
        let (sender, receiver) = mpsc::unbounded_channel();

        let builder = Self {
            sender,
            position: 0,
        };

        (builder, receiver)
    }

    /// Send a text token
    pub fn send_text(&mut self, content: impl Into<String>) -> RragResult<()> {
        let token = StreamToken::text(content, self.position);
        self.position += 1;

        self.sender
            .send(Ok(token))
            .map_err(|_| RragError::stream("token_builder", "Channel closed"))?;

        Ok(())
    }

    /// Send a tool call token
    pub fn send_tool_call(&mut self, content: impl Into<String>) -> RragResult<()> {
        let token = StreamToken::tool_call(content, self.position);
        self.position += 1;

        self.sender
            .send(Ok(token))
            .map_err(|_| RragError::stream("token_builder", "Channel closed"))?;

        Ok(())
    }

    /// Send an error token
    pub fn send_error(&mut self, error: RragError) -> RragResult<()> {
        self.sender
            .send(Err(error))
            .map_err(|_| RragError::stream("token_builder", "Channel closed"))?;

        Ok(())
    }

    /// Finalize the stream
    pub fn finish(self) -> RragResult<()> {
        let final_token = StreamToken::final_token(self.position);

        self.sender
            .send(Ok(final_token))
            .map_err(|_| RragError::stream("token_builder", "Channel closed"))?;

        // Close the channel
        drop(self.sender);

        Ok(())
    }
}

impl Default for TokenStreamBuilder {
    fn default() -> Self {
        let (builder, _) = Self::new();
        builder
    }
}

/// Convenience type alias for token streams
pub type TokenStream = StreamingResponse;

/// Utility functions for working with streams
pub mod stream_utils {
    use super::*;
    use std::time::Duration;

    /// Create a stream that emits tokens with a delay (for demo purposes)
    pub fn create_delayed_stream(text: impl Into<String>, delay: Duration) -> StreamingResponse {
        let text = text.into();
        let words: Vec<String> = text.split_whitespace().map(|s| s.to_string()).collect();

        let stream = async_stream::stream! {
            for (i, word) in words.iter().enumerate() {
                tokio::time::sleep(delay).await;
                yield Ok(StreamToken::text(format!("{} ", word), i));
            }
            yield Ok(StreamToken::final_token(words.len()));
        };

        StreamingResponse::from_stream(stream)
    }

    /// Create a stream from multiple text chunks
    pub fn create_chunked_stream(chunks: Vec<String>) -> StreamingResponse {
        let stream = async_stream::stream! {
            for (i, chunk) in chunks.iter().enumerate() {
                yield Ok(StreamToken::text(chunk.clone(), i));
            }
            yield Ok(StreamToken::final_token(chunks.len()));
        };

        StreamingResponse::from_stream(stream)
    }

    /// Merge multiple streams into one
    pub async fn merge_streams(streams: Vec<StreamingResponse>) -> RragResult<StreamingResponse> {
        let (mut builder, receiver) = TokenStreamBuilder::new();

        tokio::spawn(async move {
            let mut position = 0;

            for mut stream in streams {
                while let Some(token_result) = stream.next().await {
                    match token_result {
                        Ok(mut token) => {
                            if !token.is_final {
                                token.position = position;
                                position += 1;

                                if let Err(_) = builder.sender.send(Ok(token)) {
                                    break;
                                }
                            }
                        }
                        Err(e) => {
                            let _ = builder.send_error(e);
                            break;
                        }
                    }
                }
            }

            let _ = builder.finish();
        });

        Ok(StreamingResponse::from_channel(receiver))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use futures::StreamExt;
    use tokio_test;

    #[tokio::test]
    async fn test_streaming_response_from_text() {
        let response = StreamingResponse::from_text("Hello world test");
        let text = response.collect_text().await.unwrap();

        assert_eq!(text, "Hello world test");
    }

    #[tokio::test]
    async fn test_token_stream_builder() {
        let (mut builder, receiver) = TokenStreamBuilder::new();

        tokio::spawn(async move {
            builder.send_text("Hello").unwrap();
            builder.send_text("world").unwrap();
            builder.finish().unwrap();
        });

        let response = StreamingResponse::from_channel(receiver);
        let text = response.collect_text().await.unwrap();

        assert_eq!(text, "Hello world");
    }

    #[tokio::test]
    async fn test_filtered_stream() {
        let (mut builder, receiver) = TokenStreamBuilder::new();

        tokio::spawn(async move {
            builder.send_text("Hello").unwrap();
            builder.send_tool_call("tool_call").unwrap();
            builder.send_text("world").unwrap();
            builder.finish().unwrap();
        });

        let response = StreamingResponse::from_channel(receiver);
        let mut text_stream = response.filter_by_type(TokenType::Text);

        let mut text_tokens = Vec::new();
        while let Some(token_result) = text_stream.next().await {
            match token_result.unwrap() {
                token if token.token_type == TokenType::Text => {
                    text_tokens.push(token.content);
                }
                token if token.is_final => break,
                _ => {}
            }
        }

        assert_eq!(text_tokens, vec!["Hello ", "world "]);
    }

    #[tokio::test]
    async fn test_stream_utils_delayed() {
        use std::time::Duration;

        let start = std::time::Instant::now();
        let response = stream_utils::create_delayed_stream("one two", Duration::from_millis(10));
        let text = response.collect_text().await.unwrap();
        let elapsed = start.elapsed();

        assert_eq!(text, "one two");
        assert!(elapsed >= Duration::from_millis(20)); // At least 2 delays
    }

    #[test]
    fn test_stream_token_creation() {
        let token = StreamToken::text("hello", 0);
        assert_eq!(token.content, "hello");
        assert_eq!(token.token_type, TokenType::Text);
        assert_eq!(token.position, 0);
        assert!(!token.is_final);

        let final_token = StreamToken::final_token(10);
        assert!(final_token.is_final);
        assert_eq!(final_token.token_type, TokenType::End);
    }
}