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
#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc = include_str!("../README.md")]
#![warn(missing_docs)]
#![deny(rustdoc::broken_intra_doc_links)]
#![warn(clippy::all)]
#![warn(clippy::pedantic)]
#![allow(clippy::module_name_repetitions)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::must_use_candidate)]
#![allow(dead_code)]

//! # RRAG - Enterprise-Grade Rust RAG Framework
//!
//! [![Crates.io](https://img.shields.io/crates/v/rrag.svg)](https://crates.io/crates/rrag)
//! [![Documentation](https://docs.rs/rrag/badge.svg)](https://docs.rs/rrag)
//! [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
//! [![Build Status](https://img.shields.io/github/actions/workflow/status/yourusername/rrag/ci.yml?branch=main)](https://github.com/yourusername/rrag/actions)
//!
//! **RRAG** (Rust RAG) is a comprehensive, high-performance framework for building
//! production-ready Retrieval-Augmented Generation (RAG) applications in Rust.
//!
//! Designed for enterprise deployments requiring extreme performance, reliability, and
//! observability, RRAG provides everything needed to build, deploy, and maintain
//! sophisticated RAG systems at scale.
//!
//! ## πŸš€ Key Features
//!
//! - **πŸ”₯ Native Performance**: Zero-cost abstractions with compile-time optimizations
//! - **πŸ›‘οΈ Memory Safe**: Leverage Rust's ownership system for bulletproof memory management
//! - **⚑ Async First**: Built on Tokio for high-concurrency workloads
//! - **🎯 Type Safe**: Compile-time guarantees prevent runtime errors
//! - **πŸ”Œ Pluggable**: Modular architecture with swappable components
//! - **🌊 Streaming**: Real-time token streaming with async iterators
//! - **πŸ“Š Observable**: Built-in metrics, tracing, and health checks
//!
//! ## πŸ—οΈ Architecture Overview
//!
//! RRAG follows a modular, pipeline-based architecture that maximizes performance
//! while maintaining flexibility:
//!
//! ```text
//! β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
//! β”‚   Documents     │───▢│   Processing    │───▢│   Vector Store  β”‚
//! β”‚   (Input)       β”‚    β”‚   Pipeline      β”‚    β”‚   (Storage)     β”‚
//! β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
//!                                 β”‚
//!                                 β–Ό
//! β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
//! β”‚   Responses     │◀───│     Agent       │◀───│    Retriever    β”‚
//! β”‚   (Output)      β”‚    β”‚   (rsllm)       β”‚    β”‚   (Search)      β”‚
//! β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
//! ```
//!
//! ## πŸš€ Quick Start
//!
//! ### Basic RAG System
//!
//! ```rust
//! use rrag::prelude::*;
//!
//! #[tokio::main]
//! async fn main() -> RragResult<()> {
//!     // Create a RAG system
//!     let rag = RragSystemBuilder::new()
//!         .with_name("My RAG System")
//!         .with_environment("development")
//!         .build()
//!         .await?;
//!     
//!     // Add documents
//!     let doc = Document::new("Rust is a systems programming language...")
//!         .with_metadata("source", "documentation".into())
//!         .with_content_hash();
//!     
//!     rag.process_document(doc).await?;
//!     
//!     // Search for relevant content
//!     let results = rag.search("What is Rust?".to_string(), Some(5)).await?;
//!     println!("Found {} results", results.total_results);
//!     
//!     Ok(())
//! }
//! ```
//!
//! ### Advanced Agent with Tools
//!
//! ```rust
//! use rrag::prelude::*;
//!
//! #[tokio::main]
//! async fn main() -> RragResult<()> {
//!     // Create an agent with tools
//!     let mut agent = AgentBuilder::new()
//!         .with_model("gpt-4")
//!         .with_temperature(0.7)
//!         .with_streaming(true)
//!         .build()
//!         .await?;
//!     
//!     // Register tools
//!     agent.register_tool(Calculator::new())?;
//!     # #[cfg(feature = "http")]
//!     agent.register_tool(HttpTool::new())?;
//!     
//!     // Chat with memory
//!     let memory = ConversationBufferMemory::new(100);
//!     let response = agent.chat_with_memory(
//!         "Calculate 15 * 23",
//!         &memory
//!     ).await?;
//!     
//!     println!("Agent: {}", response.text);
//!     
//!     Ok(())
//! }
//! ```
//!
//! ## πŸ“¦ Feature Flags
//!
//! RRAG supports multiple feature flags for flexible deployments:
//!
//! - `default`: Core functionality with HTTP and concurrency support
//! - `rsllm-client`: Integration with rsllm for LLM operations
//! - `http`: HTTP client support for external services
//! - `concurrent`: Advanced concurrency features with DashMap
//! - `observability`: Metrics, monitoring, and alerting
//! - `security`: Authentication, authorization, and security features
//! - `security-full`: Complete security suite with 2FA and WebAuthn
//!
//! ```toml
//! [dependencies]
//! rrag = { version = "0.1", features = ["rsllm-client", "observability", "security"] }
//! ```

//!
//! ## πŸ—οΈ Module Organization
//!
//! RRAG is organized into focused modules, each handling specific aspects of RAG functionality:
//!
//! ### Core Modules
//!
//! - [`error`]: Comprehensive error handling with structured error types
//! - [`document`]: Document processing, chunking, and metadata management
//! - [`embeddings`]: Multi-provider embedding generation and management
//! - [`storage`]: Pluggable storage backends for documents and vectors
//! - [`memory`]: Conversation memory and context management
//! - [`agent`]: LLM agents with tool calling and streaming support
//! - [`pipeline`]: Composable processing pipelines
//! - [`system`]: High-level system orchestration and lifecycle management
//!
//! ### Advanced Modules
//!
//! - [`retrieval_core`]: Core retrieval interfaces and implementations
//! - [`retrieval_enhanced`]: Advanced hybrid retrieval with BM25 and semantic search
//! - [`reranking`]: Result reranking and relevance scoring
//! - [`evaluation`]: Framework for evaluating RAG system performance
//! - [`caching`]: Intelligent caching strategies for performance optimization
//! - [`graph_retrieval`]: Knowledge graph-based retrieval and reasoning
//! - [`incremental`]: Incremental indexing for large-scale document updates
//! - [`observability`]: Comprehensive monitoring, metrics, and alerting
//! - [`tools`]: Built-in and extensible tool implementations
//! - [`streaming`]: Real-time streaming response handling
//! - [`query`]: Query processing and optimization
//! - [`multimodal`]: Multi-modal content processing support

// Core modules - foundational components
pub mod agent;
pub mod document;
pub mod embeddings;
pub mod error;
pub mod memory;
pub mod pipeline;
pub mod retrieval_core;
pub mod storage;
pub mod streaming;
pub mod system;
pub mod tools;

// Enhanced retrieval capabilities
#[path = "retrieval/mod.rs"]
pub mod retrieval_enhanced;

// Query processing and optimization
pub mod query;

// Advanced reranking algorithms
pub mod reranking;

// Evaluation and benchmarking framework
pub mod evaluation;

// Intelligent caching layer
pub mod caching;

// Multi-modal content support
pub mod multimodal;

// Graph-based knowledge retrieval
pub mod graph_retrieval;

// Incremental indexing system
pub mod incremental;

// Observability and monitoring
pub mod observability;

// Re-exports for convenience
pub use agent::{AgentBuilder, AgentConfig, AgentResponse, ModelConfig, RragAgent, ToolCall};
pub use document::{ChunkingStrategy, Document, DocumentChunk, DocumentChunker, Metadata};
pub use embeddings::{
    Embedding, EmbeddingBatch, EmbeddingProvider, EmbeddingRequest, EmbeddingService,
    LocalEmbeddingProvider, MockEmbeddingService, OpenAIEmbeddingProvider,
};
pub use error::{ErrorSeverity, RragError, RragResult};
pub use memory::{
    ConversationBufferMemory, ConversationMessage, ConversationSummaryMemory,
    ConversationTokenBufferMemory, Memory, MemoryService, MessageRole,
};
pub use pipeline::{
    DocumentChunkingStep, EmbeddingStep, Pipeline, PipelineConfig, PipelineContext, PipelineData,
    PipelineStep, RagPipelineBuilder, RetrievalStep, TextOperation, TextPreprocessingStep,
};
pub use retrieval_core::{
    InMemoryRetriever, RetrievalService, Retriever, SearchAlgorithm, SearchConfig, SearchQuery,
    SearchResult,
};
pub use retrieval_enhanced::{
    BM25Config, BM25Retriever, FusionStrategy, HybridConfig, HybridRetriever, RankFusion,
    ReciprocalRankFusion, SemanticConfig, SemanticRetriever, TokenizerType, WeightedFusion,
};
pub use storage::{
    FileStorage, InMemoryStorage, Storage, StorageEntry, StorageKey, StorageQuery, StorageService,
};
pub use streaming::{StreamToken, StreamingResponse, TokenStreamBuilder, TokenType};
pub use system::{
    ChatResponse, HealthCheckResult, ProcessingResult, RragSystem, RragSystemBuilder,
    RragSystemConfig, SearchResponse, SystemMetrics,
};
#[cfg(feature = "http")]
pub use tools::HttpTool;
pub use tools::{Calculator, EchoTool, Tool, ToolRegistry, ToolResult};

// rsllm re-exports when feature is enabled
#[cfg(feature = "rsllm-client")]
pub use rsllm;

// Graph retrieval re-exports
pub use graph_retrieval::{
    EdgeType, Entity, EntityExtractor, EntityType, ExpansionResult, ExpansionStrategy,
    GraphAlgorithms, GraphBuildConfig, GraphConfig, GraphConfigBuilder, GraphEdge, GraphIndex,
    GraphMetrics, GraphNode, GraphQuery, GraphQueryResult, GraphRetrievalBuilder,
    GraphRetrievalConfig, GraphRetriever, GraphStorage, KnowledgeGraph, NodeType, PageRankConfig,
    PathFindingConfig, QueryExpander, RelationType, Relationship, TraversalConfig,
};

// Incremental indexing re-exports
pub use incremental::{
    AlertConfig, BatchConfig, BatchExecutor, BatchOperation, BatchProcessingStats, BatchProcessor,
    BatchResult, ChangeDetectionConfig, ChangeDetector, ChangeResult, ChangeType,
    ConflictResolution, ConsistencyReport, ContentDelta, DocumentChange, DocumentVersion,
    EmbeddingUpdate, HealthMetrics, IncrementalIndexManager, IncrementalIndexingService,
    IncrementalMetrics, IncrementalServiceBuilder, IncrementalServiceConfig, IndexManagerConfig,
    IndexOperation, IndexUpdate, IndexUpdateStrategy, IndexingStats, IntegrityChecker,
    IntegrityConfig, IntegrityError, MetricsCollector, MonitoringConfig, OperationLog,
    PerformanceTracker, QueueManager, RecoveryResult, RollbackConfig, RollbackManager,
    RollbackOperation, RollbackPoint, UpdateResult, ValidationResult, VectorBatch, VectorOperation,
    VectorUpdateConfig, VectorUpdateManager, VersionConflict, VersionHistory, VersionManager,
    VersionResolution, VersioningConfig,
};

// Observability re-exports
pub use observability::{
    AlertCondition, AlertManager, AlertNotification, AlertRule, AlertSeverity, BottleneckAnalysis,
    ComponentStatus, DashboardConfig, DashboardServer, DataRetention, ExportFormat, ExportManager,
    HealthChecker, HealthReport, HistoricalAnalyzer, LogAggregator, LogEntry, LogFilter, LogLevel,
    LogQuery, Metric, MetricType, MetricValue, MetricsCollector as ObsMetricsCollector,
    MetricsExporter, MetricsRegistry, ObservabilityBuilder, ObservabilityConfig,
    ObservabilitySystem, PerformanceMonitor, PerformanceReport, ProfileData, Profiler,
    RealtimeMetrics, ReportGenerator, RetentionPolicy, SearchAnalyzer, SystemMonitor,
    UserActivityTracker, WebSocketManager,
};

/// Prelude module for convenient imports
///
/// This module re-exports the most commonly used types and traits from RRAG,
/// making it easy to get started with a single import:
///
/// ```rust
/// use rrag::prelude::*;
/// ```
///
/// The prelude includes:
/// - Core system components ([`RragSystem`], [`RragSystemBuilder`])
/// - Document processing ([`Document`], [`DocumentChunk`], [`ChunkingStrategy`])
/// - Error handling ([`RragError`], [`RragResult`])
/// - Agents and tools ([`RragAgent`], [`Tool`], [`Calculator`])
/// - Memory management ([`Memory`], [`ConversationBufferMemory`])
/// - Streaming support ([`StreamingResponse`], [`StreamToken`])
/// - Pipeline processing ([`Pipeline`], [`RagPipelineBuilder`])
/// - Search functionality ([`SearchResult`], [`SearchQuery`])
/// - Advanced features (incremental indexing, observability)
///
/// ## Feature-Gated Exports
///
/// Some exports are only available with specific features:
/// - `rsllm-client`: [`rsllm`] integration
/// - `http`: HTTP-based tools like [`HttpTool`]
///
/// ## External Dependencies
///
/// Common external crates are also re-exported for convenience:
/// - [`tokio`]: Async runtime
/// - [`serde`]: Serialization traits
/// - [`futures`]: Stream processing
/// - [`async_trait`]: Async trait support
pub mod prelude {
    //! Convenient re-exports for common RRAG functionality
    //!
    //! Import everything you need with:
    //! ```rust
    //! use rrag::prelude::*;
    //! ```

    // System components
    pub use crate::{
        ChatResponse, HealthCheckResult, ProcessingResult, RragSystem, RragSystemBuilder,
        RragSystemConfig, SearchResponse, SystemMetrics,
    };

    // Core types and error handling
    pub use crate::{
        ChunkingStrategy, Document, DocumentChunk, DocumentChunker, Embedding, EmbeddingProvider,
        EmbeddingService, ErrorSeverity, Metadata, RragError, RragResult,
    };

    // Service interfaces
    pub use crate::{
        InMemoryRetriever, MemoryService, RetrievalService, SearchConfig, SearchQuery,
        SearchResult, StorageService,
    };

    // Agents and tools
    pub use crate::{
        AgentBuilder, AgentConfig, AgentResponse, Calculator, RragAgent, Tool, ToolRegistry,
        ToolResult,
    };

    // HTTP tools when feature is enabled
    #[cfg(feature = "http")]
    pub use crate::HttpTool;

    // Memory and conversations
    pub use crate::{
        ConversationBufferMemory, ConversationMessage, ConversationSummaryMemory,
        ConversationTokenBufferMemory, Memory, MessageRole,
    };

    // Streaming support
    pub use crate::{StreamToken, StreamingResponse, TokenStreamBuilder, TokenType};

    // Pipeline processing
    pub use crate::{
        DocumentChunkingStep, EmbeddingStep, Pipeline, PipelineContext, PipelineData, PipelineStep,
        RagPipelineBuilder, RetrievalStep, TextOperation, TextPreprocessingStep,
    };

    // Enhanced retrieval
    pub use crate::{
        BM25Retriever, FusionStrategy, HybridConfig, HybridRetriever, RankFusion,
        ReciprocalRankFusion, SemanticRetriever,
    };

    // Incremental indexing
    pub use crate::{
        BatchProcessor, ChangeDetector, ChangeResult, ChangeType, IncrementalIndexManager,
        IncrementalIndexingService, IncrementalServiceBuilder, IntegrityChecker, MetricsCollector,
        RollbackManager, VectorUpdateManager, VersionManager,
    };

    // Graph retrieval
    pub use crate::{
        EntityExtractor, GraphEdge, GraphNode, GraphRetrievalBuilder, GraphRetriever,
        KnowledgeGraph, QueryExpander,
    };

    // Observability
    pub use crate::{AlertManager, HealthChecker, MetricsRegistry, ObservabilitySystem, Profiler};

    // External dependencies commonly used with RRAG
    pub use async_trait::async_trait;
    pub use futures::{Stream, StreamExt};
    pub use serde::{Deserialize, Serialize};
    pub use tokio;

    // rsllm integration when feature is enabled
    #[cfg(feature = "rsllm-client")]
    pub use rsllm;
}

/// Framework constants and metadata
///
/// These constants provide version and identification information for the RRAG framework.

/// Current version of the RRAG framework
///
/// This version is automatically synchronized with the version in `Cargo.toml`.
/// Use this for version checking, compatibility testing, or reporting.
///
/// # Example
/// ```rust
/// use rrag::VERSION;
/// println!("RRAG Framework version: {}", VERSION);
/// ```
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Framework name identifier
///
/// The canonical name of the framework, used for logging, metrics,
/// and system identification.
pub const NAME: &str = "RRAG";

/// Framework description
///
/// A brief description of the framework's purpose and capabilities.
pub const DESCRIPTION: &str =
    "Rust RAG Framework - High-performance Retrieval-Augmented Generation";

/// Framework repository URL
///
/// The primary repository location for source code, issues, and documentation.
pub const REPOSITORY: &str = "https://github.com/leval-ai/rrag";

/// Framework license
///
/// The software license under which RRAG is distributed.
pub const LICENSE: &str = "MIT";

/// Minimum supported Rust version (MSRV)
///
/// The minimum version of Rust required to compile and use RRAG.
pub const MSRV: &str = "1.70.0";