> ## 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.

# Azure OpenAI 集成

> 使用 LangChain Python 与 Azure OpenAI LLM 集成。

<Warning>
  **您当前正在查看的是关于使用 Azure OpenAI 文本补全模型的文档。最新且最受欢迎的 Azure OpenAI 模型是[聊天补全模型](/oss/python/langchain/models)。**

  除非您特别使用 `gpt-3.5-turbo-instruct`，否则您可能需要的是[此页面](/oss/python/integrations/chat/azure_chat_openai/)。
</Warning>

本页介绍如何将 LangChain 与 [Azure OpenAI](https://aka.ms/azure-openai) 结合使用。

Azure OpenAI API 与 OpenAI 的 API 兼容。`openai` Python 包使得同时使用 OpenAI 和 Azure OpenAI 变得简单。您可以像调用 OpenAI 一样调用 Azure OpenAI，但需注意以下例外情况。

## API 配置

您可以使用环境变量配置 `openai` 包以使用 Azure OpenAI。以下是针对 `bash` 的配置：

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# 您要使用的 API 版本：对于已发布的版本，请将其设置为 `2023-12-01-preview`。
export OPENAI_API_VERSION=2023-12-01-preview
# 您的 Azure OpenAI 资源的基 URL。您可以在 Azure 门户中您的 Azure OpenAI 资源下找到它。
export AZURE_OPENAI_ENDPOINT=https://your-resource-name.openai.azure.com
# 您的 Azure OpenAI 资源的 API 密钥。您可以在 Azure 门户中您的 Azure OpenAI 资源下找到它。
export AZURE_OPENAI_API_KEY=<your Azure OpenAI API key>
```

或者，您可以在运行的 Python 环境中直接配置 API：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import os
os.environ["OPENAI_API_VERSION"] = "2023-12-01-preview"
```

## Azure 活动目录身份验证

您可以通过两种方式向 Azure OpenAI 进行身份验证：

* API 密钥
* Azure 活动目录 (AAD)

使用 API 密钥是最简单的入门方式。您可以在 Azure 门户中您的 Azure OpenAI 资源下找到您的 API 密钥。

但是，如果您有复杂的安全要求 - 您可能希望使用 Azure 活动目录。您可以在 [托管标识文档](https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/managed-identity) 中找到有关如何将 AAD 与 Azure OpenAI 结合使用的更多信息。

如果您在本地开发，则需要安装 Azure CLI 并登录。您可以从 [Azure CLI 安装指南](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli) 安装 Azure CLI。然后，运行 `az login` 进行登录。

添加一个 Azure 角色分配 `Cognitive Services OpenAI User`，其范围限定为您的 Azure OpenAI 资源。这将允许您从 AAD 获取令牌以用于 Azure OpenAI。您可以将此角色分配授予用户、组、服务主体或托管标识。有关 Azure OpenAI RBAC 角色的更多信息，请参阅[基于角色的访问控制文档](https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/role-based-access-control)。

要在 Python 中与 LangChain 一起使用 AAD，请安装 `azure-identity` 包。然后，将 `OPENAI_API_TYPE` 设置为 `azure_ad`。接下来，使用 `DefaultAzureCredential` 类通过调用 `get_token` 从 AAD 获取令牌，如下所示。最后，将 `OPENAI_API_KEY` 环境变量设置为令牌值。

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

# 获取 Azure 凭据
credential = DefaultAzureCredential()

# 将 API 类型设置为 `azure_ad`
os.environ["OPENAI_API_TYPE"] = "azure_ad"
# 将 API_KEY 设置为来自 Azure 凭据的令牌
os.environ["OPENAI_API_KEY"] = credential.get_token("https://cognitiveservices.azure.com/.default").token
```

`DefaultAzureCredential` 类是开始使用 AAD 身份验证的一种简单方式。您也可以根据需要自定义凭据链。在下面的示例中，我们首先尝试托管标识，然后回退到 Azure CLI。如果您在 Azure 中运行代码，但希望在本地开发，这会很有用。

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

credential = ChainedTokenCredential(
    ManagedIdentityCredential(),
    AzureCliCredential()
)
```

## 部署

使用 Azure OpenAI，您可以设置自己的常见 GPT-3 和 Codex 模型的部署。调用 API 时，您需要指定要使用的部署。

***注意**：这些文档适用于 Azure 文本补全模型。像 GPT-4 这样的模型是聊天模型。它们的接口略有不同，可以通过 [`AzureChatOpenAI`](https://reference.langchain.com/python/langchain-openai/chat_models/azure/AzureChatOpenAI) 类访问。有关 Azure 聊天的文档，请参阅 [Azure Chat OpenAI 文档](/oss/python/integrations/chat/azure_chat_openai)。*

假设您的部署名称是 `gpt-35-turbo-instruct-prod`。在 `openai` Python API 中，您可以使用 `engine` 参数指定此部署。例如：

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

client = openai.AzureOpenAI(
    api_version="2023-12-01-preview",
)

response = client.completions.create(
    model="gpt-35-turbo-instruct-prod",
    prompt="Test prompt"
)
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install -qU  langchain-openai
```

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

os.environ["OPENAI_API_VERSION"] = "2023-12-01-preview"
os.environ["AZURE_OPENAI_ENDPOINT"] = "..."
os.environ["AZURE_OPENAI_API_KEY"] = "..."
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# 导入 Azure OpenAI
from langchain_openai import AzureOpenAI
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# 创建 Azure OpenAI 实例
# 将部署名称替换为您自己的
llm = AzureOpenAI(
    deployment_name="gpt-35-turbo-instruct-0914",
)
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# 运行 LLM
llm.invoke("Tell me a joke")
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
" Why couldn't the bicycle stand up by itself?\n\nBecause it was two-tired!"
```

我们也可以打印 LLM 并查看其自定义打印。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
print(llm)
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
AzureOpenAI
Params: {'deployment_name': 'gpt-35-turbo-instruct-0914', 'model_name': 'gpt-3.5-turbo-instruct', 'temperature': 0.7, 'top_p': 1, 'frequency_penalty': 0, 'presence_penalty': 0, 'n': 1, 'logit_bias': {}, 'max_tokens': 256}
```

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

***

<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/llms/azure_openai.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
