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(embed): settle measured gateway charges before budget admission
Steven Enamakel2b0396b4c89b
diff --git a/crates/openhuman-core/src/agent/tinyagents/budget.rs b/crates/openhuman-core/src/agent/tinyagents/budget.rsindex 95866d319e..6f02d9e0c4 100644--- a/crates/openhuman-core/src/agent/tinyagents/budget.rs+++ b/crates/openhuman-core/src/agent/tinyagents/budget.rs@@ -17,7 +17,7 @@ impl ModelBudget {/// Apply the policy below retries and fallback selection.pub(crate) fn wrap(&self, model: Arc<dyn ChatModel<()>>) -> Arc<dyn ChatModel<()>> {Arc::new(tinyinference_llm::model::budget::BudgetedModel::new(- model,+ Arc::new(super::budget_charge::GatewayChargeModel::new(model)),self.ledger.clone(),self.call,))diff --git a/crates/openhuman-core/src/agent/tinyagents/budget_charge.rs b/crates/openhuman-core/src/agent/tinyagents/budget_charge.rsnew file mode 100644index 0000000000..aee7e8c566--- /dev/null+++ b/crates/openhuman-core/src/agent/tinyagents/budget_charge.rs@@ -0,0 +1,96 @@+//! Normalize measured gateway charges before the shared budget settles calls.++use std::sync::Arc;++use async_trait::async_trait;+use tinyinference_llm::model::{+ ChatModel, InputModality, InputSource, ModelProfile, ModelRequest, ModelResponse, ModelStream,+ ModelStreamItem,+};+use tinyinference_llm::usage::ChargedAmount;++pub(super) struct GatewayChargeModel {+ inner: Arc<dyn ChatModel<()>>,+}++impl GatewayChargeModel {+ pub(super) fn new(inner: Arc<dyn ChatModel<()>>) -> Self {+ Self { inner }+ }+}++fn normalize_charge(response: &mut ModelResponse) {+ let Some(usage) = response.usage.as_mut() else {+ // Missing usage must retain conservative token and charge reservations.+ return;+ };+ let Some(raw) = response.raw.as_ref() else {+ return;+ };+ if let Some(micros) = raw+ .pointer("/usage/buyer_cost_micro")+ .and_then(serde_json::Value::as_i64)+ {+ usage.charged_amount = (micros >= 0).then(|| ChargedAmount::usd_micros(micros));+ return;+ }+ let micros = raw+ .pointer("/usage/buyer_cost_micro")+ .and_then(serde_json::Value::as_f64)+ .or_else(|| {+ raw.pointer("/usage/cost")+ .and_then(serde_json::Value::as_f64)+ .map(|cost| cost * 1_000_000.0)+ });+ let Some(micros) = micros else {+ return;+ };+ // Buyer charge is authoritative, including zero. Invalid reported amounts+ // remain unknown, and fractional micro-units round up rather than refunding+ // money the gateway billed. No local price estimate enters the ledger.+ usage.charged_amount = (micros.is_finite() && micros >= 0.0 && micros < i64::MAX as f64)+ .then(|| ChargedAmount::usd_micros(micros.ceil() as i64));+}++#[async_trait]+impl ChatModel<()> for GatewayChargeModel {+ fn profile(&self) -> Option<&ModelProfile> {+ self.inner.profile()+ }++ fn supports_input(&self, modality: InputModality, mime: &str, source: InputSource) -> bool {+ self.inner.supports_input(modality, mime, source)+ }++ fn cache_identity(&self) -> Option<String> {+ self.inner.cache_identity()+ }++ async fn invoke(+ &self,+ state: &(),+ request: ModelRequest,+ ) -> tinyinference_llm::Result<ModelResponse> {+ let mut response = self.inner.invoke(state, request).await?;+ normalize_charge(&mut response);+ Ok(response)+ }++ async fn stream(+ &self,+ state: &(),+ request: ModelRequest,+ ) -> tinyinference_llm::Result<ModelStream> {+ let stream = self.inner.stream(state, request).await?;+ Ok(stream.map_items(|mut item| {+ if let ModelStreamItem::Completed(response) = &mut item {+ normalize_charge(response);+ }+ item+ }))+ }+}++#[cfg(test)]+#[path = "budget_charge_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/agent/tinyagents/budget_charge_tests.rs b/crates/openhuman-core/src/agent/tinyagents/budget_charge_tests.rsnew file mode 100644index 0000000000..b64d5daf30--- /dev/null+++ b/crates/openhuman-core/src/agent/tinyagents/budget_charge_tests.rs@@ -0,0 +1,81 @@+//! Host charge normalization preserves streaming settlement and unknown usage.++use super::*;+use futures::StreamExt;+use tinyinference_llm::usage::Usage;++struct StreamingFixture;++#[async_trait]+impl ChatModel<()> for StreamingFixture {+ async fn invoke(&self, _: &(), _: ModelRequest) -> tinyinference_llm::Result<ModelResponse> {+ Ok(ModelResponse {+ usage: Some(Usage::new(10, 5)),+ raw: Some(serde_json::json!({"usage": {"buyer_cost_micro": 10}})),+ ..ModelResponse::assistant("done")+ })+ }+}++#[tokio::test]+async fn streaming_gateway_charge_settles_and_releases_the_reservation() {+ use tinyinference_llm::model::budget::{Budget, BudgetedModel, CallBudget, SpendLimits};+ let budget = Budget::new(SpendLimits {+ tokens: None,+ cost_micros: Some(150),+ });+ let model = BudgetedModel::new(+ Arc::new(GatewayChargeModel::new(Arc::new(StreamingFixture))),+ budget.clone(),+ CallBudget {+ input_tokens: 10,+ output_tokens: 5,+ cost_micros: 100,+ },+ );+ for expected_cost in [10, 20] {+ let mut stream = model.stream(&(), ModelRequest::default()).await.unwrap();+ let mut completed = false;+ while let Some(item) = stream.next().await {+ if let ModelStreamItem::Completed(response) = item {+ assert_eq!(response.usage.unwrap().charged_amount.unwrap().micros, 10);+ completed = true;+ }+ }+ assert!(completed);+ assert_eq!(budget.snapshot().spent.cost_micros, expected_cost);+ }+}++#[test]+fn absent_raw_charge_preserves_typed_charge_and_absent_usage_stays_unknown() {+ let mut response = ModelResponse {+ usage: Some(Usage {+ charged_amount: Some(ChargedAmount::usd_micros(12)),+ ..Usage::new(10, 5)+ }),+ raw: Some(serde_json::json!({"usage": {}})),+ ..ModelResponse::assistant("done")+ };+ normalize_charge(&mut response);+ assert_eq!(response.usage.unwrap().charged_amount.unwrap().micros, 12);+ response.usage = None;+ response.raw = Some(serde_json::json!({"usage": {"buyer_cost_micro": 10}}));+ normalize_charge(&mut response);+ assert!(response.usage.is_none());+}++#[test]+fn integer_buyer_charge_does_not_lose_fixed_point_precision() {+ let amount = 9_007_199_254_740_993_i64;+ let mut response = ModelResponse {+ usage: Some(Usage::new(10, 5)),+ raw: Some(serde_json::json!({"usage": {"buyer_cost_micro": amount}})),+ ..ModelResponse::assistant("done")+ };+ normalize_charge(&mut response);+ assert_eq!(+ response.usage.unwrap().charged_amount.unwrap().micros,+ amount+ );+}diff --git a/crates/openhuman-core/src/agent/tinyagents/mod.rs b/crates/openhuman-core/src/agent/tinyagents/mod.rsindex 15dc769f46..d243e95a6d 100644--- a/crates/openhuman-core/src/agent/tinyagents/mod.rs+++ b/crates/openhuman-core/src/agent/tinyagents/mod.rs@@ -50,6 +50,7 @@ pub mod run_mode;// multi-tenancy), so "bring your own summarizer" is the case this seam exists// for rather than an exotic one.pub mod budget;+mod budget_charge;pub mod payload_summarizer;mod policy_denial;pub(crate) mod reaper;diff --git a/crates/openhuman-embed/tests/budget_fanout.rs b/crates/openhuman-embed/tests/budget_fanout.rsindex 95dee74726..2de088ee35 100644--- a/crates/openhuman-embed/tests/budget_fanout.rs+++ b/crates/openhuman-embed/tests/budget_fanout.rs@@ -222,3 +222,71 @@ async fn borrowed_branch_futures_overlap_within_the_declared_bound() {vec![Ok(10), Ok(20), Err("branch failed"), Ok(40), Ok(50), Ok(60)]);}++#[tokio::test]+async fn gateway_buyer_charge_settles_before_the_next_call() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/v1/chat/completions"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "model": "fixture",+ "choices": [{"message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],+ "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15,+ "buyer_cost_micro": 10, "cost": 0}+ })))+ .mount(&server)+ .await;+ let policy = policy(150);+ let client = completer(&server).budget(policy.clone());+ let response = client.complete(request("fixture")).await.unwrap();+ assert_eq!(response.usage.unwrap().cost_usd, Some(0.00001));+ assert_eq!(policy.ledger.snapshot().spent.cost_micros, 10);+ client.complete(request("fixture")).await.unwrap();+ assert_eq!(policy.ledger.snapshot().spent.cost_micros, 20);+ assert_eq!(server.received_requests().await.unwrap().len(), 2);+}++#[tokio::test]+async fn gateway_charge_precedence_and_unknown_cost_keep_budget_conservative() {+ for (charge, expected) in [+ (json!({"buyer_cost_micro": 6.4, "cost": 0}), 7),+ (json!({"buyer_cost_micro": 0, "cost": 1}), 0),+ (json!({"cost": 0.0000064}), 7),+ (json!({"buyer_cost_micro": -1, "cost": 0}), 100),+ (json!({"cost": -1}), 100),+ (json!({"cost": 1e20}), 100),+ (json!({}), 100),+ ] {+ let server = MockServer::start().await;+ let mut usage = json!({"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15});+ usage+ .as_object_mut()+ .unwrap()+ .extend(charge.as_object().unwrap().clone());+ Mock::given(method("POST"))+ .and(path("/v1/chat/completions"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "model": "fixture",+ "choices": [{"message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],+ "usage": usage+ })))+ .mount(&server)+ .await;+ let policy = policy(1_000);+ completer(&server)+ .budget(policy.clone())+ .complete(request("fixture"))+ .await+ .unwrap();+ assert_eq!(+ policy.ledger.snapshot().spent.cost_micros,+ expected,+ "{charge}"+ );+ assert_eq!(+ policy.ledger.snapshot().spent.tokens,+ 15,+ "token accounting must survive {charge}"+ );+ }+}