fix(costs): estimate through canonical provider aliases (#11916)

This commit is contained in:
SynthLuvr
2026-09-28 04:33:45 +00:00
committed by GitHub
parent 91e92ea25c
commit 98c626d74b
6 changed files with 124 additions and 60 deletions
@@ -49,6 +49,7 @@ pub fn map_provider_name(provider: &str) -> &str {
"aws_bedrock" => "amazon-bedrock",
"gcp_vertex_ai" => "google-vertex",
"gemini_oauth" => "google",
"chatgpt_codex" => "openai",
"databricks_v2" => "databricks",
"zhipu" => "zhipuai",
"together" => "togetherai",
@@ -134,12 +135,13 @@ pub fn map_to_canonical_model(
// so models that DO infer (e.g. databricks-claude-* -> anthropic/*) keep
// resolving to the richer first-party catalog entry.
if is_meta_provider(provider) {
if let Some(canonical) = registry.get(registry_provider, model) {
return Some(canonical.id.clone());
}
let normalized_model = strip_version_suffix(model);
if let Some(canonical) = registry.get(registry_provider, &normalized_model) {
return Some(canonical.id.clone());
let lowercased_model = normalized_model.to_ascii_lowercase();
// Registry keys are lowercase; deployment names may carry mixed case ("Phi-4").
for key in [model, normalized_model.as_str(), lowercased_model.as_str()] {
if let Some(canonical) = registry.get(registry_provider, key) {
return Some(canonical.id.clone());
}
}
}
@@ -347,6 +349,10 @@ mod tests {
map_to_canonical_model("openai", "gpt-4-turbo-2024-04-09", r),
Some("openai/gpt-4-turbo".to_string())
);
assert_eq!(
map_to_canonical_model("chatgpt_codex", "gpt-5.6-sol", r),
Some("openai/gpt-5.6-sol".to_string())
);
assert_eq!(
map_to_canonical_model("opencode_go", "kimi-k2.6", r),
Some("opencode-go/kimi-k2.6".to_string())
@@ -435,6 +441,10 @@ mod tests {
map_to_canonical_model("azure_foundry", "gpt-4o", r),
Some("openai/gpt-4o".to_string())
);
assert_eq!(
map_to_canonical_model("azure_foundry", "Phi-4", r),
Some("azure/phi-4".to_string())
);
// === OpenAI O-series ===
assert_eq!(
+29 -5
View File
@@ -4,6 +4,7 @@ use std::time::{Duration, Instant};
use anyhow::Result;
use async_trait::async_trait;
use futures::StreamExt;
use rmcp::model::Tool;
use crate::anthropic::{AnthropicProvider, AnthropicProviderBuilder, ANTHROPIC_API_VERSION};
@@ -438,6 +439,22 @@ fn configured_client(
Ok(client)
}
/// Usage chunks carry the model name the inference surface echoes back — the
/// deployment alias, or a value the endpoint invented — but cost estimation
/// needs the underlying model the alias resolves to, so re-tag each chunk.
fn retag_usage_model(stream: MessageStream, model: &str) -> MessageStream {
let model = model.to_string();
Box::pin(stream.map(move |item| {
item.map(|(message, usage)| {
let usage = usage.map(|mut usage| {
usage.model.clone_from(&model);
usage
});
(message, usage)
})
}))
}
#[async_trait]
impl Provider for AzureFoundryProvider {
fn get_name(&self) -> &str {
@@ -571,7 +588,7 @@ impl Provider for AzureFoundryProvider {
capability_config.model_name = capability_model.to_string();
let capability_config =
capability_config.with_canonical_limits(AZURE_FOUNDRY_PROVIDER_NAME);
match route {
let stream = match route {
InferenceRoute::ProjectResponses => {
self.responses
.as_ref()
@@ -605,7 +622,8 @@ impl Provider for AzureFoundryProvider {
)
.await
}
}
}?;
Ok(retag_usage_model(stream, underlying_model))
}
}
@@ -1112,10 +1130,11 @@ mod tests {
let provider = project_provider(&server);
let config = ModelConfig::new("production-chat").with_temperature(Some(0.7));
provider
let (_, usage) = provider
.complete(&config, "system", &[], &[])
.await
.unwrap();
assert_eq!(usage.model, "gpt-5");
let requests = server.received_requests().await.unwrap();
let payload: serde_json::Value = requests
.iter()
@@ -1385,11 +1404,16 @@ mod tests {
.await;
let provider = project_provider(&server);
for deployment in ["openai-prod", "claude-prod", "partner-prod"] {
provider
for (deployment, underlying_model) in [
("openai-prod", "gpt-5"),
("claude-prod", "claude-sonnet-4-6"),
("partner-prod", "Mistral-large"),
] {
let (_, usage) = provider
.complete(&ModelConfig::new(deployment), "system", &[], &[])
.await
.unwrap();
assert_eq!(usage.model, underlying_model);
}
}
}
+3 -19
View File
@@ -19,11 +19,12 @@ use crate::conversation::{fix_conversation, merge_consecutive_messages_for_reque
#[cfg(test)]
use crate::providers::base::stream_from_single_message;
use crate::providers::base::{MessageStream, Provider};
use crate::providers::canonical_cost::resolve_usage_cost;
use crate::providers::toolshim::{
augment_message_with_selected_tool_interpreter, convert_tool_messages_to_text,
modify_system_prompt_for_tool_json, sanitize_residual_markers,
};
use goose_providers::conversation::token_usage::{CostSource, ProviderStats, ProviderUsage, Usage};
use goose_providers::conversation::token_usage::{ProviderStats, ProviderUsage, Usage};
use goose_providers::model::ModelConfig;
use rmcp::model::{ErrorData, Tool};
use tracing::warn;
@@ -750,8 +751,7 @@ impl Agent {
let manager = self.config.session_manager.clone();
let session = manager.get_session(session_id, false).await?;
let (chunk_cost, cost_source) =
self.resolve_chunk_cost(usage, session.provider_name.as_deref());
let (chunk_cost, cost_source) = resolve_usage_cost(session.provider_name.as_deref(), usage);
let mut enriched = usage.clone();
enriched.cost = chunk_cost;
@@ -776,22 +776,6 @@ impl Agent {
Ok(enriched)
}
fn resolve_chunk_cost(
&self,
usage: &ProviderUsage,
provider_name: Option<&str>,
) -> (Option<f64>, Option<CostSource>) {
if let Some(cost) = usage.cost {
return (Some(cost), Some(CostSource::ProviderReported));
}
match provider_name.and_then(|pn| {
crate::providers::canonical_cost::estimate_model_cost(pn, &usage.model, &usage.usage)
}) {
Some(cost) => (Some(cost), Some(CostSource::Estimated)),
None => (None, None),
}
}
}
fn user_visible_provider_content(content: &MessageContent) -> Option<MessageContent> {
+3 -15
View File
@@ -1,9 +1,10 @@
use anyhow::Result;
use goose_providers::conversation::token_usage::{CostSource, ProviderUsage, Usage as TokenUsage};
use goose_providers::conversation::token_usage::{ProviderUsage, Usage as TokenUsage};
use crate::agents::state_machine::{ConversationEffect, GooseEffect};
use crate::conversation::message::MessageUsage;
use crate::conversation::Conversation;
use crate::providers::canonical_cost::resolve_usage_cost;
use crate::session::{Session, SessionManager};
fn attach_to_last_assistant(effects: &mut [GooseEffect], usage: &ProviderUsage) {
@@ -29,20 +30,7 @@ pub(super) fn enrich(session: &Session, effects: &mut [GooseEffect]) {
} => (usage.clone(), true),
_ => continue,
};
let (cost, cost_source) = if let Some(cost) = usage.cost {
(Some(cost), Some(CostSource::ProviderReported))
} else {
match session.provider_name.as_deref().and_then(|provider| {
crate::providers::canonical_cost::estimate_model_cost(
provider,
&usage.model,
&usage.usage,
)
}) {
Some(cost) => (Some(cost), Some(CostSource::Estimated)),
None => (None, None),
}
};
let (cost, cost_source) = resolve_usage_cost(session.provider_name.as_deref(), &usage);
let mut enriched = usage.clone();
enriched.cost = cost;
+73 -15
View File
@@ -27,7 +27,7 @@ use crate::config::declarative_providers::{
};
use crate::providers::base::ModelInfo;
use goose_providers::canonical::{maybe_get_canonical_model, Pricing};
use goose_providers::conversation::token_usage::Usage;
use goose_providers::conversation::token_usage::{CostSource, ProviderUsage, Usage};
use std::sync::OnceLock;
use tracing::warn;
@@ -38,6 +38,23 @@ pub fn estimate_model_cost(provider: &str, model: &str, usage: &Usage) -> Option
resolve_pricing(provider, model).and_then(|pricing| pricing.estimate_cost(usage))
}
/// Resolve the cost of a provider-reported usage chunk: the provider's own
/// figure when present, otherwise a public-price estimate for the model, or
/// nothing when the model cannot be priced. Both agent loops call this so
/// estimated and provider-reported costs behave identically on either path.
pub(crate) fn resolve_usage_cost(
provider: Option<&str>,
usage: &ProviderUsage,
) -> (Option<f64>, Option<CostSource>) {
if let Some(cost) = usage.cost {
return (Some(cost), Some(CostSource::ProviderReported));
}
match provider.and_then(|provider| estimate_model_cost(provider, &usage.model, &usage.usage)) {
Some(cost) => (Some(cost), Some(CostSource::Estimated)),
None => (None, None),
}
}
/// Resolve the pricing for a provider/model honoring the precedence described
/// in this module's documentation.
pub(crate) fn resolve_pricing(provider: &str, model: &str) -> Option<Pricing> {
@@ -190,23 +207,64 @@ mod tests {
}
}
/// Both agent loops price a chunk through `estimate_model_cost` and tag the result
/// `CostSource::Estimated` when it returns `Some` — `reply_parts::resolve_chunk_cost` for
/// the legacy path, `state_machine::usage::enrich` for the new one. Pinning the shared
/// helper covers the behaviour both paths inherit.
#[test]
fn azure_foundry_estimates_from_the_azure_catalog_rate() {
/// Prices 1M input + 1M output tokens, so `expected` reads as the model's
/// input-plus-output rate per million tokens.
fn assert_cost(provider: &str, model: &str, expected: f64) {
let used = usage(Some(1_000_000), Some(1_000_000), None);
let actual = estimate_model_cost(provider, model, &used)
.unwrap_or_else(|| panic!("{provider}/{model} should have public pricing"));
assert!((actual - expected).abs() < 1e-9, "got {actual}");
}
let gpt5 = estimate_model_cost("azure_foundry", "gpt-5", &used)
.expect("gpt-5 prices through the Azure catalog");
assert!(gpt5 > 0.0);
#[test]
fn provider_reported_cost_takes_precedence_over_public_estimate() {
let usage = ProviderUsage::new(
"gpt-5.6-sol".to_string(),
usage(Some(1_000_000), Some(1_000_000), None),
)
.with_cost(7.0, CostSource::ProviderReported);
// Priced from azure/llama-3.3-70b-instruct ($0.71/M in and out), not from the
// meta-llama publisher row that lists the open weights at 0.0/0.0.
let llama = estimate_model_cost("azure_foundry", "llama-3.3-70b-instruct", &used)
.expect("llama-3.3-70b-instruct prices through the Azure catalog");
assert!((llama - 1.42).abs() < 1e-9, "got {llama}");
assert_eq!(
resolve_usage_cost(Some("chatgpt_codex"), &usage),
(Some(7.0), Some(CostSource::ProviderReported))
);
}
#[test]
fn chatgpt_codex_uses_openai_public_rates() {
assert_cost("chatgpt_codex", "gpt-5.6-sol", 24.0);
let codex = resolve_pricing("chatgpt_codex", "gpt-5.6-sol").unwrap();
let openai = resolve_pricing("openai", "gpt-5.6-sol").unwrap();
assert_eq!(codex.input, openai.input);
assert_eq!(codex.output, openai.output);
assert_eq!(codex.cache_read, openai.cache_read);
assert_eq!(codex.cache_write, openai.cache_write);
}
#[test]
fn azure_foundry_estimates_representative_publisher_rates() {
assert_cost("azure_foundry", "gpt-5", 11.25);
assert_cost("azure_foundry", "claude-sonnet-4-6", 18.0);
assert_cost("azure_foundry", "deepseek-v3.2", 2.26);
assert_cost("azure_foundry", "mistral-large", 2.0);
}
#[test]
fn azure_foundry_uses_host_rates_for_azure_and_open_weight_models() {
assert_cost("azure_foundry", "Phi-4", 0.625);
// The upstream Meta row describes free weights; Azure's host row prices inference.
assert_cost("azure_foundry", "llama-3.3-70b-instruct", 1.42);
}
#[test]
fn azure_foundry_unknown_model_has_no_estimate() {
assert!(estimate_model_cost(
"azure_foundry",
"private-deployment-without-metadata",
&usage(Some(1_000_000), Some(1_000_000), None),
)
.is_none());
}
#[test]
@@ -379,7 +379,7 @@ The session cost is shown at the bottom of the goose window and updates dynamica
Pricing data is regularly fetched from the OpenRouter API and cached locally. The `Advanced settings` tab shows when the data was last updated and allows you to refresh.
These costs are estimates only, and not connected to your actual provider bill. The cost shown is an approximation based on token counts and public pricing data.
These costs are public-price estimates only, not invoices or a view of your actual provider bill. The displayed amount approximates usage from token counts and public catalog rates; provider-reported costs take precedence when available.
</TabItem>
<TabItem value="cli" label="goose CLI">
Show estimated cost in the goose CLI by setting the `GOOSE_CLI_SHOW_COST` [environment variable](/docs/guides/environment-variables.md#session-management) or including it in the [configuration file](/docs/guides/config-files.md).