Skip to content

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

feat(cost): track per-model token usage and cost

Steven Enamakel62302128e49f
diff --git a/crates/openhuman-core/src/agent/cost.rs b/crates/openhuman-core/src/agent/cost.rs
index 24bb95870a..78765676ad 100644
--- a/crates/openhuman-core/src/agent/cost.rs
+++ b/crates/openhuman-core/src/agent/cost.rs
@@ -1,30 +1,24 @@
-//! Per-turn cost accounting for an agent's tool-call loop.
+//! Per-call and per-turn cost accounting for an agent's tool-call loop.
//!
-//! Each provider response carries an optional [`BilledUsage`] block with
-//! `input_tokens`, `output_tokens`, `cached_input_tokens`, and an
-//! authoritative `charged_amount_usd` populated by the OpenHuman
-//! backend. [`TurnCost`] sums those across every provider call inside a
-//! single turn so the harness can:
+//! A call's cost is one of three things, never a guess:
//!
-//! - emit per-iteration cost telemetry via
-//! [`crate::agent::progress::AgentProgress::TurnCostUpdated`];
-//! - feed budget stop hooks (mid-turn USD cap);
-//! - log accurate end-of-turn cost lines.
+//! - **Charged**: the amount the provider actually billed, reported back on
+//! the response (`openhuman.billing.charged_amount_usd` from the managed
+//! backend, `total_cost_usd` from a CLI provider). It may be zero for a
+//! free route; that is still a known cost.
+//! - **Estimated**: no charge was reported, but the model is in the vendor
+//! price catalog ([`crate::platform::cost::catalog`]), so its published
+//! list rates price the token counts. Reported as an estimate.
+//! - **Unknown**: no charge and no catalogued price. Nothing is reported for
+//! it; a turn with any unknown call has an unknown total.
//!
-//! When `charged_amount_usd` is zero (older backend builds, providers
-//! that don't surface billing), we fall back to a simple token-rate
-//! estimate via [`estimate_call_cost_usd`] keyed on the model tier
-//! name. The estimate is a floor — directly-billed cost from the
-//! backend always wins when available.
-//!
-//! The pricing table is intentionally tiny: the managed default model,
-//! with the retired tier slugs (`hint:chat`, …) still resolving to its rate so
-//! older cost records estimate sanely. Every other model — catalog ids the
-//! user pins, BYOK vendor models — is priced from the vendor catalog.
+//! There is deliberately no default rate for an unrecognised model. One used
+//! to exist ($3 / $0.30 / $15 per MTok) and priced a glm-5.3-flash thread at
+//! $4.25 when the provider billed about $0.30.
use crate::inference::provider::BilledUsage;
-/// Per-million-token rates for a single model tier.
+/// Per-million-token rates for a single model.
///
/// All prices are USD per million tokens. `cached_input_per_mtok_usd`
/// applies to the `cached_input_tokens` portion of the usage block (KV
@@ -33,7 +27,7 @@ use crate::inference::provider::BilledUsage;
/// `input_per_mtok_usd`.
#[derive(Debug, Clone, Copy)]
pub(crate) struct ModelPricing {
- /// Model id, e.g. `"openrouter/deepseek/deepseek-v4-flash"`.
+ /// Model id, e.g. `"claude-sonnet-4-6"`.
pub(crate) model: &'static str,
/// Standard prompt rate, USD per million input tokens.
pub(crate) input_per_mtok_usd: f64,
@@ -43,99 +37,125 @@ pub(crate) struct ModelPricing {
pub(crate) output_per_mtok_usd: f64,
}
-/// Conservative fallback when nothing in the table matches. Picked so
-/// budget caps still bite on unknown models rather than reading as $0.
-const FALLBACK_PRICING: ModelPricing = ModelPricing {
- model: "<fallback>",
- input_per_mtok_usd: 3.00,
- cached_input_per_mtok_usd: 0.30,
- output_per_mtok_usd: 15.00,
-};
-
-/// Static price table for the managed default model.
-const PRICING_TABLE: &[ModelPricing] = &[
- // The managed default model — DeepSeek V4 Flash through the OpenRouter
- // passthrough. Estimate only; the backend's echoed `charged_amount_usd` is
- // authoritative when present. Any other catalog model the user pins is
- // priced from the vendor catalog (`platform::cost::catalog`) below.
- ModelPricing {
- model: crate::config::MODEL_MANAGED_DEFAULT,
- input_per_mtok_usd: 0.0886,
- cached_input_per_mtok_usd: 0.0886,
- output_per_mtok_usd: 0.1772,
- },
-];
-
-/// Legacy tier slugs from older transcripts and configs, mapped onto the
-/// managed default's rate so an old cost record still estimates sanely.
-const LEGACY_TIER_ROWS: &[&str] = &crate::config::LEGACY_TIER_MODELS;
-
-/// Look up pricing for a model name, falling back to [`FALLBACK_PRICING`].
-///
-/// Resolution order:
-/// 1. Exact match on the managed default model (or a retired tier slug /
-/// `hint:*` alias, which ran on it).
-/// 2. The concrete-vendor-model pricing catalog
-/// ([`crate::platform::cost::catalog`]) — accurate per-model rates for
-/// `claude-*`, `gpt-*`, `gemini-*`, `deepseek-*`, `kimi-*`, `qwen-*`,
-/// `mistral-*`, including OpenRouter-style `vendor/model` ids.
-/// 3. [`FALLBACK_PRICING`].
-pub(crate) fn lookup_pricing(model: &str) -> ModelPricing {
- let trimmed = model.trim();
- if let Some(row) = PRICING_TABLE.iter().find(|row| row.model == trimmed) {
- return *row;
+/// Published list rates for `model`, or `None` when the vendor catalog does
+/// not know it.
+pub(crate) fn lookup_pricing(model: &str) -> Option<ModelPricing> {
+ let price = crate::platform::cost::catalog::lookup(model.trim())?;
+ Some(ModelPricing {
+ model: price.model_id,
+ input_per_mtok_usd: price.input_per_mtok_usd,
+ cached_input_per_mtok_usd: price.cached_input_per_mtok_usd,
+ output_per_mtok_usd: price.output_per_mtok_usd,
+ })
+}
+
+/// List-price estimate of one call, or `None` when the model is not
+/// catalogued. Used only when the provider reported no charge.
+pub fn estimate_call_cost_usd(model: &str, usage: &BilledUsage) -> Option<f64> {
+ let pricing = lookup_pricing(model)?;
+ let cached = usage.cached_input_tokens().min(usage.input_tokens);
+ let standard_input = usage.input_tokens.saturating_sub(cached);
+ let m = 1_000_000.0_f64;
+ Some(
+ (standard_input as f64) / m * pricing.input_per_mtok_usd
+ + (cached as f64) / m * pricing.cached_input_per_mtok_usd
+ + (usage.output_tokens as f64) / m * pricing.output_per_mtok_usd,
+ )
+}
+
+/// Where a cost figure came from. Ordered from most to least certain, so the
+/// cost of several calls takes the least certain of their sources.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
+pub enum CostSource {
+ /// Every call reported the amount the provider billed.
+ #[default]
+ Charged,
+ /// At least one call was priced from the catalog's list rates.
+ Estimated,
+ /// At least one call had neither a charge nor a catalogued price, so the
+ /// total is not known.
+ Unknown,
+}
+
+/// The cost of one provider call.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub enum CallCost {
+ /// Billed by the provider (may be zero).
+ Charged(f64),
+ /// Catalog list-price estimate.
+ Estimated(f64),
+ /// Neither available.
+ Unknown,
+}
+
+impl CallCost {
+ /// The USD figure, or `None` when unknown.
+ pub fn usd(self) -> Option<f64> {
+ match self {
+ Self::Charged(usd) | Self::Estimated(usd) => Some(usd),
+ Self::Unknown => None,
+ }
}
- if trimmed.starts_with("hint:") || LEGACY_TIER_ROWS.contains(&trimmed) {
- return PRICING_TABLE[0];
+
+ /// The source this cost contributes to a total.
+ pub fn source(self) -> CostSource {
+ match self {
+ Self::Charged(_) => CostSource::Charged,
+ Self::Estimated(_) => CostSource::Estimated,
+ Self::Unknown => CostSource::Unknown,
+ }
+ }
+}
+
+/// The cost of one call: the provider's charge when it reported one, else
+/// the catalog estimate, else unknown.
+pub fn call_cost(model: &str, usage: &BilledUsage) -> CallCost {
+ if usage.charge_reported && !usage.cost_is_estimate {
+ return CallCost::Charged(usage.charged_amount_usd);
}
- if let Some(price) = crate::platform::cost::catalog::lookup(model) {
- return ModelPricing {
- model: price.model_id,
- input_per_mtok_usd: price.input_per_mtok_usd,
- cached_input_per_mtok_usd: price.cached_input_per_mtok_usd,
- output_per_mtok_usd: price.output_per_mtok_usd,
- };
+ match estimate_call_cost_usd(model, usage) {
+ Some(usd) => CallCost::Estimated(usd),
+ None => CallCost::Unknown,
}
- FALLBACK_PRICING
}
-/// Estimate the USD cost of a single provider call from its token
-/// usage. Used as a fallback when `charged_amount_usd` is missing.
-pub fn estimate_call_cost_usd(model: &str, usage: &BilledUsage) -> f64 {
- let pricing = lookup_pricing(model);
- let cached = usage.cached_input_tokens();
- let standard_input = usage.input_tokens.saturating_sub(cached);
- let m = 1_000_000.0_f64;
- (standard_input as f64) / m * pricing.input_per_mtok_usd
- + (cached as f64) / m * pricing.cached_input_per_mtok_usd
- + (usage.output_tokens as f64) / m * pricing.output_per_mtok_usd
+/// A sum of call costs that remembers how certain it is.
+#[derive(Debug, Clone, Copy, PartialEq, Default)]
+pub struct CostTally {
+ /// Sum of the known call costs. Meaningless on its own once `source` is
+ /// [`CostSource::Unknown`]; read it through [`CostTally::usd`].
+ pub known_usd: f64,
+ /// The least certain source among the calls added.
+ pub source: CostSource,
}
-/// Pick the most authoritative USD figure for a single provider call.
-///
-/// Backend-reported `charged_amount_usd` wins whenever it's > 0;
-/// otherwise we fall back to [`estimate_call_cost_usd`].
-pub fn call_cost_usd(model: &str, usage: &BilledUsage) -> f64 {
- if usage.charged_amount_usd > 0.0 {
- usage.charged_amount_usd
- } else {
- estimate_call_cost_usd(model, usage)
+impl CostTally {
+ /// Fold one call in.
+ pub fn add(&mut self, cost: CallCost) {
+ self.known_usd += cost.usd().unwrap_or(0.0);
+ self.source = self.source.max(cost.source());
+ }
+
+ /// Fold another tally in (a sub-step's or a child's).
+ pub fn merge(&mut self, other: CostTally) {
+ self.known_usd += other.known_usd;
+ self.source = self.source.max(other.source);
+ }
+
+ /// The total, or `None` when any call's cost was unknown.
+ pub fn usd(&self) -> Option<f64> {
+ (self.source != CostSource::Unknown).then_some(self.known_usd)
}
}
/// Running cost / token tally across every provider call inside a
/// single turn of the tool-call loop.
-///
-/// `charged_usd` is the sum of authoritative `charged_amount_usd`
-/// values; `estimated_usd` adds the fallback estimate for any call that
-/// lacked one. `total_usd()` returns whichever has more signal.
#[derive(Debug, Clone, Default)]
pub struct TurnCost {
pub input_tokens: u64,
pub output_tokens: u64,
pub cached_input_tokens: u64,
- pub charged_usd: f64,
- pub estimated_usd: f64,
+ pub cost: CostTally,
pub call_count: u32,
}
@@ -152,18 +172,13 @@ impl TurnCost {
self.cached_input_tokens = self
.cached_input_tokens
.saturating_add(usage.cached_input_tokens());
- if usage.charged_amount_usd > 0.0 {
- self.charged_usd += usage.charged_amount_usd;
- } else {
- self.estimated_usd += estimate_call_cost_usd(model, usage);
- }
+ self.cost.add(call_cost(model, usage));
self.call_count = self.call_count.saturating_add(1);
}
- /// Best-available USD figure: authoritative charged amount plus
- /// estimated cost for any calls that didn't carry one.
- pub fn total_usd(&self) -> f64 {
- self.charged_usd + self.estimated_usd
+ /// The turn's cost so far, or `None` when any call's cost is unknown.
+ pub fn total_usd(&self) -> Option<f64> {
+ self.cost.usd()
}
}