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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
[Feat] Allow using litellm.completion with /v1/messages API Spec (use gpt-4, gemini etc with claude code) (#11502)
Ishaan Jaff362e358a776a
diff --git a/litellm/anthropic_interface/messages/__init__.py b/litellm/anthropic_interface/messages/__init__.pyindex 15becd43af0..16bb5f3d462 100644--- a/litellm/anthropic_interface/messages/__init__.py+++ b/litellm/anthropic_interface/messages/__init__.py@@ -10,11 +10,14 @@ This is an __init__.py file to allow the following interface"""-from typing import AsyncIterator, Dict, Iterator, List, Optional, Union+from typing import Any, AsyncIterator, Coroutine, Dict, List, Optional, Unionfrom litellm.llms.anthropic.experimental_pass_through.messages.handler import (anthropic_messages as _async_anthropic_messages,)+from litellm.llms.anthropic.experimental_pass_through.messages.handler import (+ anthropic_messages_handler as _sync_anthropic_messages,+)from litellm.types.llms.anthropic_messages.anthropic_response import (AnthropicMessagesResponse,)@@ -76,7 +79,7 @@ async def acreate()-async def create(+def create(max_tokens: int,messages: List[Dict],model: str,@@ -91,7 +94,11 @@ async def create(top_k: Optional[int] = None,top_p: Optional[float] = None,**kwargs-) -> Union[AnthropicMessagesResponse, Iterator]:+) -> Union[+ AnthropicMessagesResponse,+ AsyncIterator[Any],+ Coroutine[Any, Any, Union[AnthropicMessagesResponse, AsyncIterator[Any]]],+]:"""Async wrapper for Anthropic's messages API@@ -114,4 +121,19 @@ async def create(Returns:Dict: Response from the API"""- raise NotImplementedError("This function is not implemented")+ return _sync_anthropic_messages(+ 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,+ **kwargs,+ )diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/__init__.py b/litellm/llms/anthropic/experimental_pass_through/adapters/__init__.pynew file mode 100644index 00000000000..18965622af3--- /dev/null+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/__init__.py@@ -0,0 +1,3 @@+from .transformation import LiteLLMAnthropicMessagesAdapter++__all__ = ["LiteLLMAnthropicMessagesAdapter"]diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py b/litellm/llms/anthropic/experimental_pass_through/adapters/handler.pynew file mode 100644index 00000000000..ec8cdccadc0--- /dev/null+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py@@ -0,0 +1,236 @@+from typing import Any, AsyncIterator, Coroutine, Dict, List, Optional, Union, cast++import litellm+from litellm.llms.anthropic.experimental_pass_through.adapters.transformation import (+ AnthropicAdapter,+)+from litellm.types.llms.anthropic_messages.anthropic_response import (+ AnthropicMessagesResponse,+)+from litellm.types.utils import ModelResponse++########################################################+# init adapter+ANTHROPIC_ADAPTER = AnthropicAdapter()+########################################################+++class LiteLLMMessagesToCompletionTransformationHandler:+ @staticmethod+ def _prepare_completion_kwargs(+ *,+ 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,+ extra_kwargs: Optional[Dict[str, Any]] = None,+ ) -> Dict[str, Any]:+ """Prepare kwargs for litellm.completion/acompletion"""++ request_data = {+ "model": model,+ "messages": messages,+ "max_tokens": max_tokens,+ }++ if metadata:+ request_data["metadata"] = metadata+ if stop_sequences:+ request_data["stop_sequences"] = stop_sequences+ if system:+ request_data["system"] = system+ if temperature is not None:+ request_data["temperature"] = temperature+ if thinking:+ request_data["thinking"] = thinking+ if tool_choice:+ request_data["tool_choice"] = tool_choice+ if tools:+ request_data["tools"] = tools+ if top_k is not None:+ request_data["top_k"] = top_k+ if top_p is not None:+ request_data["top_p"] = top_p++ openai_request = ANTHROPIC_ADAPTER.translate_completion_input_params(+ request_data+ )++ if openai_request is None:+ raise ValueError("Failed to translate request to OpenAI format")++ completion_kwargs: Dict[str, Any] = dict(openai_request)++ if stream:+ completion_kwargs["stream"] = stream++ excluded_keys = {"litellm_logging_obj", "anthropic_messages"}+ extra_kwargs = extra_kwargs or {}+ for key, value in extra_kwargs.items():+ if (+ key not in excluded_keys+ and key not in completion_kwargs+ and value is not None+ ):+ completion_kwargs[key] = value++ return completion_kwargs++ @staticmethod+ async def async_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,+ **kwargs,+ ) -> Union[AnthropicMessagesResponse, AsyncIterator]:+ """Handle non-Anthropic models asynchronously using the adapter"""++ completion_kwargs = (+ LiteLLMMessagesToCompletionTransformationHandler._prepare_completion_kwargs(+ 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,+ extra_kwargs=kwargs,+ )+ )++ try:+ completion_response = await litellm.acompletion(**completion_kwargs)++ if stream:+ transformed_stream = (+ ANTHROPIC_ADAPTER.translate_completion_output_params_streaming(+ completion_response+ )+ )+ if transformed_stream is not None:+ return transformed_stream+ raise ValueError("Failed to transform streaming response")+ else:+ anthropic_response = (+ ANTHROPIC_ADAPTER.translate_completion_output_params(+ cast(ModelResponse, completion_response)+ )+ )+ if anthropic_response is not None:+ return anthropic_response+ raise ValueError("Failed to transform response to Anthropic format")+ except Exception as e: # noqa: BLE001+ raise ValueError(+ f"Error calling litellm.acompletion for non-Anthropic model: {str(e)}"+ )++ @staticmethod+ 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,+ _is_async: bool = False,+ **kwargs,+ ) -> Union[+ AnthropicMessagesResponse,+ AsyncIterator[Any],+ Coroutine[Any, Any, Union[AnthropicMessagesResponse, AsyncIterator[Any]]],+ ]:+ """Handle non-Anthropic models using the adapter."""+ if _is_async is True:+ return LiteLLMMessagesToCompletionTransformationHandler.async_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,+ **kwargs,+ )++ completion_kwargs = (+ LiteLLMMessagesToCompletionTransformationHandler._prepare_completion_kwargs(+ 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,+ extra_kwargs=kwargs,+ )+ )++ try:+ completion_response = litellm.completion(**completion_kwargs)++ if stream:+ transformed_stream = (+ ANTHROPIC_ADAPTER.translate_completion_output_params_streaming(+ completion_response+ )+ )+ if transformed_stream is not None:+ return transformed_stream+ raise ValueError("Failed to transform streaming response")+ else:+ anthropic_response = (+ ANTHROPIC_ADAPTER.translate_completion_output_params(+ cast(ModelResponse, completion_response)+ )+ )+ if anthropic_response is not None:+ return anthropic_response+ raise ValueError("Failed to transform response to Anthropic format")+ except Exception as e: # noqa: BLE001+ raise ValueError(+ f"Error calling litellm.completion for non-Anthropic model: {str(e)}"+ )diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py b/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.pynew file mode 100644index 00000000000..273b9c477a1--- /dev/null+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py@@ -0,0 +1,183 @@+# What is this?+## Translates OpenAI call to Anthropic `/v1/messages` format+import json+import traceback+from typing import Any, AsyncIterator, Iterator, Optional++from litellm import verbose_logger+from litellm.types.utils import AdapterCompletionStreamWrapper+++class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):+ """+ - first chunk return 'message_start'+ - content block must be started and stopped+ - finish_reason must map exactly to anthropic reason, else anthropic client won't be able to parse it.+ """++ sent_first_chunk: bool = False+ sent_content_block_start: bool = False+ sent_content_block_finish: bool = False+ sent_last_message: bool = False+ holding_chunk: Optional[Any] = None++ def __next__(self):+ from .transformation import LiteLLMAnthropicMessagesAdapter++ try:+ if self.sent_first_chunk is False:+ self.sent_first_chunk = True+ return {+ "type": "message_start",+ "message": {+ "id": "msg_1nZdL29xx5MUA1yADyHTEsnR8uuvGzszyY",+ "type": "message",+ "role": "assistant",+ "content": [],+ "model": "claude-3-5-sonnet-20240620",+ "stop_reason": None,+ "stop_sequence": None,+ "usage": {"input_tokens": 25, "output_tokens": 1},+ },+ }+ if self.sent_content_block_start is False:+ self.sent_content_block_start = True+ return {+ "type": "content_block_start",+ "index": 0,+ "content_block": {"type": "text", "text": ""},+ }++ for chunk in self.completion_stream:+ if chunk == "None" or chunk is None:+ raise Exception++ processed_chunk = LiteLLMAnthropicMessagesAdapter().translate_streaming_openai_response_to_anthropic(+ response=chunk+ )+ if (+ processed_chunk["type"] == "message_delta"+ and self.sent_content_block_finish is False+ ):+ self.holding_chunk = processed_chunk+ self.sent_content_block_finish = True+ return {+ "type": "content_block_stop",+ "index": 0,+ }+ elif self.holding_chunk is not None:+ return_chunk = self.holding_chunk+ self.holding_chunk = processed_chunk+ return return_chunk+ else:+ return processed_chunk+ if self.holding_chunk is not None:+ return_chunk = self.holding_chunk+ self.holding_chunk = None+ return return_chunk+ if self.sent_last_message is False:+ self.sent_last_message = True+ return {"type": "message_stop"}+ raise StopIteration+ except StopIteration:+ if self.sent_last_message is False:+ self.sent_last_message = True+ return {"type": "message_stop"}+ raise StopIteration+ except Exception as e:+ verbose_logger.error(+ "Anthropic Adapter - {}\n{}".format(e, traceback.format_exc())+ )+ raise StopAsyncIteration++ async def __anext__(self):+ from .transformation import LiteLLMAnthropicMessagesAdapter++ try:+ if self.sent_first_chunk is False:+ self.sent_first_chunk = True+ return {+ "type": "message_start",+ "message": {+ "id": "msg_1nZdL29xx5MUA1yADyHTEsnR8uuvGzszyY",+ "type": "message",+ "role": "assistant",+ "content": [],+ "model": "claude-3-5-sonnet-20240620",+ "stop_reason": None,+ "stop_sequence": None,+ "usage": {"input_tokens": 25, "output_tokens": 1},+ },+ }+ if self.sent_content_block_start is False:+ self.sent_content_block_start = True+ return {+ "type": "content_block_start",+ "index": 0,+ "content_block": {"type": "text", "text": ""},+ }+ async for chunk in self.completion_stream:+ if chunk == "None" or chunk is None:+ raise Exception+ processed_chunk = LiteLLMAnthropicMessagesAdapter().translate_streaming_openai_response_to_anthropic(+ response=chunk+ )+ if (+ processed_chunk["type"] == "message_delta"+ and self.sent_content_block_finish is False+ ):+ self.holding_chunk = processed_chunk+ self.sent_content_block_finish = True+ return {+ "type": "content_block_stop",+ "index": 0,+ }+ elif self.holding_chunk is not None:+ return_chunk = self.holding_chunk+ self.holding_chunk = processed_chunk+ return return_chunk+ else:+ return processed_chunk+ if self.holding_chunk is not None:+ return_chunk = self.holding_chunk+ self.holding_chunk = None+ return return_chunk+ if self.sent_last_message is False:+ self.sent_last_message = True+ return {"type": "message_stop"}+ raise StopIteration+ except StopIteration:+ if self.sent_last_message is False:+ self.sent_last_message = True+ return {"type": "message_stop"}+ raise StopAsyncIteration++ def anthropic_sse_wrapper(self) -> Iterator[bytes]:+ """+ Convert AnthropicStreamWrapper dict chunks to Server-Sent Events format.+ Similar to the Bedrock bedrock_sse_wrapper implementation.++ This wrapper ensures dict chunks are SSE formatted with both event and data lines.+ """+ for chunk in self:+ if isinstance(chunk, dict):+ event_type: str = str(chunk.get("type", "message"))+ payload = f"event: {event_type}\ndata: {json.dumps(chunk)}\n\n"+ yield payload.encode()+ else:+ # For non-dict chunks, forward the original value unchanged+ yield chunk++ async def async_anthropic_sse_wrapper(self) -> AsyncIterator[bytes]:+ """+ Async version of anthropic_sse_wrapper.+ Convert AnthropicStreamWrapper dict chunks to Server-Sent Events format.+ """+ async for chunk in self:+ if isinstance(chunk, dict):+ event_type: str = str(chunk.get("type", "message"))+ payload = f"event: {event_type}\ndata: {json.dumps(chunk)}\n\n"+ yield payload.encode()+ else:+ # For non-dict chunks, forward the original value unchanged+ yield chunkdiff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.pynew file mode 100644index 00000000000..0cddb65ddc4--- /dev/null+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py@@ -0,0 +1,506 @@+import json+from typing import Any, AsyncIterator, List, Literal, Optional, Tuple, Union, cast++from openai.types.chat.chat_completion_chunk import Choice as OpenAIStreamingChoice++from litellm.types.llms.anthropic import (+ AllAnthropicToolsValues,+ AnthopicMessagesAssistantMessageParam,+ AnthropicFinishReason,+ AnthropicMessagesRequest,+ AnthropicMessagesToolChoice,+ AnthropicMessagesUserMessageParam,+ AnthropicResponseContentBlockText,+ AnthropicResponseContentBlockToolUse,+ ContentBlockDelta,+ ContentJsonBlockDelta,+ ContentTextBlockDelta,+ MessageBlockDelta,+ MessageDelta,+ UsageDelta,+)+from litellm.types.llms.anthropic_messages.anthropic_response import (+ AnthropicMessagesResponse,+ AnthropicUsage,+)+from litellm.types.llms.openai import (+ AllMessageValues,+ ChatCompletionAssistantMessage,+ ChatCompletionAssistantToolCall,+ ChatCompletionImageObject,+ ChatCompletionImageUrlObject,+ ChatCompletionRequest,+ ChatCompletionSystemMessage,+ ChatCompletionTextObject,+ ChatCompletionToolCallFunctionChunk,+ ChatCompletionToolChoiceFunctionParam,+ ChatCompletionToolChoiceObjectParam,+ ChatCompletionToolChoiceValues,+ ChatCompletionToolMessage,+ ChatCompletionToolParam,+ ChatCompletionToolParamFunctionChunk,+ ChatCompletionUserMessage,+)+from litellm.types.utils import Choices, ModelResponse, Usage++from .streaming_iterator import AnthropicStreamWrapper+++class AnthropicAdapter:+ def __init__(self) -> None:+ pass++ def translate_completion_input_params(+ self, kwargs+ ) -> Optional[ChatCompletionRequest]:+ """+ - translate params, where needed+ - pass rest, as is+ """++ #########################################################+ # Validate required params+ #########################################################+ model = kwargs.pop("model")+ messages = kwargs.pop("messages")+ if not model:+ raise ValueError(+ "Bad Request: model is required for Anthropic Messages Request"+ )+ if not messages:+ raise ValueError(+ "Bad Request: messages is required for Anthropic Messages Request"+ )++ #########################################################+ # Created Typed Request Body+ #########################################################+ request_body = AnthropicMessagesRequest(+ model=model, messages=messages, **kwargs+ )++ translated_body = (+ LiteLLMAnthropicMessagesAdapter().translate_anthropic_to_openai(+ anthropic_message_request=request_body+ )+ )++ return translated_body++ def translate_completion_output_params(+ self, response: ModelResponse+ ) -> Optional[AnthropicMessagesResponse]:++ return LiteLLMAnthropicMessagesAdapter().translate_openai_response_to_anthropic(+ response=response+ )++ def translate_completion_output_params_streaming(+ self, completion_stream: Any+ ) -> Union[AsyncIterator[bytes], None]:+ anthropic_wrapper = AnthropicStreamWrapper(completion_stream=completion_stream)+ # Return the SSE-wrapped version for proper event formatting+ return anthropic_wrapper.async_anthropic_sse_wrapper()+++class LiteLLMAnthropicMessagesAdapter:+ def __init__(self):+ pass++ ### FOR [BETA] `/v1/messages` endpoint support++ def translatable_anthropic_params(self) -> List:+ """+ Which anthropic params, we need to translate to the openai format.+ """+ return ["messages", "metadata", "system", "tool_choice", "tools"]++ def translate_anthropic_messages_to_openai( # noqa: PLR0915+ self,+ messages: List[+ Union[+ AnthropicMessagesUserMessageParam,+ AnthopicMessagesAssistantMessageParam,+ ]+ ],+ ) -> List:+ new_messages: List[AllMessageValues] = []+ for m in messages:+ user_message: Optional[ChatCompletionUserMessage] = None+ tool_message_list: List[ChatCompletionToolMessage] = []+ new_user_content_list: List[+ Union[ChatCompletionTextObject, ChatCompletionImageObject]+ ] = []+ ## USER MESSAGE ##+ if m["role"] == "user":+ ## translate user message+ message_content = m.get("content")+ if message_content and isinstance(message_content, str):+ user_message = ChatCompletionUserMessage(+ role="user", content=message_content+ )+ elif message_content and isinstance(message_content, list):+ for content in message_content:+ if content.get("type") == "text":+ text_obj = ChatCompletionTextObject(+ type="text", text=content.get("text", "")+ )+ new_user_content_list.append(text_obj)+ elif content.get("type") == "image":+ image_url = ChatCompletionImageUrlObject(+ url=f"data:{content.get('type', '')};base64,{content.get('source', '')}"+ )+ image_obj = ChatCompletionImageObject(+ type="image_url", image_url=image_url+ )++ new_user_content_list.append(image_obj)+ elif content.get("type") == "tool_result":+ if "content" not in content:+ tool_result = ChatCompletionToolMessage(+ role="tool",+ tool_call_id=content.get("tool_use_id", ""),+ content="",+ )+ tool_message_list.append(tool_result)+ elif isinstance(content.get("content"), str):+ tool_result = ChatCompletionToolMessage(+ role="tool",+ tool_call_id=content.get("tool_use_id", ""),+ content=str(content.get("content", "")),+ )+ tool_message_list.append(tool_result)+ elif isinstance(content.get("content"), list):+ for c in content.get("content", []):+ if isinstance(c, str):+ tool_result = ChatCompletionToolMessage(+ role="tool",+ tool_call_id=content.get("tool_use_id", ""),+ content=c,+ )+ tool_message_list.append(tool_result)+ elif isinstance(c, dict):+ if c.get("type") == "text":+ tool_result = ChatCompletionToolMessage(+ role="tool",+ tool_call_id=content.get(+ "tool_use_id", ""+ ),+ content=c.get("text", ""),+ )+ tool_message_list.append(tool_result)+ elif c.get("type") == "image":+ image_str = f"data:{c.get('type', '')};base64,{c.get('source', '')}"+ tool_result = ChatCompletionToolMessage(+ role="tool",+ tool_call_id=content.get(+ "tool_use_id", ""+ ),+ content=image_str,+ )+ tool_message_list.append(tool_result)++ if user_message is not None:+ new_messages.append(user_message)++ if len(new_user_content_list) > 0:+ new_messages.append({"role": "user", "content": new_user_content_list}) # type: ignore++ if len(tool_message_list) > 0:+ new_messages.extend(tool_message_list)++ ## ASSISTANT MESSAGE ##+ assistant_message_str: Optional[str] = None+ tool_calls: List[ChatCompletionAssistantToolCall] = []+ if m["role"] == "assistant":+ if isinstance(m.get("content"), str):+ assistant_message_str = str(m.get("content", ""))+ elif isinstance(m.get("content"), list):+ for content in m.get("content", []):+ if isinstance(content, str):+ assistant_message_str = str(content)+ elif isinstance(content, dict):+ if content.get("type") == "text":+ if assistant_message_str is None:+ assistant_message_str = content.get("text", "")+ else:+ assistant_message_str += content.get("text", "")+ elif content.get("type") == "tool_use":+ function_chunk = ChatCompletionToolCallFunctionChunk(+ name=content.get("name", ""),+ arguments=json.dumps(content.get("input", {})),+ )++ tool_calls.append(+ ChatCompletionAssistantToolCall(+ id=content.get("id", ""),+ type="function",+ function=function_chunk,+ )+ )++ if assistant_message_str is not None or len(tool_calls) > 0:+ assistant_message = ChatCompletionAssistantMessage(+ role="assistant",+ content=assistant_message_str,+ )+ if len(tool_calls) > 0:+ assistant_message["tool_calls"] = tool_calls+ new_messages.append(assistant_message)++ return new_messages++ def translate_anthropic_tool_choice_to_openai(+ self, tool_choice: AnthropicMessagesToolChoice+ ) -> ChatCompletionToolChoiceValues:+ if tool_choice["type"] == "any":+ return "required"+ elif tool_choice["type"] == "auto":+ return "auto"+ elif tool_choice["type"] == "tool":+ tc_function_param = ChatCompletionToolChoiceFunctionParam(+ name=tool_choice.get("name", "")+ )+ return ChatCompletionToolChoiceObjectParam(+ type="function", function=tc_function_param+ )+ else:+ raise ValueError(+ "Incompatible tool choice param submitted - {}".format(tool_choice)+ )++ def translate_anthropic_tools_to_openai(+ self, tools: List[AllAnthropicToolsValues]+ ) -> List[ChatCompletionToolParam]:+ new_tools: List[ChatCompletionToolParam] = []+ mapped_tool_params = ["name", "input_schema", "description"]+ for tool in tools:+ function_chunk = ChatCompletionToolParamFunctionChunk(+ name=tool["name"],+ )+ if "input_schema" in tool:+ function_chunk["parameters"] = tool["input_schema"] # type: ignore+ if "description" in tool:+ function_chunk["description"] = tool["description"] # type: ignore++ for k, v in tool.items():+ if k not in mapped_tool_params: # pass additional computer kwargs+ function_chunk.setdefault("parameters", {}).update({k: v})+ new_tools.append(+ ChatCompletionToolParam(type="function", function=function_chunk)+ )++ return new_tools++ def translate_anthropic_to_openai(+ self, anthropic_message_request: AnthropicMessagesRequest+ ) -> ChatCompletionRequest:+ """+ This is used by the beta Anthropic Adapter, for translating anthropic `/v1/messages` requests to the openai format.+ """+ new_messages: List[AllMessageValues] = []++ ## CONVERT ANTHROPIC MESSAGES TO OPENAI+ messages_list: List[+ Union[+ AnthropicMessagesUserMessageParam, AnthopicMessagesAssistantMessageParam+ ]+ ] = cast(+ List[+ Union[+ AnthropicMessagesUserMessageParam,+ AnthopicMessagesAssistantMessageParam,+ ]+ ],+ anthropic_message_request["messages"],+ )+ new_messages = self.translate_anthropic_messages_to_openai(+ messages=messages_list+ )+ ## ADD SYSTEM MESSAGE TO MESSAGES+ if "system" in anthropic_message_request:+ system_content = anthropic_message_request["system"]+ if system_content:+ new_messages.insert(+ 0,+ ChatCompletionSystemMessage(role="system", content=system_content),+ )++ new_kwargs: ChatCompletionRequest = {+ "model": anthropic_message_request["model"],+ "messages": new_messages,+ }+ ## CONVERT METADATA (user_id)+ if "metadata" in anthropic_message_request:+ metadata = anthropic_message_request["metadata"]+ if metadata and "user_id" in metadata:+ new_kwargs["user"] = metadata["user_id"]++ # Pass litellm proxy specific metadata+ if "litellm_metadata" in anthropic_message_request:+ # metadata will be passed to litellm.acompletion(), it's a litellm_param+ new_kwargs["metadata"] = anthropic_message_request.pop("litellm_metadata")++ ## CONVERT TOOL CHOICE+ if "tool_choice" in anthropic_message_request:+ tool_choice = anthropic_message_request["tool_choice"]+ if tool_choice:+ new_kwargs["tool_choice"] = (+ self.translate_anthropic_tool_choice_to_openai(+ tool_choice=cast(AnthropicMessagesToolChoice, tool_choice)+ )+ )+ ## CONVERT TOOLS+ if "tools" in anthropic_message_request:+ tools = anthropic_message_request["tools"]+ if tools:+ new_kwargs["tools"] = self.translate_anthropic_tools_to_openai(+ tools=cast(List[AllAnthropicToolsValues], tools)+ )++ translatable_params = self.translatable_anthropic_params()+ for k, v in anthropic_message_request.items():+ if k not in translatable_params: # pass remaining params as is+ new_kwargs[k] = v # type: ignore++ return new_kwargs++ def _translate_openai_content_to_anthropic(+ self, choices: List[Choices]+ ) -> List[+ Union[AnthropicResponseContentBlockText, AnthropicResponseContentBlockToolUse]+ ]:+ new_content: List[+ Union[+ AnthropicResponseContentBlockText, AnthropicResponseContentBlockToolUse+ ]+ ] = []+ for choice in choices:+ if (+ choice.message.tool_calls is not None+ and len(choice.message.tool_calls) > 0+ ):+ for tool_call in choice.message.tool_calls:+ new_content.append(+ AnthropicResponseContentBlockToolUse(+ type="tool_use",+ id=tool_call.id,+ name=tool_call.function.name or "",+ input=json.loads(tool_call.function.arguments),+ )+ )+ elif choice.message.content is not None:+ new_content.append(+ AnthropicResponseContentBlockText(+ type="text", text=choice.message.content+ )+ )++ return new_content++ def _translate_openai_finish_reason_to_anthropic(+ self, openai_finish_reason: str+ ) -> AnthropicFinishReason:+ if openai_finish_reason == "stop":+ return "end_turn"+ elif openai_finish_reason == "length":+ return "max_tokens"+ elif openai_finish_reason == "tool_calls":+ return "tool_use"+ return "end_turn"++ def translate_openai_response_to_anthropic(+ self, response: ModelResponse+ ) -> AnthropicMessagesResponse:+ ## translate content block+ anthropic_content = self._translate_openai_content_to_anthropic(choices=response.choices) # type: ignore+ ## extract finish reason+ anthropic_finish_reason = self._translate_openai_finish_reason_to_anthropic(+ openai_finish_reason=response.choices[0].finish_reason # type: ignore+ )+ # extract usage+ usage: Usage = getattr(response, "usage")+ anthropic_usage = AnthropicUsage(+ input_tokens=usage.prompt_tokens or 0,+ output_tokens=usage.completion_tokens or 0,+ )+ translated_obj = AnthropicMessagesResponse(+ id=response.id,+ type="message",+ role="assistant",+ model=response.model or "unknown-model",+ stop_sequence=None,+ usage=anthropic_usage,+ content=anthropic_content, # type: ignore+ stop_reason=anthropic_finish_reason,+ )++ return translated_obj++ def _translate_streaming_openai_chunk_to_anthropic(+ self, choices: List[OpenAIStreamingChoice]+ ) -> Tuple[+ Literal["text_delta", "input_json_delta"],+ Union[ContentTextBlockDelta, ContentJsonBlockDelta],+ ]:+ text: str = ""+ partial_json: Optional[str] = None+ for choice in choices:+ if choice.delta.content is not None:+ text += choice.delta.content+ elif choice.delta.tool_calls is not None:+ partial_json = ""+ for tool in choice.delta.tool_calls:+ if (+ tool.function is not None+ and tool.function.arguments is not None+ ):+ partial_json += tool.function.arguments++ if partial_json is not None:+ return "input_json_delta", ContentJsonBlockDelta(+ type="input_json_delta", partial_json=partial_json+ )+ else:+ return "text_delta", ContentTextBlockDelta(type="text_delta", text=text)++ def translate_streaming_openai_response_to_anthropic(+ self, response: ModelResponse+ ) -> Union[ContentBlockDelta, MessageBlockDelta]:+ ## base case - final chunk w/ finish reason+ if response.choices[0].finish_reason is not None:+ delta = MessageDelta(+ stop_reason=self._translate_openai_finish_reason_to_anthropic(+ response.choices[0].finish_reason+ ),+ )+ if getattr(response, "usage", None) is not None:+ litellm_usage_chunk: Optional[Usage] = response.usage # type: ignore+ elif (+ hasattr(response, "_hidden_params")+ and "usage" in response._hidden_params+ ):+ litellm_usage_chunk = response._hidden_params["usage"]+ else:+ litellm_usage_chunk = None+ if litellm_usage_chunk is not None:+ usage_delta = UsageDelta(+ input_tokens=litellm_usage_chunk.prompt_tokens or 0,+ output_tokens=litellm_usage_chunk.completion_tokens or 0,+ )+ else:+ usage_delta = UsageDelta(input_tokens=0, output_tokens=0)+ return MessageBlockDelta(+ type="message_delta", delta=delta, usage=usage_delta+ )+ (+ type_of_content,+ content_block_delta,+ ) = self._translate_streaming_openai_chunk_to_anthropic(+ choices=response.choices # type: ignore+ )+ return ContentBlockDelta(+ type="content_block_delta",+ index=response.choices[0].index,+ delta=content_block_delta,+ )diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/handler.py b/litellm/llms/anthropic/experimental_pass_through/messages/handler.pyindex daec92a3bd8..54fbf0a12cd 100644--- a/litellm/llms/anthropic/experimental_pass_through/messages/handler.py+++ b/litellm/llms/anthropic/experimental_pass_through/messages/handler.py@@ -23,6 +23,7 @@ from litellm.types.llms.anthropic_messages.anthropic_response import (from litellm.types.router import GenericLiteLLMParamsfrom litellm.utils import ProviderConfigManager, client+from ..adapters.handler import LiteLLMMessagesToCompletionTransformationHandlerfrom .utils import AnthropicMessagesRequestUtils####### ENVIRONMENT VARIABLES ###################@@ -57,7 +58,7 @@ async def anthropic_messages("""local_vars = locals()loop = asyncio.get_event_loop()- kwargs["anthropic_messages"] = True+ kwargs["is_async"] = Truefunc = partial(anthropic_messages_handler,@@ -112,12 +113,14 @@ def anthropic_messages_handler(**kwargs,) -> Union[AnthropicMessagesResponse,- Coroutine[Any, Any, Union[AnthropicMessagesResponse, AsyncIterator]],+ AsyncIterator[Any],+ Coroutine[Any, Any, Union[AnthropicMessagesResponse, AsyncIterator[Any]]],]:"""Makes Anthropic `/v1/messages` API calls In the Anthropic API Spec"""local_vars = locals()+ is_async = kwargs.pop("is_async", False)# Use provided client or create a new onelitellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignorelitellm_params = GenericLiteLLMParams(**kwargs)@@ -132,16 +135,34 @@ def anthropic_messages_handler(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}, custom_llm_provider: {custom_llm_provider}"+ # Handle non-Anthropic models using the adapter+ return (+ LiteLLMMessagesToCompletionTransformationHandler.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,+ _is_async=is_async,+ **kwargs,+ ))+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}"@@ -160,7 +181,7 @@ def anthropic_messages_handler(anthropic_messages_optional_request_params=dict(anthropic_messages_optional_request_params),- _is_async=True,+ _is_async=is_async,client=client,custom_llm_provider=custom_llm_provider,litellm_params=litellm_params,diff --git a/litellm/proxy/proxy_config.yaml b/litellm/proxy/proxy_config.yamlindex 64dbb50a1b6..1dbae862778 100644--- a/litellm/proxy/proxy_config.yaml+++ b/litellm/proxy/proxy_config.yaml@@ -1,109 +1,9 @@model_list:- - model_name: fake-openai-endpoint+ - model_name: gemini/*litellm_params:- model: openai/my-fake-model- api_key: my-fake-key- api_base: https://exampleopenaiendpoint-production.up.railway.app/+ model: gemini/*+ api_key: os.environ/GEMINI_API_KEY- model_name: "anthropic/*"litellm_params:model: "anthropic/*"api_key: os.environ/ANTHROPIC_API_KEY- - model_name: "bedrock/*"- litellm_params:- model: "bedrock/*"- - model_name: "bedrock-useast1/*"- litellm_params:- model: "bedrock/*"- - model_name: "bedrock-useast2/*"- litellm_params:- model: "bedrock/*"- aws_region_name: us-east-2- - model_name: "bedrock-uswest2/*"- litellm_params:- model: "bedrock/*"- aws_region_name: us-west-2- - model_name: "vertex_ai/*"- litellm_params:- model: "vertex_ai/*"- vertex_project: os.environ/VERTEX_PROJECT- vertex_location: os.environ/VERTEX_LOCATION- vertex_credentials: os.environ/VERTEX_SERVICE_ACCOUNT- - model_name: "gemini/*"- litellm_params:- model: "gemini/*"- api_key: os.environ/GEMINI_API_KEY- - model_name: "gemini-dev/*"- litellm_params:- model: "gemini/*"- api_key: os.environ/GEMINI_API_KEY_DEV- - model_name: "databricks/*"- litellm_params:- model: "databricks/*"- api_key: os.environ/DATABRICKS_API_KEY- api_base: os.environ/DATABRICKS_API_BASE--litellm_settings:- cache: True- cache_params:- type: redis- host: os.environ/REDIS_HOST- port: os.environ/REDIS_PORT- password: os.environ/REDIS_PASSWORD- supported_call_types:- - acompletion- - completion- request_timeout: 30- allowed_fails: 3- # callbacks:- # - otel- # - prometheus- failure_callback:- - sentry- success_callback:- - s3_v2- s3_callback_params:- s3_bucket_name: load-testing-oct- disable_token_counter: True- default_internal_user_params:- user_role: os.environ/DEFAULT_USER_ROLE--callback_settings:- otel:- message_logging: False--router_settings:- routing_strategy: simple-shuffle # Literal["simple-shuffle", "least-busy", "usage-based-routing","latency-based-routing"], default="simple-shuffle"- redis_host: os.environ/REDIS_HOST- redis_port: os.environ/REDIS_PORT- redis_password: os.environ/REDIS_PASSWORD- retry_policy: {- # Set the number of retries for each exception type.- # The logic is as follows:- # 1. For anything that is likely to repeat the same outcome, don't retry.- # 2. Internal server errors might be transient, so retry once.- # 3. For rate limit errors, retry twice.- # https://docs.litellm.ai/docs/routing#advanced-custom-retries-cooldowns-based-on-error-type- # Based on that doc, rate limit retries use exponential backoff whereas others are immediate.- "AuthenticationErrorRetries": 0,- "BadRequestErrorRetries": 0,- "ContentPolicyViolationErrorRetries": 0,- "InternalServerErrorRetries": 1,- "RateLimitErrorRetries": 2,- "TimeoutErrorRetries": 0- }--general_settings:- disable_spend_logs: True- proxy_batch_write_at: 60- use_redis_transaction_buffer: true- alert_types: # https://docs.litellm.ai/docs/proxy/alerting#all-possible-alert-types- - db_exceptions- - cooldown_deployment- - failed_tracking_spend- - fallback_reports- # - llm_requests_hanging- - llm_too_slow- - new_model_added- - outage_alerts- - region_outage_alerts- alerting: ["slack"]\ No newline at end of filediff --git a/litellm/types/llms/anthropic_messages/anthropic_response.py b/litellm/types/llms/anthropic_messages/anthropic_response.pyindex 270807fc8f7..158d11c463c 100644--- a/litellm/types/llms/anthropic_messages/anthropic_response.py+++ b/litellm/types/llms/anthropic_messages/anthropic_response.py@@ -2,6 +2,11 @@ from typing import Any, Dict, List, Literal, Optional, TypedDict, Unionfrom typing_extensions import TypeAlias+from litellm.types.llms.anthropic import (+ AnthropicResponseContentBlockText,+ AnthropicResponseContentBlockToolUse,+)+class AnthropicResponseTextBlock(TypedDict, total=False):"""@@ -71,7 +76,15 @@ class AnthropicMessagesResponse(TypedDict, total=False):Anthropic Messages API Response: https://docs.anthropic.com/en/api/messages"""- content: Optional[List[AnthropicResponseContentBlock]]+ content: Optional[+ List[+ Union[+ AnthropicResponseContentBlock,+ AnthropicResponseContentBlockText,+ AnthropicResponseContentBlockToolUse,+ ]+ ]+ ]id: strmodel: Optional[str] # This represents the Model type from Anthropicrole: Optional[Literal["assistant"]]diff --git a/tests/pass_through_unit_tests/base_anthropic_unified_messages_test.py b/tests/pass_through_unit_tests/base_anthropic_unified_messages_test.pynew file mode 100644index 00000000000..e67fb011894--- /dev/null+++ b/tests/pass_through_unit_tests/base_anthropic_unified_messages_test.py@@ -0,0 +1,111 @@+++import json+import os+import sys+from datetime import datetime+from typing import AsyncIterator, Dict, Any+import asyncio+import unittest.mock+from unittest.mock import AsyncMock, MagicMock++sys.path.insert(+ 0, os.path.abspath("../../..")+) # Adds the parent directory to the system path+import litellm+import pytest+from dotenv import load_dotenv+from litellm.llms.anthropic.experimental_pass_through.messages.handler import (+ anthropic_messages,+)++from typing import Optional+from litellm.types.utils import StandardLoggingPayload+from litellm.integrations.custom_logger import CustomLogger+from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler+from litellm.router import Router+import importlib+from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM+++class BaseAnthropicMessagesTest:+ """Base class for anthropic messages tests to reduce code duplication"""++ @property+ def model_config(self) -> Dict[str, Any]:+ """Override in subclasses to provide model-specific configuration"""+ raise NotImplementedError("Subclasses must implement model_config")++ def _validate_response(self, response: Any):+ """Validate non-streaming response structure"""+ # Handle type checking - response should be a dict for non-streaming+ if isinstance(response, AsyncIterator):+ pytest.fail("Expected non-streaming response but got AsyncIterator")++ assert isinstance(response, dict), f"Expected dict response, got {type(response)}"+ assert "id" in response+ assert "content" in response+ assert "model" in response+ assert response.get("role") == "assistant"++ async def _test_non_streaming_base(self):+ """Base test for non-streaming requests"""+ litellm._turn_on_debug()++ request_params = self.model_config++ # Set up test parameters+ messages = [{"role": "user", "content": "Hello, can you tell me a short joke?"}]++ # Prepare call arguments+ call_args = {+ "messages": messages,+ "max_tokens": 100,+ }+++++ # Add any additional config from subclass+ call_args.update(request_params)++ # Call the handler+ response = await litellm.anthropic.messages.acreate(**call_args)++ print(f"Non-streaming {request_params['model']} response: ", response)++ # Verify response+ self._validate_response(response)++ print(f"Non-streaming response: {json.dumps(response, indent=2, default=str)}")+ return response++ async def _test_streaming_base(self):+ """Base test for streaming requests"""+ request_params = self.model_config+ # Set up test parameters+ messages = [{"role": "user", "content": "Hello, can you tell me a short joke?"}]++ # Prepare call arguments+ call_args = {+ "messages": messages,+ "max_tokens": 100,+ "stream": True,+ "client": AsyncHTTPHandler(),+ }+++ # Add any additional config from subclass+ call_args.update(request_params)++ # Call the handler+ response = await litellm.anthropic.messages.acreate(**call_args)++ collected_chunks = []+ if isinstance(response, AsyncIterator):+ async for chunk in response:+ print("chunk=", chunk)+ collected_chunks.append(chunk)++ print("collected_chunks=", collected_chunks)+ return collected_chunks\ No newline at end of filediff --git a/tests/pass_through_unit_tests/test_anthropic_messages_passthrough.py b/tests/pass_through_unit_tests/test_anthropic_messages_passthrough.pyindex bee46b1e6cd..9f032ffaadd 100644--- a/tests/pass_through_unit_tests/test_anthropic_messages_passthrough.py+++ b/tests/pass_through_unit_tests/test_anthropic_messages_passthrough.py@@ -24,7 +24,7 @@ from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandlerfrom litellm.router import Routerimport importlibfrom litellm.llms.bedrock.base_aws_llm import BaseAWSLLM-+from base_anthropic_unified_messages_test import BaseAnthropicMessagesTest# Load environment variablesload_dotenv()@@ -70,124 +70,34 @@ def _validate_anthropic_response(response: Dict[str, Any]):assert response["role"] == "assistant"-async def test_anthropic_messages_non_streaming():- """- Test the anthropic_messages with non-streaming request- """- litellm._turn_on_debug()- # Get API key from environment- api_key = os.getenv("ANTHROPIC_API_KEY")- if not api_key:- pytest.skip("ANTHROPIC_API_KEY not found in environment")-- # Set up test parameters- messages = [{"role": "user", "content": "Hello, can you tell me a short joke?"}]-- # Call the handler- response = await litellm.anthropic.messages.acreate(- messages=messages,- api_key=api_key,- model="claude-3-haiku-20240307",- max_tokens=100,- )-- # Verify response- assert "id" in response- assert "content" in response- assert "model" in response- assert response["role"] == "assistant"-- print(f"Non-streaming response: {json.dumps(response, indent=2)}")- return response--async def test_anthropic_messages_non_streaming_bedrock_invoke():- """- Test the anthropic_messages with non-streaming request- """- litellm._turn_on_debug()-- # Set up test parameters- messages = [{"role": "user", "content": "Hello, can you tell me a short joke?"}]-- # Call the handler- response = await litellm.anthropic.messages.acreate(- messages=messages,- model="bedrock/us.anthropic.claude-3-5-sonnet-20240620-v1:0",- max_tokens=100,- )-- print("non-streaming bedrock invoke response: ", response)-- # Verify response- assert "id" in response- assert "content" in response- assert "model" in response- assert response["role"] == "assistant"-- print(f"Non-streaming response: {json.dumps(response, indent=2)}")- return response--async def test_anthropic_messages_streaming():- """- Test the anthropic_messages with streaming request- """- # Get API key from environment- api_key = os.getenv("ANTHROPIC_API_KEY")- if not api_key:- pytest.skip("ANTHROPIC_API_KEY not found in environment")-- # Set up test parameters- messages = [{"role": "user", "content": "Hello, can you tell me a short joke?"}]-- # Call the handler- async_httpx_client = AsyncHTTPHandler()- response = await litellm.anthropic.messages.acreate(- messages=messages,- api_key=api_key,- model="claude-3-haiku-20240307",- max_tokens=100,- stream=True,- client=async_httpx_client,- )- if isinstance(response, AsyncIterator):- async for chunk in response:- print("chunk=", chunk)+class TestAnthropicDirectAPI(BaseAnthropicMessagesTest):+ """Tests for direct Anthropic API calls"""+ @property+ def model_config(self) -> Dict[str, Any]:+ return {+ "model": "claude-3-haiku-20240307",+ "api_key": os.getenv("ANTHROPIC_API_KEY"),+ }+class TestAnthropicBedrockAPI(BaseAnthropicMessagesTest):+ """Tests for Anthropic via Bedrock"""+ @property+ def model_config(self) -> Dict[str, Any]:+ return {+ "model": "bedrock/us.anthropic.claude-3-5-sonnet-20240620-v1:0",+ }-async def test_anthropic_messages_streaming_bedrock_invoke():- """- Test the anthropic_messages with streaming request- """- # Get API key from environment- api_key = os.getenv("ANTHROPIC_API_KEY")- if not api_key:- pytest.skip("ANTHROPIC_API_KEY not found in environment")- # Set up test parameters- messages = [{"role": "user", "content": "Hello, can you tell me a short joke?"}]- # Call the handler- async_httpx_client = AsyncHTTPHandler()- response = await litellm.anthropic.messages.acreate(- messages=messages,- api_key=api_key,- model="bedrock/us.anthropic.claude-3-5-sonnet-20240620-v1:0",- max_tokens=100,- stream=True,- client=async_httpx_client,- )- collected_chunks = []- if isinstance(response, AsyncIterator):- async for chunk in response:- print("chunk=", chunk)- collected_chunks.append(chunk)+class TestAnthropicOpenAIAPI(BaseAnthropicMessagesTest):+ """Tests for OpenAI via Anthropic messages interface"""+ @property+ def model_config(self) -> Dict[str, Any]:+ return {+ "model": "openai/gpt-4o-mini",+ }- print("collected_chunks=", collected_chunks)@pytest.mark.asyncioasync def test_anthropic_messages_streaming_with_bad_request():@@ -196,19 +106,23 @@ async def test_anthropic_messages_streaming_with_bad_request():"""try:response = await litellm.anthropic.messages.acreate(- messages=["hi"],+ messages=[{"role": "user", "content": "hi"}],api_key=os.getenv("ANTHROPIC_API_KEY"),model="claude-3-haiku-20240307",max_tokens=100,stream=True,)print(response)- async for chunk in response:- print("chunk=", chunk)+ if isinstance(response, AsyncIterator):+ async for chunk in response:+ print("chunk=", chunk)except Exception as e:print("got exception", e)print("vars", vars(e))- assert e.status_code == 400+ if hasattr(e, 'status_code'):+ assert getattr(e, 'status_code') == 400+ else:+ assert isinstance(e, Exception)@pytest.mark.asyncio@@ -230,18 +144,22 @@ async def test_anthropic_messages_router_streaming_with_bad_request():)response = await router.aanthropic_messages(- messages=["hi"],+ messages=[{"role": "user", "content": "hi"}],model="claude-special-alias",max_tokens=100,stream=True,)print(response)- async for chunk in response:- print("chunk=", chunk)+ if isinstance(response, AsyncIterator):+ async for chunk in response:+ print("chunk=", chunk)except Exception as e:print("got exception", e)print("vars", vars(e))- assert e.status_code == 400+ if hasattr(e, 'status_code'):+ assert getattr(e, 'status_code') == 400+ else:+ assert isinstance(e, Exception)@pytest.mark.asyncio@@ -332,6 +250,8 @@ async def test_anthropic_messages_litellm_router_non_streaming_with_logging():print(f"Non-streaming response: {json.dumps(response, indent=2)}")await asyncio.sleep(1)++ assert test_custom_logger.logged_standard_logging_payload is not None, "Logging payload should not be None"assert test_custom_logger.logged_standard_logging_payload["messages"] == messagesassert test_custom_logger.logged_standard_logging_payload["response"] is not Noneassert (@@ -464,6 +384,7 @@ async def test_anthropic_messages_litellm_router_streaming_with_logging():),)+ assert test_custom_logger.logged_standard_logging_payload is not None, "Logging payload should not be None"assert test_custom_logger.logged_standard_logging_payload["messages"] == messagesassert test_custom_logger.logged_standard_logging_payload["response"] is not Noneassert (@@ -648,8 +569,8 @@ async def test_anthropic_messages_bedrock_credentials_passthrough():}mock_post.return_value = mock_response- # Test all AWS credentials parameters- test_params = {+ # Test AWS credentials parameters - separate from function call parameters+ aws_params = {"aws_access_key_id": "test_access_key","aws_secret_access_key": "test_secret_key","aws_session_token": "test_session_token",@@ -666,7 +587,7 @@ async def test_anthropic_messages_bedrock_credentials_passthrough():messages=[{"role": "user", "content": "Hello, test credentials"}],model="bedrock/us.anthropic.claude-3-5-sonnet-20240620-v1:0",max_tokens=100,- **test_params+ **aws_params)# Verify get_credentials was called with the correct parameters@@ -674,7 +595,7 @@ async def test_anthropic_messages_bedrock_credentials_passthrough():call_args = mock_get_credentials.call_args[1]# Assert that our test credentials were passed correctly- for param_name, param_value in test_params.items():+ for param_name, param_value in aws_params.items():assert call_args[param_name] == param_value, f"Parameter {param_name} was not passed correctly"@@ -740,3 +661,20 @@ async def test_anthropic_messages_bedrock_dynamic_region():credentials_args = mock_get_credentials.call_args.kwargsassert credentials_args.get('aws_region_name') == test_region++def test_sync_openai_messages():+ """+ Test the anthropic_messages with sync request+ """+ litellm._turn_on_debug()+ response = litellm.anthropic.messages.create(+ messages=[{"role": "user", "content": "Hello, can you tell me a short joke?"}],+ model="openai/gpt-4o-mini",+ max_tokens=100,+ )+ print("ANT response", response)++ assert response is not None+ assert isinstance(response, dict)+ assert response["content"][0].text is not None+diff --git a/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_sse_wrapper.py b/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_sse_wrapper.pynew file mode 100644index 00000000000..40c40c6ab62--- /dev/null+++ b/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_sse_wrapper.py@@ -0,0 +1,151 @@+import os+import sys++import pytest+from fastapi.testclient import TestClient++sys.path.insert(0, os.path.abspath("../../../../.."))++from litellm.llms.anthropic.experimental_pass_through.adapters.streaming_iterator import (+ AnthropicStreamWrapper,+)+from litellm.types.utils import Delta, ModelResponse, StreamingChoices+++# Create a simple test+class MockCompletionStream:+ def __init__(self):+ self.responses = [+ ModelResponse(+ stream=True,+ choices=[+ StreamingChoices(+ delta=Delta(content="Hello"), index=0, finish_reason=None+ )+ ],+ ),+ ModelResponse(+ stream=True,+ choices=[+ StreamingChoices(+ delta=Delta(content=" World"), index=0, finish_reason=None+ )+ ],+ ),+ ModelResponse(+ stream=True,+ choices=[+ StreamingChoices(+ delta=Delta(content=""), index=0, finish_reason="stop"+ )+ ],+ ),+ ]+ self.index = 0++ def __iter__(self):+ return self++ def __next__(self):+ if self.index >= len(self.responses):+ raise StopIteration+ response = self.responses[self.index]+ self.index += 1+ return response+++def test_anthropic_sse_wrapper_format():+ """Test that the SSE wrapper produces proper event and data formatting"""+ wrapper = AnthropicStreamWrapper(completion_stream=MockCompletionStream())++ # Get the first chunk from the SSE wrapper+ first_chunk = next(wrapper.anthropic_sse_wrapper())++ # Verify it's bytes+ assert isinstance(first_chunk, bytes)++ # Decode and check format+ chunk_str = first_chunk.decode("utf-8")++ # Should have event line and data line+ lines = chunk_str.split("\n")+ assert len(lines) >= 3 # event line, data line, empty line (+ possibly more)+ assert lines[0].startswith("event: ")+ assert lines[1].startswith("data: ")+ assert lines[2] == "" # Empty line to end the SSE chunk+++def test_anthropic_sse_wrapper_event_types():+ """Test that different chunk types produce correct event types"""+ wrapper = AnthropicStreamWrapper(completion_stream=MockCompletionStream())++ chunks = []+ for chunk in wrapper.anthropic_sse_wrapper():+ chunks.append(chunk.decode("utf-8"))+ if len(chunks) >= 3: # Get first few chunks+ break++ # First chunk should be message_start+ assert "event: message_start" in chunks[0]+ assert '"type": "message_start"' in chunks[0]++ # Second chunk should be content_block_start+ assert "event: content_block_start" in chunks[1]+ assert '"type": "content_block_start"' in chunks[1]++ # Third chunk should be content_block_delta+ assert "event: content_block_delta" in chunks[2]+ assert '"type": "content_block_delta"' in chunks[2]+++async def test_async_anthropic_sse_wrapper():+ """Test the async version of the SSE wrapper"""++ class AsyncMockCompletionStream:+ def __init__(self):+ self.responses = [+ ModelResponse(+ stream=True,+ choices=[+ StreamingChoices(+ delta=Delta(content="Hello"), index=0, finish_reason=None+ )+ ],+ ),+ ModelResponse(+ stream=True,+ choices=[+ StreamingChoices(+ delta=Delta(content=" World"), index=0, finish_reason=None+ )+ ],+ ),+ ]+ self.index = 0++ def __aiter__(self):+ return self++ async def __anext__(self):+ if self.index >= len(self.responses):+ raise StopAsyncIteration+ response = self.responses[self.index]+ self.index += 1+ return response++ wrapper = AnthropicStreamWrapper(completion_stream=AsyncMockCompletionStream())++ # Get the first chunk from the async SSE wrapper+ first_chunk = None+ async for chunk in wrapper.async_anthropic_sse_wrapper():+ first_chunk = chunk+ break++ # Verify it's bytes and properly formatted+ assert first_chunk is not None+ assert isinstance(first_chunk, bytes)++ chunk_str = first_chunk.decode("utf-8")+ assert "event: message_start" in chunk_str+ assert '"type": "message_start"' in chunk_str