Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(embeddings): add embedding ranker for tinyagents discovery

Steven Enamakel28f90564722f
diff --git a/crates/openhuman-core/src/agent/tinyagents/discovery/embedding_ranker.rs b/crates/openhuman-core/src/agent/tinyagents/discovery/embedding_ranker.rs
index a6cbb2203d..fa4dfe8a50 100644
--- a/crates/openhuman-core/src/agent/tinyagents/discovery/embedding_ranker.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/discovery/embedding_ranker.rs
@@ -1,54 +1,22 @@
-//! Host wiring for the harness `EmbeddingToolRanker`: adapt the process's
-//! `EmbeddingProvider` onto the vendor `EmbeddingModel` and decide whether the
+//! Host wiring for the harness `EmbeddingToolRanker`: take the process's
+//! `EmbeddingModel` and decide whether the
//! provider can embed at all. The ranker itself (cosine ranking, the in-memory
//! and durable catalogue cache) lives in `tinyagents-harness`
//! (`tool::discover::EmbeddingToolRanker`, `DriverEmbeddingCache`).
use std::sync::Arc;
-use async_trait::async_trait;
use tinyagents_harness::tool::discover::{DriverEmbeddingCache, EmbeddingToolRanker};
-use tinyinference_embeddings::{EmbeddingModel, Error as EmbedError, Result as EmbedResult};
+use tinyinference_embeddings::EmbeddingModel;
-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_cache(cache)` to persist it (see [`embedding_tool_ranker_in`]). 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 {
+pub fn embedding_tool_ranker(provider: Arc<dyn EmbeddingModel>) -> EmbeddingToolRanker {
let signature = provider.signature();
- EmbeddingToolRanker::new(Arc::new(RankerEmbeddingModel(provider)), signature)
+ EmbeddingToolRanker::new(provider, signature)
}
/// A ranker over `provider` whose catalogue embeddings are cached in the
@@ -56,7 +24,7 @@ pub fn embedding_tool_ranker(provider: Arc<dyn EmbeddingProvider>) -> EmbeddingT
/// backend cannot be had the ranker still works, with its in-memory cache
/// only.
pub fn embedding_tool_ranker_in(
- provider: Arc<dyn EmbeddingProvider>,
+ provider: Arc<dyn EmbeddingModel>,
workspace_dir: &std::path::Path,
) -> EmbeddingToolRanker {
let ranker = embedding_tool_ranker(provider);
@@ -73,7 +41,7 @@ pub fn embedding_tool_ranker_in(
/// 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 {
+pub fn embedding_provider_is_usable(provider: &dyn EmbeddingModel) -> bool {
provider.dimensions() > 0 && provider.name() != "none"
}
diff --git a/crates/openhuman-core/src/agent/tinyagents/embeddings.rs b/crates/openhuman-core/src/agent/tinyagents/embeddings.rs
index 2e153f5b37..e4e743fa9f 100644
--- a/crates/openhuman-core/src/agent/tinyagents/embeddings.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/embeddings.rs
@@ -1,130 +1,74 @@
-//! Adapter bridging OpenHuman's [`EmbeddingProvider`] onto the `tinyagents`
-//! crate's [`EmbeddingModel`] trait (issue #4249, workstream 09-embeddings).
+//! Cost-recording binding over the host's embedding model (issue #4249).
//!
-//! OpenHuman owns the concrete embedding providers (voyage / openai / cohere /
-//! ollama / cloud / noop) and the `embeddings/factory.rs` construction policy
-//! (rate-limit + retry). This adapter is a **thin seam**: it wraps an
-//! `Arc<dyn EmbeddingProvider>` and re-exposes it as the crate's provider-neutral
-//! [`EmbeddingModel`] so the harness's retrieval surface
-//! ([`Retriever`](tinyinference_embeddings::Retriever) /
-//! [`VectorStore`](tinyinference_embeddings::VectorStore)) can drive
-//! OpenHuman embeddings without cloning provider logic.
-//!
-//! The only real work here is bridging the batch signature: the crate trait
-//! takes `&[String]` while OpenHuman's `EmbeddingProvider::embed` takes
-//! `&[&str]`, and the crate uses its own `TinyAgentsError` while OpenHuman uses
-//! `anyhow::Error`. Both are mapped without touching the underlying providers.
-//!
-//! Wired into the recall/retrieval path in step 09.2; this step just lands the
-//! adapter + test so it compiles and is available. The `pub(crate)` re-export
-//! from `mod.rs` keeps it on the crate surface so it is not dead code.
+//! The model contract, the signature format and the batch shape all live in
+//! `tinyinference-embeddings`; this file only adds OpenHuman's per-call
+//! embedding cost recording.
use std::sync::Arc;
use async_trait::async_trait;
-use tinyinference_embeddings::EmbeddingModel as TaEmbeddingModel;
-use tinyinference_embeddings::{Error as TiError, Result as TaResult};
-
-use crate::inference::embedding_host::EmbeddingProvider;
+use tinyinference_embeddings::{EmbeddingModel, Result as EmbedResult};
-/// Wraps an OpenHuman [`EmbeddingProvider`] as a `tinyagents`
-/// [`EmbeddingModel`](TaEmbeddingModel).
-///
-/// Holds the provider behind an `Arc` (matching how providers are shared
-/// elsewhere in the codebase), so the adapter is cheap to clone and share
-/// across async task boundaries behind an `Arc<dyn EmbeddingModel>`.
+/// Wraps the host-bound [`EmbeddingModel`] (credentials, rate limit and
+/// fallback already applied by the factory) and records embedding cost per
+/// call. Everything else delegates to the model.
pub(crate) struct ProviderEmbeddingModel {
- /// The underlying OpenHuman embedding provider (voyage/openai/cohere/ollama/
- /// cloud/noop) with its factory-configured rate-limit + retry policy intact.
- provider: Arc<dyn EmbeddingProvider>,
+ model: Arc<dyn EmbeddingModel>,
}
impl ProviderEmbeddingModel {
- /// Builds an adapter over the given OpenHuman embedding provider.
- pub(crate) fn new(provider: Arc<dyn EmbeddingProvider>) -> Self {
+ /// Builds the cost-recording binding over `model`.
+ pub(crate) fn new(model: Arc<dyn EmbeddingModel>) -> Self {
tracing::debug!(
- provider = provider.name(),
- model_id = provider.model_id(),
- dimensions = provider.dimensions(),
- signature = %provider.signature(),
- "[embeddings] constructing tinyagents EmbeddingModel adapter over EmbeddingProvider"
+ provider = model.name(),
+ model_id = model.model_id(),
+ dimensions = model.dimensions(),
+ signature = %model.signature(),
+ "[embeddings] constructing cost-recording embedding binding"
);
- Self { provider }
- }
-
- /// Returns the wrapped provider's stable embedding-space signature
- /// (`provider=…;model=…;dims=…`). Preserved so a downstream vector store
- /// keyed on the signature stays byte-identical to one keyed on the raw
- /// provider (#1574 fidelity).
- #[allow(dead_code)] // Signature routing is wired into the recall facade in 09.2.
- pub(crate) fn signature(&self) -> String {
- self.provider.signature()
+ Self { model }
}
}
#[async_trait]
-impl TaEmbeddingModel for ProviderEmbeddingModel {
+impl EmbeddingModel for ProviderEmbeddingModel {
+ fn is_enabled(&self) -> bool {
+ self.model.is_enabled()
+ }
+
fn name(&self) -> &str {
- self.provider.name()
+ self.model.name()
}
fn model_id(&self) -> &str {
- self.provider.model_id()
+ self.model.model_id()
}
- async fn embed(&self, texts: &[String]) -> TaResult<Vec<Vec<f32>>> {
- tracing::debug!(
- provider = self.provider.name(),
- batch = texts.len(),
- "[embeddings] adapter embed: entry"
- );
- // Bridge the signature difference: the crate trait hands us owned
- // `String`s; OpenHuman's `EmbeddingProvider::embed` takes borrowed
- // `&str`. Borrow each without allocating new strings.
- let borrowed: Vec<&str> = texts.iter().map(String::as_str).collect();
- let result = self.provider.embed(&borrowed).await.map_err(|e| {
- tracing::warn!(
- provider = self.provider.name(),
- error = %e,
- "[embeddings] adapter embed: provider error"
- );
- // OpenHuman providers surface `anyhow::Error`; the crate expects its
- // own error type. Carry the full chain into the crate's embedding
- // error variant so nothing is lost.
- TiError::Embedding(format!("{e:#}"))
- })?;
- tracing::debug!(
- provider = self.provider.name(),
- vectors = result.len(),
- "[embeddings] adapter embed: exit"
- );
- // Best-effort embedding cost recording (06-cost step 4 / 09-embeddings
- // step 4). Records provider, model, approximate input tokens, dims, and
- // vector count as a CostRecord priced via the unified catalog. Never
- // fail an embed because cost recording failed — `record_embedding_usage`
- // swallows its own errors; we only skip the accounting call for an empty
- // batch (a non-event) so the request count isn't inflated.
+ fn dimensions(&self) -> usize {
+ self.model.dimensions()
+ }
+
+ fn signature(&self) -> String {
+ self.model.signature()
+ }
+
+ async fn embed(&self, texts: &[String]) -> EmbedResult<Vec<Vec<f32>>> {
+ let result = self.model.embed(texts).await?;
+ // Best-effort cost recording; never fails the embed. Skipped for an
+ // empty batch so the request count is not inflated.
if !result.is_empty() {
- // Rough token estimate from character count (~4 chars/token). The
- // exact value only affects the catalog price when an embedding rate
- // exists; embedding models are usually uncatalogued, in which case
- // the recorded cost is zero regardless.
let approx_input_tokens =
tinyinference_embeddings::estimate_embedding_input_tokens(texts);
crate::platform::cost::record_embedding_usage(
- self.provider.name(),
- self.provider.model_id(),
+ self.model.name(),
+ self.model.model_id(),
approx_input_tokens,
- self.provider.dimensions(),
+ self.model.dimensions(),
result.len() as u64,
);
}
Ok(result)
}
-
- fn dimensions(&self) -> usize {
- self.provider.dimensions()
- }
}
#[cfg(test)]
diff --git a/crates/openhuman-core/src/inference/embedding_host/rpc/embed.rs b/crates/openhuman-core/src/inference/embedding_host/rpc/embed.rs
index 1f3f547921..3aee247073 100644
--- a/crates/openhuman-core/src/inference/embedding_host/rpc/embed.rs
+++ b/crates/openhuman-core/src/inference/embedding_host/rpc/embed.rs
@@ -43,7 +43,7 @@ pub async fn embed(
)
.map_err(|e| e.to_string())?;
- let vectors = embedder.embed(&inputs).await.map_err(|e| e.to_string())?;
+ let vectors = embedder.embed(inputs).await.map_err(|e| e.to_string())?;
let actual_dims = vectors.first().map(|v| v.len()).unwrap_or(0);