Skip to main content

troupekit_kit/
knowledge.rs

1//! Ingest a folder into a named vector index in the store file. Unchanged
2//! files are skipped by content hash, changed files are replaced whole, a
3//! file that fails is recorded and the walk goes on, and the sources of
4//! files gone from the folder are removed.
5
6use std::collections::HashSet;
7use std::fmt;
8use std::path::{Path, PathBuf};
9use std::sync::Arc;
10pub use troupekit_context::chunk::ChunkConfig;
11pub use troupekit_context::embed::Embedder;
12use troupekit_context::ingest::{document_records, Document, Origin};
13use troupekit_context::load::walk;
14pub use troupekit_context::load::LoadSettings;
15use troupekit_context::text::stable_hash;
16use troupekit_context::ContextError;
17use troupekit_core::clock::{Clock, SystemClock};
18use troupekit_store_sqlite::SqliteVectors;
19
20const SCOPE_DEFAULT: &str = "docs";
21const CHUNK_MAX_TOKENS_DEFAULT: usize = 200;
22const CHUNK_OVERLAP_TOKENS_DEFAULT: usize = 20;
23const MAX_REMOVE_SHARE_DEFAULT: u8 = 50;
24
25/// Settings for `ingest_dir`. Defaults: scope `docs`, chunks of 200
26/// tokens with 20 of overlap, the safe folder walk of `LoadSettings` and
27/// `Origin::External`, so folder text is fenced as untrusted in prompts.
28/// A run never removes more than half the scope, or all of it from an
29/// empty folder, unless allowed. Changed origin or chunk config re-ingests.
30#[non_exhaustive]
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct IngestSettings {
33    scope: String,
34    chunk: ChunkConfig,
35    load: LoadSettings,
36    origin: Origin,
37    allow_remove_all: bool,
38    max_remove_share: u8,
39}
40
41impl Default for IngestSettings {
42    fn default() -> Self {
43        Self {
44            scope: SCOPE_DEFAULT.to_string(),
45            chunk: ChunkConfig {
46                max_tokens: CHUNK_MAX_TOKENS_DEFAULT,
47                overlap_tokens: CHUNK_OVERLAP_TOKENS_DEFAULT,
48            },
49            load: LoadSettings::default(),
50            origin: Origin::External,
51            allow_remove_all: false,
52            max_remove_share: MAX_REMOVE_SHARE_DEFAULT,
53        }
54    }
55}
56
57impl IngestSettings {
58    /// Sets the scope every chunk is stored under.
59    /// Must not be blank; `ingest_dir` refuses a blank scope.
60    /// Default `docs`.
61    pub fn with_scope(mut self, scope: impl Into<String>) -> Self {
62        self.scope = scope.into();
63        self
64    }
65
66    /// Sets the chunk size and overlap, in estimated tokens.
67    /// Checked by the chunker on the first file.
68    /// Default 200 tokens with 20 of overlap.
69    pub fn with_chunk(mut self, chunk: ChunkConfig) -> Self {
70        self.chunk = chunk;
71        self
72    }
73
74    /// Sets the folder walk bounds and filters.
75    /// A walk cap error stops the ingest before any write.
76    /// Default `LoadSettings::default()`.
77    pub fn with_load(mut self, load: LoadSettings) -> Self {
78        self.load = load;
79        self
80    }
81
82    /// Sets the origin stored on every chunk.
83    /// `Internal` text is put in prompts unfenced; use it only for text
84    /// the app wrote itself. Default `Origin::External`.
85    pub fn with_origin(mut self, origin: Origin) -> Self {
86        self.origin = origin;
87        self
88    }
89
90    /// Allows a run to remove any number of sources, all of them included,
91    /// for a folder that was emptied on purpose. Off, a walk that finds no
92    /// supported file while the scope has sources is refused. Default off.
93    pub fn with_allow_remove_all(mut self, allow: bool) -> Self {
94        self.allow_remove_all = allow;
95        self
96    }
97
98    /// Sets the largest share of the scope's sources, in percent 0 to 100,
99    /// one run may remove; a run above it is refused with the planned
100    /// count before any write. Ignored with `allow_remove_all`. Default 50.
101    pub fn with_max_remove_share(mut self, percent: u8) -> Self {
102        self.max_remove_share = percent;
103        self
104    }
105
106    /// Returns whether a run may remove every source of the scope.
107    /// Guards against an unmounted or mistyped folder.
108    /// Default false.
109    pub fn allow_remove_all(&self) -> bool {
110        self.allow_remove_all
111    }
112
113    /// Returns the largest share of sources, in percent, one run removes.
114    /// Above it the run is refused before any write.
115    /// Default 50.
116    pub fn max_remove_share(&self) -> u8 {
117        self.max_remove_share
118    }
119
120    /// Returns the scope every chunk is stored under.
121    /// It is the `scope` meta value of each chunk.
122    /// Default `docs`.
123    pub fn scope(&self) -> &str {
124        &self.scope
125    }
126
127    /// Returns the chunk size and overlap.
128    /// In estimated tokens of four chars.
129    /// Default 200 and 20.
130    pub fn chunk(&self) -> ChunkConfig {
131        self.chunk
132    }
133
134    /// Returns the folder walk settings.
135    /// Their caps bound one ingest.
136    /// Default `LoadSettings::default()`.
137    pub fn load(&self) -> &LoadSettings {
138        &self.load
139    }
140
141    /// Returns the origin stored on every chunk.
142    /// External text is fenced as untrusted.
143    /// Default `Origin::External`.
144    pub fn origin(&self) -> Origin {
145        self.origin
146    }
147}
148
149/// What one `ingest_dir` call did: files added, replaced and skipped as
150/// unchanged, sources removed because their file is gone, files the walk
151/// passed over (`unsupported`, `symlinks`), failed files with their error,
152/// and the chunks written.
153#[non_exhaustive]
154#[derive(Debug, Clone, PartialEq, Eq)]
155pub struct IngestReport {
156    pub added: usize,
157    pub replaced: usize,
158    pub skipped: usize,
159    pub removed: usize,
160    pub unsupported: usize,
161    pub symlinks: usize,
162    pub failed: Vec<(String, String)>,
163    pub chunks: usize,
164}
165
166/// Ingests every loadable file under `dir` into `vectors`: unchanged
167/// files are skipped, others swapped in with `replace_source`, and after
168/// a complete walk a source is removed only when its file is gone from
169/// disk, checked again just before removal; filtered-out files stay.
170/// Output: the report, or an error for a walk cap, a blank scope or a
171/// store write that fails.
172pub async fn ingest_dir(
173    vectors: &SqliteVectors,
174    embedder: &dyn Embedder,
175    dir: &Path,
176    settings: &IngestSettings,
177) -> Result<IngestReport, ContextError> {
178    if settings.scope.trim().is_empty() {
179        return Err(ContextError::Invalid("scope must not be empty".into()));
180    }
181    if settings.max_remove_share > 100 {
182        return Err(ContextError::Invalid(format!(
183            "max_remove_share is {}%, above 100%",
184            settings.max_remove_share
185        )));
186    }
187    let walked = walk(dir, &settings.load)?;
188    let present: HashSet<String> = walked.files.iter().map(|f| f.source.clone()).collect();
189    let stored = vectors.sources(&settings.scope).await?;
190    let gone: Vec<String> = stored
191        .iter()
192        .filter(|s| !present.contains(*s) && !on_disk(dir, s))
193        .cloned()
194        .collect();
195    check_removals(gone.len(), stored.len(), present.is_empty(), settings)?;
196    let mut report = IngestReport {
197        added: 0,
198        replaced: 0,
199        skipped: 0,
200        removed: 0,
201        unsupported: walked.unsupported,
202        symlinks: walked.symlinks,
203        failed: Vec::new(),
204        chunks: 0,
205    };
206    let at_ms = SystemClock.now_ms();
207    for file in walked.files {
208        let ingest_hash = ingest_hash(&file.content_hash, settings);
209        let previous = vectors.source_hash(&settings.scope, &file.source).await?;
210        if previous.as_deref() == Some(ingest_hash.as_str()) {
211            report.skipped += 1;
212            continue;
213        }
214        let doc = Document {
215            scope: settings.scope.clone(),
216            source: file.source.clone(),
217            text: file.text,
218            at_ms,
219            origin: settings.origin,
220            meta: Default::default(),
221        };
222        let outcome = match document_records(embedder, &doc, &settings.chunk).await {
223            Ok(records) => vectors
224                .replace_source(&settings.scope, &file.source, records, &ingest_hash)
225                .await
226                .map_err(ContextError::from),
227            Err(e) => Err(e),
228        };
229        match outcome {
230            Ok(written) => {
231                report.chunks += written;
232                if previous.is_some() {
233                    report.replaced += 1;
234                } else {
235                    report.added += 1;
236                }
237            }
238            Err(e) => {
239                let error = e.to_string();
240                vectors
241                    .record_failed_source(&settings.scope, &file.source, &error)
242                    .await?;
243                report.failed.push((file.source, error));
244            }
245        }
246    }
247    for source in &gone {
248        if on_disk(dir, source) {
249            continue;
250        }
251        vectors.remove_source(&settings.scope, source).await?;
252        report.removed += 1;
253    }
254    let handled = report.added + report.replaced + report.skipped + report.failed.len();
255    assert!(
256        handled <= settings.load.max_files(),
257        "more files handled than the walk allows"
258    );
259    Ok(report)
260}
261
262/// Hash stored per source: the file's content hash together with the
263/// origin and chunk config its chunks were made with, so a settings
264/// change no longer matches and the file is ingested again.
265/// Input: the content hash and the settings. Output: 16 hex chars.
266fn ingest_hash(content_hash: &str, settings: &IngestSettings) -> String {
267    let max = settings.chunk.max_tokens.to_string();
268    let overlap = settings.chunk.overlap_tokens.to_string();
269    let hash = format!(
270        "{:016x}",
271        stable_hash(&[content_hash, settings.origin.as_str(), &max, &overlap])
272    );
273    assert_eq!(hash.len(), 16, "ingest hash is 16 hex chars");
274    hash
275}
276
277/// Refuses a run that would wipe the scope from an empty folder, or
278/// remove more than `max_remove_share` percent of its sources, unless
279/// `allow_remove_all`. Input: planned and stored counts, whether the walk
280/// found no file, and settings. Output: `Ok`, or `Invalid` with the count.
281fn check_removals(
282    planned: usize,
283    stored: usize,
284    no_files: bool,
285    settings: &IngestSettings,
286) -> Result<(), ContextError> {
287    assert!(
288        planned <= stored,
289        "more removals planned than sources stored"
290    );
291    if settings.allow_remove_all || planned == 0 {
292        return Ok(());
293    }
294    let scope = &settings.scope;
295    if no_files {
296        return Err(ContextError::Invalid(format!(
297            "walk found no supported files but scope {scope} has {stored} sources; refusing to remove them all \
298             (check the folder, or set with_allow_remove_all(true))"
299        )));
300    }
301    let share = usize::from(settings.max_remove_share);
302    if planned * 100 > stored * share {
303        return Err(ContextError::Invalid(format!(
304            "refusing to remove {planned} of {stored} sources of scope {scope}, above max_remove_share {share}% \
305             (check the folder, or raise with_max_remove_share or set with_allow_remove_all(true))"
306        )));
307    }
308    Ok(())
309}
310
311fn on_disk(dir: &Path, source: &str) -> bool {
312    let relative = Path::new(source);
313    let plain = relative
314        .components()
315        .all(|c| matches!(c, std::path::Component::Normal(_)));
316    if !plain {
317        return false;
318    }
319    match std::fs::symlink_metadata(dir.join(relative)) {
320        Ok(_) => true,
321        Err(e) => e.kind() != std::io::ErrorKind::NotFound,
322    }
323}
324
325/// A folder an agent can search: `Knowledge::dir("docs")` plus settings.
326/// At `build` the folder is ingested into index `index` of the store file
327/// (unchanged files skipped) and the agent gets the `search_knowledge`
328/// tool. The embedder defaults to the catalog's for the agent's vendor.
329#[derive(Clone)]
330pub struct Knowledge {
331    pub(crate) dir: PathBuf,
332    pub(crate) index: String,
333    pub(crate) store: Option<PathBuf>,
334    pub(crate) embedder: Option<Arc<dyn Embedder>>,
335    pub(crate) on_device: bool,
336    #[cfg(feature = "local")]
337    pub(crate) local: Option<crate::local::LocalChoice>,
338    pub(crate) load: LoadSettings,
339    pub(crate) chunk: ChunkConfig,
340    pub(crate) allow_failed: bool,
341}
342
343impl Knowledge {
344    /// Starts settings for folder `dir`, read at `build`.
345    /// Index `docs`, the agent's SQLite checkpoint file or
346    /// `./troupekit.db`, and the `ingest_dir` walk and chunk defaults.
347    pub fn dir(dir: impl AsRef<Path>) -> Self {
348        let defaults = IngestSettings::default();
349        Knowledge {
350            dir: dir.as_ref().to_path_buf(),
351            index: defaults.scope().to_string(),
352            store: None,
353            embedder: None,
354            on_device: false,
355            #[cfg(feature = "local")]
356            local: None,
357            load: defaults.load().clone(),
358            chunk: defaults.chunk(),
359            allow_failed: false,
360        }
361    }
362
363    /// Sets the vector index and scope the folder is stored under.
364    /// 1 to 64 of `[a-z0-9_]`, checked at `build`.
365    /// Default `docs`.
366    pub fn index(mut self, index: impl Into<String>) -> Self {
367        self.index = index.into();
368        self
369    }
370
371    /// Sets the SQLite file the index lives in.
372    /// Default: the agent's `Storage::sqlite` file, else `./troupekit.db`.
373    /// Returns the settings.
374    pub fn store(mut self, path: impl AsRef<Path>) -> Self {
375        self.store = Some(path.as_ref().to_path_buf());
376        self
377    }
378
379    /// Sets the embedder for the folder and for searches, overriding the
380    /// catalog embedder of the agent's vendor; dimensions must match an
381    /// existing index of the same name.
382    /// Returns the settings.
383    pub fn embedder(mut self, embedder: Arc<dyn Embedder>) -> Self {
384        self.embedder = Some(embedder);
385        self.on_device = false;
386        self.clear_local();
387        self
388    }
389
390    /// Sets an embedder that runs on the device, with no network, and
391    /// marks it so: a private agent accepts only such an embedder.
392    /// Otherwise the same as `embedder`.
393    pub fn on_device_embedder(mut self, embedder: Arc<dyn Embedder>) -> Self {
394        self.embedder = Some(embedder);
395        self.on_device = true;
396        self.clear_local();
397        self
398    }
399
400    /// Embeds on the device with a local model: a catalog id, a GGUF
401    /// file or a loaded `Arc<dyn LocalModel>`, loaded at `build` like
402    /// `Agent::local`. Marks the embedder on-device for private agents.
403    #[cfg(feature = "local")]
404    pub fn local_embedder(mut self, choice: impl Into<crate::local::LocalChoice>) -> Self {
405        self.embedder = None;
406        self.local = Some(choice.into());
407        self.on_device = true;
408        self
409    }
410
411    #[cfg(feature = "local")]
412    fn clear_local(&mut self) {
413        self.local = None;
414    }
415
416    #[cfg(not(feature = "local"))]
417    fn clear_local(&mut self) {}
418
419    /// Sets the folder walk bounds and filters.
420    /// Default `LoadSettings::default()`.
421    /// Returns the settings.
422    pub fn load(mut self, load: LoadSettings) -> Self {
423        self.load = load;
424        self
425    }
426
427    /// Sets the chunk size and overlap, in estimated tokens.
428    /// Default 200 tokens with 20 of overlap.
429    /// Returns the settings.
430    pub fn chunk(mut self, chunk: ChunkConfig) -> Self {
431        self.chunk = chunk;
432        self
433    }
434}
435
436impl Knowledge {
437    /// Lets `build` succeed when some files fail to ingest; the rest is
438    /// searchable and failed files are retried on the next build. Default
439    /// `false`: `build` fails and lists the failed files.
440    pub fn allow_failed(mut self, allow: bool) -> Self {
441        self.allow_failed = allow;
442        self
443    }
444}
445
446impl From<&str> for Knowledge {
447    fn from(dir: &str) -> Self {
448        Knowledge::dir(dir)
449    }
450}
451
452impl From<&Path> for Knowledge {
453    fn from(dir: &Path) -> Self {
454        Knowledge::dir(dir)
455    }
456}
457
458impl From<PathBuf> for Knowledge {
459    fn from(dir: PathBuf) -> Self {
460        Knowledge::dir(dir)
461    }
462}
463
464impl fmt::Debug for Knowledge {
465    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
466        f.debug_struct("Knowledge")
467            .field("dir", &self.dir)
468            .field("index", &self.index)
469            .field("store", &self.store)
470            .field("embedder", &self.embedder.is_some())
471            .field("on_device", &self.on_device)
472            .field("allow_failed", &self.allow_failed)
473            .finish_non_exhaustive()
474    }
475}