Skip to main content

troupekit_local/
embed.rs

1use crate::error::LocalError;
2use crate::model::LocalModel;
3use async_trait::async_trait;
4use std::sync::Arc;
5use troupekit_context::embed::Embedder;
6use troupekit_context::error::ContextError;
7
8const BATCH: usize = 32;
9
10/// On-device embeddings from a `LocalModel`, for knowledge search with
11/// no network. Mean-pooled, L2-normalized vectors (the mean of the
12/// token rows); batches of at most 32 texts run off the async runtime.
13pub struct LocalEmbedder {
14    model: Arc<dyn LocalModel>,
15    dims: usize,
16}
17
18impl LocalEmbedder {
19    /// Wraps a model that can embed.
20    /// Input: the model. Output: the embedder, or
21    /// `Unsupported("embeddings")` when its embedding size is 0.
22    pub fn new(model: Arc<dyn LocalModel>) -> Result<Self, LocalError> {
23        let dims = model.info().embedding_dims();
24        if dims == 0 {
25            return Err(LocalError::Unsupported("embeddings"));
26        }
27        Ok(Self { model, dims })
28    }
29}
30
31impl std::fmt::Debug for LocalEmbedder {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        f.debug_struct("LocalEmbedder")
34            .field("dims", &self.dims)
35            .finish_non_exhaustive()
36    }
37}
38
39#[async_trait]
40impl Embedder for LocalEmbedder {
41    fn dims(&self) -> usize {
42        self.dims
43    }
44
45    async fn embed(&self, texts: &[String]) -> Result<Vec<Vec<f32>>, ContextError> {
46        let mut out = Vec::with_capacity(texts.len());
47        for batch in texts.chunks(BATCH) {
48            let model = Arc::clone(&self.model);
49            let batch = batch.to_vec();
50            let n = batch.len();
51            let vectors = tokio::task::spawn_blocking(move || model.embed(&batch))
52                .await
53                .map_err(|e| ContextError::Embed(format!("local embed task failed: {e}")))?
54                .map_err(|e| ContextError::Embed(e.to_string()))?;
55            if vectors.len() != n {
56                return Err(ContextError::Embed(format!(
57                    "local model returned {} vectors for {n} texts",
58                    vectors.len()
59                )));
60            }
61            out.extend(vectors);
62        }
63        assert!(out.len() == texts.len(), "one vector per text");
64        Ok(out)
65    }
66}