bigrag 0.1.1

Rust client for bigRAG — a self-hostable RAG platform
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
use std::time::Duration;

use crate::core::Transport;
use crate::error::BigRagError;
use crate::files::FileInput;
use crate::resources::collections::Collections;
use crate::resources::documents::Documents;
use crate::resources::queries::Queries;
use crate::resources::vectors::Vectors;
use crate::resources::webhooks::Webhooks;
use crate::sse::SseStream;
use crate::types::analytics::AnalyticsResponse;
use crate::types::collections::CollectionStatsResponse;
use crate::types::common::{HealthResponse, PlatformStatsResponse, ReadinessResponse, StatusResponse};
use crate::types::documents::{
    BatchDeleteDocumentsResponse, BatchGetDocumentsResponse, BatchStatusResponse, Document,
    DocumentChunkListResponse, DocumentListOptions, DocumentListResponse, S3IngestBody,
    S3IngestResponse, S3JobListResponse,
};
use crate::types::embeddings::EmbeddingModelListResponse;
use crate::types::query::{QueryBody, QueryResponse};

const DEFAULT_BASE_URL: &str = "http://localhost:6100";
const DEFAULT_TIMEOUT_SECS: u64 = 120;
const DEFAULT_MAX_RETRIES: u32 = 2;

/// Configuration for the bigRAG client.
#[derive(Debug, Clone)]
pub struct BigRagConfig {
    /// Base URL of the bigRAG API.
    pub base_url: String,
    /// API key for authentication.
    pub api_key: Option<String>,
    /// Request timeout.
    pub timeout: Duration,
    /// Maximum number of retries for transient errors.
    pub max_retries: u32,
}

/// The bigRAG client.
///
/// # Examples
///
/// ```no_run
/// use bigrag::BigRag;
///
/// # async fn example() -> Result<(), bigrag::BigRagError> {
/// let client = BigRag::new("http://localhost:6100", "sk-...");
/// let collections = client.collections().list(None).await?;
/// # Ok(())
/// # }
/// ```
pub struct BigRag {
    pub(crate) transport: Transport,
    pub(crate) config: BigRagConfig,
}

impl BigRag {
    /// Create a new client with a base URL and API key.
    pub fn new(base_url: &str, api_key: &str) -> Self {
        let config = BigRagConfig {
            base_url: base_url.trim_end_matches('/').to_string(),
            api_key: Some(api_key.to_string()),
            timeout: Duration::from_secs(DEFAULT_TIMEOUT_SECS),
            max_retries: DEFAULT_MAX_RETRIES,
        };
        let transport = Transport::new(
            &config.base_url,
            config.api_key.clone(),
            config.timeout,
            config.max_retries,
        );
        Self { transport, config }
    }

    /// Create a new client from environment variables.
    ///
    /// Reads `BIGRAG_BASE_URL` (default: `http://localhost:6100`) and
    /// `BIGRAG_API_KEY` (optional).
    pub fn from_env() -> Result<Self, BigRagError> {
        let base_url =
            std::env::var("BIGRAG_BASE_URL").unwrap_or_else(|_| DEFAULT_BASE_URL.to_string());
        let api_key = std::env::var("BIGRAG_API_KEY").ok();
        let config = BigRagConfig {
            base_url: base_url.trim_end_matches('/').to_string(),
            api_key,
            timeout: Duration::from_secs(DEFAULT_TIMEOUT_SECS),
            max_retries: DEFAULT_MAX_RETRIES,
        };
        let transport = Transport::new(
            &config.base_url,
            config.api_key.clone(),
            config.timeout,
            config.max_retries,
        );
        Ok(Self { transport, config })
    }

    /// Create a builder for fine-grained configuration.
    pub fn builder() -> BigRagBuilder {
        BigRagBuilder::default()
    }

    /// Access the collections resource.
    pub fn collections(&self) -> Collections<'_> {
        Collections { client: self }
    }

    /// Access the documents resource.
    pub fn documents(&self) -> Documents<'_> {
        Documents { client: self }
    }

    /// Access the queries resource.
    pub fn queries(&self) -> Queries<'_> {
        Queries { client: self }
    }

    /// Access the vectors resource.
    pub fn vectors(&self) -> Vectors<'_> {
        Vectors { client: self }
    }

    /// Access the webhooks resource.
    pub fn webhooks(&self) -> Webhooks<'_> {
        Webhooks { client: self }
    }

    /// Create a collection-scoped client for convenience.
    pub fn collection(&self, name: &str) -> CollectionClient<'_> {
        CollectionClient {
            client: self,
            name: name.to_string(),
        }
    }

    /// Check API health.
    pub async fn health(&self) -> Result<HealthResponse, BigRagError> {
        self.transport.get("/health", vec![]).await
    }

    /// Check API readiness (includes dependency health).
    pub async fn readiness(&self) -> Result<ReadinessResponse, BigRagError> {
        self.transport.get("/health/ready", vec![]).await
    }

    /// Get platform-wide statistics.
    pub async fn stats(&self) -> Result<PlatformStatsResponse, BigRagError> {
        self.transport.get("/v1/stats", vec![]).await
    }

    /// List available embedding models.
    pub async fn embedding_models(&self) -> Result<EmbeddingModelListResponse, BigRagError> {
        self.transport.get("/v1/embeddings/models", vec![]).await
    }

    /// Get analytics for a collection.
    pub async fn analytics(&self, collection: &str) -> Result<AnalyticsResponse, BigRagError> {
        let path = format!("/v1/collections/{}/analytics", crate::core::urlencode(collection));
        self.transport.get(&path, vec![]).await
    }
}

/// Builder for creating a [`BigRag`] client with custom configuration.
#[derive(Default)]
pub struct BigRagBuilder {
    base_url: Option<String>,
    api_key: Option<String>,
    timeout: Option<Duration>,
    max_retries: Option<u32>,
    reqwest_client: Option<reqwest::Client>,
}

impl BigRagBuilder {
    /// Set the base URL.
    pub fn base_url(mut self, url: &str) -> Self {
        self.base_url = Some(url.to_string());
        self
    }

    /// Set the API key.
    pub fn api_key(mut self, key: &str) -> Self {
        self.api_key = Some(key.to_string());
        self
    }

    /// Set the request timeout.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Set the maximum number of retries.
    pub fn max_retries(mut self, retries: u32) -> Self {
        self.max_retries = Some(retries);
        self
    }

    /// Provide a pre-configured `reqwest::Client`.
    pub fn reqwest_client(mut self, client: reqwest::Client) -> Self {
        self.reqwest_client = Some(client);
        self
    }

    /// Build the client.
    pub fn build(self) -> Result<BigRag, BigRagError> {
        let config = BigRagConfig {
            base_url: self
                .base_url
                .unwrap_or_else(|| DEFAULT_BASE_URL.to_string())
                .trim_end_matches('/')
                .to_string(),
            api_key: self.api_key,
            timeout: self
                .timeout
                .unwrap_or(Duration::from_secs(DEFAULT_TIMEOUT_SECS)),
            max_retries: self.max_retries.unwrap_or(DEFAULT_MAX_RETRIES),
        };

        let transport = if let Some(http) = self.reqwest_client {
            Transport::with_client(
                http,
                &config.base_url,
                config.api_key.clone(),
                config.timeout,
                config.max_retries,
            )
        } else {
            Transport::new(
                &config.base_url,
                config.api_key.clone(),
                config.timeout,
                config.max_retries,
            )
        };

        Ok(BigRag { transport, config })
    }
}

/// A collection-scoped client for convenience.
///
/// All methods automatically use the bound collection name.
///
/// # Examples
///
/// ```no_run
/// use bigrag::BigRag;
///
/// # async fn example() -> Result<(), bigrag::BigRagError> {
/// let client = BigRag::new("http://localhost:6100", "sk-...");
/// let col = client.collection("my-collection");
/// let docs = col.list_documents(None).await?;
/// # Ok(())
/// # }
/// ```
pub struct CollectionClient<'a> {
    pub(crate) client: &'a BigRag,
    pub(crate) name: String,
}

impl CollectionClient<'_> {
    /// Upload a file to this collection.
    pub async fn upload(
        &self,
        file: impl Into<FileInput>,
        metadata: Option<serde_json::Value>,
    ) -> Result<Document, BigRagError> {
        self.client.documents().upload(&self.name, file, metadata).await
    }

    /// Batch upload files to this collection.
    pub async fn batch_upload(
        &self,
        files: Vec<FileInput>,
        metadata: Option<serde_json::Value>,
    ) -> Result<DocumentListResponse, BigRagError> {
        self.client.documents().batch_upload(&self.name, files, metadata).await
    }

    /// List documents in this collection.
    pub async fn list_documents(
        &self,
        options: Option<DocumentListOptions>,
    ) -> Result<DocumentListResponse, BigRagError> {
        self.client.documents().list(&self.name, options).await
    }

    /// Get a document by ID in this collection.
    pub async fn get_document(&self, document_id: &str) -> Result<Document, BigRagError> {
        self.client.documents().get(&self.name, document_id).await
    }

    /// Delete a document from this collection.
    pub async fn delete_document(&self, document_id: &str) -> Result<StatusResponse, BigRagError> {
        self.client.documents().delete(&self.name, document_id).await
    }

    /// Reprocess a document in this collection.
    pub async fn reprocess_document(&self, document_id: &str) -> Result<StatusResponse, BigRagError> {
        self.client.documents().reprocess(&self.name, document_id).await
    }

    /// Get chunks for a document in this collection.
    pub async fn get_document_chunks(&self, document_id: &str) -> Result<DocumentChunkListResponse, BigRagError> {
        self.client.documents().get_chunks(&self.name, document_id).await
    }

    /// Get batch document status.
    pub async fn batch_get_status(&self, document_ids: &[&str]) -> Result<BatchStatusResponse, BigRagError> {
        self.client.documents().batch_get_status(&self.name, document_ids).await
    }

    /// Get batch documents.
    pub async fn batch_get_documents(&self, document_ids: &[&str]) -> Result<BatchGetDocumentsResponse, BigRagError> {
        self.client.documents().batch_get(&self.name, document_ids).await
    }

    /// Batch delete documents.
    pub async fn batch_delete(&self, document_ids: &[&str]) -> Result<BatchDeleteDocumentsResponse, BigRagError> {
        self.client.documents().batch_delete(&self.name, document_ids).await
    }

    /// Ingest from S3.
    pub async fn ingest_s3(&self, body: S3IngestBody) -> Result<S3IngestResponse, BigRagError> {
        self.client.documents().ingest_s3(&self.name, body).await
    }

    /// List S3 jobs.
    pub async fn list_s3_jobs(&self) -> Result<S3JobListResponse, BigRagError> {
        self.client.documents().list_s3_jobs(&self.name).await
    }

    /// Query this collection.
    pub async fn query(&self, body: QueryBody) -> Result<QueryResponse, BigRagError> {
        self.client.queries().query(&self.name, body).await
    }

    /// Get collection statistics.
    pub async fn stats(&self) -> Result<CollectionStatsResponse, BigRagError> {
        self.client.collections().stats(&self.name).await
    }

    /// Get collection analytics.
    pub async fn analytics(&self) -> Result<AnalyticsResponse, BigRagError> {
        let path = format!("/v1/collections/{}/analytics", &self.name);
        self.client.transport.get(&path, vec![]).await
    }

    /// Stream real-time events for this collection via SSE.
    pub async fn stream_events(&self) -> Result<SseStream, BigRagError> {
        self.client.collections().stream_events(&self.name).await
    }

    /// Stream processing progress for a document in this collection.
    pub async fn stream_document_progress(&self, document_id: &str) -> Result<SseStream, BigRagError> {
        self.client.documents().stream_progress(&self.name, document_id).await
    }

}

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

    #[test]
    fn test_new_sets_defaults() {
        let client = BigRag::new("http://localhost:6100", "sk-test");
        assert_eq!(client.config.base_url, "http://localhost:6100");
        assert_eq!(client.config.api_key.as_deref(), Some("sk-test"));
    }

    #[test]
    fn test_builder_defaults() {
        let client = BigRag::builder().api_key("sk-test").build().unwrap();
        assert_eq!(client.config.base_url, "http://localhost:6100");
    }

    #[test]
    fn test_builder_custom_base_url() {
        let client = BigRag::builder()
            .base_url("https://custom.example.com")
            .api_key("sk-test")
            .build()
            .unwrap();
        assert_eq!(client.config.base_url, "https://custom.example.com");
    }

    #[test]
    fn test_builder_strips_trailing_slash() {
        let client = BigRag::builder()
            .base_url("https://example.com/")
            .api_key("sk-test")
            .build()
            .unwrap();
        assert_eq!(client.config.base_url, "https://example.com");
    }

    #[test]
    fn test_resource_accessors_compile() {
        let client = BigRag::new("http://localhost:6100", "sk-test");
        let _collections = client.collections();
        let _documents = client.documents();
        let _queries = client.queries();
        let _vectors = client.vectors();
        let _webhooks = client.webhooks();
        let _col_client = client.collection("test");
    }
}