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]

Chat Completions <-> Responses API Bridge Improvements (#11685)

Krish Dholakiaa76cf95401f4
diff --git a/litellm/completion_extras/litellm_responses_transformation/transformation.py b/litellm/completion_extras/litellm_responses_transformation/transformation.py
index d7f4c477e2c..7f6d64e0d66 100644
--- a/litellm/completion_extras/litellm_responses_transformation/transformation.py
+++ b/litellm/completion_extras/litellm_responses_transformation/transformation.py
@@ -165,6 +165,7 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge):
request_data = {
"model": api_model,
"input": input_items,
+ **litellm_params,
}
verbose_logger.debug(
@@ -196,6 +197,7 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge):
json_mode: Optional[bool] = None,
) -> "ModelResponse":
"""Transform Responses API response to chat completion response"""
+
from openai.types.responses import (
ResponseFunctionToolCall,
ResponseOutputMessage,
@@ -213,6 +215,9 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge):
if not isinstance(raw_response, ResponsesAPIResponse):
raise ValueError(f"Unexpected response type: {type(raw_response)}")
+ if raw_response.error is not None:
+ raise ValueError(f"Error in response: {raw_response.error}")
+
choices: List[Choices] = []
index = 0
for item in raw_response.output:
@@ -256,8 +261,19 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge):
else:
raise ValueError(f"Unknown item type: {item}")
+ if len(choices) == 0:
+ if (
+ raw_response.incomplete_details is not None
+ and raw_response.incomplete_details.reason is not None
+ ):
+ raise ValueError(
+ f"{model} unable to complete request: {raw_response.incomplete_details.reason}"
+ )
+
setattr(model_response, "choices", choices)
+ model_response.model = model
+
setattr(
model_response,
"usage",
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py
index f899d57f408..4515bbc7fa4 100644
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@ -1326,6 +1326,18 @@ class Logging(LiteLLMLoggingBaseClass):
else: # streaming chunks + image gen.
self.model_call_details["response_cost"] = None
+ ## RESPONSES API USAGE OBJECT TRANSFORMATION ##
+ # MAP RESPONSES API USAGE OBJECT TO LITELLM USAGE OBJECT
+ if isinstance(result, ResponsesAPIResponse):
+ result = result.model_copy()
+ setattr(
+ result,
+ "usage",
+ ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage(
+ result.usage
+ ),
+ )
+
if (
litellm.max_budget
and self.stream is False
@@ -2601,19 +2613,35 @@ class Logging(LiteLLMLoggingBaseClass):
if self.stream and isinstance(result, ModelResponse):
return result
- result = litellm.AnthropicConfig().transform_response(
- raw_response=self.model_call_details["httpx_response"],
- model_response=litellm.ModelResponse(),
- model=self.model,
- messages=[],
- logging_obj=self,
- optional_params={},
- api_key="",
- request_data={},
- encoding=litellm.encoding,
- json_mode=False,
- litellm_params={},
- )
+ if "httpx_response" in self.model_call_details:
+ result = litellm.AnthropicConfig().transform_response(
+ raw_response=self.model_call_details.get("httpx_response", None),
+ model_response=litellm.ModelResponse(),
+ model=self.model,
+ messages=[],
+ logging_obj=self,
+ optional_params={},
+ api_key="",
+ request_data={},
+ encoding=litellm.encoding,
+ json_mode=False,
+ litellm_params={},
+ )
+ else:
+ from litellm.types.llms.anthropic import AnthropicResponse
+
+ pydantic_result = AnthropicResponse.model_validate(result)
+ import httpx
+
+ result = litellm.AnthropicConfig().transform_parsed_response(
+ completion_response=pydantic_result.model_dump(),
+ raw_response=httpx.Response(
+ status_code=200,
+ headers={},
+ ),
+ model_response=litellm.ModelResponse(),
+ json_mode=None,
+ )
return result
diff --git a/litellm/litellm_core_utils/llm_response_utils/response_metadata.py b/litellm/litellm_core_utils/llm_response_utils/response_metadata.py
index 614b5573ccc..b1085c684fc 100644
--- a/litellm/litellm_core_utils/llm_response_utils/response_metadata.py
+++ b/litellm/litellm_core_utils/llm_response_utils/response_metadata.py
@@ -38,7 +38,8 @@ class ResponseMetadata:
"""Set hidden parameters on the response"""
## ADD OTHER HIDDEN PARAMS
- model_id = kwargs.get("model_info", {}).get("id", None)
+ model_info = kwargs.get("model_info", {}) or {}
+ model_id = model_info.get("id", None)
new_params = {
"litellm_call_id": getattr(logging_obj, "litellm_call_id", None),
"api_base": get_api_base(model=model or "", optional_params=kwargs),
diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py b/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py
index ec8cdccadc0..e9d704b0a8a 100644
--- a/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py
+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py
@@ -1,4 +1,14 @@
-from typing import Any, AsyncIterator, Coroutine, Dict, List, Optional, Union, cast
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ AsyncIterator,
+ Coroutine,
+ Dict,
+ List,
+ Optional,
+ Union,
+ cast,
+)
import litellm
from litellm.llms.anthropic.experimental_pass_through.adapters.transformation import (
@@ -9,6 +19,9 @@ from litellm.types.llms.anthropic_messages.anthropic_response import (
)
from litellm.types.utils import ModelResponse
+if TYPE_CHECKING:
+ pass
+
########################################################
# init adapter
ANTHROPIC_ADAPTER = AnthropicAdapter()
diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/handler.py b/litellm/llms/anthropic/experimental_pass_through/messages/handler.py
index 54fbf0a12cd..ddb3eaed80b 100644
--- a/litellm/llms/anthropic/experimental_pass_through/messages/handler.py
+++ b/litellm/llms/anthropic/experimental_pass_through/messages/handler.py
@@ -123,7 +123,12 @@ def anthropic_messages_handler(
is_async = kwargs.pop("is_async", False)
# Use provided client or create a new one
litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignore
- litellm_params = GenericLiteLLMParams(**kwargs)
+ litellm_params = GenericLiteLLMParams(
+ **kwargs,
+ api_key=api_key,
+ api_base=api_base,
+ custom_llm_provider=custom_llm_provider,
+ )
(
model,
custom_llm_provider,
@@ -135,11 +140,12 @@ 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:
# Handle non-Anthropic models using the adapter
@@ -159,6 +165,10 @@ def anthropic_messages_handler(
top_k=top_k,
top_p=top_p,
_is_async=is_async,
+ api_key=api_key,
+ api_base=api_base,
+ client=client,
+ custom_llm_provider=custom_llm_provider,
**kwargs,
)
)
diff --git a/litellm/proxy/_new_secret_config.yaml b/litellm/proxy/_new_secret_config.yaml
index 595dec78721..e191583d5da 100644
--- a/litellm/proxy/_new_secret_config.yaml
+++ b/litellm/proxy/_new_secret_config.yaml
@@ -76,7 +76,10 @@ model_list:
litellm_params:
model: vertex_ai/claude-3-5-sonnet@20240620
vertex_project: internal-litellm-local-dev
-
+ - model_name: "openai-custom/*"
+ litellm_params:
+ model: "openai/*"
+ api_key: os.environ/OPENAI_API_KEY_TEST
general_settings:
store_model_in_db: true
diff --git a/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_anthropic_experimental_pass_through_messages_handler.py b/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_anthropic_experimental_pass_through_messages_handler.py
new file mode 100644
index 00000000000..ac01e495184
--- /dev/null
+++ b/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_anthropic_experimental_pass_through_messages_handler.py
@@ -0,0 +1,36 @@
+import os
+import sys
+
+import pytest
+from fastapi.testclient import TestClient
+
+sys.path.insert(0, os.path.abspath("../../../../.."))
+
+from unittest.mock import MagicMock, patch
+
+from litellm.llms.anthropic.experimental_pass_through.adapters.streaming_iterator import (
+ AnthropicStreamWrapper,
+)
+from litellm.types.utils import Delta, ModelResponse, StreamingChoices
+
+
+def test_anthropic_experimental_pass_through_messages_handler():
+ """
+ Test that api key is passed to litellm.completion
+ """
+ from litellm.llms.anthropic.experimental_pass_through.messages.handler import (
+ anthropic_messages_handler,
+ )
+
+ with patch("litellm.completion", return_value="test-response") as mock_completion:
+ try:
+ anthropic_messages_handler(
+ max_tokens=100,
+ messages=[{"role": "user", "content": "Hello, how are you?"}],
+ model="openai/claude-3-5-sonnet-20240620",
+ api_key="test-api-key",
+ )
+ except Exception as e:
+ print(f"Error: {e}")
+ mock_completion.assert_called_once()
+ mock_completion.call_args.kwargs["api_key"] == "test-api-key"