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(count_tokens): return a 400 naming Anthropic blocks the OpenAI and Gemini count can't convert (#46772)

Mateo Wang79ca820933a3
diff --git a/litellm/llms/anthropic/pass_through/convertible_blocks.py b/litellm/llms/anthropic/pass_through/convertible_blocks.py
new file mode 100644
index 00000000000..543a6efd4c4
--- /dev/null
+++ b/litellm/llms/anthropic/pass_through/convertible_blocks.py
@@ -0,0 +1,106 @@
+from collections.abc import Iterator, Mapping, Sequence
+from itertools import chain
+from types import MappingProxyType
+from typing import Final
+
+from pydantic import JsonValue, TypeAdapter, ValidationError
+from typing_extensions import assert_never
+
+from litellm.llms.anthropic.pass_through.messages.utils import normalize_native_messages
+from litellm.types.utils import TokenCountMessagesFormat
+
+_CONVERTIBLE_BLOCK_TYPES: Final = MappingProxyType(
+ {
+ "user": frozenset({"text", "image", "document", "tool_result"}),
+ "assistant": frozenset({"text", "tool_use", "thinking", "redacted_thinking"}),
+ }
+)
+_SOURCED_BLOCK_TYPES: Final = frozenset({"image", "document"})
+_TOOL_RESULT_BLOCK_TYPES: Final = frozenset({"text", "image", "document"})
+
+
+_JSON_MESSAGES: Final = TypeAdapter(tuple[Mapping[str, JsonValue], ...])
+
+
+def _json_messages(messages: Sequence[Mapping[str, object]]) -> tuple[Mapping[str, JsonValue], ...]:
+ try:
+ return _JSON_MESSAGES.validate_python(messages)
+ except ValidationError:
+ return ()
+
+
+def _source_label(block_type: str, source: JsonValue) -> str | None:
+ if not isinstance(source, dict):
+ return f"{block_type} without a source"
+ match source.get("type"):
+ case "base64" if source.get("data"):
+ return None
+ case "url" if source.get("url"):
+ return None
+ case "base64" | "url" as source_type:
+ return f"{block_type} with an empty {source_type} source"
+ case str() as source_type:
+ return f"{block_type} with a {source_type} source"
+ case _:
+ return f"{block_type} with an untyped source"
+
+
+def _block_label(block: JsonValue, convertible: frozenset[str]) -> str | None:
+ if not isinstance(block, dict):
+ return None
+ block_type: Final = block.get("type")
+ if not isinstance(block_type, str):
+ return "a block without a type"
+ if block_type not in convertible:
+ return block_type
+ return _source_label(block_type, block.get("source")) if block_type in _SOURCED_BLOCK_TYPES else None
+
+
+def _tool_result_labels(block: JsonValue) -> Iterator[str]:
+ if not isinstance(block, dict) or block.get("type") != "tool_result":
+ return iter(())
+ inner: Final = block.get("content")
+ if not isinstance(inner, list):
+ return iter(())
+ return (
+ f"{label} inside a tool_result"
+ for item in inner
+ if (label := _block_label(item, _TOOL_RESULT_BLOCK_TYPES)) is not None
+ )
+
+
+def _content_labels(block: JsonValue, convertible: frozenset[str]) -> Iterator[str]:
+ label: Final = _block_label(block, convertible)
+ return chain(() if label is None else (label,), _tool_result_labels(block))
+
+
+def _message_labels(message: Mapping[str, JsonValue]) -> Iterator[str]:
+ role: Final = message.get("role")
+ convertible: Final = _CONVERTIBLE_BLOCK_TYPES.get(role) if isinstance(role, str) else None
+ content: Final = message.get("content")
+ if convertible is None or not isinstance(content, list):
+ return iter(())
+ return chain.from_iterable(_content_labels(block, convertible) for block in content)
+
+
+def unconvertible_anthropic_blocks(messages: Sequence[Mapping[str, object]]) -> tuple[str, ...]:
+ normalized: Final = _json_messages(normalize_native_messages(messages))
+ return tuple(sorted(set(chain.from_iterable(_message_labels(message) for message in normalized))))
+
+
+def unconvertible_blocks_error(
+ messages: Sequence[Mapping[str, object]] | None, messages_format: TokenCountMessagesFormat
+) -> str | None:
+ match messages_format:
+ case "openai":
+ return None
+ case "anthropic":
+ labels: Final = unconvertible_anthropic_blocks(messages or ())
+ return (
+ "count_tokens can't convert these content blocks for this model, so the count would leave them out: "
+ + ", ".join(labels)
+ if labels
+ else None
+ )
+ case _:
+ assert_never(messages_format)
diff --git a/litellm/llms/gemini/common_utils.py b/litellm/llms/gemini/common_utils.py
index bac5824b981..3d04954dd41 100644
--- a/litellm/llms/gemini/common_utils.py
+++ b/litellm/llms/gemini/common_utils.py
@@ -507,6 +507,7 @@ class GoogleAIStudioTokenCounter(BaseTokenCounter):
gemini_count_contents,
inference_request_view,
provider_error_response,
+ unconvertible_messages_error,
vertex_gemini_count_context,
)
@@ -514,6 +515,9 @@ class GoogleAIStudioTokenCounter(BaseTokenCounter):
count_context: Final = vertex_gemini_count_context(system=request_view.system, tools=tools)
if isinstance(count_context, VertexGeminiCountContextError):
return count_context_error_response(count_context, request_model, model_to_use)
+ blocks_error: Final = unconvertible_messages_error(request_view.messages, messages_format)
+ if blocks_error is not None:
+ return count_context_error_response(blocks_error, request_model, model_to_use)
deployment = deployment or {}
count_tokens_params_request: Final = copy.deepcopy(deployment.get("litellm_params", {}))
diff --git a/litellm/llms/openai/responses/count_tokens/token_counter.py b/litellm/llms/openai/responses/count_tokens/token_counter.py
index b97e1329675..43b3ae9f6f1 100644
--- a/litellm/llms/openai/responses/count_tokens/token_counter.py
+++ b/litellm/llms/openai/responses/count_tokens/token_counter.py
@@ -10,6 +10,7 @@ from pydantic import JsonValue
from typing_extensions import assert_never
from litellm._logging import verbose_logger
+from litellm.llms.anthropic.pass_through.convertible_blocks import unconvertible_blocks_error
from litellm.llms.anthropic.pass_through.responses_adapters.transformation import (
LiteLLMAnthropicToResponsesAPIAdapter,
)
@@ -91,14 +92,15 @@ class OpenAITokenCounter(BaseTokenCounter):
if messages_format == "anthropic"
else None
)
- if malformed_error is not None:
+ request_error: Final = malformed_error or unconvertible_blocks_error(messages, messages_format)
+ if request_error is not None:
return TokenCountResponse(
total_tokens=0,
request_model=request_model,
model_used=model_to_use,
tokenizer_type="openai_api",
error=True,
- error_message=malformed_error,
+ error_message=request_error,
status_code=400,
)
diff --git a/litellm/llms/vertex_ai/common_utils.py b/litellm/llms/vertex_ai/common_utils.py
index 4c0026783f7..98bc679a78e 100644
--- a/litellm/llms/vertex_ai/common_utils.py
+++ b/litellm/llms/vertex_ai/common_utils.py
@@ -1362,6 +1362,7 @@ class VertexAITokenCounter(BaseTokenCounter):
gemini_count_contents,
inference_request_view,
provider_error_response,
+ unconvertible_messages_error,
vertex_gemini_count_context,
)
from litellm.llms.vertex_ai.count_tokens.handler import VertexAITokenCounter
@@ -1370,6 +1371,9 @@ class VertexAITokenCounter(BaseTokenCounter):
count_context: Final = vertex_gemini_count_context(system=request_view.system, tools=tools)
if isinstance(count_context, VertexGeminiCountContextError):
return count_context_error_response(count_context, request_model, model_to_use)
+ blocks_error: Final = unconvertible_messages_error(request_view.messages, messages_format)
+ if blocks_error is not None:
+ return count_context_error_response(blocks_error, request_model, model_to_use)
resolved_contents: Final = (
contents
diff --git a/litellm/llms/vertex_ai/count_tokens/context.py b/litellm/llms/vertex_ai/count_tokens/context.py
index 3f9289c8244..e094f4c5c0c 100644
--- a/litellm/llms/vertex_ai/count_tokens/context.py
+++ b/litellm/llms/vertex_ai/count_tokens/context.py
@@ -138,6 +138,15 @@ def vertex_gemini_count_context(
)
+def unconvertible_messages_error(
+ messages: Sequence[Mapping[str, object]] | None, messages_format: TokenCountMessagesFormat
+) -> VertexGeminiCountContextError | None:
+ from litellm.llms.anthropic.pass_through.convertible_blocks import unconvertible_blocks_error
+
+ error_message: Final = unconvertible_blocks_error(messages, messages_format)
+ return None if error_message is None else VertexGeminiCountContextError(error_message=error_message)
+
+
def count_context_error_response(
error: VertexGeminiCountContextError, request_model: str, model_used: str
) -> TokenCountResponse:
diff --git a/litellm/proxy/anthropic_endpoints/endpoints.py b/litellm/proxy/anthropic_endpoints/endpoints.py
index 1f17f0a42d2..4d0eb6a166a 100644
--- a/litellm/proxy/anthropic_endpoints/endpoints.py
+++ b/litellm/proxy/anthropic_endpoints/endpoints.py
@@ -43,7 +43,6 @@ from litellm.proxy.common_utils.openai_error_payload import (
openai_error_type,
with_litellm_call_id,
)
-from litellm.types.utils import TokenCountResponse
router: Final = APIRouter()
@@ -361,30 +360,15 @@ async def count_tokens(
messages_format="anthropic",
output_format=_requested_output_format(data),
)
- _token_response_dict: dict = {}
- if isinstance(token_response, TokenCountResponse):
- _token_response_dict = token_response.model_dump()
- elif isinstance(token_response, dict):
- _token_response_dict = token_response
-
- # Convert the internal response to Anthropic API format
- return {"input_tokens": _token_response_dict.get("total_tokens", 0)}
-
except HTTPException:
raise
except ProxyException as e:
- status_code: Final = int(e.code) if e.code and e.code.isdigit() else 500
- detail: Final = AnthropicExceptionMapping.transform_to_anthropic_error(
- status_code=status_code,
- raw_message=e.message,
- )
- raise HTTPException(
- status_code=status_code,
- detail=detail,
- )
+ return _anthropic_error_json_response(e, request)
except Exception as e:
log_llm_api_exception(e, litellm_call_id)
raise HTTPException(status_code=500, detail={"error": f"Internal server error: {e}"})
+ else:
+ return {"input_tokens": token_response.total_tokens}
@router.post(
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 3ab5826006f..2b23ccdf4f2 100644
--- a/tests/integration/providers/test_openai_count_tokens_tools_wire.py
+++ b/tests/integration/providers/test_openai_count_tokens_tools_wire.py
@@ -321,6 +321,48 @@ def test_messages_count_tokens_sends_the_input_v1_messages_inference_sends(
assert count_body["model"] == inference_body["model"]
+_UNCONVERTIBLE_BODY: Final[Mapping[str, JsonValue]] = {
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Summarize the notes."},
+ {"type": "document", "source": {"type": "text", "media_type": "text/plain", "data": "notes"}},
+ {"type": "search_result", "source": "https://example.com/notes", "title": "Notes", "content": []},
+ ],
+ },
+ {"role": "assistant", "content": [{"type": "tool_use", "id": "toolu_01", "name": "search", "input": {}}]},
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "toolu_01",
+ "content": [
+ {
+ "type": "search_result",
+ "source": "https://example.com/hits",
+ "title": "Hits",
+ "content": [{"type": "text", "text": "hit"}],
+ }
+ ],
+ }
+ ],
+ },
+ ],
+}
+
+
+def test_messages_count_tokens_rejects_blocks_it_cannot_convert(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)
+ response: Final = gateway.request("POST", "/v1/messages/count_tokens", {"model": model, **_UNCONVERTIBLE_BODY})
+ assert response.status_code == 400, response.text
+ assert "document with a text source, search_result, search_result inside a tool_result" in response.text
+ assert wire.drain() == ()
+
+
def test_messages_count_tokens_without_a_role_answers_400_before_calling_openai(counting_proxy: OwnedProxy) -> None:
gateway: Final = counting_proxy.gateway
with wire_server(_count_response) as wire, gateway.scenario() as scenario:
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 7fef79845a1..5fe82d37e9e 100644
--- a/tests/integration/providers/test_vertex_gemini_count_tokens_wire.py
+++ b/tests/integration/providers/test_vertex_gemini_count_tokens_wire.py
@@ -254,6 +254,53 @@ def test_count_tokens_sends_the_contents_messages_inference_sends(gateway: Gatew
assert _counted_contents(count_body) == generated_body["contents"]
+_UNCONVERTIBLE_MESSAGES: Final[JsonValue] = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Summarize the notes."},
+ {"type": "document", "source": {"type": "text", "media_type": "text/plain", "data": "notes"}},
+ {"type": "search_result", "source": "https://example.com/notes", "title": "Notes", "content": []},
+ ],
+ },
+ {"role": "assistant", "content": [{"type": "tool_use", "id": "toolu_01", "name": "search", "input": {}}]},
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "toolu_01",
+ "content": [
+ {
+ "type": "search_result",
+ "source": "https://example.com/hits",
+ "title": "Hits",
+ "content": [{"type": "text", "text": "hit"}],
+ }
+ ],
+ }
+ ],
+ },
+]
+
+
[email protected]("provider", ("vertex_ai", "gemini"))
+def test_count_tokens_rejects_blocks_it_cannot_convert(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)
+ )
+ response: Final = gateway.request(
+ "POST", "/v1/messages/count_tokens", {"model": model, "messages": _UNCONVERTIBLE_MESSAGES}
+ )
+ assert response.status_code == 400, response.text
+ assert "document with a text source, search_result, search_result inside a tool_result" in response.text
+ assert peer.drain() == ()
+
+
def test_count_tokens_keeps_each_text_block_in_system_instruction(gateway: Gateway) -> None:
peer: Final = _GeminiPeer()
with wire_server(peer) as wire, gateway.scenario() as scenario:
diff --git a/tests/unit/llms/anthropic/pass_through/test_convertible_blocks.py b/tests/unit/llms/anthropic/pass_through/test_convertible_blocks.py
new file mode 100644
index 00000000000..b5301b413ff
--- /dev/null
+++ b/tests/unit/llms/anthropic/pass_through/test_convertible_blocks.py
@@ -0,0 +1,192 @@
+import asyncio
+import json
+from collections.abc import Mapping
+from typing import Final
+
+import pytest
+from pydantic import JsonValue, TypeAdapter
+
+from litellm.llms.anthropic.pass_through.adapters.transformation import LiteLLMAnthropicMessagesAdapter
+from litellm.llms.anthropic.pass_through.convertible_blocks import (
+ unconvertible_anthropic_blocks,
+ unconvertible_blocks_error,
+)
+from litellm.llms.anthropic.pass_through.responses_adapters.transformation import (
+ LiteLLMAnthropicToResponsesAPIAdapter,
+)
+from litellm.llms.vertex_ai.count_tokens.context import gemini_count_contents
+from litellm.types.llms.anthropic import AllAnthropicPassThroughMessageValues
+
+_JSON_OBJECTS: Final = TypeAdapter(list[dict[str, JsonValue]])
+
+_PDF: Final = {"type": "base64", "media_type": "application/pdf", "data": "JVBERi0xLjQK"}
+_PNG: Final = {"type": "base64", "media_type": "image/png", "data": "aW1hZ2U="}
+
+_CONVERTED_BLOCKS: Final[tuple[tuple[str, Mapping[str, object]], ...]] = (
+ ("user", {"type": "text", "text": "hi"}),
+ ("user", {"type": "image", "source": _PNG}),
+ ("user", {"type": "image", "source": {"type": "url", "url": "https://example.com/a.png"}}),
+ ("user", {"type": "document", "source": _PDF}),
+ ("user", {"type": "document", "source": {"type": "url", "url": "https://example.com/a.pdf"}}),
+ ("user", {"type": "tool_result", "tool_use_id": "toolu_01", "content": "42"}),
+ ("assistant", {"type": "text", "text": "hi"}),
+ ("assistant", {"type": "tool_use", "id": "toolu_01", "name": "lookup", "input": {}}),
+ ("assistant", {"type": "thinking", "thinking": "Let me think.", "signature": "sig"}),
+)
+
+_DROPPED_BLOCKS: Final[tuple[tuple[str, Mapping[str, object], str], ...]] = (
+ ("user", {"type": "search_result", "source": "https://example.com", "title": "t", "content": []}, "search_result"),
+ ("user", {"type": "document", "source": {"type": "text", "data": "notes"}}, "document with a text source"),
+ ("user", {"type": "image", "source": {"type": "file", "file_id": "file_01"}}, "image with a file source"),
+ ("user", {"type": "image", "source": {"type": "base64", "data": ""}}, "image with an empty base64 source"),
+ ("user", {"type": "document"}, "document without a source"),
+ ("user", {"text": "untyped"}, "a block without a type"),
+ ("user", {"type": "tool_use", "id": "toolu_01", "name": "lookup", "input": {}}, "tool_use"),
+ (
+ "assistant",
+ {"type": "server_tool_use", "id": "srvtoolu_01", "name": "web_search", "input": {}},
+ "server_tool_use",
+ ),
+)
+
+
+def _adapter_messages(role: str, block: Mapping[str, object]) -> list[AllAnthropicPassThroughMessageValues]:
+ return [{"role": role, "content": [dict(block)]}] # pyright: ignore[reportReturnType] # sends block shapes the TypedDicts leave out on purpose
+
+
+def _converted_by_both_adapters(role: str, block: Mapping[str, object]) -> tuple[bool, bool]:
+ messages: Final = _adapter_messages(role, block)
+ chat: Final = _JSON_OBJECTS.validate_python(
+ LiteLLMAnthropicMessagesAdapter().translate_anthropic_messages_to_openai(messages=messages)
+ )
+ responses: Final = LiteLLMAnthropicToResponsesAPIAdapter().translate_messages_to_responses_input(messages)
+ chat_kept: Final = any(
+ message.get("content") or message.get("tool_calls") or message.get("thinking_blocks") for message in chat
+ )
+ return chat_kept, bool(responses)
+
+
[email protected](("role", "block"), _CONVERTED_BLOCKS)
+def test_blocks_both_conversions_keep_are_accepted(role: str, block: Mapping[str, object]) -> None:
+ assert _converted_by_both_adapters(role, block) == (True, True)
+ assert unconvertible_anthropic_blocks([{"role": role, "content": [block]}]) == ()
+
+
[email protected](("role", "block", "label"), _DROPPED_BLOCKS)
+def test_blocks_both_conversions_drop_are_named(role: str, block: Mapping[str, object], label: str) -> None:
+ assert _converted_by_both_adapters(role, block) == (False, False)
+ assert unconvertible_anthropic_blocks([{"role": role, "content": [block]}]) == (label,)
+
+
+def test_labels_are_listed_once_in_order_and_string_content_is_accepted() -> None:
+ messages: Final = [
+ {"role": "user", "content": "plain text"},
+ {"role": "user", "content": [{"type": "search_result"}, {"type": "container_upload"}]},
+ {"role": "assistant", "content": [{"type": "search_result"}]},
+ ]
+ assert unconvertible_anthropic_blocks(messages) == ("container_upload", "search_result")
+
+
+def test_redacted_thinking_is_accepted_like_other_replayed_thinking() -> None:
+ messages: Final = [{"role": "assistant", "content": [{"type": "redacted_thinking", "data": "opaque"}]}]
+ assert unconvertible_anthropic_blocks(messages) == ()
+
+
+def test_messages_that_are_not_json_are_left_to_the_count() -> None:
+ messages: Final = [{"role": "user", "content": [{"type": "search_result", "source": object()}]}]
+ assert unconvertible_anthropic_blocks(messages) == ()
+
+
+def _tool_turn(inner: Mapping[str, object]) -> tuple[Mapping[str, object], ...]:
+ return (
+ {"role": "assistant", "content": [{"type": "tool_use", "id": "toolu_01", "name": "lookup", "input": {}}]},
+ {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "toolu_01", "content": [dict(inner)]}]},
+ )
+
+
+def _sent_by_each_counter(inner: Mapping[str, object]) -> tuple[str, str]:
+ messages: Final = _tool_turn(inner)
+ gemini: Final = asyncio.run(gemini_count_contents(messages, "anthropic", "gemini-2.5-flash", "gemini", {}))
+ openai: Final = LiteLLMAnthropicToResponsesAPIAdapter().translate_messages_to_responses_input(
+ [dict(message) for message in messages] # pyright: ignore[reportArgumentType] # sends block shapes the TypedDicts leave out on purpose
+ )
+ return json.dumps(gemini, default=str), json.dumps(openai, default=str)
+
+
+_KEPT_INSIDE_TOOL_RESULT: Final[tuple[tuple[Mapping[str, object], str], ...]] = (
+ ({"type": "text", "text": "forty-two"}, "forty-two"),
+ ({"type": "image", "source": _PNG}, _PNG["data"]),
+ ({"type": "document", "source": _PDF}, _PDF["data"]),
+)
+
+_DROPPED_INSIDE_TOOL_RESULT: Final[tuple[tuple[Mapping[str, object], str, str], ...]] = (
+ (
+ {
+ "type": "search_result",
+ "source": "https://example.com",
+ "title": "t",
+ "content": [{"type": "text", "text": "search-snippet"}],
+ },
+ "search-snippet",
+ "search_result inside a tool_result",
+ ),
+ (
+ {"type": "document", "source": {"type": "text", "data": "text-notes"}},
+ "text-notes",
+ "document with a text source inside a tool_result",
+ ),
+ ({"type": "tool_reference", "tool_name": "find_docs"}, "find_docs", "tool_reference inside a tool_result"),
+)
+
+
[email protected](("inner", "marker"), _KEPT_INSIDE_TOOL_RESULT)
+def test_tool_result_content_both_counters_send_is_accepted(inner: Mapping[str, object], marker: str) -> None:
+ gemini, openai = _sent_by_each_counter(inner)
+
+ assert marker in gemini
+ assert marker in openai
+ assert unconvertible_anthropic_blocks(_tool_turn(inner)) == ()
+
+
[email protected](("inner", "marker", "label"), _DROPPED_INSIDE_TOOL_RESULT)
+def test_tool_result_content_both_counters_drop_is_named(inner: Mapping[str, object], marker: str, label: str) -> None:
+ gemini, openai = _sent_by_each_counter(inner)
+
+ assert marker not in gemini
+ assert marker not in openai
+ assert unconvertible_anthropic_blocks(_tool_turn(inner)) == (label,)
+
+
+def _replayed_web_search(encrypted_content: str) -> tuple[Mapping[str, object], ...]:
+ return (
+ {"role": "user", "content": "What is new?"},
+ {
+ "role": "assistant",
+ "content": [
+ {"type": "server_tool_use", "id": "srvtoolu_01", "name": "web_search", "input": {"query": "news"}},
+ {
+ "type": "web_search_tool_result",
+ "tool_use_id": "srvtoolu_01",
+ "content": [
+ {
+ "type": "web_search_result",
+ "url": "https://docs.litellm.ai/release_notes",
+ "title": "Release notes",
+ "encrypted_content": encrypted_content,
+ "snippet": "LiteLLM ships a weekly release candidate.",
+ }
+ ],
+ },
+ ],
+ },
+ )
+
+
+def test_a_replayed_web_search_inference_sends_as_text_is_accepted() -> None:
+ assert unconvertible_blocks_error(_replayed_web_search(""), "anthropic") is None
+
+
+def test_an_encrypted_web_search_inference_cannot_send_is_named() -> None:
+ error: Final = unconvertible_blocks_error(_replayed_web_search("opaque"), "anthropic")
+ assert error is not None
+ assert error.endswith("server_tool_use, web_search_tool_result")
diff --git a/tests/unit/proxy/test_proxy_token_counter.py b/tests/unit/proxy/test_proxy_token_counter.py
index 8cd6887d891..9bed719227f 100644
--- a/tests/unit/proxy/test_proxy_token_counter.py
+++ b/tests/unit/proxy/test_proxy_token_counter.py
@@ -2,6 +2,8 @@
# 1. Generate a Key, and use it to make a call
+import json
+from typing import Final
from unittest.mock import AsyncMock, MagicMock, patch
import httpx
@@ -14,7 +16,8 @@ load_dotenv()
# this file is to test litellm/proxy
-from fastapi import HTTPException, Request
+from fastapi import Request
+from fastapi.responses import JSONResponse
import litellm
from litellm import Router
@@ -1035,6 +1038,7 @@ async def test_anthropic_endpoint_returns_anthropic_error_format():
# Mock request object
mock_request = MagicMock(spec=Request)
+ mock_request.headers = {}
mock_request_data = {
"model": "claude-bedrock",
"messages": [{"role": "user", "content": "Hello!"}],
@@ -1062,14 +1066,11 @@ async def test_anthropic_endpoint_returns_anthropic_error_format():
proxy_server.count_request_tokens = mock_token_counter_error
try:
- with pytest.raises(HTTPException) as exc_info:
- await anthropic_count_tokens(mock_request, mock_user_api_key_dict)
-
- # Verify HTTP status code is correct
- assert exc_info.value.status_code == 400
+ response: Final[object] = await anthropic_count_tokens(mock_request, mock_user_api_key_dict)
- # Verify error is in Anthropic format
- detail = exc_info.value.detail
+ assert isinstance(response, JSONResponse)
+ assert response.status_code == 400
+ detail = json.loads(bytes(response.body))
assert detail["type"] == "error"
assert detail["error"]["type"] == "invalid_request_error"
assert detail["error"]["message"] == "Input is too long for requested model."
@@ -1087,6 +1088,7 @@ async def test_anthropic_endpoint_403_permission_error_format():
import litellm.proxy.proxy_server as proxy_server
mock_request = MagicMock(spec=Request)
+ mock_request.headers = {}
mock_request_data = {
"model": "claude-bedrock",
"messages": [{"role": "user", "content": "Hello!"}],
@@ -1114,12 +1116,11 @@ async def test_anthropic_endpoint_403_permission_error_format():
proxy_server.count_request_tokens = mock_token_counter_error
try:
- with pytest.raises(HTTPException) as exc_info:
- await anthropic_count_tokens(mock_request, mock_user_api_key_dict)
+ response: Final[object] = await anthropic_count_tokens(mock_request, mock_user_api_key_dict)
- assert exc_info.value.status_code == 403
-
- detail = exc_info.value.detail
+ assert isinstance(response, JSONResponse)
+ assert response.status_code == 403
+ detail = json.loads(bytes(response.body))
assert detail["type"] == "error"
assert detail["error"]["type"] == "permission_error"
assert detail["error"]["message"] == "Bearer Token has expired"
@@ -1137,6 +1138,7 @@ async def test_anthropic_endpoint_429_rate_limit_error_format():
import litellm.proxy.proxy_server as proxy_server
mock_request = MagicMock(spec=Request)
+ mock_request.headers = {}
mock_request_data = {
"model": "claude-bedrock",
"messages": [{"role": "user", "content": "Hello!"}],
@@ -1164,12 +1166,11 @@ async def test_anthropic_endpoint_429_rate_limit_error_format():
proxy_server.count_request_tokens = mock_token_counter_error
try:
- with pytest.raises(HTTPException) as exc_info:
- await anthropic_count_tokens(mock_request, mock_user_api_key_dict)
-
- assert exc_info.value.status_code == 429
+ response: Final[object] = await anthropic_count_tokens(mock_request, mock_user_api_key_dict)
- detail = exc_info.value.detail
+ assert isinstance(response, JSONResponse)
+ assert response.status_code == 429
+ detail = json.loads(bytes(response.body))
assert detail["type"] == "error"
assert detail["error"]["type"] == "rate_limit_error"
assert detail["error"]["message"] == "Rate limit exceeded"