Skip to content

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

feat(embed): add completion support to embedding crate

Steven Enamakel8f3d2c48ae70
diff --git a/crates/openhuman-embed/src/complete.rs b/crates/openhuman-embed/src/complete.rs
new file mode 100644
index 0000000000..08e87f5a1a
--- /dev/null
+++ b/crates/openhuman-embed/src/complete.rs
@@ -0,0 +1,470 @@
+//! Stateless structured completions on an explicit route.
+//!
+//! [`Completer`] is for hosts that need *one model call*, not an agent: a code
+//! reviewer asking for a JSON verdict, a classifier, an extractor. It needs no
+//! [`Runtime`](crate::Runtime), so it has none of the runtime's constraints —
+//! no process-wide singleton, no 20 MiB worker stacks — and any number of
+//! completers can run concurrently in one process.
+//!
+//! What it deliberately does **not** do, compared to an agent
+//! [`Turn`](crate::Turn):
+//!
+//! - **No prompt guard.** The guard protects an agent that holds tools from a
+//! user steering it. A completion holds none, and its callers routinely pass
+//! adversarial text (pull request diffs, issue bodies) as data. A guard would
+//! reject exactly the inputs they exist to read.
+//! - **No tools, session, memory or orchestrator prompt.** The request that
+//! reaches the wire is the one the host built.
+//! - **No silent fallback.** The route is mandatory and the requested model is
+//! sent as-is; [`CompletionResponse::answered_model`] reports what the
+//! provider says actually answered, so a host can detect a gateway-side
+//! substitution instead of paying for one blind.
+//!
+//! ```no_run
+//! # async fn demo() -> Result<(), openhuman_embed::CoreError> {
+//! use openhuman_embed::complete::{ChatMessage, CompletionRequest, Completer, ResponseFormat};
+//! use openhuman_embed::Route;
+//!
+//! let completer = Completer::new(Route::openai_compatible("https://openrouter.ai/api/v1", "sk-…"));
+//! let response = completer
+//! .complete(
+//! CompletionRequest::new(
+//! "openai/gpt-5-mini",
+//! vec![ChatMessage::system("Answer in JSON."), ChatMessage::user("Is 7 prime?")],
+//! )
+//! .response_format(ResponseFormat::JsonSchema {
+//! name: "answer".into(),
+//! schema: serde_json::json!({"type": "object", "properties": {"prime": {"type": "boolean"}}}),
+//! })
+//! .max_tokens(64),
+//! )
+//! .await?;
+//! println!("{:?} finish={:?}", response.structured, response.finish_reason);
+//! # Ok(())
+//! # }
+//! ```
+
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use tinyinference_llm::message::{ContentBlock, ImageRef, Message, SystemMessage, UserMessage};
+use tinyinference_llm::model::{ModelRequest, ModelResponse};
+
+use crate::error::CoreError;
+use crate::turn::{is_safe_endpoint_for_bearer, sanitize_url_for_display, Route};
+
+/// Method label carried by every [`CoreError`] this module returns.
+pub const COMPLETE: &str = "openhuman.complete";
+
+/// Who authored a [`ChatMessage`].
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Role {
+ /// Instructions to the model.
+ System,
+ /// Input to the model.
+ User,
+ /// A prior model reply, for few-shot or continuation prompts.
+ Assistant,
+}
+
+/// One message of a [`CompletionRequest`].
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct ChatMessage {
+ /// Author of the message.
+ pub role: Role,
+ /// Text content.
+ pub text: String,
+ /// Image URLs or `data:` URIs, attached after the text. Only meaningful on
+ /// a [`Role::User`] message; ignored elsewhere.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub images: Vec<String>,
+}
+
+impl ChatMessage {
+ /// A system message.
+ pub fn system(text: impl Into<String>) -> Self {
+ Self::new(Role::System, text)
+ }
+
+ /// A user message.
+ pub fn user(text: impl Into<String>) -> Self {
+ Self::new(Role::User, text)
+ }
+
+ /// An assistant message.
+ pub fn assistant(text: impl Into<String>) -> Self {
+ Self::new(Role::Assistant, text)
+ }
+
+ /// Attach an image (URL or `data:` URI) to this message.
+ pub fn with_image(mut self, url: impl Into<String>) -> Self {
+ self.images.push(url.into());
+ self
+ }
+
+ fn new(role: Role, text: impl Into<String>) -> Self {
+ Self {
+ role,
+ text: text.into(),
+ images: Vec::new(),
+ }
+ }
+
+ fn into_wire(self) -> Message {
+ match self.role {
+ Role::System => Message::System(SystemMessage::text(self.text)),
+ Role::Assistant => Message::assistant(self.text),
+ Role::User => {
+ let mut content = vec![ContentBlock::Text(self.text)];
+ content.extend(self.images.into_iter().map(|url| {
+ ContentBlock::Image(ImageRef {
+ mime_type: data_uri_mime(&url),
+ url,
+ })
+ }));
+ Message::User(UserMessage { content })
+ }
+ }
+ }
+}
+
+/// The MIME type a `data:` URI declares, if any.
+fn data_uri_mime(url: &str) -> Option<String> {
+ let rest = url.strip_prefix("data:")?;
+ let mime = rest.split([';', ',']).next()?.trim();
+ (!mime.is_empty()).then(|| mime.to_string())
+}
+
+/// Requested output shape.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum ResponseFormat {
+ /// Free-form text.
+ Text,
+ /// Any JSON object.
+ JsonObject,
+ /// JSON constrained to `schema`, advertised to the provider as `name`.
+ JsonSchema {
+ /// Schema name the provider sees.
+ name: String,
+ /// JSON Schema document.
+ schema: Value,
+ },
+}
+
+impl ResponseFormat {
+ fn wants_json(&self) -> bool {
+ !matches!(self, ResponseFormat::Text)
+ }
+
+ fn into_wire(self) -> tinyinference_llm::model::ResponseFormat {
+ use tinyinference_llm::model::ResponseFormat as Wire;
+ match self {
+ ResponseFormat::Text => Wire::Text,
+ ResponseFormat::JsonObject => Wire::JsonObject,
+ ResponseFormat::JsonSchema { name, schema } => Wire::JsonSchema { name, schema },
+ }
+ }
+}
+
+/// One stateless model call.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct CompletionRequest {
+ /// Model id on the route's endpoint. Required and sent verbatim.
+ pub model: String,
+ /// Conversation, in order.
+ pub messages: Vec<ChatMessage>,
+ /// Output shape. `None` leaves the provider's default (text).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub response_format: Option<ResponseFormat>,
+ /// Output token ceiling. A reply that hits it ends with
+ /// [`finish_reason`](CompletionResponse::finish_reason) `"length"`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub max_tokens: Option<u32>,
+ /// Sampling temperature.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub temperature: Option<f64>,
+ /// Provider-specific body keys merged into the request untouched — for an
+ /// OpenRouter-style gateway, `provider` routing, `reasoning`, and
+ /// `usage: {include: true}` so the response carries its cost.
+ #[serde(default, skip_serializing_if = "Value::is_null")]
+ pub provider_options: Value,
+}
+
+impl CompletionRequest {
+ /// A request for `model` over `messages` with every option unset.
+ pub fn new(model: impl Into<String>, messages: Vec<ChatMessage>) -> Self {
+ Self {
+ model: model.into(),
+ messages,
+ response_format: None,
+ max_tokens: None,
+ temperature: None,
+ provider_options: Value::Null,
+ }
+ }
+
+ /// Set the output shape.
+ pub fn response_format(mut self, format: ResponseFormat) -> Self {
+ self.response_format = Some(format);
+ self
+ }
+
+ /// Set the output token ceiling.
+ pub fn max_tokens(mut self, max_tokens: u32) -> Self {
+ self.max_tokens = Some(max_tokens);
+ self
+ }
+
+ /// Set the sampling temperature.
+ pub fn temperature(mut self, temperature: f64) -> Self {
+ self.temperature = Some(temperature);
+ self
+ }
+
+ /// Set the provider pass-through options.
+ pub fn provider_options(mut self, options: Value) -> Self {
+ self.provider_options = options;
+ self
+ }
+
+ fn into_wire(self) -> ModelRequest {
+ let mut request =
+ ModelRequest::new(self.messages.into_iter().map(ChatMessage::into_wire).collect())
+ .with_model(self.model);
+ request.response_format = self.response_format.map(ResponseFormat::into_wire);
+ request.max_tokens = self.max_tokens;
+ request.temperature = self.temperature;
+ request.provider_options = self.provider_options;
+ request
+ }
+}
+
+/// Token and cost accounting for one completion.
+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
+pub struct CompletionUsage {
+ /// Prompt tokens, including cached ones.
+ pub input_tokens: u64,
+ /// Completion tokens, including reasoning ones.
+ pub output_tokens: u64,
+ /// Prompt tokens served from the provider's cache.
+ pub cached_tokens: u64,
+ /// Reasoning tokens, when the provider reports them.
+ pub reasoning_tokens: u64,
+ /// What the provider says it charged, in USD, when it says. Never a local
+ /// price estimate: a host that wants one owns that table.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub cost_usd: Option<f64>,
+}
+
+/// The result of one [`Completer::complete`].
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct CompletionResponse {
+ /// The visible reply text (reasoning content excluded).
+ pub text: String,
+ /// `text` parsed as JSON, when a JSON [`ResponseFormat`] was requested and
+ /// the reply parses. `None` with a JSON format means the model returned
+ /// something that is not JSON — check
+ /// [`finish_reason`](Self::finish_reason) for `"length"` first.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub structured: Option<Value>,
+ /// Provider finish reason (`stop`, `length`, …).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub finish_reason: Option<String>,
+ /// The model the provider reports answering, which a routing gateway can
+ /// make differ from the one requested.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub answered_model: Option<String>,
+ /// Token and cost accounting, when the provider reports usage.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub usage: Option<CompletionUsage>,
+ /// The provider's raw response body.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub raw: Option<Value>,
+}
+
+impl CompletionResponse {
+ fn from_wire(response: ModelResponse, wants_json: bool) -> Self {
+ let text = response.text();
+ let structured = wants_json.then(|| parse_json_reply(&text)).flatten();
+ let raw = response.raw;
+ let answered_model = raw
+ .as_ref()
+ .and_then(|raw| raw.get("model"))
+ .and_then(Value::as_str)
+ .map(str::to_string);
+ let raw_cost = raw
+ .as_ref()
+ .and_then(|raw| raw.pointer("/usage/cost"))
+ .and_then(Value::as_f64);
+ let usage = response.usage.map(|usage| CompletionUsage {
+ input_tokens: usage.input_tokens,
+ output_tokens: usage.output_tokens,
+ cached_tokens: usage.cache_read_tokens,
+ reasoning_tokens: usage.reasoning_tokens,
+ cost_usd: usage
+ .charged_amount
+ .map(|amount| amount.micros as f64 / 1_000_000.0)
+ .or(raw_cost),
+ });
+ Self {
+ text,
+ structured,
+ finish_reason: response.finish_reason,
+ answered_model,
+ usage,
+ raw,
+ }
+ }
+}
+
+/// Parse a JSON reply, tolerating one surrounding Markdown code fence — a
+/// common habit of models without native structured output.
+fn parse_json_reply(text: &str) -> Option<Value> {
+ let trimmed = text.trim();
+ if let Ok(value) = serde_json::from_str(trimmed) {
+ return Some(value);
+ }
+ let inner = trimmed.strip_prefix("```")?.strip_suffix("```")?;
+ let inner = inner.split_once('\n').map_or(inner, |(lang, rest)| {
+ if lang.trim().chars().all(char::is_alphanumeric) {
+ rest
+ } else {
+ inner
+ }
+ });
+ serde_json::from_str(inner.trim()).ok()
+}
+
+/// What a [`CompletionObserver`] sees for each call.
+#[derive(Debug)]
+pub struct CompletionTrace<'a> {
+ /// The request as the host built it. The route's bearer is never part of
+ /// a request, so this is safe to export.
+ pub request: &'a CompletionRequest,
+ /// The response, or the error the call ended with.
+ pub outcome: Result<&'a CompletionResponse, &'a CoreError>,
+ /// Wall-clock time from dispatch to outcome.
+ pub latency: Duration,
+}
+
+/// Receives one [`CompletionTrace`] per [`Completer::complete`] call, success
+/// or failure — the hook a host uses to export traces (Langfuse, OTel) or
+/// meter spend without wrapping every call site.
+pub trait CompletionObserver: Send + Sync {
+ /// Called once, after the call settles. Must not block.
+ fn on_complete(&self, trace: &CompletionTrace<'_>);
+}
+
+/// Runs stateless completions against one [`Route`].
+#[derive(Clone)]
+pub struct Completer {
+ route: Route,
+ timeout: Option<Duration>,
+ observer: Option<Arc<dyn CompletionObserver>>,
+}
+
+impl std::fmt::Debug for Completer {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Completer")
+ .field("route", &self.route)
+ .field("timeout", &self.timeout)
+ .field("observer", &self.observer.is_some())
+ .finish()
+ }
+}
+
+impl Completer {
+ /// A completer for `route`, with no timeout and no observer.
+ pub fn new(route: Route) -> Self {
+ Self {
+ route,
+ timeout: None,
+ observer: None,
+ }
+ }
+
+ /// Fail a call that has not settled within `timeout`.
+ pub fn timeout(mut self, timeout: Duration) -> Self {
+ self.timeout = Some(timeout);
+ self
+ }
+
+ /// Report every call to `observer`.
+ pub fn observer(mut self, observer: Arc<dyn CompletionObserver>) -> Self {
+ self.observer = Some(observer);
+ self
+ }
+
+ /// Run `request` once.
+ ///
+ /// # Errors
+ ///
+ /// - [`CoreError::InvalidRoute`] — the route or the model id is blank.
+ /// - [`CoreError::InsecureRoute`] — the route would send its bearer over
+ /// cleartext to a non-loopback host.
+ /// - [`CoreError::Rpc`] — the provider call failed or timed out.
+ pub async fn complete(&self, request: CompletionRequest) -> Result<CompletionResponse, CoreError> {
+ let started = Instant::now();
+ let result = self.dispatch(request.clone()).await;
+ if let Some(observer) = &self.observer {
+ observer.on_complete(&CompletionTrace {
+ request: &request,
+ outcome: result.as_ref(),
+ latency: started.elapsed(),
+ });
+ }
+ result
+ }
+
+ async fn dispatch(&self, request: CompletionRequest) -> Result<CompletionResponse, CoreError> {
+ let route = self.checked_route(&request)?;
+ let wants_json = request
+ .response_format
+ .as_ref()
+ .is_some_and(ResponseFormat::wants_json);
+ let call = openhuman_core::inference::host_runtime::ops::complete_once(
+ route,
+ request.into_wire(),
+ );
+ let response = match self.timeout {
+ Some(limit) => tokio::time::timeout(limit, call).await.map_err(|_| CoreError::Rpc {
+ method: COMPLETE,
+ message: format!("timed out after {}ms", limit.as_millis()),
+ })?,
+ None => call.await,
+ }
+ .map_err(|message| CoreError::Rpc {
+ method: COMPLETE,
+ message,
+ })?;
+ Ok(CompletionResponse::from_wire(response, wants_json))
+ }
+
+ fn checked_route(
+ &self,
+ request: &CompletionRequest,
+ ) -> Result<openhuman_core::config::schema::EphemeralRoute, CoreError> {
+ if request.model.trim().is_empty() {
+ return Err(CoreError::InvalidRoute { method: COMPLETE });
+ }
+ if !is_safe_endpoint_for_bearer(&self.route.base_url) {
+ return Err(CoreError::InsecureRoute {
+ method: COMPLETE,
+ endpoint: sanitize_url_for_display(&self.route.base_url),
+ });
+ }
+ openhuman_core::config::schema::EphemeralRoute::from_params(
+ Some(self.route.base_url.clone()),
+ Some(self.route.api_key.clone()),
+ )
+ .ok_or(CoreError::InvalidRoute { method: COMPLETE })
+ }
+}
+
+#[cfg(test)]
+#[path = "complete_tests.rs"]
+mod tests;