troupekit-kit 0.4.0

Ergonomic API for the Troupekit LLM agent framework: one builder or one macro per agent, tool and graph.
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
//! Ingest a folder into a named vector index in the store file. Unchanged
//! files are skipped by content hash, changed files are replaced whole, a
//! file that fails is recorded and the walk goes on, and the sources of
//! files gone from the folder are removed.

use std::collections::HashSet;
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::Arc;
pub use troupekit_context::chunk::ChunkConfig;
pub use troupekit_context::embed::Embedder;
use troupekit_context::ingest::{document_records, Document, Origin};
use troupekit_context::load::walk;
pub use troupekit_context::load::LoadSettings;
use troupekit_context::text::stable_hash;
use troupekit_context::ContextError;
use troupekit_core::clock::{Clock, SystemClock};
use troupekit_store_sqlite::SqliteVectors;

const SCOPE_DEFAULT: &str = "docs";
const CHUNK_MAX_TOKENS_DEFAULT: usize = 200;
const CHUNK_OVERLAP_TOKENS_DEFAULT: usize = 20;
const MAX_REMOVE_SHARE_DEFAULT: u8 = 50;

/// Settings for `ingest_dir`. Defaults: scope `docs`, chunks of 200
/// tokens with 20 of overlap, the safe folder walk of `LoadSettings` and
/// `Origin::External`, so folder text is fenced as untrusted in prompts.
/// A run never removes more than half the scope, or all of it from an
/// empty folder, unless allowed. Changed origin or chunk config re-ingests.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IngestSettings {
    scope: String,
    chunk: ChunkConfig,
    load: LoadSettings,
    origin: Origin,
    allow_remove_all: bool,
    max_remove_share: u8,
}

impl Default for IngestSettings {
    fn default() -> Self {
        Self {
            scope: SCOPE_DEFAULT.to_string(),
            chunk: ChunkConfig {
                max_tokens: CHUNK_MAX_TOKENS_DEFAULT,
                overlap_tokens: CHUNK_OVERLAP_TOKENS_DEFAULT,
            },
            load: LoadSettings::default(),
            origin: Origin::External,
            allow_remove_all: false,
            max_remove_share: MAX_REMOVE_SHARE_DEFAULT,
        }
    }
}

impl IngestSettings {
    /// Sets the scope every chunk is stored under.
    /// Must not be blank; `ingest_dir` refuses a blank scope.
    /// Default `docs`.
    pub fn with_scope(mut self, scope: impl Into<String>) -> Self {
        self.scope = scope.into();
        self
    }

    /// Sets the chunk size and overlap, in estimated tokens.
    /// Checked by the chunker on the first file.
    /// Default 200 tokens with 20 of overlap.
    pub fn with_chunk(mut self, chunk: ChunkConfig) -> Self {
        self.chunk = chunk;
        self
    }

    /// Sets the folder walk bounds and filters.
    /// A walk cap error stops the ingest before any write.
    /// Default `LoadSettings::default()`.
    pub fn with_load(mut self, load: LoadSettings) -> Self {
        self.load = load;
        self
    }

    /// Sets the origin stored on every chunk.
    /// `Internal` text is put in prompts unfenced; use it only for text
    /// the app wrote itself. Default `Origin::External`.
    pub fn with_origin(mut self, origin: Origin) -> Self {
        self.origin = origin;
        self
    }

    /// Allows a run to remove any number of sources, all of them included,
    /// for a folder that was emptied on purpose. Off, a walk that finds no
    /// supported file while the scope has sources is refused. Default off.
    pub fn with_allow_remove_all(mut self, allow: bool) -> Self {
        self.allow_remove_all = allow;
        self
    }

    /// Sets the largest share of the scope's sources, in percent 0 to 100,
    /// one run may remove; a run above it is refused with the planned
    /// count before any write. Ignored with `allow_remove_all`. Default 50.
    pub fn with_max_remove_share(mut self, percent: u8) -> Self {
        self.max_remove_share = percent;
        self
    }

    /// Returns whether a run may remove every source of the scope.
    /// Guards against an unmounted or mistyped folder.
    /// Default false.
    pub fn allow_remove_all(&self) -> bool {
        self.allow_remove_all
    }

    /// Returns the largest share of sources, in percent, one run removes.
    /// Above it the run is refused before any write.
    /// Default 50.
    pub fn max_remove_share(&self) -> u8 {
        self.max_remove_share
    }

    /// Returns the scope every chunk is stored under.
    /// It is the `scope` meta value of each chunk.
    /// Default `docs`.
    pub fn scope(&self) -> &str {
        &self.scope
    }

    /// Returns the chunk size and overlap.
    /// In estimated tokens of four chars.
    /// Default 200 and 20.
    pub fn chunk(&self) -> ChunkConfig {
        self.chunk
    }

    /// Returns the folder walk settings.
    /// Their caps bound one ingest.
    /// Default `LoadSettings::default()`.
    pub fn load(&self) -> &LoadSettings {
        &self.load
    }

    /// Returns the origin stored on every chunk.
    /// External text is fenced as untrusted.
    /// Default `Origin::External`.
    pub fn origin(&self) -> Origin {
        self.origin
    }
}

/// What one `ingest_dir` call did: files added, replaced and skipped as
/// unchanged, sources removed because their file is gone, files the walk
/// passed over (`unsupported`, `symlinks`), failed files with their error,
/// and the chunks written.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IngestReport {
    pub added: usize,
    pub replaced: usize,
    pub skipped: usize,
    pub removed: usize,
    pub unsupported: usize,
    pub symlinks: usize,
    pub failed: Vec<(String, String)>,
    pub chunks: usize,
}

/// Ingests every loadable file under `dir` into `vectors`: unchanged
/// files are skipped, others swapped in with `replace_source`, and after
/// a complete walk a source is removed only when its file is gone from
/// disk, checked again just before removal; filtered-out files stay.
/// Output: the report, or an error for a walk cap, a blank scope or a
/// store write that fails.
pub async fn ingest_dir(
    vectors: &SqliteVectors,
    embedder: &dyn Embedder,
    dir: &Path,
    settings: &IngestSettings,
) -> Result<IngestReport, ContextError> {
    if settings.scope.trim().is_empty() {
        return Err(ContextError::Invalid("scope must not be empty".into()));
    }
    if settings.max_remove_share > 100 {
        return Err(ContextError::Invalid(format!(
            "max_remove_share is {}%, above 100%",
            settings.max_remove_share
        )));
    }
    let walked = walk(dir, &settings.load)?;
    let present: HashSet<String> = walked.files.iter().map(|f| f.source.clone()).collect();
    let stored = vectors.sources(&settings.scope).await?;
    let gone: Vec<String> = stored
        .iter()
        .filter(|s| !present.contains(*s) && !on_disk(dir, s))
        .cloned()
        .collect();
    check_removals(gone.len(), stored.len(), present.is_empty(), settings)?;
    let mut report = IngestReport {
        added: 0,
        replaced: 0,
        skipped: 0,
        removed: 0,
        unsupported: walked.unsupported,
        symlinks: walked.symlinks,
        failed: Vec::new(),
        chunks: 0,
    };
    let at_ms = SystemClock.now_ms();
    for file in walked.files {
        let ingest_hash = ingest_hash(&file.content_hash, settings);
        let previous = vectors.source_hash(&settings.scope, &file.source).await?;
        if previous.as_deref() == Some(ingest_hash.as_str()) {
            report.skipped += 1;
            continue;
        }
        let doc = Document {
            scope: settings.scope.clone(),
            source: file.source.clone(),
            text: file.text,
            at_ms,
            origin: settings.origin,
            meta: Default::default(),
        };
        let outcome = match document_records(embedder, &doc, &settings.chunk).await {
            Ok(records) => vectors
                .replace_source(&settings.scope, &file.source, records, &ingest_hash)
                .await
                .map_err(ContextError::from),
            Err(e) => Err(e),
        };
        match outcome {
            Ok(written) => {
                report.chunks += written;
                if previous.is_some() {
                    report.replaced += 1;
                } else {
                    report.added += 1;
                }
            }
            Err(e) => {
                let error = e.to_string();
                vectors
                    .record_failed_source(&settings.scope, &file.source, &error)
                    .await?;
                report.failed.push((file.source, error));
            }
        }
    }
    for source in &gone {
        if on_disk(dir, source) {
            continue;
        }
        vectors.remove_source(&settings.scope, source).await?;
        report.removed += 1;
    }
    let handled = report.added + report.replaced + report.skipped + report.failed.len();
    assert!(
        handled <= settings.load.max_files(),
        "more files handled than the walk allows"
    );
    Ok(report)
}

/// Hash stored per source: the file's content hash together with the
/// origin and chunk config its chunks were made with, so a settings
/// change no longer matches and the file is ingested again.
/// Input: the content hash and the settings. Output: 16 hex chars.
fn ingest_hash(content_hash: &str, settings: &IngestSettings) -> String {
    let max = settings.chunk.max_tokens.to_string();
    let overlap = settings.chunk.overlap_tokens.to_string();
    let hash = format!(
        "{:016x}",
        stable_hash(&[content_hash, settings.origin.as_str(), &max, &overlap])
    );
    assert_eq!(hash.len(), 16, "ingest hash is 16 hex chars");
    hash
}

/// Refuses a run that would wipe the scope from an empty folder, or
/// remove more than `max_remove_share` percent of its sources, unless
/// `allow_remove_all`. Input: planned and stored counts, whether the walk
/// found no file, and settings. Output: `Ok`, or `Invalid` with the count.
fn check_removals(
    planned: usize,
    stored: usize,
    no_files: bool,
    settings: &IngestSettings,
) -> Result<(), ContextError> {
    assert!(
        planned <= stored,
        "more removals planned than sources stored"
    );
    if settings.allow_remove_all || planned == 0 {
        return Ok(());
    }
    let scope = &settings.scope;
    if no_files {
        return Err(ContextError::Invalid(format!(
            "walk found no supported files but scope {scope} has {stored} sources; refusing to remove them all \
             (check the folder, or set with_allow_remove_all(true))"
        )));
    }
    let share = usize::from(settings.max_remove_share);
    if planned * 100 > stored * share {
        return Err(ContextError::Invalid(format!(
            "refusing to remove {planned} of {stored} sources of scope {scope}, above max_remove_share {share}% \
             (check the folder, or raise with_max_remove_share or set with_allow_remove_all(true))"
        )));
    }
    Ok(())
}

fn on_disk(dir: &Path, source: &str) -> bool {
    let relative = Path::new(source);
    let plain = relative
        .components()
        .all(|c| matches!(c, std::path::Component::Normal(_)));
    if !plain {
        return false;
    }
    match std::fs::symlink_metadata(dir.join(relative)) {
        Ok(_) => true,
        Err(e) => e.kind() != std::io::ErrorKind::NotFound,
    }
}

/// A folder an agent can search: `Knowledge::dir("docs")` plus settings.
/// At `build` the folder is ingested into index `index` of the store file
/// (unchanged files skipped) and the agent gets the `search_knowledge`
/// tool. The embedder defaults to the catalog's for the agent's vendor.
#[derive(Clone)]
pub struct Knowledge {
    pub(crate) dir: PathBuf,
    pub(crate) index: String,
    pub(crate) store: Option<PathBuf>,
    pub(crate) embedder: Option<Arc<dyn Embedder>>,
    pub(crate) on_device: bool,
    #[cfg(feature = "local")]
    pub(crate) local: Option<crate::local::LocalChoice>,
    pub(crate) load: LoadSettings,
    pub(crate) chunk: ChunkConfig,
    pub(crate) allow_failed: bool,
    pub(crate) allow_remove_all: bool,
}

impl Knowledge {
    /// Starts settings for folder `dir`, read at `build`.
    /// Index `docs`, the agent's SQLite checkpoint file or
    /// `./troupekit.db`, and the `ingest_dir` walk and chunk defaults.
    pub fn dir(dir: impl AsRef<Path>) -> Self {
        let defaults = IngestSettings::default();
        Knowledge {
            dir: dir.as_ref().to_path_buf(),
            index: defaults.scope().to_string(),
            store: None,
            embedder: None,
            on_device: false,
            #[cfg(feature = "local")]
            local: None,
            load: defaults.load().clone(),
            chunk: defaults.chunk(),
            allow_failed: false,
            allow_remove_all: defaults.allow_remove_all(),
        }
    }

    /// Sets the vector index and scope the folder is stored under.
    /// 1 to 64 of `[a-z0-9_]`, checked at `build`.
    /// Default `docs`.
    pub fn index(mut self, index: impl Into<String>) -> Self {
        self.index = index.into();
        self
    }

    /// Sets the SQLite file the index lives in.
    /// Default: the agent's `Storage::sqlite` file, else `./troupekit.db`.
    /// Returns the settings.
    pub fn store(mut self, path: impl AsRef<Path>) -> Self {
        self.store = Some(path.as_ref().to_path_buf());
        self
    }

    /// Sets the embedder for the folder and for searches, overriding the
    /// catalog embedder of the agent's vendor; dimensions must match an
    /// existing index of the same name.
    /// Returns the settings.
    pub fn embedder(mut self, embedder: Arc<dyn Embedder>) -> Self {
        self.embedder = Some(embedder);
        self.on_device = false;
        self.clear_local();
        self
    }

    /// Sets an embedder that runs on the device, with no network, and
    /// marks it so: a private agent accepts only such an embedder.
    /// Otherwise the same as `embedder`.
    pub fn on_device_embedder(mut self, embedder: Arc<dyn Embedder>) -> Self {
        self.embedder = Some(embedder);
        self.on_device = true;
        self.clear_local();
        self
    }

    /// Embeds on the device with a local model: a catalog id, a GGUF
    /// file or a loaded `Arc<dyn LocalModel>`, loaded at `build` like
    /// `Agent::local`. Marks the embedder on-device for private agents.
    #[cfg(feature = "local")]
    pub fn local_embedder(mut self, choice: impl Into<crate::local::LocalChoice>) -> Self {
        self.embedder = None;
        self.local = Some(choice.into());
        self.on_device = true;
        self
    }

    #[cfg(feature = "local")]
    fn clear_local(&mut self) {
        self.local = None;
    }

    #[cfg(not(feature = "local"))]
    fn clear_local(&mut self) {}

    /// Sets the folder walk bounds and filters.
    /// Default `LoadSettings::default()`.
    /// Returns the settings.
    pub fn load(mut self, load: LoadSettings) -> Self {
        self.load = load;
        self
    }

    /// Sets the chunk size and overlap, in estimated tokens.
    /// Default 200 tokens with 20 of overlap.
    /// Returns the settings.
    pub fn chunk(mut self, chunk: ChunkConfig) -> Self {
        self.chunk = chunk;
        self
    }
}

impl Knowledge {
    /// Lets `build` succeed when some files fail to ingest; the rest is
    /// searchable and failed files are retried on the next build. Default
    /// `false`: `build` fails and lists the failed files.
    pub fn allow_failed(mut self, allow: bool) -> Self {
        self.allow_failed = allow;
        self
    }

    /// Lets `build` re-ingest a folder that lost more than half its files,
    /// or all of them, removing those sources from the index. Default
    /// `false`: such a build fails, guarding against a wrong folder.
    pub fn allow_remove_all(mut self, allow: bool) -> Self {
        self.allow_remove_all = allow;
        self
    }
}

impl From<&str> for Knowledge {
    fn from(dir: &str) -> Self {
        Knowledge::dir(dir)
    }
}

impl From<&Path> for Knowledge {
    fn from(dir: &Path) -> Self {
        Knowledge::dir(dir)
    }
}

impl From<PathBuf> for Knowledge {
    fn from(dir: PathBuf) -> Self {
        Knowledge::dir(dir)
    }
}

impl fmt::Debug for Knowledge {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Knowledge")
            .field("dir", &self.dir)
            .field("index", &self.index)
            .field("store", &self.store)
            .field("embedder", &self.embedder.is_some())
            .field("on_device", &self.on_device)
            .field("allow_failed", &self.allow_failed)
            .field("allow_remove_all", &self.allow_remove_all)
            .finish_non_exhaustive()
    }
}