Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Openai Openai python Azure Client

From Leeroopedia
Knowledge Sources
Domains SDK_Infrastructure, Python
Last Updated 2026-02-15 00:00 GMT

Overview

Concrete tool for Azure OpenAI API client integration provided by the openai-python SDK.

Description

The Azure Client module provides AzureOpenAI (synchronous) and AsyncAzureOpenAI (asynchronous) client classes for interacting with Azure-hosted OpenAI services. Both classes extend the standard OpenAI / AsyncOpenAI clients and the BaseAzureClient mixin, which handles Azure-specific URL construction and deployment-based routing. The clients automatically inject api-version as a default query parameter and support three authentication methods: API key (via api_key or AZURE_OPENAI_API_KEY), Azure AD token (via azure_ad_token or AZURE_OPENAI_AD_TOKEN), and Azure AD token provider (a callable invoked per request). The api_key, azure_ad_token, and azure_ad_token_provider arguments are mutually exclusive. The BaseAzureClient overrides _build_request() to automatically route deployment-aware endpoints (completions, chat, embeddings, audio, images) via /deployments/{model} URL paths, and overrides _prepare_url() to handle non-deployment endpoints correctly when both azure_endpoint and azure_deployment are set.

Usage

Use the Azure Client when you need to call OpenAI models hosted on Microsoft Azure rather than the OpenAI platform directly. This is required for enterprise deployments that use Azure-specific endpoints, API versioning, and Azure Active Directory authentication. The clients provide the same resource interface (chat, completions, embeddings, etc.) as the standard OpenAI clients.

Code Reference

Source Location

Signature

AzureOpenAI

class AzureOpenAI(BaseAzureClient[httpx.Client, Stream[Any]], OpenAI):
    def __init__(
        self,
        *,
        api_version: str | None = None,
        azure_endpoint: str | None = None,
        azure_deployment: str | None = None,
        api_key: str | Callable[[], str] | None = None,
        azure_ad_token: str | None = None,
        azure_ad_token_provider: AzureADTokenProvider | None = None,
        organization: str | None = None,
        project: str | None = None,
        webhook_secret: str | None = None,
        websocket_base_url: str | httpx.URL | None = None,
        base_url: str | None = None,
        timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
        max_retries: int = DEFAULT_MAX_RETRIES,
        default_headers: Mapping[str, str] | None = None,
        default_query: Mapping[str, object] | None = None,
        http_client: httpx.Client | None = None,
        _strict_response_validation: bool = False,
    ) -> None: ...

AsyncAzureOpenAI

class AsyncAzureOpenAI(BaseAzureClient[httpx.AsyncClient, AsyncStream[Any]], AsyncOpenAI):
    def __init__(
        self,
        *,
        azure_endpoint: str | None = None,
        azure_deployment: str | None = None,
        api_version: str | None = None,
        api_key: str | Callable[[], Awaitable[str]] | None = None,
        azure_ad_token: str | None = None,
        azure_ad_token_provider: AsyncAzureADTokenProvider | None = None,
        organization: str | None = None,
        project: str | None = None,
        webhook_secret: str | None = None,
        base_url: str | None = None,
        websocket_base_url: str | httpx.URL | None = None,
        timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
        max_retries: int = DEFAULT_MAX_RETRIES,
        default_headers: Mapping[str, str] | None = None,
        default_query: Mapping[str, object] | None = None,
        http_client: httpx.AsyncClient | None = None,
        _strict_response_validation: bool = False,
    ) -> None: ...

BaseAzureClient

class BaseAzureClient(BaseClient[_HttpxClientT, _DefaultStreamT]):
    _azure_endpoint: httpx.URL | None
    _azure_deployment: str | None

    def _build_request(
        self,
        options: FinalRequestOptions,
        *,
        retries_taken: int = 0,
    ) -> httpx.Request: ...

    def _prepare_url(self, url: str) -> httpx.URL: ...

Import

from openai.lib.azure import AzureOpenAI, AsyncAzureOpenAI

I/O Contract

Inputs (AzureOpenAI.__init__)

Name Type Required Description
azure_endpoint str or None Conditional The Azure resource endpoint URL (e.g., https://example-resource.azure.openai.com/). Required if base_url is not provided. Falls back to AZURE_OPENAI_ENDPOINT env var.
azure_deployment str or None No The Azure model deployment name. When set with azure_endpoint, the base URL includes /deployments/{azure_deployment}.
api_version str or None Yes The Azure API version string (e.g., "2024-02-01"). Falls back to OPENAI_API_VERSION env var.
api_key str or Callable or None Conditional Azure OpenAI API key. Falls back to AZURE_OPENAI_API_KEY. Mutually exclusive with azure_ad_token and azure_ad_token_provider.
azure_ad_token str or None Conditional Azure Active Directory token. Falls back to AZURE_OPENAI_AD_TOKEN. Mutually exclusive with api_key and azure_ad_token_provider.
azure_ad_token_provider Callable or None Conditional A callable that returns an Azure AD token string, invoked on every request. Mutually exclusive with api_key and azure_ad_token.
base_url str or None Conditional Explicit base URL. Mutually exclusive with azure_endpoint.
timeout float or Timeout or None No Client-level request timeout.
max_retries int No Maximum number of retries for failed requests. Defaults to 2.
organization str or None No OpenAI organization ID. Falls back to OPENAI_ORG_ID.

Outputs

Name Type Description
instance AzureOpenAI or AsyncAzureOpenAI A fully configured client providing the same resource interface as the standard OpenAI client (chat, completions, embeddings, etc.).

Usage Examples

Basic Usage with API Key

from openai import AzureOpenAI

client = AzureOpenAI(
    azure_endpoint="https://my-resource.openai.azure.com/",
    api_key="my-azure-api-key",
    api_version="2024-02-01",
)

response = client.chat.completions.create(
    model="gpt-4",
    messages=[{"role": "user", "content": "Hello!"}],
)

Async Usage with Azure AD Token Provider

from openai import AsyncAzureOpenAI
from azure.identity.aio import DefaultAzureCredential

credential = DefaultAzureCredential()

async def get_token() -> str:
    token = await credential.get_token("https://cognitiveservices.azure.com/.default")
    return token.token

client = AsyncAzureOpenAI(
    azure_endpoint="https://my-resource.openai.azure.com/",
    azure_ad_token_provider=get_token,
    api_version="2024-02-01",
)

response = await client.chat.completions.create(
    model="gpt-4",
    messages=[{"role": "user", "content": "Hello!"}],
)

Using Environment Variables

import os
os.environ["AZURE_OPENAI_API_KEY"] = "my-key"
os.environ["AZURE_OPENAI_ENDPOINT"] = "https://my-resource.openai.azure.com/"
os.environ["OPENAI_API_VERSION"] = "2024-02-01"

from openai import AzureOpenAI
client = AzureOpenAI()  # all config inferred from environment

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment