Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 123 additions & 0 deletions crates/axe-core/src/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,11 @@ pub struct Provider {
pub claude_models: Option<ClaudeModels>,
/// Where people get a key.
pub console: &'static str,
/// The provider's public price of one model: this URL with the model
/// appended, answered without a key ([`model_price`]). For a model the
/// run's tool does not price and axe's table has no row for
/// (`usage::PRICES`): Claude Code on OpenRouter.
pub model_price: Option<&'static str>,
}

pub const PROVIDERS: &[Provider] = &[
Expand Down Expand Up @@ -101,6 +106,7 @@ pub const PROVIDERS: &[Provider] = &[
subagent: "deepseek-flash",
}),
console: "platform.deepseek.com",
model_price: None,
},
// https://openrouter.ai/docs/api-reference/api-keys/get-current-key
// (GET /api/v1/key, bearer; 401 on a wrong key; `/api/v1/models` is a
Expand Down Expand Up @@ -129,6 +135,9 @@ pub const PROVIDERS: &[Provider] = &[
subagent: "~anthropic/claude-opus-latest[1m]",
}),
console: "openrouter.ai/keys",
// https://openrouter.ai/docs/guides/overview/models: `data.pricing`
// in USD per token as strings, "0" free; public (no key, 20261202).
model_price: Some("https://openrouter.ai/api/v1/model/"),
},
// https://developers.openai.com/api/reference/resources/models/methods/list
// (GET /v1/models, bearer; `data[]` of `{id, object, created,
Expand All @@ -153,6 +162,7 @@ pub const PROVIDERS: &[Provider] = &[
anthropic_url: None,
claude_models: None,
console: "platform.openai.com/api-keys",
model_price: None,
},
// https://platform.claude.com/docs/en/api/models-list (GET /v1/models,
// `limit` 1 to 1000, newest first; `data[]` of `{id, display_name,
Expand Down Expand Up @@ -180,6 +190,7 @@ pub const PROVIDERS: &[Provider] = &[
anthropic_url: None,
claude_models: None,
console: "platform.claude.com/settings/keys",
model_price: None,
},
// https://aistudio.google.com/api-reference/models/list-models (GET
// /v1beta/models, `pageSize` up to 1000; `models[]` of `{name:
Expand All @@ -205,6 +216,7 @@ pub const PROVIDERS: &[Provider] = &[
anthropic_url: None,
claude_models: None,
console: "aistudio.google.com/apikey",
model_price: None,
},
// Any OpenAI-compatible server (`Other…`): the owner gives its base URL
// with the key. Its key check is OpenAI's list models call on that URL
Expand All @@ -227,6 +239,7 @@ pub const PROVIDERS: &[Provider] = &[
anthropic_url: None,
claude_models: None,
console: "",
model_price: None,
},
];

Expand Down Expand Up @@ -257,6 +270,7 @@ const TEST_PROVIDERS: &[Provider] = &[
anthropic_url: None,
claude_models: None,
console: "acme.test",
model_price: None,
},
Provider {
id: "acme2",
Expand All @@ -274,6 +288,7 @@ const TEST_PROVIDERS: &[Provider] = &[
anthropic_url: None,
claude_models: None,
console: "acme2.test",
model_price: None,
},
];

Expand Down Expand Up @@ -477,6 +492,73 @@ pub fn check_key(call: &Call, key: &str, timeout: Duration) -> KeyCheck {
}
}

/// How long a price lookup may take: it runs as a run's usage is read.
pub const MODEL_PRICE_TIMEOUT: Duration = Duration::from_secs(5);

/// Provider `p`'s public price of `model` now ([`Provider::model_price`]),
/// its URL's scheme and host on `base` when set (a mock). `Ok(None)`: the
/// row has no price lookup, or the answer holds no usable price.
pub fn model_price(
p: &Provider,
model: &str,
base: Option<&str>,
) -> Result<Option<crate::usage::Price>, String> {
let Some(prefix) = p.model_price else {
return Ok(None);
};
let mut url = format!("{prefix}{model}");
if let Some(b) = base {
url = on_base(b, &url);
}
let agent = ureq::AgentBuilder::new()
.timeout(MODEL_PRICE_TIMEOUT)
.redirects(0)
.build();
let body: serde_json::Value = match agent.get(&url).set("Accept", "application/json").call() {
Ok(r) => r.into_json().map_err(|e| format!("{url}: {e}"))?,
Err(ureq::Error::Status(404, _)) => return Ok(None),
Err(e) => return Err(format!("{url}: {e}")),
};
Ok(crate::usage::catalog_price(&body["data"]["pricing"]))
}

/// A node's provider price lookups ([`model_price`]), kept an hour (ten
/// minutes when the lookup failed), so a busy node asks once per model.
#[derive(Default)]
pub struct ModelPrices {
base: Option<String>,
seen: std::collections::HashMap<String, (std::time::Instant, Option<crate::usage::Price>)>,
}

impl ModelPrices {
/// Lookups go to `base` (`AXE_KEY_CHECK_BASE`, a provider mock) when set.
pub fn new(base: Option<String>) -> ModelPrices {
ModelPrices {
base: base.map(|b| b.trim_end_matches('/').to_string()),
..Default::default()
}
}

/// `provider/model`'s price now, from its provider's lookup.
pub fn price(&mut self, key: &str) -> Option<crate::usage::Price> {
let (id, model) = key.split_once('/')?;
let p = get(id).filter(|p| p.model_price.is_some())?;
if let Some((at, price)) = self.seen.get(key) {
let ttl = if price.is_some() { 3600 } else { 600 };
if at.elapsed() < Duration::from_secs(ttl) {
return *price;
}
}
let price = model_price(p, model, self.base.as_deref()).unwrap_or_else(|e| {
eprintln!("axe node: no {} price for {model}: {e}", p.label);
None
});
self.seen
.insert(key.to_string(), (std::time::Instant::now(), price));
price
}
}

#[cfg(test)]
pub(crate) mod tests {
use super::*;
Expand Down Expand Up @@ -533,6 +615,47 @@ pub(crate) mod tests {
(base, rx)
}

/// The price lookup asks OpenRouter's public model URL without a key,
/// once per model an hour; a row without one is never asked.
#[test]
fn a_model_price_is_looked_up_once_without_a_key() {
// The mock answers requests carrying the lookup's Accept header.
let (base, rx) = mock_with("application/json", |line| {
let body = match line.contains("/api/v1/model/deepseek/deepseek-v4.1-flash ") {
true => {
r#"{"data":{"id":"deepseek/deepseek-v4.1-flash","pricing":{"prompt":"0.000000051","completion":"0.000000567","input_cache_read":"0.000000018"}}}"#
}
false => r#"{"error":{"code":404}}"#,
};
(
if body.contains("error") { 404 } else { 200 },
body.to_string(),
)
});
let mut prices = ModelPrices::new(Some(base));
let p = prices
.price("openrouter/deepseek/deepseek-v4.1-flash")
.unwrap();
assert!((p.input - 0.051).abs() < 1e-9 && (p.output - 0.567).abs() < 1e-9);
assert!((p.cached - 0.018).abs() < 1e-9 && (p.cache_write - 0.051).abs() < 1e-9);
let head = rx.recv().unwrap();
assert!(
head.starts_with("GET /api/v1/model/deepseek/deepseek-v4.1-flash HTTP"),
"{head}"
);
assert!(!head.to_lowercase().contains("authorization"), "{head}");
// Kept: no second request.
assert_eq!(
prices.price("openrouter/deepseek/deepseek-v4.1-flash"),
Some(p)
);
assert!(prices.price("openrouter/acme/none").is_none());
assert!(rx.recv().unwrap().contains("/acme/none"));
assert!(prices.price("deepseek/deepseek-flash").is_none());
assert!(prices.price("openrouter/acme/none").is_none());
assert!(rx.recv_timeout(Duration::from_millis(200)).is_err());
}

#[test]
fn every_provider_row_is_complete() {
let mut ids = std::collections::BTreeSet::new();
Expand Down
19 changes: 15 additions & 4 deletions crates/axe-core/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,8 +197,9 @@ impl Default for Health {
}

/// Sends provider key checks to `http://host:port` + each check's path
/// instead of the provider ([`Registry::with_key_check_base`]): a node in a
/// test or scratch run against a local provider mock.
/// instead of the provider ([`Registry::with_key_check_base`]), and its
/// model price lookups too (`provider::ModelPrices`): a node in a test or
/// scratch run against a local provider mock.
pub const KEY_CHECK_BASE_ENV: &str = "AXE_KEY_CHECK_BASE";

/// The node's registry as its main loop last saw it (`managed`, runtimes),
Expand Down Expand Up @@ -348,8 +349,9 @@ fn base_url_file(p: &crate::provider::Provider) -> &'static str {
/// Anthropic-Messages endpoint with `key` as a bearer token, and those it
/// must not see: an Anthropic key would be sent along to the provider
/// (`x-api-key`), and a setup token would be read ahead of the login dir.
/// `url` is `Other…`'s base URL; it has no tier models, so a rule names
/// its model ([`tier_env`]).
/// A run no rule names a model for runs the row's `default_model`
/// (`ANTHROPIC_MODEL`). `url` is `Other…`'s base URL; it has no default or
/// tier models, so a rule names its model ([`tier_env`]).
fn anthropic_env(p: &crate::provider::Provider, key: String, url: Option<String>) -> LoginEnv {
let mut set = vec![
(
Expand All @@ -363,6 +365,12 @@ fn anthropic_env(p: &crate::provider::Provider, key: String, url: Option<String>
("ANTHROPIC_API_KEY", String::new()),
("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "1".into()),
];
// The row's default model when no rule names one (`--model` wins over
// it): Claude Code's own default is its Opus alias, which on OpenRouter
// is the row's Opus tier.
if !p.default_model.is_empty() {
set.push(("ANTHROPIC_MODEL", p.default_model.to_string()));
}
if let Some(m) = &p.claude_models {
set.extend([
("ANTHROPIC_DEFAULT_OPUS_MODEL", m.opus.to_string()),
Expand Down Expand Up @@ -2617,6 +2625,8 @@ exit 2
assert_eq!(get("ANTHROPIC_DEFAULT_HAIKU_MODEL"), Some("deepseek-flash"));
assert_eq!(get("CLAUDE_CODE_SUBAGENT_MODEL"), Some("deepseek-flash"));
assert_eq!(get("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"), Some("1"));
// No rule naming a model: the row's default, not Claude's Opus.
assert_eq!(get("ANTHROPIC_MODEL"), Some("deepseek-flash"));
assert_eq!(get("DEEPSEEK_API_KEY"), None);
assert_eq!(get("CLAUDE_CODE_OAUTH_TOKEN"), None);
assert!(remove.contains(&"CLAUDE_CODE_OAUTH_TOKEN"), "{remove:?}");
Expand All @@ -2628,6 +2638,7 @@ exit 2
let (set, _) = rt.env();
assert!(set.contains(&("ANTHROPIC_BASE_URL", "https://openrouter.ai/api".into())));
assert!(set.contains(&("ANTHROPIC_AUTH_TOKEN", or.clone())));
assert!(set.contains(&("ANTHROPIC_MODEL", "~anthropic/claude-sonnet-latest".into())));
const KEY: &str = "sk-ant-api03-dummy1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
rt.login(&cfg, "api_key", None, KEY).unwrap();
assert!(!login.join("OPENROUTER_API_KEY").exists());
Expand Down
49 changes: 49 additions & 0 deletions crates/axe-core/src/usage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -639,6 +639,28 @@ pub fn openai_price(model: &str) -> Option<Price> {
price_at(&format!("openai/{model}"), 0)
}

/// A provider catalog's price (OpenRouter `data.pricing`: USD per token as
/// strings), per million tokens: `prompt` and `completion`, cache reads and
/// writes at `input_cache_read` and `input_cache_write` (the 5-minute write
/// Claude Code asks for), else the prompt price. `None` without a prompt
/// and completion price, or with a negative one. Conditional `overrides`
/// (long prompts, time windows) are per request and not applied: the
/// default-conditions price, an estimate like Claude's own `costUSD`.
pub fn catalog_price(pricing: &Value) -> Option<Price> {
let per_m = |k: &str| -> Option<f64> {
let v = &pricing[k];
let n = v.as_str().map_or(v.as_f64(), |s| s.parse().ok())?;
(n >= 0.0).then_some(n * 1e6)
};
let input = per_m("prompt")?;
Some(Price {
input,
cached: per_m("input_cache_read").unwrap_or(input),
cache_write: per_m("input_cache_write").unwrap_or(input),
output: per_m("completion")?,
})
}

/// Whether the tool's own cost for a model stands: Claude Code's `costUSD`
/// only when it priced the model from its list (`costBasis: "list"`); a log
/// that names no basis (every other tool, older Claude Code) is taken as is.
Expand All @@ -660,6 +682,33 @@ impl Parsed {
self
}

/// Each `provider/model` of a run on a provider's login
/// ([`Parsed::on_provider`]) that its tool gave no trusted cost and
/// [`PRICES`] has no row for, priced at `price(model)`: its provider's
/// own price now (`provider::ModelPrices`, Claude Code on OpenRouter).
/// Its cost is then known, not $0. Runs that report their own cost
/// (OpenCode) and models the table prices keep theirs.
pub fn priced_by(
mut self,
provider: Option<&str>,
mut price: impl FnMut(&str) -> Option<Price>,
) -> Parsed {
let Some(provider) = provider else {
return self;
};
let prefix = format!("{provider}/");
for (model, t) in self.models.iter_mut() {
if !model.starts_with(&prefix) || t.cost >= COST_EPSILON || price_at(model, 0).is_some()
{
continue;
}
if let Some(p) = price(model) {
t.cost = p.cost(t);
}
}
self
}

/// The usage of a run on provider `provider`'s login (Claude Code on
/// DeepSeek): each model becomes `provider/model`, without Claude Code's
/// `[1m]` suffix, so the server prices it from [`PRICES`] when its tool
Expand Down
27 changes: 25 additions & 2 deletions crates/axe-node/src/dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,22 @@ pub(crate) fn run_model(rt: &runtime::Runtime, with: Option<&Use>) -> Option<Str
}

impl Dispatcher {
/// A run's usage on runtime `agent` as stored: its models as
/// `provider/model` on the provider that bills it ([`Self::priced_provider`]),
/// and a model nothing priced at that provider's own price
/// ([`crate::usage::Parsed::priced_by`]).
pub(crate) fn priced(
&mut self,
usage: crate::usage::Parsed,
agent: &str,
provider: Option<&'static str>,
) -> crate::usage::Parsed {
let provider = self.priced_provider(agent, provider);
usage
.on_provider(provider)
.priced_by(provider, |m| self.prices.price(m))
}

/// The provider that bills a run on runtime `agent`: its provider login
/// (`provider`, on a runtime whose logins accumulate), else the one
/// provider key the runtime holds (Claude Code on DeepSeek). `None` for
Expand Down Expand Up @@ -179,6 +195,8 @@ pub struct Dispatcher {
store: Store,
runs: Vec<Run>,
server_url: Option<String>,
/// Provider prices of models axe's table does not hold (OpenRouter).
prices: crate::provider::ModelPrices,
/// Resource admission; `None` when `[resources]` is not configured.
gate: Option<Gate>,
admission: admission::Handle,
Expand Down Expand Up @@ -461,6 +479,11 @@ impl Dispatcher {
deferred: Vec::new(),
pre_checks: Vec::new(),
profiles_unsupported: false,
prices: crate::provider::ModelPrices::new(
std::env::var(crate::runtime::KEY_CHECK_BASE_ENV)
.ok()
.filter(|b| !b.is_empty()),
),
reported: None,
hold_path: admission::hold_path(),
hold_logged: None,
Expand Down Expand Up @@ -1882,8 +1905,8 @@ impl Dispatcher {
&run.log_path,
&crate::usage::transcript_logins(&self.runtimes.runtimes),
)
.with_model(run.model.as_deref())
.on_provider(self.priced_provider(&run.pick.agent, run.provider));
.with_model(run.model.as_deref());
let usage = self.priced(usage, &run.pick.agent, run.provider);
// Only a plain exit is classified (a zero one only for a CLI that
// exits 0 on a failed model call); stops, drains and aborts keep their path.
let failure = block_note
Expand Down
4 changes: 2 additions & 2 deletions crates/axe-node/src/dispatch/bots.rs
Original file line number Diff line number Diff line change
Expand Up @@ -630,8 +630,8 @@ impl Dispatcher {
&run.log_path,
&crate::usage::transcript_logins(&self.runtimes.runtimes),
)
.with_model(run.model.as_deref())
.on_provider(self.priced_provider(&run.agent, run.provider));
.with_model(run.model.as_deref());
let usage = self.priced(usage, &run.agent, run.provider);
// A failed exit caused by quota, credit, login or provider is not the
// bot's failure (Pi exits 0 after a failed model call).
let outage = (reason == "exit")
Expand Down
Loading
Loading