Buckets:

download
raw
60.2 kB
import asyncio import json import time from collections.abc import Callable, Coroutine from typing import Final import httpx from openai import ( APITimeoutError, AsyncAzureOpenAI, AsyncOpenAI, AzureOpenAI, BadRequestError, OpenAI, ) import litellm from litellm.constants import AZURE_OPERATION_POLLING_TIMEOUT, DEFAULT_MAX_RETRIES from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj from litellm.litellm_core_utils.logging_utils import speech_request_body, track_llm_api_timing from litellm.litellm_core_utils.url_utils import SSRFError, assert_same_origin from litellm.llms.custom_httpx.http_handler import ( AsyncHTTPHandler, HTTPHandler, get_async_httpx_client, ) from litellm.types.utils import ( EmbeddingResponse, ImageResponse, LlmProviders, ModelResponse, ) from litellm.utils import ( CustomStreamWrapper, convert_to_model_response_object, modify_url, ) from ...types.llms.openai import HttpxBinaryResponseContent from ..base import BaseLLM from ..openai.common_utils import ( build_output_token_limit_response, is_output_token_limit_error, ) from .common_utils import ( AzureOpenAIError, BaseAzureLLM, get_azure_ad_token_from_oidc, process_azure_headers, select_azure_base_url_or_endpoint, ) from .image_generation import ( AzureFoundryMAIImageGenerationConfig, get_azure_image_generation_config, ) from .image_generation.http_utils import azure_deployment_image_generation_json_body class AzureOpenAIAssistantsAPIConfig: """ Reference: https://learn.microsoft.com/en-us/azure/ai-services/openai/assistants-reference-messages?tabs=python#create-message """ def __init__( self, ) -> None: pass def get_supported_openai_create_message_params(self): return [ "role", "content", "attachments", "metadata", ] def map_openai_params_create_message_params(self, non_default_params: dict, optional_params: dict): for param, value in non_default_params.items(): if param == "role": optional_params["role"] = value if param == "metadata": optional_params["metadata"] = value elif param == "content": # only string accepted if isinstance(value, str): optional_params["content"] = value else: raise litellm.utils.UnsupportedParamsError( message="Azure only accepts content as a string.", status_code=400, ) elif param == "attachments": # this is a v2 param. Azure currently supports the old 'file_id's param file_ids: list[str] = [] if isinstance(value, list): for item in value: if "file_id" in item: file_ids.append(item["file_id"]) else: if litellm.drop_params is True: pass else: raise litellm.utils.UnsupportedParamsError( message=f"Azure doesn't support {value}. To drop it from the call, set `litellm.drop_params = True.", status_code=400, ) else: raise litellm.utils.UnsupportedParamsError( message=f"Invalid param. attachments should always be a list. Got={type(value)}, Expected=List. Raw value={value}", status_code=400, ) return optional_params def _check_dynamic_azure_params( azure_client_params: dict, azure_client: AzureOpenAI | AsyncAzureOpenAI | None, ) -> bool: """ Returns True if user passed in client params != initialized azure client Currently only implemented for api version """ if azure_client is None: return True dynamic_params: Final = ["api_version"] for k, v in azure_client_params.items(): if k in dynamic_params and k == "api_version": if v is not None and v != azure_client._custom_query["api-version"]: return True return False class AzureChatCompletion(BaseAzureLLM, BaseLLM): def __init__(self) -> None: super().__init__() def make_sync_azure_openai_chat_completion_request( self, azure_client: AzureOpenAI | OpenAI, data: dict, timeout: float | httpx.Timeout, ): """ Helper to: - call chat.completions.create.with_raw_response when litellm.return_response_headers is True - call chat.completions.create by default """ try: raw_response: Final = azure_client.chat.completions.with_raw_response.create(**data, timeout=timeout) headers: Final = dict(raw_response.headers) response: Final = raw_response.parse() return headers, response except BadRequestError as e: if not is_output_token_limit_error(e): raise return build_output_token_limit_response(e=e, data=data, is_async=False) except Exception as e: raise e @track_llm_api_timing() async def make_azure_openai_chat_completion_request( self, azure_client: AsyncAzureOpenAI | AsyncOpenAI, data: dict, timeout: float | httpx.Timeout, logging_obj: LiteLLMLoggingObj, ): """ Helper to: - call chat.completions.create.with_raw_response when litellm.return_response_headers is True - call chat.completions.create by default """ start_time: Final = time.time() try: raw_response: Final = await azure_client.chat.completions.with_raw_response.create(**data, timeout=timeout) headers: Final = dict(raw_response.headers) response: Final = raw_response.parse() return headers, response except APITimeoutError as e: end_time: Final = time.time() time_delta: Final = round(end_time - start_time, 2) e.message += f" - timeout value={timeout}, time taken={time_delta} seconds" raise e except BadRequestError as e: if not is_output_token_limit_error(e): raise return build_output_token_limit_response(e=e, data=data, is_async=True) except Exception as e: raise e def completion( self, model: str, messages: list, model_response: ModelResponse, api_key: str | None, api_base: str, api_version: str, api_type: str, azure_ad_token: str | None, azure_ad_token_provider: Callable | None, dynamic_params: bool, print_verbose: Callable, timeout: float | httpx.Timeout, logging_obj: LiteLLMLoggingObj, optional_params, litellm_params, logger_fn, acompletion: bool = False, headers: dict | None = None, client=None, ): if headers: optional_params["extra_headers"] = headers try: if model is None or messages is None: raise AzureOpenAIError(status_code=422, message="Missing model or messages") max_retries = optional_params.pop("max_retries", None) if max_retries is None: max_retries = DEFAULT_MAX_RETRIES json_mode: Final[bool | None] = optional_params.pop("json_mode", False) ### CHECK IF CLOUDFLARE AI GATEWAY ### ### if so - set the model as part of the base url if api_base is not None and "gateway.ai.cloudflare.com" in api_base: client = self._init_azure_client_for_cloudflare_ai_gateway( api_base=api_base, model=model, api_version=api_version, max_retries=max_retries, timeout=timeout, api_key=api_key, azure_ad_token=azure_ad_token, azure_ad_token_provider=azure_ad_token_provider, acompletion=acompletion, client=client, litellm_params=litellm_params, ) data: dict[str, object] = {"model": None, "messages": messages, **optional_params} elif litellm.AzureOpenAIGPT5Config.is_model_gpt_5_model(model=litellm_params.get("base_model") or model): data = litellm.AzureOpenAIGPT5Config().transform_request( model=model, messages=messages, optional_params=optional_params, litellm_params=litellm_params, headers=headers or {}, ) else: data = litellm.AzureOpenAIConfig().transform_request( model=model, messages=messages, optional_params=optional_params, litellm_params=litellm_params, headers=headers or {}, ) if acompletion is True: if optional_params.get("stream", False): return self.async_streaming( logging_obj=logging_obj, api_base=api_base, dynamic_params=dynamic_params, data=data, model=model, api_key=api_key, api_version=api_version, azure_ad_token=azure_ad_token, azure_ad_token_provider=azure_ad_token_provider, timeout=timeout, client=client, max_retries=max_retries, litellm_params=litellm_params, ) else: return self.acompletion( api_base=api_base, data=data, model_response=model_response, api_key=api_key, api_version=api_version, model=model, azure_ad_token=azure_ad_token, azure_ad_token_provider=azure_ad_token_provider, dynamic_params=dynamic_params, timeout=timeout, client=client, logging_obj=logging_obj, max_retries=max_retries, convert_tool_call_to_json_mode=json_mode, litellm_params=litellm_params, ) elif "stream" in optional_params and optional_params["stream"] is True: return self.streaming( logging_obj=logging_obj, api_base=api_base, dynamic_params=dynamic_params, data=data, model=model, api_key=api_key, api_version=api_version, azure_ad_token=azure_ad_token, azure_ad_token_provider=azure_ad_token_provider, timeout=timeout, client=client, max_retries=max_retries, litellm_params=litellm_params, ) else: ## LOGGING logging_obj.pre_call( input=messages, api_key=api_key, additional_args={ "headers": { "api_key": api_key, "azure_ad_token": azure_ad_token, }, "api_version": api_version, "api_base": api_base, "complete_input_dict": data, }, ) if not isinstance(max_retries, int): raise AzureOpenAIError(status_code=422, message="max retries must be an int") # init AzureOpenAI Client azure_client: Final = self.get_azure_openai_client( api_version=api_version, api_base=api_base, api_key=api_key, model=model, client=client, _is_async=False, litellm_params=litellm_params, ) if not isinstance(azure_client, (AzureOpenAI, OpenAI)): raise AzureOpenAIError( status_code=500, message="azure_client is not an instance of AzureOpenAI or OpenAI", ) headers, response = self.make_sync_azure_openai_chat_completion_request( azure_client=azure_client, data=data, timeout=timeout ) if isinstance(response, str): raise AzureOpenAIError( status_code=500, message=f"Unexpected string response from Azure: {response[:500]}", ) stringified_response: Final = response.model_dump() ## LOGGING logging_obj.post_call( input=messages, api_key=api_key, original_response=stringified_response, additional_args={ "headers": headers, "api_version": api_version, "api_base": api_base, }, ) return convert_to_model_response_object( response_object=stringified_response, model_response_object=model_response, convert_tool_call_to_json_mode=json_mode, _response_headers=headers, ) except AzureOpenAIError as e: raise e except Exception as e: status_code: Final = getattr(e, "status_code", 500) error_headers = getattr(e, "headers", None) error_response: Final[object] = getattr(e, "response", None) error_body: Final = getattr(e, "body", None) if error_headers is None and error_response: error_headers = getattr(error_response, "headers", None) raise AzureOpenAIError( status_code=status_code, message=str(e), headers=error_headers, body=error_body, ) async def acompletion( self, api_key: str | None, api_version: str, model: str, api_base: str, data: dict, timeout: float | httpx.Timeout, dynamic_params: bool, model_response: ModelResponse, logging_obj: LiteLLMLoggingObj, max_retries: int, azure_ad_token: str | None = None, azure_ad_token_provider: Callable | None = None, convert_tool_call_to_json_mode: bool | None = None, client=None, # this is the AsyncAzureOpenAI litellm_params: dict | None = {}, ): response = None try: # setting Azure client azure_client: Final = self.get_azure_openai_client( api_version=api_version, api_base=api_base, api_key=api_key, model=model, client=client, _is_async=True, litellm_params=litellm_params, ) if not isinstance(azure_client, (AsyncAzureOpenAI, AsyncOpenAI)): raise ValueError("Azure client is not an instance of AsyncAzureOpenAI or AsyncOpenAI") ## LOGGING logging_obj.pre_call( input=data["messages"], api_key=azure_client.api_key, additional_args={ "headers": { "api_key": api_key, "azure_ad_token": azure_ad_token, }, "api_base": api_base, "acompletion": True, "complete_input_dict": data, }, ) headers, response = await self.make_azure_openai_chat_completion_request( azure_client=azure_client, data=data, timeout=timeout, logging_obj=logging_obj, ) logging_obj.model_call_details["response_headers"] = headers if isinstance(response, str): raise AzureOpenAIError( status_code=500, message=f"Unexpected string response from Azure: {response[:500]}", ) stringified_response: Final = response.model_dump() logging_obj.post_call( input=data["messages"], api_key=api_key, original_response=stringified_response, additional_args={"complete_input_dict": data}, ) return convert_to_model_response_object( response_object=stringified_response, model_response_object=model_response, hidden_params={"headers": headers}, _response_headers=headers, convert_tool_call_to_json_mode=convert_tool_call_to_json_mode, ) except AzureOpenAIError as e: ## LOGGING logging_obj.post_call( input=data["messages"], api_key=api_key, additional_args={"complete_input_dict": data}, original_response=str(e), ) raise e except asyncio.CancelledError as e: ## LOGGING logging_obj.post_call( input=data["messages"], api_key=api_key, additional_args={"complete_input_dict": data}, original_response=str(e), ) raise AzureOpenAIError(status_code=500, message=str(e)) except Exception as e: message: Final = getattr(e, "message", str(e)) body: Final = getattr(e, "body", None) ## LOGGING logging_obj.post_call( input=data["messages"], api_key=api_key, additional_args={"complete_input_dict": data}, original_response=str(e), ) if hasattr(e, "status_code"): raise e else: raise AzureOpenAIError(status_code=500, message=message, body=body) def streaming( self, logging_obj: LiteLLMLoggingObj, api_base: str, api_key: str | None, api_version: str, dynamic_params: bool, data: dict[str, object], model: str, timeout: float | httpx.Timeout, max_retries: int, azure_ad_token: str | None = None, azure_ad_token_provider: Callable | None = None, client=None, litellm_params: dict | None = {}, ): # init AzureOpenAI Client azure_client_params = { "api_version": api_version, "azure_endpoint": api_base, "azure_deployment": model, "http_client": litellm.client_session, "max_retries": max_retries, "timeout": timeout, } azure_client_params = select_azure_base_url_or_endpoint(azure_client_params=azure_client_params) if api_key is not None: azure_client_params["api_key"] = api_key elif azure_ad_token is not None: if azure_ad_token.startswith("oidc/"): azure_ad_token = get_azure_ad_token_from_oidc(azure_ad_token) azure_client_params["azure_ad_token"] = azure_ad_token elif azure_ad_token_provider is not None: azure_client_params["azure_ad_token_provider"] = azure_ad_token_provider azure_client: Final = self.get_azure_openai_client( api_version=api_version, api_base=api_base, api_key=api_key, model=model, client=client, _is_async=False, litellm_params=litellm_params, ) if not isinstance(azure_client, (AzureOpenAI, OpenAI)): raise AzureOpenAIError( status_code=500, message="azure_client is not an instance of AzureOpenAI or OpenAI", ) ## LOGGING logging_obj.pre_call( input=data["messages"], api_key=azure_client.api_key, additional_args={ "headers": { "api_key": api_key, "azure_ad_token": azure_ad_token, }, "api_base": api_base, "acompletion": True, "complete_input_dict": data, }, ) headers, response = self.make_sync_azure_openai_chat_completion_request( azure_client=azure_client, data=data, timeout=timeout ) streamwrapper: Final = CustomStreamWrapper( completion_stream=response, model=model, custom_llm_provider="azure", logging_obj=logging_obj, stream_options=data.get("stream_options", None), _response_headers=process_azure_headers(headers), ) return streamwrapper async def async_streaming( self, logging_obj: LiteLLMLoggingObj, api_base: str, api_key: str | None, api_version: str, dynamic_params: bool, data: dict, model: str, timeout: float | httpx.Timeout, max_retries: int, azure_ad_token: str | None = None, azure_ad_token_provider: Callable | None = None, client=None, litellm_params: dict | None = {}, ): try: azure_client: Final = self.get_azure_openai_client( api_version=api_version, api_base=api_base, api_key=api_key, model=model, client=client, _is_async=True, litellm_params=litellm_params, ) if not isinstance(azure_client, (AsyncAzureOpenAI, AsyncOpenAI)): raise ValueError("Azure client is not an instance of AsyncAzureOpenAI or AsyncOpenAI") ## LOGGING logging_obj.pre_call( input=data["messages"], api_key=azure_client.api_key, additional_args={ "headers": { "api_key": api_key, "azure_ad_token": azure_ad_token, }, "api_base": api_base, "acompletion": True, "complete_input_dict": data, }, ) headers, response = await self.make_azure_openai_chat_completion_request( azure_client=azure_client, data=data, timeout=timeout, logging_obj=logging_obj, ) logging_obj.model_call_details["response_headers"] = headers # return response streamwrapper: Final = CustomStreamWrapper( completion_stream=response, model=model, custom_llm_provider="azure", logging_obj=logging_obj, stream_options=data.get("stream_options", None), _response_headers=headers, ) return streamwrapper ## DO NOT make this into an async for ... loop, it will yield an async generator, which won't raise errors if the response fails except Exception as e: status_code: Final = getattr(e, "status_code", 500) error_headers = getattr(e, "headers", None) error_response: Final[object] = getattr(e, "response", None) message: Final = getattr(e, "message", str(e)) error_body: Final = getattr(e, "body", None) if error_headers is None and error_response: error_headers = getattr(error_response, "headers", None) raise AzureOpenAIError( status_code=status_code, message=message, headers=error_headers, body=error_body, ) async def aembedding( self, model: str, data: dict, model_response: EmbeddingResponse, input: list, logging_obj: LiteLLMLoggingObj, api_base: str, api_key: str | None = None, api_version: str | None = None, client: AsyncAzureOpenAI | None = None, timeout: float | httpx.Timeout | None = None, max_retries: int | None = None, azure_ad_token: str | None = None, azure_ad_token_provider: Callable | None = None, litellm_params: dict | None = {}, ) -> EmbeddingResponse: response = None try: openai_aclient: Final = self.get_azure_openai_client( api_version=api_version, api_base=api_base, api_key=api_key, model=model, _is_async=True, client=client, litellm_params=litellm_params, ) if not isinstance(openai_aclient, (AsyncAzureOpenAI, AsyncOpenAI)): raise ValueError("Azure client is not an instance of AsyncAzureOpenAI or AsyncOpenAI") raw_response: Final = await openai_aclient.embeddings.with_raw_response.create(**data, timeout=timeout) headers: Final = dict(raw_response.headers) # Convert json.JSONDecodeError to AzureOpenAIError for two critical reasons: # # 1. ROUTER BEHAVIOR: The router relies on exception.status_code to determine cooldown logic: # - JSONDecodeError has no status_code → router skips cooldown evaluation # - AzureOpenAIError has status_code → router properly evaluates for cooldown # # 2. CONNECTION CLEANUP: When response.parse() throws JSONDecodeError, the response # body may not be fully consumed, preventing httpx from properly returning the # connection to the pool. By catching the exception and accessing raw_response.status_code, # we trigger httpx's internal cleanup logic. Without this: # - parse() fails → JSONDecodeError bubbles up → httpx never knows response was acknowledged → connection leak # This completely eliminates "Unclosed connection" warnings during high load. try: response = raw_response.parse() except json.JSONDecodeError as json_error: raise AzureOpenAIError( status_code=raw_response.status_code or 500, message=f"Failed to parse raw Azure embedding response: {json_error}", ) from json_error if isinstance(response, str): raise AzureOpenAIError( status_code=raw_response.status_code or 500, message=f"Unexpected string response from Azure: {response[:500]}", ) stringified_response: Final = response.model_dump() ## LOGGING logging_obj.post_call( input=input, api_key=api_key, additional_args={"complete_input_dict": data}, original_response=stringified_response, ) embedding_response: Final = convert_to_model_response_object( response_object=stringified_response, model_response_object=model_response, hidden_params={"headers": headers}, _response_headers=process_azure_headers(headers), response_type="embedding", ) if not isinstance(embedding_response, EmbeddingResponse): raise AzureOpenAIError( status_code=500, message="embedding_response is not an instance of EmbeddingResponse", ) return embedding_response except Exception as e: ## LOGGING logging_obj.post_call( input=input, api_key=api_key, additional_args={"complete_input_dict": data}, original_response=str(e), ) raise e def embedding( self, model: str, input: list, api_base: str, api_version: str, timeout: float, logging_obj: LiteLLMLoggingObj, model_response: EmbeddingResponse, optional_params: dict, api_key: str | None = None, azure_ad_token: str | None = None, azure_ad_token_provider: Callable | None = None, max_retries: int | None = None, client=None, aembedding=None, headers: dict | None = None, litellm_params: dict | None = None, ) -> EmbeddingResponse | Coroutine[object, object, EmbeddingResponse]: if headers: optional_params["extra_headers"] = headers if self._client_session is None: self._client_session = self.create_client_session() try: data: Final = {"model": model, "input": input, **optional_params} if max_retries is None: max_retries = litellm.DEFAULT_MAX_RETRIES ## LOGGING logging_obj.pre_call( input=input, api_key=api_key, additional_args={ "complete_input_dict": data, "headers": {"api_key": api_key, "azure_ad_token": azure_ad_token}, }, ) if aembedding is True: return self.aembedding( data=data, input=input, model=model, logging_obj=logging_obj, api_key=api_key, model_response=model_response, timeout=timeout, client=client, litellm_params=litellm_params, api_base=api_base, api_version=api_version, ) azure_client: Final = self.get_azure_openai_client( api_version=api_version, api_base=api_base, api_key=api_key, model=model, _is_async=False, client=client, litellm_params=litellm_params, ) if not isinstance(azure_client, (AzureOpenAI, OpenAI)): raise AzureOpenAIError( status_code=500, message="azure_client is not an instance of AzureOpenAI or OpenAI", ) ## COMPLETION CALL raw_response = azure_client.embeddings.with_raw_response.create(**data, timeout=timeout) headers = dict(raw_response.headers) response: Final = raw_response.parse() if isinstance(response, str): raise AzureOpenAIError( status_code=raw_response.status_code or 500, message=f"Unexpected string response from Azure: {response[:500]}", ) ## LOGGING logging_obj.post_call( input=input, api_key=api_key, additional_args={"complete_input_dict": data, "api_base": api_base}, original_response=response, ) return convert_to_model_response_object( response_object=response.model_dump(), model_response_object=model_response, response_type="embedding", _response_headers=process_azure_headers(headers), ) except AzureOpenAIError as e: raise e except Exception as e: status_code: Final = getattr(e, "status_code", 500) error_headers = getattr(e, "headers", None) error_response: Final = getattr(e, "response", None) error_text = str(e) if error_headers is None and error_response: error_headers = getattr(error_response, "headers", None) error_text = error_response.text raise AzureOpenAIError(status_code=status_code, message=error_text, headers=error_headers) async def make_async_azure_httpx_request( self, client: AsyncHTTPHandler | None, timeout: float | httpx.Timeout | None, api_base: str, api_version: str, api_key: str, data: dict, headers: dict, deployment_name: str | None = None, ) -> httpx.Response: """ Implemented for azure dall-e-2 image gen calls Alternative to needing a custom transport implementation """ if client is None: _params: Final = {} if timeout is not None: if isinstance(timeout, float) or isinstance(timeout, int): _httpx_timeout: Final = httpx.Timeout(timeout) _params["timeout"] = _httpx_timeout else: _params["timeout"] = httpx.Timeout(timeout=600.0, connect=5.0) async_handler = get_async_httpx_client( llm_provider=LlmProviders.AZURE, params=_params, ) else: async_handler = client if ( "images/generations" in api_base and api_version in [ # dall-e-3 starts from `2023-12-01-preview` so we should be able to avoid conflict "2023-06-01-preview", "2023-07-01-preview", "2023-08-01-preview", "2023-09-01-preview", "2023-10-01-preview", ] ): # CREATE + POLL for azure dall-e-2 calls api_base = modify_url(original_url=api_base, new_path="/openai/images/generations:submit") data.pop( "model", None ) # REMOVE 'model' from dall-e-2 arg https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#request-a-generated-image-dall-e-2-preview response = await async_handler.post( url=api_base, data=json.dumps(data), headers=headers, ) if "operation-location" in response.headers: operation_location_url: Final = response.headers["operation-location"] else: raise AzureOpenAIError(status_code=500, message=response.text) # Reject polling URLs that don't share an origin with ``api_base``. # Without this an upstream-controlled or attacker-controlled # value would receive the operator's Azure API key in the # request headers below. VERIA-51. try: assert_same_origin(operation_location_url, api_base) except SSRFError as ssrf_err: raise AzureOpenAIError( status_code=502, message=f"Rejected polling URL: {ssrf_err}", ) response = await async_handler.get( url=operation_location_url, headers=headers, ) await response.aread() timeout_secs: Final[int] = AZURE_OPERATION_POLLING_TIMEOUT start_time: Final = time.time() if "status" not in response.json(): # Don't reflect the raw response body — when the polling # URL points at an internal JSON API (cloud metadata # service etc.) reflecting it here turns Blind SSRF into # Full-Read SSRF. VERIA-51. raise AzureOpenAIError( status_code=502, message="Polling response missing 'status' field", ) while response.json()["status"] not in ["succeeded", "failed"]: if time.time() - start_time > timeout_secs: raise AzureOpenAIError(status_code=408, message="Operation polling timed out.") await asyncio.sleep(int(response.headers.get("retry-after") or 10)) response = await async_handler.get( url=operation_location_url, headers=headers, ) await response.aread() if response.json()["status"] == "failed": error_data: Final = response.json() # Preserve Azure error details (e.g. content_policy_violation, # inner_error, content_filter_results) as structured body so # exception_type() can route them correctly. _error_body: Final = error_data.get("error", error_data) _error_msg: Final = ( _error_body.get("message", "Image generation failed") if isinstance(_error_body, dict) else json.dumps(error_data) ) raise AzureOpenAIError( status_code=400, message=_error_msg, body=error_data, ) result: Final = response.json()["result"] return httpx.Response( status_code=200, headers=response.headers, content=json.dumps(result).encode("utf-8"), request=httpx.Request(method="POST", url="https://api.openai.com/v1"), ) request_json: Final = azure_deployment_image_generation_json_body(api_base, data, deployment_name) return await async_handler.post( url=api_base, json=request_json, headers=headers, ) def make_sync_azure_httpx_request( self, client: HTTPHandler | None, timeout: float | httpx.Timeout | None, api_base: str, api_version: str, api_key: str, data: dict, headers: dict, deployment_name: str | None = None, ) -> httpx.Response: """ Implemented for azure dall-e-2 image gen calls Alternative to needing a custom transport implementation """ if client is None: _params: Final = {} if timeout is not None: if isinstance(timeout, float) or isinstance(timeout, int): _httpx_timeout: Final = httpx.Timeout(timeout) _params["timeout"] = _httpx_timeout else: _params["timeout"] = httpx.Timeout(timeout=600.0, connect=5.0) sync_handler = HTTPHandler(**_params, client=litellm.client_session) else: sync_handler = client if ( "images/generations" in api_base and api_version in [ # dall-e-3 starts from `2023-12-01-preview` so we should be able to avoid conflict "2023-06-01-preview", "2023-07-01-preview", "2023-08-01-preview", "2023-09-01-preview", "2023-10-01-preview", ] ): # CREATE + POLL for azure dall-e-2 calls api_base = modify_url(original_url=api_base, new_path="/openai/images/generations:submit") data.pop( "model", None ) # REMOVE 'model' from dall-e-2 arg https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#request-a-generated-image-dall-e-2-preview response = sync_handler.post( url=api_base, data=json.dumps(data), headers=headers, ) if "operation-location" in response.headers: operation_location_url: Final = response.headers["operation-location"] else: raise AzureOpenAIError(status_code=500, message=response.text) try: assert_same_origin(operation_location_url, api_base) except SSRFError as ssrf_err: raise AzureOpenAIError( status_code=502, message=f"Rejected polling URL: {ssrf_err}", ) response = sync_handler.get( url=operation_location_url, headers=headers, ) response.read() timeout_secs: Final[int] = AZURE_OPERATION_POLLING_TIMEOUT start_time: Final = time.time() if "status" not in response.json(): raise AzureOpenAIError( status_code=502, message="Polling response missing 'status' field", ) while response.json()["status"] not in ["succeeded", "failed"]: if time.time() - start_time > timeout_secs: raise AzureOpenAIError(status_code=408, message="Operation polling timed out.") time.sleep(int(response.headers.get("retry-after") or 10)) response = sync_handler.get( url=operation_location_url, headers=headers, ) response.read() if response.json()["status"] == "failed": error_data: Final = response.json() # Preserve Azure error details (e.g. content_policy_violation, # inner_error, content_filter_results) as structured body so # exception_type() can route them correctly. _error_body: Final = error_data.get("error", error_data) _error_msg: Final = ( _error_body.get("message", "Image generation failed") if isinstance(_error_body, dict) else json.dumps(error_data) ) raise AzureOpenAIError( status_code=400, message=_error_msg, body=error_data, ) result: Final = response.json()["result"] return httpx.Response( status_code=200, headers=response.headers, content=json.dumps(result).encode("utf-8"), request=httpx.Request(method="POST", url="https://api.openai.com/v1"), ) request_json: Final = azure_deployment_image_generation_json_body(api_base, data, deployment_name) return sync_handler.post( url=api_base, json=request_json, headers=headers, ) def create_azure_base_url( self, azure_client_params: dict, model: str | None, base_model: str | None = None, ) -> str: from litellm.llms.azure_ai.image_generation import ( AzureFoundryFluxImageGenerationConfig, AzureFoundryMAIImageGenerationConfig, ) # deployment-scoped endpoints are moved to "base_url" by select_azure_base_url_or_endpoint api_base: str = (azure_client_params.get("azure_endpoint") or azure_client_params.get("base_url") or "").rstrip( "/" ) api_version: Final[str] = azure_client_params.get("api_version", "") if model is None: model = "" if AzureFoundryMAIImageGenerationConfig.is_mai_model(base_model or model): return AzureFoundryMAIImageGenerationConfig.get_mai_image_generation_url( api_base=api_base, api_version=api_version, ) # Handle FLUX 2 models on Azure AI which use a different URL pattern # e.g., /providers/blackforestlabs/v1/flux-2-pro instead of /openai/deployments/{model}/images/generations if AzureFoundryFluxImageGenerationConfig.is_flux2_model(model): return AzureFoundryFluxImageGenerationConfig.get_flux2_image_generation_url( api_base=api_base, model=model, api_version=api_version, ) v1_url: Final = BaseAzureLLM.get_azure_v1_image_url( api_base=api_base, api_version=api_version, route="/openai/images/generations", ) if v1_url is not None: return v1_url if "/openai/deployments/" in api_base: base_url_with_deployment = api_base else: base_url_with_deployment = api_base + "/openai/deployments/" + model base_url_with_deployment += "/images/generations" base_url_with_deployment += "?api-version=" + api_version return base_url_with_deployment async def aimage_generation( self, data: dict, model_response: ImageResponse | None, azure_client_params: dict, api_key: str, input: list, logging_obj: LiteLLMLoggingObj, headers: dict, client=None, timeout=None, model: str | None = None, ) -> ImageResponse: response: dict | None = None try: # response = await azure_client.images.generate(**data, timeout=timeout) api_base: str = azure_client_params.get("api_base", "") # "https://example-endpoint.openai.azure.com" if api_base.endswith("/"): api_base = api_base.rstrip("/") api_version: Final[str] = azure_client_params.get("api_version", "") img_gen_api_base: Final = self.create_azure_base_url( azure_client_params=azure_client_params, model=model or data.get("model", ""), base_model=data.get("model", ""), ) ## LOGGING logging_obj.pre_call( input=data["prompt"], api_key=api_key, additional_args={ "complete_input_dict": data, "api_base": img_gen_api_base, "headers": headers, }, ) httpx_response: Final[httpx.Response] = await self.make_async_azure_httpx_request( client=None, timeout=timeout, api_base=img_gen_api_base, api_version=api_version, api_key=api_key, data=data, headers=headers, deployment_name=model, ) provider_config: Final = get_azure_image_generation_config(data.get("model", "dall-e-2")) if provider_config is not None: return provider_config.transform_image_generation_response( model=data.get("model", "dall-e-2"), raw_response=httpx_response, model_response=model_response or ImageResponse(), logging_obj=logging_obj, request_data=data, optional_params=data, litellm_params=data, encoding=litellm.encoding, ) else: response = httpx_response.json() stringified_response: Final = response ## LOGGING logging_obj.post_call( input=input, api_key=api_key, additional_args={"complete_input_dict": data}, original_response=stringified_response, ) return convert_to_model_response_object( response_object=stringified_response, model_response_object=model_response, response_type="image_generation", ) except Exception as e: ## LOGGING logging_obj.post_call( input=input, api_key=api_key, additional_args={"complete_input_dict": data}, original_response=str(e), ) raise e def image_generation( self, prompt: str, timeout: float, optional_params: dict, logging_obj: LiteLLMLoggingObj, headers: dict, model: str | None = None, api_key: str | None = None, api_base: str | None = None, api_version: str | None = None, model_response: ImageResponse | None = None, azure_ad_token: str | None = None, azure_ad_token_provider: Callable | None = None, client=None, aimg_generation=None, litellm_params: dict | None = None, ) -> ImageResponse: try: if model and len(model) > 0: model = model else: model = None ## BASE MODEL CHECK if ( model_response is not None and litellm_params is not None and litellm_params.get("base_model", None) is not None ): model_response._hidden_params["model"] = litellm_params.get("base_model", None) # Azure image generation API doesn't support extra_body parameter extra_body: Final = optional_params.pop("extra_body", {}) flattened_params: Final = {**optional_params, **extra_body} base_model: Final = litellm_params.get("base_model", None) if litellm_params else None data: Final = {"model": base_model or model, "prompt": prompt, **flattened_params} max_retries: Final = data.pop("max_retries", 2) if not isinstance(max_retries, int): raise AzureOpenAIError(status_code=422, message="max retries must be an int") if api_key is None and azure_ad_token_provider is not None: azure_ad_token = azure_ad_token_provider() if azure_ad_token: headers.pop("api-key", None) headers["Authorization"] = f"Bearer {azure_ad_token}" # init AzureOpenAI Client azure_client_params: Final[dict[str, object]] = self.initialize_azure_sdk_client( litellm_params=litellm_params or {}, api_key=api_key, model_name=model or "", api_version=api_version, api_base=api_base, is_async=False, ) if aimg_generation is True: return self.aimage_generation( data=data, input=input, logging_obj=logging_obj, model_response=model_response, api_key=api_key, client=client, azure_client_params=azure_client_params, timeout=timeout, headers=headers, model=model, ) img_gen_api_base: Final = self.create_azure_base_url( azure_client_params=azure_client_params, model=model, base_model=base_model, ) ## LOGGING logging_obj.pre_call( input=data["prompt"], api_key=api_key, additional_args={ "complete_input_dict": data, "api_base": img_gen_api_base, "headers": headers, }, ) httpx_response: Final[httpx.Response] = self.make_sync_azure_httpx_request( client=None, timeout=timeout, api_base=img_gen_api_base, api_version=api_version or "", api_key=api_key or "", data=data, headers=headers, deployment_name=model, ) provider_config: Final = get_azure_image_generation_config(data.get("model", "dall-e-2")) if isinstance(provider_config, AzureFoundryMAIImageGenerationConfig): return provider_config.transform_image_generation_response( model=data.get("model", "dall-e-2"), raw_response=httpx_response, model_response=model_response or ImageResponse(), logging_obj=logging_obj, request_data=data, optional_params=data, litellm_params=data, encoding=litellm.encoding, ) response: Final = httpx_response.json() ## LOGGING logging_obj.post_call( input=prompt, api_key=api_key, additional_args={"complete_input_dict": data}, original_response=response, ) # return response return convert_to_model_response_object( response_object=response, model_response_object=model_response, response_type="image_generation", ) except AzureOpenAIError as e: raise e except Exception as e: error_code: Final = getattr(e, "status_code", None) if error_code is not None: raise AzureOpenAIError(status_code=error_code, message=str(e)) else: raise AzureOpenAIError(status_code=500, message=str(e)) def audio_speech( self, model: str, input: str, voice: str, optional_params: dict, api_key: str | None, api_base: str | None, api_version: str | None, organization: str | None, max_retries: int, timeout: float | httpx.Timeout, logging_obj: LiteLLMLoggingObj, azure_ad_token: str | None = None, azure_ad_token_provider: Callable | None = None, aspeech: bool | None = None, client=None, litellm_params: dict | None = None, ) -> HttpxBinaryResponseContent: max_retries = optional_params.pop("max_retries", 2) if aspeech is not None and aspeech is True: return self.async_audio_speech( model=model, input=input, voice=voice, optional_params=optional_params, api_key=api_key, api_base=api_base, api_version=api_version, azure_ad_token=azure_ad_token, azure_ad_token_provider=azure_ad_token_provider, max_retries=max_retries, timeout=timeout, logging_obj=logging_obj, client=client, litellm_params=litellm_params, ) azure_client: Final[AzureOpenAI] = self.get_azure_openai_client( api_base=api_base, api_version=api_version, api_key=api_key, model=model, _is_async=False, client=client, litellm_params=litellm_params, ) logging_obj.pre_call( input=input, api_key=api_key, additional_args={ # mutable-ok: loggers isinstance-check this payload as a dict "complete_input_dict": speech_request_body(model, voice, optional_params), "api_base": str(azure_client.base_url), }, ) response: Final = azure_client.audio.speech.create( model=model, voice=voice, input=input, **optional_params, ) return HttpxBinaryResponseContent(response=response.response) async def async_audio_speech( self, model: str, input: str, voice: str, optional_params: dict, api_key: str | None, api_base: str | None, api_version: str | None, azure_ad_token: str | None, azure_ad_token_provider: Callable | None, max_retries: int, timeout: float | httpx.Timeout, logging_obj: LiteLLMLoggingObj, client=None, litellm_params: dict | None = None, ) -> HttpxBinaryResponseContent: azure_client: Final[AsyncAzureOpenAI] = self.get_azure_openai_client( api_base=api_base, api_version=api_version, api_key=api_key, model=model, _is_async=True, client=client, litellm_params=litellm_params, ) logging_obj.pre_call( input=input, api_key=api_key, additional_args={ # mutable-ok: loggers isinstance-check this payload as a dict "complete_input_dict": speech_request_body(model, voice, optional_params), "api_base": str(azure_client.base_url), }, ) azure_response: Final = await azure_client.audio.speech.create( model=model, voice=voice, input=input, **optional_params, ) return HttpxBinaryResponseContent(response=azure_response.response) def get_headers( self, model: str | None, api_key: str, api_base: str, api_version: str, timeout: float, mode: str, messages: list | None = None, input: list | None = None, prompt: str | None = None, ) -> dict: client_session: Final = litellm.client_session or httpx.Client() if api_base is not None and "gateway.ai.cloudflare.com" in api_base: ## build base url - assume api base includes resource name if not api_base.endswith("/"): api_base += "/" api_base += f"{model}" client = AzureOpenAI( base_url=api_base, api_version=api_version, api_key=api_key, timeout=timeout, http_client=client_session, ) model = None # cloudflare ai gateway, needs model=None else: client = AzureOpenAI( api_version=api_version, azure_endpoint=api_base, api_key=api_key, timeout=timeout, http_client=client_session, ) # only run this check if it's not cloudflare ai gateway if model is None and mode != "image_generation": raise Exception("model is not set") completion = None if messages is None: messages = [{"role": "user", "content": "Hey"}] try: completion = client.chat.completions.with_raw_response.create( model=model, messages=messages, ) except Exception as e: raise e response: Final = {} if completion is None or not hasattr(completion, "headers"): raise Exception("invalid completion response") if ( completion.headers.get("x-ratelimit-remaining-requests", None) is not None ): # not provided for dall-e requests response["x-ratelimit-remaining-requests"] = completion.headers["x-ratelimit-remaining-requests"] if completion.headers.get("x-ratelimit-remaining-tokens", None) is not None: response["x-ratelimit-remaining-tokens"] = completion.headers["x-ratelimit-remaining-tokens"] if completion.headers.get("x-ms-region", None) is not None: response["x-ms-region"] = completion.headers["x-ms-region"] return response
import asyncio
import json
import time
from collections.abc import Callable, Coroutine
from typing import Final
import httpx
from openai import (
APITimeoutError,
AsyncAzureOpenAI,
AsyncOpenAI,
AzureOpenAI,
BadRequestError,
OpenAI,
)
import litellm
from litellm.constants import AZURE_OPERATION_POLLING_TIMEOUT, DEFAULT_MAX_RETRIES
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.litellm_core_utils.logging_utils import speech_request_body, track_llm_api_timing
from litellm.litellm_core_utils.url_utils import SSRFError, assert_same_origin
from litellm.llms.custom_httpx.http_handler import (
AsyncHTTPHandler,
HTTPHandler,
get_async_httpx_client,
)
from litellm.types.utils import (
EmbeddingResponse,
ImageResponse,
LlmProviders,
ModelResponse,
)
from litellm.utils import (
CustomStreamWrapper,
convert_to_model_response_object,
modify_url,
)
from ...types.llms.openai import HttpxBinaryResponseContent
from ..base import BaseLLM
from ..openai.common_utils import (
build_output_token_limit_response,
is_output_token_limit_error,
)
from .common_utils import (
AzureOpenAIError,
BaseAzureLLM,
get_azure_ad_token_from_oidc,
process_azure_headers,
select_azure_base_url_or_endpoint,
)
from .image_generation import (
AzureFoundryMAIImageGenerationConfig,
get_azure_image_generation_config,
)
from .image_generation.http_utils import azure_deployment_image_generation_json_body
class AzureOpenAIAssistantsAPIConfig:
"""
Reference: https://learn.microsoft.com/en-us/azure/ai-services/openai/assistants-reference-messages?tabs=python#create-message
"""
def __init__(
self,
) -> None:
pass
def get_supported_openai_create_message_params(self):
return [
"role",
"content",
"attachments",
"metadata",
]
def map_openai_params_create_message_params(self, non_default_params: dict, optional_params: dict):
for param, value in non_default_params.items():
if param == "role":
optional_params["role"] = value
if param == "metadata":
optional_params["metadata"] = value
elif param == "content": # only string accepted
if isinstance(value, str):
optional_params["content"] = value
else:
raise litellm.utils.UnsupportedParamsError(
message="Azure only accepts content as a string.",
status_code=400,
)
elif param == "attachments": # this is a v2 param. Azure currently supports the old 'file_id's param
file_ids: list[str] = []
if isinstance(value, list):
for item in value:
if "file_id" in item:
file_ids.append(item["file_id"])
else:
if litellm.drop_params is True:
pass
else:

Xet Storage Details

Size:
60.2 kB
·
Xet hash:
4e5b3941403161287978635a4c8bdd4d00ef44e2890f4413802bd1f33d97994c

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.