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(responses)!: count input tokens the way inference sends the request (#47363)

Mateo Wang91724bb0a7c8
diff --git a/litellm/litellm_core_utils/prompt_templates/common_utils.py b/litellm/litellm_core_utils/prompt_templates/common_utils.py
index b89e4d609ad..60be4d44706 100644
--- a/litellm/litellm_core_utils/prompt_templates/common_utils.py
+++ b/litellm/litellm_core_utils/prompt_templates/common_utils.py
@@ -624,7 +624,7 @@ def update_messages_with_model_file_ids(
def update_responses_input_with_model_file_ids(
input: object,
model_id: str | None = None,
- model_file_id_mapping: dict[str, dict[str, str]] | None = None,
+ model_file_id_mapping: Mapping[str, Mapping[str, str]] | None = None,
) -> object:
"""
Updates responses API input with provider-specific file IDs.
@@ -665,7 +665,7 @@ def update_responses_input_with_model_file_ids(
for content_item in content:
if isinstance(content_item, dict) and content_item.get("type") == "input_file":
file_id = content_item.get("file_id")
- if file_id:
+ if isinstance(file_id, str) and file_id:
provider_file_id = file_id # Default to original
# Check if we have a mapping for this file ID
@@ -761,7 +761,7 @@ def _decode_vector_store_ids_in_tools(
def update_responses_tools_with_model_file_ids(
tools: list[dict[str, object]] | None,
model_id: str | None = None,
- model_file_id_mapping: dict[str, dict[str, str]] | None = None,
+ model_file_id_mapping: Mapping[str, Mapping[str, str]] | None = None,
) -> list[dict[str, object]] | None:
"""
Updates responses API tools with provider-specific file IDs.
diff --git a/litellm/llms/anthropic/count_tokens/token_counter.py b/litellm/llms/anthropic/count_tokens/token_counter.py
index ecf050d185e..0764fb41941 100644
--- a/litellm/llms/anthropic/count_tokens/token_counter.py
+++ b/litellm/llms/anthropic/count_tokens/token_counter.py
@@ -2,6 +2,8 @@
Anthropic Token Counter implementation using the CountTokens API.
"""
+from collections.abc import Mapping
+from types import MappingProxyType
from typing import Any, Final
from pydantic import JsonValue
@@ -10,6 +12,11 @@ import litellm
from litellm._logging import verbose_logger
from litellm.exceptions import AuthenticationError
from litellm.llms.anthropic.count_tokens.handler import AnthropicCountTokensHandler
+from litellm.llms.anthropic.count_tokens.transformation import (
+ AnthropicCountFields,
+ ChatCountTranslationError,
+ anthropic_count_fields,
+)
from litellm.llms.base_llm.base_utils import BaseTokenCounter
from litellm.types.utils import CountContextManagement, LlmProviders, TokenCountMessagesFormat, TokenCountResponse
@@ -38,6 +45,8 @@ class AnthropicTokenCounter(BaseTokenCounter):
messages_format: TokenCountMessagesFormat = "anthropic",
output_format: JsonValue = None,
context_management: CountContextManagement | None = None,
+ chat_params: Mapping[str, JsonValue] = MappingProxyType({}),
+ count_options: Mapping[str, JsonValue] = MappingProxyType({}),
) -> TokenCountResponse | None:
"""
Count tokens using Anthropic's CountTokens API.
@@ -57,6 +66,30 @@ class AnthropicTokenCounter(BaseTokenCounter):
if not messages:
return None
+ from litellm.llms.anthropic.chat.transformation import AnthropicConfig
+
+ match translated := await anthropic_count_fields(
+ model_to_use, messages, system, tools, messages_format, AnthropicConfig(), chat_params
+ ):
+ case ChatCountTranslationError():
+ return translated.response(request_model, model_to_use, "anthropic_api")
+ case AnthropicCountFields():
+ return await self.count_tokens(
+ model_to_use=model_to_use,
+ messages=[dict(message) for message in translated.messages],
+ contents=contents,
+ deployment=deployment,
+ request_model=request_model,
+ tools=[dict(tool) for tool in translated.tools] if translated.tools is not None else None,
+ system=translated.system,
+ messages_format="anthropic",
+ output_format=output_format,
+ context_management=context_management,
+ count_options=translated.options,
+ )
+ case None:
+ pass
+
deployment = deployment or {}
litellm_params: Final = deployment.get("litellm_params", {})
api_base: Final = litellm_params.get("api_base")
@@ -89,6 +122,7 @@ class AnthropicTokenCounter(BaseTokenCounter):
api_base=api_base,
tools=tools,
system=system,
+ optional_params=count_options,
)
if result is not None:
diff --git a/litellm/llms/anthropic/count_tokens/transformation.py b/litellm/llms/anthropic/count_tokens/transformation.py
index 8e2688d4360..592b5fb0f00 100644
--- a/litellm/llms/anthropic/count_tokens/transformation.py
+++ b/litellm/llms/anthropic/count_tokens/transformation.py
@@ -4,25 +4,37 @@ Anthropic CountTokens API transformation logic.
This module handles the transformation of requests to Anthropic's CountTokens API format.
"""
+import copy
from collections.abc import Mapping, Sequence
+from dataclasses import dataclass
+from itertools import chain
from types import MappingProxyType
-from typing import Final
+from typing import (
+ Final,
+ Protocol,
+ TypeAlias,
+ cast, # noqa: TID251 # caller chat messages go to chat inference translation as-is
+)
-from pydantic import JsonValue, TypeAdapter
+from pydantic import ConfigDict, JsonValue, TypeAdapter, with_config
+from typing_extensions import NotRequired, ReadOnly, TypedDict
from litellm.constants import ANTHROPIC_TOKEN_COUNTING_BETA_VERSION
+from litellm.litellm_core_utils.asyncify import asyncify
from litellm.litellm_core_utils.prompt_templates.mid_conversation_system import (
anthropic_system_blocks,
split_leading_system_run,
)
from litellm.llms.anthropic.common_utils import merge_anthropic_beta_headers
from litellm.llms.anthropic.wif import resolve_anthropic_base
-from litellm.types.llms.openai import ChatCompletionImageObject
+from litellm.types.llms.openai import AllMessageValues, ChatCompletionImageObject, ValidUserMessageContentTypes
+from litellm.types.utils import TokenCountMessagesFormat, TokenCountResponse
_COUNT_REQUEST: Final = TypeAdapter(dict[str, JsonValue])
_SYSTEM_BLOCKS: Final = TypeAdapter(list[JsonValue])
_IMAGE_BLOCK: Final = TypeAdapter(ChatCompletionImageObject)
COUNT_TOKEN_OPTION_NAMES: Final = ("thinking", "tool_choice", "output_config")
+_PLAIN_MESSAGE_KEYS: Final = frozenset({"role", "content"})
def _count_image(block: JsonValue) -> JsonValue:
@@ -74,6 +86,213 @@ def _lift_leading_system(
return conversation, lifted or system
+@dataclass(frozen=True, slots=True)
+class AnthropicCountFields:
+ messages: tuple[Mapping[str, JsonValue], ...]
+ system: JsonValue
+ tools: tuple[Mapping[str, JsonValue], ...] | None
+ options: Mapping[str, JsonValue]
+
+
+@dataclass(frozen=True, slots=True)
+class ChatCountTranslationError:
+ message: str
+
+ def response(self, request_model: str, model_used: str, tokenizer_type: str) -> TokenCountResponse:
+ return TokenCountResponse(
+ total_tokens=0,
+ request_model=request_model,
+ model_used=model_used,
+ tokenizer_type=tokenizer_type,
+ error=True,
+ error_message=self.message,
+ status_code=400,
+ rejected_before_provider_call=True,
+ )
+
+
+@with_config(ConfigDict(extra="ignore"))
+class _AnthropicChatRequest(TypedDict):
+ messages: ReadOnly[tuple[Mapping[str, JsonValue], ...]]
+ system: NotRequired[ReadOnly[JsonValue]]
+ tools: NotRequired[ReadOnly[tuple[Mapping[str, JsonValue], ...]]]
+ thinking: NotRequired[ReadOnly[JsonValue]]
+ tool_choice: NotRequired[ReadOnly[JsonValue]]
+ output_config: NotRequired[ReadOnly[JsonValue]]
+ output_format: NotRequired[ReadOnly[JsonValue]]
+
+
+_ANTHROPIC_CHAT_REQUEST: Final = TypeAdapter(_AnthropicChatRequest)
+_ChatParams: TypeAlias = dict[str, object]
+_ChatMessages: TypeAlias = list[AllMessageValues]
+
+
+class _ChatRequestTranslator(Protocol):
+ def map_openai_params(
+ self, non_default_params: _ChatParams, optional_params: _ChatParams, model: str, drop_params: bool
+ ) -> _ChatParams: ...
+
+ def transform_request(
+ self,
+ model: str,
+ messages: _ChatMessages,
+ optional_params: _ChatParams,
+ litellm_params: _ChatParams,
+ headers: _ChatParams,
+ ) -> _ChatParams: ...
+
+
+def _needs_chat_translation(message: Mapping[str, object]) -> bool:
+ return message.get("role") == "tool" or not _PLAIN_MESSAGE_KEYS.issuperset(message.keys())
+
+
+def _is_chat_tool(tool: Mapping[str, object]) -> bool:
+ from litellm.litellm_core_utils.prompt_templates.factory import is_flat_responses_tool
+
+ return is_flat_responses_tool(tool) or (tool.get("type") == "function" and "function" in tool)
+
+
+def _has_non_chat_user_block(message: Mapping[str, object]) -> bool:
+ content: Final = message.get("content")
+ if message.get("role") != "user" or not isinstance(content, list):
+ return False
+ blocks: Final = _SYSTEM_BLOCKS.validate_python(content)
+ return any(isinstance(block, dict) and block.get("type") not in ValidUserMessageContentTypes for block in blocks)
+
+
+def _gets_placeholder_name(tool: Mapping[str, object]) -> bool:
+ from litellm.llms.anthropic.pass_through.adapters.transformation import is_provider_native_tool_dict
+
+ name: Final = tool.get("name")
+ return not (_is_chat_tool(tool) or is_provider_native_tool_dict(tool) or (isinstance(name, str) and name.strip()))
+
+
+def _untranslatable_input(
+ messages: Sequence[Mapping[str, object]], tools: Sequence[Mapping[str, object]]
+) -> ChatCountTranslationError | None:
+ invalid_index: Final = next(
+ (index for index, message in enumerate(messages) if _has_non_chat_user_block(message)), None
+ )
+ if invalid_index is not None:
+ return ChatCountTranslationError(
+ message=f"Invalid user message at index {invalid_index}. "
+ "Please ensure all user messages are valid OpenAI chat completion messages."
+ )
+ unnamed_tool: Final = next(filter(_gets_placeholder_name, tools), None)
+ if unnamed_tool is not None:
+ return ChatCountTranslationError(
+ message=f"Invalid request for token counting: tool type {unnamed_tool.get('type')!r} "
+ "has no Chat Completions equivalent"
+ )
+ return None
+
+
+def _system_messages(system: object) -> tuple[Mapping[str, object], ...]:
+ message: Final[Mapping[str, object]] = {"role": "system", "content": system}
+ return (message,) if isinstance(system, (str, list)) and system else ()
+
+
+def _count_options(request: _AnthropicChatRequest) -> Mapping[str, JsonValue]:
+ """Structured output reaches chat inference as the beta ``output_format``, which count_tokens
+ refuses; its GA ``output_config.format`` form counts the same schema the same way."""
+ output_config: Final = request.get("output_config")
+ output_format: Final = request.get("output_format")
+ counted_config: Final = {
+ **(output_config if isinstance(output_config, dict) else {}),
+ **({} if output_format is None else {"format": output_format}),
+ }
+ return MappingProxyType(
+ {
+ key: value
+ for key, value in (
+ ("thinking", request.get("thinking")),
+ ("tool_choice", request.get("tool_choice")),
+ ("output_config", counted_config or None),
+ )
+ if value is not None
+ }
+ )
+
+
+def _translated_chat_request(
+ model: str,
+ messages: Sequence[Mapping[str, object]],
+ system: object,
+ tools: Sequence[Mapping[str, object]],
+ chat_params: Mapping[str, object],
+ translator: _ChatRequestTranslator,
+) -> _ChatParams:
+ from litellm.litellm_core_utils.prompt_templates.factory import chat_completion_tools_for
+
+ chat_tools: Final = [dict(chat_tool) for chat_tool in chain.from_iterable(map(chat_completion_tools_for, tools))]
+ openai_params: Final = {name: value for name, value in chat_params.items() if name != "drop_params"}
+ mapped_params: Final = {**openai_params, **({"tools": chat_tools} if chat_tools else {})}
+ chat_messages: Final = cast( # cast-ok: chat-shaped request messages, read the way chat inference reads them
+ _ChatMessages, copy.deepcopy([*_system_messages(system), *messages])
+ )
+ return translator.transform_request(
+ model=model,
+ messages=chat_messages,
+ optional_params=translator.map_openai_params(
+ mapped_params, {}, model, drop_params=chat_params.get("drop_params") is True
+ )
+ if mapped_params
+ else {},
+ litellm_params={},
+ headers={},
+ )
+
+
+def anthropic_fields_for_chat_tool_use(
+ model: str,
+ messages: Sequence[Mapping[str, object]],
+ system: object,
+ tools: Sequence[Mapping[str, object]] | None,
+ translator: _ChatRequestTranslator,
+ chat_params: Mapping[str, object] = MappingProxyType({}),
+) -> AnthropicCountFields | ChatCountTranslationError | None:
+ counted_tools: Final = tools or ()
+ if (
+ not chat_params
+ and not any(map(_is_chat_tool, counted_tools))
+ and not any(map(_needs_chat_translation, messages))
+ ):
+ return None
+ untranslatable: Final = _untranslatable_input(messages, counted_tools)
+ if untranslatable is not None:
+ return untranslatable
+ from litellm.exceptions import BadRequestError
+ from litellm.llms.anthropic.common_utils import AnthropicError
+
+ try:
+ request: Final = _translated_chat_request(model, messages, system, counted_tools, chat_params, translator)
+ except (AnthropicError, BadRequestError) as e:
+ return ChatCountTranslationError(message=str(e.message))
+ except (ValueError, KeyError) as e:
+ return ChatCountTranslationError(message=f"Invalid request for token counting: {e}")
+ translated: Final = _ANTHROPIC_CHAT_REQUEST.validate_python(request)
+ return AnthropicCountFields(
+ messages=translated["messages"],
+ system=translated.get("system"),
+ tools=translated.get("tools"),
+ options=_count_options(translated),
+ )
+
+
+async def anthropic_count_fields(
+ model: str,
+ messages: Sequence[Mapping[str, object]],
+ system: object,
+ tools: Sequence[Mapping[str, object]] | None,
+ messages_format: TokenCountMessagesFormat,
+ translator: _ChatRequestTranslator,
+ chat_params: Mapping[str, object] = MappingProxyType({}),
+) -> AnthropicCountFields | ChatCountTranslationError | None:
+ if messages_format != "openai":
+ return None
+ return await asyncify(anthropic_fields_for_chat_tool_use)(model, messages, system, tools, translator, chat_params)
+
+
class AnthropicCountTokensConfig:
"""
Configuration and transformation logic for Anthropic CountTokens API.
diff --git a/litellm/llms/azure_ai/anthropic/count_tokens/handler.py b/litellm/llms/azure_ai/anthropic/count_tokens/handler.py
index 53734a77f3c..0f8afaae681 100644
--- a/litellm/llms/azure_ai/anthropic/count_tokens/handler.py
+++ b/litellm/llms/azure_ai/anthropic/count_tokens/handler.py
@@ -4,6 +4,7 @@ Azure AI Anthropic CountTokens API handler.
Uses httpx for HTTP requests with Azure authentication.
"""
+from collections.abc import Mapping
from typing import Final
import httpx
@@ -36,6 +37,7 @@ class AzureAIAnthropicCountTokensHandler(AzureAIAnthropicCountTokensConfig):
timeout: float | httpx.Timeout | None = None,
tools: list[dict[str, JsonValue]] | None = None,
system: object = None,
+ optional_params: Mapping[str, JsonValue] | None = None,
) -> dict[str, object]:
"""
Handle a CountTokens request using httpx with Azure authentication.
@@ -66,6 +68,7 @@ class AzureAIAnthropicCountTokensHandler(AzureAIAnthropicCountTokensConfig):
messages=messages,
tools=tools,
system=system,
+ optional_params=optional_params,
)
verbose_logger.debug("Transformed request: %s", request_body)
diff --git a/litellm/llms/azure_ai/anthropic/count_tokens/token_counter.py b/litellm/llms/azure_ai/anthropic/count_tokens/token_counter.py
index d1f45751d3e..af7cf9d81ce 100644
--- a/litellm/llms/azure_ai/anthropic/count_tokens/token_counter.py
+++ b/litellm/llms/azure_ai/anthropic/count_tokens/token_counter.py
@@ -3,12 +3,19 @@ Azure AI Anthropic Token Counter implementation using the CountTokens API.
"""
import os
+from collections.abc import Mapping
+from types import MappingProxyType
from typing import Any, Final
from pydantic import JsonValue
import litellm
from litellm._logging import verbose_logger
+from litellm.llms.anthropic.count_tokens.transformation import (
+ AnthropicCountFields,
+ ChatCountTranslationError,
+ anthropic_count_fields,
+)
from litellm.llms.azure_ai.anthropic.count_tokens.handler import (
AzureAIAnthropicCountTokensHandler,
)
@@ -55,6 +62,8 @@ class AzureAIAnthropicTokenCounter(BaseTokenCounter):
messages_format: TokenCountMessagesFormat = "anthropic",
output_format: JsonValue = None,
context_management: CountContextManagement | None = None,
+ chat_params: Mapping[str, JsonValue] = MappingProxyType({}),
+ count_options: Mapping[str, JsonValue] = MappingProxyType({}),
) -> TokenCountResponse | None:
"""
Count tokens using Azure AI Anthropic's CountTokens API.
@@ -74,6 +83,30 @@ class AzureAIAnthropicTokenCounter(BaseTokenCounter):
if not messages:
return None
+ from litellm.llms.azure_ai.anthropic.transformation import AzureAnthropicConfig
+
+ match translated := await anthropic_count_fields(
+ model_to_use, messages, system, tools, messages_format, AzureAnthropicConfig(), chat_params
+ ):
+ case ChatCountTranslationError():
+ return translated.response(request_model, model_to_use, "azure_ai_anthropic_api")
+ case AnthropicCountFields():
+ return await self.count_tokens(
+ model_to_use=model_to_use,
+ messages=[dict(message) for message in translated.messages],
+ contents=contents,
+ deployment=deployment,
+ request_model=request_model,
+ tools=[dict(tool) for tool in translated.tools] if translated.tools is not None else None,
+ system=translated.system,
+ messages_format="anthropic",
+ output_format=output_format,
+ context_management=context_management,
+ count_options=translated.options,
+ )
+ case None:
+ pass
+
deployment = deployment or {}
litellm_params: Final = deployment.get("litellm_params", {})
@@ -101,6 +134,7 @@ class AzureAIAnthropicTokenCounter(BaseTokenCounter):
litellm_params=litellm_params,
tools=tools,
system=system,
+ optional_params=count_options,
)
if result is not None:
diff --git a/litellm/llms/base_llm/base_utils.py b/litellm/llms/base_llm/base_utils.py
index 640930a780d..a9ec1f97d20 100644
--- a/litellm/llms/base_llm/base_utils.py
+++ b/litellm/llms/base_llm/base_utils.py
@@ -9,6 +9,7 @@ import re
from abc import ABC, abstractmethod
from collections.abc import Iterator, Mapping, Sequence
from dataclasses import dataclass
+from types import MappingProxyType
from typing import Any, Final
from openai.lib import _parsing, _pydantic # pyright: ignore[reportPrivateUsage] # SDK parser internals
@@ -40,6 +41,7 @@ class BaseTokenCounter(ABC):
messages_format: TokenCountMessagesFormat = "openai",
output_format: JsonValue = None,
context_management: CountContextManagement | None = None,
+ chat_params: Mapping[str, JsonValue] = MappingProxyType({}),
) -> TokenCountResponse | None:
pass
diff --git a/litellm/llms/base_llm/files/batch_records.py b/litellm/llms/base_llm/files/batch_records.py
index 6bb98456e69..070cf73cd57 100644
--- a/litellm/llms/base_llm/files/batch_records.py
+++ b/litellm/llms/base_llm/files/batch_records.py
@@ -18,6 +18,7 @@ def _responses_request_keys() -> frozenset[str]:
def responses_batch_body_to_chat_body(
openai_request_body: Mapping[str, object],
custom_llm_provider: str | None = None,
+ drop_params: bool | None = None,
) -> dict[str, object]: # mutable-ok: provider transforms take the bridged chat body as a plain dict
"""
Rewrite the body of an OpenAI `/v1/responses` batch record as a Chat Completions body.
@@ -50,5 +51,6 @@ def responses_batch_body_to_chat_body(
input=chat_input,
responses_api_request=responses_request,
custom_llm_provider=custom_llm_provider,
+ drop_params=drop_params,
metadata=openai_request_body.get("metadata"),
)
diff --git a/litellm/llms/bedrock/count_tokens/bedrock_token_counter.py b/litellm/llms/bedrock/count_tokens/bedrock_token_counter.py
index 068cf4f2e67..21fbdb04896 100644
--- a/litellm/llms/bedrock/count_tokens/bedrock_token_counter.py
+++ b/litellm/llms/bedrock/count_tokens/bedrock_token_counter.py
@@ -4,12 +4,15 @@ Bedrock Token Counter implementation using the CountTokens API.
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
+from types import MappingProxyType
from typing import Any, Final
from pydantic import JsonValue
from typing_extensions import assert_never
from litellm._logging import verbose_logger
+from litellm.llms.anthropic.chat.transformation import AnthropicConfig
+from litellm.llms.anthropic.count_tokens.transformation import ChatCountTranslationError, anthropic_count_fields
from litellm.llms.base_llm.base_utils import BaseTokenCounter
from litellm.llms.bedrock.common_utils import BedrockError, get_bedrock_base_model
from litellm.llms.bedrock.count_tokens.handler import BedrockCountTokensHandler
@@ -58,6 +61,17 @@ def _runtime_rejected_claude_model(outcome: CountTokensOutcome, resolved_model:
)
+def _request_data(
+ model: str, messages: Sequence[Mapping[str, object]], tools: Sequence[Mapping[str, object]] | None, system: object
+) -> Mapping[str, object]:
+ return {
+ "model": model,
+ "messages": [dict(message) for message in messages],
+ **({"tools": [dict(tool) for tool in tools]} if tools else {}),
+ **({"system": system} if system else {}),
+ }
+
+
class BedrockTokenCounter(BaseTokenCounter):
"""Counts on the configured Bedrock endpoint, with Mantle retry when Runtime rejects a Claude model"""
@@ -81,13 +95,13 @@ class BedrockTokenCounter(BaseTokenCounter):
self,
handler: BedrockCountTokensHandler | BedrockMantleCountTokensHandler,
tokenizer_type: str,
- request_data: dict[str, object],
+ request_data: Mapping[str, object],
litellm_params: dict[str, object],
resolved_model: str,
) -> CountTokensOutcome:
try:
result: Final = await handler.handle_count_tokens_request(
- request_data=request_data,
+ request_data=dict(request_data),
litellm_params=litellm_params,
resolved_model=resolved_model,
client=self._client,
@@ -115,30 +129,44 @@ class BedrockTokenCounter(BaseTokenCounter):
messages_format: TokenCountMessagesFormat = "anthropic",
output_format: JsonValue = None,
context_management: CountContextManagement | None = None,
+ chat_params: Mapping[str, JsonValue] = MappingProxyType({}),
) -> TokenCountResponse | None:
if not messages:
return None
- litellm_params: Final = (deployment or {}).get("litellm_params", {})
- request_data: Final[dict[str, object]] = {
- "model": model_to_use,
- "messages": messages,
- **({"tools": tools} if tools else {}),
- **({"system": system} if system else {}),
- }
use_mantle: Final = model_to_use.startswith("bedrock_mantle/")
- resolved_model: Final = get_bedrock_base_model(model_to_use.removeprefix("bedrock_mantle/"))
-
- primary: Final = await self._count_with(
- self._mantle_handler if use_mantle else self._runtime_handler,
- MANTLE_TOKENIZER_TYPE if use_mantle else RUNTIME_TOKENIZER_TYPE,
- request_data,
- litellm_params,
- resolved_model,
+ counted_model: Final = model_to_use.removeprefix("bedrock_mantle/")
+ resolved_model: Final = get_bedrock_base_model(counted_model)
+ primary_tokenizer: Final = MANTLE_TOKENIZER_TYPE if use_mantle else RUNTIME_TOKENIZER_TYPE
+ translated: Final = (
+ await anthropic_count_fields(
+ counted_model, messages, system, tools, messages_format, AnthropicConfig(), chat_params
+ )
+ if is_mantle_claude_model(resolved_model)
+ else None
+ )
+ if isinstance(translated, ChatCountTranslationError):
+ return translated.response(request_model, model_to_use, primary_tokenizer)
+ litellm_params: Final = (deployment or {}).get("litellm_params", {})
+ runtime_request: Final = (
+ _request_data(model_to_use, messages, tools, system)
+ if translated is None
+ else _request_data(model_to_use, translated.messages, translated.tools, translated.system)
+ )
+ mantle_request: Final = runtime_request if translated is None else {**runtime_request, **translated.options}
+
+ primary: Final = (
+ await self._count_with(
+ self._mantle_handler, primary_tokenizer, mantle_request, litellm_params, resolved_model
+ )
+ if use_mantle
+ else await self._count_with(
+ self._runtime_handler, primary_tokenizer, runtime_request, litellm_params, resolved_model
+ )
)
outcome: Final = (
await self._count_with(
- self._mantle_handler, MANTLE_TOKENIZER_TYPE, request_data, litellm_params, resolved_model
+ self._mantle_handler, MANTLE_TOKENIZER_TYPE, mantle_request, litellm_params, resolved_model
)
if not use_mantle and _runtime_rejected_claude_model(primary, resolved_model)
else primary
diff --git a/litellm/llms/bedrock/count_tokens/mantle_handler.py b/litellm/llms/bedrock/count_tokens/mantle_handler.py
index 4ea4440a3c4..4b1a6a75a7a 100644
--- a/litellm/llms/bedrock/count_tokens/mantle_handler.py
+++ b/litellm/llms/bedrock/count_tokens/mantle_handler.py
@@ -1,3 +1,4 @@
+from collections.abc import Mapping
from typing import Final
import httpx
@@ -6,7 +7,7 @@ from typing_extensions import NotRequired, ReadOnly, TypedDict
import litellm
from litellm._logging import verbose_logger
-from litellm.llms.anthropic.count_tokens.transformation import AnthropicCountTokensConfig
+from litellm.llms.anthropic.count_tokens.transformation import COUNT_TOKEN_OPTION_NAMES, AnthropicCountTokensConfig
from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM, run_aws_signing
from litellm.llms.bedrock.common_utils import BedrockError, build_mantle_messages_url
from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, get_async_httpx_client
@@ -23,6 +24,7 @@ class MantleCountTokensRequest(TypedDict):
_COUNT_REQUEST: Final = TypeAdapter(MantleCountTokensRequest)
_COUNT_RESPONSE: Final = TypeAdapter(dict[str, JsonValue])
+_COUNT_OPTIONS: Final[TypeAdapter[Mapping[str, JsonValue]]] = TypeAdapter(Mapping[str, JsonValue])
class BedrockMantleCountTokensHandler(BaseAWSLLM):
@@ -61,6 +63,9 @@ class BedrockMantleCountTokensHandler(BaseAWSLLM):
messages=request["messages"],
tools=request.get("tools"),
system=request.get("system"),
+ optional_params=_COUNT_OPTIONS.validate_python(
+ {name: value for name, value in request_data.items() if name in COUNT_TOKEN_OPTION_NAMES}
+ ),
)
verbose_logger.debug("Making bedrock-mantle count_tokens request to: %s", endpoint_url)
api_key: Final = litellm_params.get("api_key")
diff --git a/litellm/llms/bedrock/count_tokens/transformation.py b/litellm/llms/bedrock/count_tokens/transformation.py
index 48fc41ed12b..7cca4f69acc 100644
--- a/litellm/llms/bedrock/count_tokens/transformation.py
+++ b/litellm/llms/bedrock/count_tokens/transformation.py
@@ -52,12 +52,15 @@ def _sanitized_bedrock_tool_name(raw_name: JsonValue) -> str:
def _to_bedrock_tool_spec(tool: JsonValue) -> dict[str, JsonValue]:
fields: Final = _json_dict(tool)
- name: Final = _sanitized_bedrock_tool_name(fields.get("name", ""))
+ chat_function: Final = _json_dict(fields.get("function"))
+ spec: Final = chat_function or fields
+ name: Final = _sanitized_bedrock_tool_name(spec.get("name", ""))
+ schema_field: Final = "parameters" if chat_function else "input_schema"
return {
"toolSpec": {
"name": name,
- "description": fields.get("description") or name,
- "inputSchema": {"json": fields.get("input_schema", {"type": "object", "properties": {}})},
+ "description": spec.get("description") or name,
+ "inputSchema": {"json": spec.get(schema_field, {"type": "object", "properties": {}})},
}
}
diff --git a/litellm/llms/gemini/common_utils.py b/litellm/llms/gemini/common_utils.py
index c5ebd84e00f..b1a726be876 100644
--- a/litellm/llms/gemini/common_utils.py
+++ b/litellm/llms/gemini/common_utils.py
@@ -3,6 +3,7 @@ import datetime
import json
import math
from collections.abc import Mapping, Sequence
+from types import MappingProxyType
from typing import Any, Final
import httpx
@@ -498,6 +499,7 @@ class GoogleAIStudioTokenCounter(BaseTokenCounter):
messages_format: TokenCountMessagesFormat = "openai",
output_format: JsonValue = None,
context_management: CountContextManagement | None = None,
+ chat_params: Mapping[str, JsonValue] = MappingProxyType({}),
) -> TokenCountResponse | None:
import copy
diff --git a/litellm/llms/openai/responses/count_tokens/handler.py b/litellm/llms/openai/responses/count_tokens/handler.py
index 6f911e9c40f..739966c95d1 100644
--- a/litellm/llms/openai/responses/count_tokens/handler.py
+++ b/litellm/llms/openai/responses/count_tokens/handler.py
@@ -34,7 +34,7 @@ class OpenAICountTokensHandler(OpenAICountTokensConfig):
tools: Sequence[Mapping[str, object]] | None = None,
instructions: str | None = None,
text: Mapping[str, object] | None = None,
- ) -> dict[str, object]:
+ ) -> Mapping[str, object]:
"""
Handle a token counting request to OpenAI's Responses API.
@@ -56,7 +56,19 @@ class OpenAICountTokensHandler(OpenAICountTokensConfig):
instructions=instructions,
text=text,
)
+ except ValueError as e:
+ verbose_logger.error("Error in CountTokens handler: %s", e)
+ raise OpenAIError(status_code=500, message=f"CountTokens processing error: {e}")
+ return await self.post_count_request(request_body, api_key, api_base, timeout)
+ async def post_count_request(
+ self,
+ request_body: Mapping[str, object],
+ api_key: str,
+ api_base: str | None = None,
+ timeout: float | httpx.Timeout | None = None,
+ ) -> Mapping[str, object]:
+ try:
endpoint_url: Final = self.get_openai_count_tokens_endpoint(api_base)
verbose_logger.debug("Making request to: %s", endpoint_url)
@@ -70,7 +82,7 @@ class OpenAICountTokensHandler(OpenAICountTokensConfig):
response: Final = await async_client.post(
endpoint_url,
headers=headers,
- json=request_body,
+ json=dict(request_body),
timeout=request_timeout,
)
diff --git a/litellm/llms/openai/responses/count_tokens/token_counter.py b/litellm/llms/openai/responses/count_tokens/token_counter.py
index b12fdb95765..437f19a4dc6 100644
--- a/litellm/llms/openai/responses/count_tokens/token_counter.py
+++ b/litellm/llms/openai/responses/count_tokens/token_counter.py
@@ -2,7 +2,9 @@
OpenAI Token Counter implementation using the Responses API /input_tokens endpoint.
"""
-from collections.abc import Mapping, Sequence
+from collections.abc import Awaitable, Callable, Mapping, Sequence
+from dataclasses import dataclass
+from types import MappingProxyType
from typing import Any, Final
import openai
@@ -11,6 +13,8 @@ from typing_extensions import assert_never
from litellm._logging import verbose_logger
from litellm.litellm_core_utils.asyncify import asyncify
+from litellm.litellm_core_utils.core_helpers import as_str_mapping
+from litellm.litellm_core_utils.tool_fields import DropPolicy
from litellm.llms.anthropic.pass_through.convertible_blocks import deployment_drops_params, unconvertible_blocks_error
from litellm.llms.anthropic.pass_through.responses_adapters.transformation import (
LiteLLMAnthropicToResponsesAPIAdapter,
@@ -23,6 +27,7 @@ from litellm.llms.openai.responses.count_tokens.handler import (
from litellm.llms.openai.responses.count_tokens.transformation import (
OpenAICountTokensConfig,
ResponsesCountRequestParts,
+ native_count_request,
)
from litellm.llms.openai.workload_identity import (
OpenAIWorkloadIdentityConfig,
@@ -50,6 +55,46 @@ def _workload_identity_config(
return e
+@dataclass(frozen=True, slots=True)
+class _CountCredential:
+ api_base: str | None
+ credential: str | OpenAIWorkloadIdentityConfig
+
+
+def _count_credential(deployment: Mapping[str, object] | None, model_label: str) -> _CountCredential | OpenAIError:
+ litellm_params: Final = as_str_mapping(None if deployment is None else deployment.get("litellm_params")) or {}
+ api_base: Final = litellm_params.get("api_base")
+ api_key: Final = litellm_params.get("api_key")
+ credentials: Final = get_openai_credentials(
+ api_base=api_base if isinstance(api_base, str) else None,
+ api_key=api_key if isinstance(api_key, str) else None,
+ )
+ credential: Final = openai_static_api_key(credentials.api_key) or _workload_identity_config(litellm_params)
+ if isinstance(credential, OpenAIError):
+ return credential
+ if credential is None:
+ return OpenAIError(
+ status_code=401,
+ message=(
+ f"No OpenAI API key is set for model {model_label}, so tokens can't be counted. Set api_key or "
+ "workload identity on the deployment, or OPENAI_API_KEY in the proxy environment."
+ ),
+ )
+ return _CountCredential(api_base=credentials.api_base, credential=credential)
+
+
+def _count_error(model_to_use: str, request_model: str, message: str, status_code: int) -> TokenCountResponse:
+ return TokenCountResponse(
+ total_tokens=0,
+ request_model=request_model,
+ model_used=model_to_use,
+ tokenizer_type="openai_api",
+ error=True,
+ error_message=message,
+ status_code=status_code,
+ )
+
+
class OpenAITokenCounter(BaseTokenCounter):
"""Token counter implementation for OpenAI provider using the Responses API."""
@@ -102,6 +147,7 @@ class OpenAITokenCounter(BaseTokenCounter):
messages_format: TokenCountMessagesFormat = "openai",
output_format: JsonValue = None,
context_management: CountContextManagement | None = None,
+ chat_params: Mapping[str, JsonValue] = MappingProxyType({}),
) -> TokenCountResponse | None:
"""
Count tokens using OpenAI's Responses API /input_tokens endpoint.
@@ -129,41 +175,9 @@ class OpenAITokenCounter(BaseTokenCounter):
rejected_before_provider_call=True,
)
- deployment = deployment or {}
- litellm_params: Final = deployment.get("litellm_params", {})
-
- credentials: Final = get_openai_credentials(
- api_base=litellm_params.get("api_base"), api_key=litellm_params.get("api_key")
- )
- credential: Final = openai_static_api_key(credentials.api_key) or _workload_identity_config(litellm_params)
-
- if isinstance(credential, OpenAIError):
- return TokenCountResponse(
- total_tokens=0,
- request_model=request_model,
- model_used=model_to_use,
- tokenizer_type="openai_api",
- error=True,
- error_message=credential.message,
- status_code=credential.status_code,
- )
-
- if credential is None:
- return TokenCountResponse(
- total_tokens=0,
- request_model=request_model,
- model_used=model_to_use,
- tokenizer_type="openai_api",
- error=True,
- error_message=(
- f"No OpenAI API key is set for model {request_model or model_to_use}, so tokens can't be "
- "counted. Set api_key or workload identity on the deployment, or OPENAI_API_KEY in the proxy "
- "environment."
- ),
- status_code=401,
- )
-
- api_base: Final = credentials.api_base
+ resolved: Final = _count_credential(deployment, request_model or model_to_use)
+ if isinstance(resolved, OpenAIError):
+ return _count_error(model_to_use, request_model, resolved.message, resolved.status_code)
input_items, instructions, counted_tools, text = self._responses_request_parts(
model_to_use=model_to_use,
@@ -178,13 +192,9 @@ class OpenAITokenCounter(BaseTokenCounter):
if not input_items:
return None
- try:
- api_key: Final = (
- credential
- if isinstance(credential, str)
- else await asyncify(get_workload_identity_bearer_token)(credential)
- )
- result: Final = await openai_count_tokens_handler.handle_count_tokens_request(
+ return await self._counted(
+ resolved,
+ lambda api_key, api_base: openai_count_tokens_handler.handle_count_tokens_request(
model=model_to_use,
input=input_items,
api_key=api_key,
@@ -192,7 +202,44 @@ class OpenAITokenCounter(BaseTokenCounter):
tools=counted_tools,
instructions=instructions,
text=text,
+ ),
+ model_to_use,
+ request_model,
+ )
+
+ async def count_responses_request(
+ self,
+ model_to_use: str,
+ request: Mapping[str, object],
+ policy: DropPolicy,
+ deployment: Mapping[str, object] | None,
+ request_model: str,
+ ) -> TokenCountResponse | None:
+ resolved: Final = _count_credential(deployment, request_model or model_to_use)
+ if isinstance(resolved, OpenAIError):
+ return _count_error(model_to_use, request_model, resolved.message, resolved.status_code)
+ body: Final = native_count_request(request, model_to_use, policy)
+ return await self._counted(
+ resolved,
+ lambda api_key, api_base: openai_count_tokens_handler.post_count_request(body, api_key, api_base),
+ model_to_use,
+ request_model,
+ )
+
+ @staticmethod
+ async def _counted(
+ resolved: _CountCredential,
+ send: Callable[[str, str | None], Awaitable[Mapping[str, object]]],
+ model_to_use: str,
+ request_model: str,
+ ) -> TokenCountResponse | None:
+ try:
+ api_key: Final = (
+ resolved.credential
+ if isinstance(resolved.credential, str)
+ else await asyncify(get_workload_identity_bearer_token)(resolved.credential)
)
+ result: Final = await send(api_key, resolved.api_base)
if result is not None:
return TokenCountResponse.model_validate(
@@ -206,36 +253,12 @@ class OpenAITokenCounter(BaseTokenCounter):
)
except OpenAIError as e:
verbose_logger.warning("OpenAI CountTokens API error: status=%s, message=%s", e.status_code, e.message)
- return TokenCountResponse(
- total_tokens=0,
- request_model=request_model,
- model_used=model_to_use,
- tokenizer_type="openai_api",
- error=True,
- error_message=e.message,
- status_code=e.status_code,
- )
+ return _count_error(model_to_use, request_model, e.message, e.status_code)
except openai.AuthenticationError as e:
verbose_logger.warning("OpenAI workload identity token exchange failed: %s", e.message)
- return TokenCountResponse(
- total_tokens=0,
- request_model=request_model,
- model_used=model_to_use,
- tokenizer_type="openai_api",
- error=True,
- error_message=e.message,
- status_code=401,
- )
+ return _count_error(model_to_use, request_model, e.message, 401)
except Exception as e:
verbose_logger.warning("Error calling OpenAI CountTokens API: %s", e)
- return TokenCountResponse(
- total_tokens=0,
- request_model=request_model,
- model_used=model_to_use,
- tokenizer_type="openai_api",
- error=True,
- error_message=str(e),
- status_code=500,
- )
+ return _count_error(model_to_use, request_model, str(e), 500)
return None
diff --git a/litellm/llms/openai/responses/count_tokens/transformation.py b/litellm/llms/openai/responses/count_tokens/transformation.py
index 438aa05a4e9..6d882e0eeb1 100644
--- a/litellm/llms/openai/responses/count_tokens/transformation.py
+++ b/litellm/llms/openai/responses/count_tokens/transformation.py
@@ -4,12 +4,15 @@ OpenAI Responses API token counting transformation logic.
This module handles the transformation of requests to OpenAI's /v1/responses/input_tokens endpoint.
"""
+import copy
from collections.abc import Mapping, Sequence
from typing import Any, Final, Literal, TypeAlias
+from openai.types.responses.input_token_count_params import InputTokenCountParams
from pydantic import JsonValue, TypeAdapter, ValidationError
from typing_extensions import ReadOnly, TypedDict
+from litellm.litellm_core_utils.tool_fields import DropPolicy
from litellm.llms.anthropic.pass_through.convertible_blocks import malformed_tool_result_text_error
from litellm.llms.anthropic.pass_through.messages.utils import normalize_native_messages
from litellm.llms.anthropic.pass_through.responses_adapters.transformation import (
@@ -17,6 +20,8 @@ from litellm.llms.anthropic.pass_through.responses_adapters.transformation impor
)
from litellm.responses.utils import ResponsesAPIRequestUtils
from litellm.types.llms.anthropic import AnthropicMessagesRequest, AnthropicOutputSchema
+from litellm.types.llms.openai import ResponsesAPIRequestParams
+from litellm.types.utils import all_litellm_params
class ResponsesInputTextPart(TypedDict):
@@ -340,3 +345,34 @@ class OpenAICountTokensConfig:
input_items: object, instructions: object, tools: object, text: object = None
) -> ResponsesCountRequestParts:
return _RESPONSES_COUNT_REQUEST_PARTS.validate_python((input_items, instructions, tools, text))
+
+
+_COUNT_FIELDS_THE_SDK_TYPE_OMITS: Final = frozenset({"prompt"})
+_COUNT_REQUEST_FIELDS: Final = (
+ InputTokenCountParams.__required_keys__ | InputTokenCountParams.__optional_keys__ | _COUNT_FIELDS_THE_SDK_TYPE_OMITS
+)
+_INFERENCE_REQUEST_FIELDS: Final = (
+ ResponsesAPIRequestParams.__required_keys__ | ResponsesAPIRequestParams.__optional_keys__
+)
+_LITELLM_REQUEST_FIELDS: Final = frozenset((*all_litellm_params, "drop_params", "additional_drop_params"))
+
+
+def _forwards(field: str, policy: DropPolicy) -> bool:
+ if field in _LITELLM_REQUEST_FIELDS or field in policy.additional_drop_params:
+ return False
+ return field in _COUNT_REQUEST_FIELDS or (not policy.drop_params and field in _INFERENCE_REQUEST_FIELDS)
+
+
+def _restored(field: str, value: object) -> object:
+ match field, value:
+ case "input", _:
+ return ResponsesAPIRequestUtils.restore_encrypted_content_item_ids_in_input(copy.deepcopy(value))
+ case "previous_response_id", str():
+ return ResponsesAPIRequestUtils.decode_previous_response_id_to_original_previous_response_id(value)
+ case _:
+ return value
+
+
+def native_count_request(request: Mapping[str, object], model: str, policy: DropPolicy) -> Mapping[str, object]:
+ forwarded: Final = {field: _restored(field, value) for field, value in request.items() if _forwards(field, policy)}
+ return {**forwarded, "model": model}
diff --git a/litellm/llms/vertex_ai/common_utils.py b/litellm/llms/vertex_ai/common_utils.py
index 8298edd6744..f85a5a8cda9 100644
--- a/litellm/llms/vertex_ai/common_utils.py
+++ b/litellm/llms/vertex_ai/common_utils.py
@@ -1,5 +1,5 @@
import re
-from collections.abc import Mapping
+from collections.abc import Mapping, Sequence
from copy import deepcopy
from datetime import datetime, timezone
from enum import Enum
@@ -1263,6 +1263,52 @@ class VertexAITokenCounter(BaseTokenCounter):
return custom_llm_provider == LlmProviders.VERTEX_AI.value
+ async def _count_translated_claude_request(
+ self,
+ model_to_use: str,
+ messages: Sequence[Mapping[str, object]] | None,
+ deployment: Mapping[str, object],
+ request_model: str,
+ tools: Sequence[Mapping[str, object]] | None,
+ system: object | None,
+ messages_format: TokenCountMessagesFormat,
+ output_format: JsonValue,
+ context_management: CountContextManagement | None,
+ chat_params: Mapping[str, JsonValue],
+ ) -> TokenCountResponse | None:
+ from litellm.llms.anthropic.count_tokens.transformation import (
+ AnthropicCountFields,
+ ChatCountTranslationError,
+ anthropic_count_fields,
+ )
+ from litellm.llms.vertex_ai.vertex_ai_partner_models.count_tokens.handler import count_tokens_publisher
+
+ if count_tokens_publisher(model_to_use) != "anthropic":
+ return None
+ from litellm.llms.vertex_ai.vertex_ai_partner_models.anthropic.transformation import VertexAIAnthropicConfig
+
+ match translated := await anthropic_count_fields(
+ model_to_use, messages or [], system, tools, messages_format, VertexAIAnthropicConfig(), chat_params
+ ):
+ case ChatCountTranslationError():
+ return translated.response(request_model, model_to_use, "vertex_ai_partner_models")
+ case AnthropicCountFields():
+ return await self.count_tokens(
+ model_to_use=model_to_use,
+ messages=[dict(message) for message in translated.messages],
+ contents=None,
+ deployment=dict(deployment),
+ request_model=request_model,
+ tools=[dict(tool) for tool in translated.tools] if translated.tools is not None else None,
+ system=translated.system,
+ messages_format="anthropic",
+ output_format=output_format,
+ context_management=context_management,
+ count_options=translated.options,
+ )
+ case None:
+ return None
+
async def count_tokens(
self,
model_to_use: str,
@@ -1275,6 +1321,8 @@ class VertexAITokenCounter(BaseTokenCounter):
messages_format: TokenCountMessagesFormat = "openai",
output_format: JsonValue = None,
context_management: CountContextManagement | None = None,
+ chat_params: Mapping[str, JsonValue] = MappingProxyType({}),
+ count_options: Mapping[str, JsonValue] = MappingProxyType({}),
) -> TokenCountResponse | None:
import copy
@@ -1313,6 +1361,21 @@ class VertexAITokenCounter(BaseTokenCounter):
# Check if this is a partner model (Claude, Mistral, etc.)
if VertexAIPartnerModels.is_vertex_partner_model(model_to_use):
+ translated_count: Final = await self._count_translated_claude_request(
+ model_to_use=model_to_use,
+ messages=messages,
+ deployment=deployment,
+ request_model=request_model,
+ tools=tools,
+ system=system,
+ messages_format=messages_format,
+ output_format=output_format,
+ context_management=context_management,
+ chat_params=chat_params,
+ )
+ if translated_count is not None:
+ return translated_count
+
# Use partner models token counter
partner_models_handler: Final = VertexAIPartnerModels()
@@ -1343,6 +1406,7 @@ class VertexAITokenCounter(BaseTokenCounter):
vertex_credentials=vertex_credentials,
system=system,
tools=tools,
+ count_options=count_options,
)
except (PartnerVertexAIError, httpx.HTTPStatusError) as e:
status_code: Final = e.response.status_code
diff --git a/litellm/llms/vertex_ai/vertex_ai_partner_models/main.py b/litellm/llms/vertex_ai/vertex_ai_partner_models/main.py
index c855a073648..bb200fd542d 100644
--- a/litellm/llms/vertex_ai/vertex_ai_partner_models/main.py
+++ b/litellm/llms/vertex_ai/vertex_ai_partner_models/main.py
@@ -1,6 +1,6 @@
# What is this?
## API Handler for calling Vertex AI Partner Models
-from collections.abc import Callable
+from collections.abc import Callable, Mapping
from enum import Enum
from types import MappingProxyType
from typing import Final
@@ -266,6 +266,7 @@ class VertexAIPartnerModels(VertexBase):
vertex_credentials=None,
system: object | None = None,
tools: list[dict[str, object]] | None = None,
+ count_options: Mapping[str, object] = MappingProxyType({}),
):
"""
Count tokens for Vertex AI partner models (Anthropic Claude, Mistral, etc.)
@@ -302,6 +303,7 @@ class VertexAIPartnerModels(VertexBase):
**MappingProxyType(
{key: value for key, value in (("system", system), ("tools", tools)) if value is not None}
),
+ **count_options,
}
# Prepare litellm_params with credentials
diff --git a/litellm/main.py b/litellm/main.py
index 71cb7af1fbb..f9bdf64c667 100644
--- a/litellm/main.py
+++ b/litellm/main.py
@@ -9247,6 +9247,7 @@ async def acount_tokens(
request_model=model,
tools=tools,
system=system,
+ messages_format="openai",
)
if result is not None and not result.error:
return result
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index c5128ddab87..f87b1edc2e5 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -14701,7 +14701,9 @@ async def run_thread(
# dependencies=[Depends(user_api_key_auth)],
# )
# async def get_available_routes(user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth)):
+from litellm.litellm_core_utils.tool_fields import DropPolicy, drop_policy
from litellm.llms.base_llm.base_utils import BaseTokenCounter
+from litellm.llms.openai.responses.count_tokens.token_counter import OpenAITokenCounter
from litellm.proxy.db.routing_prisma_wrapper import WriterPinnedClient
from litellm.repositories.config_repository import ConfigRepository
from litellm.repositories.model_repository import ModelRepository
@@ -14714,6 +14716,11 @@ from litellm.repositories.table_repositories import (
)
from litellm.repositories.team_repository import TeamRepository
from litellm.repositories.user_repository import UserRepository
+from litellm.responses.litellm_completion_transformation.count_request import (
+ ChatCountBridgeError,
+ chat_count_request,
+ with_provider_file_ids,
+)
def _get_provider_token_counter(
@@ -14771,6 +14778,18 @@ def _get_provider_token_counter(
return None, None, None
+def _provider_count_outcome(
+ result: Union["TokenCountResponse", None],
+) -> Union["TokenCountResponse", ProviderCountFailure, None]:
+ if result is not None and result.error is True:
+ return ProviderCountFailure(
+ status_code=result.status_code or 500,
+ message=result.error_message or "Token counting failed",
+ rejected_before_provider_call=result.rejected_before_provider_call,
+ )
+ return result
+
+
def _with_resolved_api_key(litellm_params: object) -> Mapping[str, object]:
call_params: Final = _LITELLM_PARAMS_COPY.validate_python(litellm_params)
try:
@@ -14785,6 +14804,12 @@ def _with_resolved_api_key(litellm_params: object) -> Mapping[str, object]:
return call_params
+def _with_resolved_credentials(deployment: Mapping[str, object] | None) -> dict[str, object] | None:
+ if deployment is None:
+ return None
+ return {**deployment, "litellm_params": _with_resolved_api_key(deployment.get("litellm_params", {}))}
+
+
_DEPLOYMENT_LITELLM_PARAMS: Final = TypeAdapter(Mapping[str, object])
@@ -14825,6 +14850,7 @@ async def _try_provider_token_count(
messages_format: TokenCountMessagesFormat = "openai",
output_format: JsonValue = None,
context_management: CountContextManagement | None = None,
+ chat_params: Mapping[str, JsonValue] = MappingProxyType({}),
) -> Union["TokenCountResponse", ProviderCountFailure, None]:
"""Attempt provider-specific token counting. Returns None to fall through to local counting."""
if not provider_counter.should_use_token_counting_api(custom_llm_provider=custom_llm_provider):
@@ -14844,31 +14870,44 @@ async def _try_provider_token_count(
model_to_use=model_to_use or "",
messages=messages,
contents=contents,
- deployment=None
- if deployment_in_region is None
- else {
- **deployment_in_region,
- "litellm_params": _with_resolved_api_key(deployment_in_region.get("litellm_params", {})),
- },
+ deployment=_with_resolved_credentials(deployment_in_region),
request_model=request_model,
tools=tools,
system=system,
messages_format=messages_format,
output_format=output_format,
context_management=context_management,
+ chat_params=chat_params,
)
except httpx.HTTPStatusError as e:
return ProviderCountFailure(
status_code=getattr(e, "status_code", None) or e.response.status_code,
message=getattr(e, "message", None) or str(e),
)
- if result is not None and result.error is True:
- return ProviderCountFailure(
- status_code=result.status_code or 500,
- message=result.error_message or "Token counting failed",
- rejected_before_provider_call=result.rejected_before_provider_call,
+ return _provider_count_outcome(result)
+
+
+async def _try_native_responses_count(
+ provider_counter: OpenAITokenCounter,
+ custom_llm_provider: str | None,
+ model_to_use: str,
+ _region: str | None,
+ responses_request: Mapping[str, object],
+ policy: DropPolicy,
+ deployment: Mapping[str, object] | None,
+ request_model: str,
+) -> Union["TokenCountResponse", ProviderCountFailure, None]:
+ if not provider_counter.should_use_token_counting_api(custom_llm_provider=custom_llm_provider):
+ return None
+ return _provider_count_outcome(
+ await provider_counter.count_responses_request(
+ model_to_use=model_to_use,
+ request=responses_request,
+ policy=policy,
+ deployment=_with_resolved_credentials(deployment),
+ request_model=request_model,
)
- return result
+ )
async def _provider_token_count(
@@ -15150,6 +15189,7 @@ class _TokenCountDeployment(TypedDict, total=False):
_TOKEN_COUNT_DEPLOYMENT: Final = TypeAdapter(_TokenCountDeployment)
+_ROUTED_DEPLOYMENT: Final[TypeAdapter[Mapping[str, object] | None]] = TypeAdapter(Mapping[str, object] | None)
def _model_group_deployment(router: Router | None, model_group: str) -> Mapping[str, object] | None:
@@ -15228,6 +15268,43 @@ def _count_context_management(
)
+def _responses_routing_kwargs(responses_request: Mapping[str, object] | None) -> Mapping[str, object]:
+ previous_response_id: Final = None if responses_request is None else responses_request.get("previous_response_id")
+ return {"previous_response_id": previous_response_id} if isinstance(previous_response_id, str) else {}
+
+
+def _count_drop_policy(deployment: Mapping[str, object] | None, responses_request: Mapping[str, object]) -> DropPolicy:
+ litellm_params: Final = as_str_mapping(None if deployment is None else deployment.get("litellm_params")) or {}
+ router_defaults: Final[Mapping[str, object]] = (
+ {} if llm_router is None else _router_default_litellm_params(llm_router)
+ )
+ return drop_policy({**litellm_params, **router_defaults, **responses_request})
+
+
+def _native_responses_count(
+ provider_counter: BaseTokenCounter,
+ custom_llm_provider: str | None,
+ responses_request: Mapping[str, object] | None,
+ deployment: Mapping[str, object] | None,
+ request_model: str,
+) -> Callable[[str, str | None], Awaitable[Union["TokenCountResponse", ProviderCountFailure, None]]] | None:
+ if responses_request is None or not isinstance(provider_counter, OpenAITokenCounter):
+ return None
+ return partial(
+ _try_native_responses_count,
+ provider_counter,
+ custom_llm_provider,
+ responses_request=responses_request,
+ policy=_count_drop_policy(deployment, responses_request),
+ deployment=deployment,
+ request_model=request_model,
+ )
+
+
+def _deployment_api_base(deployment: _TokenCountDeployment) -> str | None:
+ return _non_empty_str(deployment.get("litellm_params", {}).get("api_base"))
+
+
def _system_message(system: object) -> ChatCompletionSystemMessage | None:
if not isinstance(system, (str, list)) or not system:
return None
@@ -15260,6 +15337,7 @@ async def count_request_tokens(
output_format: JsonValue = None,
context_management: JsonValue = None,
request_litellm_params: Mapping[str, JsonValue] = MappingProxyType({}),
+ responses_request: Mapping[str, object] | None = None,
) -> TokenCountResponse:
prompt: Final = request.prompt
messages: Final = request.messages
@@ -15281,7 +15359,7 @@ async def count_request_tokens(
try:
deployment = await llm_router.async_get_available_deployment(
model=request.model,
- request_kwargs={},
+ request_kwargs=dict(_responses_routing_kwargs(responses_request)),
)
except Exception:
verbose_proxy_logger.exception(
@@ -15335,23 +15413,54 @@ async def count_request_tokens(
request_messages: Final = _counted_request_messages(messages, messages_format, count_deployment)
contents_estimable: Final = not contents or (bool(messages) and _estimable_contents(contents))
prompt_as_message: Final = prompt_only and custom_llm_provider in _PROVIDERS_COUNTING_WITHOUT_MESSAGES
+ routed_deployment: Final = _ROUTED_DEPLOYMENT.validate_python(deployment)
+ routed_request: Final = (
+ None if responses_request is None else with_provider_file_ids(responses_request, routed_deployment)
+ )
+ chat_count: Final = (
+ None
+ if routed_request is None or provider_counter is None or isinstance(provider_counter, OpenAITokenCounter)
+ else await chat_count_request(
+ model_to_use,
+ custom_llm_provider,
+ _deployment_api_base(deployment_view),
+ routed_request,
+ _count_drop_policy(routed_deployment, routed_request),
+ )
+ )
+ if isinstance(chat_count, ChatCountBridgeError):
+ raise ProxyException(message=chat_count.message, type="invalid_request_error", param=None, code=400)
ladder: Final = (
None
if provider_counter is None
else await _provider_token_count(
- count_with=partial(
+ count_with=_native_responses_count(
+ provider_counter,
+ custom_llm_provider,
+ routed_request,
+ routed_deployment,
+ request.model,
+ )
+ or partial(
_try_provider_token_count,
provider_counter,
custom_llm_provider,
- messages=[{"role": "user", "content": prompt}] if prompt_as_message else request_messages,
+ messages=(
+ [dict(message) for message in chat_count.messages]
+ if chat_count is not None
+ else [{"role": "user", "content": prompt}]
+ if prompt_as_message
+ else request_messages
+ ),
contents=None if prompt_as_message else contents,
deployment=count_deployment,
request_model=request.model,
- tools=tools,
+ tools=tools if chat_count is None else [dict(tool) for tool in chat_count.tools or ()] or None,
system=system,
messages_format=messages_format,
output_format=output_format,
context_management=_count_context_management(context_management, request.model, request_litellm_params),
+ chat_params=MappingProxyType({}) if chat_count is None else chat_count.params,
),
model_to_use=model_to_use,
settings=settings,
diff --git a/litellm/proxy/response_api_endpoints/endpoints.py b/litellm/proxy/response_api_endpoints/endpoints.py
index a0fb2b190e0..c918ea3f1d1 100644
--- a/litellm/proxy/response_api_endpoints/endpoints.py
+++ b/litellm/proxy/response_api_endpoints/endpoints.py
@@ -32,12 +32,13 @@ from typing_extensions import NotRequired, ReadOnly, TypedDict
import litellm
from litellm._logging import verbose_proxy_logger
from litellm.anthropic_interface.exceptions.exception_mapping_utils import AnthropicExceptionMapping
+from litellm.caching.dual_cache import DualCache
from litellm.constants import EMPTY_MAPPING, MANAGED_BACKGROUND_RESPONSE_METADATA_KEY, TERMINAL_RESPONSE_STATUSES
from litellm.integrations.custom_guardrail import ModifyResponseException
from litellm.litellm_core_utils.core_helpers import as_str_mapping, get_metadata_variable_name_from_kwargs
from litellm.litellm_core_utils.internal_call_metadata import is_background_response, requests_background
from litellm.litellm_core_utils.litellm_logging import StandardLoggingPayloadSetup
-from litellm.litellm_core_utils.tool_fields import first_validation_error
+from litellm.litellm_core_utils.tool_fields import TOOL_FIELDS, first_validation_error
from litellm.llms.openai.responses.guardrail_translation.handler import (
OpenAIResponsesHandler,
build_blocked_response,
@@ -79,6 +80,7 @@ from litellm.proxy.pass_through_endpoints.llm_provider_handlers.batch_attributio
)
from litellm.proxy.route_llm_request import raise_if_required_body_param_missing
from litellm.proxy.utils import handle_exception_on_proxy
+from litellm.responses.litellm_completion_transformation.count_request import MODEL_FILE_ID_MAPPING_FIELD
from litellm.responses.streaming_iterator import GuardedResponsesWsFrame, ResponsesWsFrameGuard, spawn_logging_task
from litellm.router import Router
from litellm.types.llms.base import LiteLLMBaseModel
@@ -89,7 +91,7 @@ from litellm.types.llms.openai import (
)
from litellm.types.responses.main import DeleteResponseResult
from litellm.types.token_count import TokenCountSourceFields
-from litellm.types.utils import TokenCountResponse
+from litellm.types.utils import ADDRESSED_RESPONSE_ID_FIELD, TokenCountResponse
if TYPE_CHECKING:
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
@@ -1388,13 +1390,15 @@ class _TokenCountPayload(TypedDict):
class _TokenCounter(Protocol):
- def __call__(self, request: TokenCountRequest, call_endpoint: bool) -> Awaitable[TokenCountResponse]: ...
+ def __call__(
+ self, *, request: TokenCountRequest, call_endpoint: bool, responses_request: Mapping[str, object] | None
+ ) -> Awaitable[TokenCountResponse]: ...
def _proxy_token_counter() -> _TokenCounter:
- from litellm.proxy.proxy_server import token_counter
+ from litellm.proxy.proxy_server import count_request_tokens
- return token_counter
+ return count_request_tokens
_token_counter_dep: Final = Depends(_proxy_token_counter)
@@ -1409,6 +1413,67 @@ def _proxy_llm_router() -> Router | None:
_llm_router_dep: Final = Depends(_proxy_llm_router)
+def _proxy_response_id_security() -> ResponsesIDSecurity | None:
+ from litellm.proxy.proxy_server import proxy_logging_obj
+
+ security_hook: Final = proxy_logging_obj.get_proxy_hook("responses_id_security")
+ return security_hook if isinstance(security_hook, ResponsesIDSecurity) else None
+
+
+_response_id_security_dep: Final = Depends(_proxy_response_id_security)
+
+
+class _ManagedFileAccess(Protocol):
+ async def async_pre_call_hook(
+ self,
+ user_api_key_dict: UserAPIKeyAuth,
+ cache: DualCache,
+ data: dict[str, object],
+ call_type: Literal["aresponses"],
+ ) -> object: ...
+
+
+def _proxy_managed_files_hook() -> _ManagedFileAccess | None:
+ from litellm.proxy.proxy_server import proxy_logging_obj
+
+ return proxy_logging_obj.get_proxy_hook("managed_files")
+
+
+_managed_files_hook_dep: Final = Depends(_proxy_managed_files_hook)
+
+
+async def _with_managed_file_id_mapping(
+ data: Mapping[str, object], managed_files: _ManagedFileAccess | None, user_api_key_dict: UserAPIKeyAuth
+) -> Mapping[str, object]:
+ caller_fields: Final = {name: value for name, value in data.items() if name != MODEL_FILE_ID_MAPPING_FIELD}
+ if managed_files is None:
+ return caller_fields
+ from litellm.proxy.proxy_server import user_api_key_cache
+
+ hooked: Final = dict(caller_fields)
+ try:
+ await managed_files.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict, cache=user_api_key_cache, data=hooked, call_type="aresponses"
+ )
+ except HTTPException as e:
+ raise ProxyException(message=str(e.detail), type="permission_error", param=None, code=e.status_code) from e
+ mapping: Final = hooked.get(MODEL_FILE_ID_MAPPING_FIELD)
+ return caller_fields if mapping is None else {**caller_fields, MODEL_FILE_ID_MAPPING_FIELD: mapping}
+
+
+def _with_authorized_previous_response(
+ data: Mapping[str, object], security: ResponsesIDSecurity | None, user_api_key_dict: UserAPIKeyAuth
+) -> Mapping[str, object]:
+ previous_response_id: Final = data.get("previous_response_id")
+ if security is None or not isinstance(previous_response_id, str) or not previous_response_id:
+ return data
+ try:
+ authorized_id: Final = security.authorize_response_id(previous_response_id, user_api_key_dict)
+ except HTTPException as e:
+ raise ProxyException(message=str(e.detail), type="permission_error", param=None, code=e.status_code) from e
+ return {**data, "previous_response_id": authorized_id, ADDRESSED_RESPONSE_ID_FIELD: previous_response_id}
+
+
def _responses_invalid_request_response(message: str, param: str | None, code: str | None) -> JSONResponse:
body: Final[_ResponsesApiErrorBody] = {
"error": {
@@ -1546,6 +1611,8 @@ async def responses_input_tokens(
token_counter: _TokenCounter = _token_counter_dep,
llm_router: Router | None = _llm_router_dep,
user_api_key_dict: UserAPIKeyAuth = _user_api_key_auth_dep,
+ response_id_security: ResponsesIDSecurity | None = _response_id_security_dep,
+ managed_files: _ManagedFileAccess | None = _managed_files_hook_dep,
):
"""
Count the input tokens of a Responses API request without calling the model.
@@ -1579,7 +1646,7 @@ async def responses_input_tokens(
)
counted_fields: Final = {
- name: data[name] for name in ("model", "tools", "drop_params", "additional_drop_params") if name in data
+ name: data[name] for name in ("model", "drop_params", "additional_drop_params", *TOOL_FIELDS) if name in data
}
token_fields: Final = resolve_counted_tool_fields(counted_fields, llm_router, user_api_key_dict.team_id)
if isinstance(token_fields, ProxyException):
@@ -1604,8 +1671,20 @@ async def responses_input_tokens(
message=f"Invalid request for token counting: {e}", param=None, code=None
)
+ request_fields: Final = _PROXY_SERVER_REQUEST_ADAPTER.validate_python(data)
+ responses_request: Final = await _with_managed_file_id_mapping(
+ _with_authorized_previous_response(
+ {**{name: value for name, value in request_fields.items() if name not in counted_fields}, **token_fields},
+ response_id_security,
+ user_api_key_dict,
+ ),
+ managed_files,
+ user_api_key_dict,
+ )
try:
- token_response: Final = await token_counter(request=token_request, call_endpoint=True)
+ token_response: Final = await token_counter(
+ request=token_request, call_endpoint=True, responses_request=responses_request
+ )
except ProxyException as e:
if e.type != _PROVIDER_COUNT_ERROR_TYPE:
raise
diff --git a/litellm/responses/file_search/emulated_handler.py b/litellm/responses/file_search/emulated_handler.py
index e2bb2ae40ea..7121908517b 100644
--- a/litellm/responses/file_search/emulated_handler.py
+++ b/litellm/responses/file_search/emulated_handler.py
@@ -45,7 +45,7 @@ class FileSearchToolCallArgs(TypedDict):
def should_use_emulated_file_search(
- tools: Iterable[ToolParam] | None,
+ tools: Iterable[object] | None,
provider_config: "BaseResponsesAPIConfig | None",
) -> bool:
"""Return True when there is a file_search tool and the provider can't handle it natively."""
@@ -105,7 +105,7 @@ def _build_function_tool(vector_store_ids: list[str]) -> dict[str, object]:
}
-def _replace_file_search_tools(
+def replace_file_search_tools(
tools: Iterable[ToolParam] | None,
) -> tuple[list[object], list[str]]:
"""
@@ -529,7 +529,7 @@ async def aresponses_with_emulated_file_search(
_include_search_results, call_kwargs = _prepare_emulated_file_search_call(kwargs=kwargs)
# 1. Replace file_search tools with function tool
- transformed_tools, all_vs_ids = _replace_file_search_tools(tools)
+ transformed_tools, all_vs_ids = replace_file_search_tools(tools)
# 2. First provider call — provider will call the file_search function.
# Mark as an internal sub-call so wrapper_async skips billing callbacks;
diff --git a/litellm/responses/litellm_completion_transformation/count_request.py b/litellm/responses/litellm_completion_transformation/count_request.py
new file mode 100644
index 00000000000..56a0b9024c5
--- /dev/null
+++ b/litellm/responses/litellm_completion_transformation/count_request.py
@@ -0,0 +1,207 @@
+from collections.abc import Mapping
+from dataclasses import dataclass
+from typing import Final, cast # noqa: TID251 # input items are forwarded as sent, as inference does
+
+from pydantic import BaseModel, JsonValue, TypeAdapter, ValidationError
+
+from litellm.exceptions import BadRequestError
+from litellm.litellm_core_utils.core_helpers import as_str_mapping
+from litellm.litellm_core_utils.prompt_templates.common_utils import (
+ update_responses_input_with_model_file_ids,
+ update_responses_tools_with_model_file_ids,
+)
+from litellm.litellm_core_utils.tool_fields import DropPolicy
+from litellm.llms.base_llm.files.batch_records import responses_batch_body_to_chat_body
+from litellm.responses.additional_tools import hoist_additional_tools
+from litellm.responses.file_search.emulated_handler import replace_file_search_tools
+from litellm.responses.litellm_completion_transformation.transformation import LiteLLMCompletionResponsesConfig
+from litellm.responses.main import previous_response_client_ids
+from litellm.types.llms.openai import ResponseInputParam
+from litellm.utils import ProviderConfigManager
+
+_COUNTED_CHAT_PARAMS: Final = (
+ "tool_choice",
+ "parallel_tool_calls",
+ "response_format",
+ "web_search_options",
+ "reasoning_effort",
+)
+_ITEMS: Final[TypeAdapter[tuple[object, ...]]] = TypeAdapter(tuple[object, ...])
+_MAPPINGS: Final[TypeAdapter[tuple[Mapping[str, object], ...]]] = TypeAdapter(tuple[Mapping[str, object], ...])
+_JSON_PARAMS: Final[TypeAdapter[Mapping[str, JsonValue]]] = TypeAdapter(Mapping[str, JsonValue])
+_ENTRY: Final[TypeAdapter[Mapping[str, object]]] = TypeAdapter(Mapping[str, object])
+_MARKED_ENTRY_LISTS: Final = frozenset({"content", "tool_calls"})
+_FILE_ID_MAPPING: Final[TypeAdapter[Mapping[str, Mapping[str, str]] | None]] = TypeAdapter(
+ Mapping[str, Mapping[str, str]] | None
+)
+MODEL_FILE_ID_MAPPING_FIELD: Final = "model_file_id_mapping"
+
+
+@dataclass(frozen=True, slots=True)
+class ChatCountRequest:
+ messages: tuple[Mapping[str, object], ...]
+ tools: tuple[Mapping[str, object], ...] | None
+ params: Mapping[str, JsonValue]
+
+
+@dataclass(frozen=True, slots=True)
+class ChatCountBridgeError:
+ message: str
+
+
+def _plain(item: object) -> object:
+ return item.model_dump(exclude_none=True) if isinstance(item, BaseModel) else item
+
+
+def _mappings(value: object) -> tuple[Mapping[str, object], ...]:
+ return _MAPPINGS.validate_python(tuple(_plain(item) for item in _ITEMS.validate_python(value or ())))
+
+
+def _unmarked(entry: Mapping[str, object]) -> Mapping[str, object]:
+ return {
+ key: _unmarked_entries(value) if key in _MARKED_ENTRY_LISTS else value
+ for key, value in entry.items()
+ if key != "cache_control"
+ }
+
+
+def _unmarked_entries(value: object) -> object:
+ return (
+ [
+ _unmarked(_ENTRY.validate_python(item)) if isinstance(item, Mapping) else item
+ for item in _ITEMS.validate_python(value)
+ ]
+ if isinstance(value, list)
+ else value
+ )
+
+
+def _routed_model_id(deployment: Mapping[str, object] | None) -> str | None:
+ model_info: Final = as_str_mapping(None if deployment is None else deployment.get("model_info")) or {}
+ model_id: Final = model_info.get("id")
+ return model_id if isinstance(model_id, str) else None
+
+
+def with_provider_file_ids(
+ responses_request: Mapping[str, object], deployment: Mapping[str, object] | None
+) -> Mapping[str, object]:
+ mapping: Final = _FILE_ID_MAPPING.validate_python(responses_request.get(MODEL_FILE_ID_MAPPING_FIELD))
+ model_id: Final = _routed_model_id(deployment)
+ fields: Final = {name: value for name, value in responses_request.items() if name != MODEL_FILE_ID_MAPPING_FIELD}
+ tools: Final = fields.get("tools")
+ return {
+ **fields,
+ **(
+ {"input": update_responses_input_with_model_file_ids(fields["input"], model_id, mapping)}
+ if "input" in fields
+ else {}
+ ),
+ **(
+ {
+ "tools": update_responses_tools_with_model_file_ids(
+ cast(list[dict[str, object]], tools), # cast-ok: entries that are not tools pass through as sent
+ model_id,
+ mapping,
+ )
+ }
+ if isinstance(tools, list)
+ else {}
+ ),
+ }
+
+
+def _with_hoisted_additional_tools(responses_request: Mapping[str, object]) -> Mapping[str, object]:
+ responses_input: Final = responses_request.get("input")
+ if not isinstance(responses_input, list):
+ return responses_request
+ input_items: Final = cast(ResponseInputParam, responses_input) # cast-ok: forwarded as sent, as inference does
+ hoisted: Final = hoist_additional_tools(input_items, None)
+ if not hoisted.hoisted:
+ return responses_request
+ return {
+ **responses_request,
+ "input": hoisted.input,
+ "tools": [*_ITEMS.validate_python(responses_request.get("tools") or ()), *hoisted.hoisted],
+ }
+
+
+def _with_emulated_file_search(responses_request: Mapping[str, object]) -> Mapping[str, object]:
+ tools: Final = responses_request.get("tools")
+ if tools is None:
+ return responses_request
+ return {**responses_request, "tools": replace_file_search_tools(_ITEMS.validate_python(tools))[0]}
+
+
+async def _with_previous_turns(
+ chat_body: Mapping[str, object],
+ model: str,
+ custom_llm_provider: str,
+ responses_request: Mapping[str, object],
+ policy: DropPolicy,
+) -> Mapping[str, object]:
+ previous_response_id: Final = responses_request.get("previous_response_id")
+ if not isinstance(previous_response_id, str) or not previous_response_id:
+ return chat_body
+ instructions: Final = responses_request.get("instructions")
+ return await LiteLLMCompletionResponsesConfig.async_responses_api_session_handler( # pyright: ignore[reportUnknownMemberType] # the session handler takes a bare dict request
+ previous_response_id=previous_response_id,
+ litellm_completion_request={**chat_body, "model": model, "custom_llm_provider": custom_llm_provider},
+ instructions=instructions if isinstance(instructions, str) else None,
+ request_kwargs={"drop_params": policy.drop_params},
+ previous_response_client_ids=previous_response_client_ids(previous_response_id, responses_request),
+ )
+
+
+def _counted_params(
+ chat_body: Mapping[str, object], tools: tuple[Mapping[str, object], ...], policy: DropPolicy
+) -> Mapping[str, JsonValue]:
+ sent: Final = {
+ name: chat_body[name]
+ for name in _COUNTED_CHAT_PARAMS
+ if chat_body.get(name) is not None and name not in policy.additional_drop_params
+ }
+ return _JSON_PARAMS.validate_python(
+ {**sent, **({"drop_params": True} if policy.drop_params and (sent or tools) else {})}
+ )
+
+
+async def chat_count_request(
+ model: str,
+ custom_llm_provider: str | None,
+ api_base: str | None,
+ responses_request: Mapping[str, object],
+ policy: DropPolicy,
+) -> ChatCountRequest | ChatCountBridgeError | None:
+ """The chat request Responses inference sends a provider with no native Responses API, or None
+ when inference sends this provider the Responses body itself."""
+ if custom_llm_provider is None or (
+ ProviderConfigManager.get_provider_responses_api_config(
+ provider=custom_llm_provider, model=model, api_base=api_base
+ )
+ is not None
+ ):
+ return None
+ try:
+ chat_body: Final = await _with_previous_turns(
+ responses_batch_body_to_chat_body(
+ _with_emulated_file_search(_with_hoisted_additional_tools(responses_request)),
+ custom_llm_provider,
+ policy.drop_params,
+ ),
+ model,
+ custom_llm_provider,
+ responses_request,
+ policy,
+ )
+ tools: Final = (
+ () if "tools" in policy.additional_drop_params else tuple(map(_unmarked, _mappings(chat_body.get("tools"))))
+ )
+ return ChatCountRequest(
+ messages=tuple(map(_unmarked, _mappings(chat_body.get("messages")))),
+ tools=tools or None,
+ params=_counted_params(chat_body, tools, policy),
+ )
+ except BadRequestError as e:
+ return ChatCountBridgeError(message=str(e.message))
+ except (ValidationError, ValueError, KeyError) as e:
+ return ChatCountBridgeError(message=f"Invalid request for token counting: {e}")
diff --git a/litellm/responses/litellm_completion_transformation/transformation.py b/litellm/responses/litellm_completion_transformation/transformation.py
index b613b817225..d9ebf50cc1a 100644
--- a/litellm/responses/litellm_completion_transformation/transformation.py
+++ b/litellm/responses/litellm_completion_transformation/transformation.py
@@ -1005,7 +1005,7 @@ class LiteLLMCompletionResponsesConfig:
session_lookup: Callable[[str], Awaitable[ChatCompletionSession]] | None = None,
request_kwargs: Mapping[str, object] = MappingProxyType({}),
previous_response_client_ids: tuple[str, ...] = (),
- ) -> dict:
+ ) -> dict[str, object]:
"""
Async hook to get the chain of previous input and output pairs and return a list of Chat Completion messages
"""
diff --git a/litellm/responses/main.py b/litellm/responses/main.py
index 51cd3be1b63..995921beed1 100644
--- a/litellm/responses/main.py
+++ b/litellm/responses/main.py
@@ -548,7 +548,7 @@ def _bridges_to_chat_completions(
_RESPONSES_ONLY_REQUEST_FIELDS_NEVER_BRIDGED: Final = frozenset({"client_metadata"})
-def _previous_response_client_ids(previous_response_id: str | None, kwargs: Mapping[str, object]) -> tuple[str, ...]:
+def previous_response_client_ids(previous_response_id: str | None, kwargs: Mapping[str, object]) -> tuple[str, ...]:
"""The forms of the previous response's id the client held, which its spend log row can be stored under."""
if not previous_response_id:
return ()
@@ -1622,7 +1622,7 @@ def responses(
if _bridges_to_chat_completions(responses_api_provider_config, use_chat_completions_api):
bridge_kwargs: Final = _bridge_kwargs(kwargs, responses_api_provider_config, allowed_openai_params)
return litellm_completion_transformation_handler.response_api_handler(
- _previous_response_client_ids(previous_response_id, kwargs),
+ previous_response_client_ids(previous_response_id, kwargs),
model=model,
input=input,
responses_api_request=response_api_optional_params,
diff --git a/tests/integration/providers/_count_tokens_system_lift.py b/tests/integration/providers/_count_tokens_system_lift.py
index 56619d1c963..dedf6b5006d 100644
--- a/tests/integration/providers/_count_tokens_system_lift.py
+++ b/tests/integration/providers/_count_tokens_system_lift.py
@@ -49,6 +49,87 @@ TOOLS: Final[list[JsonValue]] = [
}
]
+WEATHER_SCHEMA: Final[dict[str, JsonValue]] = {
+ "type": "object",
+ "properties": {"city": {"type": "string", "description": "City to look up"}},
+ "required": ["city"],
+}
+RESPONSES_TOOLS: Final[list[JsonValue]] = [
+ {
+ "type": "function",
+ "name": "get_weather",
+ "description": "Look up the current weather for a city",
+ "parameters": WEATHER_SCHEMA,
+ }
+]
+RESPONSES_TOOL_USE: Final[Mapping[str, dict[str, JsonValue]]] = MappingProxyType(
+ {
+ "function-tool": {"input": "Count this message", "instructions": "Be terse", "tools": RESPONSES_TOOLS},
+ "tool-round-trip": {
+ "input": [
+ {"role": "user", "content": "What is the weather in Paris?"},
+ {"type": "function_call", "call_id": "call_1", "name": "get_weather", "arguments": '{"city": "Paris"}'},
+ {"type": "function_call_output", "call_id": "call_1", "output": "Sunny, 21C"},
+ ],
+ "tools": RESPONSES_TOOLS,
+ },
+ }
+)
+
+
+def counted_fields(body: Mapping[str, JsonValue]) -> dict[str, JsonValue]:
+ return {field: body[field] for field in ("messages", "system", "tools") if field in body}
+
+
+REPORT_SCHEMA: Final[dict[str, JsonValue]] = {
+ "type": "object",
+ "properties": {"city": {"type": "string"}, "summary": {"type": "string"}},
+ "required": ["city", "summary"],
+ "additionalProperties": False,
+}
+WEATHER_QUESTION: Final = "What is the weather in Paris?"
+RESPONSES_REQUEST_OPTIONS: Final[Mapping[str, dict[str, JsonValue]]] = MappingProxyType(
+ {
+ "text-format": {
+ "input": WEATHER_QUESTION,
+ "text": {"format": {"type": "json_schema", "name": "weather_report", "schema": REPORT_SCHEMA}},
+ },
+ "forced-tool-choice-dropped": {
+ "input": WEATHER_QUESTION,
+ "tools": RESPONSES_TOOLS,
+ "tool_choice": {"type": "function", "name": "get_weather"},
+ "parallel_tool_calls": False,
+ "drop_params": True,
+ },
+ "reasoning": {
+ "input": WEATHER_QUESTION,
+ "tools": RESPONSES_TOOLS,
+ "tool_choice": "auto",
+ "reasoning": {"effort": "low"},
+ },
+ }
+)
+_REQUEST_OPTIONS: Final = ("tool_choice", "thinking")
+
+
+def count_request_fields(count_body: Mapping[str, JsonValue]) -> dict[str, JsonValue]:
+ options: Final = (*_REQUEST_OPTIONS, "output_config", "output_format")
+ return {**counted_fields(count_body), **{field: count_body[field] for field in options if field in count_body}}
+
+
+def inference_count_fields(inference_body: Mapping[str, JsonValue]) -> dict[str, JsonValue]:
+ output_config: Final = inference_body.get("output_config")
+ output_format: Final = inference_body.get("output_format")
+ counted_config: Final = {
+ **(output_config if isinstance(output_config, dict) else {}),
+ **({} if output_format is None else {"format": output_format}),
+ }
+ return {
+ **counted_fields(inference_body),
+ **{field: inference_body[field] for field in _REQUEST_OPTIONS if field in inference_body},
+ **({"output_config": counted_config} if counted_config else {}),
+ }
+
@dataclass(frozen=True, slots=True)
class LiftCase:
diff --git a/tests/integration/providers/test_anthropic_count_tokens_system_lift_wire.py b/tests/integration/providers/test_anthropic_count_tokens_system_lift_wire.py
index afd25fcfa04..27cbbe81a13 100644
--- a/tests/integration/providers/test_anthropic_count_tokens_system_lift_wire.py
+++ b/tests/integration/providers/test_anthropic_count_tokens_system_lift_wire.py
@@ -6,6 +6,7 @@ from collections.abc import Callable, Iterator, Mapping
from concurrent.futures import ThreadPoolExecutor
from contextlib import AbstractContextManager, ExitStack
from dataclasses import dataclass
+from pathlib import Path
from queue import SimpleQueue
from types import MappingProxyType
from typing import Final, cast
@@ -14,8 +15,10 @@ import httpcore
import httpx
import psutil
import pytest
+import yaml
from anthropic.types import MessageParam
-from integration._support.client import Gateway, Scenario, eventually, gateway_from_environment
+from integration._support.client import Gateway, Scenario, eventually, gateway_from_environment, object_value
+from integration._support.process import graceful_stop_seconds, owned_proxy
from integration._support.wire import Reply, Request, Wire, wire_server
from integration._support.ports import allocate_port
from integration.providers._count_tokens_system_lift import (
@@ -32,18 +35,24 @@ from integration.providers._count_tokens_system_lift import (
MID_SYSTEM,
REJECTION,
REMINDER,
+ RESPONSES_REQUEST_OPTIONS,
+ RESPONSES_TOOL_USE,
STRING_CASE,
TOKEN_COUNTING_BETA,
TOOLS,
USER,
USER_TEXT,
+ WEATHER_QUESTION,
LiftCase,
accepts_count_body,
anthropic_client,
async_anthropic_client,
async_openai_client,
count_request,
+ count_request_fields,
+ counted_fields,
expected_count_body,
+ inference_count_fields,
openai_client,
)
from pydantic import JsonValue, TypeAdapter
@@ -480,9 +489,7 @@ def test_messages_count_tokens_unauthenticated_request_never_reaches_the_peer(
assert peer.drain() == ()
-def test_peer_outage_between_concurrent_waves_errors_then_recovers(
- deployment: _Deployment, gateway: Gateway
-) -> None:
+def test_peer_outage_between_concurrent_waves_errors_then_recovers(deployment: _Deployment, gateway: Gateway) -> None:
with ExitStack() as stack:
clients: Final = _clients(stack, str(gateway.client.base_url), 8)
pool: Final = stack.enter_context(ThreadPoolExecutor(max_workers=len(clients)))
@@ -573,3 +580,164 @@ def test_chat_completions_on_the_same_deployment_keeps_a_mid_conversation_system
{"role": "assistant", "content": [{"type": "text", "text": "One."}]},
{"role": "user", "content": [{"type": "text", "text": "Again"}]},
], body
+
+
+_GENERATED: Final[dict[str, JsonValue]] = {
+ "id": "msg_generated",
+ "type": "message",
+ "role": "assistant",
+ "model": _MODEL,
+ "content": [{"type": "text", "text": "done"}],
+ "stop_reason": "end_turn",
+ "stop_sequence": None,
+ "usage": {"input_tokens": 12, "output_tokens": 3},
+}
+
+
+def _generating(provider: _Provider) -> Callable[[Request], Reply]:
+ def respond(request: Request) -> Reply:
+ if request.target == provider.target.removesuffix("/count_tokens"):
+ return _json_reply(200, _GENERATED)
+ return _peer(provider)(request)
+
+ return respond
+
+
[email protected]("request_body", RESPONSES_TOOL_USE.values(), ids=RESPONSES_TOOL_USE.keys())
+def test_responses_input_tokens_counts_what_responses_inference_sends(
+ deployment: _Deployment, gateway: Gateway, request_body: dict[str, JsonValue]
+) -> None:
+ with wire_server(_generating(deployment.provider), port=deployment.port) as peer:
+ generated: Final = gateway.request(
+ "POST", "/v1/responses", {**request_body, "model": deployment.model, "max_output_tokens": 16}
+ )
+ assert generated.status_code == 200, generated.text
+ response: Final = gateway.request(
+ "POST", "/v1/responses/input_tokens", {**request_body, "model": deployment.model}
+ )
+ assert _payload(response)["input_tokens"] == _COUNT, response.text
+ inference, counted = (counted_fields(JSON_OBJECT.validate_json(request.body)) for request in peer.drain())
+ assert counted == inference, (counted, inference)
+
+
+def _inference_and_count(peer: Wire) -> tuple[dict[str, JsonValue], dict[str, JsonValue]]:
+ inference, counted = (JSON_OBJECT.validate_json(request.body) for request in peer.drain())
+ return inference, counted
+
+
[email protected]("request_body", RESPONSES_REQUEST_OPTIONS.values(), ids=RESPONSES_REQUEST_OPTIONS.keys())
+def test_responses_input_tokens_counts_the_request_options_responses_inference_sends(
+ deployment: _Deployment, gateway: Gateway, request_body: dict[str, JsonValue]
+) -> None:
+ with wire_server(_generating(deployment.provider), port=deployment.port) as peer:
+ generated: Final = gateway.request(
+ "POST", "/v1/responses", {**request_body, "model": deployment.model, "max_output_tokens": 4096}
+ )
+ assert generated.status_code == 200, generated.text
+ response: Final = gateway.request(
+ "POST", "/v1/responses/input_tokens", {**request_body, "model": deployment.model}
+ )
+ assert _payload(response)["input_tokens"] == _COUNT, response.text
+ inference, counted = _inference_and_count(peer)
+ assert count_request_fields(counted) == inference_count_fields(inference), (counted, inference)
+
+
+def _text_blocks(message: JsonValue) -> JsonValue:
+ if not isinstance(message, dict) or not isinstance(message.get("content"), str):
+ return message
+ return {**message, "content": [{"type": "text", "text": message["content"]}]}
+
+
+def _with_text_blocks(fields: dict[str, JsonValue]) -> dict[str, JsonValue]:
+ messages: Final = fields["messages"]
+ assert isinstance(messages, list), fields
+ return {**fields, "messages": [_text_blocks(message) for message in messages]}
+
+
+def test_responses_input_tokens_leaves_tool_choice_out_when_drop_params_drops_every_tool(
+ deployment: _Deployment, gateway: Gateway
+) -> None:
+ request_body: Final[dict[str, JsonValue]] = {
+ "input": WEATHER_QUESTION,
+ "tools": [5],
+ "tool_choice": "required",
+ "drop_params": True,
+ }
+ with wire_server(_generating(deployment.provider), port=deployment.port) as peer:
+ generated: Final = gateway.request(
+ "POST", "/v1/responses", {**request_body, "model": deployment.model, "max_output_tokens": 16}
+ )
+ assert generated.status_code == 200, generated.text
+ response: Final = gateway.request(
+ "POST", "/v1/responses/input_tokens", {**request_body, "model": deployment.model}
+ )
+ assert _payload(response)["input_tokens"] == _COUNT, response.text
+ inference, counted = _inference_and_count(peer)
+ assert "tools" not in counted and "tool_choice" not in counted, counted
+ assert _with_text_blocks(count_request_fields(counted)) == inference_count_fields(inference), (
+ counted,
+ inference,
+ )
+
+
+def _config_storing_prompts(directory: Path) -> Path:
+ config: Final = object_value(yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text()))
+ general_settings: Final = object_value(config["general_settings"])
+ path: Final = directory / "store-prompts.yaml"
+ path.write_text(
+ yaml.safe_dump({**config, "general_settings": {**general_settings, "store_prompts_in_spend_logs": True}})
+ )
+ return path
+
+
+def _replying(answer: str) -> Callable[[Request], Reply]:
+ def respond(request: Request) -> Reply:
+ if request.target == _ANTHROPIC.target:
+ return _counted(request)
+ if request.target == "/v1/messages":
+ return _json_reply(
+ 200,
+ {**_GENERATED, "id": f"msg_{uuid.uuid4().hex}", "content": [{"type": "text", "text": answer}]},
+ )
+ return _json_reply(404, {"error": f"unscripted target {request.target}"})
+
+ return respond
+
+
+def _spend_rows_with(prompt_gateway: Gateway, marker: str) -> list[dict[str, JsonValue]]:
+ return prompt_gateway.rows(
+ 'SELECT request_id FROM "LiteLLM_SpendLogs" WHERE proxy_server_request::text LIKE %s', (f"%{marker}%",)
+ )
+
+
[email protected](2 * graceful_stop_seconds() + 120)
+def test_responses_input_tokens_counts_the_turns_previous_response_id_replays(gateway: Gateway, tmp_path: Path) -> None:
+ first_prompt: Final = f"Remember the number {uuid.uuid4().hex}"
+ answer: Final = f"Remembered {uuid.uuid4().hex}"
+ follow_up: Final[dict[str, JsonValue]] = {"input": "What number did I ask you to remember?"}
+ port: Final = allocate_port()
+ with (
+ wire_server(_replying(answer), port=port) as peer,
+ owned_proxy(gateway, tmp_path, {}, config=_config_storing_prompts(tmp_path), workers=1) as prompt_gateway,
+ prompt_gateway.scenario() as scenario,
+ ):
+ model: Final = scenario.model(
+ model_info=None, model=f"anthropic/{_MODEL}", api_base=f"http://127.0.0.1:{port}", api_key=_API_KEY
+ )
+ first: Final = prompt_gateway.request(
+ "POST", "/v1/responses", {"model": model, "input": first_prompt, "max_output_tokens": 16}
+ )
+ assert first.status_code == 200, first.text
+ previous: Final = {
+ **follow_up,
+ "model": model,
+ "previous_response_id": JSON_OBJECT.validate_json(first.content)["id"],
+ }
+ eventually(lambda: _spend_rows_with(prompt_gateway, first_prompt), lambda rows: len(rows) == 1, seconds=70)
+ response: Final = prompt_gateway.request("POST", "/v1/responses/input_tokens", previous)
+ assert _payload(response)["input_tokens"] == _COUNT, response.text
+ generated: Final = prompt_gateway.request("POST", "/v1/responses", {**previous, "max_output_tokens": 16})
+ assert generated.status_code == 200, generated.text
+ _, counted, inference = (JSON_OBJECT.validate_json(request.body) for request in peer.drain())
+ assert first_prompt in json.dumps(inference["messages"]) and answer in json.dumps(inference["messages"])
+ assert counted_fields(counted) == counted_fields(inference), (counted, inference)
diff --git a/tests/integration/providers/test_bedrock_mantle_count_tokens_wire.py b/tests/integration/providers/test_bedrock_mantle_count_tokens_wire.py
index 4fe29fa49d8..063b0e46479 100644
--- a/tests/integration/providers/test_bedrock_mantle_count_tokens_wire.py
+++ b/tests/integration/providers/test_bedrock_mantle_count_tokens_wire.py
@@ -32,9 +32,12 @@ from integration.providers._count_tokens_system_lift import (
LIFTED,
MID_SYSTEM,
REMINDER,
+ RESPONSES_TOOLS,
STRING_CASE,
USER,
USER_TEXT,
+ WEATHER_QUESTION,
+ WEATHER_SCHEMA,
LiftCase,
accepts_count_body,
async_openai_client,
@@ -1636,3 +1639,107 @@ def test_utils_token_counter_local_mode_never_calls_either_peer(counting_proxy:
model: Final = _fallback_deployment(scenario, runtime.url)
assert _local_count(gateway, _full(model)) > 0
assert runtime.drain() == () and mantle.drain() == ()
+
+
+_FORCED_TOOL_CHOICE: Final[dict[str, JsonValue]] = {
+ "input": WEATHER_QUESTION,
+ "tools": RESPONSES_TOOLS,
+ "tool_choice": {"type": "function", "name": "get_weather"},
+}
+_CHAT_TOOLS: Final[list[JsonValue]] = [
+ {
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "description": "Look up the current weather for a city",
+ "parameters": WEATHER_SCHEMA,
+ },
+ }
+]
+_WEATHER_MESSAGES: Final[list[JsonValue]] = [{"role": "user", "content": WEATHER_QUESTION}]
+_TOOL_USE_FIELDS: Final = ("tools", "tool_choice")
+
+
+def _tool_use_fields(body: Mapping[str, JsonValue]) -> dict[str, JsonValue]:
+ return {field: body[field] for field in _TOOL_USE_FIELDS if field in body}
+
+
+def _converse_count_tools(request: Request) -> JsonValue:
+ count_input: Final = _JSON_OBJECT.validate_python(_JSON_OBJECT.validate_json(request.body)["input"])
+ converse: Final = _JSON_OBJECT.validate_python(count_input["converse"])
+ return _JSON_OBJECT.validate_python(converse["toolConfig"])["tools"]
+
+
+def _requests_to(requests: Sequence[Request], pattern: re.Pattern[str]) -> tuple[Request, ...]:
+ return tuple(request for request in requests if pattern.match(target_of(request)))
+
+
+def test_responses_input_tokens_sends_mantle_the_tool_use_invoke_inference_sends(
+ counting_proxy: OwnedProxy, mantle_port: int
+) -> None:
+ gateway: Final = counting_proxy.gateway
+ with (
+ wire_server(_runtime) as runtime,
+ wire_server(_mantle(), port=mantle_port) as mantle,
+ gateway.scenario() as scenario,
+ ):
+ counted_model: Final = _deployment(scenario, runtime.url)
+ invoked_model: Final = _deployment(scenario, runtime.url, f"invoke/{_OPUS}")
+ generated: Final = gateway.request(
+ "POST", "/v1/responses", {**_FORCED_TOOL_CHOICE, "model": invoked_model, "max_output_tokens": 16}
+ )
+ assert generated.status_code == 200, generated.text
+ response: Final = gateway.request(
+ "POST", "/v1/responses/input_tokens", {**_FORCED_TOOL_CHOICE, "model": counted_model}
+ )
+ assert _payload(response)["input_tokens"] == _MANTLE_COUNT, response.text
+ requests: Final = runtime.drain()
+ (invoked,) = _requests_to(requests, _INVOKE_TARGET)
+ (mantle_count,) = _mantle_bodies(mantle)
+ expected: Final = _tool_use_fields(_JSON_OBJECT.validate_json(invoked.body))
+ assert set(expected) == set(_TOOL_USE_FIELDS), expected
+ assert _requests_to(requests, _COUNT_TARGET) == ()
+ assert _tool_use_fields(mantle_count) == expected, mantle_count
+
+
+def _counting_every_model(request: Request) -> Reply:
+ if _COUNT_TARGET.match(target_of(request)):
+ return _json_reply(200, {"inputTokens": _RUNTIME_COUNT})
+ return runtime_generation(request)
+
+
+_NOVA_COUNTS: Final[Mapping[str, tuple[str, dict[str, JsonValue], str]]] = MappingProxyType(
+ {
+ "utils-token-counter": (
+ "/utils/token_counter?call_endpoint=true",
+ {"messages": _WEATHER_MESSAGES, "tools": _CHAT_TOOLS},
+ "total_tokens",
+ ),
+ "responses-input-tokens": (
+ "/v1/responses/input_tokens",
+ {"input": WEATHER_QUESTION, "tools": RESPONSES_TOOLS},
+ "input_tokens",
+ ),
+ }
+)
+
+
[email protected]("route", _NOVA_COUNTS.keys())
+def test_nova_count_sends_the_tool_specs_converse_inference_sends(counting_proxy: OwnedProxy, route: str) -> None:
+ path, body, count_field = _NOVA_COUNTS[route]
+ gateway: Final = counting_proxy.gateway
+ with wire_server(_counting_every_model) as runtime, gateway.scenario() as scenario:
+ model: Final = _deployment(scenario, runtime.url, _NOVA)
+ generated: Final = gateway.request(
+ "POST",
+ "/v1/chat/completions",
+ {"model": model, "messages": _WEATHER_MESSAGES, "tools": _CHAT_TOOLS, "max_tokens": 16},
+ )
+ assert generated.status_code == 200, generated.text
+ response: Final = gateway.request("POST", path, {**body, "model": model})
+ assert _payload(response)[count_field] == _RUNTIME_COUNT, response.text
+ requests: Final = runtime.drain()
+ (converse,) = (request for request in requests if target_of(request) == f"/model/{_NOVA}/converse")
+ (counted,) = _requests_to(requests, _COUNT_TARGET)
+ inference_tools: Final = _JSON_OBJECT.validate_python(_JSON_OBJECT.validate_json(converse.body)["toolConfig"])
+ assert _converse_count_tools(counted) == inference_tools["tools"], counted.body
diff --git a/tests/integration/providers/test_malformed_tools_wire.py b/tests/integration/providers/test_malformed_tools_wire.py
index 706babac398..910f3faf312 100644
--- a/tests/integration/providers/test_malformed_tools_wire.py
+++ b/tests/integration/providers/test_malformed_tools_wire.py
@@ -1418,7 +1418,7 @@ def test_count_tokens_rejects_malformed_tools_when_a_request_list_replaces_the_d
assert _delivered(rig, marker) == ()
-def test_responses_input_tokens_drops_the_bad_entry_a_deployment_list_names(
+def test_responses_input_tokens_drops_the_tools_a_deployment_list_names(
rig: _Rig, field_groups: _FieldGroups
) -> None:
marker: Final = _marker()
@@ -1428,8 +1428,7 @@ def test_responses_input_tokens_drops_the_bad_entry_a_deployment_list_names(
{"model": field_groups.anthropic, "input": marker, "tools": [RESPONSES.tool, 5]},
)
assert response.status_code == 200, response.text
- tools: Final = _one_delivery(rig, marker, "/v1/messages/count_tokens")["tools"]
- assert isinstance(tools, list) and len(tools) == 1 and "get_weather" in json.dumps(tools), tools
+ assert "tools" not in _one_delivery(rig, marker, "/v1/messages/count_tokens")
def test_responses_input_tokens_rejects_malformed_tools_when_a_request_list_replaces_the_deployment_list(
@@ -1669,7 +1668,7 @@ _CHECKED: Final[Mapping[str, _Checked]] = MappingProxyType(
send=_input_tokens,
target="/v1/messages/count_tokens",
answered=_counted({"object": "response.input_tokens", "input_tokens": _COUNT, **_PROVIDER_SOURCE}),
- kept_by_a_tools_list=("get_weather",),
+ kept_by_a_tools_list=(),
bad_entry=_RESPONSES_BAD_ENTRY,
),
}
@@ -2336,14 +2335,14 @@ def test_a_deployment_list_with_a_non_string_entry_drops_tools_it_names_on_messa
@_TOKEN_COUNTS
-def test_token_counting_with_a_request_list_with_a_non_string_entry_drops_the_bad_entry(
+def test_token_counting_with_a_request_list_with_a_non_string_entry_counts_the_tools_its_route_keeps(
rig: _Rig, checked: _Checked
) -> None:
marker: Final = _marker()
response: Final = checked.send(
rig, rig.anthropic, marker, {"tools": [checked.tool, 5], "additional_drop_params": ["tools", 5]}
)
- _assert_forwarded(rig, checked, response, marker, ("get_weather",))
+ _assert_forwarded(rig, checked, response, marker, checked.kept_by_a_tools_list)
def _alias(suffix: str, variant: str) -> str:
diff --git a/tests/integration/providers/test_openai_count_tokens_tools_wire.py b/tests/integration/providers/test_openai_count_tokens_tools_wire.py
index 16a5b8685ad..96410b03a92 100644
--- a/tests/integration/providers/test_openai_count_tokens_tools_wire.py
+++ b/tests/integration/providers/test_openai_count_tokens_tools_wire.py
@@ -415,4 +415,76 @@ def test_responses_input_tokens_passes_an_openai_count_error_through(
response: Final = gateway.request("POST", "/v1/responses/input_tokens", {"model": model, "input": "hello"})
assert response.status_code == 400, response.text
assert response.json() == {"error": {"param": None, "code": None, **error}}, response.text
- assert _count_body(wire)["input"] == [{"role": "user", "content": "hello"}]
+ assert _count_body(wire)["input"] == "hello"
+
+
+_NATIVE_TEXT: Final[dict[str, JsonValue]] = {
+ "format": {"type": "json_schema", "name": "answer", "schema": _ANSWER_SCHEMA},
+}
+_NATIVE_BODY: Final[Mapping[str, JsonValue]] = {
+ "input": [
+ {"role": "user", "content": "hi"},
+ {"type": "reasoning", "summary": [], "encrypted_content": _WRAPPED_REASONING},
+ {"role": "user", "content": "again"},
+ ],
+ "text": _NATIVE_TEXT,
+ "max_output_tokens": "lots",
+ "metadata": {"run": "nightly"},
+}
+
+
+ ("drop_params", "expected_extra"),
+ [pytest.param(False, {"max_output_tokens": "lots"}, id="as-sent"), pytest.param(True, {}, id="drop-params")],
+)
+def test_responses_input_tokens_sends_the_callers_body_to_openai(
+ counting_proxy: OwnedProxy, drop_params: bool, expected_extra: dict[str, JsonValue]
+) -> None:
+ gateway: Final = counting_proxy.gateway
+ with wire_server(_count_response) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model="openai/gpt-4o-mini",
+ api_base=f"{wire.url}/v1",
+ api_key="sk-integration-openai",
+ drop_params=drop_params,
+ )
+ response: Final = gateway.request("POST", "/v1/responses/input_tokens", {"model": model, **_NATIVE_BODY})
+ assert response.status_code == 200, response.text
+ assert _JSON_OBJECT.validate_json(response.content)["input_tokens"] == _COUNT
+ assert _count_body(wire) == {
+ "model": "gpt-4o-mini",
+ "input": [
+ {"role": "user", "content": "hi"},
+ {"type": "reasoning", "summary": [], "encrypted_content": "gAAAAoriginal"},
+ {"role": "user", "content": "again"},
+ ],
+ "text": _NATIVE_TEXT,
+ **expected_extra,
+ }
+
+
+def test_responses_input_tokens_sends_openai_the_owners_previous_response_id(counting_proxy: OwnedProxy) -> None:
+ gateway: Final = counting_proxy.gateway
+ with wire_server(_responses_peer) as wire, gateway.scenario() as scenario:
+ model: Final = _deployment(scenario, wire.url)
+ team: Final = scenario.team(models=[model])
+ owner_key: Final = scenario.key(team_id=team, user_id=scenario.member(team), models=[model])
+ other_key: Final = scenario.key(team_id=team, user_id=scenario.member(team), models=[model])
+ generated: Final = gateway.request("POST", "/v1/responses", {"model": model, "input": "hi"}, key=owner_key)
+ assert generated.status_code == 200, generated.text
+ follow_up: Final = {
+ "model": model,
+ "input": "again",
+ "previous_response_id": _JSON_OBJECT.validate_json(generated.content)["id"],
+ }
+ _body_for(wire.drain(), "/v1/responses")
+
+ refused: Final = gateway.request("POST", "/v1/responses/input_tokens", follow_up, key=other_key)
+ assert refused.status_code == 403, refused.text
+ assert _JSON_OBJECT.validate_json(refused.content)["error"]["type"] == "permission_error", refused.text
+ assert wire.drain() == ()
+
+ counted: Final = gateway.request("POST", "/v1/responses/input_tokens", follow_up, key=owner_key)
+ assert counted.status_code == 200, counted.text
+ count_body: Final = _body_for(wire.drain(), "/v1/responses/input_tokens")
+ assert count_body["previous_response_id"] == _RESPONSES_REPLY["id"]
diff --git a/tests/integration/providers/test_responses_core_wire.py b/tests/integration/providers/test_responses_core_wire.py
index 791b2b8783f..9a24903a20d 100644
--- a/tests/integration/providers/test_responses_core_wire.py
+++ b/tests/integration/providers/test_responses_core_wire.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import json
import os
import uuid
+from collections.abc import Callable
from typing import Final
import openai
@@ -192,6 +193,42 @@ def test_previous_response_id_uses_the_raw_id_and_affinity(
], [request.body for request in requests]
+def _counting_peer(raw_id: str, input_tokens: int) -> Callable[[Request], Reply]:
+ def respond(request: Request) -> Reply:
+ if request.method == "GET" and request.target == "/v1/models":
+ return model_discovery_reply(_MODEL)
+ if request.target == "/v1/responses/input_tokens":
+ return Reply(body=json.dumps({"object": "response.input_tokens", "input_tokens": input_tokens}).encode())
+ return Reply(body=_response(raw_id))
+
+ return respond
+
+
+def test_input_tokens_count_goes_to_the_deployment_that_served_the_previous_response(gateway: Gateway) -> None:
+ raw_id: Final = f"resp_count_affinity_{uuid.uuid4().hex}"
+ with (
+ wire_server(_counting_peer(raw_id, 37)) as first_wire,
+ wire_server(_counting_peer(raw_id, 99)) as second_wire,
+ gateway.scenario() as scenario,
+ ):
+ model: Final = f"integration-{uuid.uuid4().hex}"
+ _enable_responses_affinity(scenario)
+ assert _register(scenario, first_wire, model) == model
+ client: Final = openai.OpenAI(base_url=f"{gateway.client.base_url}/v1", api_key=gateway.key, max_retries=0)
+ first: Final = client.responses.create(model=model, input="turn one")
+ _register_in_group(scenario, second_wire, model, order=1)
+ counted: Final = client.responses.input_tokens.count(
+ model=model, input="turn two", previous_response_id=first.id
+ )
+ assert counted.input_tokens == 37, counted.model_dump_json()
+ assert drain_contract_requests(second_wire) == (), "the count left the previous response's deployment"
+ requests: Final = drain_contract_requests(first_wire)
+ assert [(request.target, _JSON_OBJECT.validate_json(request.body)) for request in requests] == [
+ ("/v1/responses", {"model": _MODEL, "input": "turn one"}),
+ ("/v1/responses/input_tokens", {"model": _MODEL, "input": "turn two", "previous_response_id": raw_id}),
+ ], [request.body for request in requests]
+
+
@pytest.mark.parametrize("prefix", _ALIASES)
def test_codex_responses_request_preserves_all_supported_fields(gateway: Gateway, prefix: str) -> None:
response_id: Final = f"resp_codex_{uuid.uuid4().hex}"
diff --git a/tests/integration/providers/test_vertex_gemini_count_tokens_wire.py b/tests/integration/providers/test_vertex_gemini_count_tokens_wire.py
index ec3fb941037..1632e424c55 100644
--- a/tests/integration/providers/test_vertex_gemini_count_tokens_wire.py
+++ b/tests/integration/providers/test_vertex_gemini_count_tokens_wire.py
@@ -1096,3 +1096,57 @@ def test_utils_token_counter_counts_a_local_prompt_with_system_or_tools_like_its
assert as_message.status_code == 200, as_message.text
assert _total_tokens(prompted) == _total_tokens(as_message)
assert requests == ()
+
+
+_RESPONSES_TOOL_ROUND_TRIP: Final[Mapping[str, JsonValue]] = MappingProxyType(
+ {
+ "instructions": "Follow the system instruction.",
+ "input": [
+ {"role": "user", "content": "Look up the value."},
+ {"type": "function_call", "call_id": "call_lookup", "name": "lookup", "arguments": '{"query":"value"}'},
+ {"type": "function_call_output", "call_id": "call_lookup", "output": "result"},
+ ],
+ "tools": [
+ {
+ "type": "function",
+ "name": "lookup",
+ "description": "Look up a value",
+ "parameters": {"type": "object", "properties": {"query": {"type": "string"}}},
+ }
+ ],
+ }
+)
+
+
[email protected]("provider", ("vertex_ai", "gemini"))
+def test_responses_input_tokens_counts_the_tool_round_trip_contents_responses_inference_sends(
+ gateway: Gateway, provider: str
+) -> None:
+ peer: Final = _GeminiPeer()
+ with wire_server(peer) as wire, gateway.scenario() as scenario:
+ model: Final = (
+ _deployment(gateway, scenario, wire.url)
+ if provider == "vertex_ai"
+ else _ai_studio_deployment(scenario, wire.url)
+ )
+ body: Final = {"model": model, **_RESPONSES_TOOL_ROUND_TRIP}
+ generated: Final = gateway.request("POST", "/v1/responses", {**body, "max_output_tokens": 16})
+ counted: Final = gateway.request("POST", "/v1/responses/input_tokens", body)
+ assert generated.status_code == 200, generated.text
+ assert counted.status_code == 200, counted.text
+ assert _JSON_OBJECT.validate_json(counted.content)["input_tokens"] == _COUNT, counted.text
+ requests: Final = peer.drain()
+ (generated_request,) = (request for request in requests if request.target.endswith(":generateContent"))
+ (count_request,) = (request for request in requests if request.target.endswith(":countTokens"))
+ instruction: Final[JsonValue] = {"text": _RESPONSES_TOOL_ROUND_TRIP["instructions"]}
+ first_turn, *later_turns = _JSON_LIST.validate_python(_counted_contents(_json_body(count_request)))
+ first_parts: Final = _JSON_LIST.validate_python(_JSON_OBJECT.validate_python(first_turn)["parts"])
+ assert instruction in first_parts, count_request.body
+ counted_turns: Final = [
+ {
+ **_JSON_OBJECT.validate_python(first_turn),
+ "parts": [part for part in first_parts if part != instruction],
+ },
+ *later_turns,
+ ]
+ assert counted_turns == _json_body(generated_request)["contents"], count_request.body
diff --git a/tests/integration/providers/test_vertex_partner_count_tokens_wire.py b/tests/integration/providers/test_vertex_partner_count_tokens_wire.py
index 1956301f1be..c679311e4cc 100644
--- a/tests/integration/providers/test_vertex_partner_count_tokens_wire.py
+++ b/tests/integration/providers/test_vertex_partner_count_tokens_wire.py
@@ -19,6 +19,13 @@ from integration._support.client import Gateway, Scenario, eventually
from integration._support.process import graceful_stop_seconds, owned_proxy_process
from integration._support.vertex import service_account_json
from integration._support.wire import Reply, Request, Wire, wire_server
+from integration.providers._count_tokens_system_lift import (
+ RESPONSES_REQUEST_OPTIONS,
+ RESPONSES_TOOL_USE,
+ count_request_fields,
+ counted_fields,
+ inference_count_fields,
+)
from integration._support.ports import allocate_port
from pydantic import JsonValue, TypeAdapter
from tokenizers import Regex, Tokenizer, models, pre_tokenizers
@@ -427,14 +434,22 @@ def test_utils_token_counter_local_mode_never_calls_the_peer(gateway: Gateway) -
assert wire.drain() == ()
-def test_utils_token_counter_surfaces_the_peer_error_for_openai_tools(gateway: Gateway) -> None:
+def _inference_and_count_fields(wire: Wire) -> tuple[dict[str, JsonValue], ...]:
+ requests: Final = wire.drain()
+ (inference,) = (request for request in requests if request.target == _MESSAGE_TARGET)
+ return (counted_fields(_JSON_OBJECT.validate_json(inference.body)), *map(counted_fields, _count_bodies(requests)))
+
+
+def test_utils_token_counter_counts_openai_tools_the_way_chat_inference_sends_them(gateway: Gateway) -> None:
with wire_server(_peer(_strict)) as wire, gateway.scenario() as scenario:
model: Final = _deployment(gateway, scenario, wire.url)
body: Final = {**_bare(model), "tools": _OPENAI_TOOLS}
+ generated: Final = gateway.request("POST", "/v1/chat/completions", {**body, "max_tokens": 16})
+ assert generated.status_code == 200, generated.text
response: Final = gateway.request("POST", "/utils/token_counter", body, params={"call_endpoint": "true"})
- assert response.status_code == 400, response.text
- assert "total_tokens" not in response.text, response.text
- assert _counted_bodies(wire) == ({**_PEER_BARE, "tools": _OPENAI_TOOLS},)
+ assert _payload(response)["total_tokens"] == _PEER_COUNT, response.text
+ inference, counted = _inference_and_count_fields(wire)
+ assert counted == inference, (counted, inference)
def test_responses_input_tokens_counts_through_the_partner_peer(gateway: Gateway) -> None:
@@ -451,8 +466,24 @@ def test_responses_input_tokens_counts_through_the_partner_peer(gateway: Gateway
assert _counted_bodies(wire) == (_PEER_BARE,)
-def test_responses_input_tokens_surfaces_the_peer_error(gateway: Gateway) -> None:
[email protected]("request_body", RESPONSES_TOOL_USE.values(), ids=RESPONSES_TOOL_USE.keys())
+def test_responses_input_tokens_counts_what_responses_inference_sends(
+ gateway: Gateway, request_body: dict[str, JsonValue]
+) -> None:
with wire_server(_peer(_strict)) as wire, gateway.scenario() as scenario:
+ model: Final = _deployment(gateway, scenario, wire.url)
+ generated: Final = gateway.request(
+ "POST", "/v1/responses", {**request_body, "model": model, "max_output_tokens": 16}
+ )
+ assert generated.status_code == 200, generated.text
+ response: Final = gateway.request("POST", "/v1/responses/input_tokens", {**request_body, "model": model})
+ assert _payload(response)["input_tokens"] == _PEER_COUNT, response.text
+ inference, counted = _inference_and_count_fields(wire)
+ assert counted == inference, (counted, inference)
+
+
+def test_responses_input_tokens_surfaces_the_peer_error(gateway: Gateway) -> None:
+ with wire_server(_peer(_rejecting(400))) as wire, gateway.scenario() as scenario:
model: Final = _deployment(gateway, scenario, wire.url)
response: Final = gateway.request(
"POST",
@@ -462,7 +493,33 @@ def test_responses_input_tokens_surfaces_the_peer_error(gateway: Gateway) -> Non
assert response.status_code == 400, response.text
assert response.json() == _RESPONSES_ROUTE.rejection(_REJECTION), response.text
(sent,) = _counted_bodies(wire)
- assert sent["tools"] == _RESPONSES_TOOLS, sent
+ assert sent["system"] == [{"type": "text", "text": "Be terse"}], sent
+ assert sent["tools"] == [
+ {
+ "name": "get_weather",
+ "input_schema": _WEATHER_SCHEMA,
+ "type": "custom",
+ "description": "Look up the current weather for a city",
+ }
+ ], sent
+
+
+def test_responses_input_tokens_rejects_an_unpaired_tool_output_without_calling_vertex(gateway: Gateway) -> None:
+ with wire_server(_peer(_strict)) as wire, gateway.scenario() as scenario:
+ model: Final = _deployment(gateway, scenario, wire.url)
+ body: Final[dict[str, JsonValue]] = {
+ "model": model,
+ "input": [
+ {"role": "user", "content": "What is the weather in Paris?"},
+ {"type": "function_call", "call_id": "call_1", "name": "get_weather", "arguments": "Paris?"},
+ {"type": "function_call_output", "call_id": "call_1", "output": "Sunny"},
+ ],
+ "tools": _RESPONSES_TOOLS,
+ }
+ response: Final = gateway.request("POST", "/v1/responses/input_tokens", body)
+ assert response.status_code == 400, response.text
+ assert "get_weather" in _error_message(_JSON_OBJECT.validate_json(response.content)), response.text
+ assert wire.drain() == ()
def test_responses_input_tokens_types_a_peer_error_by_its_status(gateway: Gateway) -> None:
@@ -890,3 +947,20 @@ def test_responses_endpoint_on_the_same_deployment_still_generates(gateway: Gate
(sent,) = wire.drain()
assert sent.target == _MESSAGE_TARGET, sent.target
assert marker in sent.body.decode(), sent.body
+
+
+def test_responses_input_tokens_counts_the_structured_output_responses_inference_sends(gateway: Gateway) -> None:
+ request_body: Final = RESPONSES_REQUEST_OPTIONS["text-format"]
+ with wire_server(_peer(_strict)) as wire, gateway.scenario() as scenario:
+ model: Final = _deployment(gateway, scenario, wire.url)
+ generated: Final = gateway.request(
+ "POST", "/v1/responses", {**request_body, "model": model, "max_output_tokens": 4096}
+ )
+ assert generated.status_code == 200, generated.text
+ response: Final = gateway.request("POST", "/v1/responses/input_tokens", {**request_body, "model": model})
+ assert _payload(response)["input_tokens"] == _PEER_COUNT, response.text
+ requests: Final = wire.drain()
+ (inference,) = (request for request in requests if request.target == _MESSAGE_TARGET)
+ (counted,) = _count_bodies(requests)
+ expected: Final = inference_count_fields(_JSON_OBJECT.validate_json(inference.body))
+ assert count_request_fields(counted) == expected, (counted, expected)
diff --git a/tests/integration/sdk/test_vertex_partner_count_tokens_sdk.py b/tests/integration/sdk/test_vertex_partner_count_tokens_sdk.py
index e59d3f9264a..2e1205be688 100644
--- a/tests/integration/sdk/test_vertex_partner_count_tokens_sdk.py
+++ b/tests/integration/sdk/test_vertex_partner_count_tokens_sdk.py
@@ -1,5 +1,5 @@
import json
-from collections.abc import Callable
+from collections.abc import Callable, Mapping
from typing import Final
import litellm
@@ -88,3 +88,77 @@ async def test_acount_tokens_falls_back_to_the_local_tokenizer_when_the_peer_rej
assert len(_count_requests(wire.drain())) == 1
assert counted.tokenizer_type == "local_tokenizer", counted
assert counted.total_tokens > 0 and counted.total_tokens != _PEER_COUNT, counted
+
+
+_WEATHER_SCHEMA: Final[dict[str, JsonValue]] = {
+ "type": "object",
+ "properties": {"city": {"type": "string"}},
+ "required": ["city"],
+}
+_CHAT_TOOLS: Final[list[dict[str, JsonValue]]] = [
+ {
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "description": "Look up the current weather for a city",
+ "parameters": _WEATHER_SCHEMA,
+ },
+ }
+]
+_CHAT_TOOL_USE: Final[list[dict[str, JsonValue]]] = [
+ {"role": "user", "content": "What is the weather in Paris?"},
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {"id": "call_1", "type": "function", "function": {"name": "get_weather", "arguments": '{"city": "Paris"}'}}
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_1", "content": "Sunny, 21C"},
+]
+_GENERATED: Final[dict[str, JsonValue]] = {
+ "id": "msg_sdk_count",
+ "type": "message",
+ "role": "assistant",
+ "model": _BACKEND,
+ "content": [{"type": "text", "text": "It is sunny."}],
+ "stop_reason": "end_turn",
+ "stop_sequence": None,
+ "usage": {"input_tokens": 12, "output_tokens": 3},
+}
+_COUNTED_FIELDS: Final = ("messages", "system", "tools")
+
+
+def _generating_peer(request: Request) -> Reply:
+ if request.target == "/_oauth/token":
+ token: Final = {"access_token": "scripted-token", "token_type": "Bearer", "expires_in": 3600}
+ return Reply(body=json.dumps(token).encode())
+ if "count-tokens" in request.target:
+ return Reply(body=json.dumps({"input_tokens": _PEER_COUNT}).encode())
+ if request.target.endswith(f"/{_BACKEND}:rawPredict"):
+ return Reply(body=json.dumps(_GENERATED).encode())
+ return Reply(status=404, body=json.dumps({"error": request.target}).encode())
+
+
+def _counted_fields(body: Mapping[str, JsonValue]) -> dict[str, JsonValue]:
+ return {field: body[field] for field in _COUNTED_FIELDS if field in body}
+
+
+async def test_acount_tokens_sends_chat_tool_use_the_way_acompletion_sends_it(
+ vertex_environment: Callable[[str], None],
+) -> None:
+ with wire_server(_generating_peer) as wire:
+ vertex_environment(wire.url)
+ generated: Final = await litellm.acompletion(
+ model=f"vertex_ai/{_BACKEND}", messages=_CHAT_TOOL_USE, tools=_CHAT_TOOLS, max_tokens=16, api_base=wire.url
+ )
+ assert generated.choices[0].message.content == "It is sunny.", generated
+ counted: Final = await litellm.acount_tokens(
+ model=f"vertex_ai/{_BACKEND}", messages=_CHAT_TOOL_USE, tools=_CHAT_TOOLS, api_base=wire.url
+ )
+ assert (counted.total_tokens, counted.tokenizer_type) == (_PEER_COUNT, "vertex_ai_partner_models"), counted
+ requests: Final = wire.drain()
+ (inference,) = (request for request in requests if request.target.endswith(f"/{_BACKEND}:rawPredict"))
+ (count,) = _count_requests(requests)
+ expected: Final = _counted_fields(_JSON_OBJECT.validate_json(inference.body))
+ assert _counted_fields(_JSON_OBJECT.validate_json(count.body)) == expected, (count.body, expected)
diff --git a/tests/unit/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_common_utils.py b/tests/unit/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_common_utils.py
index c08eeea4bb9..cc0ef062e4b 100644
--- a/tests/unit/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_common_utils.py
+++ b/tests/unit/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_common_utils.py
@@ -1085,6 +1085,30 @@ def test_update_responses_input_with_model_file_ids_decodes_xlitellm_encoded_id(
assert updated[0]["content"][1]["file_id"] == raw_id
+
[email protected]("unusable_file_id", [[1], {"a": 1}])
+def test_update_responses_input_with_model_file_ids_keeps_a_non_string_file_id_as_sent(unusable_file_id):
+ from litellm.litellm_core_utils.prompt_templates.common_utils import (
+ update_responses_input_with_model_file_ids,
+ )
+
+ encoded_id = _xlitellm_encoded("file-ExTuCawUqxEMjVFK6xwR9B", "gpt-5.1")
+ input_items = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "input_file", "file_id": encoded_id},
+ {"type": "input_file", "file_id": unusable_file_id},
+ ],
+ }
+ ]
+
+ updated = update_responses_input_with_model_file_ids(
+ input_items, "model-A", {encoded_id: {"model-A": "file-on-a"}}
+ )
+
+ assert [item["file_id"] for item in updated[0]["content"]] == ["file-on-a", unusable_file_id]
+
def test_update_messages_xlitellm_decode_does_not_override_mapping():
"""If the call-site already resolved a provider id via the mapping, that
wins. The new decode fallback runs only when no mapping match."""
diff --git a/tests/unit/llms/anthropic/test_anthropic_count_tokens_transformation.py b/tests/unit/llms/anthropic/test_anthropic_count_tokens_transformation.py
index 9af7497bc82..63f149fabe4 100644
--- a/tests/unit/llms/anthropic/test_anthropic_count_tokens_transformation.py
+++ b/tests/unit/llms/anthropic/test_anthropic_count_tokens_transformation.py
@@ -1,7 +1,10 @@
import asyncio
from base64 import b64encode
+from collections.abc import Mapping
from copy import deepcopy
+from queue import SimpleQueue
from threading import get_ident
+from types import MappingProxyType
from typing import Final
import httpx
@@ -10,16 +13,20 @@ import respx
from pydantic import JsonValue, TypeAdapter
import litellm
+from litellm.llms.anthropic.chat.transformation import AnthropicConfig
from litellm.llms.anthropic.count_tokens.handler import AnthropicCountTokensHandler
+from litellm.llms.anthropic.count_tokens.token_counter import AnthropicTokenCounter
from litellm.llms.anthropic.count_tokens.transformation import (
AnthropicCountTokensConfig,
)
from litellm.llms.azure_ai.anthropic.count_tokens.handler import (
AzureAIAnthropicCountTokensHandler,
)
+from litellm.llms.azure_ai.anthropic.count_tokens.token_counter import AzureAIAnthropicTokenCounter
from litellm.llms.azure_ai.anthropic.count_tokens.transformation import (
AzureAIAnthropicCountTokensConfig,
)
+from litellm.types.utils import TokenCountMessagesFormat, TokenCountResponse
@pytest.mark.parametrize(
@@ -441,3 +448,302 @@ async def test_handler_sends_the_leading_system_run_as_system_not_as_a_message(h
"system": [{"type": "text", "text": "Be terse"}],
"messages": [{"role": "user", "content": "Hello, how are you?"}],
}
+
+
+_WEATHER_SCHEMA: Final[dict[str, JsonValue]] = {"type": "object", "properties": {"city": {"type": "string"}}}
+
+_CHAT_TOOL_TURNS: Final[list[dict[str, JsonValue]]] = [
+ {"role": "system", "content": "Be terse."},
+ {"role": "user", "content": "Weather in SF?"},
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {"id": "call_1", "type": "function", "function": {"name": "get_weather", "arguments": '{"city": "SF"}'}}
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_1", "content": "sunny"},
+]
+
+
+_COUNTERS: Final = pytest.mark.parametrize(
+ ("counter_type", "count_endpoint"),
+ (
+ (AnthropicTokenCounter, "https://gateway.example/v1/messages/count_tokens"),
+ (AzureAIAnthropicTokenCounter, "https://gateway.example/anthropic/v1/messages/count_tokens"),
+ ),
+)
+
+
+async def _counted_body(
+ counter_type: type[AnthropicTokenCounter] | type[AzureAIAnthropicTokenCounter],
+ count_endpoint: str,
+ messages: list[dict[str, JsonValue]],
+ tools: list[dict[str, JsonValue]] | None,
+ messages_format: TokenCountMessagesFormat,
+ chat_params: Mapping[str, JsonValue] = MappingProxyType({}),
+) -> tuple[TokenCountResponse | None, tuple[dict[str, JsonValue], ...]]:
+ sent: Final[SimpleQueue[bytes]] = SimpleQueue()
+
+ def count(request: httpx.Request) -> httpx.Response:
+ sent.put(request.content)
+ return httpx.Response(200, json={"input_tokens": 31})
+
+ with respx.mock:
+ respx.post(count_endpoint).mock(side_effect=count)
+ result: Final = await counter_type().count_tokens(
+ model_to_use="claude-opus-5-5",
+ messages=messages,
+ contents=None,
+ deployment={"litellm_params": {"api_key": "sk-ant-api03-test-key", "api_base": "https://gateway.example"}},
+ request_model="claude-opus-5-5",
+ tools=tools,
+ messages_format=messages_format,
+ chat_params=chat_params,
+ )
+ return result, tuple(TypeAdapter(dict[str, JsonValue]).validate_json(sent.get()) for _ in range(sent.qsize()))
+
+
[email protected]("httpx_transport_clients")
+@_COUNTERS
+ "tool",
+ (
+ {"type": "function", "name": "get_weather", "description": "Look up the weather", "parameters": _WEATHER_SCHEMA},
+ {
+ "type": "function",
+ "function": {"name": "get_weather", "description": "Look up the weather", "parameters": _WEATHER_SCHEMA},
+ },
+ ),
+)
+async def test_counter_sends_chat_tool_use_in_the_shape_chat_inference_sends(
+ counter_type: type[AnthropicTokenCounter] | type[AzureAIAnthropicTokenCounter],
+ count_endpoint: str,
+ tool: dict[str, JsonValue],
+) -> None:
+ """Responses and chat bodies reach the counter as chat messages and tools, which Anthropic rejects
+ with a 400 unless they are translated the way the chat inference request translates them."""
+ original: Final = deepcopy(_CHAT_TOOL_TURNS)
+ result, bodies = await _counted_body(counter_type, count_endpoint, _CHAT_TOOL_TURNS, [tool], "openai")
+
+ assert result is not None
+ assert result.error is not True
+ assert result.total_tokens == 31
+ assert bodies == (
+ {
+ "model": "claude-opus-5-5",
+ "system": [{"type": "text", "text": "Be terse."}],
+ "messages": [
+ {"role": "user", "content": [{"type": "text", "text": "Weather in SF?"}]},
+ {
+ "role": "assistant",
+ "content": [{"type": "tool_use", "id": "call_1", "name": "get_weather", "input": {"city": "SF"}}],
+ },
+ {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "call_1", "content": "sunny"}]},
+ ],
+ "tools": [
+ {
+ "name": "get_weather",
+ "input_schema": _WEATHER_SCHEMA,
+ "type": "custom",
+ "description": "Look up the weather",
+ }
+ ],
+ },
+ )
+ assert _CHAT_TOOL_TURNS == original
+
+
+_ANTHROPIC_TOOL_USE: Final[list[dict[str, JsonValue]]] = [
+ {"role": "user", "content": "Weather in SF?"},
+ {"role": "assistant", "content": [{"type": "tool_use", "id": "toolu_1", "name": "get_weather", "input": {}}]},
+ {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "toolu_1", "content": "sunny"}]},
+]
+
+
[email protected]("httpx_transport_clients")
+@_COUNTERS
+ ("messages", "tool", "messages_format"),
+ (
+ (_ANTHROPIC_TOOL_USE, {"name": "get_weather", "input_schema": _WEATHER_SCHEMA}, "openai"),
+ (
+ [{"role": "user", "content": "Weather in SF?"}],
+ {"type": "function", "name": "get_weather", "parameters": _WEATHER_SCHEMA},
+ "anthropic",
+ ),
+ ),
+)
+async def test_counter_sends_anthropic_shaped_and_messages_api_requests_as_sent(
+ counter_type: type[AnthropicTokenCounter] | type[AzureAIAnthropicTokenCounter],
+ count_endpoint: str,
+ messages: list[dict[str, JsonValue]],
+ tool: dict[str, JsonValue],
+ messages_format: TokenCountMessagesFormat,
+) -> None:
+ _, bodies = await _counted_body(counter_type, count_endpoint, messages, [tool], messages_format)
+
+ assert bodies == ({"model": "claude-opus-5-5", "messages": messages, "tools": [tool]},)
+
+
[email protected]("httpx_transport_clients")
+@_COUNTERS
+async def test_counter_rejects_a_tool_call_chat_inference_rejects_without_calling_anthropic(
+ counter_type: type[AnthropicTokenCounter] | type[AzureAIAnthropicTokenCounter], count_endpoint: str
+) -> None:
+ messages: Final[list[dict[str, JsonValue]]] = [
+ {"role": "user", "content": "Weather in SF?"},
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {"id": "call_1", "type": "function", "function": {"name": "get_weather", "arguments": "sunny?"}}
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_1", "content": "sunny"},
+ ]
+ result, bodies = await _counted_body(counter_type, count_endpoint, messages, None, "openai")
+
+ assert bodies == ()
+ assert result is not None
+ assert result.error is True
+ assert result.status_code == 400
+ assert result.rejected_before_provider_call is True
+ assert "Failed to parse tool call arguments for tool 'get_weather'" in (result.error_message or "")
+
+
[email protected]("httpx_transport_clients")
+@_COUNTERS
+async def test_counter_rejects_a_chat_tool_without_a_name_without_calling_anthropic(
+ counter_type: type[AnthropicTokenCounter] | type[AzureAIAnthropicTokenCounter], count_endpoint: str
+) -> None:
+ result, bodies = await _counted_body(
+ counter_type,
+ count_endpoint,
+ [{"role": "user", "content": "Weather in SF?"}],
+ [{"type": "function", "function": {"parameters": _WEATHER_SCHEMA}}],
+ "openai",
+ )
+
+ assert bodies == ()
+ assert result is not None
+ assert (result.error, result.status_code, result.rejected_before_provider_call) == (True, 400, True)
+
+
+_CHAT_WEATHER_TOOL: Final[dict[str, JsonValue]] = {
+ "type": "function",
+ "function": {"name": "get_weather", "parameters": _WEATHER_SCHEMA},
+}
+
+
[email protected]("httpx_transport_clients")
+@_COUNTERS
+ ("messages", "tools"),
+ (
+ pytest.param(
+ [
+ {
+ "role": "user",
+ "name": "ana",
+ "content": [
+ {"type": "text", "text": "Describe this"},
+ {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "iVBORw0K"}},
+ ],
+ }
+ ],
+ None,
+ id="native-image-block",
+ ),
+ pytest.param(
+ [
+ {"role": "user", "content": "Weather in SF?"},
+ {
+ "role": "assistant",
+ "content": [{"type": "tool_use", "id": "toolu_1", "name": "get_weather", "input": {"city": "SF"}}],
+ },
+ {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "toolu_1", "content": "sunny"}]},
+ ],
+ [_CHAT_WEATHER_TOOL],
+ id="native-tool-result-block",
+ ),
+ pytest.param(
+ [{"role": "user", "content": "Open the docs"}],
+ [
+ {"type": "computer_use_preview", "display_width": 1024, "display_height": 768, "environment": "browser"},
+ _CHAT_WEATHER_TOOL,
+ ],
+ id="computer-use-preview-tool",
+ ),
+ pytest.param(
+ [{"role": "user", "content": "Ask the wiki"}],
+ [{"type": "mcp", "server_label": "wiki", "server_url": "https://mcp.example/mcp"}, _CHAT_WEATHER_TOOL],
+ id="mcp-tool",
+ ),
+ ),
+)
+async def test_counter_rejects_input_chat_translation_would_leave_out_without_calling_anthropic(
+ counter_type: type[AnthropicTokenCounter] | type[AzureAIAnthropicTokenCounter],
+ count_endpoint: str,
+ messages: list[dict[str, JsonValue]],
+ tools: list[dict[str, JsonValue]] | None,
+) -> None:
+ result, bodies = await _counted_body(counter_type, count_endpoint, messages, tools, "openai")
+
+ assert bodies == ()
+ assert result is not None
+ assert (result.error, result.status_code, result.rejected_before_provider_call) == (True, 400, True)
+
+
+_ANSWER_SCHEMA: Final[dict[str, JsonValue]] = {
+ "type": "object",
+ "properties": {"answer": {"type": "string"}},
+ "required": ["answer"],
+ "additionalProperties": False,
+}
+
+
[email protected]("httpx_transport_clients")
+@_COUNTERS
+async def test_counter_sends_the_structured_output_tool_choice_and_thinking_chat_inference_sends(
+ counter_type: type[AnthropicTokenCounter] | type[AzureAIAnthropicTokenCounter], count_endpoint: str
+) -> None:
+ """count_tokens refuses the beta output_format that chat inference sends, so the count carries the same
+ schema as output_config.format, next to the inference request's thinking and tool_choice."""
+ messages: Final[list[dict[str, JsonValue]]] = [{"role": "user", "content": "Weather in SF?"}]
+ tool: Final[dict[str, JsonValue]] = {
+ "type": "function",
+ "function": {"name": "get_weather", "parameters": _WEATHER_SCHEMA},
+ }
+ chat_params: Final[dict[str, JsonValue]] = {
+ "response_format": {"type": "json_schema", "json_schema": {"name": "answer", "schema": _ANSWER_SCHEMA}},
+ "reasoning_effort": "low",
+ "tool_choice": "auto",
+ }
+ config: Final = AnthropicConfig()
+ inference: Final = config.transform_request(
+ model="claude-opus-5-5",
+ messages=deepcopy(messages),
+ optional_params=config.map_openai_params(
+ {**chat_params, "tools": [tool]}, {}, "claude-opus-5-5", drop_params=False
+ ),
+ litellm_params={},
+ headers={},
+ )
+
+ _, bodies = await _counted_body(counter_type, count_endpoint, messages, [tool], "openai", chat_params)
+
+ (body,) = bodies
+ assert "output_format" not in body
+ assert body["output_config"] == {**inference.get("output_config", {}), "format": inference["output_format"]}
+ assert (body["thinking"], body["tool_choice"], body["tools"]) == (
+ inference["thinking"],
+ inference["tool_choice"],
+ inference["tools"],
+ )
diff --git a/tests/unit/llms/bedrock/count_tokens/test_bedrock_count_tokens_transformation.py b/tests/unit/llms/bedrock/count_tokens/test_bedrock_count_tokens_transformation.py
index b357c5ac126..052baf601f9 100644
--- a/tests/unit/llms/bedrock/count_tokens/test_bedrock_count_tokens_transformation.py
+++ b/tests/unit/llms/bedrock/count_tokens/test_bedrock_count_tokens_transformation.py
@@ -168,6 +168,25 @@ def test_transform_includes_tools():
assert tools[0]["toolSpec"]["inputSchema"]["json"]["type"] == "object"
+def test_transform_maps_chat_function_tools():
+ parameters = {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}
+ request = {
+ "model": "amazon.nova-pro-v1:0",
+ "messages": [{"role": "user", "content": "Weather in Paris?"}],
+ "tools": [
+ {
+ "type": "function",
+ "function": {"name": "get_weather", "description": "Look up the weather", "parameters": parameters},
+ }
+ ],
+ }
+
+ result = BedrockCountTokensConfig().transform_anthropic_to_bedrock_count_tokens(request)
+
+ assert result["input"]["converse"]["toolConfig"]["tools"] == [
+ {"toolSpec": {"name": "get_weather", "description": "Look up the weather", "inputSchema": {"json": parameters}}}
+ ]
+
def test_transform_includes_system_and_tools_together():
"""Test that both system and tools are included together."""
config = BedrockCountTokensConfig()
diff --git a/tests/unit/llms/bedrock/count_tokens/test_bedrock_token_counter.py b/tests/unit/llms/bedrock/count_tokens/test_bedrock_token_counter.py
index dd0d6429f8a..6fb47491323 100644
--- a/tests/unit/llms/bedrock/count_tokens/test_bedrock_token_counter.py
+++ b/tests/unit/llms/bedrock/count_tokens/test_bedrock_token_counter.py
@@ -1,3 +1,4 @@
+import base64
from collections.abc import Mapping
from typing import Final
@@ -176,6 +177,130 @@ async def test_claude_runtime_404_retries_with_system_and_tools_on_mantle() -> N
}
+def _invoke_body(request: httpx.Request) -> dict[str, JsonValue]:
+ invoke_model: Final = _JSON_BODY.validate_json(request.content)["input"]
+ assert isinstance(invoke_model, dict)
+ encoded: Final = invoke_model["invokeModel"]
+ assert isinstance(encoded, dict) and isinstance(encoded["body"], str)
+ return _JSON_BODY.validate_json(base64.b64decode(encoded["body"]))
+
+
+ "chat_params",
+ [
+ {"tool_choice": "required"},
+ {
+ "response_format": {
+ "type": "json_schema",
+ "json_schema": {"name": "city", "schema": {"type": "object", "properties": {"city": {"type": "string"}}}},
+ }
+ },
+ {"reasoning_effort": "low"},
+ ],
+)
+async def test_runtime_count_leaves_out_the_options_only_mantle_counts(chat_params: dict[str, JsonValue]) -> None:
+ runtime_counts: Final = _Bedrock(runtime=(200, {"inputTokens": 412}), mantle=(200, {"input_tokens": 2177}))
+ mantle_counts: Final = _Bedrock(runtime=(404, UNSUPPORTED), mantle=(200, {"input_tokens": 2177}))
+ request: Final = {
+ "model_to_use": "global.anthropic.claude-opus-4-8",
+ "messages": [{"role": "user", "content": "Weather in SF?"}],
+ "contents": None,
+ "deployment": DEPLOYMENT,
+ "request_model": "claude-opus-4-8",
+ "tools": [{"type": "function", "function": {"name": "get_weather", "parameters": {"type": "object"}}}],
+ "messages_format": "openai",
+ "chat_params": chat_params,
+ }
+
+ await _counter(runtime_counts).count_tokens(**request)
+ await _counter(mantle_counts).count_tokens(**request)
+
+ assert runtime_counts.posted_hosts() == (RUNTIME_HOST,)
+ assert mantle_counts.posted_hosts() == (RUNTIME_HOST, MANTLE_HOST)
+ options: Final = ("thinking", "tool_choice", "output_config")
+ invoke_body: Final = _invoke_body(runtime_counts.requests[0])
+ mantle_body: Final = _JSON_BODY.validate_json(mantle_counts.requests[1].content)
+ assert [name for name in options if name in invoke_body] == []
+ assert [name for name in options if name in mantle_body] != []
+ assert {name: mantle_body[name] for name in ("messages", "tools")} == {
+ name: invoke_body[name] for name in ("messages", "tools")
+ }
+
+
+async def test_claude_chat_tool_use_is_counted_in_the_shape_claude_inference_sends() -> None:
+ bedrock: Final = _Bedrock(runtime=(200, {"inputTokens": 412}), mantle=(200, {"input_tokens": 2177}))
+ schema: Final = {"type": "object", "properties": {"city": {"type": "string"}}}
+
+ result: Final = await _counter(bedrock).count_tokens(
+ model_to_use="global.anthropic.claude-opus-4-8",
+ messages=[
+ {"role": "user", "content": "Weather in SF?"},
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {"id": "call_1", "type": "function", "function": {"name": "get_weather", "arguments": "{}"}}
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_1", "content": "sunny"},
+ ],
+ contents=None,
+ deployment=DEPLOYMENT,
+ request_model="claude-opus-4-8",
+ tools=[{"type": "function", "function": {"name": "get_weather", "parameters": schema}}],
+ messages_format="openai",
+ )
+
+ assert result is not None
+ assert (result.error, result.total_tokens) == (False, 412)
+ assert bedrock.posted_hosts() == (RUNTIME_HOST,)
+ body: Final = _invoke_body(bedrock.requests[0])
+ assert body["tools"] == [{"name": "get_weather", "input_schema": schema, "type": "custom"}]
+ assert body["messages"] == [
+ {"role": "user", "content": [{"type": "text", "text": "Weather in SF?"}]},
+ {"role": "assistant", "content": [{"type": "tool_use", "id": "call_1", "name": "get_weather", "input": {}}]},
+ {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "call_1", "content": "sunny"}]},
+ ]
+
+async def test_claude_chat_tool_use_counted_on_mantle_metadata_route_is_translated_too() -> None:
+ bedrock: Final = _Bedrock(runtime=(200, {"inputTokens": 412}), mantle=(200, {"input_tokens": 2177}))
+ schema: Final = {"type": "object", "properties": {"city": {"type": "string"}}}
+
+ result: Final = await _counter(bedrock).count_tokens(
+ model_to_use="bedrock_mantle/global.anthropic.claude-opus-4-8",
+ messages=[
+ {"role": "user", "content": "Weather in SF?"},
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {"id": "call_1", "type": "function", "function": {"name": "get_weather", "arguments": "{}"}}
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_1", "content": "sunny"},
+ ],
+ contents=None,
+ deployment=DEPLOYMENT,
+ request_model="claude-opus-4-8",
+ tools=[{"type": "function", "function": {"name": "get_weather", "parameters": schema}}],
+ messages_format="openai",
+ )
+
+ assert result is not None
+ assert (result.error, result.total_tokens) == (False, 2177)
+ assert bedrock.posted_hosts() == (MANTLE_HOST,)
+ body: Final = _JSON_BODY.validate_json(bedrock.requests[0].content)
+ assert body["tools"] == [{"name": "get_weather", "input_schema": schema, "type": "custom"}]
+ assert body["messages"] == [
+ {"role": "user", "content": [{"type": "text", "text": "Weather in SF?"}]},
+ {"role": "assistant", "content": [{"type": "tool_use", "id": "call_1", "name": "get_weather", "input": {}}]},
+ {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "call_1", "content": "sunny"}]},
+ ]
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize(
("model", "host", "tokenizer", "expected_tokens"),
diff --git a/tests/unit/llms/openai/responses/count_tokens/test_token_counter.py b/tests/unit/llms/openai/responses/count_tokens/test_token_counter.py
index 7495d98b42a..17c1b35e211 100644
--- a/tests/unit/llms/openai/responses/count_tokens/test_token_counter.py
+++ b/tests/unit/llms/openai/responses/count_tokens/test_token_counter.py
@@ -1,3 +1,4 @@
+import copy
import json
import operator
from collections.abc import Mapping
@@ -9,6 +10,7 @@ import respx
from pydantic import JsonValue, ValidationError
import litellm
+from litellm.litellm_core_utils.tool_fields import DropPolicy
from litellm.llms.openai.responses.count_tokens.token_counter import OpenAITokenCounter
from litellm.responses.utils import ResponsesAPIRequestUtils
from litellm.types.utils import TokenCountMessagesFormat, TokenCountResponse
@@ -521,3 +523,122 @@ async def test_count_sends_the_global_key_only_to_the_global_api_base(monkeypatc
assert result is not None
assert result.total_tokens == 4
assert route.calls.last.request.headers["authorization"] == "Bearer sk-private-gateway"
+
+
+_KEEP_ALL: Final = DropPolicy(drop_params=False, additional_drop_params=frozenset())
+_ANSWER_FORMAT: Final[dict[str, object]] = {
+ "format": {"type": "json_schema", "name": "answer", "schema": {"type": "object", "properties": {}}}
+}
+_STORED_PROMPT: Final[dict[str, object]] = {"id": "pmpt_abc", "variables": {"city": "Paris"}}
+_CALLER_BODY: Final[dict[str, object]] = {
+ "model": "my-gpt",
+ "input": "hi",
+ "text": _ANSWER_FORMAT,
+ "prompt": _STORED_PROMPT,
+ "max_output_tokens": "lots",
+ "metadata": {"run": "nightly"},
+ "drop_params": False,
+ "additional_drop_params": [],
+ "timeout": 30,
+ "extra_headers": {"x-trace": "1"},
+ "disable_fallbacks": True,
+ "spend_logs_metadata": {"team": "search"},
+ "mock_testing_fallbacks": True,
+}
+
+
+async def _native_count(
+ monkeypatch: pytest.MonkeyPatch, request: Mapping[str, object], policy: DropPolicy, response: httpx.Response
+) -> tuple[TokenCountResponse | None, object]:
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ with respx.mock:
+ route: Final = respx.post(COUNT_URL).mock(return_value=response)
+ result: Final = await OpenAITokenCounter().count_responses_request(
+ model_to_use="gpt-4o",
+ request=request,
+ policy=policy,
+ deployment={"litellm_params": {"api_key": "sk-test"}},
+ request_model="my-gpt",
+ )
+ return result, json.loads(route.calls.last.request.content)
+
+
+ ("policy", "expected_sent"),
+ [
+ pytest.param(
+ _KEEP_ALL,
+ {
+ "model": "gpt-4o",
+ "input": "hi",
+ "text": _ANSWER_FORMAT,
+ "prompt": _STORED_PROMPT,
+ "max_output_tokens": "lots",
+ },
+ id="keeps-responses-fields",
+ ),
+ pytest.param(
+ DropPolicy(drop_params=True, additional_drop_params=frozenset()),
+ {"model": "gpt-4o", "input": "hi", "text": _ANSWER_FORMAT, "prompt": _STORED_PROMPT},
+ id="drop-params-keeps-count-fields",
+ ),
+ pytest.param(
+ DropPolicy(drop_params=False, additional_drop_params=frozenset({"text"})),
+ {"model": "gpt-4o", "input": "hi", "prompt": _STORED_PROMPT, "max_output_tokens": "lots"},
+ id="additional-drop-params",
+ ),
+ ],
+)
+async def test_native_count_sends_the_callers_body_without_litellm_fields(
+ monkeypatch: pytest.MonkeyPatch, policy: DropPolicy, expected_sent: dict[str, object]
+) -> None:
+ result, sent = await _native_count(
+ monkeypatch, _CALLER_BODY, policy, httpx.Response(200, json={"input_tokens": 76})
+ )
+
+ assert sent == expected_sent
+ assert result is not None
+ assert (result.total_tokens, result.model_used, result.error) == (76, "gpt-4o", False)
+
+
+async def test_native_count_restores_provider_ids_on_a_copy_of_the_callers_body(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ wrapped: Final = ResponsesAPIRequestUtils.wrap_encrypted_content_with_model_id("gAAAAoriginal", "deployment-1")
+ request: Final[dict[str, object]] = {
+ "model": "my-gpt",
+ "previous_response_id": ResponsesAPIRequestUtils._build_responses_api_response_id(
+ "openai", "deployment-1", "resp_original"
+ ),
+ "input": [
+ {"type": "reasoning", "summary": [], "encrypted_content": wrapped},
+ {"role": "user", "content": "again"},
+ ],
+ }
+ before: Final = copy.deepcopy(request)
+
+ _, sent = await _native_count(monkeypatch, request, _KEEP_ALL, httpx.Response(200, json={"input_tokens": 1}))
+
+ assert sent == {
+ "model": "gpt-4o",
+ "previous_response_id": "resp_original",
+ "input": [
+ {"type": "reasoning", "summary": [], "encrypted_content": "gAAAAoriginal"},
+ {"role": "user", "content": "again"},
+ ],
+ }
+ assert request == before
+
+
+async def test_native_count_answers_openais_rejection_with_its_status_and_text(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ rejection: Final = json.dumps({"error": {"message": "Unknown parameter: 'max_output_tokens'."}})
+
+ result, _ = await _native_count(monkeypatch, _CALLER_BODY, _KEEP_ALL, httpx.Response(400, text=rejection))
+
+ assert result is not None
+ assert (result.error, result.status_code, result.error_message) == (True, 400, rejection)
diff --git a/tests/unit/llms/test_file_search_responses.py b/tests/unit/llms/test_file_search_responses.py
index 9d2a5dbaf59..b2cbcd4a6dd 100644
--- a/tests/unit/llms/test_file_search_responses.py
+++ b/tests/unit/llms/test_file_search_responses.py
@@ -573,11 +573,11 @@ class TestEmulatedFileSearchHandler:
def test_H1_file_search_replaced_with_function_tool(self):
from litellm.responses.file_search.emulated_handler import (
- _replace_file_search_tools,
+ replace_file_search_tools,
)
tools = [{"type": "file_search", "vector_store_ids": ["vs_abc", "vs_def"]}]
- new_tools, vs_ids = _replace_file_search_tools(tools)
+ new_tools, vs_ids = replace_file_search_tools(tools)
assert vs_ids == ["vs_abc", "vs_def"]
assert len(new_tools) == 1
@@ -590,14 +590,14 @@ class TestEmulatedFileSearchHandler:
def test_H2_non_file_search_tools_preserved(self):
from litellm.responses.file_search.emulated_handler import (
- _replace_file_search_tools,
+ replace_file_search_tools,
)
tools = [
{"type": "web_search"},
{"type": "file_search", "vector_store_ids": ["vs_abc"]},
]
- new_tools, vs_ids = _replace_file_search_tools(tools)
+ new_tools, vs_ids = replace_file_search_tools(tools)
assert len(new_tools) == 2 # web_search + generated function tool
assert new_tools[0]["type"] == "web_search"
@@ -605,22 +605,22 @@ class TestEmulatedFileSearchHandler:
def test_H3_no_file_search_tools_returns_unchanged(self):
from litellm.responses.file_search.emulated_handler import (
- _replace_file_search_tools,
+ replace_file_search_tools,
)
tools = [{"type": "web_search"}]
- new_tools, vs_ids = _replace_file_search_tools(tools)
+ new_tools, vs_ids = replace_file_search_tools(tools)
assert vs_ids == []
assert new_tools == [{"type": "web_search"}]
def test_H4_empty_vector_store_ids_no_function_tool(self):
from litellm.responses.file_search.emulated_handler import (
- _replace_file_search_tools,
+ replace_file_search_tools,
)
tools = [{"type": "file_search", "vector_store_ids": []}]
- new_tools, vs_ids = _replace_file_search_tools(tools)
+ new_tools, vs_ids = replace_file_search_tools(tools)
assert vs_ids == []
assert new_tools == [] # no function tool added without store IDs
diff --git a/tests/unit/llms/vertex_ai/test_vertex_ai_common_utils.py b/tests/unit/llms/vertex_ai/test_vertex_ai_common_utils.py
index 7d380205ca1..38737df7545 100644
--- a/tests/unit/llms/vertex_ai/test_vertex_ai_common_utils.py
+++ b/tests/unit/llms/vertex_ai/test_vertex_ai_common_utils.py
@@ -28,6 +28,7 @@ from litellm.llms.vertex_ai.common_utils import (
vertex_request_labels_from_litellm_params,
)
from litellm.llms.vertex_ai.count_tokens import handler as vertex_count_tokens_handler
+from litellm.llms.vertex_ai.vertex_ai_partner_models.anthropic.transformation import VertexAIAnthropicConfig
from litellm.types.utils import CountContextManagement, TokenCountMessagesFormat
@@ -64,7 +65,9 @@ async def test_vertex_gemini_rejects_non_text_system_blocks_before_request(
"google/gemma-4-26b-a4b-it-maas",
),
)
-async def test_vertex_partner_model_without_an_inference_matching_count_answers_400_naming_the_model(model: str) -> None:
+async def test_vertex_partner_model_without_an_inference_matching_count_answers_400_naming_the_model(
+ model: str,
+) -> None:
result: Final = await VertexAITokenCounter().count_tokens(
model_to_use=model,
messages=[{"role": "user", "content": "Count this"}],
@@ -488,7 +491,6 @@ def test_anyof_conversion_forwards_a_non_object_branch_for_the_provider_to_judge
assert schema == {"type": "object", "properties": {"example": {"anyOf": expected}}}
-
@pytest.mark.parametrize(
("field", "expected"),
[
@@ -534,6 +536,7 @@ def test_vertex_schema_folds_every_null_branch_into_nullable(field: JsonValue, e
assert schema["properties"]["value"] == expected
+
def test_anyof_with_excessive_nesting():
"""Test conversion with excessive nesting > max levels +1 deep."""
# generate a schema with excessive nesting
@@ -1700,6 +1703,148 @@ async def test_vertex_ai_token_counter_forwards_system_and_tools_to_partner_requ
assert without_optional_fields.total_tokens == 37
+_PARTNER_CHAT_TOOL_TURNS: Final[list[dict[str, object]]] = [
+ {"role": "user", "content": "Weather in SF?"},
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "get_weather", "arguments": "{}"}}],
+ },
+ {"role": "tool", "tool_call_id": "call_1", "content": "sunny"},
+]
+_PARTNER_RESPONSES_TOOL: Final[dict[str, object]] = {
+ "type": "function",
+ "name": "get_weather",
+ "parameters": {"type": "object", "properties": {}},
+}
+
+
+async def _partner_counted_bodies(
+ model: str, chat_params: dict[str, JsonValue] | None = None
+) -> tuple[dict[str, object], ...]:
+ from litellm.llms.vertex_ai.vertex_ai_partner_models.count_tokens import handler
+
+ class FakeResponse:
+ status_code = 200
+
+ def json(self) -> dict[str, int]:
+ return {"input_tokens": 37}
+
+ class FakeHttpClient:
+ posted_bodies: tuple[dict[str, object], ...] = ()
+
+ async def post(
+ self, url: str, headers: dict[str, str], json: dict[str, object], timeout: float
+ ) -> FakeResponse:
+ self.posted_bodies = (*self.posted_bodies, json)
+ return FakeResponse()
+
+ fake_http_client: Final = FakeHttpClient()
+ with (
+ patch.object(handler, "get_async_httpx_client", return_value=fake_http_client),
+ patch.object(
+ handler.VertexAIPartnerModelsTokenCounter,
+ "_ensure_access_token_async",
+ new=AsyncMock(return_value=("fake-token", "test-project")),
+ ),
+ ):
+ result: Final = await VertexAITokenCounter().count_tokens(
+ model_to_use=model,
+ messages=copy.deepcopy(_PARTNER_CHAT_TOOL_TURNS),
+ contents=None,
+ deployment={"litellm_params": {"vertex_project": "test-project", "vertex_location": "us-east5"}},
+ tools=[_PARTNER_RESPONSES_TOOL],
+ chat_params=chat_params or {},
+ )
+
+ assert result is not None
+ assert result.total_tokens == 37
+ return fake_http_client.posted_bodies
+
+
+async def test_vertex_claude_count_sends_chat_tool_use_in_the_shape_chat_inference_sends() -> None:
+ assert await _partner_counted_bodies("claude-opus-5-5") == (
+ {
+ "model": "claude-opus-5-5",
+ "messages": [
+ {"role": "user", "content": [{"type": "text", "text": "Weather in SF?"}]},
+ {
+ "role": "assistant",
+ "content": [{"type": "tool_use", "id": "call_1", "name": "get_weather", "input": {}}],
+ },
+ {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "call_1", "content": "sunny"}]},
+ ],
+ "tools": [
+ {
+ "name": "get_weather",
+ "input_schema": {"type": "object", "properties": {}},
+ "type": "custom",
+ "description": "",
+ }
+ ],
+ },
+ )
+
+
+async def test_vertex_claude_count_sends_the_structured_output_vertex_inference_sends() -> None:
+ model: Final = "claude-haiku-4-5"
+ chat_params: Final[dict[str, JsonValue]] = {
+ "response_format": {
+ "type": "json_schema",
+ "json_schema": {
+ "name": "answer",
+ "schema": {"type": "object", "properties": {"answer": {"type": "string"}}, "required": ["answer"]},
+ },
+ }
+ }
+ config: Final = VertexAIAnthropicConfig()
+ inference: Final = config.transform_request(
+ model=model,
+ messages=copy.deepcopy(_PARTNER_CHAT_TOOL_TURNS),
+ optional_params=config.map_openai_params(
+ {
+ **chat_params,
+ "tools": [
+ {
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "description": "",
+ "parameters": _PARTNER_RESPONSES_TOOL["parameters"],
+ },
+ }
+ ],
+ },
+ {},
+ model,
+ drop_params=False,
+ ),
+ litellm_params={},
+ headers={},
+ )
+
+ (body,) = await _partner_counted_bodies(model, chat_params)
+
+ assert (body["tools"], body.get("tool_choice"), body.get("output_config")) == (
+ inference["tools"],
+ inference.get("tool_choice"),
+ inference.get("output_config"),
+ )
+
+
+async def test_vertex_llama_count_sends_chat_tool_use_as_sent() -> None:
+ assert await _partner_counted_bodies("meta/llama-4-maverick-17b-128e-instruct-maas") == (
+ {
+ "model": "meta/llama-4-maverick-17b-128e-instruct-maas",
+ "messages": _PARTNER_CHAT_TOOL_TURNS,
+ "tools": [_PARTNER_RESPONSES_TOOL],
+ },
+ )
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize(
("provider_failure", "expected_status", "expected_message"),
diff --git a/tests/unit/proxy/response_api_endpoints/test_endpoints.py b/tests/unit/proxy/response_api_endpoints/test_endpoints.py
index e3ce513dbcb..32b77c3b564 100644
--- a/tests/unit/proxy/response_api_endpoints/test_endpoints.py
+++ b/tests/unit/proxy/response_api_endpoints/test_endpoints.py
@@ -4171,10 +4171,17 @@ class TestResponsesInputTokens:
path: str = "/v1/responses/input_tokens",
counter: AsyncMock | None = None,
llm_router: litellm.Router | None = None,
+ response_id_security: object | None = None,
+ managed_files: object | None = None,
) -> tuple[Response, AsyncMock]:
from litellm.proxy._types import UserAPIKeyAuth
from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
- from litellm.proxy.response_api_endpoints.endpoints import _proxy_llm_router, _proxy_token_counter
+ from litellm.proxy.response_api_endpoints.endpoints import (
+ _proxy_llm_router,
+ _proxy_managed_files_hook,
+ _proxy_response_id_security,
+ _proxy_token_counter,
+ )
from litellm.types.utils import TokenCountResponse
token_counter_mock = (
@@ -4192,6 +4199,10 @@ class TestResponsesInputTokens:
app.dependency_overrides[user_api_key_auth] = lambda: UserAPIKeyAuth(api_key="sk-test", request_route=path)
app.dependency_overrides[_proxy_token_counter] = lambda: token_counter_mock
app.dependency_overrides[_proxy_llm_router] = lambda: llm_router
+ if response_id_security is not None:
+ app.dependency_overrides[_proxy_response_id_security] = lambda: response_id_security
+ if managed_files is not None:
+ app.dependency_overrides[_proxy_managed_files_hook] = lambda: managed_files
try:
client = TestClient(app)
response = client.post(path, json=body, headers={"Authorization": "Bearer sk-9876"})
@@ -4200,6 +4211,8 @@ class TestResponsesInputTokens:
app.dependency_overrides.pop(user_api_key_auth, None)
app.dependency_overrides.pop(_proxy_token_counter, None)
app.dependency_overrides.pop(_proxy_llm_router, None)
+ app.dependency_overrides.pop(_proxy_response_id_security, None)
+ app.dependency_overrides.pop(_proxy_managed_files_hook, None)
def test_string_input_returns_openai_input_tokens_shape(self):
response, counter = self._post_input_tokens({"model": "gpt-4o", "input": "Hello, how are you?"})
@@ -4324,6 +4337,139 @@ class TestResponsesInputTokens:
assert response.status_code == 200, response.text
assert counter.await_args.kwargs["request"].tools == [{"type": "web_search"}]
+ assert counter.await_args.kwargs["responses_request"]["tools"] == [{"type": "web_search"}]
+
+ @pytest.mark.parametrize(
+ ("tools", "expected"),
+ [
+ ([5], {}),
+ (
+ [5, {"type": "web_search"}],
+ {"tools": [{"type": "web_search"}], "tool_choice": "required", "parallel_tool_calls": False},
+ ),
+ ],
+ )
+ def test_tool_choice_leaves_the_count_with_the_tools_drop_params_drops(
+ self, tools: list[object], expected: dict[str, object]
+ ) -> None:
+ response, counter = self._post_input_tokens(
+ {
+ "model": "gpt-4o",
+ "input": "hi",
+ "tools": tools,
+ "tool_choice": "required",
+ "parallel_tool_calls": False,
+ "drop_params": True,
+ }
+ )
+
+ assert response.status_code == 200, response.text
+ sent = counter.await_args.kwargs["responses_request"]
+ assert {name: sent[name] for name in ("tools", "tool_choice", "parallel_tool_calls") if name in sent} == expected
+
+ def test_previous_response_id_reaches_the_counter_authorized_next_to_the_id_the_client_held(self) -> None:
+ from litellm.types.utils import ADDRESSED_RESPONSE_ID_FIELD
+
+ class DecodingSecurity:
+ def authorize_response_id(self, response_id: str, user_api_key_dict: object) -> str:
+ return {"resp_client_form": "resp_raw"}[response_id]
+
+ response, counter = self._post_input_tokens(
+ {"model": "gpt-4o", "input": "hi", "previous_response_id": "resp_client_form"},
+ response_id_security=DecodingSecurity(),
+ )
+
+ assert response.status_code == 200, response.text
+ responses_request: Final = counter.await_args.kwargs["responses_request"]
+ assert (responses_request["previous_response_id"], responses_request[ADDRESSED_RESPONSE_ID_FIELD]) == (
+ "resp_raw",
+ "resp_client_form",
+ )
+
+ def test_managed_file_ids_reach_the_counter_with_the_mapping_inference_uses(self) -> None:
+ from litellm.integrations.custom_logger import CustomLogger
+
+ mapping: Final = {"litellm-managed-file": {"deployment-a": "file-on-a"}}
+
+ class ManagedFiles(CustomLogger):
+ async def async_pre_call_hook(self, user_api_key_dict, cache, data, call_type):
+ if call_type == "aresponses":
+ data["model_file_id_mapping"] = mapping
+ return None
+
+ response, counter = self._post_input_tokens(
+ {
+ "model": "gpt-4o",
+ "input": [{"role": "user", "content": [{"type": "input_file", "file_id": "litellm-managed-file"}]}],
+ },
+ managed_files=ManagedFiles(),
+ )
+
+ assert response.status_code == 200, response.text
+ assert counter.await_args.kwargs["responses_request"]["model_file_id_mapping"] == mapping
+
+ @pytest.mark.parametrize("caller_mapping", [5, "lots", [1], {"file-x": {"deployment-a": 7}}])
+ def test_a_caller_sent_model_file_id_mapping_does_not_break_the_count(
+ self, monkeypatch: pytest.MonkeyPatch, caller_mapping: object
+ ) -> None:
+ from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
+ from litellm.llms.openai.responses.count_tokens import handler as openai_count_tokens_http
+ from litellm.proxy.proxy_server import count_request_tokens
+
+ router: Final = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-files",
+ "litellm_params": {
+ "model": "openai/gpt-4o-mini",
+ "api_key": "test-key",
+ "api_base": "https://count.test/v1",
+ },
+ "model_info": {"id": "deployment-a"},
+ }
+ ]
+ )
+ monkeypatch.setattr(litellm.proxy.proxy_server, "llm_router", router)
+ sent: Final[list[object]] = [] # mutable-ok: collects what the mock peer receives
+
+ def count_peer(request: httpx.Request) -> httpx.Response:
+ sent.append(json.loads(request.content))
+ return httpx.Response(200, json={"object": "response.input_tokens", "input_tokens": 7}, request=request)
+
+ with patch.object(
+ openai_count_tokens_http,
+ "get_async_httpx_client",
+ return_value=AsyncHTTPHandler(transport=httpx.MockTransport(count_peer)),
+ ):
+ response, _ = self._post_input_tokens(
+ {"model": "gpt-files", "input": "hi", "model_file_id_mapping": caller_mapping},
+ counter=AsyncMock(side_effect=count_request_tokens),
+ llm_router=router,
+ )
+
+ assert (response.status_code, response.json().get("input_tokens")) == (200, 7), response.text
+ assert sent == [{"model": "gpt-4o-mini", "input": "hi"}]
+
+ def test_a_managed_file_the_key_cannot_read_answers_403_without_a_count(self) -> None:
+ from litellm.integrations.custom_logger import CustomLogger
+
+ denied: Final = "User u1 does not have access to the file litellm-managed-file"
+
+ class ManagedFiles(CustomLogger):
+ async def async_pre_call_hook(self, user_api_key_dict, cache, data, call_type):
+ raise HTTPException(status_code=403, detail=denied)
+
+ response, counter = self._post_input_tokens(
+ {
+ "model": "gpt-4o",
+ "input": [{"role": "user", "content": [{"type": "input_file", "file_id": "litellm-managed-file"}]}],
+ },
+ managed_files=ManagedFiles(),
+ )
+
+ assert response.status_code == 403, response.text
+ assert response.json()["error"]["message"] == denied
+ counter.assert_not_awaited()
def test_malformed_tools_follow_the_counted_deployment_even_when_fallbacks_are_configured(self) -> None:
router: Final = litellm.Router(
@@ -4345,6 +4491,7 @@ class TestResponsesInputTokens:
assert response.status_code == 200, response.text
assert counter.await_args.kwargs["request"].tools is None
+ assert "tools" not in counter.await_args.kwargs["responses_request"]
def test_malformed_tools_for_a_model_outside_the_router_get_a_clean_400(self) -> None:
router: Final = litellm.Router(
diff --git a/tests/unit/proxy/test_proxy_token_counter.py b/tests/unit/proxy/test_proxy_token_counter.py
index 714d8bb77d7..46e88614bb6 100644
--- a/tests/unit/proxy/test_proxy_token_counter.py
+++ b/tests/unit/proxy/test_proxy_token_counter.py
@@ -57,8 +57,10 @@ from litellm.llms.bedrock.count_tokens.kimi_k3 import (
)
from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
from litellm.llms.gemini.count_tokens import handler as gemini_count_tokens_handler
+from litellm.llms.openai.responses.count_tokens import handler as openai_count_tokens_http
from litellm.llms.vertex_ai.vertex_ai_partner_models.count_tokens.handler import VertexAIPartnerModelsTokenCounter
from litellm.proxy._types import ProxyException, TokenCountRequest, UserAPIKeyAuth
+from litellm.responses.litellm_completion_transformation.session_handler import ResponsesSessionHandler
from litellm.proxy.anthropic_endpoints.endpoints import (
count_tokens as anthropic_count_tokens,
)
@@ -77,9 +79,16 @@ from litellm.proxy.proxy_server import (
count_request_tokens,
token_counter,
)
+from litellm.responses.utils import ResponsesAPIRequestUtils
from litellm.rust_bridge.fork_guard import ForkedAfterNativeRuntimeStarted
from litellm.types.secret_managers.main import KeyManagementSettings, KeyManagementSystem
-from litellm.types.utils import SelectTokenizerResponse, TokenCountMessagesFormat, TokenCountResponse
+from litellm.types.utils import (
+ ADDRESSED_RESPONSE_ID_FIELD,
+ SelectTokenizerResponse,
+ SpecialEnums,
+ TokenCountMessagesFormat,
+ TokenCountResponse,
+)
def _hugging_face_offline() -> NoReturn:
@@ -270,6 +279,50 @@ async def test_token_counter_reads_an_oidc_api_key_only_when_it_calls_the_provid
assert str(tmp_path) not in excinfo.value.message
+async def test_native_openai_responses_count_sends_the_token_an_oidc_api_key_points_to(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ monkeypatch.setenv("LITELLM_OIDC_ALLOWED_CREDENTIAL_DIRS", str(tmp_path))
+ token_file: Final = tmp_path / "token"
+ token_file.write_text("sa-token-from-file")
+ monkeypatch.setattr(
+ litellm.proxy.proxy_server,
+ "llm_router",
+ Router(
+ model_list=[
+ {
+ "model_name": "gpt-oidc",
+ "litellm_params": {
+ "model": "openai/gpt-4o-mini",
+ "api_key": f"oidc/file/{token_file}",
+ "api_base": "https://count.test/v1",
+ },
+ }
+ ]
+ ),
+ )
+ authorizations: Final[list[str | None]] = [] # mutable-ok: collects what the mock peer receives
+
+ def count_peer(request: httpx.Request) -> httpx.Response:
+ authorizations.append(request.headers.get("authorization"))
+ return httpx.Response(200, json={"object": "response.input_tokens", "input_tokens": 9}, request=request)
+
+ with patch.object(
+ openai_count_tokens_http,
+ "get_async_httpx_client",
+ return_value=AsyncHTTPHandler(transport=httpx.MockTransport(count_peer)),
+ ):
+ result: Final = await count_request_tokens(
+ request=TokenCountRequest(model="gpt-oidc", messages=[{"role": "user", "content": "hello"}]),
+ call_endpoint=True,
+ responses_request={"model": "gpt-oidc", "input": "hello"},
+ )
+
+ assert (result.error, result.total_tokens) == (False, 9)
+ assert authorizations == ["Bearer sa-token-from-file"]
+
+
@pytest.mark.asyncio
async def test_anthropic_messages_count_tokens_endpoint():
"""
@@ -1567,6 +1620,7 @@ class _ScriptedCounter(BaseTokenCounter):
messages_format: TokenCountMessagesFormat = "openai",
output_format: JsonValue = None,
context_management: object = None,
+ chat_params: object = None,
) -> TokenCountResponse | None:
self.calls.append((model_to_use, messages, tools, system))
self.regions.append(None if deployment is None else deployment["litellm_params"].get("aws_region_name"))
@@ -3505,3 +3559,325 @@ async def test_call_endpoint_prompt_keeps_the_local_count_on_a_counter_that_need
local.total_tokens,
local.tokenizer_type,
)
+
+
+_PINNED_COUNTS: Final = MappingProxyType({"deployment-a.test": 11, "deployment-b.test": 22})
+
+
+def _pinned_count_peer(request: httpx.Request) -> httpx.Response:
+ if json.loads(request.content).get("previous_response_id") != "resp_original":
+ return httpx.Response(400, json={"error": {"message": "previous_response_id was not decoded"}}, request=request)
+ return httpx.Response(200, json={"input_tokens": _PINNED_COUNTS[request.url.host]}, request=request)
+
+
[email protected]("pinned", ["deployment-a", "deployment-b"])
+async def test_responses_count_goes_to_the_deployment_that_served_the_previous_response(
+ monkeypatch: pytest.MonkeyPatch, pinned: str
+) -> None:
+ router: Final = Router(
+ model_list=[
+ {
+ "model_name": "gpt-group",
+ "litellm_params": {
+ "model": "openai/gpt-4o-mini",
+ "api_key": "test-key",
+ "api_base": f"https://{identity}.test/v1",
+ },
+ "model_info": {"id": identity},
+ }
+ for identity in ("deployment-a", "deployment-b")
+ ],
+ optional_pre_call_checks=["responses_api_deployment_check"],
+ )
+ monkeypatch.setattr(litellm.proxy.proxy_server, "llm_router", router)
+ client: Final = AsyncHTTPHandler(transport=httpx.MockTransport(_pinned_count_peer))
+ previous_response_id: Final = ResponsesAPIRequestUtils._build_responses_api_response_id(
+ "openai", pinned, "resp_original"
+ )
+
+ with patch.object(openai_count_tokens_http, "get_async_httpx_client", return_value=client):
+ counts: Final = [
+ (
+ await count_request_tokens(
+ request=TokenCountRequest(model="gpt-group", messages=[{"role": "user", "content": "again"}]),
+ call_endpoint=True,
+ responses_request={
+ "model": "gpt-group",
+ "input": "again",
+ "previous_response_id": previous_response_id,
+ },
+ )
+ ).total_tokens
+ for _ in range(8)
+ ]
+
+ assert counts == [_PINNED_COUNTS[f"{pinned}.test"]] * 8
+
+
+def _managed_file_id(provider_file_id: str, model_id: str) -> str:
+ unified: Final = SpecialEnums.LITELLM_MANAGED_FILE_COMPLETE_STR.value.format(
+ "application/pdf", "3f0c9a", "gpt-files", provider_file_id, model_id
+ )
+ return base64.urlsafe_b64encode(unified.encode()).decode().rstrip("=")
+
+
[email protected](("with_mapping", "expected_file_id"), [(False, "file-uploaded"), (True, "file-on-a")])
+async def test_responses_count_sends_openai_the_provider_file_id_inference_sends(
+ monkeypatch: pytest.MonkeyPatch, with_mapping: bool, expected_file_id: str
+) -> None:
+ router: Final = Router(
+ model_list=[
+ {
+ "model_name": "gpt-files",
+ "litellm_params": {"model": "openai/gpt-4o-mini", "api_key": "test-key", "api_base": "https://count.test/v1"},
+ "model_info": {"id": "deployment-a"},
+ }
+ ]
+ )
+ monkeypatch.setattr(litellm.proxy.proxy_server, "llm_router", router)
+ managed_id: Final = _managed_file_id("file-uploaded", "deployment-a")
+ bodies: Final[list[dict[str, JsonValue]]] = [] # mutable-ok: collects what the mock peer receives
+
+ def count_peer(request: httpx.Request) -> httpx.Response:
+ bodies.append(json.loads(request.content))
+ return httpx.Response(200, json={"object": "response.input_tokens", "input_tokens": 49}, request=request)
+
+ with patch.object(
+ openai_count_tokens_http,
+ "get_async_httpx_client",
+ return_value=AsyncHTTPHandler(transport=httpx.MockTransport(count_peer)),
+ ):
+ result: Final = await count_request_tokens(
+ request=TokenCountRequest(model="gpt-files", messages=[{"role": "user", "content": "Summarize"}]),
+ call_endpoint=True,
+ responses_request={
+ "model": "gpt-files",
+ "input": [{"role": "user", "content": [{"type": "input_file", "file_id": managed_id}]}],
+ **({"model_file_id_mapping": {managed_id: {"deployment-a": "file-on-a"}}} if with_mapping else {}),
+ },
+ )
+
+ assert (result.error, result.total_tokens) == (False, 49)
+ (body,) = bodies
+ assert body["input"] == [{"role": "user", "content": [{"type": "input_file", "file_id": expected_file_id}]}]
+ assert "model_file_id_mapping" not in body
+
+
+_ANSWER_SCHEMA: Final[dict[str, JsonValue]] = {
+ "type": "object",
+ "properties": {"answer": {"type": "string"}},
+ "required": ["answer"],
+ "additionalProperties": False,
+}
+
+
+async def test_responses_count_on_claude_counts_the_chat_request_responses_inference_sends(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ router: Final = Router(
+ model_list=[
+ {
+ "model_name": "claude-counted",
+ "litellm_params": {
+ "model": "anthropic/claude-opus-5-5",
+ "api_key": "test-key",
+ "api_base": "https://count-tokens.test",
+ },
+ }
+ ]
+ )
+ monkeypatch.setattr(litellm.proxy.proxy_server, "llm_router", router)
+ bodies: Final[list[dict[str, JsonValue]]] = [] # mutable-ok: collects what the mock peer receives
+
+ def count_peer(request: httpx.Request) -> httpx.Response:
+ bodies.append(json.loads(request.content))
+ return httpx.Response(200, json={"input_tokens": 77}, request=request)
+
+ responses_tools: Final[list[dict[str, JsonValue]]] = [
+ {"type": "function", "name": "get_weather", "parameters": {"type": "object", "properties": {}}},
+ {"type": "web_search"},
+ {"type": "file_search", "vector_store_ids": ["vs_docs"]},
+ ]
+ with patch.object(
+ anthropic_count_tokens_handler,
+ "get_async_httpx_client",
+ return_value=AsyncHTTPHandler(transport=httpx.MockTransport(count_peer)),
+ ):
+ result: Final = await count_request_tokens(
+ request=TokenCountRequest(
+ model="claude-counted", messages=[{"role": "user", "content": "Weather?"}], tools=responses_tools
+ ),
+ call_endpoint=True,
+ responses_request={
+ "model": "claude-counted",
+ "input": "Weather?",
+ "tools": responses_tools,
+ "tool_choice": "auto",
+ "text": {"format": {"type": "json_schema", "name": "answer", "schema": _ANSWER_SCHEMA}},
+ "reasoning": {"effort": "low"},
+ },
+ )
+
+ assert (result.error, result.total_tokens) == (False, 77)
+ (body,) = bodies
+ tools: Final = body["tools"]
+ assert isinstance(tools, list)
+ tool_names: Final = [tool["name"] for tool in tools if isinstance(tool, dict)]
+ assert sorted(tool_names) == ["get_weather", "litellm_file_search", "web_search"]
+ assert any(isinstance(tool, dict) and str(tool.get("type")).startswith("web_search") for tool in tools)
+ assert body["tool_choice"] == {"type": "auto"}
+ output_config: Final = body["output_config"]
+ assert isinstance(output_config, dict)
+ assert output_config["format"] == {"type": "json_schema", "schema": _ANSWER_SCHEMA}
+ assert "thinking" in body
+
+
+_WEATHER_TOOL: Final[dict[str, JsonValue]] = {
+ "type": "function",
+ "name": "get_weather",
+ "parameters": {"type": "object", "properties": {}},
+}
+
+
+async def _claude_count(
+ monkeypatch: pytest.MonkeyPatch,
+ deployment_params: Mapping[str, JsonValue],
+ responses_request: Mapping[str, object],
+) -> tuple[TokenCountResponse, list[dict[str, JsonValue]]]:
+ router: Final = Router(
+ model_list=[
+ {
+ "model_name": "claude-counted",
+ "litellm_params": {
+ "model": "anthropic/claude-zeta-9",
+ "api_key": "test-key",
+ "api_base": "https://count-tokens.test",
+ **deployment_params,
+ },
+ }
+ ]
+ )
+ monkeypatch.setattr(litellm.proxy.proxy_server, "llm_router", router)
+ bodies: Final[list[dict[str, JsonValue]]] = [] # mutable-ok: collects what the mock peer receives
+
+ def count_peer(request: httpx.Request) -> httpx.Response:
+ bodies.append(json.loads(request.content))
+ return httpx.Response(200, json={"input_tokens": 77}, request=request)
+
+ with patch.object(
+ anthropic_count_tokens_handler,
+ "get_async_httpx_client",
+ return_value=AsyncHTTPHandler(transport=httpx.MockTransport(count_peer)),
+ ):
+ result: Final = await count_request_tokens(
+ request=TokenCountRequest(model="claude-counted", messages=[{"role": "user", "content": "Weather?"}]),
+ call_endpoint=True,
+ responses_request={"model": "claude-counted", **responses_request},
+ )
+ return result, bodies
+
+
+ ("deployment_params", "request_params"),
+ [({"drop_params": True}, {}), ({}, {"drop_params": True})],
+ ids=["deployment", "request"],
+)
+async def test_responses_count_on_claude_downgrades_forced_tool_choice_under_drop_params(
+ monkeypatch: pytest.MonkeyPatch,
+ deployment_params: Mapping[str, JsonValue],
+ request_params: Mapping[str, JsonValue],
+) -> None:
+ monkeypatch.setitem(litellm.model_cost, "claude-zeta-9", {"supports_forced_tool_use": False})
+
+ result, bodies = await _claude_count(
+ monkeypatch,
+ deployment_params,
+ {"input": "Weather?", "tools": [_WEATHER_TOOL], "tool_choice": "required", **request_params},
+ )
+
+ assert (result.error, result.total_tokens) == (False, 77)
+ (body,) = bodies
+ assert body["tool_choice"] == {"type": "auto"}
+
+
+async def test_responses_count_on_claude_rejects_forced_tool_choice_without_drop_params(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setitem(litellm.model_cost, "claude-zeta-9", {"supports_forced_tool_use": False})
+
+ with pytest.raises(ProxyException) as rejected:
+ await _claude_count(
+ monkeypatch, {}, {"input": "Weather?", "tools": [_WEATHER_TOOL], "tool_choice": "required"}
+ )
+
+ assert (rejected.value.code, "forced tool use" in rejected.value.message) == ("400", True)
+
+
+def _texts(message: JsonValue) -> list[str]:
+ assert isinstance(message, dict)
+ content: Final = message["content"]
+ if isinstance(content, str):
+ return [content]
+ assert isinstance(content, list)
+ return [str(block["text"]) for block in content if isinstance(block, dict) and "text" in block]
+
+
+async def test_responses_count_on_claude_counts_the_turns_previous_response_id_replays(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ stored_turn: Final = {
+ "request_id": "chatcmpl-stored",
+ "call_type": "aresponses",
+ "session_id": "session-1",
+ "proxy_server_request": {"input": "Who won in 1998?", "model": "claude-counted"},
+ "response": {
+ "id": "chatcmpl-stored",
+ "object": "chat.completion",
+ "choices": [
+ {
+ "index": 0,
+ "message": {
+ "role": "assistant",
+ "content": "The Bulls.",
+ "reasoning_content": "Chicago beat Utah in six games.",
+ },
+ "finish_reason": "stop",
+ }
+ ],
+ },
+ "status": "success",
+ }
+
+ with patch.object(
+ ResponsesSessionHandler,
+ "get_all_spend_logs_for_previous_response_id",
+ new_callable=AsyncMock,
+ return_value=[stored_turn],
+ ) as spend_logs:
+ result, bodies = await _claude_count(
+ monkeypatch,
+ {},
+ {
+ "input": "And in 1999?",
+ "previous_response_id": "chatcmpl-stored",
+ ADDRESSED_RESPONSE_ID_FIELD: "resp_client_form",
+ },
+ )
+
+ assert (result.error, result.total_tokens) == (False, 77)
+ (body,) = bodies
+ messages: Final = body["messages"]
+ assert isinstance(messages, list)
+ assert list(itertools.chain.from_iterable(map(_texts, messages))) == [
+ "Who won in 1998?",
+ "The Bulls.",
+ "And in 1999?",
+ ]
+ assert [sorted(message) for message in messages if isinstance(message, dict)] == [["content", "role"]] * 3
+ spend_logs.assert_awaited_once_with("chatcmpl-stored", ("chatcmpl-stored", "resp_client_form"))
diff --git a/tests/unit/responses/litellm_completion_transformation/test_count_request.py b/tests/unit/responses/litellm_completion_transformation/test_count_request.py
new file mode 100644
index 00000000000..464bdb1a367
--- /dev/null
+++ b/tests/unit/responses/litellm_completion_transformation/test_count_request.py
@@ -0,0 +1,127 @@
+import json
+from typing import Final
+
+import pytest
+from pydantic import JsonValue
+
+from litellm.litellm_core_utils.tool_fields import DropPolicy
+from litellm.responses.litellm_completion_transformation.count_request import (
+ ChatCountBridgeError,
+ ChatCountRequest,
+ chat_count_request,
+)
+
+_MARK: Final[dict[str, JsonValue]] = {"type": "ephemeral"}
+_MARKED_RESPONSES_REQUEST: Final[dict[str, JsonValue]] = {
+ "model": "claude-opus-5-5",
+ "instructions": "Be terse.",
+ "input": [
+ {"type": "message", "role": "user", "content": "Weather in SF?", "cache_control": _MARK},
+ {
+ "type": "message",
+ "role": "user",
+ "content": [{"type": "input_text", "text": "And in LA?", "cache_control": _MARK}],
+ },
+ {
+ "type": "function_call",
+ "call_id": "call_1",
+ "name": "get_weather",
+ "arguments": '{"city": "SF"}',
+ "cache_control": _MARK,
+ },
+ {"type": "function_call_output", "call_id": "call_1", "output": "sunny", "cache_control": _MARK},
+ ],
+ "tools": [
+ {
+ "type": "function",
+ "name": "get_weather",
+ "parameters": {"type": "object", "properties": {"city": {"type": "string"}}},
+ "cache_control": _MARK,
+ }
+ ],
+}
+
+
[email protected]("drop_params", (False, True))
+async def test_claude_count_request_leaves_out_every_cache_control_mark(drop_params: bool) -> None:
+ request: Final = await chat_count_request(
+ model="claude-opus-5-5",
+ custom_llm_provider="anthropic",
+ api_base=None,
+ responses_request=_MARKED_RESPONSES_REQUEST,
+ policy=DropPolicy(drop_params=drop_params, additional_drop_params=frozenset()),
+ )
+
+ assert isinstance(request, ChatCountRequest)
+ counted: Final = json.dumps({"messages": request.messages, "tools": request.tools}, default=str)
+ assert "cache_control" not in counted
+ for kept in ("Weather in SF?", "And in LA?", "call_1", "sunny", "get_weather"):
+ assert kept in counted
+
+
+_WEATHER_TOOL: Final[dict[str, JsonValue]] = {
+ "type": "function",
+ "name": "get_weather",
+ "parameters": {"type": "object", "properties": {"city": {"type": "string"}}},
+}
+_QUESTION: Final[dict[str, JsonValue]] = {"role": "user", "content": "Weather in SF?"}
+
+
+async def _claude_count(
+ responses_request: dict[str, JsonValue], policy: DropPolicy
+) -> ChatCountRequest | ChatCountBridgeError | None:
+ return await chat_count_request(
+ model="claude-opus-5-5",
+ custom_llm_provider="anthropic",
+ api_base=None,
+ responses_request={"model": "claude-opus-5-5", **responses_request},
+ policy=policy,
+ )
+
+
+async def test_claude_count_request_counts_additional_tools_input_items_as_tools_like_inference() -> None:
+ policy: Final = DropPolicy(drop_params=False, additional_drop_params=frozenset())
+
+ hoisted: Final = await _claude_count(
+ {"input": [{"type": "additional_tools", "tools": [_WEATHER_TOOL]}, _QUESTION]}, policy
+ )
+
+ assert isinstance(hoisted, ChatCountRequest)
+ assert hoisted.tools is not None
+ assert hoisted == await _claude_count({"input": [_QUESTION], "tools": [_WEATHER_TOOL]}, policy)
+
+
+async def test_claude_count_request_drops_a_malformed_tool_flag_under_drop_params_like_inference() -> None:
+ policy: Final = DropPolicy(drop_params=True, additional_drop_params=frozenset())
+
+ flagged: Final = await _claude_count(
+ {"input": [_QUESTION], "tools": [{**_WEATHER_TOOL, "defer_loading": "yes"}]}, policy
+ )
+
+ assert isinstance(flagged, ChatCountRequest)
+ assert flagged == await _claude_count({"input": [_QUESTION], "tools": [_WEATHER_TOOL]}, policy)
+
+
+async def test_claude_count_request_rejects_a_malformed_tool_flag_without_drop_params() -> None:
+ flagged: Final = await _claude_count(
+ {"input": [_QUESTION], "tools": [{**_WEATHER_TOOL, "defer_loading": "yes"}]},
+ DropPolicy(drop_params=False, additional_drop_params=frozenset()),
+ )
+
+ assert isinstance(flagged, ChatCountBridgeError)
+ assert "defer_loading" in flagged.message
+
+
+async def test_claude_count_request_leaves_out_tools_the_deployment_drops() -> None:
+ policy: Final = DropPolicy(drop_params=False, additional_drop_params=frozenset({"tools"}))
+
+ dropped: Final = await _claude_count({"input": [_QUESTION], "tools": [_WEATHER_TOOL]}, policy)
+
+ assert isinstance(dropped, ChatCountRequest)
+ assert dropped.tools is None
+ assert dropped == await _claude_count({"input": [_QUESTION]}, policy)
diff --git a/tests/unit/test_count_tokens_public_api.py b/tests/unit/test_count_tokens_public_api.py
index e33bc1e5907..4eb8bea3427 100644
--- a/tests/unit/test_count_tokens_public_api.py
+++ b/tests/unit/test_count_tokens_public_api.py
@@ -3,9 +3,13 @@ Tests for litellm.acount_tokens() public API.
"""
import asyncio
+import json
import os
from unittest.mock import AsyncMock, patch
+import httpx
+import pytest
+import respx
import litellm
from litellm.types.utils import TokenCountResponse
@@ -157,3 +161,45 @@ def test_acount_tokens_no_api_key_falls_back(monkeypatch):
assert result.tokenizer_type == "local_tokenizer"
+
+
+def httpx_transport_clients(monkeypatch):
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ for name in ("ANTHROPIC_API_BASE", "ANTHROPIC_BASE_URL"):
+ monkeypatch.delenv(name, raising=False)
+ litellm.in_memory_llm_clients_cache.flush_cache()
+ yield
+ litellm.in_memory_llm_clients_cache.flush_cache()
+
+
+def test_acount_tokens_sends_chat_tool_use_to_anthropic_in_the_shape_claude_inference_sends(httpx_transport_clients):
+ schema = {"type": "object", "properties": {"city": {"type": "string"}}}
+ with respx.mock(assert_all_called=True) as router:
+ route = router.post("https://api.anthropic.com/v1/messages/count_tokens").mock(
+ return_value=httpx.Response(200, json={"input_tokens": 52})
+ )
+ result = asyncio.run(
+ litellm.acount_tokens(
+ model="anthropic/claude-opus-5-5",
+ messages=[
+ {"role": "user", "content": "Weather in SF?"},
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {"id": "call_1", "type": "function", "function": {"name": "get_weather", "arguments": "{}"}}
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_1", "content": "sunny"},
+ ],
+ tools=[{"type": "function", "function": {"name": "get_weather", "parameters": schema}}],
+ api_key="sk-ant-test-key",
+ )
+ )
+
+ assert (result.error, result.total_tokens) == (False, 52)
+ sent = json.loads(route.calls.last.request.content)
+ assert sent["tools"] == [{"name": "get_weather", "input_schema": schema, "type": "custom"}]
+ assert [message["role"] for message in sent["messages"]] == ["user", "assistant", "user"]
+ assert sent["messages"][2]["content"] == [{"type": "tool_result", "tool_use_id": "call_1", "content": "sunny"}]