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] A2a gateway - Add cost per token pricing (#17780)

Ishaan Jaff49b91c4a3524
diff --git a/docs/my-website/docs/proxy/config_settings.md b/docs/my-website/docs/proxy/config_settings.md
index 52757b846d3..eefdab926c2 100644
--- a/docs/my-website/docs/proxy/config_settings.md
+++ b/docs/my-website/docs/proxy/config_settings.md
@@ -641,6 +641,7 @@ router_settings:
| LANGFUSE_PUBLIC_KEY | Public key for Langfuse authentication
| LANGFUSE_RELEASE | Release version of Langfuse integration
| LANGFUSE_SECRET_KEY | Secret key for Langfuse authentication
+| LANGFUSE_PROPAGATE_TRACE_ID | Flag to enable propagating trace ID to Langfuse. Default is False
| LANGSMITH_API_KEY | API key for Langsmith platform
| LANGSMITH_BASE_URL | Base URL for Langsmith service
| LANGSMITH_BATCH_SIZE | Batch size for operations in Langsmith
@@ -855,6 +856,8 @@ router_settings:
| WEBHOOK_URL | URL for receiving webhooks from external services
| SPEND_LOG_RUN_LOOPS | Constant for setting how many runs of 1000 batch deletes should spend_log_cleanup task run
| SPEND_LOG_CLEANUP_BATCH_SIZE | Number of logs deleted per batch during cleanup. Default is 1000
+| SPEND_LOG_QUEUE_POLL_INTERVAL | Polling interval in seconds for spend log queue. Default is 2.0
+| SPEND_LOG_QUEUE_SIZE_THRESHOLD | Threshold for spend log queue size before processing. Default is 100
| COROUTINE_CHECKER_MAX_SIZE_IN_MEMORY | Maximum size for CoroutineChecker in-memory cache. Default is 1000
| DEFAULT_SHARED_HEALTH_CHECK_TTL | Time-to-live in seconds for cached health check results in shared health check mode. Default is 300 (5 minutes)
| DEFAULT_SHARED_HEALTH_CHECK_LOCK_TTL | Time-to-live in seconds for health check lock in shared health check mode. Default is 60 (1 minute)
diff --git a/litellm/a2a_protocol/cost_calculator.py b/litellm/a2a_protocol/cost_calculator.py
index a701e575ac5..f3e84c5b84d 100644
--- a/litellm/a2a_protocol/cost_calculator.py
+++ b/litellm/a2a_protocol/cost_calculator.py
@@ -1,8 +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.
+Supports dynamic cost parameters that allow platform owners
+to define custom costs per agent query or per token.
"""
from typing import TYPE_CHECKING, Any, Optional
@@ -23,13 +23,15 @@ class A2ACostCalculator:
"""
Calculate the cost of an A2A send_message call.
- Supports cost_per_query parameter for platform owners to define
- custom costs per agent query.
+ Supports multiple cost parameters for platform owners:
+ - cost_per_query: Fixed cost per query
+ - input_cost_per_token + output_cost_per_token: Token-based pricing
Priority order:
1. response_cost - if set directly (backward compatibility)
- 2. cost_per_query - in litellm_params
- 3. Default to 0.0
+ 2. cost_per_query - fixed cost per query
+ 3. input_cost_per_token + output_cost_per_token - token-based cost
+ 4. Default to 0.0
Args:
litellm_logging_obj: The LiteLLM logging object containing call details
@@ -47,10 +49,55 @@ class A2ACostCalculator:
if response_cost is not None:
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:
+ # Get litellm_params for cost parameters
+ litellm_params = model_call_details.get("litellm_params", {}) or {}
+
+ # Check for cost_per_query (fixed cost per query)
+ if litellm_params.get("cost_per_query") is not None:
return float(litellm_params["cost_per_query"])
+ # Check for token-based pricing
+ input_cost_per_token = litellm_params.get("input_cost_per_token")
+ output_cost_per_token = litellm_params.get("output_cost_per_token")
+
+ if input_cost_per_token is not None or output_cost_per_token is not None:
+ return A2ACostCalculator._calculate_token_based_cost(
+ model_call_details=model_call_details,
+ input_cost_per_token=input_cost_per_token,
+ output_cost_per_token=output_cost_per_token,
+ )
+
# Default to 0.0 for A2A calls
return 0.0
+
+ @staticmethod
+ def _calculate_token_based_cost(
+ model_call_details: dict,
+ input_cost_per_token: Optional[float],
+ output_cost_per_token: Optional[float],
+ ) -> float:
+ """
+ Calculate cost based on token usage and per-token pricing.
+
+ Args:
+ model_call_details: The model call details containing usage
+ input_cost_per_token: Cost per input token (can be None, defaults to 0)
+ output_cost_per_token: Cost per output token (can be None, defaults to 0)
+
+ Returns:
+ float: The calculated cost
+ """
+ # Get usage from model_call_details
+ usage = model_call_details.get("usage")
+ if usage is None:
+ return 0.0
+
+ # Get token counts
+ prompt_tokens = getattr(usage, "prompt_tokens", 0) or 0
+ completion_tokens = getattr(usage, "completion_tokens", 0) or 0
+
+ # Calculate costs
+ input_cost = prompt_tokens * (float(input_cost_per_token) if input_cost_per_token else 0.0)
+ output_cost = completion_tokens * (float(output_cost_per_token) if output_cost_per_token else 0.0)
+
+ return input_cost + output_cost
diff --git a/tests/test_litellm/a2a_protocol/test_cost_calculator.py b/tests/test_litellm/a2a_protocol/test_cost_calculator.py
index 1c4f8a1f801..9f0948dc509 100644
--- a/tests/test_litellm/a2a_protocol/test_cost_calculator.py
+++ b/tests/test_litellm/a2a_protocol/test_cost_calculator.py
@@ -65,3 +65,102 @@ async def test_asend_message_uses_cost_per_query():
await asyncio.sleep(0.1)
assert cost_logger.response_cost == 0.05
+
+
+class TokenAndCostLogger(CustomLogger):
+ """Custom logger to capture both token counts and cost."""
+
+ def __init__(self):
+ self.response_cost: Optional[float] = None
+ self.prompt_tokens: Optional[int] = None
+ self.completion_tokens: Optional[int] = 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)
+ self.prompt_tokens = slp.get("prompt_tokens") if isinstance(slp, dict) else getattr(slp, "prompt_tokens", None)
+ self.completion_tokens = slp.get("completion_tokens") if isinstance(slp, dict) else getattr(slp, "completion_tokens", None)
+
+
+async def test_asend_message_uses_input_output_cost_per_token():
+ """
+ Test that asend_message calculates cost using input_cost_per_token and output_cost_per_token.
+ Validates exact cost calculation: cost = (prompt_tokens * input_cost) + (completion_tokens * output_cost)
+ """
+ from litellm.a2a_protocol import asend_message
+
+ # Setup logger
+ litellm.logging_callback_manager._reset_all_callbacks()
+ token_cost_logger = TokenAndCostLogger()
+ litellm.callbacks = [token_cost_logger]
+
+ # Mock A2A client
+ mock_client = MagicMock()
+ mock_client._litellm_agent_card = MagicMock()
+ mock_client._litellm_agent_card.name = "test-agent"
+
+ # Realistic A2A response with message parts
+ mock_response = MagicMock()
+ mock_response.model_dump = MagicMock(return_value={
+ "id": "test-123",
+ "jsonrpc": "2.0",
+ "result": {
+ "status": {"state": "completed"},
+ "message": {
+ "role": "assistant",
+ "parts": [{"kind": "text", "text": "Hello! I am your assistant. How can I help you today?"}],
+ "messageId": "msg-456",
+ }
+ },
+ })
+ mock_client.send_message = AsyncMock(return_value=mock_response)
+
+ # Mock request with message parts
+ mock_request = MagicMock()
+ mock_request.id = "test-123"
+ mock_request.params = MagicMock()
+ mock_request.params.message = {
+ "role": "user",
+ "parts": [{"kind": "text", "text": "Hello, what can you do?"}],
+ "messageId": "msg-123",
+ }
+
+ # Define specific cost per token values
+ input_cost_per_token = 0.00001 # $0.01 per 1000 tokens
+ output_cost_per_token = 0.00002 # $0.02 per 1000 tokens
+
+ await asend_message(
+ a2a_client=mock_client,
+ request=mock_request,
+ input_cost_per_token=input_cost_per_token,
+ output_cost_per_token=output_cost_per_token,
+ )
+
+ await asyncio.sleep(0.1)
+
+ # Get actual token counts from logger
+ prompt_tokens = token_cost_logger.prompt_tokens
+ completion_tokens = token_cost_logger.completion_tokens
+ response_cost = token_cost_logger.response_cost
+
+ print(f"\n=== Token-Based Cost Results ===")
+ print(f"prompt_tokens: {prompt_tokens}")
+ print(f"completion_tokens: {completion_tokens}")
+ print(f"input_cost_per_token: {input_cost_per_token}")
+ print(f"output_cost_per_token: {output_cost_per_token}")
+ print(f"response_cost: {response_cost}")
+
+ # Verify tokens were captured
+ assert prompt_tokens is not None, "prompt_tokens should be captured"
+ assert completion_tokens is not None, "completion_tokens should be captured"
+ assert response_cost is not None, "response_cost should be captured"
+
+ # Calculate expected cost
+ expected_cost = (prompt_tokens * input_cost_per_token) + (completion_tokens * output_cost_per_token)
+ print(f"expected_cost: {expected_cost}")
+
+ # Verify exact cost calculation
+ assert response_cost == expected_cost, f"response_cost {response_cost} should equal expected {expected_cost}"