The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(discovery): correct embedding ranker to use cosine similarity
Steven Enamakele11a08f6e48e
diff --git a/crates/openhuman-core/src/agent/tinyagents/discovery/embedding_ranker.rs b/crates/openhuman-core/src/agent/tinyagents/discovery/embedding_ranker.rsnew file mode 100644index 0000000000..6a51f20773--- /dev/null+++ b/crates/openhuman-core/src/agent/tinyagents/discovery/embedding_ranker.rs@@ -0,0 +1,61 @@+//! Host wiring for the harness `EmbeddingToolRanker`: adapt the process's+//! `EmbeddingProvider` onto the vendor `EmbeddingModel` and decide whether the+//! provider can embed at all. The ranker itself (cosine ranking, the in-memory+//! and on-disk catalogue cache) lives in `tinyagents-harness`+//! (`tool::discover::EmbeddingToolRanker`).++use std::sync::Arc;++use async_trait::async_trait;+use tinyagents_harness::tool::discover::EmbeddingToolRanker;+use tinyinference_embeddings::{EmbeddingModel, Error as EmbedError, Result as EmbedResult};++use crate::inference::embedding_host::EmbeddingProvider;++/// A provider viewed as an `EmbeddingModel`, with no side effects.+///+/// Deliberately not [`ProviderEmbeddingModel`](crate::agent::tinyagents::embeddings):+/// that adapter records embedding cost per call, and catalogue ranking has never+/// been metered.+struct RankerEmbeddingModel(Arc<dyn EmbeddingProvider>);++#[async_trait]+impl EmbeddingModel for RankerEmbeddingModel {+ fn name(&self) -> &str {+ self.0.name()+ }++ fn model_id(&self) -> &str {+ self.0.model_id()+ }++ fn dimensions(&self) -> usize {+ self.0.dimensions()+ }++ async fn embed(&self, texts: &[String]) -> EmbedResult<Vec<Vec<f32>>> {+ let borrowed: Vec<&str> = texts.iter().map(String::as_str).collect();+ self.0+ .embed(&borrowed)+ .await+ .map_err(|error| EmbedError::Embedding(format!("{error:#}")))+ }+}++/// A ranker over `provider` with an in-memory cache; chain+/// `.with_disk_cache(path)` to persist it. The cache is keyed by the provider's+/// embedding-space signature, so a model change invalidates it.+pub fn embedding_tool_ranker(provider: Arc<dyn EmbeddingProvider>) -> EmbeddingToolRanker {+ let signature = provider.signature();+ EmbeddingToolRanker::new(Arc::new(RankerEmbeddingModel(provider)), signature)+}++/// Whether `provider` can embed at all. The `none` provider embeds nothing and+/// would rank everything at zero.+pub fn embedding_provider_is_usable(provider: &dyn EmbeddingProvider) -> bool {+ provider.dimensions() > 0 && provider.name() != "none"+}++#[cfg(test)]+#[path = "embedding_ranker_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/agent/tinyagents/discovery/embedding_ranker_tests.rs b/crates/openhuman-core/src/agent/tinyagents/discovery/embedding_ranker_tests.rsnew file mode 100644index 0000000000..dc80a05a76--- /dev/null+++ b/crates/openhuman-core/src/agent/tinyagents/discovery/embedding_ranker_tests.rs@@ -0,0 +1,81 @@+use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::Arc;++use tinytools::{RankCandidate, RankContext, ToolRanker};++use super::*;++/// Counts embed calls and maps every text to a fixed three-word bag.+struct BagEmbedder {+ calls: AtomicUsize,+}++#[async_trait::async_trait]+impl EmbeddingProvider for BagEmbedder {+ fn name(&self) -> &str {+ "bag"+ }+ fn model_id(&self) -> &str {+ "bag-v1"+ }+ fn dimensions(&self) -> usize {+ 3+ }+ fn signature(&self) -> String {+ "provider=bag;model=bag-v1;dims=3".into()+ }+ async fn embed(&self, texts: &[&str]) -> anyhow::Result<Vec<Vec<f32>>> {+ self.calls.fetch_add(1, Ordering::SeqCst);+ Ok(texts+ .iter()+ .map(|t| {+ let t = t.to_ascii_lowercase();+ vec![+ f32::from(u8::from(t.contains("message") || t.contains("ping"))),+ f32::from(u8::from(t.contains("email") || t.contains("mail"))),+ f32::from(u8::from(t.contains("file"))),+ ]+ })+ .collect())+ }+}++fn candidates() -> Vec<RankCandidate> {+ vec![+ RankCandidate::new("SLACK_SEND_MESSAGE", "send a message to a channel")+ .with_family("slack"),+ RankCandidate::new("GMAIL_SEND_EMAIL", "send an email").with_family("gmail"),+ RankCandidate::new("file_read", "read a file"),+ ]+}++/// The provider adapter carries the embedding through to the vendor ranker, and+/// the provider's signature keys the disk cache it writes.+#[tokio::test]+async fn the_ranker_ranks_through_the_provider_and_keys_its_cache_by_signature() {+ let tmp = tempfile::tempdir().unwrap();+ let path = tmp.path().join("cache.json");+ let embedder = Arc::new(BagEmbedder {+ calls: AtomicUsize::new(0),+ });+ let ranker = embedding_tool_ranker(embedder.clone()).with_disk_cache(path.clone());+ let hits = ranker+ .rank("ping alex", &RankContext::empty(), &candidates(), 1)+ .await+ .unwrap();+ assert_eq!(hits[0].key, "SLACK_SEND_MESSAGE");+ let on_disk: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();+ assert_eq!(on_disk["signature"], "provider=bag;model=bag-v1;dims=3");+}++#[test]+fn the_none_provider_is_unusable() {+ let none = crate::inference::embedding_host::TinyInferenceEmbeddingProvider::new(+ tinyinference_embeddings::NoopEmbeddingModel,+ );+ assert!(!embedding_provider_is_usable(&none));+ let bag = BagEmbedder {+ calls: AtomicUsize::new(0),+ };+ assert!(embedding_provider_is_usable(&bag));+}diff --git a/crates/openhuman-core/src/agent/tinyagents/discovery/mod.rs b/crates/openhuman-core/src/agent/tinyagents/discovery/mod.rsindex 9f4988fc29..6c8484b584 100644--- a/crates/openhuman-core/src/agent/tinyagents/discovery/mod.rs+++ b/crates/openhuman-core/src/agent/tinyagents/discovery/mod.rs@@ -214,7 +214,7 @@ impl ToolRanker for OverlapRanker {mod embedding_ranker;-pub use embedding_ranker::EmbeddingToolRanker;+pub use embedding_ranker::{embedding_provider_is_usable, embedding_tool_ranker};#[cfg(test)]#[path = "discovery_tests.rs"]