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: add MCP to Responses API and bump openai python sdk (#11029)
Ishaan Jaffdd4a65b83a7c
diff --git a/.circleci/config.yml b/.circleci/config.ymlindex 4306fa5cf05..c523b1d191e 100644--- a/.circleci/config.yml+++ b/.circleci/config.yml@@ -95,7 +95,7 @@ jobs:pip install opentelemetry-api==1.25.0pip install opentelemetry-sdk==1.25.0pip install opentelemetry-exporter-otlp==1.25.0- pip install openai==1.68.2+ pip install openai==1.81.0pip install prisma==0.11.0pip install "detect_secrets==1.5.0"pip install "httpx==0.24.1"@@ -218,7 +218,7 @@ jobs:pip install opentelemetry-api==1.25.0pip install opentelemetry-sdk==1.25.0pip install opentelemetry-exporter-otlp==1.25.0- pip install openai==1.68.2+ pip install openai==1.81.0pip install prisma==0.11.0pip install "detect_secrets==1.5.0"pip install "httpx==0.24.1"@@ -325,7 +325,7 @@ jobs:pip install opentelemetry-api==1.25.0pip install opentelemetry-sdk==1.25.0pip install opentelemetry-exporter-otlp==1.25.0- pip install openai==1.68.2+ pip install openai==1.81.0pip install prisma==0.11.0pip install "detect_secrets==1.5.0"pip install "httpx==0.24.1"@@ -581,7 +581,7 @@ jobs:pip install opentelemetry-api==1.25.0pip install opentelemetry-sdk==1.25.0pip install opentelemetry-exporter-otlp==1.25.0- pip install openai==1.68.2+ pip install openai==1.81.0pip install prisma==0.11.0pip install "detect_secrets==1.5.0"pip install "httpx==0.24.1"@@ -1472,7 +1472,7 @@ jobs:pip install "aiodynamo==23.10.1"pip install "asyncio==3.4.3"pip install "PyGithub==1.59.1"- pip install "openai==1.68.2"+ pip install "openai==1.81.0"- run:name: Install Grypecommand: |@@ -1610,7 +1610,7 @@ jobs:pip install "aiodynamo==23.10.1"pip install "asyncio==3.4.3"pip install "PyGithub==1.59.1"- pip install "openai==1.68.2"+ pip install "openai==1.81.0"# Run pytest and generate JUnit XML report- run:name: Build Docker image@@ -1733,7 +1733,7 @@ jobs:pip install "aiodynamo==23.10.1"pip install "asyncio==3.4.3"pip install "PyGithub==1.59.1"- pip install "openai==1.68.2"+ pip install "openai==1.81.0"- run:name: Build Docker imagecommand: docker build -t my-app:latest -f ./docker/Dockerfile.database .@@ -2256,7 +2256,7 @@ jobs:pip install "pytest-asyncio==0.21.1"pip install "google-cloud-aiplatform==1.43.0"pip install aiohttp- pip install "openai==1.68.2"+ pip install "openai==1.81.0"pip install "assemblyai==0.37.0"python -m pip install --upgrade pippip install "pydantic==2.10.2"@@ -2644,7 +2644,7 @@ jobs:pip install "pytest-retry==1.6.3"pip install "pytest-asyncio==0.21.1"pip install aiohttp- pip install "openai==1.68.2"+ pip install "openai==1.81.0"python -m pip install --upgrade pippip install "pydantic==2.10.2"pip install "pytest==7.3.1"diff --git a/.circleci/requirements.txt b/.circleci/requirements.txtindex 0e2362c4e3d..b720d15a7fd 100644--- a/.circleci/requirements.txt+++ b/.circleci/requirements.txt@@ -1,5 +1,5 @@# used by CI/CD testing-openai==1.68.2+openai==1.81.0python-dotenvtiktokenimportlib_metadatadiff --git a/.github/workflows/test-linting.yml b/.github/workflows/test-linting.ymlindex 0e1c895c3a4..ceeedbe7e13 100644--- a/.github/workflows/test-linting.yml+++ b/.github/workflows/test-linting.yml@@ -22,9 +22,9 @@ jobs:- name: Install dependenciesrun: |- pip install openai==1.68.2+ pip install openai==1.81.0poetry install --with dev- pip install openai==1.68.2+ pip install openai==1.81.0diff --git a/docs/my-website/docs/providers/openai/responses_api.md b/docs/my-website/docs/providers/openai/responses_api.mdindex 578ce038f37..e88512ecfd4 100644--- a/docs/my-website/docs/providers/openai/responses_api.md+++ b/docs/my-website/docs/providers/openai/responses_api.md@@ -318,3 +318,133 @@ print(response)</TabItem></Tabs>+++## MCP Tools++<Tabs>+<TabItem value="sdk" label="LiteLLM Python SDK">++```python showLineNumbers title="MCP Tools with LiteLLM SDK"+import litellm+from typing import Optional++# Configure MCP Tools+MCP_TOOLS = [+ {+ "type": "mcp",+ "server_label": "deepwiki",+ "server_url": "https://mcp.deepwiki.com/mcp",+ "allowed_tools": ["ask_question"]+ }+]++# Step 1: Make initial request - OpenAI will use MCP LIST and return MCP calls for approval+response = litellm.responses(+ model="openai/gpt-4.1",+ tools=MCP_TOOLS,+ input="What transport protocols does the 2025-03-26 version of the MCP spec support?"+)++# Get the MCP approval ID+mcp_approval_id = None+for output in response.output:+ if output.type == "mcp_approval_request":+ mcp_approval_id = output.id+ break++# Step 2: Send followup with approval for the MCP call+response_with_mcp_call = litellm.responses(+ model="openai/gpt-4.1",+ tools=MCP_TOOLS,+ input=[+ {+ "type": "mcp_approval_response",+ "approve": True,+ "approval_request_id": mcp_approval_id+ }+ ],+ previous_response_id=response.id,+)++print(response_with_mcp_call)+```++</TabItem>+<TabItem value="proxy" label="LiteLLM Proxy">++1. Set up config.yaml++```yaml showLineNumbers title="OpenAI Proxy Configuration"+model_list:+ - model_name: openai/gpt-4.1+ litellm_params:+ model: openai/gpt-4.1+ api_key: os.environ/OPENAI_API_KEY+```++2. Start LiteLLM Proxy Server++```bash title="Start LiteLLM Proxy Server"+litellm --config /path/to/config.yaml++# RUNNING on http://0.0.0.0:4000+```++3. Test it!++```python showLineNumbers title="MCP Tools with OpenAI SDK via LiteLLM Proxy"+from openai import OpenAI+from typing import Optional++# Initialize client with your proxy URL+client = OpenAI(+ base_url="http://localhost:4000", # Your proxy URL+ api_key="your-api-key" # Your proxy API key+)++# Configure MCP Tools+MCP_TOOLS = [+ {+ "type": "mcp",+ "server_label": "deepwiki",+ "server_url": "https://mcp.deepwiki.com/mcp",+ "allowed_tools": ["ask_question"]+ }+]++# Step 1: Make initial request - OpenAI will use MCP LIST and return MCP calls for approval+response = client.responses.create(+ model="openai/gpt-4.1",+ tools=MCP_TOOLS,+ input="What transport protocols does the 2025-03-26 version of the MCP spec support?"+)++# Get the MCP approval ID+mcp_approval_id = None+for output in response.output:+ if output.type == "mcp_approval_request":+ mcp_approval_id = output.id+ break++# Step 2: Send followup with approval for the MCP call+response_with_mcp_call = client.responses.create(+ model="openai/gpt-4.1",+ tools=MCP_TOOLS,+ input=[+ {+ "type": "mcp_approval_response",+ "approve": True,+ "approval_request_id": mcp_approval_id+ }+ ],+ previous_response_id=response.id,+)++print(response_with_mcp_call)+```++</TabItem>+</Tabs>++diff --git a/litellm/llms/bedrock/image/cost_calculator.py b/litellm/llms/bedrock/image/cost_calculator.pyindex 0a20b44cb38..a0dc91d7119 100644--- a/litellm/llms/bedrock/image/cost_calculator.py+++ b/litellm/llms/bedrock/image/cost_calculator.py@@ -37,5 +37,7 @@ def cost_calculator()output_cost_per_image: float = _model_info.get("output_cost_per_image") or 0.0- num_images: int = len(image_response.data)+ num_images: int = 0+ if image_response.data:+ num_images = len(image_response.data)return output_cost_per_image * num_imagesdiff --git a/litellm/llms/vertex_ai/image_generation/cost_calculator.py b/litellm/llms/vertex_ai/image_generation/cost_calculator.pyindex 2ba18c095bd..646c6080a2e 100644--- a/litellm/llms/vertex_ai/image_generation/cost_calculator.py+++ b/litellm/llms/vertex_ai/image_generation/cost_calculator.py@@ -19,5 +19,7 @@ def cost_calculator()output_cost_per_image: float = _model_info.get("output_cost_per_image") or 0.0- num_images: int = len(image_response.data)+ num_images: int = 0+ if image_response.data:+ num_images = len(image_response.data)return output_cost_per_image * num_imagesdiff --git a/litellm/responses/litellm_completion_transformation/transformation.py b/litellm/responses/litellm_completion_transformation/transformation.pyindex 5812daad462..baffca3ac68 100644--- a/litellm/responses/litellm_completion_transformation/transformation.py+++ b/litellm/responses/litellm_completion_transformation/transformation.py@@ -457,8 +457,8 @@ class LiteLLMCompletionResponsesConfig:function=ChatCompletionToolParamFunctionChunk(name=tool["name"],description=tool.get("description") or "",- parameters=tool.get("parameters", {}),- strict=tool.get("strict", False),+ parameters=dict(tool.get("parameters", {}) or {}),+ strict=tool.get("strict", False) or False,),))diff --git a/litellm/responses/streaming_iterator.py b/litellm/responses/streaming_iterator.pyindex a111fbec094..e9e41789f09 100644--- a/litellm/responses/streaming_iterator.py+++ b/litellm/responses/streaming_iterator.py@@ -44,7 +44,7 @@ class BaseResponsesAPIStreamingIterator:self.responses_api_provider_config = responses_api_provider_configself.completed_response: Optional[ResponsesAPIStreamingResponse] = Noneself.start_time = datetime.now()-+# set request kwargsself.litellm_metadata = litellm_metadataself.custom_llm_provider = custom_llm_provider@@ -330,7 +330,8 @@ class MockResponsesAPIStreamingIterator(BaseResponsesAPIStreamingIterator):def _collect_text(self, resp: ResponsesAPIResponse) -> str:out = ""for out_item in resp.output:- if out_item.type == "message":+ item_type = getattr(out_item, "type", None)+ if item_type == "message":for c in getattr(out_item, "content", []):out += c.textreturn outdiff --git a/litellm/types/llms/openai.py b/litellm/types/llms/openai.pyindex f5aa27a9eaf..367f86fd3f4 100644--- a/litellm/types/llms/openai.py+++ b/litellm/types/llms/openai.py@@ -1000,7 +1000,7 @@ class ResponsesAPIResponse(BaseLiteLLMOpenAIResponseObject):model: Optional[str]object: Optional[str]output: Union[- List[ResponseOutputItem],+ List[Union[ResponseOutputItem, Dict]],List[Union[GenericResponseOutputItem, OutputFunctionToolCall]],]parallel_tool_calls: booldiff --git a/litellm/types/utils.py b/litellm/types/utils.pyindex 4d23ec0f395..a9acce9a797 100644--- a/litellm/types/utils.py+++ b/litellm/types/utils.py@@ -33,6 +33,7 @@ from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, model_validatorfrom typing_extensions import Callable, Dict, Required, TypedDict, overrideimport litellm+from litellm.types.llms.base import BaseLiteLLMOpenAIResponseObjectfrom ..litellm_core_utils.core_helpers import map_finish_reasonfrom .guardrails import GuardrailEventHooks@@ -1542,19 +1543,46 @@ class ImageObject(OpenAIImage):return self.dict()+class ImageUsageInputTokensDetails(BaseLiteLLMOpenAIResponseObject):+ image_tokens: int+ """The number of image tokens in the input prompt."""++ text_tokens: int+ """The number of text tokens in the input prompt."""+++class ImageUsage(BaseLiteLLMOpenAIResponseObject):+ input_tokens: int+ """The number of tokens (images and text) in the input prompt."""++ input_tokens_details: ImageUsageInputTokensDetails+ """The input tokens detailed information for the image generation."""++ output_tokens: int+ """The number of image tokens in the output image."""++ total_tokens: int+ """The total number of tokens (images and text) used for the image generation."""++from openai.types.images_response import ImagesResponse as OpenAIImageResponse-class ImageResponse(OpenAIImageResponse):+class ImageResponse(OpenAIImageResponse, BaseLiteLLMOpenAIResponseObject):_hidden_params: dict = {}- usage: Usage++ usage: Optional[ImageUsage] = None # type: ignore+ """+ Users might use litellm with older python versions, we don't want this to break for them.+ Happens when their OpenAIImageResponse has the old OpenAI usage class.+ """def __init__(self,created: Optional[int] = None,data: Optional[List[ImageObject]] = None,response_ms=None,- usage: Optional[Usage] = None,+ usage: Optional[ImageUsage] = None,hidden_params: Optional[dict] = None,):if response_ms:@@ -1577,9 +1605,14 @@ class ImageResponse(OpenAIImageResponse):_data.append(ImageObject(**d))elif isinstance(d, BaseModel):_data.append(ImageObject(**d.model_dump()))- _usage = usage or Usage(- prompt_tokens=0,- completion_tokens=0,++ _usage = usage or ImageUsage(+ input_tokens=0,+ input_tokens_details=ImageUsageInputTokensDetails(+ image_tokens=0,+ text_tokens=0,+ ),+ output_tokens=0,total_tokens=0,)super().__init__(created=created, data=_data, usage=_usage) # type: ignorediff --git a/poetry.lock b/poetry.lockindex 9c361b597d5..2bd91505cb2 100644--- a/poetry.lock+++ b/poetry.lock@@ -4935,4 +4935,4 @@ utils = ["numpydoc"][metadata]lock-version = "2.1"python-versions = ">=3.8.1,<4.0, !=3.9.7"-content-hash = "4c385d4e27013d9cacf9573f5532c5e13d22fc27af6344e87ba2417340c9be93"+content-hash = "15bad8ae37c1e7cf21555b0023150bfd4bd7d6d548828f6c65a66283d14a189b"diff --git a/pyproject.toml b/pyproject.tomlindex 2607937e7b1..6a5ed32e6e9 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -21,7 +21,7 @@ Documentation = "https://docs.litellm.ai"[tool.poetry.dependencies]python = ">=3.8.1,<4.0, !=3.9.7"httpx = ">=0.23.0"-openai = ">=1.68.2, <1.76.0"+openai = ">=1.68.2"python-dotenv = ">=0.2.0"tiktoken = ">=0.7.0"importlib-metadata = ">=6.8.0"diff --git a/requirements.txt b/requirements.txtindex db040686f1e..e3aae6f90fc 100644--- a/requirements.txt+++ b/requirements.txt@@ -1,7 +1,7 @@# LITELLM PROXY DEPENDENCIES #anyio==4.5.0 # openai + http req.httpx==0.27.0 # Pin Httpx dependency-openai==1.68.2 # openai req.+openai==1.81.0 # openai req.fastapi==0.115.5 # server depbackoff==2.2.1 # server deppyyaml==6.0.2 # server depdiff --git a/tests/image_gen_tests/base_image_generation_test.py b/tests/image_gen_tests/base_image_generation_test.pyindex df64d353c71..c3a5cfb2251 100644--- a/tests/image_gen_tests/base_image_generation_test.py+++ b/tests/image_gen_tests/base_image_generation_test.py@@ -68,10 +68,17 @@ class BaseImageGenTest(ABC):assert logged_standard_logging_payload is not Noneassert logged_standard_logging_payload["response_cost"] is not Noneassert logged_standard_logging_payload["response_cost"] > 0-+ import openaifrom openai.types.images_response import ImagesResponse- ImagesResponse.model_validate(response.model_dump())+ # print openai version+ print("openai version=", openai.__version__)++ response_dict = dict(response)+ if "usage" in response_dict:+ response_dict["usage"] = dict(response_dict["usage"])+ print("response usage=", response_dict.get("usage"))+ ImagesResponse.model_validate(response_dict)for d in response.data:assert isinstance(d, Image)diff --git a/tests/llm_responses_api_testing/test_openai_responses_api.py b/tests/llm_responses_api_testing/test_openai_responses_api.pyindex 333f99f9d46..4c3998e0c31 100644--- a/tests/llm_responses_api_testing/test_openai_responses_api.py+++ b/tests/llm_responses_api_testing/test_openai_responses_api.py@@ -2,7 +2,7 @@ import osimport sysimport pytestimport asyncio-from typing import Optional+from typing import Optional, castfrom unittest.mock import patch, AsyncMocksys.path.insert(0, os.path.abspath("../.."))@@ -1032,4 +1032,51 @@ def test_basic_computer_use_preview_tool_call():# Validate the input formatassert isinstance(request_body["input"], str)assert request_body["input"] == "Check the latest OpenAI news on bing.com."-\ No newline at end of file++++def test_mcp_tools_with_responses_api():+ litellm._turn_on_debug()+ MCP_TOOLS = [+ {+ "type": "mcp",+ "server_label": "deepwiki",+ "server_url": "https://mcp.deepwiki.com/mcp",+ "allowed_tools": ["ask_question"]+ }+ ]+ MODEL = "openai/gpt-4.1"+ USER_QUERY = "What transport protocols does the 2025-03-26 version of the MCP spec (modelcontextprotocol/modelcontextprotocol) support?"+ #########################################################+ # Step 1: OpenAI will use MCP LIST, and return a list of MCP calls for our approval+ response = litellm.responses(+ model=MODEL,+ tools=MCP_TOOLS,+ input=USER_QUERY+ )+ print(response)++ response = cast(ResponsesAPIResponse, response)++ mcp_approval_id: Optional[str]+ for output in response.output:+ if output.type == "mcp_approval_request":+ mcp_approval_id = output.id+ break++ # Step 2: Send followup with approval for the MCP call+ response_with_mcp_call = litellm.responses(+ model=MODEL,+ tools=MCP_TOOLS,+ input=[+ {+ "type": "mcp_approval_response",+ "approve": True,+ "approval_request_id": mcp_approval_id+ }+ ],+ previous_response_id=response.id,+ )+ print(response_with_mcp_call)++