Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

feat(rust): settle EdenAI Messages reported cost (#45698)

yujonglee05cf42876138
diff --git a/litellm-rust/crates/callbacks-legacy-python/src/adapter.rs b/litellm-rust/crates/callbacks-legacy-python/src/adapter.rs
index dd3da8991cc..9f56f12a8f9 100644
--- a/litellm-rust/crates/callbacks-legacy-python/src/adapter.rs
+++ b/litellm-rust/crates/callbacks-legacy-python/src/adapter.rs
@@ -442,7 +442,7 @@ impl LegacyLogging {
py: Python<'_>,
facts: &litellm_host::interceptors::ExecutionFacts,
) -> PyResult<HookStep<Self, ()>> {
- use litellm_host::interceptors::ResultSource;
+ use litellm_host::interceptors::{Cost, ResultSource};
let logger = self.logger()?.object(py);
let params = logger
@@ -462,6 +462,12 @@ impl LegacyLogging {
),
)?;
let details = logger.getattr("model_call_details")?;
+ let reported_cost = match &facts.cost {
+ Cost::Reported { amount } => amount.as_f64(),
+ Cost::CacheHit | Cost::Deferred => None,
+ };
+ logger.setattr("_provider_reported_cost", reported_cost)?;
+ details.call_method1("pop", ("response_cost", py.None()))?;
self.cache_key = match &facts.source {
ResultSource::Provider => None,
ResultSource::Cache { key } => Some(key.clone()),
@@ -958,6 +964,81 @@ on_pre_call = lambda additional_args: None
check = lambda: None
";
+ #[rstest]
+ #[case::reported(Some(0.37), false)]
+ #[case::free(Some(0.0), false)]
+ #[case::deferred(None, false)]
+ #[case::cached(None, true)]
+ fn result_ready_hands_only_a_reported_cost_to_the_spend_logging_record(
+ #[case] reported: Option<f64>,
+ #[case] cache_hit: bool,
+ #[values(0.001, 7.0)] existing_cost: f64,
+ ) {
+ Python::initialize();
+ Python::attach(|py| {
+ let locals = namespace(py, PAYLOAD_LOGGER);
+ run(
+ py,
+ &locals,
+ c"
+logger.litellm_params = {}
+logger.optional_params = {}
+logger.model_call_details = {'response_cost': 7.0}
+logger._provider_reported_cost = None
+",
+ );
+ let mut logging = LegacyLogging {
+ logger: Some(PythonLogger::new(local(&locals, "logger").unbind())),
+ ..legacy_call(py, &locals, false)
+ };
+ let source = if cache_hit {
+ litellm_host::interceptors::ResultSource::Cache {
+ key: "cached-test".into(),
+ }
+ } else {
+ litellm_host::interceptors::ResultSource::Provider
+ };
+ let facts = litellm_host::interceptors::ExecutionFacts {
+ provider: litellm_host::interceptors::ProviderIdentity {
+ model: "native-test".into(),
+ provider: "edenai".into(),
+ },
+ cost: litellm_host::interceptors::Cost::settle(
+ &source,
+ reported.and_then(serde_json::Number::from_f64),
+ ),
+ source,
+ };
+ let previous = litellm_host::interceptors::ExecutionFacts {
+ provider: facts.provider.clone(),
+ cost: litellm_host::interceptors::Cost::Reported {
+ amount: serde_json::Number::from_f64(9.0).unwrap(),
+ },
+ source: litellm_host::interceptors::ResultSource::Provider,
+ };
+ logging.result_ready(py, &previous).unwrap();
+ local(&locals, "logger")
+ .getattr("model_call_details")
+ .unwrap()
+ .set_item("response_cost", existing_cost)
+ .unwrap();
+ let step = logging.result_ready(py, &facts).unwrap();
+ assert!(matches!(step, HookStep::Ready(())));
+ locals.set_item("reported", reported).unwrap();
+ locals.set_item("cache_hit", cache_hit).unwrap();
+ run(
+ py,
+ &locals,
+ c"
+assert logger.model_call_details.get('response_cost') is None, logger.model_call_details
+assert logger._provider_reported_cost == reported, logger._provider_reported_cost
+assert logger.model_call_details['cache_hit'] is cache_hit, logger.model_call_details
+assert logger.update['custom_llm_provider'] == 'edenai', logger.update
+",
+ );
+ });
+ }
+
const DOCUMENT: &str = "data:application/pdf;base64,YWJj";
const EDITED: &str = "data:application/pdf;base64,ZWRpdGVk";
diff --git a/litellm-rust/crates/core-utils/src/get_llm_provider_logic.rs b/litellm-rust/crates/core-utils/src/get_llm_provider_logic.rs
index 982831bcc5e..acea48799c0 100644
--- a/litellm-rust/crates/core-utils/src/get_llm_provider_logic.rs
+++ b/litellm-rust/crates/core-utils/src/get_llm_provider_logic.rs
@@ -22,6 +22,8 @@ pub enum LlmProviders {
Cohere,
#[strum(serialize = "deepseek")]
Deepseek,
+ #[strum(serialize = "edenai")]
+ Edenai,
#[strum(serialize = "minimax")]
Minimax,
#[strum(serialize = "mistral")]
diff --git a/litellm-rust/crates/host/src/interceptors.rs b/litellm-rust/crates/host/src/interceptors.rs
index 3633fc7ee39..f0fd7434c6d 100644
--- a/litellm-rust/crates/host/src/interceptors.rs
+++ b/litellm-rust/crates/host/src/interceptors.rs
@@ -42,10 +42,32 @@ pub enum ResultSource {
Cache { key: String },
}
+/// What the call cost, settled once by the route. A host records it; it never re-derives it.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum Cost {
+ /// The amount the provider itself billed, taken from its response.
+ Reported { amount: serde_json::Number },
+ /// Served from the cache, so nothing was billed.
+ CacheHit,
+ /// No provider figure: the host estimates from usage and its price table.
+ Deferred,
+}
+
+impl Cost {
+ pub fn settle(source: &ResultSource, reported: Option<serde_json::Number>) -> Self {
+ match (source, reported) {
+ (ResultSource::Cache { .. }, _) => Self::CacheHit,
+ (ResultSource::Provider, Some(amount)) => Self::Reported { amount },
+ (ResultSource::Provider, None) => Self::Deferred,
+ }
+ }
+}
+
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExecutionFacts {
pub provider: ProviderIdentity,
pub source: ResultSource,
+ pub cost: Cost,
}
pub trait Interceptors<E>: Send + Sync {
diff --git a/litellm-rust/crates/inference-messages/src/common_utils.rs b/litellm-rust/crates/inference-messages/src/common_utils.rs
index 91b135a6a4a..66e7e1cfe25 100644
--- a/litellm-rust/crates/inference-messages/src/common_utils.rs
+++ b/litellm-rust/crates/inference-messages/src/common_utils.rs
@@ -8,6 +8,7 @@ use litellm_llms::{
base_llm::messages::transformation::BaseMessagesConfig,
bedrock::messages::invoke_transformations::anthropic_claude3_transformation::BEDROCK_ANTHROPIC_MESSAGES_CONFIG,
deepseek::messages::transformation::DEEPSEEK_ANTHROPIC_MESSAGES_CONFIG,
+ edenai::messages::transformation::EDENAI_MESSAGES_CONFIG,
minimax::messages::transformation::MINIMAX_MESSAGES_CONFIG,
vertex_ai::messages::transformation::VERTEX_ANTHROPIC_MESSAGES_CONFIG,
};
@@ -53,6 +54,7 @@ pub(crate) fn messages_provider(provider: LlmProviders, model: &str) -> Option<M
LlmProviders::Bedrock => &BEDROCK_ANTHROPIC_MESSAGES_CONFIG,
LlmProviders::BedrockMantle => &BEDROCK_MANTLE_MESSAGES_CONFIG,
LlmProviders::Deepseek => &DEEPSEEK_ANTHROPIC_MESSAGES_CONFIG,
+ LlmProviders::Edenai => &EDENAI_MESSAGES_CONFIG,
LlmProviders::Minimax => &MINIMAX_MESSAGES_CONFIG,
LlmProviders::VertexAi if model.to_ascii_lowercase().contains("claude") => {
&VERTEX_ANTHROPIC_MESSAGES_CONFIG
@@ -85,6 +87,7 @@ mod tests {
#[case::azure_ai("azure_ai")]
#[case::bedrock("bedrock")]
#[case::deepseek("deepseek")]
+ #[case::edenai("edenai")]
#[case::minimax("minimax")]
#[case::vertex_ai("vertex_ai")]
fn provider_keeps_its_python_name(#[case] name: &str) {
diff --git a/litellm-rust/crates/inference-messages/src/handler.rs b/litellm-rust/crates/inference-messages/src/handler.rs
index 4e883320303..178f96c4c33 100644
--- a/litellm-rust/crates/inference-messages/src/handler.rs
+++ b/litellm-rust/crates/inference-messages/src/handler.rs
@@ -25,7 +25,7 @@ use litellm_inference::{context::CallContext, outbound::outbound_request};
pub(super) struct ProviderCall {
pub identity: ProviderIdentity,
pub wire: WireRequest,
- provider: super::common_utils::MessagesProvider,
+ pub(super) provider: super::common_utils::MessagesProvider,
signer: Option<litellm_auth_aws::SigV4Signer>,
timeout: Option<Duration>,
stream: bool,
diff --git a/litellm-rust/crates/inference-messages/src/lib.rs b/litellm-rust/crates/inference-messages/src/lib.rs
index 6cf7e34e52a..c690c7a2ef4 100644
--- a/litellm-rust/crates/inference-messages/src/lib.rs
+++ b/litellm-rust/crates/inference-messages/src/lib.rs
@@ -7,7 +7,7 @@ mod types;
use futures_util::FutureExt;
use litellm_auth::AuthServices;
-use litellm_host::interceptors::{ExecutionFacts, Interceptors, ResultSource};
+use litellm_host::interceptors::{Cost, ExecutionFacts, Interceptors, ResultSource};
use litellm_inference::{caching::CallCache, context::CallContext};
use litellm_secrets::source::SecretSource;
@@ -87,6 +87,7 @@ impl MessagesRoute {
&request.wire,
);
let identity = request.identity.clone();
+ let config = request.provider.config();
let (output, source) = match cache.lookup().await {
Some(hit) => hit,
None => (
@@ -94,9 +95,14 @@ impl MessagesRoute {
ResultSource::Provider,
),
};
+ let reported = match &output {
+ MessagesCallResponse::Complete(response) => config.reported_cost(response),
+ MessagesCallResponse::Stream { .. } => None,
+ };
context
.result_ready(ExecutionFacts {
provider: identity,
+ cost: Cost::settle(&source, reported),
source: source.clone(),
})
.await?;
diff --git a/litellm-rust/crates/inference-messages/tests/caching.rs b/litellm-rust/crates/inference-messages/tests/caching.rs
index e9005123119..32c962091ad 100644
--- a/litellm-rust/crates/inference-messages/tests/caching.rs
+++ b/litellm-rust/crates/inference-messages/tests/caching.rs
@@ -13,8 +13,8 @@ use litellm_cache_response::{
CacheOptions, CacheScope, ResponseCache, ResponseCacheConfig, ResponseCacheService, ScopedCache,
};
use litellm_host::interceptors::{
- ExecutionFacts, Interceptors, ProviderIdentity, RawResponse, RequestContext, ResultSource,
- WireRequest,
+ Cost, ExecutionFacts, Interceptors, ProviderIdentity, RawResponse, RequestContext,
+ ResultSource, WireRequest,
};
use litellm_inference::{
RouteError,
@@ -241,3 +241,55 @@ async fn messages_cache_identity_follows_resolved_configuration_and_request_call
first.verify().await;
second.verify().await;
}
+
+#[rstest]
+#[case::reported(json!(0.37), Some(0.37))]
+#[case::free(json!(0), Some(0.0))]
+#[case::malformed(json!("invalid"), None)]
+#[case::missing(Value::Null, None)]
+#[tokio::test]
+async fn provider_reported_cost_is_delivered_once_and_never_charged_for_a_cache_hit(
+ cache: Arc<dyn ResponseCacheService>,
+ #[case] cost: Value,
+ #[case] expected: Option<f64>,
+) {
+ use litellm_inference_messages::{MessagesCall, MessagesCallResponse};
+ let response = json!({"id": "msg_cost", "type": "message", "role": "assistant", "model": "native-test",
+ "content": [{"type": "text", "text": "answer"}], "stop_reason": "end_turn", "stop_sequence": null,
+ "usage": {"input_tokens": 3, "output_tokens": 2}, "cost": cost});
+ let upstream = support::upstream([support::json_response(response)]).await;
+ let hooks = ChangingHooks::default();
+ let route = support::messages_route(litellm_inference_testing::no_secrets())
+ .with_cache(ScopedCache::new(cache, CacheScope::Shared));
+ let request = || {
+ MessagesCall {
+ body: serde_json::from_value(json!({"model": "native-test", "messages": [{"role": "user", "content": "hi"}], "max_tokens": 16})).unwrap(),
+ api_key: Some("eden-key".into()), api_base: Some(upstream.uri()), custom_llm_provider: Some("edenai".into()),
+ litellm_params: Default::default(), extra_headers: None, provider_specific_header: None,
+ timeout: None, shaping: Default::default(),
+ }
+ };
+ let first = route.execute(request(), &hooks, None).await.unwrap();
+ let second = route.execute(request(), &hooks, None).await.unwrap();
+ let (MessagesCallResponse::Complete(first), MessagesCallResponse::Complete(second)) =
+ (first, second)
+ else {
+ panic!("expected Messages responses");
+ };
+ assert_eq!(first, second);
+ assert_eq!(first.extra.get("cost"), Some(&cost));
+ assert_eq!(support::received(&upstream).await.len(), 1);
+ let facts = hooks.facts.lock().unwrap();
+ let [provider, cached] = facts.as_slice() else {
+ panic!("expected provider and cache results");
+ };
+ assert_eq!(provider.source, ResultSource::Provider);
+ assert_eq!(
+ provider.cost,
+ expected.map_or(Cost::Deferred, |amount| Cost::Reported {
+ amount: serde_json::Number::from_f64(amount).unwrap()
+ })
+ );
+ assert!(matches!(cached.source, ResultSource::Cache { .. }));
+ assert_eq!(cached.cost, Cost::CacheHit);
+}
diff --git a/litellm-rust/crates/inference-messages/tests/live.rs b/litellm-rust/crates/inference-messages/tests/live.rs
index 639b14dda6f..24468598141 100644
--- a/litellm-rust/crates/inference-messages/tests/live.rs
+++ b/litellm-rust/crates/inference-messages/tests/live.rs
@@ -1,5 +1,8 @@
#[path = "live/support.rs"]
mod support;
+#[path = "live/edenai.rs"]
+mod edenai;
+
#[path = "live/vertex_ai.rs"]
mod vertex_ai;
diff --git a/litellm-rust/crates/inference-messages/tests/live/edenai.rs b/litellm-rust/crates/inference-messages/tests/live/edenai.rs
new file mode 100644
index 00000000000..28c17679865
--- /dev/null
+++ b/litellm-rust/crates/inference-messages/tests/live/edenai.rs
@@ -0,0 +1,92 @@
+use litellm_host::interceptors::Cost;
+use litellm_inference_messages::MessagesRoute;
+use litellm_inference_testing::live::within_deadline;
+use rstest::rstest;
+use serde_json::{Number, Value, json};
+
+use super::support::{LiveCall, assert_text, call, complete, request, route, stream_events};
+
+const PROVIDER: &str = "edenai";
+
+#[rstest]
+#[case::basic(json!({"messages": [{"role": "user", "content": "Say hello."}]}))]
+#[case::system_text(json!({
+ "system": "You are a helpful assistant.",
+ "messages": [{"role": "user", "content": "Say hello."}]
+}))]
+#[case::portable_cache_hint(json!({
+ "system": [{"type": "text", "text": "You are a helpful assistant.", "cache_control": {"type": "ephemeral", "ttl": "1h"}}],
+ "messages": [{"role": "user", "content": "Say hello."}]
+}))]
+#[ignore = "calls a real provider, requires credentials and a live model"]
+#[tokio::test]
+async fn completion_and_cost_handoff(route: MessagesRoute, #[case] payload: Value) {
+ within_deadline(async {
+ let host = LiveCall::new(PROVIDER);
+ let message = complete(request(&route, call(PROVIDER, payload), &host).await);
+ assert_text(&message);
+ host.assert_provider_result();
+ let expected_cost = message
+ .extra
+ .get("cost")
+ .and_then(|value| match value {
+ Value::Number(number) => number.as_f64(),
+ Value::String(text) => text.parse::<f64>().ok(),
+ _ => None,
+ })
+ .filter(|cost| *cost >= 0.0)
+ .and_then(Number::from_f64)
+ .map_or(Cost::Deferred, |amount| Cost::Reported { amount });
+ assert_eq!(host.facts().cost, expected_cost);
+ println!("{}", serde_json::to_string(&message).unwrap());
+ })
+ .await;
+}
+
+#[rstest]
+#[ignore = "calls a real provider, requires credentials and a live model"]
+#[tokio::test]
+async fn streaming(route: MessagesRoute) {
+ within_deadline(async {
+ let host = LiveCall::new(PROVIDER);
+ let events = stream_events(
+ request(
+ &route,
+ call(
+ PROVIDER,
+ json!({
+ "stream": true, "messages": [{"role": "user", "content": "Say hello."}]
+ }),
+ ),
+ &host,
+ )
+ .await,
+ )
+ .await;
+ assert!(events.iter().any(|event| {
+ event["delta"]["text"]
+ .as_str()
+ .is_some_and(|text| !text.is_empty())
+ }));
+ host.assert_provider_result();
+ assert_eq!(host.facts().cost, Cost::Deferred);
+ })
+ .await;
+}
+
+#[rstest]
+#[case::complete(false)]
+#[case::streaming(true)]
+#[ignore = "calls a real provider, requires credentials and a live model"]
+#[tokio::test]
+async fn tool_round_trip(route: MessagesRoute, #[case] stream: bool) {
+ super::support::tool_round_trip(
+ route,
+ PROVIDER,
+ stream,
+ json!({
+ "max_tokens": 512, "tool_choice": {"type": "auto"}
+ }),
+ )
+ .await;
+}
diff --git a/litellm-rust/crates/inference-messages/tests/messages/request.rs b/litellm-rust/crates/inference-messages/tests/messages/request.rs
index 7c02d2a2e5a..aa8cb05b170 100644
--- a/litellm-rust/crates/inference-messages/tests/messages/request.rs
+++ b/litellm-rust/crates/inference-messages/tests/messages/request.rs
@@ -894,3 +894,38 @@ async fn provider_validation_runs_before_caller_parameter_removal(
);
assert!(received(&upstream).await.is_empty());
}
+
+#[rstest]
+#[tokio::test]
+async fn edenai_preserves_native_thinking_and_strips_billing_and_cache_extensions(
+ call: MessagesCall,
+) {
+ let upstream = upstream([message_response()]).await;
+ let thinking = json!({"type": "enabled", "budget_tokens": 512, "native_field": true});
+ run_message(MessagesCall {
+ custom_llm_provider: Some("edenai".into()),
+ api_base: Some(format!("{}/v3", upstream.uri())),
+ api_key: Some("eden-key".into()),
+ extra_headers: headers([("Anthropic-Beta", "unregistered-native-beta")]),
+ ..with_fields(call, json!({
+ "thinking": thinking, "temperature": 0.25,
+ "system": [{"type": "text", "text": "x-anthropic-billing-header: hidden"},
+ {"type": "text", "text": "keep", "cache_control": {"type": "ephemeral", "ttl": "1h", "scope": "global"}}],
+ }))
+ }).await;
+ let sent = only_request(&upstream).await;
+ assert_eq!(sent.url.path(), "/v3/v1/messages");
+ assert_eq!(sent.header("authorization"), Some("Bearer eden-key"));
+ assert_eq!(
+ sent.header("anthropic-beta"),
+ Some("unregistered-native-beta")
+ );
+ assert_eq!(
+ sent.json(),
+ json!({
+ "model": MODEL, "max_tokens": 16, "messages": [{"role": "user", "content": "hi"}],
+ "thinking": thinking, "temperature": 0.25,
+ "system": [{"type": "text", "text": "keep", "cache_control": {"type": "ephemeral"}}],
+ })
+ );
+}
diff --git a/litellm-rust/crates/inference-messages/tests/messages/stream.rs b/litellm-rust/crates/inference-messages/tests/messages/stream.rs
index 7deaa4fbd3f..cda688107b5 100644
--- a/litellm-rust/crates/inference-messages/tests/messages/stream.rs
+++ b/litellm-rust/crates/inference-messages/tests/messages/stream.rs
@@ -348,6 +348,7 @@ async fn the_timeout_covers_a_stalled_stream_body(call: MessagesCall) {
#[rstest]
#[case::anthropic("anthropic")]
#[case::azure_ai("azure_ai")]
+#[case::edenai("edenai")]
#[tokio::test]
async fn the_sdk_returns_stream_headers_and_every_sse_byte(
call: MessagesCall,
@@ -358,6 +359,7 @@ async fn the_sdk_returns_stream_headers_and_every_sse_byte(
.execute(
MessagesCall {
custom_llm_provider: Some(provider.into()),
+ api_key: Some("stream-key".into()),
litellm_params: Default::default(),
..streaming(call, upstream.uri())
},
diff --git a/litellm-rust/crates/inference-testing/README.md b/litellm-rust/crates/inference-testing/README.md
index 959aaccbb08..caf66073c35 100644
--- a/litellm-rust/crates/inference-testing/README.md
+++ b/litellm-rust/crates/inference-testing/README.md
@@ -14,7 +14,7 @@ Completion checks text and usage. Streaming consumes SSE to completion and check
Messages setup and assertions live in `inference-messages/tests/live/support.rs`. Provider modules under `tests/live/` select their payloads and tool policy. The shared helpers consume streams completely and reconstruct text, thinking signatures and tool arguments for the follow-up request
-The initial provider case is `vertex_ai`. A registered ignored case is available coverage, not evidence that it passed against that provider
+The initial provider cases are `vertex_ai` and `edenai`. A registered ignored case is available coverage, not evidence that it passed against that provider
Run one provider's cases explicitly
@@ -29,7 +29,12 @@ For Vertex AI, set `LITELLM_LIVE_MESSAGES_VERTEX_AI_MODEL` to a Claude model pub
Vertex AI cases live in `inference-messages/tests/live/vertex_ai.rs`. They cover plain and system messages, text streaming, and complete and streaming tool round trips. Tool cases use automatic selection because current Claude models reject forced `tool_choice`. Each case still requires a tool call, checks its arguments, and sends the tool result back
-Tool cases require a model that supports forced `tool_choice`, except where a provider's section says otherwise. A provider rejection fails the selected case instead of skipping it
+For EdenAI, set `LITELLM_LIVE_MESSAGES_EDENAI_MODEL` and `EDENAI_API_KEY`, and select `edenai`. EdenAI requires a production token for live coverage, because sandbox tokens return dummy responses
+
+EdenAI cases live in `inference-messages/tests/live/edenai.rs`. They cover system messages, portable cache hints, provider-reported cost handoff, text streaming, and complete and streaming tool round trips. The cost assertion compares the public response with the execution facts instead of pinning a vendor price
+EdenAI tool cases use automatic selection because current Claude models reject forced `tool_choice`. The test still requires a tool call and verifies its arguments and follow-up response
+
+Other tool cases require a model that supports forced `tool_choice`, except where a provider's section says otherwise. A provider rejection fails the selected case instead of skipping it
Select one behavior by its test name, for example `completion::case_1_basic`. To list every available cell without contacting any provider
diff --git a/litellm-rust/crates/inference/src/caching.rs b/litellm-rust/crates/inference/src/caching.rs
index d2f4198b910..6dfda20ead4 100644
--- a/litellm-rust/crates/inference/src/caching.rs
+++ b/litellm-rust/crates/inference/src/caching.rs
@@ -13,7 +13,9 @@ use litellm_cache_response::{
};
use litellm_host::{
call::{CallOutput, OutputOf},
- interceptors::{ExecutionFacts, Interceptors, ProviderIdentity, ResultSource, WireRequest},
+ interceptors::{
+ Cost, ExecutionFacts, Interceptors, ProviderIdentity, ResultSource, WireRequest,
+ },
lifecycle::{CallEvent, ExecutionEvent},
observation::ObservationSender,
protocol::Protocol,
@@ -168,10 +170,12 @@ where
None => (provider().await?, ResultSource::Provider),
};
let from_provider = source == ResultSource::Provider;
+ let cost = Cost::settle(&source, None);
publish(
ExecutionFacts {
provider: identity,
source,
+ cost,
},
interceptors,
observers,
@@ -212,6 +216,7 @@ where
publish(
ExecutionFacts {
provider: identity,
+ cost: Cost::settle(&source, None),
source: source.clone(),
},
interceptors,
diff --git a/litellm-rust/crates/llms/src/base_llm/messages/transformation.rs b/litellm-rust/crates/llms/src/base_llm/messages/transformation.rs
index 61398fe4ea9..6f0ea5c8f2a 100644
--- a/litellm-rust/crates/llms/src/base_llm/messages/transformation.rs
+++ b/litellm-rust/crates/llms/src/base_llm/messages/transformation.rs
@@ -41,6 +41,10 @@ pub trait BaseMessagesConfig: Sync {
Ok(response)
}
+ fn reported_cost(&self, _response: &MessagesResponse) -> Option<serde_json::Number> {
+ None
+ }
+
fn secret_names(&self) -> &'static [&'static str];
/// Shapes the forwarded headers and names the credential, the way Python's
diff --git a/litellm-rust/crates/llms/src/edenai/messages/mod.rs b/litellm-rust/crates/llms/src/edenai/messages/mod.rs
new file mode 100644
index 00000000000..f239b6921fa
--- /dev/null
+++ b/litellm-rust/crates/llms/src/edenai/messages/mod.rs
@@ -0,0 +1 @@
+pub mod transformation;
diff --git a/litellm-rust/crates/llms/src/edenai/messages/transformation.rs b/litellm-rust/crates/llms/src/edenai/messages/transformation.rs
new file mode 100644
index 00000000000..7fd001ddbbc
--- /dev/null
+++ b/litellm-rust/crates/llms/src/edenai/messages/transformation.rs
@@ -0,0 +1,120 @@
+use litellm_auth::{CredentialPlacement, SecretValue};
+use litellm_core_utils::settings::resolve_non_empty;
+use litellm_llms_types::formats::messages::{
+ MessagesOptionalParams, MessagesRequest, MessagesResponse,
+};
+use litellm_llms_types::providers::anthropic::DEFAULT_HEADERS;
+use litellm_router_types::LitellmParams;
+use serde_json::Value;
+
+use crate::{
+ Error,
+ anthropic::{
+ common_utils::{filter_billing_headers_from_system, has_anthropic_credential},
+ messages::transformation::update_headers_with_anthropic_beta,
+ },
+ base_llm::{
+ auth::AuthScheme,
+ messages::{
+ context::MessagesTransformContext,
+ transformation::{BaseMessagesConfig, Headers, ValidatedEnvironment},
+ },
+ },
+ openai_like::messages::transformation::{complete_messages_url, portable_cache_control},
+};
+
+const API_KEY_ENV: &str = "EDENAI_API_KEY";
+const API_BASE_ENV: &str = "EDENAI_API_BASE";
+const DEFAULT_BASE: &str = "https://api.edenai.run/v3";
+
+pub struct EdenAIAnthropicMessagesConfig;
+pub const EDENAI_MESSAGES_CONFIG: EdenAIAnthropicMessagesConfig = EdenAIAnthropicMessagesConfig;
+
+impl BaseMessagesConfig for EdenAIAnthropicMessagesConfig {
+ fn validate_environment(
+ &self,
+ headers: Headers,
+ api_key: Option<&str>,
+ _model: &str,
+ _params: &LitellmParams,
+ env: &dyn Fn(&str) -> Option<String>,
+ ) -> Result<ValidatedEnvironment, Error> {
+ let key = resolve_non_empty(api_key, env, &[API_KEY_ENV]).ok_or(Error::Auth(
+ litellm_auth::Error::MissingApiKey {
+ provider: "Eden AI",
+ environment_variable: API_KEY_ENV,
+ },
+ ))?;
+ if has_anthropic_credential(&headers) {
+ return Ok(ValidatedEnvironment {
+ headers,
+ auth: AuthScheme::Forwarded,
+ });
+ }
+ Ok(ValidatedEnvironment {
+ headers,
+ auth: AuthScheme::Credential {
+ placement: CredentialPlacement::Bearer,
+ secret: SecretValue::new(key),
+ },
+ })
+ }
+
+ fn get_complete_url(
+ &self,
+ api_base: Option<&str>,
+ _model: &str,
+ _params: &LitellmParams,
+ _stream: bool,
+ env: &dyn Fn(&str) -> Option<String>,
+ ) -> Result<String, Error> {
+ let base = resolve_non_empty(api_base, env, &[API_BASE_ENV])
+ .unwrap_or_else(|| DEFAULT_BASE.into());
+ Ok(complete_messages_url(&base))
+ }
+
+ fn transform_anthropic_messages_request(
+ &self,
+ request: MessagesRequest,
+ _context: &MessagesTransformContext,
+ ) -> Result<MessagesRequest, Error> {
+ Ok(MessagesRequest {
+ params: MessagesOptionalParams {
+ system: request
+ .params
+ .system
+ .and_then(filter_billing_headers_from_system),
+ ..request.params
+ },
+ ..request
+ })
+ }
+
+ fn secret_names(&self) -> &'static [&'static str] {
+ &[API_KEY_ENV, API_BASE_ENV]
+ }
+
+ fn default_headers(&self) -> &'static [(&'static str, &'static str)] {
+ DEFAULT_HEADERS
+ }
+
+ fn request_headers(&self, headers: Headers, request: &MessagesRequest) -> Headers {
+ update_headers_with_anthropic_beta(headers, request)
+ }
+
+ fn wire_body(&self, body: Value) -> Value {
+ portable_cache_control(body)
+ }
+
+ fn reported_cost(&self, response: &MessagesResponse) -> Option<serde_json::Number> {
+ let cost = match response.extra.get("cost")? {
+ Value::Number(cost) => cost.as_f64()?,
+ Value::String(cost) => cost.parse::<f64>().ok()?,
+ _ => return None,
+ };
+ if cost < 0.0 {
+ return None;
+ }
+ serde_json::Number::from_f64(cost)
+ }
+}
diff --git a/litellm-rust/crates/llms/src/edenai/mod.rs b/litellm-rust/crates/llms/src/edenai/mod.rs
new file mode 100644
index 00000000000..ba63992f3cb
--- /dev/null
+++ b/litellm-rust/crates/llms/src/edenai/mod.rs
@@ -0,0 +1 @@
+pub mod messages;
diff --git a/litellm-rust/crates/llms/src/lib.rs b/litellm-rust/crates/llms/src/lib.rs
index 1cf69ab5745..eb232404d93 100644
--- a/litellm-rust/crates/llms/src/lib.rs
+++ b/litellm-rust/crates/llms/src/lib.rs
@@ -6,6 +6,7 @@ pub mod bedrock;
pub mod bedrock_mantle;
pub mod cohere;
pub mod deepseek;
+pub mod edenai;
mod error;
pub mod minimax;
pub mod mistral;
diff --git a/litellm-rust/crates/llms/src/openai_like/messages/mod.rs b/litellm-rust/crates/llms/src/openai_like/messages/mod.rs
new file mode 100644
index 00000000000..f239b6921fa
--- /dev/null
+++ b/litellm-rust/crates/llms/src/openai_like/messages/mod.rs
@@ -0,0 +1 @@
+pub mod transformation;
diff --git a/litellm-rust/crates/llms/src/openai_like/messages/transformation.rs b/litellm-rust/crates/llms/src/openai_like/messages/transformation.rs
new file mode 100644
index 00000000000..f69bc3d59be
--- /dev/null
+++ b/litellm-rust/crates/llms/src/openai_like/messages/transformation.rs
@@ -0,0 +1,100 @@
+use serde_json::{Map, Value};
+
+pub fn complete_messages_url(base: &str) -> String {
+ let base = base.trim_end_matches('/');
+ if base.ends_with("/v1/messages") {
+ return base.into();
+ }
+ format!("{}/v1/messages", base.strip_suffix("/v1").unwrap_or(base))
+}
+
+pub fn portable_cache_control(body: Value) -> Value {
+ let Value::Object(fields) = body else {
+ return body;
+ };
+ Value::Object(
+ portable_block(fields)
+ .into_iter()
+ .map(|(key, value)| {
+ let value = match key.as_str() {
+ "system" | "tools" => map_blocks(value, portable_value),
+ "messages" => map_blocks(value, portable_message),
+ _ => value,
+ };
+ (key, value)
+ })
+ .collect(),
+ )
+}
+
+fn portable_block(fields: Map<String, Value>) -> Map<String, Value> {
+ fields
+ .into_iter()
+ .filter_map(|(key, value)| {
+ if key != "cache_control" {
+ return Some((key, value));
+ }
+ let Value::Object(cache) = value else {
+ return None;
+ };
+ let kind = cache
+ .get("type")
+ .and_then(Value::as_str)
+ .unwrap_or("ephemeral");
+ Some((key, serde_json::json!({"type": kind})))
+ })
+ .collect()
+}
+
+fn portable_value(value: Value) -> Value {
+ match value {
+ Value::Object(fields) => Value::Object(portable_block(fields)),
+ other => other,
+ }
+}
+
+fn map_blocks(value: Value, map: fn(Value) -> Value) -> Value {
+ match value {
+ Value::Array(blocks) => Value::Array(blocks.into_iter().map(map).collect()),
+ other => other,
+ }
+}
+
+fn portable_message(value: Value) -> Value {
+ let Value::Object(fields) = value else {
+ return value;
+ };
+ Value::Object(
+ fields
+ .into_iter()
+ .map(|(key, value)| {
+ let value = if key == "content" {
+ map_blocks(value, portable_content)
+ } else {
+ value
+ };
+ (key, value)
+ })
+ .collect(),
+ )
+}
+
+fn portable_content(value: Value) -> Value {
+ let Value::Object(fields) = value else {
+ return value;
+ };
+ let tool_result = fields.get("type").and_then(Value::as_str) == Some("tool_result");
+ Value::Object(
+ portable_block(fields)
+ .into_iter()
+ .map(|(key, value)| {
+ let value = if tool_result && key == "content" {
+ map_blocks(value, portable_value)
+ } else {
+ value
+ };
+ (key, value)
+ })
+ .collect(),
+ )
+}
diff --git a/litellm-rust/crates/llms/src/openai_like/mod.rs b/litellm-rust/crates/llms/src/openai_like/mod.rs
index df0cc73a5b0..3ea6fc63fa4 100644
--- a/litellm-rust/crates/llms/src/openai_like/mod.rs
+++ b/litellm-rust/crates/llms/src/openai_like/mod.rs
@@ -1,2 +1,3 @@
pub mod chat;
pub mod common_utils;
+pub mod messages;
diff --git a/litellm-rust/crates/llms/tests/edenai_messages_transformation.rs b/litellm-rust/crates/llms/tests/edenai_messages_transformation.rs
new file mode 100644
index 00000000000..72b882f94ca
--- /dev/null
+++ b/litellm-rust/crates/llms/tests/edenai_messages_transformation.rs
@@ -0,0 +1,34 @@
+use litellm_llms::{
+ base_llm::messages::transformation::BaseMessagesConfig,
+ edenai::messages::transformation::EDENAI_MESSAGES_CONFIG,
+};
+use litellm_llms_types::formats::messages::MessagesResponse;
+use rstest::rstest;
+use serde_json::{Value, json};
+
+#[rstest]
+#[case::number(json!(0.025), Some(0.025))]
+#[case::free(json!(0), Some(0.0))]
+#[case::text(json!("0.75"), Some(0.75))]
+#[case::absent(Value::Null, None)]
+#[case::malformed(json!("not-a-cost"), None)]
+#[case::negative(json!(-1), None)]
+#[case::boolean(json!(true), None)]
+#[case::infinite(json!("inf"), None)]
+#[case::nan(json!("NaN"), None)]
+fn reported_cost_is_a_finite_nonnegative_amount(
+ #[case] cost: Value,
+ #[case] expected: Option<f64>,
+) {
+ let response: MessagesResponse = serde_json::from_value(json!({
+ "id": "msg_test", "type": "message", "role": "assistant", "model": "native-test",
+ "content": [], "stop_reason": "end_turn", "stop_sequence": null, "cost": cost,
+ }))
+ .unwrap();
+ assert_eq!(
+ EDENAI_MESSAGES_CONFIG
+ .reported_cost(&response)
+ .and_then(|cost| cost.as_f64()),
+ expected
+ );
+}
diff --git a/litellm-rust/crates/llms/tests/openai_like_messages_transformation.rs b/litellm-rust/crates/llms/tests/openai_like_messages_transformation.rs
new file mode 100644
index 00000000000..824c7d8e5f2
--- /dev/null
+++ b/litellm-rust/crates/llms/tests/openai_like_messages_transformation.rs
@@ -0,0 +1,64 @@
+use litellm_llms::openai_like::messages::transformation::{
+ complete_messages_url, portable_cache_control,
+};
+use rstest::rstest;
+use serde_json::{Value, json};
+
+#[rstest]
+#[case::root("https://native.test", "https://native.test/v1/messages")]
+#[case::trailing_slash("https://native.test/", "https://native.test/v1/messages")]
+#[case::versioned("https://native.test/v1/", "https://native.test/v1/messages")]
+#[case::full_url(
+ "https://native.test/v3/v1/messages/",
+ "https://native.test/v3/v1/messages"
+)]
+#[case::gateway_prefix("https://native.test/v3", "https://native.test/v3/v1/messages")]
+fn messages_url_appends_the_endpoint_once(#[case] base: &str, #[case] expected: &str) {
+ assert_eq!(complete_messages_url(base), expected);
+}
+
+#[rstest]
+#[case::extended(json!({"type": "ephemeral", "ttl": "1h", "scope": "global"}), Some(json!({"type": "ephemeral"})))]
+#[case::missing_type(json!({"ttl": "1h"}), Some(json!({"type": "ephemeral"})))]
+#[case::invalid_type(json!({"type": 7}), Some(json!({"type": "ephemeral"})))]
+#[case::null(Value::Null, None)]
+#[case::scalar(json!(false), None)]
+fn portable_cache_only_rewrites_protocol_cache_hints(
+ #[case] cache: Value,
+ #[case] expected_cache: Option<Value>,
+) {
+ let application_data = json!({"cache_control": cache, "nested": {"cache_control": cache}});
+ let body = json!({
+ "cache_control": cache,
+ "model": "native-test",
+ "system": [{"type": "text", "text": "system", "cache_control": cache}],
+ "tools": [{"name": "tool", "cache_control": cache, "input_schema": application_data}],
+ "messages": [{"role": "user", "content": [
+ {"type": "tool_use", "input": application_data, "cache_control": cache},
+ {"type": "tool_result", "content": [{"type": "text", "text": "result", "cache_control": cache}], "cache_control": cache},
+ ]}],
+ });
+ let hint = |value: Value| {
+ let fields = value.as_object().unwrap().clone();
+ Value::Object(
+ fields
+ .into_iter()
+ .chain(
+ expected_cache
+ .clone()
+ .map(|cache| ("cache_control".into(), cache)),
+ )
+ .collect(),
+ )
+ };
+ let expected = hint(json!({
+ "model": "native-test",
+ "system": [hint(json!({"type": "text", "text": "system"}))],
+ "tools": [hint(json!({"name": "tool", "input_schema": application_data}))],
+ "messages": [{"role": "user", "content": [
+ hint(json!({"type": "tool_use", "input": application_data})),
+ hint(json!({"type": "tool_result", "content": [hint(json!({"type": "text", "text": "result"}))]})),
+ ]}],
+ }));
+ assert_eq!(portable_cache_control(body), expected);
+}
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py
index d6c97b120c9..5395383f8bd 100644
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@ -5,6 +5,7 @@ import copy
import datetime
import functools
import json
+import math
import os
import re
import subprocess
@@ -732,6 +733,7 @@ class Logging(LiteLLMLoggingBaseClass):
# Initialize cost breakdown field
self.cost_breakdown: CostBreakdown | None = None
self.billed_token_rates: BilledTokenRates | None = None
+ self._provider_reported_cost: float | None = None
# Init Caching related details
self.caching_details: CachingDetails | None = None
@@ -1948,7 +1950,16 @@ class Logging(LiteLLMLoggingBaseClass):
return None
try:
- response_cost: Final = litellm.response_cost_calculator(**response_cost_calculator_kwargs)
+ reported_cost: Final = self._provider_reported_cost
+ response_cost: Final = (
+ reported_cost
+ if isinstance(reported_cost, float)
+ and math.isfinite(reported_cost)
+ and reported_cost >= 0
+ and not custom_pricing
+ and base_model is None
+ else litellm.response_cost_calculator(**response_cost_calculator_kwargs)
+ )
verbose_logger.debug("response_cost: %s", response_cost)
additional_response_cost: Final[object] = self.model_call_details.get("additional_response_cost")
diff --git a/tests/unit/litellm_core_utils/test_litellm_logging.py b/tests/unit/litellm_core_utils/test_litellm_logging.py
index 7dbb7cc3924..870378e93f6 100644
--- a/tests/unit/litellm_core_utils/test_litellm_logging.py
+++ b/tests/unit/litellm_core_utils/test_litellm_logging.py
@@ -4551,6 +4551,103 @@ def test_process_hidden_params_recalculates_cost_after_failure_handler_zero():
assert slo.get("response_cost", 0) > 0
[email protected]("reported_cost", [0.0, 0.37])
[email protected]("cache_hit", [False, True])
+def test_provider_reported_cost_reaches_metadata_and_spend(reported_cost: float, cache_hit: bool) -> None:
+ started: Final = datetime_standard_logging(2026, 1, 1)
+ logging_obj: Final = LitellmLogging(
+ model="native-test",
+ messages=[{"role": "user", "content": "test"}],
+ stream=False,
+ call_type="anthropic_messages",
+ start_time=started,
+ litellm_call_id="reported-cost",
+ function_id="reported-cost",
+ )
+ logging_obj.update_from_kwargs(kwargs={}, optional_params={})
+ logging_obj._provider_reported_cost = reported_cost
+ logging_obj.model_call_details.update({"cache_hit": cache_hit, "litellm_params": {}})
+ response: Final = ModelResponse(
+ id="reported-cost",
+ model="native-test",
+ choices=[{"message": {"role": "assistant", "content": "ok"}}],
+ )
+ expected: Final = 0.0 if cache_hit else reported_cost
+ assert logging_obj.response_cost_calculator(response) == expected
+ logging_obj._process_hidden_params_and_response_cost(response, started, started)
+ assert logging_obj.model_call_details["response_cost"] == expected
+ assert logging_obj.model_call_details["standard_logging_object"]["response_cost"] == expected
+
+
[email protected]("pricing_policy", ["reported", "custom", "base"])
[email protected]("reported_cost", [None, 0.0, 0.37])
[email protected]("additional_cost", [0.0, 0.12])
[email protected]("cache_hit", [False, True])
+def test_reported_cost_respects_configured_pricing_and_additional_charges(
+ monkeypatch: pytest.MonkeyPatch,
+ pricing_policy: Literal["reported", "custom", "base"],
+ reported_cost: float | None,
+ additional_cost: float,
+ cache_hit: bool,
+) -> None:
+ pricing_model: Final = "anthropic/reported-cost-pricing-test"
+ input_rate: Final = 0.002
+ output_rate: Final = 0.004
+ prompt_tokens: Final = 10
+ completion_tokens: Final = 5
+ monkeypatch.setitem(
+ litellm.model_cost,
+ pricing_model,
+ {"input_cost_per_token": input_rate, "output_cost_per_token": output_rate, "litellm_provider": "anthropic"},
+ )
+ started: Final = datetime_standard_logging(2026, 1, 1)
+ logging_obj: Final = LitellmLogging(
+ model=pricing_model,
+ messages=[{"role": "user", "content": "test"}],
+ stream=False,
+ call_type="anthropic_messages",
+ start_time=started,
+ litellm_call_id="reported-cost-pricing",
+ function_id="reported-cost-pricing",
+ )
+ logging_obj.update_from_kwargs(
+ kwargs={},
+ optional_params={"provider_reported_cost": 0.0, "_provider_reported_cost": 0.0},
+ litellm_params={
+ **({"base_model": pricing_model} if pricing_policy == "base" else {}),
+ "metadata": {
+ "model_info": {
+ "id": pricing_model,
+ **(
+ {"input_cost_per_token": input_rate, "output_cost_per_token": output_rate}
+ if pricing_policy == "custom"
+ else {}
+ ),
+ }
+ }
+ }
+ )
+ logging_obj.model_call_details.update(
+ {"additional_response_cost": additional_cost, "cache_hit": cache_hit}
+ )
+ logging_obj._provider_reported_cost = reported_cost
+ response: Final = ModelResponse(
+ model=pricing_model,
+ choices=[{"message": {"role": "assistant", "content": "ok"}}],
+ usage=Usage(prompt_tokens=prompt_tokens, completion_tokens=completion_tokens),
+ )
+ base_cost: Final = (
+ prompt_tokens * input_rate + completion_tokens * output_rate
+ if pricing_policy != "reported" or reported_cost is None
+ else reported_cost
+ )
+ expected: Final = 0.0 if cache_hit else base_cost + additional_cost
+ assert logging_obj.response_cost_calculator(response) == pytest.approx(expected)
+ logging_obj._process_hidden_params_and_response_cost(response, started, started)
+ assert logging_obj.model_call_details["response_cost"] == pytest.approx(expected)
+ assert logging_obj.model_call_details["standard_logging_object"]["response_cost"] == pytest.approx(expected)
+
+
def test_process_hidden_params_preserves_zero_cost_in_hidden_params():
"""Pass-through handlers often set response_cost on result._hidden_params (including 0)."""
from datetime import datetime