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;
#[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 {
pub fn with_scope(mut self, scope: impl Into<String>) -> Self {
self.scope = scope.into();
self
}
pub fn with_chunk(mut self, chunk: ChunkConfig) -> Self {
self.chunk = chunk;
self
}
pub fn with_load(mut self, load: LoadSettings) -> Self {
self.load = load;
self
}
pub fn with_origin(mut self, origin: Origin) -> Self {
self.origin = origin;
self
}
pub fn with_allow_remove_all(mut self, allow: bool) -> Self {
self.allow_remove_all = allow;
self
}
pub fn with_max_remove_share(mut self, percent: u8) -> Self {
self.max_remove_share = percent;
self
}
pub fn allow_remove_all(&self) -> bool {
self.allow_remove_all
}
pub fn max_remove_share(&self) -> u8 {
self.max_remove_share
}
pub fn scope(&self) -> &str {
&self.scope
}
pub fn chunk(&self) -> ChunkConfig {
self.chunk
}
pub fn load(&self) -> &LoadSettings {
&self.load
}
pub fn origin(&self) -> Origin {
self.origin
}
}
#[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,
}
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)
}
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
}
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,
}
}
#[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,
}
impl Knowledge {
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,
}
}
pub fn index(mut self, index: impl Into<String>) -> Self {
self.index = index.into();
self
}
pub fn store(mut self, path: impl AsRef<Path>) -> Self {
self.store = Some(path.as_ref().to_path_buf());
self
}
pub fn embedder(mut self, embedder: Arc<dyn Embedder>) -> Self {
self.embedder = Some(embedder);
self.on_device = false;
self.clear_local();
self
}
pub fn on_device_embedder(mut self, embedder: Arc<dyn Embedder>) -> Self {
self.embedder = Some(embedder);
self.on_device = true;
self.clear_local();
self
}
#[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) {}
pub fn load(mut self, load: LoadSettings) -> Self {
self.load = load;
self
}
pub fn chunk(mut self, chunk: ChunkConfig) -> Self {
self.chunk = chunk;
self
}
}
impl Knowledge {
pub fn allow_failed(mut self, allow: bool) -> Self {
self.allow_failed = 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)
.finish_non_exhaustive()
}
}