llama-gguf 0.14.0

A high-performance Rust implementation of llama.cpp - LLM inference engine with full GGUF 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
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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
//! Knowledge Base - AWS Bedrock-style RAG interface
//!
//! This module provides a high-level Knowledge Base abstraction similar to
//! AWS Bedrock Knowledge Bases, with features like:
//!
//! - Multiple data source types (files, directories, URLs)
//! - Configurable chunking strategies (fixed, semantic, hierarchical)
//! - Hybrid search (semantic + keyword)
//! - Result reranking
//! - Source citations
//! - Retrieve and Generate (RAG) pipeline
//!
//! # Example
//!
//! ```rust,ignore
//! use llama_gguf::rag::{KnowledgeBase, KnowledgeBaseConfig, DataSource, ChunkingStrategy};
//!
//! // Create a knowledge base
//! let kb = KnowledgeBase::create(KnowledgeBaseConfig {
//!     name: "my-kb".into(),
//!     description: Some("My knowledge base".into()),
//!     chunking: ChunkingStrategy::FixedSize { 
//!         max_tokens: 300, 
//!         overlap_percentage: 20 
//!     },
//!     ..Default::default()
//! }).await?;
//!
//! // Ingest data
//! kb.ingest(DataSource::Directory { 
//!     path: "./docs".into(),
//!     pattern: Some("**/*.md".into()),
//! }).await?;
//!
//! // Retrieve and generate
//! let response = kb.retrieve_and_generate(
//!     "What is the main feature?",
//!     RetrievalConfig::default(),
//! ).await?;
//!
//! println!("Answer: {}", response.output);
//! for citation in response.citations {
//!     println!("Source: {} (score: {:.2})", citation.source, citation.score);
//! }
//! ```

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;

use crate::backend::Backend;
use crate::model::LlamaModel;
use crate::tokenizer::Tokenizer;

use super::{
    Document, EmbeddingGenerator, MetadataFilter, NewDocument, RagConfig, RagError, RagResult,
    RagStore, SearchType, TextChunker,
};

// =============================================================================
// Configuration Types
// =============================================================================

/// Knowledge base configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KnowledgeBaseConfig {
    /// Unique name for the knowledge base
    pub name: String,

    /// Optional description
    #[serde(default)]
    pub description: Option<String>,

    /// RAG store configuration
    #[serde(default)]
    pub storage: RagConfig,

    /// Chunking strategy for documents
    #[serde(default)]
    pub chunking: ChunkingStrategy,

    /// Search/retrieval configuration
    #[serde(default)]
    pub retrieval: RetrievalConfig,

    /// Whether to enable hybrid search (semantic + keyword)
    #[serde(default)]
    pub hybrid_search: bool,

    /// Reranking configuration
    #[serde(default)]
    pub reranking: Option<RerankingConfig>,
}

impl Default for KnowledgeBaseConfig {
    fn default() -> Self {
        Self {
            name: "default".into(),
            description: None,
            storage: RagConfig::default(),
            chunking: ChunkingStrategy::default(),
            retrieval: RetrievalConfig::default(),
            hybrid_search: false,
            reranking: None,
        }
    }
}

/// Chunking strategy for splitting documents
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ChunkingStrategy {
    /// No chunking - store documents as-is
    None,

    /// Fixed size chunks with optional overlap
    FixedSize {
        /// Maximum tokens per chunk (approximate, based on chars/4)
        max_tokens: usize,
        /// Overlap percentage between chunks (0-50)
        overlap_percentage: u8,
    },

    /// Semantic chunking - split on sentence/paragraph boundaries
    Semantic {
        /// Maximum tokens per chunk
        max_tokens: usize,
        /// Buffer size for boundary detection
        buffer_size: usize,
    },

    /// Hierarchical chunking - parent/child relationships
    Hierarchical {
        /// Parent chunk max tokens
        parent_max_tokens: usize,
        /// Child chunk max tokens
        child_max_tokens: usize,
        /// Overlap percentage for child chunks
        child_overlap_percentage: u8,
    },
}

impl Default for ChunkingStrategy {
    fn default() -> Self {
        Self::FixedSize {
            max_tokens: 300,
            overlap_percentage: 20,
        }
    }
}

/// Search/retrieval configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RetrievalConfig {
    /// Maximum number of results to retrieve
    #[serde(default = "default_max_results")]
    pub max_results: usize,

    /// Minimum similarity score (0.0-1.0)
    #[serde(default = "default_min_score")]
    pub min_score: f32,

    /// Search type
    #[serde(default)]
    pub search_type: SearchType,

    /// Optional metadata filter
    #[serde(skip)]
    pub filter: Option<MetadataFilter>,

    /// Override prompt template for generation
    #[serde(default)]
    pub prompt_template: Option<String>,
}

fn default_max_results() -> usize {
    5
}
fn default_min_score() -> f32 {
    0.5
}

impl Default for RetrievalConfig {
    fn default() -> Self {
        Self {
            max_results: 5,
            min_score: 0.5,
            search_type: SearchType::Semantic,
            filter: None,
            prompt_template: None,
        }
    }
}

/// Reranking configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RerankingConfig {
    /// Number of candidates to fetch before reranking
    pub num_candidates: usize,
    /// Reranking model/method
    pub method: RerankingMethod,
}

/// Reranking methods
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum RerankingMethod {
    /// Simple score-based reranking
    ScoreBased,
    /// Cross-encoder reranking (requires model)
    CrossEncoder { model_path: String },
    /// Reciprocal Rank Fusion for hybrid search
    RRF { k: usize },
}

// =============================================================================
// Data Sources
// =============================================================================

/// Data source for ingestion
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum DataSource {
    /// Single file
    File {
        path: PathBuf,
    },

    /// Directory of files
    Directory {
        path: PathBuf,
        /// Optional glob pattern (e.g., "**/*.md")
        pattern: Option<String>,
        /// Recursive search
        #[serde(default = "default_true")]
        recursive: bool,
    },

    /// Raw text content
    Text {
        content: String,
        /// Source identifier for citations
        source_id: String,
        /// Optional metadata
        metadata: Option<serde_json::Value>,
    },

    /// Web URL (for future implementation)
    Url {
        url: String,
        /// Crawl depth (0 = single page)
        #[serde(default)]
        depth: usize,
    },

    /// S3-style object storage path
    ObjectStorage {
        /// Bucket/container name
        bucket: String,
        /// Object prefix/path
        prefix: String,
        /// Endpoint URL (for S3-compatible services)
        endpoint: Option<String>,
    },
}

fn default_true() -> bool {
    true
}

/// Result of data source ingestion
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IngestionResult {
    /// Number of documents processed
    pub documents_processed: usize,
    /// Number of chunks created
    pub chunks_created: usize,
    /// Failed documents (path/id -> error message)
    pub failures: HashMap<String, String>,
    /// Metadata about the ingestion
    pub metadata: IngestionMetadata,
}

/// Metadata about an ingestion job
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IngestionMetadata {
    /// Data source identifier
    pub source_id: String,
    /// Timestamp
    pub timestamp: String,
    /// Chunking strategy used
    pub chunking_strategy: String,
    /// Total characters processed
    pub total_characters: usize,
}

// =============================================================================
// Retrieval and Generation
// =============================================================================

/// Retrieved chunk with metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RetrievedChunk {
    /// Chunk content
    pub content: String,
    /// Similarity/relevance score
    pub score: f32,
    /// Source document/location
    pub source: SourceLocation,
    /// Document metadata
    pub metadata: Option<serde_json::Value>,
}

/// Source location for citations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SourceLocation {
    /// Source type (file, url, etc.)
    pub source_type: String,
    /// Source identifier (path, URL, etc.)
    pub uri: String,
    /// Optional location within source
    pub location: Option<TextLocation>,
}

/// Location within a text document
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TextLocation {
    /// Start character offset
    pub start: usize,
    /// End character offset
    pub end: usize,
}

/// Citation in a generated response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Citation {
    /// Text span in the generated output that this citation supports
    pub generated_text_span: Option<TextLocation>,
    /// Source location
    pub source: SourceLocation,
    /// Relevance score
    pub score: f32,
    /// Retrieved content that supports this citation
    pub content: String,
}

/// Retrieve-only response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RetrievalResponse {
    /// Retrieved chunks
    pub chunks: Vec<RetrievedChunk>,
    /// Query that was used
    pub query: String,
    /// Next token for pagination (if applicable)
    pub next_token: Option<String>,
}

/// Retrieve and Generate response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RetrieveAndGenerateResponse {
    /// Generated output text
    pub output: String,
    /// Citations for the generated content
    pub citations: Vec<Citation>,
    /// Retrieved chunks used for generation
    pub retrieved_chunks: Vec<RetrievedChunk>,
    /// Guardrail action taken (if any)
    pub guardrail_action: Option<String>,
}

// =============================================================================
// Reranking
// =============================================================================

/// Rerank retrieved chunks according to the given reranking configuration.
///
/// - `ScoreBased` — sort by score descending.
/// - `RRF { k }` — sort by score descending (RRF scoring already happened at store level).
/// - `CrossEncoder { model_path }` — log a warning and fall back to score-based sort.
pub fn rerank(mut chunks: Vec<RetrievedChunk>, config: &RerankingConfig) -> Vec<RetrievedChunk> {
    match &config.method {
        RerankingMethod::ScoreBased => {
            chunks.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal));
        }
        RerankingMethod::RRF { k: _ } => {
            // RRF scoring already happened at the store level; just sort by score descending.
            chunks.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal));
        }
        RerankingMethod::CrossEncoder { model_path } => {
            tracing::warn!(
                "CrossEncoder reranking with model '{}' is not yet implemented; falling back to score-based sort",
                model_path
            );
            chunks.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal));
        }
    }
    chunks
}

// =============================================================================
// Knowledge Base Implementation
// =============================================================================

/// Knowledge Base - high-level RAG interface
pub struct KnowledgeBase {
    config: KnowledgeBaseConfig,
    store: RagStore,
    embedding_gen: Option<EmbeddingGenerator>,
}

impl KnowledgeBase {
    /// Create a new knowledge base
    pub async fn create(config: KnowledgeBaseConfig) -> RagResult<Self> {
        let store = RagStore::connect(config.storage.clone()).await?;
        store.create_table().await?;

        Ok(Self {
            config,
            store,
            embedding_gen: None,
        })
    }

    /// Connect to an existing knowledge base
    pub async fn connect(config: KnowledgeBaseConfig) -> RagResult<Self> {
        let store = RagStore::connect(config.storage.clone()).await?;
        Ok(Self {
            config,
            store,
            embedding_gen: None,
        })
    }

    /// Attach an embedding generator to this knowledge base
    pub fn with_embedding_generator(mut self, emb_gen: EmbeddingGenerator) -> Self {
        self.embedding_gen = Some(emb_gen);
        self
    }

    /// Get the knowledge base name
    pub fn name(&self) -> &str {
        &self.config.name
    }

    /// Get the knowledge base configuration
    pub fn config(&self) -> &KnowledgeBaseConfig {
        &self.config
    }

    /// Ingest data from a source
    pub async fn ingest(&self, source: DataSource) -> RagResult<IngestionResult> {
        let mut result = IngestionResult {
            documents_processed: 0,
            chunks_created: 0,
            failures: HashMap::new(),
            metadata: IngestionMetadata {
                source_id: self.source_id(&source),
                timestamp: chrono_now(),
                chunking_strategy: format!("{:?}", self.config.chunking),
                total_characters: 0,
            },
        };

        match source {
            DataSource::File { path } => {
                self.ingest_file(&path, &mut result).await?;
            }
            DataSource::Directory {
                path,
                pattern,
                recursive,
            } => {
                self.ingest_directory(&path, pattern.as_deref(), recursive, &mut result)
                    .await?;
            }
            DataSource::Text {
                content,
                source_id,
                metadata,
            } => {
                self.ingest_text(&content, &source_id, metadata, &mut result)
                    .await?;
            }
            DataSource::Url { url, depth: _ } => {
                result.failures.insert(
                    url,
                    "URL ingestion not yet implemented".into(),
                );
            }
            DataSource::ObjectStorage {
                bucket,
                prefix,
                endpoint: _,
            } => {
                result.failures.insert(
                    format!("{}:{}", bucket, prefix),
                    "Object storage ingestion not yet implemented".into(),
                );
            }
        }

        Ok(result)
    }

    /// Retrieve relevant chunks for a query
    pub async fn retrieve(
        &self,
        query: &str,
        config: Option<RetrievalConfig>,
    ) -> RagResult<RetrievalResponse> {
        let config = config.unwrap_or_else(|| self.config.retrieval.clone());

        // Generate query embedding
        let query_embedding = self.embed_query(query)?;

        // Dispatch to hybrid or semantic search based on configuration
        let docs = if self.config.storage.search_type() == SearchType::Hybrid {
            self.store
                .search_hybrid(
                    &query_embedding,
                    query,
                    Some(config.max_results),
                    config.filter,
                )
                .await?
        } else {
            self.store
                .search_with_filter(&query_embedding, Some(config.max_results), config.filter)
                .await?
        };

        // Convert to retrieved chunks
        let mut chunks: Vec<RetrievedChunk> = docs
            .into_iter()
            .filter(|d| d.score.unwrap_or(0.0) >= config.min_score)
            .map(|d| self.doc_to_chunk(d))
            .collect();

        // Apply reranking if configured
        if let Some(reranking_config) = &self.config.reranking {
            chunks = rerank(chunks, reranking_config);
        }

        Ok(RetrievalResponse {
            chunks,
            query: query.to_string(),
            next_token: None,
        })
    }

    /// Retrieve and generate a response
    ///
    /// This combines retrieval with LLM generation. In practice, you would
    /// pass the retrieved context to your LLM for generation.
    pub async fn retrieve_and_generate(
        &self,
        query: &str,
        config: Option<RetrievalConfig>,
    ) -> RagResult<RetrieveAndGenerateResponse> {
        let config = config.unwrap_or_else(|| self.config.retrieval.clone());

        // Retrieve relevant chunks
        let retrieval = self.retrieve(query, Some(config.clone())).await?;

        // Build context from retrieved chunks
        let context = self.build_context(&retrieval.chunks);

        // Build prompt
        let prompt = if let Some(template) = &config.prompt_template {
            template
                .replace("{context}", &context)
                .replace("{query}", query)
                .replace("{question}", query)
        } else {
            self.default_prompt(&context, query)
        };

        // Create citations from retrieved chunks
        let citations: Vec<Citation> = retrieval
            .chunks
            .iter()
            .map(|chunk| Citation {
                generated_text_span: None, // Would be filled by actual generation
                source: chunk.source.clone(),
                score: chunk.score,
                content: chunk.content.clone(),
            })
            .collect();

        // Note: Actual LLM generation would happen here
        // For now, return the prompt as output (user should pass to LLM)
        Ok(RetrieveAndGenerateResponse {
            output: prompt,
            citations,
            retrieved_chunks: retrieval.chunks,
            guardrail_action: None,
        })
    }

    /// Sync the knowledge base (re-process all data sources)
    pub async fn sync(&self) -> RagResult<()> {
        // In a full implementation, this would track data sources
        // and re-ingest changed/new documents
        Ok(())
    }

    /// Delete the knowledge base
    pub async fn delete(&self) -> RagResult<()> {
        self.store.clear().await?;
        Ok(())
    }

    /// Get statistics about the knowledge base
    pub async fn stats(&self) -> RagResult<KnowledgeBaseStats> {
        let document_count = self.store.count().await? as usize;
        
        Ok(KnowledgeBaseStats {
            name: self.config.name.clone(),
            document_count,
            embedding_dimension: self.config.storage.embedding_dim(),
            chunking_strategy: format!("{:?}", self.config.chunking),
            hybrid_search_enabled: self.config.hybrid_search,
        })
    }

    // =========================================================================
    // Private helpers
    // =========================================================================

    fn source_id(&self, source: &DataSource) -> String {
        match source {
            DataSource::File { path } => path.to_string_lossy().to_string(),
            DataSource::Directory { path, .. } => path.to_string_lossy().to_string(),
            DataSource::Text { source_id, .. } => source_id.clone(),
            DataSource::Url { url, .. } => url.clone(),
            DataSource::ObjectStorage { bucket, prefix, .. } => {
                format!("s3://{}/{}", bucket, prefix)
            }
        }
    }

    async fn ingest_file(
        &self,
        path: &std::path::Path,
        result: &mut IngestionResult,
    ) -> RagResult<()> {
        match std::fs::read_to_string(path) {
            Ok(content) => {
                let source_id = path.to_string_lossy().to_string();
                let metadata = serde_json::json!({
                    "source": source_id,
                    "source_type": "file",
                    "filename": path.file_name().map(|n| n.to_string_lossy().to_string()),
                });

                self.ingest_text(&content, &source_id, Some(metadata), result)
                    .await?;
                result.documents_processed += 1;
            }
            Err(e) => {
                result
                    .failures
                    .insert(path.to_string_lossy().to_string(), e.to_string());
            }
        }
        Ok(())
    }

    async fn ingest_directory(
        &self,
        path: &std::path::Path,
        pattern: Option<&str>,
        recursive: bool,
        result: &mut IngestionResult,
    ) -> RagResult<()> {
        let entries = if recursive {
            self.walk_directory_recursive(path, pattern)?
        } else {
            self.walk_directory_flat(path, pattern)?
        };

        for entry in entries {
            self.ingest_file(&entry, result).await?;
        }

        Ok(())
    }

    fn walk_directory_recursive(
        &self,
        path: &std::path::Path,
        pattern: Option<&str>,
    ) -> RagResult<Vec<PathBuf>> {
        let mut files = Vec::new();

        fn visit_dir(dir: &std::path::Path, files: &mut Vec<PathBuf>) -> std::io::Result<()> {
            for entry in std::fs::read_dir(dir)? {
                let entry = entry?;
                let path = entry.path();
                if path.is_dir() {
                    visit_dir(&path, files)?;
                } else if path.is_file() {
                    files.push(path);
                }
            }
            Ok(())
        }

        visit_dir(path, &mut files)
            .map_err(|e| RagError::ConfigError(format!("Failed to read directory: {}", e)))?;

        if let Some(pattern) = pattern {
            files.retain(|f| {
                let path_str = f.to_string_lossy();
                matches_glob_pattern(&path_str, pattern)
            });
        }

        Ok(files)
    }

    fn walk_directory_flat(
        &self,
        path: &std::path::Path,
        pattern: Option<&str>,
    ) -> RagResult<Vec<PathBuf>> {
        let mut files = Vec::new();

        let entries = std::fs::read_dir(path)
            .map_err(|e| RagError::ConfigError(format!("Failed to read directory: {}", e)))?;

        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_file() {
                files.push(path);
            }
        }

        if let Some(pattern) = pattern {
            files.retain(|f| {
                let path_str = f.to_string_lossy();
                matches_glob_pattern(&path_str, pattern)
            });
        }

        Ok(files)
    }

    async fn ingest_text(
        &self,
        content: &str,
        source_id: &str,
        metadata: Option<serde_json::Value>,
        result: &mut IngestionResult,
    ) -> RagResult<()> {
        result.metadata.total_characters += content.len();

        // Chunk the content
        let chunks = self.chunk_text(content);

        // Create documents for each chunk
        for (i, chunk_text) in chunks.iter().enumerate() {
            let chunk_metadata = serde_json::json!({
                "source": source_id,
                "chunk_index": i,
                "total_chunks": chunks.len(),
                "parent": metadata.clone(),
            });

            // Generate embedding (placeholder)
            let embedding = self.embed_text(chunk_text)?;

            let doc = NewDocument {
                content: chunk_text.clone(),
                embedding,
                metadata: Some(chunk_metadata),
            };

            self.store.insert(doc).await?;
            result.chunks_created += 1;
        }

        Ok(())
    }

    fn chunk_text(&self, text: &str) -> Vec<String> {
        match &self.config.chunking {
            ChunkingStrategy::None => vec![text.to_string()],

            ChunkingStrategy::FixedSize {
                max_tokens,
                overlap_percentage,
            } => {
                let char_size = max_tokens * 4; // Approximate chars per token
                let overlap = (char_size * *overlap_percentage as usize) / 100;

                let chunker = TextChunker::new(char_size).with_overlap(overlap);
                chunker.chunk(text)
            }

            ChunkingStrategy::Semantic {
                max_tokens,
                buffer_size: _,
            } => {
                // Semantic chunking: split on sentence boundaries
                let char_size = max_tokens * 4;
                let sentences: Vec<&str> = text
                    .split(['.', '!', '?'])
                    .filter(|s| !s.trim().is_empty())
                    .collect();

                let mut chunks = Vec::new();
                let mut current_chunk = String::new();

                for sentence in sentences {
                    let sentence = sentence.trim().to_string() + ".";

                    if current_chunk.len() + sentence.len() > char_size {
                        if !current_chunk.is_empty() {
                            chunks.push(current_chunk.trim().to_string());
                        }
                        current_chunk = sentence;
                    } else {
                        if !current_chunk.is_empty() {
                            current_chunk.push(' ');
                        }
                        current_chunk.push_str(&sentence);
                    }
                }

                if !current_chunk.is_empty() {
                    chunks.push(current_chunk.trim().to_string());
                }

                chunks
            }

            ChunkingStrategy::Hierarchical {
                parent_max_tokens,
                child_max_tokens,
                child_overlap_percentage,
            } => {
                // First create parent chunks
                let parent_char_size = parent_max_tokens * 4;
                let child_char_size = child_max_tokens * 4;
                let child_overlap = (child_char_size * *child_overlap_percentage as usize) / 100;

                let parent_chunker = TextChunker::new(parent_char_size);
                let child_chunker = TextChunker::new(child_char_size).with_overlap(child_overlap);

                let parents = parent_chunker.chunk(text);
                let mut all_chunks = Vec::new();

                for parent in parents {
                    let children = child_chunker.chunk(&parent);
                    all_chunks.extend(children);
                }

                all_chunks
            }
        }
    }

    fn embed_text(&self, text: &str) -> RagResult<Vec<f32>> {
        if let Some(emb) = &self.embedding_gen {
            emb.embed(text)
        } else {
            // Fallback: zero vector (for testing without a model)
            Ok(vec![0.0f32; self.config.storage.embedding_dim()])
        }
    }

    fn embed_query(&self, query: &str) -> RagResult<Vec<f32>> {
        if let Some(emb) = &self.embedding_gen {
            emb.embed(query)
        } else {
            // Fallback: zero vector (for testing without a model)
            Ok(vec![0.0f32; self.config.storage.embedding_dim()])
        }
    }

    fn doc_to_chunk(&self, doc: Document) -> RetrievedChunk {
        let source_uri = doc
            .metadata
            .as_ref()
            .and_then(|m| m.get("source"))
            .and_then(|v| v.as_str())
            .unwrap_or("unknown")
            .to_string();

        RetrievedChunk {
            content: doc.content,
            score: doc.score.unwrap_or(0.0),
            source: SourceLocation {
                source_type: "document".into(),
                uri: source_uri,
                location: None,
            },
            metadata: doc.metadata,
        }
    }

    fn build_context(&self, chunks: &[RetrievedChunk]) -> String {
        chunks
            .iter()
            .enumerate()
            .map(|(i, c)| format!("[{}] {}", i + 1, c.content))
            .collect::<Vec<_>>()
            .join("\n\n")
    }

    fn default_prompt(&self, context: &str, query: &str) -> String {
        format!(
            r#"Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.

Context:
{context}

Question: {query}

Helpful Answer:"#
        )
    }
}

/// Knowledge base statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KnowledgeBaseStats {
    pub name: String,
    pub document_count: usize,
    pub embedding_dimension: usize,
    pub chunking_strategy: String,
    pub hybrid_search_enabled: bool,
}

/// Get current timestamp as string
fn chrono_now() -> String {
    // Simple timestamp without chrono dependency
    use std::time::{SystemTime, UNIX_EPOCH};
    let duration = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default();
    format!("{}s", duration.as_secs())
}

/// Check whether a path string matches a glob pattern.
///
/// Uses the `glob` crate's `Pattern` for matching. Returns `false` if the
/// pattern is invalid.
fn matches_glob_pattern(path: &str, pattern: &str) -> bool {
    glob::Pattern::new(pattern)
        .map(|p| p.matches(path))
        .unwrap_or(false)
}

// =============================================================================
// Builder Pattern
// =============================================================================

/// Builder for KnowledgeBaseConfig
pub struct KnowledgeBaseBuilder {
    config: KnowledgeBaseConfig,
    model: Option<Arc<LlamaModel>>,
    tokenizer: Option<Arc<Tokenizer>>,
    backend: Option<Arc<dyn Backend>>,
}

impl KnowledgeBaseBuilder {
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            config: KnowledgeBaseConfig {
                name: name.into(),
                ..Default::default()
            },
            model: None,
            tokenizer: None,
            backend: None,
        }
    }

    /// Set the model, tokenizer, and backend for real embedding generation
    pub fn with_model(
        mut self,
        model: Arc<LlamaModel>,
        tokenizer: Arc<Tokenizer>,
        backend: Arc<dyn Backend>,
    ) -> Self {
        self.model = Some(model);
        self.tokenizer = Some(tokenizer);
        self.backend = Some(backend);
        self
    }

    pub fn description(mut self, desc: impl Into<String>) -> Self {
        self.config.description = Some(desc.into());
        self
    }

    pub fn storage(mut self, storage: RagConfig) -> Self {
        self.config.storage = storage;
        self
    }

    pub fn chunking(mut self, strategy: ChunkingStrategy) -> Self {
        self.config.chunking = strategy;
        self
    }

    pub fn fixed_size_chunking(mut self, max_tokens: usize, overlap_pct: u8) -> Self {
        self.config.chunking = ChunkingStrategy::FixedSize {
            max_tokens,
            overlap_percentage: overlap_pct.min(50),
        };
        self
    }

    pub fn semantic_chunking(mut self, max_tokens: usize) -> Self {
        self.config.chunking = ChunkingStrategy::Semantic {
            max_tokens,
            buffer_size: 100,
        };
        self
    }

    pub fn hierarchical_chunking(
        mut self,
        parent_tokens: usize,
        child_tokens: usize,
        overlap_pct: u8,
    ) -> Self {
        self.config.chunking = ChunkingStrategy::Hierarchical {
            parent_max_tokens: parent_tokens,
            child_max_tokens: child_tokens,
            child_overlap_percentage: overlap_pct.min(50),
        };
        self
    }

    pub fn retrieval(mut self, retrieval: RetrievalConfig) -> Self {
        self.config.retrieval = retrieval;
        self
    }

    pub fn max_results(mut self, max: usize) -> Self {
        self.config.retrieval.max_results = max;
        self
    }

    pub fn min_score(mut self, min: f32) -> Self {
        self.config.retrieval.min_score = min.clamp(0.0, 1.0);
        self
    }

    pub fn hybrid_search(mut self, enabled: bool) -> Self {
        self.config.hybrid_search = enabled;
        self
    }

    pub fn reranking(mut self, config: RerankingConfig) -> Self {
        self.config.reranking = Some(config);
        self
    }

    pub fn build(self) -> KnowledgeBaseConfig {
        self.config
    }

    pub async fn create(self) -> RagResult<KnowledgeBase> {
        let mut kb = KnowledgeBase::create(self.config).await?;

        // Construct EmbeddingGenerator when model, tokenizer, and backend are all provided
        if let (Some(model), Some(tokenizer), Some(backend)) =
            (self.model, self.tokenizer, self.backend)
        {
            kb.embedding_gen = Some(EmbeddingGenerator::new(model, tokenizer, backend));
        }

        Ok(kb)
    }
}

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

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

    #[test]
    fn test_rerank_score_based() {
        let low = RetrievedChunk {
            content: "low score chunk".into(),
            score: 0.3,
            source: SourceLocation {
                source_type: "document".into(),
                uri: "low.txt".into(),
                location: None,
            },
            metadata: None,
        };
        let high = RetrievedChunk {
            content: "high score chunk".into(),
            score: 0.9,
            source: SourceLocation {
                source_type: "document".into(),
                uri: "high.txt".into(),
                location: None,
            },
            metadata: None,
        };

        // Feed them in low-first order
        let chunks = vec![low, high];
        let config = RerankingConfig {
            num_candidates: 10,
            method: RerankingMethod::ScoreBased,
        };

        let result = rerank(chunks, &config);

        assert_eq!(result.len(), 2);
        assert_eq!(result[0].content, "high score chunk");
        assert_eq!(result[1].content, "low score chunk");
        assert!(result[0].score > result[1].score);
    }

    #[test]
    fn test_glob_pattern_matching() {
        // Markdown files match **/*.md
        assert!(matches_glob_pattern("docs/readme.md", "**/*.md"));

        // Rust source files match **/*.rs
        assert!(matches_glob_pattern("src/lib.rs", "**/*.rs"));

        // PNG file does NOT match **/*.md
        assert!(!matches_glob_pattern("image.png", "**/*.md"));

        // Edge cases
        assert!(matches_glob_pattern("a.md", "**/*.md"));
        assert!(!matches_glob_pattern("docs/readme.txt", "**/*.md"));
    }
}