Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Knowledge

Knowledge lets an agent answer from your own documents instead of from what the model happens to know. You point it at a folder, troupekit indexes the files, and the agent gets a search tool it can call while it works.

Turn on the knowledge feature and add .knowledge(Knowledge::dir(path)) to the agent. The folder is ingested when you call build, and files that have not changed since the last build are skipped. The agent gets one tool, search_knowledge. Its results reach the model fenced as untrusted text, because a document can contain instructions and the model should treat them as data.

A searchable folder

This test builds the same agent twice over one folder. We check that the agent got the search tool, and that the second build calls the embedder zero times:

#![allow(unused)]
fn main() {
let reader = || {
    Agent::new("reader")
        .instructions("Read.")
        .model("fake/m")
        .model_client(echo_user_text())
        .checkpoints(Storage::sqlite(dir.path().join("kb.db")))
        .knowledge(Knowledge::dir(&docs).embedder(embedder.clone()))
};
let built = reader().build().await.unwrap();
assert_eq!(built.persona().tools, ["search_knowledge".to_string()]);
let after_first = embedder.calls.load(Ordering::SeqCst);
assert!(after_first > 0);
reader().build().await.unwrap();
assert_eq!(embedder.calls.load(Ordering::SeqCst), after_first);
}

The second build embeds nothing because no file changed. In an app, this is what keeps startup cheap after the first run.

Settings

MethodMeaningDefault
index(name)vector index and scope the folder is stored under, 1 to 64 of [a-z0-9_]docs
store(path)SQLite file the index lives inthe agent's Storage::sqlite file, else ./troupekit.db
embedder(e)embedder for the folder and for searchesthe catalog embedder of the agent's vendor
on_device_embedder(e)an embedder marked as on-device, for private agentsnone
local_embedder(choice)embed with a local model: catalog id, GGUF file or loaded modelnone
chunk(cfg)chunk size and overlap, in estimated tokens200 tokens, 20 of overlap
load(settings)folder walk bounds and filtersLoadSettings::default()
allow_failed(on)let build succeed when some files fail; they retry on the next buildfalse
allow_remove_all(on)let build re-ingest a folder that lost more than half its files, or all of themfalse

Note

If your agent's vendor has no embedding model in the catalog, you must set one with .embedder(..). Without it, build fails and tells you so.

What is read

The walk reads text, Markdown and HTML files: txt, md, markdown, html and htm. It skips hidden entries such as .git, and it does not follow symlinks, because a link can point outside the folder you chose.

The walk also has limits, so a huge or deep folder cannot take over the process:

LimitDefault
files10 000
bytes per file8 MiB
depth16
directory entries100 000

Going over a limit is an error that names the limit. A walk never stops halfway without telling you.

Before indexing, each file is split into chunks of at most max_tokens tokens, estimated at four characters per token. The splitter cuts at a paragraph break when it can, then at a sentence end, then at a space.

Keyword search finds exact terms, such as an error code or a product name. Vector search finds passages that mean the same thing in other words. hybrid_search runs both and merges the two ranked lists with reciprocal rank fusion, which gives you the strengths of each. Set HybridMode::Vector or HybridMode::Keyword to use one list alone.

SettingDefault
modeHybrid
k_rrf60
candidates per list per scope50
results8
filter pairs16
query length2 000 chars

The keyword list comes from SQLite FTS5 and the vector list from troupekit-index. The default vector index, IndexKind::BruteForce, is exact. IndexKind::Hnsw(params) is an approximate graph index; the benchmarks check that its default settings reach a recall@10 of 0.95 against brute force. Either one stores vectors as Quantization::F32 by default, or as F16 or I8 to save memory.

The engine API

You can also skip the builder and drive the engine crates yourself. Here the support example opens the store and ingests a folder:

#![allow(unused)]
fn main() {
pub async fn open(db: &Path, docs: &Path, embedder: &dyn Embedder) -> Outcome<(SqliteStore, Arc<SqliteVectors>, IngestReport)> {
    let store = SqliteStore::open(db).await?;
    let vectors = Arc::new(store.vectors(INDEX, VectorSettings::new(embedder.dims())).await?);
    let report = ingest_dir(&vectors, embedder, docs, &IngestSettings::default()).await?;
    Ok((store, vectors, report))
}
}

See the Support agent guide for the whole program.

From the command line

You can build the same index without writing any code. troupekit ingest puts a folder into one SQLite file:

usage: troupekit ingest <dir> [--db FILE] [--index NAME] [--scope NAME] --embedder SELECTOR [--catalog FILE] [--key-env VAR] [--chunk-tokens N] [--overlap-tokens N] [--kind brute|hnsw] [--quant f32|f16|i8] [--max-remove-share PERCENT] [--allow-remove-all]

--embedder takes an embedding model from the catalog as vendor/model, or hashing:<dims> for an offline hashing embedder that needs no key and no network.