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] Agent Gateway - Add cost per query for agent invocations (#17774)

Ishaan Jaff7a33579af6d3
diff --git a/litellm/a2a_protocol/cost_calculator.py b/litellm/a2a_protocol/cost_calculator.py
index 2d821bb9c3b..a701e575ac5 100644
--- a/litellm/a2a_protocol/cost_calculator.py
+++ b/litellm/a2a_protocol/cost_calculator.py
@@ -1,5 +1,8 @@
"""
Cost calculator for A2A (Agent-to-Agent) calls.
+
+Supports dynamic cost_per_query parameter that allows platform owners
+to define custom costs per agent query.
"""
from typing import TYPE_CHECKING, Any, Optional
@@ -20,17 +23,34 @@ class A2ACostCalculator:
"""
Calculate the cost of an A2A send_message call.
- Default is 0.0. In the future, users can configure cost per agent call.
+ Supports cost_per_query parameter for platform owners to define
+ custom costs per agent query.
+
+ Priority order:
+ 1. response_cost - if set directly (backward compatibility)
+ 2. cost_per_query - in litellm_params
+ 3. Default to 0.0
+
+ Args:
+ litellm_logging_obj: The LiteLLM logging object containing call details
+
+ Returns:
+ float: The cost of the A2A call
"""
if litellm_logging_obj is None:
return 0.0
- # Check if user set a custom response cost
- response_cost = litellm_logging_obj.model_call_details.get(
- "response_cost", None
- )
+ model_call_details = litellm_logging_obj.model_call_details
+
+ # Check if user set a custom response cost (backward compatibility)
+ response_cost = model_call_details.get("response_cost", None)
if response_cost is not None:
- return response_cost
+ return float(response_cost)
+
+ # Check for cost_per_query in litellm_params (standard location for cost params)
+ litellm_params = model_call_details.get("litellm_params", {})
+ if litellm_params and litellm_params.get("cost_per_query") is not None:
+ return float(litellm_params["cost_per_query"])
# Default to 0.0 for A2A calls
return 0.0
diff --git a/litellm/litellm_core_utils/get_litellm_params.py b/litellm/litellm_core_utils/get_litellm_params.py
index 4dcc08e284e..0d35cfa3140 100644
--- a/litellm/litellm_core_utils/get_litellm_params.py
+++ b/litellm/litellm_core_utils/get_litellm_params.py
@@ -42,6 +42,7 @@ def get_litellm_params(
input_cost_per_token=None,
output_cost_per_token=None,
output_cost_per_second=None,
+ cost_per_query=None,
cooldown_time=None,
text_completion=None,
azure_ad_token_provider=None,
@@ -87,6 +88,7 @@ def get_litellm_params(
"input_cost_per_second": input_cost_per_second,
"output_cost_per_token": output_cost_per_token,
"output_cost_per_second": output_cost_per_second,
+ "cost_per_query": cost_per_query,
"cooldown_time": cooldown_time,
"text_completion": text_completion,
"azure_ad_token_provider": azure_ad_token_provider,
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 4d1a34f49c4..8c8f3b3ddf2 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -170,8 +170,8 @@ from litellm.constants import (
PROXY_BUDGET_RESCHEDULER_MIN_TIME,
)
from litellm.exceptions import RejectedRequestError
-from litellm.integrations.custom_logger import CustomLogger
from litellm.integrations.custom_guardrail import ModifyResponseException
+from litellm.integrations.custom_logger import CustomLogger
from litellm.integrations.SlackAlerting.slack_alerting import SlackAlerting
from litellm.litellm_core_utils.core_helpers import (
_get_parent_otel_span_from_kwargs,
@@ -1085,11 +1085,12 @@ def mount_swagger_ui():
mount_swagger_ui()
docs_url = _get_docs_url()
-root_redirect_url = os.getenv("ROOT_REDIRECT_URL")
-if docs_url != "/" and root_redirect_url:
+root_redirect_url: Optional[str] = os.getenv("ROOT_REDIRECT_URL")
+if docs_url != "/" and root_redirect_url is not None:
+
@app.get("/", include_in_schema=False)
async def root_redirect():
- return RedirectResponse(url=root_redirect_url)
+ return RedirectResponse(url=root_redirect_url) # type: ignore[arg-type]
from typing import Dict
@@ -4439,7 +4440,7 @@ class ProxyStartupEvent:
### MONITOR SPEND LOGS QUEUE (queue-size-based job) ###
if general_settings.get("disable_spend_logs", False) is False:
from litellm.proxy.utils import _monitor_spend_logs_queue
-
+
# Start background task to monitor spend logs queue size
asyncio.create_task(
_monitor_spend_logs_queue(
@@ -4485,63 +4486,12 @@ class ProxyStartupEvent:
misfire_grace_time=APSCHEDULER_MISFIRE_GRACE_TIME,
)
await proxy_config.get_credentials(prisma_client=prisma_client)
- if (
- proxy_logging_obj is not None
- and proxy_logging_obj.slack_alerting_instance.alerting is not None
- and prisma_client is not None
- ):
- print("Alerting: Initializing Weekly/Monthly Spend Reports") # noqa
- ### Schedule weekly/monthly spend reports ###
- ### Schedule spend reports ###
- spend_report_frequency: str = (
- general_settings.get("spend_report_frequency", "7d") or "7d"
- )
-
- # Parse the frequency
- days = int(spend_report_frequency[:-1])
- if spend_report_frequency[-1].lower() != "d":
- raise ValueError(
- "spend_report_frequency must be specified in days, e.g., '1d', '7d'"
- )
-
- scheduler.add_job(
- proxy_logging_obj.slack_alerting_instance.send_weekly_spend_report,
- "interval",
- days=days,
- # REMOVED jitter parameter - major cause of memory leak
- # Use random start time instead for distribution
- next_run_time=datetime.now()
- + timedelta(
- seconds=10 + random.randint(0, 300)
- ), # Random 0-5 min offset
- args=[spend_report_frequency],
- id="weekly_spend_report_job",
- replace_existing=True,
- misfire_grace_time=APSCHEDULER_MISFIRE_GRACE_TIME,
- )
-
- scheduler.add_job(
- proxy_logging_obj.slack_alerting_instance.send_monthly_spend_report,
- "cron",
- day=1,
- id="monthly_spend_report_job",
- replace_existing=True,
- )
-
- # Beta Feature - only used when prometheus api is in .env
- if os.getenv("PROMETHEUS_URL"):
- from zoneinfo import ZoneInfo
-
- scheduler.add_job(
- proxy_logging_obj.slack_alerting_instance.send_fallback_stats_from_prometheus,
- "cron",
- hour=PROMETHEUS_FALLBACK_STATS_SEND_TIME_HOURS,
- minute=0,
- timezone=ZoneInfo("America/Los_Angeles"), # Pacific Time
- id="prometheus_fallback_stats_job",
- replace_existing=True,
- )
- await proxy_logging_obj.slack_alerting_instance.send_fallback_stats_from_prometheus()
+ await cls._initialize_slack_alerting_jobs(
+ scheduler=scheduler,
+ general_settings=general_settings,
+ proxy_logging_obj=proxy_logging_obj,
+ prisma_client=prisma_client,
+ )
await cls._initialize_spend_tracking_background_jobs(scheduler=scheduler)
@@ -4681,6 +4631,65 @@ class ProxyStartupEvent:
"Key rotation disabled (set LITELLM_KEY_ROTATION_ENABLED=true to enable)"
)
+ @classmethod
+ async def _initialize_slack_alerting_jobs(
+ cls,
+ scheduler: AsyncIOScheduler,
+ general_settings: dict,
+ proxy_logging_obj: ProxyLogging,
+ prisma_client: PrismaClient,
+ ):
+ """Initialize Slack alerting background jobs for spend reports."""
+ if (
+ proxy_logging_obj is not None
+ and proxy_logging_obj.slack_alerting_instance.alerting is not None
+ and prisma_client is not None
+ ):
+ print("Alerting: Initializing Weekly/Monthly Spend Reports") # noqa
+ spend_report_frequency: str = (
+ general_settings.get("spend_report_frequency", "7d") or "7d"
+ )
+
+ days = int(spend_report_frequency[:-1])
+ if spend_report_frequency[-1].lower() != "d":
+ raise ValueError(
+ "spend_report_frequency must be specified in days, e.g., '1d', '7d'"
+ )
+
+ scheduler.add_job(
+ proxy_logging_obj.slack_alerting_instance.send_weekly_spend_report,
+ "interval",
+ days=days,
+ next_run_time=datetime.now()
+ + timedelta(seconds=10 + random.randint(0, 300)),
+ args=[spend_report_frequency],
+ id="weekly_spend_report_job",
+ replace_existing=True,
+ misfire_grace_time=APSCHEDULER_MISFIRE_GRACE_TIME,
+ )
+
+ scheduler.add_job(
+ proxy_logging_obj.slack_alerting_instance.send_monthly_spend_report,
+ "cron",
+ day=1,
+ id="monthly_spend_report_job",
+ replace_existing=True,
+ )
+
+ if os.getenv("PROMETHEUS_URL"):
+ from zoneinfo import ZoneInfo
+
+ scheduler.add_job(
+ proxy_logging_obj.slack_alerting_instance.send_fallback_stats_from_prometheus,
+ "cron",
+ hour=PROMETHEUS_FALLBACK_STATS_SEND_TIME_HOURS,
+ minute=0,
+ timezone=ZoneInfo("America/Los_Angeles"),
+ id="prometheus_fallback_stats_job",
+ replace_existing=True,
+ )
+ await proxy_logging_obj.slack_alerting_instance.send_fallback_stats_from_prometheus()
+
@classmethod
async def _setup_prisma_client(
cls,
@@ -5123,14 +5132,14 @@ async def completion( # noqa: PLR0915
if _data.get("stream", None) is not None and _data["stream"] is True:
_text_response = litellm.ModelResponse()
- _text_response.choices[0].text = e.message
- _text_response.model = e.model # type: ignore
+ _text_response.choices[0].text = e.message # type: ignore[attr-defined]
+ _text_response.model = e.model # type: ignore[assignment]
_usage = litellm.Usage(
prompt_tokens=0,
completion_tokens=0,
total_tokens=0,
)
- _text_response.usage = _usage # type: ignore
+ _text_response.usage = _usage # type: ignore[assignment]
_iterator = litellm.utils.ModelResponseIterator(
model_response=_text_response, convert_to_delta=True
)
diff --git a/tests/test_litellm/a2a_protocol/test_cost_calculator.py b/tests/test_litellm/a2a_protocol/test_cost_calculator.py
new file mode 100644
index 00000000000..1c4f8a1f801
--- /dev/null
+++ b/tests/test_litellm/a2a_protocol/test_cost_calculator.py
@@ -0,0 +1,67 @@
+"""
+Test A2A cost calculator with cost_per_query parameter.
+"""
+
+import asyncio
+from typing import Optional
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+import litellm
+from litellm.integrations.custom_logger import CustomLogger
+
+
+class CostLogger(CustomLogger):
+ """Custom logger to capture response_cost."""
+
+ def __init__(self):
+ self.response_cost: Optional[float] = None
+ super().__init__()
+
+ async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
+ slp = kwargs.get("standard_logging_object")
+ if slp:
+ self.response_cost = slp.get("response_cost") if isinstance(slp, dict) else getattr(slp, "response_cost", None)
+
+
+async def test_asend_message_uses_cost_per_query():
+ """
+ Test that asend_message uses cost_per_query param for response_cost.
+ """
+ from litellm.a2a_protocol import asend_message
+
+ # Setup logger
+ litellm.logging_callback_manager._reset_all_callbacks()
+ cost_logger = CostLogger()
+ litellm.callbacks = [cost_logger]
+
+ # Mock A2A client
+ mock_client = MagicMock()
+ mock_client._litellm_agent_card = MagicMock()
+ mock_client._litellm_agent_card.name = "test-agent"
+
+ # Mock response with required fields
+ mock_response = MagicMock()
+ mock_response.model_dump = MagicMock(return_value={
+ "id": "test-123",
+ "jsonrpc": "2.0",
+ "result": {"status": "completed"},
+ })
+ mock_client.send_message = AsyncMock(return_value=mock_response)
+
+ # Mock request
+ mock_request = MagicMock()
+ mock_request.id = "test-123"
+
+ # Call asend_message with cost_per_query
+ await asend_message(
+ a2a_client=mock_client,
+ request=mock_request,
+ cost_per_query=0.05,
+ )
+
+ await asyncio.sleep(0.1)
+
+ assert cost_logger.response_cost == 0.05