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]

[Refactor] Anthropic /v1/messages endpoint - Refactor to use base llm http handler and transformations (#10677)

Ishaan Jaff9d8f570f14fb
diff --git a/litellm/anthropic_interface/messages/__init__.py b/litellm/anthropic_interface/messages/__init__.py
index f3249f981b1..15becd43af0 100644
--- a/litellm/anthropic_interface/messages/__init__.py
+++ b/litellm/anthropic_interface/messages/__init__.py
@@ -28,7 +28,7 @@ async def acreate(
stop_sequences: Optional[List[str]] = None,
stream: Optional[bool] = False,
system: Optional[str] = None,
- temperature: Optional[float] = 1.0,
+ temperature: Optional[float] = None,
thinking: Optional[Dict] = None,
tool_choice: Optional[Dict] = None,
tools: Optional[List[Dict]] = None,
@@ -84,7 +84,7 @@ async def create(
stop_sequences: Optional[List[str]] = None,
stream: Optional[bool] = False,
system: Optional[str] = None,
- temperature: Optional[float] = 1.0,
+ temperature: Optional[float] = None,
thinking: Optional[Dict] = None,
tool_choice: Optional[Dict] = None,
tools: Optional[List[Dict]] = None,
diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/handler.py b/litellm/llms/anthropic/experimental_pass_through/messages/handler.py
index ab335ca7c16..50384d2247c 100644
--- a/litellm/llms/anthropic/experimental_pass_through/messages/handler.py
+++ b/litellm/llms/anthropic/experimental_pass_through/messages/handler.py
@@ -5,8 +5,10 @@
"""
-import json
-from typing import AsyncIterator, Dict, List, Optional, Union, cast
+import asyncio
+import contextvars
+from functools import partial
+from typing import Any, AsyncIterator, Coroutine, Dict, List, Optional, Union
import httpx
@@ -15,17 +17,21 @@ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLogging
from litellm.llms.base_llm.anthropic_messages.transformation import (
BaseAnthropicMessagesConfig,
)
-from litellm.llms.custom_httpx.http_handler import (
- AsyncHTTPHandler,
- get_async_httpx_client,
-)
+from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
+from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler
from litellm.types.llms.anthropic_messages.anthropic_response import (
AnthropicMessagesResponse,
)
from litellm.types.router import GenericLiteLLMParams
-from litellm.types.utils import ProviderSpecificHeader
from litellm.utils import ProviderConfigManager, client
+from .utils import AnthropicMessagesRequestUtils
+
+####### ENVIRONMENT VARIABLES ###################
+# Initialize any necessary instances or variables here
+base_llm_http_handler = BaseLLMHTTPHandler()
+#################################################
+
class AnthropicMessagesHandler:
@staticmethod
@@ -84,114 +90,121 @@ async def anthropic_messages(
custom_llm_provider: Optional[str] = None,
**kwargs,
) -> Union[AnthropicMessagesResponse, AsyncIterator]:
+ """
+ Async: Make llm api request in Anthropic /messages API spec
+ """
+ local_vars = locals()
+ loop = asyncio.get_event_loop()
+ kwargs["anthropic_messages"] = True
+
+ func = partial(
+ anthropic_messages_handler,
+ max_tokens=max_tokens,
+ messages=messages,
+ model=model,
+ metadata=metadata,
+ stop_sequences=stop_sequences,
+ stream=stream,
+ system=system,
+ temperature=temperature,
+ thinking=thinking,
+ tool_choice=tool_choice,
+ tools=tools,
+ top_k=top_k,
+ top_p=top_p,
+ api_key=api_key,
+ api_base=api_base,
+ client=client,
+ custom_llm_provider=custom_llm_provider,
+ **kwargs,
+ )
+ ctx = contextvars.copy_context()
+ func_with_context = partial(ctx.run, func)
+ init_response = await loop.run_in_executor(None, func_with_context)
+
+ if asyncio.iscoroutine(init_response):
+ response = await init_response
+ else:
+ response = init_response
+ return response
+
+
+def anthropic_messages_handler(
+ max_tokens: int,
+ messages: List[Dict],
+ model: str,
+ metadata: Optional[Dict] = None,
+ stop_sequences: Optional[List[str]] = None,
+ stream: Optional[bool] = False,
+ system: Optional[str] = None,
+ temperature: Optional[float] = None,
+ thinking: Optional[Dict] = None,
+ tool_choice: Optional[Dict] = None,
+ tools: Optional[List[Dict]] = None,
+ top_k: Optional[int] = None,
+ top_p: Optional[float] = None,
+ api_key: Optional[str] = None,
+ api_base: Optional[str] = None,
+ client: Optional[AsyncHTTPHandler] = None,
+ custom_llm_provider: Optional[str] = None,
+ **kwargs,
+) -> Union[
+ AnthropicMessagesResponse,
+ Coroutine[Any, Any, Union[AnthropicMessagesResponse, AsyncIterator]],
+]:
"""
Makes Anthropic `/v1/messages` API calls In the Anthropic API Spec
"""
+ local_vars = locals()
# Use provided client or create a new one
- optional_params = GenericLiteLLMParams(**kwargs)
+ litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignore
+ litellm_params = GenericLiteLLMParams(**kwargs)
(
model,
- _custom_llm_provider,
+ custom_llm_provider,
dynamic_api_key,
dynamic_api_base,
) = litellm.get_llm_provider(
model=model,
custom_llm_provider=custom_llm_provider,
- api_base=optional_params.api_base,
- api_key=optional_params.api_key,
+ api_base=litellm_params.api_base,
+ api_key=litellm_params.api_key,
)
- anthropic_messages_provider_config: Optional[BaseAnthropicMessagesConfig] = (
- ProviderConfigManager.get_provider_anthropic_messages_config(
- model=model,
- provider=litellm.LlmProviders(_custom_llm_provider),
- )
+ anthropic_messages_provider_config: Optional[
+ BaseAnthropicMessagesConfig
+ ] = ProviderConfigManager.get_provider_anthropic_messages_config(
+ model=model,
+ provider=litellm.LlmProviders(custom_llm_provider),
)
if anthropic_messages_provider_config is None:
raise ValueError(
f"Anthropic messages provider config not found for model: {model}"
)
- if client is None or not isinstance(client, AsyncHTTPHandler):
- async_httpx_client = get_async_httpx_client(
- llm_provider=litellm.LlmProviders.ANTHROPIC
+ if custom_llm_provider is None:
+ raise ValueError(
+ f"custom_llm_provider is required for Anthropic messages, passed in model={model}, custom_llm_provider={custom_llm_provider}"
)
- else:
- async_httpx_client = client
-
- litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj", None)
- # Prepare headers
- provider_specific_header = cast(
- Optional[ProviderSpecificHeader], kwargs.get("provider_specific_header", None)
- )
- extra_headers = (
- provider_specific_header.get("extra_headers", {})
- if provider_specific_header
- else {}
+ local_vars.update(kwargs)
+ anthropic_messages_optional_request_params = (
+ AnthropicMessagesRequestUtils.get_requested_anthropic_messages_optional_param(
+ params=local_vars
+ )
)
- headers = anthropic_messages_provider_config.validate_environment(
- headers=extra_headers or {},
+ return base_llm_http_handler.anthropic_messages_handler(
model=model,
+ messages=messages,
+ anthropic_messages_provider_config=anthropic_messages_provider_config,
+ anthropic_messages_optional_request_params=dict(
+ anthropic_messages_optional_request_params
+ ),
+ _is_async=True,
+ client=client,
+ custom_llm_provider=custom_llm_provider,
+ litellm_params=litellm_params,
+ logging_obj=litellm_logging_obj,
api_key=api_key,
+ api_base=api_base,
+ stream=stream,
+ kwargs=kwargs,
)
-
- litellm_logging_obj.update_environment_variables(
- model=model,
- optional_params=dict(optional_params),
- litellm_params={
- "metadata": kwargs.get("metadata", {}),
- "preset_cache_key": None,
- "stream_response": {},
- **optional_params.model_dump(exclude_unset=True),
- },
- custom_llm_provider=_custom_llm_provider,
- )
- # Prepare request body
- request_body = locals().copy()
- request_body = {
- k: v
- for k, v in request_body.items()
- if k
- in anthropic_messages_provider_config.get_supported_anthropic_messages_params(
- model=model
- )
- and v is not None
- }
- request_body["stream"] = stream
- request_body["model"] = model
- litellm_logging_obj.stream = stream
- litellm_logging_obj.model_call_details.update(request_body)
-
- # Make the request
- request_url = anthropic_messages_provider_config.get_complete_url(
- api_base=api_base, model=model
- )
-
- litellm_logging_obj.pre_call(
- input=[{"role": "user", "content": json.dumps(request_body)}],
- api_key="",
- additional_args={
- "complete_input_dict": request_body,
- "api_base": str(request_url),
- "headers": headers,
- },
- )
-
- response = await async_httpx_client.post(
- url=request_url,
- headers=headers,
- data=json.dumps(request_body),
- stream=stream or False,
- )
- response.raise_for_status()
-
- # used for logging + cost tracking
- litellm_logging_obj.model_call_details["httpx_response"] = response
-
- if stream:
- return await AnthropicMessagesHandler._handle_anthropic_streaming(
- response=response,
- request_body=request_body,
- litellm_logging_obj=litellm_logging_obj,
- )
- else:
- return response.json()
diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py b/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py
index e9b598f18da..551aadd3cba 100644
--- a/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py
+++ b/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py
@@ -1,8 +1,18 @@
-from typing import Optional
+from typing import Dict, List, Optional
+import httpx
+
+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.llms.base_llm.anthropic_messages.transformation import (
BaseAnthropicMessagesConfig,
)
+from litellm.types.llms.anthropic import AnthropicMessagesRequest
+from litellm.types.llms.anthropic_messages.anthropic_response import (
+ AnthropicMessagesResponse,
+)
+from litellm.types.router import GenericLiteLLMParams
+
+from ...common_utils import AnthropicError
DEFAULT_ANTHROPIC_API_BASE = "https://api.anthropic.com"
DEFAULT_ANTHROPIC_API_VERSION = "2023-06-01"
@@ -45,3 +55,49 @@ class AnthropicMessagesConfig(BaseAnthropicMessagesConfig):
if "content-type" not in headers:
headers["content-type"] = "application/json"
return headers
+
+ def transform_anthropic_messages_request(
+ self,
+ model: str,
+ messages: List[Dict],
+ anthropic_messages_optional_request_params: Dict,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Dict:
+ """
+ No transformation is needed for Anthropic messages
+
+
+ This takes in a request in the Anthropic /v1/messages API spec -> transforms it to /v1/messages API spec (i.e) no transformation is needed
+ """
+ max_tokens = anthropic_messages_optional_request_params.pop("max_tokens", None)
+ if max_tokens is None:
+ raise AnthropicError(
+ message="max_tokens is required for Anthropic /v1/messages API",
+ status_code=400,
+ )
+ ####### get required params for all anthropic messages requests ######
+ anthropic_messages_request: AnthropicMessagesRequest = AnthropicMessagesRequest(
+ messages=messages,
+ max_tokens=max_tokens,
+ model=model,
+ **anthropic_messages_optional_request_params,
+ )
+ return dict(anthropic_messages_request)
+
+ def transform_anthropic_messages_response(
+ self,
+ model: str,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> AnthropicMessagesResponse:
+ """
+ No transformation is needed for Anthropic messages, since we want the response in the Anthropic /v1/messages API spec
+ """
+ try:
+ raw_response_json = raw_response.json()
+ except Exception:
+ raise AnthropicError(
+ message=raw_response.text, status_code=raw_response.status_code
+ )
+ return AnthropicMessagesResponse(**raw_response_json)
diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/utils.py b/litellm/llms/anthropic/experimental_pass_through/messages/utils.py
new file mode 100644
index 00000000000..29d00cd04cc
--- /dev/null
+++ b/litellm/llms/anthropic/experimental_pass_through/messages/utils.py
@@ -0,0 +1,24 @@
+from typing import Any, Dict, cast, get_type_hints
+
+from litellm.types.llms.anthropic import AnthropicMessagesRequestOptionalParams
+
+
+class AnthropicMessagesRequestUtils:
+ @staticmethod
+ def get_requested_anthropic_messages_optional_param(
+ params: Dict[str, Any],
+ ) -> AnthropicMessagesRequestOptionalParams:
+ """
+ Filter parameters to only include those defined in AnthropicMessagesRequestOptionalParams.
+
+ Args:
+ params: Dictionary of parameters to filter
+
+ Returns:
+ AnthropicMessagesRequestOptionalParams instance with only the valid parameters
+ """
+ valid_keys = get_type_hints(AnthropicMessagesRequestOptionalParams).keys()
+ filtered_params = {
+ k: v for k, v in params.items() if k in valid_keys and v is not None
+ }
+ return cast(AnthropicMessagesRequestOptionalParams, filtered_params)
diff --git a/litellm/llms/base_llm/anthropic_messages/transformation.py b/litellm/llms/base_llm/anthropic_messages/transformation.py
index 7619ffbbf6c..2ca5bdc0725 100644
--- a/litellm/llms/base_llm/anthropic_messages/transformation.py
+++ b/litellm/llms/base_llm/anthropic_messages/transformation.py
@@ -1,5 +1,12 @@
from abc import ABC, abstractmethod
-from typing import TYPE_CHECKING, Any, Optional
+from typing import TYPE_CHECKING, Any, Dict, List, Optional
+
+import httpx
+
+from litellm.types.llms.anthropic_messages.anthropic_response import (
+ AnthropicMessagesResponse,
+)
+from litellm.types.router import GenericLiteLLMParams
if TYPE_CHECKING:
from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj
@@ -33,3 +40,23 @@ class BaseAnthropicMessagesConfig(ABC):
@abstractmethod
def get_supported_anthropic_messages_params(self, model: str) -> list:
pass
+
+ @abstractmethod
+ def transform_anthropic_messages_request(
+ self,
+ model: str,
+ messages: List[Dict],
+ anthropic_messages_optional_request_params: Dict,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Dict:
+ pass
+
+ @abstractmethod
+ def transform_anthropic_messages_response(
+ self,
+ model: str,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ ) -> AnthropicMessagesResponse:
+ pass
diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.py
index abbbc2e5959..70ec04a5e13 100644
--- a/litellm/llms/custom_httpx/llm_http_handler.py
+++ b/litellm/llms/custom_httpx/llm_http_handler.py
@@ -1,5 +1,16 @@
import json
-from typing import TYPE_CHECKING, Any, Coroutine, Dict, Optional, Tuple, Union
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ AsyncIterator,
+ Coroutine,
+ Dict,
+ List,
+ Optional,
+ Tuple,
+ Union,
+ cast,
+)
import httpx # type: ignore
@@ -8,6 +19,9 @@ import litellm.litellm_core_utils
import litellm.types
import litellm.types.utils
from litellm._logging import verbose_logger
+from litellm.llms.base_llm.anthropic_messages.transformation import (
+ BaseAnthropicMessagesConfig,
+)
from litellm.llms.base_llm.audio_transcription.transformation import (
BaseAudioTranscriptionConfig,
)
@@ -29,6 +43,9 @@ from litellm.responses.streaming_iterator import (
ResponsesAPIStreamingIterator,
SyncResponsesAPIStreamingIterator,
)
+from litellm.types.llms.anthropic_messages.anthropic_response import (
+ AnthropicMessagesResponse,
+)
from litellm.types.llms.openai import (
CreateFileRequest,
OpenAIFileObject,
@@ -1001,6 +1018,154 @@ class BaseLLMHTTPHandler:
return returned_response
return model_response
+ async def async_anthropic_messages_handler(
+ self,
+ model: str,
+ messages: List[Dict],
+ anthropic_messages_provider_config: BaseAnthropicMessagesConfig,
+ anthropic_messages_optional_request_params: Dict,
+ custom_llm_provider: str,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ client: Optional[AsyncHTTPHandler] = None,
+ extra_headers: Optional[Dict[str, Any]] = None,
+ api_key: Optional[str] = None,
+ api_base: Optional[str] = None,
+ stream: Optional[bool] = False,
+ kwargs: Optional[Dict[str, Any]] = None,
+ ) -> Union[AnthropicMessagesResponse, AsyncIterator]:
+ from litellm.llms.anthropic.experimental_pass_through.messages.handler import (
+ AnthropicMessagesHandler,
+ )
+
+ if client is None or not isinstance(client, AsyncHTTPHandler):
+ async_httpx_client = get_async_httpx_client(
+ llm_provider=litellm.LlmProviders.ANTHROPIC
+ )
+ else:
+ async_httpx_client = client
+
+ # Prepare headers
+ kwargs = kwargs or {}
+ provider_specific_header = cast(
+ Optional[litellm.types.utils.ProviderSpecificHeader],
+ kwargs.get("provider_specific_header", None),
+ )
+ extra_headers = (
+ provider_specific_header.get("extra_headers", {})
+ if provider_specific_header
+ else {}
+ )
+ headers = anthropic_messages_provider_config.validate_environment(
+ headers=extra_headers or {},
+ model=model,
+ api_key=api_key,
+ )
+
+ logging_obj.update_environment_variables(
+ model=model,
+ optional_params=dict(anthropic_messages_optional_request_params),
+ litellm_params={
+ "metadata": kwargs.get("metadata", {}),
+ "preset_cache_key": None,
+ "stream_response": {},
+ **anthropic_messages_optional_request_params,
+ },
+ custom_llm_provider=custom_llm_provider,
+ )
+ # Prepare request body
+ request_body = anthropic_messages_provider_config.transform_anthropic_messages_request(
+ model=model,
+ messages=messages,
+ anthropic_messages_optional_request_params=anthropic_messages_optional_request_params,
+ litellm_params=litellm_params,
+ headers=headers,
+ )
+ request_body["stream"] = stream
+ request_body["model"] = model
+ logging_obj.stream = stream
+ logging_obj.model_call_details.update(request_body)
+
+ # Make the request
+ request_url = anthropic_messages_provider_config.get_complete_url(
+ api_base=api_base, model=model
+ )
+
+ logging_obj.pre_call(
+ input=[{"role": "user", "content": json.dumps(request_body)}],
+ api_key="",
+ additional_args={
+ "complete_input_dict": request_body,
+ "api_base": str(request_url),
+ "headers": headers,
+ },
+ )
+
+ response = await async_httpx_client.post(
+ url=request_url,
+ headers=headers,
+ data=json.dumps(request_body),
+ stream=stream or False,
+ logging_obj=logging_obj,
+ )
+ response.raise_for_status()
+
+ # used for logging + cost tracking
+ logging_obj.model_call_details["httpx_response"] = response
+
+ if stream:
+ return await AnthropicMessagesHandler._handle_anthropic_streaming(
+ response=response,
+ request_body=request_body,
+ litellm_logging_obj=logging_obj,
+ )
+ else:
+ return anthropic_messages_provider_config.transform_anthropic_messages_response(
+ model=model,
+ raw_response=response,
+ logging_obj=logging_obj,
+ )
+
+ def anthropic_messages_handler(
+ self,
+ model: str,
+ messages: List[Dict],
+ anthropic_messages_provider_config: BaseAnthropicMessagesConfig,
+ anthropic_messages_optional_request_params: Dict,
+ custom_llm_provider: str,
+ _is_async: bool,
+ litellm_params: GenericLiteLLMParams,
+ logging_obj: LiteLLMLoggingObj,
+ client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,
+ api_key: Optional[str] = None,
+ api_base: Optional[str] = None,
+ stream: Optional[bool] = False,
+ kwargs: Optional[Dict[str, Any]] = None,
+ ) -> Union[
+ AnthropicMessagesResponse,
+ Coroutine[Any, Any, Union[AnthropicMessagesResponse, AsyncIterator]],
+ ]:
+ """
+ LLM HTTP Handler for Anthropic Messages
+ """
+ if _is_async:
+ # Return the async coroutine if called with _is_async=True
+ return self.async_anthropic_messages_handler(
+ model=model,
+ messages=messages,
+ anthropic_messages_provider_config=anthropic_messages_provider_config,
+ anthropic_messages_optional_request_params=anthropic_messages_optional_request_params,
+ client=client if isinstance(client, AsyncHTTPHandler) else None,
+ custom_llm_provider=custom_llm_provider,
+ litellm_params=litellm_params,
+ logging_obj=logging_obj,
+ api_key=api_key,
+ api_base=api_base,
+ stream=stream,
+ kwargs=kwargs,
+ )
+ raise ValueError("anthropic_messages_handler is not implemented for sync calls")
+
def response_api_handler(
self,
model: str,
@@ -1455,7 +1620,7 @@ class BaseLLMHTTPHandler:
timeout=timeout,
client=client,
)
-
+
if client is None or not isinstance(client, HTTPHandler):
sync_httpx_client = _get_httpx_client(
params={"ssl_verify": litellm_params.get("ssl_verify", None)}
@@ -1496,9 +1661,7 @@ class BaseLLMHTTPHandler:
)
try:
- response = sync_httpx_client.get(
- url=url, headers=headers, params=data
- )
+ response = sync_httpx_client.get(url=url, headers=headers, params=data)
except Exception as e:
raise self._handle_error(
e=e,
diff --git a/litellm/types/llms/anthropic.py b/litellm/types/llms/anthropic.py
index 781d3caa9ff..785472d76c7 100644
--- a/litellm/types/llms/anthropic.py
+++ b/litellm/types/llms/anthropic.py
@@ -153,22 +153,23 @@ AllAnthropicMessageValues = Union[
]
-class AnthropicMessageRequestBase(TypedDict, total=False):
- messages: Required[List[AllAnthropicMessageValues]]
- max_tokens: Required[int]
- metadata: AnthropicMetadata
- stop_sequences: List[str]
- stream: bool
- system: Union[str, List]
- temperature: float
- tool_choice: AnthropicMessagesToolChoice
- tools: List[AllAnthropicToolsValues]
- top_k: int
- top_p: float
-
-
-class AnthropicMessagesRequest(AnthropicMessageRequestBase, total=False):
+class AnthropicMessagesRequestOptionalParams(TypedDict, total=False):
+ max_tokens: Optional[int]
+ metadata: Optional[Union[AnthropicMetadata, Dict]]
+ stop_sequences: Optional[List[str]]
+ stream: Optional[bool]
+ system: Optional[Union[str, List]]
+ temperature: Optional[float]
+ thinking: Optional[Dict]
+ tool_choice: Optional[Union[AnthropicMessagesToolChoice, Dict]]
+ tools: Optional[List[Union[AllAnthropicToolsValues, Dict]]]
+ top_k: Optional[int]
+ top_p: Optional[float]
+
+
+class AnthropicMessagesRequest(AnthropicMessagesRequestOptionalParams, total=False):
model: Required[str]
+ messages: Required[Union[List[AllAnthropicMessageValues], List[Dict]]]
# litellm param - used for tracking litellm proxy metadata in the request
litellm_metadata: dict
diff --git a/tests/pass_through_unit_tests/test_anthropic_messages_passthrough.py b/tests/pass_through_unit_tests/test_anthropic_messages_passthrough.py
index 51b89f10fce..ef288ba41ce 100644
--- a/tests/pass_through_unit_tests/test_anthropic_messages_passthrough.py
+++ b/tests/pass_through_unit_tests/test_anthropic_messages_passthrough.py
@@ -489,3 +489,68 @@ async def test_anthropic_messages_with_extra_headers():
assert response == mock_response.json.return_value
return response
+
+
+
+async def test_anthropic_messages_with_thinking():
+ """
+ Test the anthropic_messages with thinking
+ """
+ # Get API key from environment
+ api_key = os.getenv("ANTHROPIC_API_KEY", "fake-api-key")
+
+ # Set up test parameters
+ messages = [{"role": "user", "content": "Hello, can you tell me a short joke?"}]
+
+
+ # Create a mock response
+ mock_response = MagicMock()
+ mock_response.raise_for_status = MagicMock()
+ mock_response.json.return_value = {
+ "id": "msg_123456",
+ "type": "message",
+ "role": "assistant",
+ "content": [
+ {
+ "type": "text",
+ "text": "Why did the chicken cross the road? To get to the other side!",
+ }
+ ],
+ "model": "claude-3-haiku-20240307",
+ "stop_reason": "end_turn",
+ "usage": {"input_tokens": 10, "output_tokens": 20},
+ }
+
+ # Create a mock client with AsyncMock for the post method
+ mock_client = MagicMock(spec=AsyncHTTPHandler)
+ mock_client.post = AsyncMock(return_value=mock_response)
+
+ # Call the handler with extra_headers and our mocked client
+ response = await litellm.anthropic.messages.acreate(
+ messages=messages,
+ api_key=api_key,
+ model="claude-3-haiku-20240307",
+ max_tokens=100,
+ client=mock_client,
+ thinking={"budget_tokens": 100},
+ )
+
+ # Verify the post method was called with the right parameters
+ mock_client.post.assert_called_once()
+ call_kwargs = mock_client.post.call_args.kwargs
+ print("CALL KWARGS", call_kwargs)
+
+ # Verify headers were passed correctly
+ request_body = json.loads(call_kwargs.get("data", {}))
+ print("REQUEST BODY", request_body)
+ assert request_body["max_tokens"] == 100
+ assert request_body["model"] == "claude-3-haiku-20240307"
+ assert request_body["messages"] == messages
+ assert request_body["thinking"] == {"budget_tokens": 100}
+
+
+ # Verify the response was processed correctly
+ assert response == mock_response.json.return_value
+
+ return response