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(proxy): close the adversarial-review findings on the tool spend rollup

Tin Chi Lo1240c1a76d12
diff --git a/litellm/litellm_core_utils/prompt_templates/factory.py b/litellm/litellm_core_utils/prompt_templates/factory.py
index c13cf0817b5..4e3d94e2ab3 100644
--- a/litellm/litellm_core_utils/prompt_templates/factory.py
+++ b/litellm/litellm_core_utils/prompt_templates/factory.py
@@ -5382,14 +5382,18 @@ def _parse_tool_call_arguments(raw: Any, tool_name: Optional[str], context: str)
return parsed if isinstance(parsed, dict) else {}
-def _tool_calls_from_chat_completion_response(response: Any) -> list[NormalizedToolCall]:
+def _tool_calls_from_chat_completion_response(
+ response: Any, include_all_choices: bool = False
+) -> list[NormalizedToolCall]:
choices = get_attribute_or_key(response, "choices", None)
if not (isinstance(choices, list) and choices):
return []
- message = get_attribute_or_key(choices[0], "message", None)
- tool_calls = get_attribute_or_key(message, "tool_calls", None) if message else None
- if not isinstance(tool_calls, list):
- return []
+ tool_calls: list[Any] = []
+ for choice in choices if include_all_choices else choices[:1]:
+ message = get_attribute_or_key(choice, "message", None)
+ choice_tool_calls = get_attribute_or_key(message, "tool_calls", None) if message else None
+ if isinstance(choice_tool_calls, list):
+ tool_calls.extend(choice_tool_calls)
result: list[NormalizedToolCall] = []
for tc in tool_calls:
fn = get_attribute_or_key(tc, "function", None)
@@ -5452,7 +5456,7 @@ def _tool_calls_from_anthropic_messages_response(response: Any) -> list[Normaliz
return result
-def get_tool_calls_from_response(response: Any) -> list[NormalizedToolCall]:
+def get_tool_calls_from_response(response: Any, include_all_choices: bool = False) -> list[NormalizedToolCall]:
"""
Extract tool/function calls from a response object into a normalized
``{"id", "name", "arguments"}`` shape, regardless of which API surface
@@ -5460,11 +5464,20 @@ def get_tool_calls_from_response(response: Any) -> list[NormalizedToolCall]:
the Responses API (``output`` items of type ``function_call``), or the
Anthropic Messages API (``content`` blocks of type ``tool_use``).
+ ``include_all_choices`` decides the chat-completions scope: the default
+ reads only ``choices[0]``, which is what consumers that act on THE reply
+ (e.g. guardrails rebuilding the primary assistant message) want; usage
+ accounting passes True because every choice of an ``n>1`` request costs
+ money and its tool calls really ran. The other surfaces have a single
+ output, so the flag has no effect on them.
+
Callers that only care about a specific tool should filter the result by
``name`` themselves -- this returns every tool call found.
"""
+ chat_tool_calls = _tool_calls_from_chat_completion_response(response, include_all_choices=include_all_choices)
+ if chat_tool_calls:
+ return chat_tool_calls
for extractor in (
- _tool_calls_from_chat_completion_response,
_tool_calls_from_responses_api_response,
_tool_calls_from_anthropic_messages_response,
):
diff --git a/litellm/proxy/db/spend_log_tool_index.py b/litellm/proxy/db/spend_log_tool_index.py
index 064d08acb59..a478248b0fa 100644
--- a/litellm/proxy/db/spend_log_tool_index.py
+++ b/litellm/proxy/db/spend_log_tool_index.py
@@ -18,7 +18,7 @@ from datetime import datetime, timezone
from itertools import groupby
from typing import TYPE_CHECKING, Any, Sequence
-from litellm.proxy._types import DB_CONNECTION_ERROR_TYPES
+import httpx
if TYPE_CHECKING:
from litellm.proxy.utils import PrismaClient
@@ -37,7 +37,8 @@ class ToolUsageTransaction:
def response_tool_call_names(completion_response: Any) -> tuple[str, ...]:
"""Tool names invoked in a completion response, in call order, for any response
surface get_tool_calls_from_response understands (chat completions, Responses
- API output items, Anthropic Messages tool_use blocks)."""
+ API output items, Anthropic Messages tool_use blocks). Reads every choice of
+ an ``n>1`` chat response: each choice cost money and its tool calls ran."""
if completion_response is None or isinstance(completion_response, Exception):
return ()
from litellm.litellm_core_utils.prompt_templates.factory import (
@@ -46,7 +47,7 @@ def response_tool_call_names(completion_response: Any) -> tuple[str, ...]:
return tuple(
stripped
- for tool_call in get_tool_calls_from_response(completion_response)
+ for tool_call in get_tool_calls_from_response(completion_response, include_all_choices=True)
if isinstance(name := tool_call.get("name"), str) and (stripped := name.strip())
)
@@ -97,11 +98,13 @@ async def flush_tool_usage_transactions(
n_retry_times: int = 3,
) -> None:
"""Write index rows and rollup upserts for a drained queue batch in one
- transaction. Connection errors are retried with backoff, which cannot
- double-count because a failed batch commits nothing; every other error
- propagates so the caller drops the batch. Callers must not add their own
- retry around this function: a batch that DID commit must never run again,
- since the rollup update increments counters."""
+ transaction. Retries only ConnectError, the one failure that proves the
+ statements never reached the database. Post-send failures (Read timeouts
+ and errors) are ambiguous and are NOT retried: the engine can abandon the
+ transaction open on the pooled connection, so a retry's statements stack
+ into the same transaction and one commit applies both increment sets.
+ Ambiguous failures drop the batch; the caller logs it at error. Callers
+ must not add their own retry around this function."""
if not transactions:
return
@@ -141,7 +144,7 @@ async def flush_tool_usage_transactions(
},
)
return
- except DB_CONNECTION_ERROR_TYPES:
+ except httpx.ConnectError:
if attempt >= n_retry_times:
raise
await asyncio.sleep(2**attempt + random.uniform(0, 1))
diff --git a/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py b/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py
index bcda88ea609..9565de1139c 100644
--- a/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py
+++ b/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py
@@ -3166,3 +3166,34 @@ async def test_bedrock_converse_message_level_cache_point_preserves_ttl_async():
)
assert _collect_cache_points(result) == [{"type": "default", "ttl": "1h"}]
+
+
+def _n_choices_response(*names_per_choice):
+ from types import SimpleNamespace
+
+ choices = [
+ SimpleNamespace(
+ message=SimpleNamespace(
+ tool_calls=[SimpleNamespace(id=f"c{i}", function=SimpleNamespace(name=name, arguments="{}"))]
+ )
+ )
+ for i, name in enumerate(names_per_choice)
+ ]
+ return SimpleNamespace(choices=choices)
+
+
+def test_get_tool_calls_from_response_defaults_to_primary_choice_only():
+ from litellm.litellm_core_utils.prompt_templates.factory import get_tool_calls_from_response
+
+ response = _n_choices_response("tool_alpha", "tool_beta")
+
+ assert [tc["name"] for tc in get_tool_calls_from_response(response)] == ["tool_alpha"]
+
+
+def test_get_tool_calls_from_response_include_all_choices_reads_every_choice():
+ from litellm.litellm_core_utils.prompt_templates.factory import get_tool_calls_from_response
+
+ response = _n_choices_response("tool_alpha", "tool_beta")
+
+ names = [tc["name"] for tc in get_tool_calls_from_response(response, include_all_choices=True)]
+ assert names == ["tool_alpha", "tool_beta"]
diff --git a/tests/test_litellm/proxy/db/test_db_spend_update_writer.py b/tests/test_litellm/proxy/db/test_db_spend_update_writer.py
index 8759b008549..cd293325c15 100644
--- a/tests/test_litellm/proxy/db/test_db_spend_update_writer.py
+++ b/tests/test_litellm/proxy/db/test_db_spend_update_writer.py
@@ -181,6 +181,24 @@ async def test_update_database_enqueues_realtime_tool_usage():
assert prisma.tool_usage_transactions[0].tool_names == ("rt_tool",)
+def test_enqueue_tool_registry_upsert_reads_every_choice():
+ from types import SimpleNamespace as NS
+
+ db_writer = DBSpendUpdateWriter()
+ db_writer.tool_discovery_queue = MagicMock()
+ response = NS(
+ choices=[
+ NS(message=NS(tool_calls=[NS(function=NS(name="tool_alpha"))])),
+ NS(message=NS(tool_calls=[NS(function=NS(name="tool_beta"))])),
+ ]
+ )
+
+ db_writer._enqueue_tool_registry_upsert(kwargs={}, completion_response=response)
+
+ enqueued = [call.args[0]["tool_name"] for call in db_writer.tool_discovery_queue.add_update.call_args_list]
+ assert enqueued == ["tool_alpha", "tool_beta"]
+
+
@pytest.mark.asyncio
async def test_update_database_skips_tool_usage_when_spend_logs_disabled():
db_writer = DBSpendUpdateWriter()
diff --git a/tests/test_litellm/proxy/db/test_spend_log_tool_index.py b/tests/test_litellm/proxy/db/test_spend_log_tool_index.py
index 3b6acaa1eb3..71073fd216e 100644
--- a/tests/test_litellm/proxy/db/test_spend_log_tool_index.py
+++ b/tests/test_litellm/proxy/db/test_spend_log_tool_index.py
@@ -134,6 +134,29 @@ class TestBuildToolUsageTransaction:
assert transaction is not None
assert transaction.tool_names == ("get_weather",)
+ def test_n_greater_than_one_tools_from_every_choice_reach_the_transaction(self):
+ # Regression: an n>1 request pays for every choice, and a tool invoked
+ # only in a later choice really ran; it must not be dropped because the
+ # extractor read choices[0] alone.
+ from types import SimpleNamespace as NS
+
+ response = NS(
+ choices=[
+ NS(message=NS(tool_calls=[NS(function=NS(name="tool_alpha"))])),
+ NS(message=NS(tool_calls=[NS(function=NS(name="tool_beta"))])),
+ ]
+ )
+ transaction = build_tool_usage_transaction(
+ request_id="r1",
+ start_time_iso="2026-07-25T10:00:00+00:00",
+ mcp_namespaced_tool_name=None,
+ spend=0.5,
+ total_tokens=100,
+ completion_response=response,
+ )
+ assert transaction is not None
+ assert transaction.tool_names == ("tool_alpha", "tool_beta")
+
def test_unparseable_start_time_returns_none(self):
assert (
build_tool_usage_transaction(
@@ -307,3 +330,19 @@ class TestFlushToolUsageTransactions:
with pytest.raises(ValueError):
await flush_tool_usage_transactions(prisma_client=prisma, transactions=[_transaction("r1")])
prisma.db.batch_.assert_called_once()
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("ambiguous_error", ["ReadTimeout", "ReadError"])
+ async def test_post_send_ambiguous_errors_drop_without_retry(self, ambiguous_error):
+ # A ReadTimeout means the statements were sent and the outcome is
+ # unknown; the engine can leave the transaction open on the pooled
+ # connection, so a retry's statements would stack into it and one
+ # commit would apply both increment sets. These must never retry.
+ import httpx
+
+ error = getattr(httpx, ambiguous_error)("ambiguous")
+ prisma = MagicMock()
+ prisma.db.batch_ = MagicMock(side_effect=error)
+ with pytest.raises((httpx.ReadTimeout, httpx.ReadError)):
+ await flush_tool_usage_transactions(prisma_client=prisma, transactions=[_transaction("r1")])
+ prisma.db.batch_.assert_called_once()
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/UsageTab.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/UsageTab.test.tsx
index beeb9466b1d..5c26ac30477 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/UsageTab.test.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/UsageTab.test.tsx
@@ -28,17 +28,20 @@ vi.mock("@/components/shared/charts", () => ({
categories,
colors,
showLegend,
+ maxBarSize,
}: {
data: unknown;
categories: string[];
colors?: readonly string[];
showLegend?: boolean;
+ maxBarSize?: number;
}) => (
<div
data-testid="bar-chart"
data-categories={categories.join(",")}
data-colors={(colors ?? []).join(",")}
data-show-legend={String(showLegend ?? true)}
+ data-max-bar-size={maxBarSize === undefined ? "" : String(maxBarSize)}
data-series={JSON.stringify(data)}
/>
),
@@ -240,6 +243,9 @@ describe("UsageTab", () => {
const bars = await findAllByTestId("bar-chart");
const series = JSON.parse(bars[0].getAttribute("data-series") ?? "[]");
expect(series[0]).toMatchObject({ tool_name: "search", spend: 4.0 });
+ // The 64px bar cap is this card's opt-in; the shared BarChart must not cap
+ // by default (other consumers keep their pre-existing geometry).
+ expect(bars[0].getAttribute("data-max-bar-size")).toBe("64");
});
it("renders the tool legend once outside the charts, with both charts sharing the tool colors", async () => {
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/UsageTab.tsx b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/UsageTab.tsx
index 829a79d7638..ec37418e0b5 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/UsageTab.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/UsageTab.tsx
@@ -282,6 +282,7 @@ const UsageTab: React.FC<UsageTabProps> = ({ accessToken, activity }) => {
colorByDatum
layout="vertical"
yAxisWidth={140}
+ maxBarSize={64}
showLegend={false}
valueFormatter={usd}
/>
@@ -295,6 +296,7 @@ const UsageTab: React.FC<UsageTabProps> = ({ accessToken, activity }) => {
categories={topToolNames}
colors={toolColors}
stack
+ maxBarSize={64}
valueFormatter={usd}
showLegend={false}
/>
diff --git a/ui/litellm-dashboard/src/components/shared/charts/bar_chart.tsx b/ui/litellm-dashboard/src/components/shared/charts/bar_chart.tsx
index 6bfcf14c2a0..ab2cc66eaf4 100644
--- a/ui/litellm-dashboard/src/components/shared/charts/bar_chart.tsx
+++ b/ui/litellm-dashboard/src/components/shared/charts/bar_chart.tsx
@@ -7,14 +7,13 @@ import { cn } from "@/lib/cva.config";
import { ValueTooltip, type ChartTooltipComponent } from "./chart_tooltip";
import { categoryFills, type ChartColor } from "./colors";
-const MAX_BAR_SIZE = 64;
-
export type BarChartProps<TDatum extends Record<string, unknown>> = {
data: readonly TDatum[];
index: string;
categories: readonly string[];
colors?: readonly ChartColor[];
colorByDatum?: boolean;
+ maxBarSize?: number;
valueFormatter?: (value: number) => string;
stack?: boolean;
layout?: "horizontal" | "vertical";
@@ -36,6 +35,7 @@ export function BarChart<TDatum extends Record<string, unknown>>({
categories,
colors,
colorByDatum = false,
+ maxBarSize,
valueFormatter,
stack = false,
layout = "horizontal",
@@ -119,7 +119,7 @@ export function BarChart<TDatum extends Record<string, unknown>>({
fill={fills[i]}
stackId={stack ? "stack" : undefined}
isAnimationActive={false}
- maxBarSize={MAX_BAR_SIZE}
+ maxBarSize={maxBarSize}
onClick={
onValueChange
? (item: { payload?: TDatum }) => {