> ## Documentation Index
> Fetch the complete documentation index at: https://cndoc-langchain.site/llms.txt
> Use this file to discover all available pages before exploring further.

# AzureChatOpenAI 集成

> 使用 LangChain Python 集成 AzureChatOpenAI 聊天模型。

你可以在 [Azure 文档](https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/models) 中找到有关 Azure OpenAI 最新模型及其成本、上下文窗口和支持的输入类型的信息。有关 LangChain 中 Microsoft 集成的完整集合（包括 Azure AI Search、Azure Database for PostgreSQL 和 M365 套件等工具），请参阅 [Microsoft 提供者页面](/oss/python/integrations/providers/microsoft)。

<Info>
  **Azure OpenAI 与 OpenAI**

  Azure OpenAI 指的是托管在 [Microsoft Azure 平台](https://azure.microsoft.com/en-us/products/ai-services/openai-service) 上的 OpenAI 模型。托管在 Azure 上的模型附带了额外的企业功能，包括支持使用 Entra ID 进行无密钥身份验证。
</Info>

<Info>
  **使用 `ChatOpenAI` 与 v1 API（推荐）**

  Azure OpenAI 的 [v1 API](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/api-version-lifecycle?tabs=python)（自 2025 年 8 月起正式发布）允许你直接使用 [`ChatOpenAI`](/oss/python/integrations/chat/openai/#using-with-azure-openai) 与 Azure 端点。这消除了对过时的 `api-version` 参数的需求，并提供了对 Microsoft Entra ID 身份验证的原生支持，支持自动令牌刷新。

  我们继续支持 [`AzureChatOpenAI`](https://reference.langchain.com/python/langchain-openai/chat_models/azure/AzureChatOpenAI)，它现在与 [`ChatOpenAI`](https://reference.langchain.com/python/langchain-openai/chat_models/base/ChatOpenAI) 共享相同的基础实现，后者直接与 OpenAI 服务交互。

  本页作为身份验证和将你的 Azure OpenAI 聊天模型连接到 LangChain 的快速入门指南。
</Info>

<Tip>
  **API 参考**

  有关所有功能和配置选项的详细文档，请访问 [`AzureChatOpenAI`](https://reference.langchain.com/python/langchain-openai/chat_models/azure/AzureChatOpenAI) API 参考。有关可用功能的详细信息，请访问 [`ChatOpenAI` 文档](/oss/python/integrations/chat/openai/)。
</Tip>

## 概述

### 集成详情

| 类                                                                                                              | 包                                                                              | 可序列化 |                              JS/TS 支持                             |                                                                                              下载量                                                                                             |                                                                                                                 最新版本                                                                                                                 |
| :------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------- | :--: | :---------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: |
| [`AzureChatOpenAI`](https://reference.langchain.com/python/langchain-openai/chat_models/azure/AzureChatOpenAI) | [`langchain-openai`](https://reference.langchain.com/python/langchain-openai/) | beta | ✅ [(npm)](https://js.langchain.com/docs/integrations/chat/openai) | <a href="https://pypi.org/project/langchain-openai/" target="_blank"><img src="https://static.pepy.tech/badge/langchain-openai/month" alt="每月下载量" noZoom height="100" class="rounded" /></a> | <a href="https://pypi.org/project/langchain-openai/" target="_blank"><img src="https://img.shields.io/pypi/v/langchain-openai?style=flat-square&label=%20&color=orange" alt="PyPI - 最新版本" noZoom height="100" class="rounded" /></a> |

### 模型功能

| [工具调用](/oss/python/langchain/tools) | [结构化输出](/oss/python/langchain/structured-output) | [图像输入](/oss/python/langchain/messages#multimodal) | 音频输入 | 视频输入 | [令牌级流式传输](/oss/python/langchain/streaming/) | 原生异步 | [令牌使用量](/oss/python/langchain/models#token-usage) | [对数概率](/oss/python/langchain/models#log-probabilities) |
| :---------------------------------: | :----------------------------------------------: | :-----------------------------------------------: | :--: | :--: | :-----------------------------------------: | :--: | :-----------------------------------------------: | :----------------------------------------------------: |
|                  ✅                  |                         ✅                        |                         ✅                         |   ❌  |   ❌  |                      ✅                      |   ✅  |                         ✅                         |                            ✅                           |

## 设置

要访问 Azure OpenAI 模型，你需要 [创建一个 Azure 帐户](https://account.azure.com/signup)，创建一个 Azure OpenAI 模型的部署，获取部署的名称和端点，并安装 `langchain-openai` 集成包。

### 安装

<CodeGroup>
  ```bash pip theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  pip install -U langchain-openai
  ```

  ```bash uv theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  uv add langchain-openai
  ```
</CodeGroup>

## 凭证

[`ChatOpenAI`](https://reference.langchain.com/python/langchain-openai/chat_models/base/ChatOpenAI) 和 [`AzureChatOpenAI`](https://reference.langchain.com/python/langchain-openai/chat_models/azure/AzureChatOpenAI) 都支持使用 **Microsoft Entra ID**（推荐）或 **API 密钥** 进行 Azure OpenAI 身份验证。

### Microsoft Entra ID

[Microsoft Entra ID](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/managed-identity) 提供无密钥身份验证和自动令牌刷新。安装 `azure-identity` 包并创建一个令牌提供者——同一个提供者适用于 `ChatOpenAI` 和 `AzureChatOpenAI`：

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install azure-identity
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from azure.identity import DefaultAzureCredential, get_bearer_token_provider

token_provider = get_bearer_token_provider(
    DefaultAzureCredential(),
    "https://cognitiveservices.azure.com/.default",
)
```

### API 密钥

前往 [Azure 文档](https://learn.microsoft.com/en-us/azure/ai-services/openai/chatgpt-quickstart?tabs=command-line%2Cpython-new\&pivots=programming-language-python) 创建你的部署并生成 API 密钥。设置 `AZURE_OPENAI_API_KEY` 和 `AZURE_OPENAI_ENDPOINT` 环境变量：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import getpass
import os

if "AZURE_OPENAI_API_KEY" not in os.environ:
    os.environ["AZURE_OPENAI_API_KEY"] = getpass.getpass(
        "Enter your AzureOpenAI API key: "
    )
os.environ["AZURE_OPENAI_ENDPOINT"] = "https://YOUR-RESOURCE-NAME.openai.azure.com/"
```

要启用模型调用的自动跟踪，请设置你的 [LangSmith](/langsmith/home) API 密钥：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
os.environ["LANGSMITH_TRACING"] = "true"
```

## 实例化

### 使用 v1 API 的 ChatOpenAI

将 `base_url` 设置为你的 Azure 端点，并附加 `/openai/v1/`。使用 v1 API，你可以通过单一接口调用部署在 [Microsoft Foundry](https://learn.microsoft.com/en-us/azure/ai-foundry/) 中的任何模型（包括 OpenAI、Llama、DeepSeek、Mistral 和 Phi），只需将 `model` 指向你的部署名称。

<Tabs>
  <Tab title="Entra ID（推荐）">
    将令牌提供者传递给 `api_key`：

    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    from langchain_openai import ChatOpenAI

    llm = ChatOpenAI(
        model="gpt-5.4-mini",  # 你的 Azure 部署名称
        base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
        api_key=token_provider,  # 处理令牌刷新的可调用对象
    )
    ```
  </Tab>

  <Tab title="API 密钥">
    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    from langchain_openai import ChatOpenAI

    llm = ChatOpenAI(
        model="gpt-5.4-mini",  # 你的 Azure 部署名称
        base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
        api_key="your-azure-api-key",
    )
    ```
  </Tab>
</Tabs>

### AzureChatOpenAI

当使用需要 `api_version` 的传统 Azure OpenAI API 版本时，请使用 [`AzureChatOpenAI`](https://reference.langchain.com/python/langchain-openai/chat_models/azure/AzureChatOpenAI)。

<Tabs>
  <Tab title="Entra ID（推荐）">
    将令牌提供者传递给 `azure_ad_token_provider`：

    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    from langchain_openai import AzureChatOpenAI

    llm = AzureChatOpenAI(
        azure_deployment="gpt-5.4-mini",  # 或你的部署
        api_version="2025-04-01-preview",  # 或你的 api 版本
        azure_ad_token_provider=token_provider,
    )
    ```
  </Tab>

  <Tab title="API 密钥">
    从环境中读取 `AZURE_OPENAI_API_KEY` 和 `AZURE_OPENAI_ENDPOINT`：

    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    from langchain_openai import AzureChatOpenAI

    llm = AzureChatOpenAI(
        azure_deployment="gpt-5.4-mini",  # 或你的部署
        api_version="2025-04-01-preview",  # 或你的 api 版本
        temperature=0,
        max_tokens=None,
        timeout=None,
        max_retries=2,
        # 其他参数...
    )
    ```
  </Tab>
</Tabs>

## 调用

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
messages = [
    (
        "system",
        "You are a helpful assistant that translates English to French. Translate the user sentence.",
    ),
    ("human", "I love programming."),
]
ai_msg = llm.invoke(messages)
print(ai_msg.text)
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
J'adore la programmation.
```

## 工具调用

使用 Pydantic 类、字典模式、LangChain 工具或函数将工具绑定到模型：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_openai import ChatOpenAI
from pydantic import BaseModel, Field


class GetWeather(BaseModel):
    """Get the current weather in a given location"""

    location: str = Field(description="The city and state, e.g. San Francisco, CA")


llm = ChatOpenAI(
    model="gpt-5.4-mini",
    base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
    api_key="your-azure-api-key",
)

llm_with_tools = llm.bind_tools([GetWeather])

ai_msg = llm_with_tools.invoke("What is the weather like in San Francisco?")
ai_msg.tool_calls
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
[{'name': 'GetWeather',
  'args': {'location': 'San Francisco, CA'},
  'id': 'call_jUqhd8wzAIzInTJl72Rla8ht',
  'type': 'tool_call'}]
```

有关绑定工具和工具调用输出的更多信息，请访问 [工具调用](/oss/python/langchain/tools) 文档。

## 构建代理

使用 [`create_agent`](https://reference.langchain.com/python/langchain/agents/factory/create_agent) 构建一个使用 Azure OpenAI 和工具的代理：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="gpt-5.4-mini",
    base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
    api_key="your-azure-api-key",
)


def get_weather(city: str) -> str:
    """Get weather for a given city."""
    return f"It's always sunny in {city}!"


agent = create_agent(
    model=llm,
    tools=[get_weather],
    system_prompt="You are a helpful assistant",
)

# 流式传输代理响应
for chunk in agent.stream(
    {"messages": [{"role": "user", "content": "What is the weather in SF?"}]},
    stream_mode="updates",
):
    for step, data in chunk.items():
        print(f"step: {step}")
        print(f"content: {data['messages'][-1].text}")
```

## 流式传输使用量元数据

OpenAI 的 Chat Completions API 默认不流式传输令牌使用量统计信息（参见 [OpenAI API 参考中的流式选项](https://platform.openai.com/docs/api-reference/completions/create#completions-create-stream_options)）。

要在流式传输时恢复令牌计数，请将 `stream_usage=True` 设置为初始化参数或在调用时设置：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="gpt-5.4-mini",
    base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
    api_key="your-azure-api-key",
    stream_usage=True,  # [!code highlight]
)
```

## Responses API

Azure OpenAI 支持 [Responses API](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/responses)，它提供有状态的对话、内置的服务器端工具（代码解释器、图像生成、文件搜索和远程 MCP）以及结构化的推理摘要。当你设置 `reasoning` 参数时，[`ChatOpenAI`](https://reference.langchain.com/python/langchain-openai/chat_models/base/ChatOpenAI) 会自动路由到 Responses API，或者你可以通过 `use_responses_api=True` 显式选择使用：

<Tabs>
  <Tab title="Entra ID（推荐）">
    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    from langchain_openai import ChatOpenAI

    llm = ChatOpenAI(
        model="gpt-5.4-mini",  # 你的 Azure 部署名称
        base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
        api_key=token_provider,
        use_responses_api=True,  # [!code highlight]
    )

    # 绑定一个内置的服务器端工具
    llm_with_tools = llm.bind_tools(  # [!code highlight]
        [{"type": "code_interpreter", "container": {"type": "auto"}}]  # [!code highlight]
    )  # [!code highlight]

    response = llm_with_tools.invoke(
        "Use the code interpreter to compute the 25th Fibonacci number."
    )
    print(response.text)
    ```
  </Tab>

  <Tab title="API 密钥">
    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    from langchain_openai import ChatOpenAI

    llm = ChatOpenAI(
        model="gpt-5.4-mini",  # 你的 Azure 部署名称
        base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
        api_key="your-azure-api-key",
        use_responses_api=True,  # [!code highlight]
    )

    # 绑定一个内置的服务器端工具
    llm_with_tools = llm.bind_tools(  # [!code highlight]
        [{"type": "code_interpreter", "container": {"type": "auto"}}]  # [!code highlight]
    )  # [!code highlight]

    response = llm_with_tools.invoke(
        "Use the code interpreter to compute the 25th Fibonacci number."
    )
    print(response.text)
    ```
  </Tab>
</Tabs>

有关内置工具及其使用方法的详细信息，请参阅 [Azure OpenAI Responses API 文档](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/responses)。

## 推理努力与摘要

Azure OpenAI [推理模型](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/reasoning)（例如 `o4-mini`、`gpt-5`）在生成最终答案之前会花费额外的令牌来思考请求。使用 v1 API 上的 `ChatOpenAI`，你可以配置模型在推理上花费多少努力，并可选择请求其思维链的摘要。

### 推理努力

将 `reasoning_effort` 设置为 `"low"`、`"medium"` 或 `"high"`。较高的设置让模型在推理上花费更多令牌，这通常会提高复杂任务的质量，但会增加延迟：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="gpt-5.4-mini",  # 你的 Azure 推理模型部署
    base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
    api_key=token_provider,
    reasoning_effort="medium",
)

response = llm.invoke("Tell me about the bitter lesson.")
print(response.text)
```

<Note>
  推理模型使用令牌进行内部推理（`completion_tokens_details` 中的 `reasoning_tokens`）。这些令牌不会出现在消息内容中，但会计入输出令牌限制。如果你看到空响应，请增加 `max_tokens` 或将其留空，以便模型有足够的空间进行推理和输出。
</Note>

### 推理摘要

当通过 Responses API 使用推理模型时，你可以通过传递 `reasoning` 字典来请求模型思维链的摘要。设置 `reasoning` 会自动将 `ChatOpenAI` 路由到 Responses API：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_openai import ChatOpenAI

reasoning = {
    "effort": "high",    # 'low', 'medium', 或 'high'
    "summary": "auto",   # 'auto', 'concise', 或 'detailed'
}

llm = ChatOpenAI(
    model="gpt-5.4-mini",  # 你的 Azure 推理模型部署
    base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
    api_key=token_provider,
    reasoning=reasoning,
)

response = llm.invoke("What's the optimal strategy to win at poker?")

# 最终答案
print(response.text)

# 推理摘要块
for block in response.content_blocks:
    if block["type"] == "reasoning":
        print(block["reasoning"])
```

<Warning>
  尝试通过推理摘要参数以外的方法提取原始推理令牌不受支持，并且可能违反 Azure 的可接受使用策略。请使用 `summary` 字段访问模型推理。
</Warning>

<Note>
  即使启用，推理摘要也不保证在每个步骤或请求中都提供——这是预期行为。
</Note>

## 指定模型版本（旧版 API）

<Note>
  本节仅适用于使用传统 API 版本的 `AzureChatOpenAI`。v1 API 不需要 `api_version` 参数。
</Note>

使用 `AzureChatOpenAI` 时，Azure OpenAI 响应包含一个 `model_name` 响应元数据属性。与原生 OpenAI 响应不同，它不包含模型的具体版本（该版本在 Azure 中的部署上设置）。传递 `model_version` 以区分不同版本：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_openai import AzureChatOpenAI

llm = AzureChatOpenAI(
    azure_deployment="gpt-5.4-mini",  # 或你的部署
    api_version="2025-04-01-preview",  # 或你的 api 版本
    model_version="0301",
)
```

***

## API 参考

有关所有功能和配置选项的详细文档，请访问 [`AzureChatOpenAI`](https://reference.langchain.com/python/langchain-openai/chat_models/azure/AzureChatOpenAI) API 参考。

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档连接](/use-these-docs)到 Claude、VSCode 等，通过 MCP 获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/python/integrations/chat/azure_chat_openai.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
