litellm/tests/unit/proxy/test_route_a2a_models.py
quietjules 7e646ab4c9
fix(a2a): bill chat route agent calls at the agent's own price (#51808)
* fix(a2a): bill chat route agent calls at the agent's own price

* fix(a2a): name the agent's model group on /v1/responses and /v1/messages spend rows

* fix(a2a): bill chat route agents with the proxy's margins and keep streamed and failed calls on the agent's row

The agent's price now goes through cost_discount_config and cost_margin_config like other chat calls, a price
that is not a number leaves the cost unset instead of failing the call, and pricing keys agent billing ignores
log one warning per agent. model_group goes only on the proxy's own metadata, so /v1/responses no longer echoes
it back to the caller

A Databricks agent that answers a stream request with one JSON body now finishes the stream with its text and
usage, so the streamed call writes the same spend row as a plain one. A failed agent call's spend row now names
the agent it was billed to

* fix(a2a): name the agent on failed calls' spend rows and report a token-priced agent's input and output cost

A failed agent call's spend row now names the agent on the proxy's real failure path. The agent id is lifted off the
logging object with the other failure fields, before the proxy drops that object, so the row no longer says
agent_id null

A token-priced agent's cost breakdown now carries its input and output cost, and a per-query agent's leaves both out,
so the response cost headers and the OpenTelemetry span stop reporting 0 for them. A malformed cost_margin_config or
cost_discount_config now leaves an agent call's cost unset instead of failing the call with a 500

The tests now also check the streamed reply text and the additional_response_cost an agent call adds, and the
warn-once test no longer depends on which test warned first

* fix(a2a): leave an agent call's cost unset for a cost config of any wrong shape

A cost_discount_config or cost_margin_config of the wrong shape, such as a list, now leaves an agent call's cost
unset and the call still answers, the way a model call with the same config does. Before, only a value that was
not a number did, and a list failed the call with a 500

The tests now also check that a per-query agent sends no input or output cost header and that a non-finite agent
price puts no NaN into the cost headers

* fix(a2a): bill only cost_per_query through the agent path and keep model calls' own pricing, retries and overrides

The chat route now bills an agent's cost_per_query through the agent path for bridge and URL agents alike, with the
proxy's discount, margin and additional_response_cost. Every other agent price goes through the normal per-call
pricing, as it did before this PR, so per-second, tiered and cache-read prices bill again and an unpriced agent bills
nothing instead of the fixed margin

A request that carries an allowed client price skips the agent path, so the caller's override wins as it did before.
URL agents get their per-query price, their other prices through per-call pricing, and agent_id on their spend rows

The route no longer stamps a model group, so SDK retries and context-window fallbacks run for agent calls again and
model_max_budget is untouched. The whole-JSON branch in the Databricks agent stream parser is reverted, since real
agent streams are SSE events

* fix(a2a): bill an agent's fallback at the fallback model's price, honor allowed base_model overrides, and name the agent on OAuth failures

A fallback model that answers an a2a/<agent> chat call bills at its own price and no longer carries the agent's agent_id
A caller allowed to set base_model gets that price instead of the agent's cost_per_query
A Databricks OAuth token failure now writes the agent's agent_id on the failure row

* fix(a2a): bill each fallback at its own price and keep failed requests on the agent's row

URL agents now get the agent's own token price for every price key the caller left unset, the same way bridge agents do. Before, any caller price or allowed base_model dropped all of the agent's prices on URL agents only

A fallback model that answers an agent request is billed at its own price. The agent's token prices no longer ride into the fallback attempts, for bridge and URL agents alike

When the agent and every fallback fail, the failure row keeps the agent's id, so the failed request stays on the agent's spend row

* fix(a2a): leave a request a fallback answered off the agent's failure row

When the agent failed and a fallback model answered, a later proxy failure still wrote the agent's id on the failure row. A post-call guardrail that rejects the fallback's answer, or a fallback stream that breaks part way, then charged the agent with a failed request it never served

The fallback loop now stops attributing the call to the agent once a fallback answers, so only a request no fallback answered stays on the agent's row

* fix(a2a): keep billing an agent that answers its own fallback retry

A fallback that calls the same model again, such as a dict fallback with no model key, is a retry of the agent. It now keeps the agent's per-query price and agent id, where it used to bill nothing and drop the agent from both rows

Main's fallback loop already drops every price param when the model changes, so the agent's price keys no longer need their own list on the logging object

* fix(a2a): restore an agent's price on its own fallback retry and honor a caller's per-second price

* fix(a2a): keep the caller's agent on spend rows and the agent url in api_base

A caller that already names its own agent (a key owned by an agent, the
x-litellm-agent-id header, or a managed agent) keeps that agent on the spend
row of an a2a/<agent> chat call. Only calls with no caller agent are
attributed to the called agent.

A URL agent call writes the agent's url into the request's api_base again,
so post-call hooks and guardrails read it as they did before. The agent's
prices still go only into the inner call.

A per-query price that is negative, nan or inf leaves the cost unset, the
same check a managed agent's price gets.

* chore(a2a): correct the pricing error suppression reason

* fix(a2a): leave an agent's non-numeric token price unbilled instead of failing the call

A chat route call to an A2A agent whose token price is text, such as
input_cost_per_token: "abc", now answers and bills the agent's other prices.
The text price is dropped with a warning naming it, where before the call
failed with a 500

---------

Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
2026-11-26 05:44:54 +00:00

1423 lines
56 KiB
Python

"""
Test A2A model routing in proxy.
Maps to: litellm/proxy/agent_endpoints/a2a_routing.py
"""
import asyncio
import base64
import datetime
import json
import math
import time
from collections.abc import Iterator, Mapping
from types import MappingProxyType
from typing import Final
from unittest.mock import AsyncMock, Mock, patch
from tests.unit.proxy.router_entry_point_stubs import route_entry_points_to_stubs
import httpx
import pytest
import respx
from fastapi import HTTPException
import litellm
from litellm.integrations.custom_logger import CustomLogger
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.litellm_core_utils.streaming_handler import CustomStreamWrapper
from litellm.proxy._types import SpendLogsPayload
from litellm.proxy.agent_endpoints.a2a_routing import route_a2a_agent_request
from litellm.proxy.agent_endpoints.agent_registry import AgentRegistry
from litellm.proxy.agent_endpoints.databricks_oauth import databricks_app_oauth_token_cache
from litellm.proxy.common_request_processing import cost_headers
from litellm.proxy.route_llm_request import route_request
from litellm.proxy.spend_tracking.spend_tracking_utils import get_logging_payload
from litellm.proxy.utils import _failure_fields_to_lift
from litellm.types.agents import AgentResponse
from litellm.types.utils import ModelResponse
@pytest.mark.asyncio
async def test_route_a2a_model_bypasses_router():
"""Test that a2a/ prefixed models bypass router and go directly to litellm with api_base"""
# Mock data for chat completion with a2a model
data = {
"model": "a2a/test-agent",
"messages": [{"role": "user", "content": "Hello"}],
}
# Mock router that doesn't have the a2a model
mock_router = route_entry_points_to_stubs(Mock())
mock_router.model_names = ["gpt-4", "gpt-3.5-turbo"]
mock_router.deployment_names = []
mock_router.has_model_id = Mock(return_value=False)
mock_router.is_recognized_model = Mock(return_value=False)
mock_router.model_group_alias = None
mock_router.router_general_settings = Mock(pass_through_all_models=False)
mock_router.default_deployment = None
mock_router.pattern_router = Mock(patterns=[])
mock_router.map_team_model = Mock(return_value=None)
# Mock agent in registry
from litellm.types.agents import AgentResponse
mock_agent = AgentResponse(
agent_id="test-agent-id",
agent_name="test-agent",
agent_card_params={"url": "http://agent.example.com"},
litellm_params=None,
)
mock_registry = Mock()
mock_registry.get_agent_by_id = Mock(return_value=None)
mock_registry.get_agent_by_name = Mock(return_value=mock_agent)
# Mock litellm.acompletion to verify it's called
mock_acompletion = AsyncMock(return_value={"id": "test-response"})
with patch("litellm.acompletion", mock_acompletion):
with patch(
"litellm.proxy.agent_endpoints.agent_registry.global_agent_registry",
mock_registry,
):
result = await route_request(
data=data,
llm_router=mock_router,
user_model=None,
route_type="acompletion",
)
# Verify litellm.acompletion was called with api_base injected
mock_acompletion.assert_called_once()
call_kwargs = mock_acompletion.call_args.kwargs
assert call_kwargs["model"] == "a2a/test-agent"
assert call_kwargs["api_base"] == "http://agent.example.com"
@pytest.mark.asyncio
async def test_route_non_a2a_model_raises_error_if_not_in_router():
"""Test that non-a2a models that aren't in router raise an error"""
# Mock data for chat completion with model not in router
data = {
"model": "unknown-model",
"messages": [{"role": "user", "content": "Hello"}],
}
# Mock router without the model
mock_router = route_entry_points_to_stubs(Mock())
mock_router.model_names = ["gpt-4", "gpt-3.5-turbo"]
mock_router.deployment_names = []
mock_router.has_model_id = Mock(return_value=False)
mock_router.is_recognized_model = Mock(return_value=False)
mock_router.model_group_alias = None
mock_router.router_general_settings = Mock(pass_through_all_models=False)
mock_router.default_deployment = None
mock_router.pattern_router = Mock(patterns=[])
mock_router.map_team_model = Mock(return_value=None)
# Should raise ProxyModelNotFoundError
from litellm.proxy.route_llm_request import ProxyModelNotFoundError
with pytest.raises(ProxyModelNotFoundError):
await route_request(
data=data,
llm_router=mock_router,
user_model=None,
route_type="acompletion",
)
class _DbAgentRow:
def __init__(self, agent_id: str, agent_name: str) -> None:
self.agent_id = agent_id
self.agent_name = agent_name
self.object_permission = None
self.spend = 0.0
def model_dump(self):
return {
"agent_id": self.agent_id,
"agent_name": self.agent_name,
"agent_card_params": {"name": self.agent_name, "url": "http://sibling-db-agent.example.com"},
"litellm_params": {},
"object_permission": None,
"spend": self.spend,
}
def _router_without_models():
mock_router = route_entry_points_to_stubs(Mock())
mock_router.model_names = []
mock_router.deployment_names = []
mock_router.has_model_id = Mock(return_value=False)
mock_router.model_group_alias = None
mock_router.router_general_settings = Mock(pass_through_all_models=False)
mock_router.default_deployment = None
mock_router.pattern_router = Mock(patterns=[])
mock_router.map_team_model = Mock(return_value=None)
mock_router.is_recognized_model = Mock(return_value=False)
mock_router.team_public_model_names = []
return mock_router
@pytest.mark.asyncio
async def test_route_a2a_model_read_through_recovers_agent_created_on_sibling_replica(monkeypatch):
import litellm.proxy.proxy_server as proxy_server
from litellm.proxy.agent_endpoints.agent_registry import global_agent_registry
agent_name = "a2a-sibling-replica-agent"
prisma_client = Mock()
prisma_client.db.litellm_agentstable.find_unique = AsyncMock(
side_effect=[None, _DbAgentRow("a2a-sibling-replica-agent-id", agent_name)]
)
prisma_client.writer_db.litellm_agentstable.find_unique = AsyncMock(
return_value=_DbAgentRow("a2a-sibling-replica-agent-id", agent_name)
)
monkeypatch.setattr(proxy_server, "prisma_client", prisma_client)
monkeypatch.setattr(proxy_server, "store_model_in_db", True)
original_agents = list(global_agent_registry.agent_list)
original_config_agents = getattr(global_agent_registry, "config_agents", ())
global_agent_registry.agent_list = []
global_agent_registry.config_agents = ()
data = {
"model": f"a2a/{agent_name}",
"messages": [{"role": "user", "content": "Hello"}],
}
mock_acompletion = AsyncMock(return_value={"id": "read-through-response"})
try:
with patch("litellm.acompletion", mock_acompletion):
await route_request(
data=data,
llm_router=_router_without_models(),
user_model=None,
route_type="acompletion",
)
finally:
global_agent_registry.agent_list = original_agents
global_agent_registry.config_agents = original_config_agents
mock_acompletion.assert_called_once()
call_kwargs = mock_acompletion.call_args.kwargs
assert call_kwargs["model"] == f"a2a/{agent_name}"
assert call_kwargs["api_base"] == "http://sibling-db-agent.example.com"
prisma_client.db.litellm_agentstable.find_unique.assert_awaited()
WORKSPACE = "https://adb-1.azuredatabricks.net"
APP_URL = "https://my-app-1.azure.databricksapps.com/responses"
AGENT_REPLY = {
"output": [
{"type": "message", "id": "msg_1", "role": "assistant", "content": [{"type": "output_text", "text": "pong"}]}
]
}
A2A_REPLY = {
"jsonrpc": "2.0",
"id": "1",
"result": {"kind": "message", "role": "agent", "messageId": "m-1", "parts": [{"kind": "text", "text": "pong"}]},
}
@pytest.fixture
def httpx_transport(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
databricks_app_oauth_token_cache.flush_cache()
yield
databricks_app_oauth_token_cache.flush_cache()
def _registry_with(agent: AgentResponse) -> AgentRegistry:
registry = AgentRegistry()
registry.register_agent(agent)
return registry
def _token_route(workspace: str) -> respx.Route:
return respx.post(f"{workspace}/oidc/v1/token").mock(
return_value=httpx.Response(200, json={"access_token": "minted-oauth", "expires_in": 3600})
)
@respx.mock
async def test_route_a2a_bridge_agent_calls_the_endpoint_with_the_agent_params(httpx_transport: None) -> None:
agent = AgentResponse(
agent_id="dbx-agent-id",
agent_name="dbx-agent",
agent_card_params={"url": WORKSPACE},
litellm_params={
"custom_llm_provider": "databricks_agent",
"model": "my-agent",
"api_base": WORKSPACE,
"api_key": "pat-1",
"custom_inputs": {"tenant": "t-1"},
"is_public": True,
},
)
endpoint = respx.post(f"{WORKSPACE}/serving-endpoints/my-agent/invocations").mock(
return_value=httpx.Response(200, json=AGENT_REPLY)
)
data = {"model": "a2a/dbx-agent", "messages": [{"role": "user", "content": "ping"}]}
with patch("litellm.proxy.agent_endpoints.agent_registry.global_agent_registry", _registry_with(agent)):
response = await (await route_a2a_agent_request(data=data, route_type="acompletion"))
sent = endpoint.calls.last.request
assert sent.headers["Authorization"] == "Bearer pat-1"
assert json.loads(sent.content) == {
"input": [{"role": "user", "content": "ping"}],
"custom_inputs": {"tenant": "t-1"},
}
assert response.choices[0].message.content == "pong"
@respx.mock
async def test_route_a2a_bridge_agent_merges_client_static_and_agent_extra_headers(httpx_transport: None) -> None:
agent = AgentResponse(
agent_id="dbx-agent-id",
agent_name="dbx-agent",
agent_card_params={"url": WORKSPACE},
static_headers={"X-Static": "static", "x-shared": "from-static", "X-Both": "from-static"},
litellm_params={
"custom_llm_provider": "databricks_agent",
"model": "my-agent",
"api_base": WORKSPACE,
"api_key": "pat-1",
"extra_headers": {"X-Agent": "agent", "x-both": "from-agent"},
},
)
endpoint = respx.post(f"{WORKSPACE}/serving-endpoints/my-agent/invocations").mock(
return_value=httpx.Response(200, json=AGENT_REPLY)
)
data = {
"model": "a2a/dbx-agent",
"messages": [{"role": "user", "content": "ping"}],
"extra_headers": {"X-Trace": "trace-1", "X-Shared": "from-client", "X-LiteLLM-User-Id": "spoofed-user"},
}
with patch("litellm.proxy.agent_endpoints.agent_registry.global_agent_registry", _registry_with(agent)):
await (await route_a2a_agent_request(data=data, route_type="acompletion"))
sent = endpoint.calls.last.request
assert "X-LiteLLM-User-Id" not in sent.headers
assert sent.headers["X-Trace"] == "trace-1"
assert sent.headers["X-Static"] == "static"
assert sent.headers["X-Agent"] == "agent"
assert sent.headers.get_list("X-Shared") == ["from-static"]
assert sent.headers.get_list("X-Both") == ["from-agent"]
assert sent.headers["Authorization"] == "Bearer pat-1"
async def test_route_a2a_bridge_agent_lets_the_request_win_except_for_the_agent_credentials() -> None:
agent = AgentResponse(
agent_id="dbx-agent-id",
agent_name="dbx-agent",
agent_card_params={"url": WORKSPACE},
litellm_params={
"custom_llm_provider": "databricks_agent",
"model": "my-agent",
"api_base": WORKSPACE,
"api_key": "pat-1",
"metadata": {"tags": ["agent-tag"]},
"custom_inputs": {"tenant": "t-1"},
"timeout": 30,
},
)
proxy_metadata = {"user_api_key_hash": "key-hash", "user_api_key_team_id": "team-1"}
data = {
"model": "a2a/dbx-agent",
"messages": [{"role": "user", "content": "ping"}],
"metadata": proxy_metadata,
"api_base": "https://elsewhere.example.com",
"api_key": "client-key",
}
completion = Mock(return_value="reply")
with (
patch("litellm.proxy.agent_endpoints.agent_registry.global_agent_registry", _registry_with(agent)),
patch.object(litellm, "acompletion", completion),
):
await route_a2a_agent_request(data=data, route_type="acompletion")
sent = completion.call_args.kwargs
assert sent["metadata"] == proxy_metadata
assert (sent["api_base"], sent["api_key"]) == (WORKSPACE, "pat-1")
assert (sent["custom_inputs"], sent["timeout"]) == ({"tenant": "t-1"}, 30)
assert sent["model"] == "databricks_agent/my-agent"
@respx.mock
async def test_route_a2a_bridge_agent_keeps_its_custom_inputs_and_extra_body_keys_over_the_callers(
httpx_transport: None,
) -> None:
agent = AgentResponse(
agent_id="dbx-agent-id",
agent_name="dbx-agent",
agent_card_params={"url": WORKSPACE},
litellm_params={
"custom_llm_provider": "databricks_agent",
"model": "my-agent",
"api_base": WORKSPACE,
"api_key": "pat-1",
"custom_inputs": {"tenant": "owner"},
"extra_body": {"metadata": {"tenant": "owner"}},
},
)
endpoint = respx.post(f"{WORKSPACE}/serving-endpoints/my-agent/invocations").mock(
return_value=httpx.Response(200, json=AGENT_REPLY)
)
data = {
"model": "a2a/dbx-agent",
"messages": [{"role": "user", "content": "ping"}],
"custom_inputs": {"tenant": "caller", "session": "s-1"},
"extra_body": {"metadata": {"tenant": "caller", "turn": "2"}},
}
with patch("litellm.proxy.agent_endpoints.agent_registry.global_agent_registry", _registry_with(agent)):
await (await route_a2a_agent_request(data=data, route_type="acompletion"))
assert json.loads(endpoint.calls.last.request.content) == {
"input": [{"role": "user", "content": "ping"}],
"custom_inputs": {"tenant": "owner", "session": "s-1"},
"metadata": {"tenant": "owner", "turn": "2"},
}
@respx.mock
async def test_route_a2a_bridge_agent_with_an_empty_oauth_block_fails_before_calling_the_app(
httpx_transport: None,
) -> None:
agent = AgentResponse(
agent_id="dbx-app-id",
agent_name="dbx-app",
agent_card_params={"url": APP_URL},
litellm_params={"custom_llm_provider": "databricks_agent", "databricks_oauth": {}},
)
app = respx.post(APP_URL).mock(return_value=httpx.Response(200, json=AGENT_REPLY))
data = {"model": "a2a/dbx-app", "messages": [{"role": "user", "content": "ping"}]}
with patch("litellm.proxy.agent_endpoints.agent_registry.global_agent_registry", _registry_with(agent)):
with pytest.raises(litellm.BadRequestError, match="missing required field") as info:
await route_a2a_agent_request(data=data, route_type="acompletion")
assert info.value.status_code == 400
assert not app.called
@respx.mock
@pytest.mark.parametrize(
"oauth_params",
[
{"databricks_oauth": {"client_id": "sp", "client_secret": "s", "workspace_url": WORKSPACE}},
{"client_id": "sp", "client_secret": "s", "workspace_url": WORKSPACE, "scope": "all-apis"},
],
)
async def test_route_a2a_bridge_agent_with_databricks_oauth_sends_the_minted_token(
httpx_transport: None, oauth_params: dict[str, object]
) -> None:
agent = AgentResponse(
agent_id="dbx-app-id",
agent_name="dbx-app",
agent_card_params={"url": APP_URL},
litellm_params={"custom_llm_provider": "databricks_agent", **oauth_params},
)
token = _token_route(WORKSPACE)
app = respx.post(APP_URL).mock(return_value=httpx.Response(200, json=AGENT_REPLY))
data = {
"model": "a2a/dbx-app",
"messages": [{"role": "user", "content": "ping"}],
"extra_headers": {"X-Tenant": "t"},
}
with patch("litellm.proxy.agent_endpoints.agent_registry.global_agent_registry", _registry_with(agent)):
response = await (await route_a2a_agent_request(data=data, route_type="acompletion"))
assert token.calls.last.request.headers["Authorization"] == f"Basic {base64.b64encode(b'sp:s').decode()}"
sent = app.calls.last.request
assert sent.headers["Authorization"] == "Bearer minted-oauth"
assert sent.headers["X-Tenant"] == "t"
assert json.loads(sent.content) == {"input": [{"role": "user", "content": "ping"}]}
assert response.choices[0].message.content == "pong"
@respx.mock
@pytest.mark.parametrize(
"oauth_block",
[
{"client_id": "sp", "client_secret": "s", "workspace_url": WORKSPACE},
{"client_id": "sp"},
"not-a-mapping",
{"client_id": "sp", "client_secret": "s", "workspace_url": "https://my-app-1.azure.databricksapps.com"},
],
ids=["complete", "partial", "not-a-mapping", "app-host-as-workspace"],
)
async def test_route_a2a_url_agent_chat_keeps_the_client_authorization_over_its_databricks_oauth(
httpx_transport: None, oauth_block: object
) -> None:
agent_url = "https://my-a2a-app.azure.databricksapps.com"
agent = AgentResponse(
agent_id="a2a-app-id",
agent_name="a2a-app",
agent_card_params={"url": agent_url},
litellm_params={"databricks_oauth": oauth_block},
)
token = _token_route(WORKSPACE)
app = respx.post(agent_url).mock(return_value=httpx.Response(200, json=A2A_REPLY))
data = {
"model": "a2a/a2a-app",
"messages": [{"role": "user", "content": "ping"}],
"extra_headers": {"Authorization": "Bearer client-token"},
}
with patch("litellm.proxy.agent_endpoints.agent_registry.global_agent_registry", _registry_with(agent)):
response = await (await route_a2a_agent_request(data=data, route_type="acompletion"))
sent = app.calls.last.request
assert sent.headers["Authorization"] == "Bearer client-token"
assert json.loads(sent.content)["method"] == "message/send"
assert not token.called
assert response.choices[0].message.content == "pong"
@respx.mock
async def test_route_a2a_agent_with_another_provider_keeps_calling_its_card_url_over_a2a(
httpx_transport: None,
) -> None:
agent_url = "https://pydantic-agent.example.com"
agent = AgentResponse(
agent_id="pydantic-agent-id",
agent_name="pydantic-agent",
agent_card_params={"url": agent_url},
litellm_params={"custom_llm_provider": "pydantic_ai_agents", "model": "pydantic-agent"},
)
agent_endpoint = respx.post(agent_url).mock(return_value=httpx.Response(200, json=A2A_REPLY))
data = {"model": "a2a/pydantic-agent", "messages": [{"role": "user", "content": "ping"}]}
with patch("litellm.proxy.agent_endpoints.agent_registry.global_agent_registry", _registry_with(agent)):
response = await (await route_a2a_agent_request(data=data, route_type="acompletion"))
assert json.loads(agent_endpoint.calls.last.request.content)["method"] == "message/send"
assert response.choices[0].message.content == "pong"
@respx.mock
@pytest.mark.parametrize("client_target", ["api_base", "base_url"])
async def test_route_a2a_bridge_agent_ignores_a_client_target_over_its_card_url(
httpx_transport: None, client_target: str
) -> None:
agent = AgentResponse(
agent_id="dbx-agent-id",
agent_name="dbx-agent",
agent_card_params={"url": WORKSPACE},
litellm_params={"custom_llm_provider": "databricks_agent", "model": "my-agent", "api_key": "pat-1"},
)
endpoint = respx.post(f"{WORKSPACE}/serving-endpoints/my-agent/invocations").mock(
return_value=httpx.Response(200, json=AGENT_REPLY)
)
data = {
"model": "a2a/dbx-agent",
client_target: "https://collector.example.com",
"messages": [{"role": "user", "content": "ping"}],
}
with patch("litellm.proxy.agent_endpoints.agent_registry.global_agent_registry", _registry_with(agent)):
response = await (await route_a2a_agent_request(data=data, route_type="acompletion"))
assert endpoint.call_count == 1
assert endpoint.calls.last.request.headers["Authorization"] == "Bearer pat-1"
assert response.choices[0].message.content == "pong"
@respx.mock
@pytest.mark.parametrize("endpoint_name", [{"model": ""}, {"model": None}, {}])
async def test_route_a2a_bridge_agent_without_an_endpoint_name_answers_400_before_calling_databricks(
httpx_transport: None, endpoint_name: dict[str, object]
) -> None:
agent = AgentResponse(
agent_id="dbx-agent-id",
agent_name="dbx-agent",
agent_card_params={"url": WORKSPACE},
litellm_params={
"custom_llm_provider": "databricks_agent",
"api_base": WORKSPACE,
"api_key": "p",
**endpoint_name,
},
)
workspace = respx.route(host="adb-1.azuredatabricks.net").mock(return_value=httpx.Response(200, json=AGENT_REPLY))
data = {"model": "a2a/dbx-agent", "messages": [{"role": "user", "content": "ping"}]}
with patch("litellm.proxy.agent_endpoints.agent_registry.global_agent_registry", _registry_with(agent)):
with pytest.raises(litellm.BadRequestError, match="must name the Databricks serving endpoint"):
await (await route_a2a_agent_request(data=data, route_type="acompletion"))
assert not workspace.called
@respx.mock
async def test_route_a2a_bridge_app_agent_without_an_endpoint_name_calls_the_app(httpx_transport: None) -> None:
agent = AgentResponse(
agent_id="dbx-app-id",
agent_name="dbx-app",
agent_card_params={"url": APP_URL},
litellm_params={"custom_llm_provider": "databricks_agent", "api_key": "p"},
)
app = respx.post(APP_URL).mock(return_value=httpx.Response(200, json=AGENT_REPLY))
data = {"model": "a2a/dbx-app", "messages": [{"role": "user", "content": "ping"}]}
with patch("litellm.proxy.agent_endpoints.agent_registry.global_agent_registry", _registry_with(agent)):
response = await (await route_a2a_agent_request(data=data, route_type="acompletion"))
assert app.called
assert response.choices[0].message.content == "pong"
@respx.mock
@pytest.mark.parametrize(
("credential", "env_api_key", "expected_authorization"),
[
({"api_key": "pat-1"}, None, "Bearer pat-1"),
({}, "env-pat", "Bearer env-pat"),
({"client_id": "sp", "client_secret": "s", "workspace_url": WORKSPACE}, "env-pat", "Bearer minted-oauth"),
(
{"client_id": "sp", "client_secret": "s", "workspace_url": WORKSPACE, "api_key": "pat-1"},
None,
"Bearer minted-oauth",
),
({}, None, "Bearer client-token"),
],
)
async def test_route_a2a_bridge_agent_credential_wins_over_a_client_authorization(
httpx_transport: None,
monkeypatch: pytest.MonkeyPatch,
credential: dict[str, object],
env_api_key: str | None,
expected_authorization: str,
) -> None:
if env_api_key is None:
monkeypatch.delenv("DATABRICKS_API_KEY", raising=False)
else:
monkeypatch.setenv("DATABRICKS_API_KEY", env_api_key)
agent = AgentResponse(
agent_id="dbx-app-id",
agent_name="dbx-app",
agent_card_params={"url": APP_URL},
litellm_params={"custom_llm_provider": "databricks_agent", **credential},
)
_token_route(WORKSPACE)
app = respx.post(APP_URL).mock(return_value=httpx.Response(200, json=AGENT_REPLY))
data = {
"model": "a2a/dbx-app",
"messages": [{"role": "user", "content": "ping"}],
"extra_headers": {"authorization": "Bearer client-token", "X-Tenant": "t"},
}
with patch("litellm.proxy.agent_endpoints.agent_registry.global_agent_registry", _registry_with(agent)):
await (await route_a2a_agent_request(data=data, route_type="acompletion"))
sent = app.calls.last.request
assert sent.headers.get_list("Authorization") == [expected_authorization]
assert sent.headers["X-Tenant"] == "t"
@respx.mock
@pytest.mark.parametrize("extra_headers", [5, ["X-A"], {"X-N": 5}, "x"])
async def test_route_a2a_bridge_agent_answers_400_for_malformed_client_extra_headers(
httpx_transport: None, extra_headers: object
) -> None:
agent = AgentResponse(
agent_id="dbx-app-id",
agent_name="dbx-app",
agent_card_params={"url": APP_URL},
litellm_params={"custom_llm_provider": "databricks_agent", "api_key": "p"},
)
app = respx.post(APP_URL).mock(return_value=httpx.Response(200, json=AGENT_REPLY))
data = {"model": "a2a/dbx-app", "messages": [{"role": "user", "content": "ping"}], "extra_headers": extra_headers}
with patch("litellm.proxy.agent_endpoints.agent_registry.global_agent_registry", _registry_with(agent)):
with pytest.raises(HTTPException) as info:
await route_a2a_agent_request(data=data, route_type="acompletion")
assert info.value.status_code == 400
assert "extra_headers" in str(info.value.detail)
assert not app.called
@respx.mock
@pytest.mark.parametrize(
("extra_headers", "drop_params"),
[
(5, {"drop_params": True}),
({"X-N": 5}, {"drop_params": True}),
("", {}),
({}, {}),
(None, {}),
],
)
async def test_route_a2a_bridge_agent_calls_without_client_extra_headers_it_drops_or_finds_empty(
httpx_transport: None, extra_headers: object, drop_params: dict[str, object]
) -> None:
agent = AgentResponse(
agent_id="dbx-app-id",
agent_name="dbx-app",
agent_card_params={"url": APP_URL},
litellm_params={"custom_llm_provider": "databricks_agent", "api_key": "p"},
)
app = respx.post(APP_URL).mock(return_value=httpx.Response(200, json=AGENT_REPLY))
data = {
"model": "a2a/dbx-app",
"messages": [{"role": "user", "content": "ping"}],
"extra_headers": extra_headers,
**drop_params,
}
with patch("litellm.proxy.agent_endpoints.agent_registry.global_agent_registry", _registry_with(agent)):
response = await (await route_a2a_agent_request(data=data, route_type="acompletion"))
assert app.calls.last.request.headers["Authorization"] == "Bearer p"
assert "X-N" not in app.calls.last.request.headers
assert response.choices[0].message.content == "pong"
PER_QUERY_PRICE: Final = {"cost_per_query": 0.05}
PER_TOKEN_PRICE: Final = {"input_cost_per_token": 0.0001, "output_cost_per_token": 0.0002}
AGENT_URL: Final = "https://agent.example.com/a2a"
AGENT_STREAM_EVENTS: Final = (
{"type": "response.output_text.delta", "item_id": "msg_1", "delta": "po"},
{"type": "response.output_text.delta", "item_id": "msg_1", "delta": "ng"},
{"type": "response.output_item.done", "item": AGENT_REPLY["output"][0]},
)
def _priced_dbx_agent(name: str, price: Mapping[str, object]) -> AgentResponse:
return AgentResponse(
agent_id=f"{name}-id",
agent_name=name,
litellm_params={
"custom_llm_provider": "databricks_agent",
"model": "my-agent",
"api_base": WORKSPACE,
"api_key": "pat-1",
**price,
},
agent_card_params={"url": WORKSPACE},
)
def _priced_url_agent(name: str, price: Mapping[str, object]) -> AgentResponse:
return AgentResponse(
agent_id=f"{name}-id",
agent_name=name,
litellm_params=dict(price),
agent_card_params={"url": AGENT_URL, "name": name},
)
def _proxy_logging_obj(stream: bool = False) -> LiteLLMLoggingObj:
return LiteLLMLoggingObj(
model="a2a/agent",
messages=[{"role": "user", "content": "ping"}],
stream=stream,
call_type="acompletion",
start_time=datetime.datetime(2026, 1, 1, tzinfo=datetime.timezone.utc),
litellm_call_id="a2a-chat-call",
function_id="a2a-chat",
)
async def _billed_chat_call(
registry: AgentRegistry, agent_name: str, request: Mapping[str, object] = MappingProxyType({})
) -> tuple[float | None, ModelResponse, LiteLLMLoggingObj]:
logging_obj: Final = _proxy_logging_obj()
data: Final = {
"model": f"a2a/{agent_name}",
"messages": [{"role": "user", "content": "ping"}],
"metadata": {"user_api_key_hash": "key-hash"},
"litellm_logging_obj": logging_obj,
**request,
}
with patch("litellm.proxy.agent_endpoints.agent_registry.global_agent_registry", registry):
response: Final = await (await route_a2a_agent_request(data=data, route_type="acompletion"))
return logging_obj.response_cost_calculator(result=response), response, logging_obj
@respx.mock
async def test_route_a2a_bridge_agents_bill_their_own_price_whatever_another_agent_was_billed(
httpx_transport: None,
) -> None:
respx.post(f"{WORKSPACE}/serving-endpoints/my-agent/invocations").mock(
return_value=httpx.Response(200, json=AGENT_REPLY)
)
registry: Final = AgentRegistry()
for agent in (
_priced_dbx_agent("per-token", PER_TOKEN_PRICE),
_priced_dbx_agent("per-query", PER_QUERY_PRICE),
_priced_dbx_agent("per-second", {"input_cost_per_second": 0.5}),
_priced_dbx_agent("unpriced", {}),
_priced_dbx_agent("per-query-and-token", {**PER_QUERY_PRICE, **PER_TOKEN_PRICE}),
):
registry.register_agent(agent)
per_token_cost, per_token_response, _ = await _billed_chat_call(registry, "per-token")
per_query_cost, _, _ = await _billed_chat_call(registry, "per-query")
per_query_and_token_cost, _, _ = await _billed_chat_call(registry, "per-query-and-token")
per_second_cost, _, _ = await _billed_chat_call(registry, "per-second")
unpriced_cost, _, _ = await _billed_chat_call(registry, "unpriced")
usage: Final = per_token_response.usage
assert usage.prompt_tokens > 0
assert per_token_cost == pytest.approx(usage.prompt_tokens * 0.0001 + usage.completion_tokens * 0.0002)
assert per_query_cost == pytest.approx(0.05)
assert per_query_and_token_cost == pytest.approx(0.05)
assert per_second_cost is not None and per_second_cost > 0
assert unpriced_cost is None
@respx.mock
async def test_route_a2a_bridge_agent_without_a_price_bills_no_fixed_margin(
httpx_transport: None, monkeypatch: pytest.MonkeyPatch
) -> None:
respx.post(f"{WORKSPACE}/serving-endpoints/my-agent/invocations").mock(
return_value=httpx.Response(200, json=AGENT_REPLY)
)
monkeypatch.setattr(litellm, "cost_margin_config", {"global": {"fixed_amount": 0.01}})
unpriced_cost, _, _ = await _billed_chat_call(_registry_with(_priced_dbx_agent("unpriced", {})), "unpriced")
per_query_cost, _, _ = await _billed_chat_call(
_registry_with(_priced_dbx_agent("per-query", PER_QUERY_PRICE)), "per-query"
)
assert unpriced_cost is None
assert per_query_cost == pytest.approx(0.06)
@respx.mock
async def test_route_a2a_bridge_agent_bills_the_callers_allowed_price_override(httpx_transport: None) -> None:
respx.post(f"{WORKSPACE}/serving-endpoints/my-agent/invocations").mock(
return_value=httpx.Response(200, json=AGENT_REPLY)
)
cost, response, _ = await _billed_chat_call(
_registry_with(_priced_dbx_agent("per-query", PER_QUERY_PRICE)),
"per-query",
{"input_cost_per_token": 1.0, "output_cost_per_token": 1.0},
)
assert cost == pytest.approx(response.usage.prompt_tokens + response.usage.completion_tokens)
@respx.mock
async def test_route_a2a_bridge_agent_call_is_attributed_to_the_agent(httpx_transport: None) -> None:
respx.post(f"{WORKSPACE}/serving-endpoints/my-agent/invocations").mock(
return_value=httpx.Response(200, json=AGENT_REPLY)
)
_, _, logging_obj = await _billed_chat_call(
_registry_with(_priced_dbx_agent("per-query", PER_QUERY_PRICE)), "per-query"
)
assert logging_obj.model_call_details["agent_id"] == "per-query-id"
@respx.mock
async def test_route_a2a_bridge_agent_call_retries_as_many_times_as_the_caller_asked(httpx_transport: None) -> None:
endpoint: Final = respx.post(f"{WORKSPACE}/serving-endpoints/my-agent/invocations").mock(
return_value=httpx.Response(500, json={"error_code": "INTERNAL_ERROR", "message": "agent down"})
)
with pytest.raises(litellm.InternalServerError):
await _billed_chat_call(
_registry_with(_priced_dbx_agent("per-query", PER_QUERY_PRICE)),
"per-query",
{"num_retries": 2, "retry_strategy": "constant_retry"},
)
assert endpoint.call_count == 3
@respx.mock
async def test_route_a2a_url_agents_bill_their_own_price(httpx_transport: None) -> None:
respx.post(AGENT_URL).mock(return_value=httpx.Response(200, json=A2A_REPLY))
registry: Final = AgentRegistry()
for agent in (
_priced_url_agent("url-per-query", PER_QUERY_PRICE),
_priced_url_agent("url-per-token", PER_TOKEN_PRICE),
):
registry.register_agent(agent)
per_query_cost, _, per_query_logging_obj = await _billed_chat_call(registry, "url-per-query")
per_token_cost, per_token_response, _ = await _billed_chat_call(registry, "url-per-token")
usage: Final = per_token_response.usage
assert usage.prompt_tokens > 0
assert per_query_cost == pytest.approx(0.05)
assert per_query_logging_obj.model_call_details["agent_id"] == "url-per-query-id"
assert per_token_cost == pytest.approx(usage.prompt_tokens * 0.0001 + usage.completion_tokens * 0.0002)
@respx.mock
async def test_route_a2a_bridge_agent_price_gets_the_proxys_discount_and_margin(
httpx_transport: None, monkeypatch: pytest.MonkeyPatch
) -> None:
respx.post(f"{WORKSPACE}/serving-endpoints/my-agent/invocations").mock(
return_value=httpx.Response(200, json=AGENT_REPLY)
)
monkeypatch.setattr(litellm, "cost_discount_config", {"databricks_agent": 0.2})
monkeypatch.setattr(litellm, "cost_margin_config", {"global": 0.1})
cost, _, logging_obj = await _billed_chat_call(
_registry_with(_priced_dbx_agent("per-query", PER_QUERY_PRICE)), "per-query"
)
assert cost == pytest.approx(0.05 * 0.8 * 1.1)
assert logging_obj.cost_breakdown is not None
assert logging_obj.cost_breakdown["original_cost"] == pytest.approx(0.05)
@respx.mock
@pytest.mark.parametrize(
"cost_per_query",
["five cents", "", "nan", float("inf"), -0.05],
ids=["words", "empty", "nan", "inf", "negative"],
)
async def test_route_a2a_bridge_agent_with_an_unusable_price_still_answers(
httpx_transport: None, cost_per_query: object
) -> None:
respx.post(f"{WORKSPACE}/serving-endpoints/my-agent/invocations").mock(
return_value=httpx.Response(200, json=AGENT_REPLY)
)
cost, response, logging_obj = await _billed_chat_call(
_registry_with(_priced_dbx_agent("odd-price", {"cost_per_query": cost_per_query})), "odd-price"
)
assert response.choices[0].message.content == "pong"
assert cost is None
header_values: Final = cost_headers(response_cost=cost, litellm_logging_obj=logging_obj).values()
assert all(math.isfinite(float(value)) for value in header_values if value not in (None, "None"))
@respx.mock
@pytest.mark.parametrize(
"agent",
[
_priced_dbx_agent("text-price", {"input_cost_per_token": "abc", "output_cost_per_token": 0.0002}),
_priced_url_agent("url-text-price", {"input_cost_per_token": "abc", "output_cost_per_token": 0.0002}),
],
ids=["bridge", "url"],
)
async def test_route_a2a_agent_with_a_token_price_that_is_not_a_number_answers_and_bills_its_other_price(
httpx_transport: None, agent: AgentResponse
) -> None:
respx.post(f"{WORKSPACE}/serving-endpoints/my-agent/invocations").mock(
return_value=httpx.Response(200, json=AGENT_REPLY)
)
respx.post(AGENT_URL).mock(return_value=httpx.Response(200, json=A2A_REPLY))
cost, response, _ = await _billed_chat_call(_registry_with(agent), agent.agent_name)
assert response.choices[0].message.content == "pong"
assert response.usage.completion_tokens > 0
assert cost == pytest.approx(response.usage.completion_tokens * 0.0002)
@respx.mock
async def test_route_a2a_bridge_per_query_agent_reports_no_input_or_output_cost(httpx_transport: None) -> None:
respx.post(f"{WORKSPACE}/serving-endpoints/my-agent/invocations").mock(
return_value=httpx.Response(200, json=AGENT_REPLY)
)
cost, _, logging_obj = await _billed_chat_call(
_registry_with(_priced_dbx_agent("per-query", PER_QUERY_PRICE)), "per-query"
)
headers: Final = cost_headers(response_cost=cost, litellm_logging_obj=logging_obj)
assert float(headers["x-litellm-response-cost"]) == pytest.approx(0.05)
assert (headers["x-litellm-response-cost-input"], headers["x-litellm-response-cost-output"]) == (None, None)
@respx.mock
@pytest.mark.parametrize(
("config_name", "config"),
[
("cost_margin_config", {"global": {"percentage": "ten"}}),
("cost_margin_config", {"global": {"fixed_amount": None}}),
("cost_discount_config", {"databricks_agent": "a fifth"}),
("cost_discount_config", ["databricks_agent"]),
],
)
async def test_route_a2a_bridge_agent_with_a_malformed_cost_config_answers_and_bills_its_unadjusted_price(
httpx_transport: None, monkeypatch: pytest.MonkeyPatch, config_name: str, config: object
) -> None:
respx.post(f"{WORKSPACE}/serving-endpoints/my-agent/invocations").mock(
return_value=httpx.Response(200, json=AGENT_REPLY)
)
registry: Final = _registry_with(_priced_dbx_agent("per-query", PER_QUERY_PRICE))
unadjusted_cost, _, _ = await _billed_chat_call(registry, "per-query")
monkeypatch.setattr(litellm, config_name, config)
cost, response, _ = await _billed_chat_call(registry, "per-query")
assert response.choices[0].message.content == "pong"
assert unadjusted_cost is not None
assert cost == pytest.approx(unadjusted_cost)
@respx.mock
async def test_route_a2a_bridge_agent_cost_adds_the_calls_additional_response_cost(httpx_transport: None) -> None:
respx.post(f"{WORKSPACE}/serving-endpoints/my-agent/invocations").mock(
return_value=httpx.Response(200, json=AGENT_REPLY)
)
_, response, logging_obj = await _billed_chat_call(
_registry_with(_priced_dbx_agent("per-query", PER_QUERY_PRICE)), "per-query"
)
logging_obj.model_call_details["additional_response_cost"] = 0.01
assert logging_obj.response_cost_calculator(result=response) == pytest.approx(0.06)
class _SpendRowCapture(CustomLogger):
def __init__(self, row: asyncio.Future[SpendLogsPayload]) -> None:
super().__init__()
self._row = row
async def async_log_success_event(
self,
kwargs: dict[str, object],
response_obj: object,
start_time: datetime.datetime,
end_time: datetime.datetime,
) -> None:
self._row.set_result(
get_logging_payload(kwargs=kwargs, response_obj=response_obj, start_time=start_time, end_time=end_time)
)
async def _logged_spend_row(
agent: AgentResponse,
stream: bool,
monkeypatch: pytest.MonkeyPatch,
caller_metadata: Mapping[str, object] = MappingProxyType({}),
) -> tuple[SpendLogsPayload, str | None]:
row: Final[asyncio.Future[SpendLogsPayload]] = asyncio.get_running_loop().create_future()
capture: Final = _SpendRowCapture(row)
monkeypatch.setattr(litellm, "callbacks", [capture])
monkeypatch.setattr(litellm, "_async_success_callback", [capture])
data: Final = {
"model": f"a2a/{agent.agent_name}",
"messages": [{"role": "user", "content": "ping"}],
"metadata": {"user_api_key_hash": "key-hash", **caller_metadata},
"litellm_logging_obj": _proxy_logging_obj(stream=stream),
"stream": stream,
}
with patch("litellm.proxy.agent_endpoints.agent_registry.global_agent_registry", _registry_with(agent)):
response: Final = await (await route_a2a_agent_request(data=data, route_type="acompletion"))
text: Final = (
"".join([chunk.choices[0].delta.content or "" async for chunk in response])
if isinstance(response, CustomStreamWrapper)
else response.choices[0].message.content
)
return await asyncio.wait_for(row, timeout=5), text
@respx.mock
async def test_route_a2a_bridge_per_query_agent_streamed_call_bills_the_same_as_a_plain_call(
httpx_transport: None, monkeypatch: pytest.MonkeyPatch
) -> None:
endpoint: Final = respx.post(f"{WORKSPACE}/serving-endpoints/my-agent/invocations")
agent: Final = _priced_dbx_agent("per-query", PER_QUERY_PRICE)
endpoint.mock(return_value=httpx.Response(200, json=AGENT_REPLY))
plain_row, plain_text = await _logged_spend_row(agent, False, monkeypatch)
endpoint.mock(
return_value=httpx.Response(
200,
text="".join(f"data: {json.dumps(event)}\n\n" for event in AGENT_STREAM_EVENTS),
headers={"content-type": "text/event-stream"},
)
)
streamed_row, streamed_text = await _logged_spend_row(agent, True, monkeypatch)
assert streamed_text == plain_text == "pong"
assert (streamed_row["spend"], streamed_row["agent_id"]) == (pytest.approx(0.05), "per-query-id")
assert (plain_row["spend"], plain_row["agent_id"]) == (pytest.approx(0.05), "per-query-id")
@respx.mock
@pytest.mark.parametrize(
"agent",
[_priced_dbx_agent("per-query", PER_QUERY_PRICE), _priced_url_agent("url-per-query", PER_QUERY_PRICE)],
ids=["bridge", "url"],
)
async def test_route_a2a_agent_call_from_a_caller_agent_bills_the_agent_and_keeps_the_caller_on_the_spend_row(
httpx_transport: None, monkeypatch: pytest.MonkeyPatch, agent: AgentResponse
) -> None:
respx.post(f"{WORKSPACE}/serving-endpoints/my-agent/invocations").mock(
return_value=httpx.Response(200, json=AGENT_REPLY)
)
respx.post(AGENT_URL).mock(return_value=httpx.Response(200, json=A2A_REPLY))
row, _ = await _logged_spend_row(agent, False, monkeypatch, {"agent_id": "caller-agent-id"})
assert (row["spend"], row["agent_id"]) == (pytest.approx(0.05), "caller-agent-id")
@respx.mock
async def test_route_a2a_failed_agent_call_from_a_caller_agent_leaves_the_caller_on_the_failure_row(
httpx_transport: None,
) -> None:
respx.post(f"{WORKSPACE}/serving-endpoints/my-agent/invocations").mock(
return_value=httpx.Response(500, json={"error_code": "INTERNAL_ERROR", "message": "agent down"})
)
logging_obj: Final = _proxy_logging_obj()
data: Final = {
"model": "a2a/per-query",
"messages": [{"role": "user", "content": "ping"}],
"metadata": {"user_api_key_hash": "key-hash", "agent_id": "caller-agent-id"},
"litellm_logging_obj": logging_obj,
}
with patch(
"litellm.proxy.agent_endpoints.agent_registry.global_agent_registry",
_registry_with(_priced_dbx_agent("per-query", PER_QUERY_PRICE)),
):
with pytest.raises(litellm.InternalServerError):
await (await route_a2a_agent_request(data=data, route_type="acompletion"))
assert "agent_id" not in _failure_fields_to_lift({"litellm_logging_obj": logging_obj})
@respx.mock
async def test_route_a2a_url_agent_call_leaves_the_agent_url_in_the_request_post_call_hooks_read(
httpx_transport: None,
) -> None:
respx.post(AGENT_URL).mock(return_value=httpx.Response(200, json=A2A_REPLY))
data: Final = {
"model": "a2a/url-per-query",
"messages": [{"role": "user", "content": "ping"}],
"metadata": {"user_api_key_hash": "key-hash"},
"litellm_logging_obj": _proxy_logging_obj(),
}
with patch(
"litellm.proxy.agent_endpoints.agent_registry.global_agent_registry",
_registry_with(_priced_url_agent("url-per-query", PER_QUERY_PRICE)),
):
await (await route_a2a_agent_request(data=data, route_type="acompletion"))
assert data["api_base"] == AGENT_URL
assert "cost_per_query" not in data
@respx.mock
@pytest.mark.parametrize(
"client_price",
[
{"base_model": "a2a-client-base-model"},
{"metadata": {"model_info": {"base_model": "a2a-client-base-model"}}},
],
ids=["base-model", "model-info-base-model"],
)
@pytest.mark.parametrize(
"agent",
[_priced_dbx_agent("per-query", PER_QUERY_PRICE), _priced_url_agent("url-per-query", PER_QUERY_PRICE)],
ids=["bridge-per-query", "url-per-query"],
)
async def test_route_a2a_agents_bill_the_callers_allowed_base_model(
httpx_transport: None, monkeypatch: pytest.MonkeyPatch, agent: AgentResponse, client_price: Mapping[str, object]
) -> None:
respx.post(f"{WORKSPACE}/serving-endpoints/my-agent/invocations").mock(
return_value=httpx.Response(200, json=AGENT_REPLY)
)
respx.post(AGENT_URL).mock(return_value=httpx.Response(200, json=A2A_REPLY))
monkeypatch.setitem(
litellm.model_cost,
"a2a-client-base-model",
{"input_cost_per_token": 0.5, "output_cost_per_token": 0.5, "litellm_provider": "openai", "mode": "chat"},
)
cost, response, _ = await _billed_chat_call(_registry_with(agent), agent.agent_name, client_price)
assert response.usage.prompt_tokens > 0
assert cost == pytest.approx(0.5 * (response.usage.prompt_tokens + response.usage.completion_tokens))
@respx.mock
@pytest.mark.parametrize(
("client_price", "billed_output_price"),
[({"base_model": "a2a-client-base-model"}, 0.0002), ({"output_cost_per_token": 1.0}, 1.0)],
ids=["base-model", "output-price-only"],
)
@pytest.mark.parametrize(
"agent",
[_priced_dbx_agent("per-token", PER_TOKEN_PRICE), _priced_url_agent("url-per-token", PER_TOKEN_PRICE)],
ids=["bridge", "url"],
)
async def test_route_a2a_agents_bill_their_own_token_price_for_every_side_the_caller_did_not_price(
httpx_transport: None,
monkeypatch: pytest.MonkeyPatch,
agent: AgentResponse,
client_price: Mapping[str, object],
billed_output_price: float,
) -> None:
respx.post(f"{WORKSPACE}/serving-endpoints/my-agent/invocations").mock(
return_value=httpx.Response(200, json=AGENT_REPLY)
)
respx.post(AGENT_URL).mock(return_value=httpx.Response(200, json=A2A_REPLY))
monkeypatch.setitem(
litellm.model_cost,
"a2a-client-base-model",
{"input_cost_per_token": 0.5, "output_cost_per_token": 0.5, "litellm_provider": "openai", "mode": "chat"},
)
cost, response, _ = await _billed_chat_call(_registry_with(agent), agent.agent_name, client_price)
usage: Final = response.usage
assert usage.prompt_tokens > 0
assert cost == pytest.approx(usage.prompt_tokens * 0.0001 + usage.completion_tokens * billed_output_price)
@respx.mock
async def test_route_a2a_agent_that_answers_itself_is_billed_as_the_agent_when_a_fallback_is_set(
httpx_transport: None,
) -> None:
respx.post(f"{WORKSPACE}/serving-endpoints/my-agent/invocations").mock(
return_value=httpx.Response(200, json=AGENT_REPLY)
)
cost, _, logging_obj = await _billed_chat_call(
_registry_with(_priced_dbx_agent("per-query", PER_QUERY_PRICE)),
"per-query",
{"fallbacks": ["databricks_agent/backup-agent"]},
)
assert cost == pytest.approx(0.05)
assert logging_obj.model_call_details["agent_id"] == "per-query-id"
assert _failure_fields_to_lift({"litellm_logging_obj": logging_obj})["agent_id"] == "per-query-id"
@respx.mock
async def test_route_a2a_agent_call_answered_by_a_fallback_model_bills_the_fallback_not_the_agent(
httpx_transport: None,
) -> None:
respx.post(f"{WORKSPACE}/serving-endpoints/my-agent/invocations").mock(
return_value=httpx.Response(404, json={"error_code": "RESOURCE_DOES_NOT_EXIST", "message": "no endpoint"})
)
respx.post(f"{WORKSPACE}/serving-endpoints/backup-agent/invocations").mock(
return_value=httpx.Response(200, json=AGENT_REPLY)
)
fallback: Final = {
"model": "databricks_agent/backup-agent",
"input_cost_per_token": 1.0,
"output_cost_per_token": 1.0,
}
cost, response, logging_obj = await _billed_chat_call(
_registry_with(_priced_dbx_agent("per-query", PER_QUERY_PRICE)), "per-query", {"fallbacks": [fallback]}
)
assert response.choices[0].message.content == "pong"
assert cost == pytest.approx(response.usage.prompt_tokens + response.usage.completion_tokens)
assert "agent_id" not in logging_obj.model_call_details
FALLBACK_API_BASE: Final = "https://fallback.example.com/v1"
FALLBACK_REPLY: Final = {
"id": "chatcmpl-fallback",
"object": "chat.completion",
"created": 1,
"model": "a2a-fallback-model",
"choices": [{"index": 0, "message": {"role": "assistant", "content": "pong"}, "finish_reason": "stop"}],
"usage": {"prompt_tokens": 7, "completion_tokens": 3, "total_tokens": 10},
}
@respx.mock
@pytest.mark.parametrize(
"agent",
[_priced_dbx_agent("per-token", PER_TOKEN_PRICE), _priced_url_agent("url-per-token", PER_TOKEN_PRICE)],
ids=["bridge", "url"],
)
async def test_route_a2a_agent_call_answered_by_an_unpriced_fallback_is_billed_and_attributed_as_the_fallback(
httpx_transport: None, monkeypatch: pytest.MonkeyPatch, agent: AgentResponse
) -> None:
respx.post(f"{WORKSPACE}/serving-endpoints/my-agent/invocations").mock(
return_value=httpx.Response(404, json={"error_code": "RESOURCE_DOES_NOT_EXIST", "message": "no endpoint"})
)
respx.post(AGENT_URL).mock(return_value=httpx.Response(500, json={"error": "agent down"}))
respx.post(f"{FALLBACK_API_BASE}/chat/completions").mock(return_value=httpx.Response(200, json=FALLBACK_REPLY))
monkeypatch.setitem(
litellm.model_cost,
"a2a-fallback-model",
{"input_cost_per_token": 0.5, "output_cost_per_token": 0.5, "litellm_provider": "openai", "mode": "chat"},
)
fallback: Final = {"model": "openai/a2a-fallback-model", "api_base": FALLBACK_API_BASE, "api_key": "sk-fallback"}
cost, response, logging_obj = await _billed_chat_call(
_registry_with(agent), agent.agent_name, {"fallbacks": [fallback]}
)
assert response.choices[0].message.content == "pong"
assert cost == pytest.approx(0.5 * (response.usage.prompt_tokens + response.usage.completion_tokens))
assert "agent_id" not in logging_obj.model_call_details
assert "agent_id" not in _failure_fields_to_lift({"litellm_logging_obj": logging_obj})
@respx.mock
@pytest.mark.parametrize(
"agent",
[_priced_dbx_agent("per-token", PER_TOKEN_PRICE), _priced_url_agent("url-per-token", PER_TOKEN_PRICE)],
ids=["bridge", "url"],
)
async def test_route_a2a_agent_call_no_fallback_answered_stays_on_the_agents_failure_row(
httpx_transport: None, agent: AgentResponse
) -> None:
respx.post(f"{WORKSPACE}/serving-endpoints/my-agent/invocations").mock(
return_value=httpx.Response(404, json={"error_code": "RESOURCE_DOES_NOT_EXIST", "message": "no endpoint"})
)
respx.post(AGENT_URL).mock(return_value=httpx.Response(500, json={"error": "agent down"}))
respx.post(f"{FALLBACK_API_BASE}/chat/completions").mock(
return_value=httpx.Response(400, json={"error": {"message": "fallback refused"}})
)
logging_obj: Final = _proxy_logging_obj()
data: Final = {
"model": f"a2a/{agent.agent_name}",
"messages": [{"role": "user", "content": "ping"}],
"litellm_logging_obj": logging_obj,
"fallbacks": [{"model": "openai/a2a-fallback-model", "api_base": FALLBACK_API_BASE, "api_key": "sk-fallback"}],
}
with (
patch("litellm.proxy.agent_endpoints.agent_registry.global_agent_registry", _registry_with(agent)),
pytest.raises(Exception, match="All fallback attempts failed"),
):
await (await route_a2a_agent_request(data=data, route_type="acompletion"))
assert _failure_fields_to_lift({"litellm_logging_obj": logging_obj})["agent_id"] == agent.agent_id
@respx.mock
@pytest.mark.parametrize(
"agent",
[_priced_dbx_agent("per-query", PER_QUERY_PRICE), _priced_url_agent("url-per-query", PER_QUERY_PRICE)],
ids=["bridge", "url"],
)
async def test_route_a2a_agent_that_answers_its_own_retry_is_billed_and_attributed_as_the_agent(
httpx_transport: None, agent: AgentResponse
) -> None:
respx.post(f"{WORKSPACE}/serving-endpoints/my-agent/invocations").mock(
side_effect=[
httpx.Response(500, json={"error_code": "TEMPORARILY_UNAVAILABLE"}),
httpx.Response(200, json=AGENT_REPLY),
]
)
respx.post(AGENT_URL).mock(
side_effect=[httpx.Response(500, json={"error": "agent down"}), httpx.Response(200, json=A2A_REPLY)]
)
cost, response, logging_obj = await _billed_chat_call(
_registry_with(agent), agent.agent_name, {"fallbacks": [{"timeout": 30}]}
)
assert response.choices[0].message.content == "pong"
assert cost == pytest.approx(0.05)
assert logging_obj.model_call_details["agent_id"] == agent.agent_id
assert _failure_fields_to_lift({"litellm_logging_obj": logging_obj})["agent_id"] == agent.agent_id
@respx.mock
@pytest.mark.parametrize(
"agent",
[_priced_dbx_agent("per-query", PER_QUERY_PRICE), _priced_url_agent("url-per-query", PER_QUERY_PRICE)],
ids=["bridge", "url"],
)
async def test_route_a2a_agent_that_answers_its_retry_after_a_failed_fallback_model_is_billed_and_attributed_as_the_agent(
httpx_transport: None, agent: AgentResponse
) -> None:
respx.post(f"{WORKSPACE}/serving-endpoints/my-agent/invocations").mock(
side_effect=[
httpx.Response(500, json={"error_code": "TEMPORARILY_UNAVAILABLE"}),
httpx.Response(200, json=AGENT_REPLY),
]
)
respx.post(AGENT_URL).mock(
side_effect=[httpx.Response(500, json={"error": "agent down"}), httpx.Response(200, json=A2A_REPLY)]
)
respx.post(f"{FALLBACK_API_BASE}/chat/completions").mock(
return_value=httpx.Response(400, json={"error": {"message": "fallback refused"}})
)
fallbacks: Final = [
{"model": "openai/a2a-fallback-model", "api_base": FALLBACK_API_BASE, "api_key": "sk-fallback"},
{"timeout": 30},
]
cost, response, logging_obj = await _billed_chat_call(
_registry_with(agent), agent.agent_name, {"fallbacks": fallbacks}
)
assert response.choices[0].message.content == "pong"
assert cost == pytest.approx(0.05)
assert logging_obj.model_call_details["agent_id"] == agent.agent_id
assert _failure_fields_to_lift({"litellm_logging_obj": logging_obj})["agent_id"] == agent.agent_id
CLIENT_COST_PER_SECOND: Final = 1_000_000.0
@respx.mock
@pytest.mark.parametrize("per_second_price", ["cost_per_second", "input_cost_per_second"])
@pytest.mark.parametrize(
"agent",
[_priced_dbx_agent("per-token", PER_TOKEN_PRICE), _priced_url_agent("url-per-token", PER_TOKEN_PRICE)],
ids=["bridge", "url"],
)
async def test_route_a2a_agents_bill_the_callers_per_second_price_over_their_own_token_price(
httpx_transport: None, agent: AgentResponse, per_second_price: str
) -> None:
respx.post(f"{WORKSPACE}/serving-endpoints/my-agent/invocations").mock(
return_value=httpx.Response(200, json=AGENT_REPLY)
)
respx.post(AGENT_URL).mock(return_value=httpx.Response(200, json=A2A_REPLY))
started: Final = time.monotonic()
cost, _, _ = await _billed_chat_call(
_registry_with(agent), agent.agent_name, {per_second_price: CLIENT_COST_PER_SECOND}
)
elapsed: Final = time.monotonic() - started
assert cost is not None
assert 1.0 < cost <= CLIENT_COST_PER_SECOND * elapsed
@respx.mock
async def test_route_a2a_bridge_agent_call_whose_oauth_token_request_fails_is_attributed_to_the_agent(
httpx_transport: None,
) -> None:
respx.post(f"{WORKSPACE}/oidc/v1/token").mock(return_value=httpx.Response(401, json={"error": "invalid_client"}))
agent: Final = AgentResponse(
agent_id="dbx-app-id",
agent_name="dbx-app",
agent_card_params={"url": APP_URL},
litellm_params={
"custom_llm_provider": "databricks_agent",
"databricks_oauth": {"client_id": "sp", "client_secret": "s", "workspace_url": WORKSPACE},
**PER_QUERY_PRICE,
},
)
logging_obj: Final = _proxy_logging_obj()
data: Final = {
"model": "a2a/dbx-app",
"messages": [{"role": "user", "content": "ping"}],
"litellm_logging_obj": logging_obj,
}
with patch("litellm.proxy.agent_endpoints.agent_registry.global_agent_registry", _registry_with(agent)):
with pytest.raises(ValueError, match="OAuth token request failed"):
await route_a2a_agent_request(data=data, route_type="acompletion")
assert logging_obj.model_call_details["agent_id"] == "dbx-app-id"