> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-docs-zh.mintlify.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 模型是 [聊天补全模型](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/models.md)。**
>
> 除非您正在特别使用 `gpt-3.5-turbo-instruct`，否则您可能需要查找 [这个页面](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/chat/azure_chat_openai.md)。

本页面将介绍如何使用 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={null}
# The API version you want to use: set this to `2023-12-01-preview` for the released version.
export OPENAI_API_VERSION=2023-12-01-preview
# The base URL for your Azure OpenAI resource.  You can find this in the Azure portal under your Azure OpenAI resource.
export AZURE_OPENAI_ENDPOINT=https://your-resource-name.openai.azure.com
# The API key for your Azure OpenAI resource.  You can find this in the Azure portal under your Azure OpenAI resource.
export AZURE_OPENAI_API_KEY=<your Azure OpenAI API key>
```

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

```python theme={null}
import os
os.environ["OPENAI_API_VERSION"] = "2023-12-01-preview"
```

## Azure 主动目录认证

您可以通过以下两种方式认证到 Azure OpenAI：

* API 密钥
* Azure Active Directory (AAD)

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

然而，如果您有复杂的 безопасности需求 - 您可能想要使用 Azure Active Directory。有关如何使用 AAD 与 Azure OpenAI 的更多信息，请参阅 [托管身份文档](https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/managed-identity)。

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

为您的 Azure OpenAI 资源添加一个 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={null}
import os
from azure.identity import DefaultAzureCredential

# Get the Azure Credential
credential = DefaultAzureCredential()

# Set the API type to `azure_ad`
os.environ["OPENAI_API_TYPE"] = "azure_ad"
# Set the API_KEY to the token from the Azure credential
os.environ["OPENAI_API_KEY"] = credential.get_token("https://cognitiveservices.azure.com/.default").token
```

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

```python theme={null}
from azure.identity import ChainedTokenCredential, ManagedIdentityCredential, AzureCliCredential

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

## 部署

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

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

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

```python theme={null}
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={null}
pip install -qU  langchain-openai
```

```python theme={null}
import os

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

```python theme={null}
# Import Azure OpenAI
from langchain_openai import AzureOpenAI
```

```python theme={null}
# Create an instance of Azure OpenAI
# Replace the deployment name with your own
llm = AzureOpenAI(
    deployment_name="gpt-35-turbo-instruct-0914",
)
```

```python theme={null}
# Run the LLM
llm.invoke("Tell me a joke")
```

```text theme={null}
" Why couldn't the bicycle stand up by itself?\n\nBecause it was two-tired!"
```

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

```python theme={null}
print(llm)
```

```text theme={null}
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={null}
```

***

> 官方原文：[src/oss/python/integrations/llms/azure\_openai.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/python/integrations/llms/azure_openai.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.