diff --git a/src/openai/lib/azure.py b/src/openai/lib/azure.py index 4fcae24788..08ef97663f 100644 --- a/src/openai/lib/azure.py +++ b/src/openai/lib/azure.py @@ -72,8 +72,15 @@ def _build_request( ) -> httpx.Request: if options.url in _deployments_endpoints and is_mapping(options.json_data): model = options.json_data.get("model") - if model is not None and "/deployments" not in str(self.base_url.path): + uses_deployment_path = "/deployments" in str(self.base_url.path) + if model is not None and not uses_deployment_path: + options = model_copy(options) options.url = f"/deployments/{model}{options.url}" + uses_deployment_path = True + + if uses_deployment_path and "model" in options.json_data: + options = model_copy(options) + options.json_data = {key: value for key, value in options.json_data.items() if key != "model"} return super()._build_request(options, retries_taken=retries_taken) diff --git a/tests/lib/test_azure.py b/tests/lib/test_azure.py index 3e1d783e2c..fe3fd7427e 100644 --- a/tests/lib/test_azure.py +++ b/tests/lib/test_azure.py @@ -1,5 +1,6 @@ from __future__ import annotations +import json import logging from typing import Union, cast from typing_extensions import Literal, Protocol @@ -540,6 +541,47 @@ def test_prepare_url_deployment_endpoint( assert client.base_url == base_url +@pytest.mark.parametrize( + "client", + [ + AzureOpenAI( + api_version="2024-10-21", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com", + ), + AsyncAzureOpenAI( + api_version="2024-10-21", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com", + ), + ], +) +def test_deployment_endpoint_strips_model_from_request_body(client: Client) -> None: + body = { + "model": "gpt-image-1-5", + "prompt": "A sunset over mountains", + "size": "1024x1024", + } + + req = client._build_request( + FinalRequestOptions.construct( + method="post", + url="/images/generations", + json_data=body, + ) + ) + + assert req.url == httpx.URL( + "https://example-resource.azure.openai.com/openai/deployments/" + "gpt-image-1-5/images/generations?api-version=2024-10-21" + ) + assert json.loads(req.content) == { + "prompt": "A sunset over mountains", + "size": "1024x1024", + } + assert body["model"] == "gpt-image-1-5" + + @pytest.mark.parametrize( "client,base_url,api,json_data,expected", [