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]

fix(mcp)!: bill both model calls of a chat completions MCP auto-execute on one spend row (#47422)

Mateo Wangdaa133da5cb5
diff --git a/litellm/responses/mcp/chat_completions_handler.py b/litellm/responses/mcp/chat_completions_handler.py
index a8c93eebff3..b100858b306 100644
--- a/litellm/responses/mcp/chat_completions_handler.py
+++ b/litellm/responses/mcp/chat_completions_handler.py
@@ -6,11 +6,18 @@ from typing import TYPE_CHECKING, Final, cast
from typing_extensions import TypedDict, Unpack
+from litellm._internal_context import internal_sub_call
from litellm.litellm_core_utils.hidden_params import HIDDEN_PARAMS_ATTR, set_hidden_params
+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.responses.mcp.litellm_proxy_mcp_handler import (
LiteLLM_Proxy_MCP_Handler,
)
from litellm.responses.mcp.request_context import MCPRequestContext
+from litellm.responses.mcp.round_billing import (
+ billed_for_every_round,
+ first_round_billed_on_failure,
+ summed_cost_breakdown,
+)
from litellm.types.utils import Message, ModelResponse
from litellm.utils import CustomStreamWrapper
@@ -588,19 +595,21 @@ async def acompletion_with_mcp(
return cast(CustomStreamWrapper, MCPStreamWrapper(initial_stream, iterator))
- # Non-streaming mode: use existing logic
initial_call_args = dict(base_call_args)
initial_call_args["stream"] = False
if mock_tool_calls is not None:
initial_call_args["mock_tool_calls"] = mock_tool_calls
- # Make initial call
- initial_response: Final = await litellm_acompletion(**initial_call_args)
+ logging_obj: Final = kwargs.get("litellm_logging_obj")
+ if isinstance(logging_obj, LiteLLMLoggingObj):
+ logging_obj.carry_failed_attempt_usage()
+ with internal_sub_call():
+ initial_response: Final = await litellm_acompletion(**initial_call_args)
+ first_round_breakdown: Final = logging_obj.cost_breakdown if isinstance(logging_obj, LiteLLMLoggingObj) else None
if not isinstance(initial_response, ModelResponse):
return initial_response
- # Extract tool calls from response
tool_calls: Final = LiteLLM_Proxy_MCP_Handler.extract_tool_calls_from_chat_response(response=initial_response)
if not tool_calls:
@@ -610,48 +619,62 @@ async def acompletion_with_mcp(
)
return initial_response
- # Execute tool calls
- tool_results: Final = await LiteLLM_Proxy_MCP_Handler.execute_tool_calls(
- tool_server_map=tool_server_map,
- tool_calls=tool_calls,
- served_tools=deduplicated_mcp_tools,
- user_api_key_auth=user_api_key_auth,
- mcp_auth_header=mcp_auth_header,
- mcp_server_auth_headers=mcp_server_auth_headers,
- oauth2_headers=oauth2_headers,
- raw_headers=raw_headers,
- litellm_call_id=context.litellm_call_id,
- litellm_trace_id=context.litellm_trace_id,
- request_tags=request_tags,
- guardrail_context=context.guardrail_context,
- )
+ with first_round_billed_on_failure(logging_obj, initial_response):
+ tool_results: Final = await LiteLLM_Proxy_MCP_Handler.execute_tool_calls(
+ tool_server_map=tool_server_map,
+ tool_calls=tool_calls,
+ served_tools=deduplicated_mcp_tools,
+ user_api_key_auth=user_api_key_auth,
+ mcp_auth_header=mcp_auth_header,
+ mcp_server_auth_headers=mcp_server_auth_headers,
+ oauth2_headers=oauth2_headers,
+ raw_headers=raw_headers,
+ litellm_call_id=context.litellm_call_id,
+ litellm_trace_id=context.litellm_trace_id,
+ request_tags=request_tags,
+ guardrail_context=context.guardrail_context,
+ )
- if not tool_results:
- _add_mcp_metadata_to_response(
+ if not tool_results:
+ _add_mcp_metadata_to_response(
+ response=initial_response,
+ openai_tools=openai_tools,
+ tool_calls=tool_calls,
+ )
+ return initial_response
+
+ follow_up_messages: Final = LiteLLM_Proxy_MCP_Handler.create_follow_up_messages_for_chat(
+ original_messages=messages,
response=initial_response,
- openai_tools=openai_tools,
- tool_calls=tool_calls,
+ tool_results=tool_results,
)
- return initial_response
- # Create follow-up messages with tool results
- follow_up_messages: Final = LiteLLM_Proxy_MCP_Handler.create_follow_up_messages_for_chat(
- original_messages=messages,
- response=initial_response,
- tool_results=tool_results,
- )
+ follow_up_call_args: Final = dict(base_call_args)
+ follow_up_call_args["messages"] = follow_up_messages
+ follow_up_call_args["stream"] = stream
- # Make follow-up call with original stream setting
- follow_up_call_args: Final = dict(base_call_args)
- follow_up_call_args["messages"] = follow_up_messages
- follow_up_call_args["stream"] = stream
+ with internal_sub_call():
+ final_response: Final = await litellm_acompletion(**follow_up_call_args)
- response = await litellm_acompletion(**follow_up_call_args)
- if isinstance(response, (ModelResponse, CustomStreamWrapper)):
- _add_mcp_metadata_to_response(
- response=response,
- openai_tools=openai_tools,
- tool_calls=tool_calls,
- tool_results=tool_results,
+ if not isinstance(final_response, ModelResponse):
+ return final_response
+ _add_mcp_metadata_to_response(
+ response=final_response,
+ openai_tools=openai_tools,
+ tool_calls=tool_calls,
+ tool_results=tool_results,
+ )
+ final_round_breakdown: Final = logging_obj.cost_breakdown if isinstance(logging_obj, LiteLLMLoggingObj) else None
+ if isinstance(logging_obj, LiteLLMLoggingObj):
+ logging_obj.cost_breakdown = summed_cost_breakdown(
+ first=initial_response,
+ first_breakdown=first_round_breakdown,
+ final=final_response,
+ final_breakdown=final_round_breakdown,
)
- return response
+ return billed_for_every_round(
+ first=initial_response,
+ first_breakdown=first_round_breakdown,
+ final=final_response,
+ final_breakdown=final_round_breakdown,
+ )
diff --git a/litellm/responses/mcp/litellm_proxy_mcp_handler.py b/litellm/responses/mcp/litellm_proxy_mcp_handler.py
index e66a7d1102b..e3c3ab671ea 100644
--- a/litellm/responses/mcp/litellm_proxy_mcp_handler.py
+++ b/litellm/responses/mcp/litellm_proxy_mcp_handler.py
@@ -773,9 +773,7 @@ class LiteLLM_Proxy_MCP_Handler:
}
]
tool_logging_call_id = (
- f"{litellm_call_id}_{tool_call_id or uuid.uuid4()}"
- if request_trace_id and litellm_call_id
- else litellm_call_id or str(uuid.uuid4())
+ f"{litellm_call_id}_{tool_call_id or uuid.uuid4()}" if litellm_call_id else str(uuid.uuid4())
)
logging_metadata: dict[str, object] = {
"tool_call_id": tool_call_id,
diff --git a/litellm/responses/mcp/round_billing.py b/litellm/responses/mcp/round_billing.py
index f20d01785a5..ae34ab31633 100644
--- a/litellm/responses/mcp/round_billing.py
+++ b/litellm/responses/mcp/round_billing.py
@@ -2,21 +2,24 @@ from asyncio import CancelledError
from collections.abc import Generator, Mapping
from contextlib import contextmanager
from types import MappingProxyType
-from typing import Final
+from typing import Final, TypeVar
from pydantic import TypeAdapter
+from pydantic_core import to_jsonable_python
-from litellm.litellm_core_utils.hidden_params import served_from_cache
+from litellm.litellm_core_utils.hidden_params import get_hidden_params, served_from_cache, set_hidden_params
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.responses.utils import ResponseAPILoggingUtils
from litellm.types.llms.openai import ResponseAPIUsage, ResponsesAPIResponse
-from litellm.types.utils import CostBreakdown
+from litellm.types.utils import CostBreakdown, ModelResponse, Usage
_PER_REQUEST_KEYS: Final = frozenset({"discount_percent", "margin_percent", "margin_fixed_amount"})
_TOTALS_WITH_FIXED_MARGIN: Final = ("total_cost", "margin_total_amount")
_COST_BREAKDOWN: Final = TypeAdapter(CostBreakdown)
_STR_KEYED: Final = TypeAdapter(Mapping[str, object])
+_Round = TypeVar("_Round", ResponsesAPIResponse, ModelResponse)
+
def _summed(first: object, final: object) -> object:
if first is None:
@@ -49,10 +52,43 @@ def merged_round_usage(first: ResponseAPIUsage | None, final: ResponseAPIUsage |
return ResponseAPIUsage.model_validate(_summed_mapping(first.model_dump(), final.model_dump()))
+def _merged_chat_usage(first: Usage, final: Usage) -> Usage:
+ summed: Final = _summed_mapping(first.model_dump(), final.model_dump())
+ return Usage.model_validate(to_jsonable_python(summed, fallback=dict))
+
+
+def _chat_usage(round_response: ResponsesAPIResponse | ModelResponse) -> Usage | None:
+ if isinstance(round_response, ResponsesAPIResponse):
+ return (
+ None
+ if round_response.usage is None
+ else ResponseAPILoggingUtils.transform_response_api_usage_to_chat_usage(round_response.usage)
+ )
+ usage: Final = getattr(round_response, "usage", None)
+ return usage if isinstance(usage, Usage) else None
+
+
+def _response_cost(round_response: ResponsesAPIResponse | ModelResponse) -> object:
+ hidden_params: Final = get_hidden_params(round_response)
+ return None if hidden_params is None else hidden_params.get("response_cost")
+
+
+def _usage_of_both_rounds(
+ first: ResponsesAPIResponse | ModelResponse, final: ResponsesAPIResponse | ModelResponse
+) -> ResponseAPIUsage | Usage | None:
+ if isinstance(first, ResponsesAPIResponse) and isinstance(final, ResponsesAPIResponse):
+ return merged_round_usage(first.usage, final.usage)
+ first_usage: Final = _chat_usage(first)
+ final_usage: Final = _chat_usage(final)
+ if first_usage is None or final_usage is None:
+ return final_usage if first_usage is None else first_usage
+ return _merged_chat_usage(first_usage, final_usage)
+
+
def _repeated_fixed_margin(
- first: ResponsesAPIResponse,
+ first: ResponsesAPIResponse | ModelResponse,
first_breakdown: CostBreakdown | None,
- final: ResponsesAPIResponse,
+ final: ResponsesAPIResponse | ModelResponse,
final_breakdown: CostBreakdown | None,
) -> float:
if first_breakdown is None or final_breakdown is None or first_breakdown is final_breakdown:
@@ -70,9 +106,9 @@ def _less_repeated_fixed_margin(summed: Mapping[str, object], repeated: float) -
def summed_cost_breakdown(
- first: ResponsesAPIResponse,
+ first: ResponsesAPIResponse | ModelResponse,
first_breakdown: CostBreakdown | None,
- final: ResponsesAPIResponse,
+ final: ResponsesAPIResponse | ModelResponse,
final_breakdown: CostBreakdown | None,
) -> CostBreakdown | None:
"""The breakdown of the charged rounds, or None when a charged round was priced without its own breakdown, since a
@@ -94,41 +130,38 @@ def summed_cost_breakdown(
def billed_for_every_round(
- first: ResponsesAPIResponse,
+ first: _Round,
first_breakdown: CostBreakdown | None,
- final: ResponsesAPIResponse,
+ final: _Round,
final_breakdown: CostBreakdown | None,
-) -> ResponsesAPIResponse:
+) -> _Round:
"""The final round's response carrying the usage and cost of both rounds, so the one logged row bills the request.
Costs are summed per round rather than repriced from the summed usage, because a round's price can depend on its
own size (tiered rates) or on charges the usage does not show (built-in tools, provider-reported costs). The fixed
margin both rounds added is charged once, since it is a per-request fee.
"""
- first_cost: Final = first.hidden_params.get("response_cost")
- final_cost: Final = final.hidden_params.get("response_cost")
+ first_cost: Final = _response_cost(first)
+ final_cost: Final = _response_cost(final)
total_cost: Final = (
first_cost + final_cost - _repeated_fixed_margin(first, first_breakdown, final, final_breakdown)
if isinstance(first_cost, (int, float)) and isinstance(final_cost, (int, float))
else None
)
- billed: Final = final.model_copy(update=MappingProxyType({"usage": merged_round_usage(first.usage, final.usage)}))
- billed.hidden_params = {
- **final.hidden_params,
- "response_cost": total_cost,
- }
+ billed: Final = final.model_copy(update=MappingProxyType({"usage": _usage_of_both_rounds(first, final)}))
+ set_hidden_params(billed, {**(get_hidden_params(final) or {}), "response_cost": total_cost})
return billed
@contextmanager
-def first_round_billed_on_failure(logging_obj: object, first: ResponsesAPIResponse) -> Generator[None]:
+def first_round_billed_on_failure(logging_obj: object, first: ResponsesAPIResponse | ModelResponse) -> Generator[None]:
try:
yield
except (Exception, CancelledError):
- first_cost: Final = first.hidden_params.get("response_cost")
- if isinstance(logging_obj, LiteLLMLoggingObj) and first.usage is not None and not served_from_cache(first):
+ first_cost: Final = _response_cost(first)
+ first_usage: Final = _chat_usage(first)
+ if isinstance(logging_obj, LiteLLMLoggingObj) and first_usage is not None and not served_from_cache(first):
logging_obj.record_partial_usage_for_failure(
- ResponseAPILoggingUtils.transform_response_api_usage_to_chat_usage(first.usage),
- float(first_cost) if isinstance(first_cost, (int, float)) else 0.0,
+ first_usage, float(first_cost) if isinstance(first_cost, (int, float)) else 0.0
)
raise
diff --git a/tests/integration/mcp/test_mcp_llm_endpoints.py b/tests/integration/mcp/test_mcp_llm_endpoints.py
index 4edf7b620f2..c5ffb88506a 100644
--- a/tests/integration/mcp/test_mcp_llm_endpoints.py
+++ b/tests/integration/mcp/test_mcp_llm_endpoints.py
@@ -6,6 +6,7 @@ from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from dataclasses import dataclass
from hashlib import sha256
+from itertools import chain
from pathlib import Path
from typing import Final, Literal, TypeVar
@@ -54,6 +55,10 @@ def _llm_gateway(tmp_path_factory: pytest.TempPathFactory) -> Iterator[tuple[Gat
{
**stock,
"general_settings": {**object_value(stock["general_settings"]), "store_prompts_in_spend_logs": True},
+ "litellm_settings": {
+ **object_value(stock["litellm_settings"]),
+ "cost_margin_config": {"hosted_vllm": {"fixed_amount": FIXED_MARGIN}},
+ },
}
)
)
@@ -81,6 +86,8 @@ ANSWER: Final = "the sum is 5"
GATEWAY_REF: Final = {"type": "mcp", "server_url": "litellm_proxy", "server_label": "litellm"}
AUTO: Final = {**GATEWAY_REF, "require_approval": "never"}
OUTAGE: Final = "bridge-outage"
+DIRECT: Final = "answer-without-tools"
+FIXED_MARGIN: Final = 0.25
JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])
JSON_VALUE: Final[TypeAdapter[JsonValue]] = TypeAdapter(JsonValue)
@@ -169,17 +176,27 @@ def _tool_result_block(item: Mapping[str, JsonValue]) -> str | None:
return None
-def _responses_stream(response: Mapping[str, JsonValue], item: Mapping[str, JsonValue]) -> Reply:
+def _item_events(index: int, item: Mapping[str, JsonValue]) -> tuple[dict[str, JsonValue], ...]:
+ return (
+ {"type": "response.output_item.added", "output_index": index, "item": dict(item)},
+ {"type": "response.output_item.done", "output_index": index, "item": dict(item)},
+ )
+
+
+def _responses_stream(response: Mapping[str, JsonValue], items: Sequence[Mapping[str, JsonValue]]) -> Reply:
+ item_events: Final = tuple(chain.from_iterable(_item_events(index, item) for index, item in enumerate(items)))
events: Final = (
- {"type": "response.created", "sequence_number": 0, "response": {**response, "status": "in_progress"}},
- {"type": "response.in_progress", "sequence_number": 1, "response": {**response, "status": "in_progress"}},
- {"type": "response.output_item.added", "sequence_number": 2, "output_index": 0, "item": item},
- {"type": "response.output_item.done", "sequence_number": 3, "output_index": 0, "item": item},
- {"type": "response.completed", "sequence_number": 4, "response": response},
+ {"type": "response.created", "response": {**response, "status": "in_progress"}},
+ {"type": "response.in_progress", "response": {**response, "status": "in_progress"}},
+ *item_events,
+ {"type": "response.completed", "response": response},
)
return Reply(
content_type="text/event-stream",
- chunks=tuple(f"event: {event['type']}\ndata: {json.dumps(event)}\n\n".encode() for event in events),
+ chunks=tuple(
+ f"event: {event['type']}\ndata: {json.dumps({**event, 'sequence_number': number})}\n\n".encode()
+ for number, event in enumerate(events)
+ ),
)
@@ -233,7 +250,7 @@ def _anthropic_tool_result_rule(body: Mapping[str, JsonValue]) -> Reply | None:
def _model_double(
- plan: Callable[[Mapping[str, JsonValue]], Turn], billing: Billing = EVEN_ROUNDS
+ plan: Callable[[Mapping[str, JsonValue]], Turn], billing: Billing = EVEN_ROUNDS, parallel: int = 1
) -> Callable[[Request], Reply]:
def respond(request: Request) -> Reply:
if request.method == "GET" and request.target.endswith("/models"):
@@ -243,11 +260,13 @@ def _model_double(
outage: Final = {"error": {"message": "scripted provider outage", "type": "server_error", "code": None}}
return Reply(status=500, body=json.dumps(outage).encode())
turn: Final = plan(body)
- done: Final = _has_tool_result(body)
- if done and billing.follow_up_fails:
+ answered: Final = _has_tool_result(body)
+ if answered and billing.follow_up_fails:
failure: Final = {"error": {"message": FOLLOW_UP_OUTAGE, "type": "server_error", "code": None}}
return Reply(status=500, body=json.dumps(failure).encode())
- prompt_tokens, completion_tokens = billing.follow_up if done else billing.first
+ done: Final = answered or DIRECT in _prompt(body)
+ calls: Final = range(1, parallel + 1)
+ prompt_tokens, completion_tokens = billing.follow_up if answered else billing.first
identity: Final = uuid.uuid4().hex[:12]
usage: Final = {
"prompt_tokens": prompt_tokens,
@@ -255,27 +274,21 @@ def _model_double(
"total_tokens": prompt_tokens + completion_tokens,
}
if request.target.endswith("/chat/completions"):
+ requested: Final = tuple(
+ {"id": f"call_{call}", "type": "function", "function": {"name": turn.tool, "arguments": turn.arguments}}
+ for call in calls
+ )
message: Final = (
{"role": "assistant", "content": turn.answer}
if done
- else {
- "role": "assistant",
- "content": None,
- "tool_calls": [
- {
- "id": "call_1",
- "type": "function",
- "function": {"name": turn.tool, "arguments": turn.arguments},
- }
- ],
- }
+ else {"role": "assistant", "content": None, "tool_calls": [*requested]}
)
finish: Final = "stop" if done else "tool_calls"
if body.get("stream") is True:
delta: Final = (
- {**message, "tool_calls": [{**call, "index": 0} for call in message["tool_calls"]]}
- if "tool_calls" in message
- else message
+ message
+ if done
+ else {**message, "tool_calls": [{**call, "index": index} for index, call in enumerate(requested)]}
)
chunk: Final = {
"id": f"chatcmpl-{identity}",
@@ -307,7 +320,10 @@ def _model_double(
content: Final = (
[{"type": "text", "text": turn.answer}]
if done
- else [{"type": "tool_use", "id": "toolu_1", "name": turn.tool, "input": json.loads(turn.arguments)}]
+ else [
+ {"type": "tool_use", "id": f"toolu_{call}", "name": turn.tool, "input": json.loads(turn.arguments)}
+ for call in calls
+ ]
)
return _json(
{
@@ -322,23 +338,28 @@ def _model_double(
}
)
assert request.target.endswith("/responses"), request.target
- item: Final[dict[str, JsonValue]] = (
- {
- "type": "message",
- "id": f"msg_{identity}",
- "role": "assistant",
- "status": "completed",
- "content": [{"type": "output_text", "text": turn.answer, "annotations": []}],
- }
+ items: Final[tuple[dict[str, JsonValue], ...]] = (
+ (
+ {
+ "type": "message",
+ "id": f"msg_{identity}",
+ "role": "assistant",
+ "status": "completed",
+ "content": [{"type": "output_text", "text": turn.answer, "annotations": []}],
+ },
+ )
if done
- else {
- "type": "function_call",
- "id": f"fc_{identity}",
- "call_id": f"call_{identity}",
- "name": turn.tool,
- "arguments": turn.arguments,
- "status": "completed",
- }
+ else tuple(
+ {
+ "type": "function_call",
+ "id": f"fc_{identity}_{call}",
+ "call_id": f"call_{identity}_{call}",
+ "name": turn.tool,
+ "arguments": turn.arguments,
+ "status": "completed",
+ }
+ for call in calls
+ )
)
response: Final[dict[str, JsonValue]] = {
"id": f"resp_{identity}",
@@ -346,14 +367,14 @@ def _model_double(
"created_at": 1,
"status": "completed",
"model": "gpt-4o-mini",
- "output": [item],
+ "output": [*items],
"usage": {
"input_tokens": prompt_tokens,
"output_tokens": completion_tokens,
"total_tokens": prompt_tokens + completion_tokens,
},
}
- return _responses_stream(response, item) if body.get("stream") is True else _json(response)
+ return _responses_stream(response, items) if body.get("stream") is True else _json(response)
return respond
@@ -373,17 +394,19 @@ class Rig:
def tool(self) -> str:
return f"{self.alias}-add"
- def send(self, key: str, tools: Sequence[Mapping[str, object]], **extra: object) -> httpx.Response:
- prompt: Final = f"add {self.alias}"
+ def send(
+ self, key: str, tools: Sequence[Mapping[str, object]], prompt: str | None = None, **extra: object
+ ) -> httpx.Response:
+ text: Final = prompt or f"add {self.alias}"
headers: Final = {"Authorization": f"Bearer {key}"}
if self.surface == "chat":
- body: Final = {"model": self.model, "messages": [{"role": "user", "content": prompt}], "tools": list(tools)}
+ body: Final = {"model": self.model, "messages": [{"role": "user", "content": text}], "tools": list(tools)}
return self.gateway.client.post("/v1/chat/completions", headers=headers, json={**body, **extra}, timeout=90)
if self.surface == "responses":
return self.gateway.client.post(
"/v1/responses",
headers=headers,
- json={"model": self.model, "input": prompt, "tools": list(tools), **extra},
+ json={"model": self.model, "input": text, "tools": list(tools), **extra},
timeout=90,
)
return self.gateway.client.post(
@@ -392,7 +415,7 @@ class Rig:
json={
"model": self.model,
"max_tokens": 64,
- "messages": [{"role": "user", "content": prompt}],
+ "messages": [{"role": "user", "content": text}],
"tools": list(tools),
**extra,
},
@@ -451,11 +474,12 @@ def _rig(
upstream: Surface | None = None,
billing: Billing = EVEN_ROUNDS,
prices: Mapping[str, JsonValue] | None = None,
+ parallel: int = 1,
) -> Iterator[Rig]:
alias: Final = "llm" + uuid.uuid4().hex[:8]
with (
mcp_peer() as peer,
- wire_server(_model_double(_fixed_turn(f"{alias}-add"), billing)) as wire,
+ wire_server(_model_double(_fixed_turn(f"{alias}-add"), billing, parallel)) as wire,
gateway.scenario() as scenario,
):
server_id: Final = register_mcp(scenario, peer, alias)
@@ -753,12 +777,12 @@ def _price(*rounds: tuple[int, int]) -> float:
return sum(prompt * input_price + completion * output_price for prompt, completion in rounds)
-def _responses_rows(call_id: str, status: str) -> list[dict[str, JsonValue]]:
+def _spend_rows(call_id: str, call_type: str, status: str) -> list[dict[str, JsonValue]]:
return eventually(
lambda: read_rows(
"SELECT request_id, spend, prompt_tokens, completion_tokens, session_id "
'FROM "LiteLLM_SpendLogs" WHERE litellm_call_id=%s AND call_type=%s AND status=%s',
- (call_id, "aresponses", status),
+ (call_id, call_type, status),
),
lambda found: len(found) >= 1,
seconds=70,
@@ -791,7 +815,7 @@ def test_nonstream_responses_auto_execute_logs_the_answer_and_bills_both_rounds(
assert response.status_code == 200, response.text
body: Final = JSON_OBJECT.validate_json(response.content)
assert rig.final_text(body) == ANSWER, response.text
- rows: Final = _responses_rows(response.headers["x-litellm-call-id"], "success")
+ rows: Final = _spend_rows(response.headers["x-litellm-call-id"], "aresponses", "success")
assert len(rows) == 1, rows
row: Final = rows[0]
assert row["request_id"] == body["id"], row
@@ -810,24 +834,123 @@ def test_nonstream_responses_auto_execute_logs_the_answer_and_bills_both_rounds(
)
-def test_nonstream_responses_failed_follow_up_bills_round_one_on_the_failure_row(gateway: Gateway) -> None:
+def test_nonstream_chat_auto_execute_logs_the_answer_and_bills_both_rounds(gateway: Gateway) -> None:
+ billing: Final = Billing(FIRST_ROUND, FOLLOW_UP_ROUND)
+ with _rig(gateway, "chat", billing=billing, prices=PRICES) as rig:
+ response: Final = rig.send(_granted_key(rig), [AUTO])
+ assert response.status_code == 200, response.text
+ body: Final = JSON_OBJECT.validate_json(response.content)
+ assert rig.final_text(body) == ANSWER, response.text
+ rows: Final = _spend_rows(response.headers["x-litellm-call-id"], "acompletion", "success")
+ assert len(rows) == 1, rows
+ row: Final = rows[0]
+ assert row["request_id"] == body["id"], row
+ assert (row["prompt_tokens"], row["completion_tokens"]) == (
+ FIRST_ROUND[0] + FOLLOW_UP_ROUND[0],
+ FIRST_ROUND[1] + FOLLOW_UP_ROUND[1],
+ ), row
+ assert object_value(body["usage"])["prompt_tokens"] == row["prompt_tokens"], body
+ assert float(str(row["spend"])) == pytest.approx(_price(FIRST_ROUND, FOLLOW_UP_ROUND)), row
+ assert float(response.headers["x-litellm-response-cost"]) == pytest.approx(float(str(row["spend"])))
+
+
+def test_nonstream_chat_auto_execute_without_a_tool_call_bills_the_one_call_it_made(gateway: Gateway) -> None:
+ billing: Final = Billing(FIRST_ROUND, FOLLOW_UP_ROUND)
+ with _rig(gateway, "chat", billing=billing, prices=PRICES) as rig:
+ response: Final = rig.send(_granted_key(rig), [AUTO], prompt=f"{DIRECT} {rig.alias}")
+ assert response.status_code == 200, response.text
+ body: Final = JSON_OBJECT.validate_json(response.content)
+ assert rig.final_text(body) == ANSWER, response.text
+ assert len(rig.upstream_tools()) == 1 and _peer_add_calls(rig.peer) == ()
+ rows: Final = _spend_rows(response.headers["x-litellm-call-id"], "acompletion", "success")
+ assert len(rows) == 1 and rows[0]["request_id"] == body["id"], rows
+ assert (rows[0]["prompt_tokens"], rows[0]["completion_tokens"]) == FIRST_ROUND, rows
+ assert float(str(rows[0]["spend"])) == pytest.approx(_price(FIRST_ROUND)), rows
+ assert float(response.headers["x-litellm-response-cost"]) == pytest.approx(float(str(rows[0]["spend"])))
+
+
+def test_nonstream_chat_auto_execute_charges_the_fixed_margin_once(gateway: Gateway) -> None:
+ billing: Final = Billing(FIRST_ROUND, FOLLOW_UP_ROUND)
+ with _rig(gateway, "chat", upstream="messages_bridge", billing=billing, prices=PRICES) as rig:
+ response: Final = rig.send(_granted_key(rig), [AUTO])
+ assert response.status_code == 200, response.text
+ assert len(rig.upstream_tools()) == 2
+ rows: Final = _spend_rows(response.headers["x-litellm-call-id"], "acompletion", "success")
+ assert len(rows) == 1, rows
+ assert float(str(rows[0]["spend"])) == pytest.approx(_price(FIRST_ROUND, FOLLOW_UP_ROUND) + FIXED_MARGIN), rows
+ assert float(response.headers["x-litellm-response-cost"]) == pytest.approx(float(str(rows[0]["spend"])))
+
+
+def test_nonstream_chat_auto_execute_whose_calls_both_come_from_the_response_cache_bills_nothing(
+ gateway: Gateway,
+) -> None:
+ billing: Final = Billing(FIRST_ROUND, FOLLOW_UP_ROUND)
+ with _rig(gateway, "chat", billing=billing, prices=PRICES) as rig:
+ key: Final = _granted_key(rig)
+ paid: Final = rig.send(key, [AUTO])
+ assert paid.status_code == 200, paid.text
+ assert len(rig.upstream_tools()) == 2 and len(_peer_add_calls(rig.peer)) == 1
+ cached: Final = rig.send(key, [{**AUTO, "server_label": "relabeled"}])
+ assert cached.status_code == 200, cached.text
+ assert rig.final_text(JSON_OBJECT.validate_json(cached.content)) == ANSWER, cached.text
+ assert rig.upstream_tools() == () and len(_peer_add_calls(rig.peer)) == 1
+ rows: Final = _spend_rows(cached.headers["x-litellm-call-id"], "acompletion", "success")
+ assert all(float(str(row["spend"])) == 0.0 for row in rows), rows
+ assert float(cached.headers["x-litellm-response-cost"]) == 0.0
+
+
[email protected](("surface", "call_type"), (("responses", "aresponses"), ("chat", "acompletion")))
+def test_nonstream_failed_follow_up_bills_round_one_on_the_failure_row(
+ gateway: Gateway, surface: Surface, call_type: str
+) -> None:
billing: Final = Billing(FIRST_ROUND, FOLLOW_UP_ROUND, follow_up_fails=True)
- with _rig(gateway, "responses", billing=billing, prices=PRICES) as rig:
+ with _rig(gateway, surface, billing=billing, prices=PRICES) as rig:
response: Final = rig.send(_granted_key(rig), [AUTO])
assert response.status_code == 500 and FOLLOW_UP_OUTAGE in response.text, response.text
call_id: Final = response.headers["x-litellm-call-id"]
- rows: Final = _responses_rows(call_id, "failure")
+ rows: Final = _spend_rows(call_id, call_type, "failure")
assert len(rows) == 1, rows
assert float(str(rows[0]["spend"])) == pytest.approx(_price(FIRST_ROUND)), rows
assert (
read_rows(
'SELECT request_id FROM "LiteLLM_SpendLogs" WHERE litellm_call_id=%s AND call_type=%s AND status=%s',
- (call_id, "aresponses", "success"),
+ (call_id, call_type, "success"),
)
== []
)
+def _tool_rows(call_id: str, expected: int) -> list[dict[str, JsonValue]]:
+ return eventually(
+ lambda: read_rows(
+ 'SELECT request_id FROM "LiteLLM_SpendLogs" WHERE call_type=%s AND strpos(request_id, %s) = 1',
+ ("call_mcp_tool", call_id),
+ ),
+ lambda found: len(found) >= expected,
+ seconds=70,
+ )
+
+
+ ("surface", "stream"),
+ (("chat", False), ("chat", True), ("messages", False), ("responses", True), ("responses", False)),
+ ids=("chat", "chat-stream", "messages", "responses-stream", "responses"),
+)
+def test_every_auto_executed_tool_call_lands_its_own_spend_row_under_the_request_call_id(
+ gateway: Gateway, surface: Surface, stream: bool
+) -> None:
+ with _rig(gateway, surface, parallel=2) as rig:
+ response: Final = rig.send(_granted_key(rig), [AUTO], stream=stream)
+ assert response.status_code == 200, response.text
+ assert [_add_call_arguments(call) for call in _peer_add_calls(rig.peer)] == [ADD, ADD]
+ call_id: Final = response.headers["x-litellm-call-id"]
+ request_ids: Final = frozenset(str(row["request_id"]) for row in _tool_rows(call_id, 2))
+ assert len(request_ids) == 2 and all(request_id.startswith(f"{call_id}_") for request_id in request_ids), (
+ call_id,
+ request_ids,
+ )
+
+
def test_bridged_responses_auto_execute_answers_every_tool_use_with_its_result(gateway: Gateway) -> None:
with _rig(gateway, "responses", upstream="messages") as rig:
response: Final = rig.send(_granted_key(rig), [AUTO])
diff --git a/tests/unit/responses/mcp/test_chat_completions_handler.py b/tests/unit/responses/mcp/test_chat_completions_handler.py
index 27477f24d92..9064eba161d 100644
--- a/tests/unit/responses/mcp/test_chat_completions_handler.py
+++ b/tests/unit/responses/mcp/test_chat_completions_handler.py
@@ -1,14 +1,23 @@
+import asyncio
import json
import sys
import types
+from collections.abc import Mapping, Sequence
+from datetime import datetime
+from types import MappingProxyType
+from typing import Final, cast
import pytest
import respx
from httpx import Response
+from mcp.types import Tool as MCPTool
from unittest.mock import AsyncMock, patch
import litellm
-from litellm.types.utils import ModelResponse
+from litellm.integrations.custom_logger import CustomLogger
+from litellm.litellm_core_utils.litellm_logging import Logging
+from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER
+from litellm.types.utils import ModelResponse, StandardLoggingPayload
from litellm.responses.mcp import chat_completions_handler
from litellm.responses.mcp.chat_completions_handler import (
@@ -1479,3 +1488,226 @@ async def test_request_selected_mcp_guardrail_blocks_before_upstream(monkeypatch
assert upstream.await_count == (0 if selected else 1)
tool_message = model_call.await_args.kwargs["messages"][-1]
assert ("request-selected MCP block" in tool_message["content"]) is selected
+
+
+_ECHO_ARGUMENTS: Final = '{"value": "PING"}'
+_CHAT_ROUND_ONE: Final = MappingProxyType(
+ {
+ "id": "chatcmpl-round-one",
+ "object": "chat.completion",
+ "created": 1,
+ "model": "gpt-5.6",
+ "choices": (
+ MappingProxyType(
+ {
+ "index": 0,
+ "finish_reason": "tool_calls",
+ "message": MappingProxyType(
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": (
+ MappingProxyType(
+ {
+ "id": "call_echo",
+ "type": "function",
+ "function": MappingProxyType({"name": "echo", "arguments": _ECHO_ARGUMENTS}),
+ }
+ ),
+ ),
+ }
+ ),
+ }
+ ),
+ ),
+ "usage": MappingProxyType(
+ {
+ "prompt_tokens": 71,
+ "completion_tokens": 19,
+ "total_tokens": 90,
+ "prompt_tokens_details": MappingProxyType({"cached_tokens": 32}),
+ }
+ ),
+ }
+)
+_CHAT_ROUND_TWO: Final = MappingProxyType(
+ {
+ "id": "chatcmpl-round-two",
+ "object": "chat.completion",
+ "created": 2,
+ "model": "gpt-5.6",
+ "choices": (
+ MappingProxyType(
+ {
+ "index": 0,
+ "finish_reason": "stop",
+ "message": MappingProxyType({"role": "assistant", "content": "PING"}),
+ }
+ ),
+ ),
+ "usage": MappingProxyType(
+ {
+ "prompt_tokens": 149,
+ "completion_tokens": 5,
+ "total_tokens": 154,
+ "prompt_tokens_details": MappingProxyType({"cached_tokens": 64}),
+ }
+ ),
+ }
+)
+_CONTEXT_WINDOW_ERROR: Final = MappingProxyType(
+ {
+ "error": MappingProxyType(
+ {
+ "message": "Your input exceeds the context window of this model.",
+ "type": "invalid_request_error",
+ "param": "messages",
+ "code": "context_length_exceeded",
+ }
+ )
+ }
+)
+
+
+class _ChatRoundRecorder(CustomLogger):
+ def __init__(self) -> None:
+ super().__init__()
+ self.logged: tuple[StandardLoggingPayload, ...] = ()
+ self.failed: tuple[StandardLoggingPayload, ...] = ()
+
+ async def async_log_success_event(
+ self, kwargs: Mapping[str, object], response_obj: object, start_time: datetime, end_time: datetime
+ ) -> None:
+ self.logged = (*self.logged, cast(StandardLoggingPayload, kwargs["standard_logging_object"]))
+
+ async def async_log_failure_event(
+ self, kwargs: Mapping[str, object], response_obj: object, start_time: datetime, end_time: datetime
+ ) -> None:
+ self.failed = (*self.failed, cast(StandardLoggingPayload, kwargs["standard_logging_object"]))
+
+
+def _chat_round_cost(body: Mapping[str, object]) -> float:
+ return litellm.completion_cost(
+ completion_response=ModelResponse(**json.loads(json.dumps(body, default=dict))),
+ model="gpt-5.6",
+ custom_llm_provider="openai",
+ )
+
+
+async def _settled() -> None:
+ await asyncio.sleep(0)
+ await asyncio.wait_for(GLOBAL_LOGGING_WORKER.flush(), timeout=10)
+
+
+async def _auto_execute_chat_echo(
+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch, rounds: Sequence[Response], call_id: str
+) -> tuple[_ChatRoundRecorder, ModelResponse | Exception]:
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ monkeypatch.setenv("DISABLE_AIOHTTP_TRANSPORT", "True")
+ litellm.in_memory_llm_clients_cache.flush_cache()
+ respx_mock.post("https://mcp-chat-rounds.example.com/v1/chat/completions").mock(side_effect=list(rounds))
+ recorder: Final = _ChatRoundRecorder()
+ logging_obj: Final = Logging(
+ model="openai/gpt-5.6",
+ messages=[{"role": "user", "content": "Call echo with PING"}],
+ stream=False,
+ call_type="acompletion",
+ start_time=datetime(2026, 1, 1),
+ litellm_call_id=call_id,
+ function_id=call_id,
+ dynamic_async_success_callbacks=[recorder],
+ dynamic_async_failure_callbacks=[recorder],
+ )
+ echo_tool: Final = MCPTool.model_validate(
+ {"name": "echo", "inputSchema": {"type": "object", "properties": {"value": {"type": "string"}}}},
+ by_name=False,
+ )
+ with (
+ patch.object(
+ LiteLLM_Proxy_MCP_Handler,
+ "process_mcp_tools_without_openai_transform",
+ AsyncMock(return_value=([echo_tool], {"echo": "demo"})),
+ ),
+ patch.object(
+ LiteLLM_Proxy_MCP_Handler,
+ "execute_tool_calls",
+ AsyncMock(return_value=[{"tool_call_id": "call_echo", "result": "PING", "name": "echo"}]),
+ ),
+ ):
+ try:
+ response: Final = await litellm.acompletion(
+ model="openai/gpt-5.6",
+ messages=[{"role": "user", "content": "Call echo with PING"}],
+ tools=[{"type": "mcp", "server_url": "litellm_proxy/mcp/demo", "require_approval": "never"}],
+ api_key="sk-mcp-chat-rounds",
+ api_base="https://mcp-chat-rounds.example.com/v1",
+ litellm_logging_obj=logging_obj,
+ )
+ except Exception as error:
+ await _settled()
+ return recorder, error
+ await _settled()
+ assert isinstance(response, ModelResponse)
+ return recorder, response
+
+
+def _ok(body: Mapping[str, object]) -> Response:
+ return Response(200, content=json.dumps(body, default=dict))
+
+
+async def test_non_stream_auto_execute_logs_one_row_billing_both_rounds_and_matching_the_client_cost(
+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
+):
+ recorder, response = await _auto_execute_chat_echo(
+ respx_mock, monkeypatch, (_ok(_CHAT_ROUND_ONE), _ok(_CHAT_ROUND_TWO)), "mcp-chat-rounds-both"
+ )
+
+ assert isinstance(response, ModelResponse)
+ assert response.choices[0].message.content == "PING"
+ both_rounds: Final = _chat_round_cost(_CHAT_ROUND_ONE) + _chat_round_cost(_CHAT_ROUND_TWO)
+ assert len(recorder.logged) == 1
+ row: Final = recorder.logged[0]
+ assert row["id"] == response.id
+ assert (row["prompt_tokens"], row["completion_tokens"]) == (71 + 149, 19 + 5)
+ assert row["metadata"]["usage_object"]["prompt_tokens_details"]["cached_tokens"] == 32 + 64
+ assert row["response_cost"] == pytest.approx(both_rounds)
+ assert row["cost_breakdown"]["total_cost"] == pytest.approx(both_rounds)
+ assert response.hidden_params["response_cost"] == pytest.approx(both_rounds)
+ assert (response.usage.prompt_tokens, response.usage.completion_tokens) == (71 + 149, 19 + 5)
+ assert recorder.failed == ()
+
+
+async def test_non_stream_auto_execute_without_a_tool_call_logs_the_one_round_it_made(
+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
+):
+ recorder, response = await _auto_execute_chat_echo(
+ respx_mock, monkeypatch, (_ok(_CHAT_ROUND_TWO),), "mcp-chat-rounds-no-tool-call"
+ )
+
+ assert isinstance(response, ModelResponse)
+ assert len(recorder.logged) == 1
+ assert recorder.logged[0]["id"] == response.id
+ assert (recorder.logged[0]["prompt_tokens"], recorder.logged[0]["completion_tokens"]) == (149, 5)
+ assert recorder.logged[0]["response_cost"] == pytest.approx(_chat_round_cost(_CHAT_ROUND_TWO))
+ assert response.hidden_params["response_cost"] == pytest.approx(recorder.logged[0]["response_cost"])
+
+
+async def test_non_stream_auto_execute_bills_the_paid_first_round_when_the_follow_up_fails(
+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
+):
+ recorder, outcome = await _auto_execute_chat_echo(
+ respx_mock,
+ monkeypatch,
+ (_ok(_CHAT_ROUND_ONE), Response(400, content=json.dumps(_CONTEXT_WINDOW_ERROR, default=dict))),
+ "mcp-chat-rounds-follow-up-fails",
+ )
+
+ assert isinstance(outcome, litellm.BadRequestError)
+ assert recorder.logged == ()
+ assert len(recorder.failed) == 1
+ assert (recorder.failed[0]["prompt_tokens"], recorder.failed[0]["completion_tokens"]) == (71, 19)
+ assert recorder.failed[0]["response_cost"] == pytest.approx(_chat_round_cost(_CHAT_ROUND_ONE))
+ assert recorder.failed[0]["response_cost"] > 0
diff --git a/tests/unit/responses/mcp/test_litellm_proxy_mcp_handler.py b/tests/unit/responses/mcp/test_litellm_proxy_mcp_handler.py
index f43e15cb342..26553558298 100644
--- a/tests/unit/responses/mcp/test_litellm_proxy_mcp_handler.py
+++ b/tests/unit/responses/mcp/test_litellm_proxy_mcp_handler.py
@@ -420,20 +420,16 @@ async def test_execute_tool_calls_logs_failure_via_post_call_failure_hook(monkey
@pytest.mark.asyncio
-async def test_execute_tool_calls_passes_litellm_call_id_and_trace_id_to_function_setup(
+async def test_execute_tool_calls_logs_each_tool_call_under_its_own_id_on_the_request_trace(
monkeypatch,
):
- """
- Regression test for ae4d92ad...:
- Ensure litellm_call_id / litellm_trace_id are forwarded into function_setup kwargs.
- """
_setup_proxy_logging(monkeypatch)
call_tool_mock = _setup_mcp_call_environment(monkeypatch)
- captured = {}
+ captured: list[dict[str, object]] = []
def fake_function_setup(*_args, **kwargs):
- captured.update(kwargs)
+ captured.append(kwargs)
return None, None
# NOTE: Don't patch via dotted string path here because `litellm.responses`
@@ -443,7 +439,10 @@ async def test_execute_tool_calls_passes_litellm_call_id_and_trace_id_to_functio
monkeypatch.setattr(handler_module, "function_setup", fake_function_setup)
tool_name = "deepwiki-read_wiki_structure"
- tool_calls = [{"id": "call-1", "function": {"name": tool_name, "arguments": "{}"}}]
+ tool_calls = [
+ {"id": "call-1", "function": {"name": tool_name, "arguments": "{}"}},
+ {"id": "call-2", "function": {"name": tool_name, "arguments": "{}"}},
+ ]
await LiteLLM_Proxy_MCP_Handler.execute_tool_calls(
tool_server_map={tool_name: "deepwiki"},
@@ -453,11 +452,13 @@ async def test_execute_tool_calls_passes_litellm_call_id_and_trace_id_to_functio
litellm_trace_id="tid",
)
- # Ensure the tool call was attempted (sanity)
- assert call_tool_mock.await_count == 1
-
- assert captured.get("litellm_call_id") == "cid"
- assert captured.get("litellm_trace_id") == "tid"
+ assert call_tool_mock.await_count == 2
+ tool_call_ids: Final = [kwargs.get("litellm_call_id") for kwargs in captured]
+ assert len(tool_call_ids) == 2
+ assert "cid" not in tool_call_ids
+ assert len(set(tool_call_ids)) == 2
+ assert all(isinstance(tool_call_id, str) and tool_call_id.startswith("cid") for tool_call_id in tool_call_ids)
+ assert [kwargs.get("litellm_trace_id") for kwargs in captured] == ["tid", "tid"]
@pytest.mark.asyncio
diff --git a/tests/unit/responses/mcp/test_round_billing.py b/tests/unit/responses/mcp/test_round_billing.py
index 993b38de16a..99bb931bc27 100644
--- a/tests/unit/responses/mcp/test_round_billing.py
+++ b/tests/unit/responses/mcp/test_round_billing.py
@@ -4,9 +4,10 @@ from typing import Final
import pytest
+from litellm.llms.anthropic.chat.transformation import AnthropicConfig
from litellm.responses.mcp.round_billing import billed_for_every_round, merged_round_usage, summed_cost_breakdown
from litellm.types.llms.openai import ResponseAPIUsage, ResponsesAPIResponse
-from litellm.types.utils import CostBreakdown
+from litellm.types.utils import CostBreakdown, ModelResponse, Usage
def _round(response_id: str, response_cost: object, served_from_cache: bool = False) -> ResponsesAPIResponse:
@@ -216,3 +217,71 @@ def test_a_round_served_from_the_response_cache_drops_out_of_the_breakdown(
)
assert breakdown == (None if kept_breakdown is None else breakdowns[kept_breakdown])
+
+
+def _anthropic_chat_round(response_id: str, anthropic_usage: Mapping[str, object]) -> ModelResponse:
+ response: Final = ModelResponse(
+ id=response_id,
+ model="claude-haiku-5-5",
+ usage=AnthropicConfig().calculate_usage(anthropic_usage, reasoning_content=None),
+ )
+ response._hidden_params["response_cost"] = 0.001
+ return response
+
+
+def _usage_of(response: ModelResponse) -> Usage:
+ usage: Final = response.usage
+ assert isinstance(usage, Usage)
+ return usage
+
+
+def test_billed_chat_usage_sums_every_provider_counter_and_adds_no_field_the_rounds_lacked():
+ first: Final = _anthropic_chat_round(
+ "msg_first",
+ MappingProxyType(
+ {
+ "input_tokens": 400,
+ "output_tokens": 10,
+ "cache_creation_input_tokens": 50,
+ "cache_read_input_tokens": 30,
+ "cache_creation": MappingProxyType({"ephemeral_5m_input_tokens": 50, "ephemeral_1h_input_tokens": 0}),
+ "server_tool_use": MappingProxyType({"web_search_requests": 1}),
+ "service_tier": "standard",
+ }
+ ),
+ )
+ final: Final = _anthropic_chat_round(
+ "msg_final",
+ MappingProxyType(
+ {
+ "input_tokens": 500,
+ "output_tokens": 20,
+ "cache_creation_input_tokens": 0,
+ "cache_read_input_tokens": 80,
+ "cache_creation": MappingProxyType({"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0}),
+ "server_tool_use": MappingProxyType({"web_search_requests": 2}),
+ "service_tier": "priority",
+ }
+ ),
+ )
+
+ billed: Final = _usage_of(billed_for_every_round(first=first, first_breakdown=None, final=final, final_breakdown=None))
+ first_usage: Final = _usage_of(first)
+ final_usage: Final = _usage_of(final)
+
+ assert billed.model_dump(exclude_none=True).keys() == first_usage.model_dump(exclude_none=True).keys()
+ assert billed.prompt_tokens == first_usage.prompt_tokens + final_usage.prompt_tokens
+ assert billed.completion_tokens == first_usage.completion_tokens + final_usage.completion_tokens
+ assert billed["cache_read_input_tokens"] == 30 + 80
+ assert billed["cache_creation_input_tokens"] == 50 + 0
+ assert billed.server_tool_use is not None
+ assert billed.server_tool_use.web_search_requests == 1 + 2
+ assert billed.prompt_tokens_details is not None
+ assert billed.prompt_tokens_details.cached_tokens == 30 + 80
+ assert billed.prompt_tokens_details.model_dump(exclude_none=True) == {
+ key: first_value + final_value
+ for key, first_value in first_usage.prompt_tokens_details.model_dump(exclude_none=True).items()
+ if isinstance(first_value, int)
+ and isinstance(final_value := final_usage.prompt_tokens_details.model_dump()[key], int)
+ } | {"cache_creation_token_details": {"ephemeral_5m_input_tokens": 50, "ephemeral_1h_input_tokens": 0}}
+ assert billed["service_tier"] == "priority"