rucora 0.1.5

High-performance, type-safe LLM agent framework with built-in tools and multi-provider support
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
//! RAG(检索增强生成)管线模块
//!
//! # 概述
//!
//! 本模块提供 RAG(Retrieval-Augmented Generation)的最小管线实现,包括:
//! - 文本分块(chunking)
//! - 索引(indexing)
//! - 检索(retrieval)
//! - 引用生成(citation)
//!
//! # RAG 流程
//!
//! ```text
//! 原始文本
//!//!//! ┌─────────────────┐
//! │  chunk_text()   │ 文本分块
//! └────────┬────────┘
//!//!//! ┌─────────────────┐
//! │ index_chunks()  │ 嵌入并索引
//! └────────┬────────┘
//!//!//!      向量存储
//!
//! --- 查询阶段 ---
//!
//! 用户查询
//!//!//! ┌─────────────────┐
//! │   retrieve()    │ 检索相关片段
//! └────────┬────────┘
//!//!//!   Citation 列表
//! ```
//!
//! # 使用示例
//!
//! ## 索引文本
//!
//! ```rust,no_run
//! use rucora::embed::OpenAiEmbedding;
//! use rucora::retrieval::ChromaVectorStore;
//! use rucora::rag::{index_text, chunk_text};
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let embedder = OpenAiEmbedding::from_env()?;
//! let store = ChromaVectorStore::from_env()?;
//!
//! // 分块并索引
//! let chunks = index_text(
//!     &embedder,
//!     &store,
//!     "doc1",           // 文档 ID
//!     "这是一段长文本...", // 原始文本
//!     500,              // 每块最大字符数
//!     50,               // 重叠字符数
//! ).await?;
//!
//! println!("索引了 {} 个块", chunks.len());
//! # Ok(())
//! # }
//! ```
//!
//! ## 检索引用
//!
//! ```rust,no_run
//! use rucora::embed::OpenAiEmbedding;
//! use rucora::retrieval::ChromaVectorStore;
//! use rucora::rag::retrieve;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let embedder = OpenAiEmbedding::from_env()?;
//! let store = ChromaVectorStore::from_env()?;
//!
//! // 检索相关片段
//! let citations = retrieve(
//!     &embedder,
//!     &store,
//!     "查询问题",
//!     5,  // top_k
//! ).await?;
//!
//! for cite in citations {
//!     println!("引用:{}", cite.text.unwrap_or_default());
//! }
//! # Ok(())
//! # }
//! ```
//!
//! # 核心函数
//!
//! ## chunk_text
//!
//! 将长文本分块,支持重叠:
//!
//! ```rust
//! use rucora::rag::chunk_text;
//!
//! let chunks = chunk_text(
//!     "doc1",      // 文档 ID
//!     "长文本...",  // 原始文本
//!     500,         // 每块最大字符数
//!     50,          // 重叠字符数
//! );
//! ```
//!
//! ## index_chunks
//!
//! 将分块嵌入并索引到向量存储:
//!
//! ```rust,no_run
//! use rucora::rag::index_chunks;
//! # use rucora::embed::OpenAiEmbedding;
//! # use rucora::retrieval::ChromaVectorStore;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let embedder = OpenAiEmbedding::from_env()?;
//! let store = ChromaVectorStore::from_env()?;
//! let chunks = vec![];  // TextChunk 列表
//!
//! index_chunks(&embedder, &store, &chunks).await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## retrieve
//!
//! 检索相关片段并生成引用:
//!
//! ```rust,no_run
//! use rucora::rag::retrieve;
//! # use rucora::embed::OpenAiEmbedding;
//! # use rucora::retrieval::ChromaVectorStore;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let embedder = OpenAiEmbedding::from_env()?;
//! let store = ChromaVectorStore::from_env()?;
//!
//! let citations = retrieve(&embedder, &store, "查询", 5).await?;
//! # Ok(())
//! # }
//! ```
//!
//! # Citation 格式
//!
//! [`Citation`] 包含检索结果的完整信息:
//!
//! ```rust
//! use rucora::rag::Citation;
//!
//! let citation = Citation {
//!     doc_id: Some("doc1".to_string()),
//!     chunk_id: "doc1:0".to_string(),
//!     score: 0.95,
//!     text: Some("相关片段内容".to_string()),
//!     metadata: None,
//! };
//!
//! // 渲染引用标识
//! println!("引用自:{}", citation.render());
//! ```
//!
//! # 最佳实践
//!
//! ## 分块大小
//!
//! - **小文本**(< 1000 字符): 不需要分块
//! - **中等文本**(1000-5000 字符): 500 字符/块,50 字符重叠
//! - **大文本**(> 5000 字符): 1000 字符/块,100 字符重叠
//!
//! ## TopK 选择
//!
//! - **精确查询**: top_k = 3-5
//! - **模糊查询**: top_k = 5-10
//! - **探索性查询**: top_k = 10-20
//!
//! ## 性能优化
//!
//! - 使用 [`CachedEmbeddingProvider`] 减少重复嵌入
//! - 批量嵌入(`embed_batch`)优于单次嵌入
//! - 定期清理向量存储(`clear`)

use rucora_core::{
    embed::EmbeddingProvider,
    error::ProviderError,
    retrieval::{SearchResult, VectorQuery, VectorRecord, VectorStore},
};
use serde_json::{Value, json};

/// 文本块
///
/// 包含分块后的文本及其元数据。
///
/// # 字段说明
///
/// - `id`: 块的唯一标识(格式:`{doc_id}:{chunk_index}`)
/// - `text`: 块内容
/// - `metadata`: 元数据(文档 ID、块索引、位置等)
///
/// # 示例
///
/// ```rust
/// use rucora::rag::TextChunk;
///
/// let chunk = TextChunk {
///     id: "doc1:0".to_string(),
///     text: "Hello, World!".to_string(),
///     metadata: Some(serde_json::json!({
///         "doc_id": "doc1",
///         "chunk_index": 0,
///         "start_char": 0,
///         "end_char": 13
///     })),
/// };
/// ```
#[derive(Debug, Clone)]
pub struct TextChunk {
    /// 块的唯一标识
    pub id: String,
    /// 块内容
    pub text: String,
    /// 元数据
    pub metadata: Option<Value>,
}

/// 将文本分块
///
/// # 参数
///
/// - `doc_id`: 文档 ID
/// - `text`: 原始文本
/// - `max_chars`: 每块最大字符数
/// - `overlap_chars`: 块间重叠字符数
///
/// # 返回值
///
/// 返回 [`TextChunk`] 列表。
///
/// # 示例
///
/// ```rust
/// use rucora::rag::chunk_text;
///
/// let chunks = chunk_text(
///     "doc1",
///     "这是一段长文本,需要分成多个块。",
///     100,  // 每块最大 100 字符
///     10,   // 重叠 10 字符
/// );
///
/// for chunk in chunks {
///     println!("块 {}: {}", chunk.id, chunk.text);
/// }
/// ```
pub fn chunk_text(
    doc_id: &str,
    text: &str,
    max_chars: usize,
    overlap_chars: usize,
) -> Vec<TextChunk> {
    let max_chars = max_chars.max(1);
    let overlap_chars = overlap_chars.min(max_chars.saturating_sub(1));

    let chars: Vec<char> = text.chars().collect();
    if chars.is_empty() {
        return Vec::new();
    }

    let mut out = Vec::new();
    let mut start = 0usize;
    let mut idx = 0usize;

    while start < chars.len() {
        let end = (start + max_chars).min(chars.len());
        let chunk_text: String = chars[start..end].iter().collect();
        let id = format!("{doc_id}:{idx}");

        out.push(TextChunk {
            id,
            text: chunk_text,
            metadata: Some(
                json!({"doc_id": doc_id, "chunk_index": idx, "start_char": start, "end_char": end}),
            ),
        });

        if end == chars.len() {
            break;
        }

        idx += 1;
        start = end.saturating_sub(overlap_chars);
        if start >= end {
            start = end;
        }
    }

    out
}

/// 索引分块列表
///
/// # 参数
///
/// - `embedder`: Embedding Provider
/// - `store`: VectorStore
/// - `chunks`: [`TextChunk`] 列表
///
/// # 返回值
///
/// 成功返回 `Ok(())`,失败返回 [`ProviderError`]。
///
/// # 示例
///
/// ```rust,no_run
/// use rucora::rag::{chunk_text, index_chunks};
/// use rucora::embed::OpenAiEmbedding;
/// use rucora::retrieval::ChromaVectorStore;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let embedder = OpenAiEmbedding::from_env()?;
/// let store = ChromaVectorStore::from_env()?;
///
/// let chunks = chunk_text("doc1", "长文本...", 500, 50);
/// index_chunks(&embedder, &store, &chunks).await?;
/// # Ok(())
/// # }
/// ```
pub async fn index_chunks<P, S>(
    embedder: &P,
    store: &S,
    chunks: &[TextChunk],
) -> Result<(), ProviderError>
where
    P: EmbeddingProvider,
    S: VectorStore,
{
    if chunks.is_empty() {
        return Ok(());
    }

    let texts: Vec<String> = chunks.iter().map(|c| c.text.clone()).collect();
    let vectors = embedder.embed_batch(&texts).await?;

    if vectors.len() != chunks.len() {
        return Err(ProviderError::Message(
            "embed_batch 返回的向量数量与输入不一致".to_string(),
        ));
    }

    let records: Vec<VectorRecord> = chunks
        .iter()
        .zip(vectors)
        .map(|(c, v)| {
            let mut r = VectorRecord::new(c.id.clone(), v).with_text(c.text.clone());
            if let Some(md) = &c.metadata {
                r = r.with_metadata(md.clone());
            }
            r
        })
        .collect();

    store.upsert(records).await
}

/// 索引文本
///
///  Convenience 函数:先分块,再索引。
///
/// # 参数
///
/// - `embedder`: Embedding Provider
/// - `store`: VectorStore
/// - `doc_id`: 文档 ID
/// - `text`: 原始文本
/// - `max_chars`: 每块最大字符数
/// - `overlap_chars`: 块间重叠字符数
///
/// # 返回值
///
/// 返回 [`TextChunk`] 列表。
///
/// # 示例
///
/// ```rust,no_run
/// use rucora::rag::index_text;
/// use rucora::embed::OpenAiEmbedding;
/// use rucora::retrieval::ChromaVectorStore;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let embedder = OpenAiEmbedding::from_env()?;
/// let store = ChromaVectorStore::from_env()?;
///
/// let chunks = index_text(
///     &embedder,
///     &store,
///     "doc1",
///     "长文本...",
///     500,
///     50,
/// ).await?;
/// # Ok(())
/// # }
/// ```
pub async fn index_text<P, S>(
    embedder: &P,
    store: &S,
    doc_id: &str,
    text: &str,
    max_chars: usize,
    overlap_chars: usize,
) -> Result<Vec<TextChunk>, ProviderError>
where
    P: EmbeddingProvider,
    S: VectorStore,
{
    let chunks = chunk_text(doc_id, text, max_chars, overlap_chars);
    index_chunks(embedder, store, &chunks).await?;
    Ok(chunks)
}

/// 引用
///
/// 包含检索结果及其元数据,用于生成回答时的引用。
///
/// # 字段说明
///
/// - `doc_id`: 文档 ID(可选)
/// - `chunk_id`: 块 ID
/// - `score`: 相似度分数
/// - `text`: 块内容(可选)
/// - `metadata`: 元数据(可选)
///
/// # 示例
///
/// ```rust
/// use rucora::rag::Citation;
///
/// let citation = Citation {
///     doc_id: Some("doc1".to_string()),
///     chunk_id: "doc1:0".to_string(),
///     score: 0.95,
///     text: Some("相关片段内容".to_string()),
///     metadata: None,
/// };
///
/// // 渲染引用标识
/// println!("引用自:{}", citation.render());
/// ```
#[derive(Debug, Clone)]
pub struct Citation {
    /// 文档 ID(可选)
    pub doc_id: Option<String>,
    /// 块 ID
    pub chunk_id: String,
    /// 相似度分数
    pub score: f32,
    /// 块内容(可选)
    pub text: Option<String>,
    /// 元数据(可选)
    pub metadata: Option<Value>,
}

impl Citation {
    /// 渲染引用标识
    ///
    /// # 示例
    ///
    /// ```rust
    /// use rucora::rag::Citation;
    ///
    /// let citation = Citation {
    ///     doc_id: Some("doc1".to_string()),
    ///     chunk_id: "0".to_string(),
    ///     score: 0.95,
    ///     text: None,
    ///     metadata: None,
    /// };
    ///
    /// assert_eq!(citation.render(), "doc1:0");
    /// ```
    pub fn render(&self) -> String {
        match &self.doc_id {
            Some(d) => format!("{}:{}", d, self.chunk_id),
            None => self.chunk_id.clone(),
        }
    }
}

/// 检索相关片段
///
/// # 参数
///
/// - `embedder`: Embedding Provider
/// - `store`: VectorStore
/// - `query_text`: 查询文本
/// - `top_k`: 返回数量
///
/// # 返回值
///
/// 返回 [`Citation`] 列表。
///
/// # 示例
///
/// ```rust,no_run
/// use rucora::rag::retrieve;
/// use rucora::embed::OpenAiEmbedding;
/// use rucora::retrieval::ChromaVectorStore;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let embedder = OpenAiEmbedding::from_env()?;
/// let store = ChromaVectorStore::from_env()?;
///
/// let citations = retrieve(&embedder, &store, "查询问题", 5).await?;
///
/// for cite in citations {
///     println!("引用 [{}]: {}", cite.render(), cite.text.unwrap_or_default());
/// }
/// # Ok(())
/// # }
/// ```
pub async fn retrieve<P, S>(
    embedder: &P,
    store: &S,
    query_text: &str,
    top_k: usize,
) -> Result<Vec<Citation>, ProviderError>
where
    P: EmbeddingProvider,
    S: VectorStore,
{
    let vector = embedder.embed(query_text).await?;
    let query = VectorQuery::new(vector).with_top_k(top_k);
    let results = store.search(query).await?;
    Ok(results.into_iter().map(search_result_to_citation).collect())
}

/// 将 SearchResult 转换为 Citation
fn search_result_to_citation(r: SearchResult) -> Citation {
    let doc_id = r
        .metadata
        .as_ref()
        .and_then(|m| m.get("doc_id"))
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    Citation {
        doc_id,
        chunk_id: r.id,
        score: r.score,
        text: r.text,
        metadata: r.metadata,
    }
}