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

# Microsoft 集成

> 使用 LangChain Python 集成 Microsoft。

本页面涵盖了与 [Microsoft Azure](https://portal.azure.com) 及其他 [Microsoft](https://www.microsoft.com) 产品的所有 LangChain 集成。

> [!TIP]
>
> **推荐：Microsoft Foundry**
>
> 对于以 [Microsoft Foundry](https://learn.microsoft.com/en-us/azure/foundry/) 为中心的新的 LangChain 或 LangGraph 应用，请从 [`langchain-azure-ai`](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/providers/azure_ai) 开始。它添加了 Foundry 项目端点、Azure 凭证集成、智能体服务、托管、工具、内容安全、检索和 Azure 可观察性。
>
> 对于直接访问 [Azure OpenAI v1 API](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/api-version-lifecycle?tabs=python) 模型，代码在 OpenAI 和 Azure 之间切换、传统 Azure OpenAI API 版本、完成式 LLM 或更小的依赖表面，请使用 `langchain-openai` 包。
>
> Foundry 资源包括 Azure OpenAI 功能，并增加了更广泛的模型目录、智能体服务和评估功能。如果您使用 Azure OpenAI 资源，[将其升级为 Foundry 资源](https://learn.microsoft.com/en-us/azure/foundry/how-to/upgrade-azure-openai) 以保留现有的 API 端点、状态和安全配置，同时获得 Foundry 功能的访问权限。
>
> 对于智能体托管，请使用 [Microsoft Foundry 托管的智能体](#微软工厂托管智能体) 在具有内置运行时、会话、扩展、身份和协议端点的托管智能体平台上部署自定义 LangGraph 代码。
>
> **示例和教程：**
>
> * [microsoft-foundry/foundry-samples LangGraph 托管的智能体示例](https://github.com/microsoft-foundry/foundry-samples/tree/main/samples/python/hosted-agents/langgraph)：在本地运行 LangGraph 智能体或将它们部署到 Microsoft Foundry，包含响应、调用和 A2A 示例。
> * [Azure-Samples/langchain-azure-openai-starter](https://github.com/Azure-Samples/langchain-azure-openai-starter)：从生产就绪的 LangChain 和 Azure OpenAI 应用模板开始，允许您使用单个 `azd` 命令直接部署到 Azure。
> * [microsoft/langchain-for-beginners](https://github.com/microsoft/langchain-for-beginners)：一个动手课程，介绍使用 Azure OpenAI 的 LangChain。
> * [Azure-Samples/langchain-agent-python](https://github.com/Azure-Samples/langchain-agent-python)：在 Azure 上构建和部署 LangChain 智能体。

> [!NOTE]
>
> **Azure 上的 Claude**
>
> Microsoft Foundry 还提供对所有 [Anthropic Claude 模型](https://learn.microsoft.com/en-us/azure/foundry/foundry-models/how-to/use-foundry-models-claude) 的访问，包括 Opus、Sonnet 和 Haiku。Claude 模型通过专用的 Anthropic 原生端点提供服务，而不是 Azure OpenAI v1 API。使用 [`langchain-anthropic`](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/chat/anthropic) 指向您的 Foundry Anthropic 端点。

## 选择包

`langchain-azure-ai` 和 @\[`langchain-openai`] 是互补而非替代品。`langchain-azure-ai` 依赖于 `langchain-openai`，其聊天和嵌入类从 @\[`ChatOpenAI`] 和 @\[`OpenAIEmbeddings`] 继承，因此安装 Azure 包不会从您的依赖链中移除 OpenAI 包。

使用以下表格选择起点：

| 场景 | 包 |
| - | - |
| 以 Foundry 项目为中心的新应用 | `langchain-azure-ai` |
| Foundry 智能体服务、托管的 LangGraph、工具箱、内容安全、Azure 工具或 Application Insights | `langchain-azure-ai` |
| 从 Foundry 项目端点配置的嵌入 | `langchain-azure-ai` |
| 直接 Azure OpenAI v1 聊天调用 | `langchain-openai` |
| 相同代码必须在 OpenAI 和 Azure 之间切换 | `langchain-openai` |
| 现有的 @\[`AzureChatOpenAI`] 应用 | `langchain-openai` |
| 传统日期的 Azure OpenAI API 版本 | `langchain-openai` |
| 完成式 LLM 接口 | `langchain-openai` |
| 最小的依赖和操作表面 | `langchain-openai` |

将现有的 `langchain-openai` 应用迁移到 `langchain-azure-ai` 不是一个即插即用的导入更改：

* 配置不同。`azure_endpoint`、`azure_deployment`、`api_version` 和 token-provider 参数变为 `project_endpoint` 或 `endpoint`、`model` 和 `credential`。
* 默认行为不同。`AzureAIOpenAIApiChatModel` 在解析项目端点时默认为响应 API。设置 `use_responses_api=False` 以保持聊天补全行为。
* `langchain-azure-ai` 中不存在 @\[`AzureOpenAI`] 的完成式 LLM 对等物。
* @\[`AzureChatOpenAI`] 携带 Azure 特定的响应元数据和内容过滤处理，Foundry 聊天模型不会重现。
* 两个包都遵循官方 OpenAI 架构，因此由 DeepSeek 或 Mistral 等兼容提供者返回的非标准字段可能不会被保留。

## 聊天模型

Microsoft 通过 Azure 提供三种主要选项来访问聊天模型：

1. **Microsoft Foundry**（推荐用于以项目为中心的应用）：使用 `AzureAIOpenAIApiChatModel` 从 `langchain-azure-ai`，并使用 Foundry 项目端点和 Azure 凭证。此包还与 Foundry 智能体、托管、工具、内容安全、检索和可观察性集成。
2. **[Azure OpenAI](https://learn.microsoft.com/en-us/azure/ai-services/openai/)**：使用 `ChatOpenAI` 从 `langchain-openai` 进行直接 v1 API 调用或切换 OpenAI 和 Azure 的代码。使用 `AzureChatOpenAI` 用于传统 Azure OpenAI API 版本和现有应用。
3. **[Azure ML](https://learn.microsoft.com/en-us/azure/machine-learning/)**：允许使用 Azure 机器学习部署和管理自定义或微调的开源模型。

### Microsoft Foundry

Microsoft Foundry 提供项目级别的模型和 Azure 服务访问。当您的应用使用 Foundry 项目、Azure 凭证或其他 Foundry 功能时，请使用 `AzureAIOpenAIApiChatModel` 从 `langchain-azure-ai`。

```bash pip theme={null}
pip install -U langchain-azure-ai
```

```bash uv theme={null}
uv add langchain-azure-ai
```

设置您的项目端点：

```bash theme={null}
export AZURE_AI_PROJECT_ENDPOINT="https://<resource>.services.ai.azure.com/api/projects/<project>"
```

然后创建聊天模型：

```python theme={null}
from azure.identity import DefaultAzureCredential
from langchain_azure_ai.chat_models import AzureAIOpenAIApiChatModel

llm = AzureAIOpenAIApiChatModel(
    model="gpt-5.2",  # your Foundry model deployment name
    credential=DefaultAzureCredential(),
)
```

有关完整设置指南，请参阅 [Microsoft Foundry 聊天模型集成](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/chat/azure_ai.md)。

### Azure OpenAI

对于直接 Azure OpenAI 访问，[创建 Azure 部署](https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/create-resource) 并安装 `langchain-openai` 包：

```bash pip theme={null}
pip install -U langchain-openai
```

```bash uv theme={null}
uv add langchain-openai
```

在 v1 API 上，直接使用 `ChatOpenAI` 对您的 Azure 端点——无需 `api_version`：

> [tab] Entra ID (recommended)
>
> ```bash theme={null}
> pip install azure-identity
> ```
>
> ```python theme={null}
> from azure.identity import DefaultAzureCredential, get_bearer_token_provider
> from langchain_openai import ChatOpenAI
>
> token_provider = get_bearer_token_provider(
>     DefaultAzureCredential(),
>     "https://cognitiveservices.azure.com/.default",
> )
>
> llm = ChatOpenAI(
>     model="gpt-5.4-mini",  # your Azure deployment name
>     base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
>     api_key=token_provider,  # callable that handles token refresh
> )
> ```

> [tab] API key
>
> ```python theme={null}
> from langchain_openai import ChatOpenAI
>
> llm = ChatOpenAI(
>     model="gpt-5.4-mini",  # your Azure deployment name
>     base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
>     api_key="your-azure-api-key",
> )
> ```

对于传统的 Azure OpenAI API 版本，使用 `AzureChatOpenAI`：

```python theme={null}
from langchain_openai import AzureChatOpenAI
```

查看 [Azure ChatOpenAI 集成页面](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/chat/azure_chat_openai.md) 了解端到端设置、Entra ID 身份验证、工具调用和推理示例。

#### 响应 API

Azure OpenAI 支持 [响应 API](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/responses)，该 API 提供有状态对话、内置工具（网络搜索、文件搜索、代码解释器）和结构化推理摘要。 `ChatOpenAI` 在你设置 `reasoning` 参数时自动路由到响应 API，或者你可以使用 `use_responses_api=True` 显式启用：

> [tab] Entra ID (recommended)
>
> ```python theme={null}
> from azure.identity import DefaultAzureCredential, get_bearer_token_provider
> from langchain_openai import ChatOpenAI
>
> token_provider = get_bearer_token_provider(
>     DefaultAzureCredential(),
>     "https://cognitiveservices.azure.com/.default",
> )
>
> llm = ChatOpenAI(
>     model="gpt-5.4-mini",
>     base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
>     api_key=token_provider,
>     use_responses_api=True,
> )
>
> response = llm.invoke("Summarize the bitter lesson.")
> print(response.text)
> ```

> [tab] API key
>
> ```python theme={null}
> 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",
>     use_responses_api=True,
> )
>
> response = llm.invoke("Summarize the bitter lesson.")
> print(response.text)
> ```

有关响应 API 的推理工作、推理摘要和流式输出的使用说明，请查看 [Azure ChatOpenAI 集成页面](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/chat/azure_chat_openai.md)。

## 智能体

Microsoft 通过 Azure 提供两种主要选项来访问智能体：

1. **[Azure OpenAI](https://learn.microsoft.com/en-us/azure/ai-services/openai/)**（推荐）：使用 `AzureOpenAI` 从 `langchain-openai` 的 Azure OpenAI 文本补全部署。
2. **[Azure ML](https://learn.microsoft.com/en-us/azure/machine-learning/)**：使用部署在 Azure 机器学习在线端点上的自定义或开源模型。

### Azure OpenAI

查看 [使用示例](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/llms/azure_openai.md)。

```bash pip theme={null}
pip install -U langchain-openai
```

```bash uv theme={null}
uv add langchain-openai
```

> [tab] Entra ID (recommended)
>
> ```python theme={null}
> from azure.identity import DefaultAzureCredential, get_bearer_token_provider
> from langchain_openai import AzureOpenAI
>
> token_provider = get_bearer_token_provider(
>     DefaultAzureCredential(),
>     "https://cognitiveservices.azure.com/.default",
> )
>
> llm = AzureOpenAI(
>     azure_deployment="gpt-5.4-mini",  # your Azure deployment name
>     api_version="2025-04-01-preview",
>     azure_ad_token_provider=token_provider,
> )
>
> print(llm.invoke("Write a haiku about the ocean."))
> ```

> [tab] API key
>
> ```python theme={null}
> from langchain_openai import AzureOpenAI
>
> llm = AzureOpenAI(
>     azure_deployment="gpt-5.4-mini",  # your Azure deployment name
>     api_version="2025-04-01-preview",
>     azure_endpoint="https://YOUR-RESOURCE-NAME.openai.azure.com/",
>     api_key="your-azure-api-key",
> )
>
> print(llm.invoke("Write a haiku about the ocean."))
> ```

## 嵌入模型

根据你的应用程序如何连接到 Azure 选择嵌入集成：

1. **Microsoft Foundry**（推荐用于以项目为中心的应用程序）：使用 `AzureAIOpenAIApiEmbeddingsModel` 从 `langchain-azure-ai`，结合 Foundry 项目配置和 Azure 凭据。
2. **[Azure OpenAI](https://learn.microsoft.com/en-us/azure/ai-services/openai/)**：使用 @\[`AzureOpenAIEmbeddings`] 从 `langchain-openai`，用于直接或传统的 Azure OpenAI 端点、现有应用程序或更小的依赖表面。

### Microsoft Foundry

安装 `langchain-azure-ai`：

```bash pip theme={null}
pip install -U langchain-azure-ai
```

```bash uv theme={null}
uv add langchain-azure-ai
```

设置你的项目端点：

```bash theme={null}
export AZURE_AI_PROJECT_ENDPOINT="https://<resource>.services.ai.azure.com/api/projects/<project>"
```

然后创建嵌入模型：

```python theme={null}
from azure.identity import DefaultAzureCredential
from langchain_azure_ai.embeddings import AzureAIOpenAIApiEmbeddingsModel

embeddings = AzureAIOpenAIApiEmbeddingsModel(
    model="text-embedding-3-small",  # your Foundry model deployment name
    credential=DefaultAzureCredential(),
)
```

> [!NOTE]
>
> Foundry 项目配置目前直接派生 `/openai/v1` 端点，因为嵌入尚未通过项目端点本身提供服务。

更多信息，请查看 [Microsoft Foundry 嵌入集成](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/providers/azure_ai.md#azure-ai模型推理（嵌入）)。

### Azure OpenAI

查看 [使用示例](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/embeddings/azure_openai.md)。

```bash pip theme={null}
pip install -U langchain-openai
```

```bash uv theme={null}
uv add langchain-openai
```

> [tab] Entra ID (recommended)
>
> ```python theme={null}
> from azure.identity import DefaultAzureCredential, get_bearer_token_provider
> from langchain_openai import AzureOpenAIEmbeddings
>
> token_provider = get_bearer_token_provider(
>     DefaultAzureCredential(),
>     "https://cognitiveservices.azure.com/.default",
> )
>
> embeddings = AzureOpenAIEmbeddings(
>     azure_deployment="text-embedding-3-small",  # your Azure deployment name
>     api_version="2025-04-01-preview",
>     azure_ad_token_provider=token_provider,
> )
>
> vector = embeddings.embed_query("LangChain makes agents easy.")
> ```

> [tab] API key
>
> ```python theme={null}
> from langchain_openai import AzureOpenAIEmbeddings
>
> embeddings = AzureOpenAIEmbeddings(
>     azure_deployment="text-embedding-3-small",  # your Azure deployment name
>     api_version="2025-04-01-preview",
>     azure_endpoint="https://YOUR-RESOURCE-NAME.openai.azure.com/",
>     api_key="your-azure-api-key",
> )
>
> vector = embeddings.embed_query("LangChain makes agents easy.")
> ```

## 中间件

### Azure AI 内容安全中间件

> [Azure AI 内容安全](https://learn.microsoft.com/en-us/azure/ai-services/content-safety/overview) 提供了您可以通过中间件应用于 LangChain 智能体的约束。`langchain-azure-ai` 包目前导出用于文本审核、图像审核、提示词注入检测、受保护材料检测和事实性评估的中间件。

安装中间件包：

```bash pip theme={null}
pip install -U langchain-azure-ai
```

```bash uv theme={null}
uv add langchain-azure-ai
```

参见 [Microsoft Foundry 中间件指南](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/middleware/azure_ai.md)。

```python theme={null}
from langchain_azure_ai.agents.middleware import AzureContentModerationMiddleware
```

## 文档加载器

### Azure Blob 存储

> [Azure Blob 存储](https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blobs-introduction) 是微软的云对象存储解决方案。Blob 存储针对存储海量非结构化数据进行了优化。非结构化数据是指不遵循特定数据模型或定义的数据，例如文本或二进制数据。

`Azure Blob Storage` 设计用于：

* 直接将图像或文档提供给浏览器。
* 存储用于分布式访问的文件。
* 流式传输视频和音频。
* 写入日志文件。
* 存储用于备份和恢复、灾难恢复和归档的数据。
* 存储用于本地或 Azure 托管的服务的分析的数据。

```bash pip theme={null}
pip install langchain-azure-storage
```

```bash uv theme={null}
uv add langchain-azure-storage
```

参见 [Azure Blob 存储加载器的使用示例](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/document_loaders/azure_blob_storage.md)。

```python theme={null}
from langchain_azure_storage.document_loaders import AzureBlobStorageLoader
```

## 后端

### Azure Blob 存储后端

> [Azure Blob 存储](https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blobs-introduction) 是微软的云对象存储解决方案。`AzureBlobBackend` 实现了 Deep Agents `BackendProtocol`，因此深度智能体可以将其整个工作区（文件、记忆和工件）持久化到 blob 容器中。

> [!NOTE]
>
> `AzureBlobBackend` 是 `langchain-azure-storage` 包的一部分，该包目前处于 **公共预览** 状态。

使用 `deepagents` 扩展进行安装（需要 Python 3.11+）：

```bash pip theme={null}
pip install -U "langchain-azure-storage[deepagents]"
```

```bash uv theme={null}
uv add "langchain-azure-storage[deepagents]"
```

```python theme={null}
from langchain_azure_storage.deepagents import AzureBlobBackend
```

**快速入门：**

```python theme={null}
from deepagents import create_deep_agent
from langchain_azure_storage.deepagents import AzureBlobBackend

backend = AzureBlobBackend(
    account_url="https://<my-storage-account-name>.blob.core.windows.net",
    container_name="agent-workspace",
    prefix="session-001/",  # Optional: isolate each agent/session under a prefix.
)

agent = create_deep_agent(backend=backend)

result = agent.invoke(
    {"messages": [{"role": "user", "content": "Write a hello world script to hello.py"}]}
)
```

后端默认为 [`DefaultAzureCredential`](https://learn.microsoft.com/en-us/azure/developer/python/sdk/authentication/credential-chains?tabs=dac#defaultazurecredential-overview)，并接受 `credential` 覆盖。

有关更多信息，请参见 [后端集成](https://langchain-docs-zh.mintlify.site/langchain/oss/integrations/backends.md)。有关完整使用细节和安全指南，请参见 [包存储库](https://github.com/langchain-ai/langchain-azure/tree/main/libs/azure-storage)。

## 记忆

### Azure cosmos DB 聊天消息历史

> [Azure Cosmos DB](https://learn.microsoft.com/azure/cosmos-db/) 为对话式 AI 应用程序提供聊天消息历史存储，使您能够以低延迟和高可用性持久化和检索对话历史。

```bash pip theme={null}
pip install langchain-azure-cosmosdb
```

```bash uv theme={null}
uv add langchain-azure-cosmosdb
```

配置您的 Azure Cosmos DB 连接（同步或异步，使用访问密钥或 Microsoft Entra ID）：

```python theme={null}
from langchain_azure_cosmosdb import CosmosDBChatMessageHistory

history = CosmosDBChatMessageHistory(
    cosmos_endpoint="https://<your-account>.documents.azure.com:443/",
    cosmos_database="<your-database>",
    cosmos_container="<your-container>",
    session_id="<session-id>",
    user_id="<user-id>",
    credential="<your-key-or-token-credential>",
    ttl=3600,  # optional: messages expire after 1 hour
)
history.prepare_cosmos()

history.add_user_message("Hello!")
history.add_ai_message("Hi there!")
```

对于异步使用，从同一包中导入 `AsyncCosmosDBChatMessageHistory`。

### Azure cosmos DB 语义缓存

> [`AzureCosmosDBNoSqlSemanticCache`](https://github.com/langchain-ai/langchain-azure/tree/main/libs/azure-cosmosdb) 在 Azure Cosmos DB 中缓存 LLM 响应以 NoSQL 使用向量相似性，当再次看到语义相似的提示词时返回缓存的结果。

```bash pip theme={null}
pip install langchain-azure-cosmosdb
```

```bash uv theme={null}
uv add langchain-azure-cosmosdb
```

```python theme={null}
from azure.cosmos import CosmosClient, PartitionKey
from langchain_core.globals import set_llm_cache
from langchain_azure_cosmosdb import AzureCosmosDBNoSqlSemanticCache

cosmos_client = CosmosClient("<endpoint>", "<key>")

cache = AzureCosmosDBNoSqlSemanticCache(
    cosmos_client=cosmos_client,
    embedding=embedding,
    vector_embedding_policy=vector_embedding_policy,
    indexing_policy=indexing_policy,
    cosmos_container_properties={"partition_key": PartitionKey(path="/id")},
    cosmos_database_properties={"id": "cache-db"},
    vector_search_fields={"text_field": "text", "embedding_field": "embedding"},
    database_name="cache-db",
    container_name="cache-container",
)

set_llm_cache(cache)
```

对于异步使用，导入 `AsyncAzureCosmosDBNoSqlSemanticCache`。

## 向量存储

### Azure cosmos DB

AI 智能体可以依赖 Azure Cosmos DB 作为统一的 [记忆系统](https://learn.microsoft.com/en-us/azure/cosmos-db/ai-agents#ai-agent-memory-system) 解决方案，享受速度、规模和简单性。该服务成功 [使 OpenAI 的 ChatGPT 服务](https://www.youtube.com/watch?v=6IIUtEFKJec\&t) 能够以高可靠性和低维护成本动态扩展。由 atom-record-sequence 引擎驱动，它是世界上第一个提供无服务器模式的 [NoSQL](https://learn.microsoft.com/en-us/azure/cosmos-db/distributed-nosql)、[关系型](https://learn.microsoft.com/en-us/azure/cosmos-db/distributed-relational) 和 [向量数据库](https://learn.microsoft.com/en-us/azure/cosmos-db/vector-database) 服务。

以下是两个可用的 Azure Cosmos DB API，它们可以提供向量存储功能。

#### Azure cosmos DB for MongoDB (vCore)

> [Azure Cosmos DB for MongoDB vCore](https://learn.microsoft.com/en-us/azure/documentdb/) 使创建具有完整原生 MongoDB 支持的数据库变得轻松。
> 您可以通过将应用程序指向 MongoDB vCore 账户的连接字符串来应用您的 MongoDB 经验，并继续使用您喜欢的 MongoDB 驱动程序、SDK 和工具。
> 在 Azure Cosmos DB for MongoDB vCore 中使用向量搜索，可以无缝地将基于 AI 的应用程序与存储在 Azure Cosmos DB 中的数据集成。

#### 安装和设置

参见 [详细配置说明](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/vectorstores/azure_cosmos_db_mongo_vcore.md)。

我们需要安装 `langchain-azure-ai` 和 `pymongo` Python 包。

```bash pip theme={null}
pip install langchain-azure-ai pymongo
```

```bash uv theme={null}
uv add langchain-azure-ai pymongo
```

#### 在 Microsoft Azure 上部署 Azure cosmos DB

Azure Cosmos DB for MongoDB vCore 为开发人员提供了一个完全托管的 MongoDB 兼容数据库服务，用于构建具有熟悉架构的现代应用程序。

使用 Cosmos DB for MongoDB vCore，开发人员可以享受原生 Azure 集成、低拥有总成本（TCO）以及在迁移现有应用程序或构建新应用程序时熟悉的 vCore 架构带来的好处。

[免费注册](https://azure.microsoft.com/en-us/free/) 以开始使用。

参见 [使用示例](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/vectorstores/azure_cosmos_db_mongo_vcore.md)。

```python theme={null}
from langchain_azure_ai.vectorstores import AzureCosmosDBMongoVCoreVectorSearch
```

#### Azure cosmos DB NoSQL

> [Azure Cosmos DB for NoSQL](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/vector-search) 现在提供向量索引和搜索功能（预览版）。
> 此功能设计用于处理高维向量，能够在任何规模下实现高效和准确的向量搜索。现在您可以直接在文档中将向量存储在您的数据旁边。这意味着数据库中的每个文档不仅可以包含传统的无模式数据，还可以包含作为文档其他属性的维度向量。数据和向量的这种共存允许高效索引和搜索，因为向量存储在与它们表示的数据相同的逻辑单元中。这简化了数据管理、AI 应用程序架构以及基于向量的操作的效率。

#### 安装和设置

参见 [详细配置说明](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/vectorstores/azure_cosmos_db_no_sql.md)。

我们需要安装 `langchain-azure-cosmosdb` 和 `azure-cosmos` Python 包。

```bash pip theme={null}
pip install langchain-azure-cosmosdb azure-cosmos
```

```bash uv theme={null}
uv add langchain-azure-cosmosdb azure-cosmos
```

#### 在 Microsoft Azure 上部署 Azure cosmos DB

Azure Cosmos DB 通过动态和弹性自动扩展提供高度响应的解决方案，适用于现代应用和智能工作负载。它可在每个 Azure 区域提供，并自动将数据复制到靠近用户的位置。它具有 SLA 保证的低延迟和高可用性。

[免费注册](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/quickstart-python?pivots=devcontainer-codespace)，立即开始使用。

查看 [使用示例](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/vectorstores/azure_cosmos_db_no_sql.md)。

```python theme={null}
from langchain_azure_cosmosdb import AzureCosmosDBNoSqlVectorSearch
```

### Azure Database for PostgreSQL

> [Azure Database for PostgreSQL - Flexible Server](https://learn.microsoft.com/en-us/azure/postgresql/flexible-server/service-overview) 是基于开源 Postgres 数据库引擎的关系型数据库服务。它是一种完全管理的数据库即服务，能够以可预测的性能、安全性、高可用性和动态可扩展性处理关键任务工作负载。

查看 Azure Database for PostgreSQL 的 [设置说明](https://learn.microsoft.com/en-us/azure/postgresql/flexible-server/quickstart-create-server-portal)。

直接使用 Azure 门户中的 [连接字符串](https://learn.microsoft.com/en-us/azure/postgresql/flexible-server/connect-python?tabs=cmd%2Cpassword#add-authentication-code)。

由于 Azure Database for PostgreSQL 是开源 Postgres，您可以使用 [LangChain 的 Postgres 支持](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/vectorstores/pgvector.md) 连接到 Azure Database for PostgreSQL。

### Azure SQL Database

> [Azure SQL Database](https://learn.microsoft.com/azure/azure-sql/database/sql-database-paas-overview?view=azuresql) 是一种强大的服务，结合了可扩展性、安全性和高可用性，提供现代数据库解决方案的所有好处。它还提供专用的 Vector 数据类型和内置函数，可简化在关系型数据库中直接存储和查询向量嵌入。这消除了对单独向量数据库及相关集成的需求，提高了解决方案的安全性，同时降低了整体复杂性。

通过利用现有的 SQL Server 数据库进行向量搜索，您可以在最小化成本的同时增强数据能力，并避免过渡到新系统的挑战。

#### 安装和设置

查看 [详细配置说明](https://learn.microsoft.com/azure/azure-sql/database/ai-artificial-intelligence-intelligent-applications?view=azuresql)。

我们需要安装 `langchain-sqlserver` Python 包。

```bash theme={null}
!pip install langchain-sqlserver==0.1.1
```

#### 在 Microsoft Azure 上部署 Azure SQL DB

[免费注册](https://learn.microsoft.com/azure/azure-sql/database/free-offer?view=azuresql)，立即开始使用。

查看 [使用示例](https://learn.microsoft.com/azure/azure-sql/database/ai-artificial-intelligence-intelligent-applications?view=azuresql)。

```python theme={null}
from langchain_sqlserver import SQLServer_VectorStore
```

## 向量存储

### Azure Database for PostgreSQL

> [Azure Database for PostgreSQL - Flexible Server](https://learn.microsoft.com/en-us/azure/postgresql/flexible-server/service-overview) 是基于开源 Postgres 数据库引擎的关系型数据库服务。它是一种完全管理的数据库即服务，能够以可预测的性能、安全性、高可用性和动态可扩展性处理关键任务工作负载。

查看 Azure Database for PostgreSQL 的 [设置说明](https://learn.microsoft.com/en-us/azure/postgresql/flexible-server/quickstart-create-server-portal)。

您需要在数据库中 [启用 pgvector 扩展](https://learn.microsoft.com/en-us/azure/postgresql/flexible-server/how-to-use-pgvector)，才能将 Postgres 用作向量存储。启用扩展后，您可以使用 [PGVector in LangChain](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/vectorstores/pgvector.md) 连接到 Azure Database for PostgreSQL。

查看 [使用示例](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/vectorstores/pgvector.md)。直接使用 Azure 门户中的 [连接字符串](https://learn.microsoft.com/en-us/azure/postgresql/flexible-server/connect-python?tabs=cmd%2Cpassword#add-authentication-code)。

## 工具

### Microsoft Foundry 工具

Microsoft Foundry 暴露 LangChain 服务工具，用于 Azure AI 内容理解、文档智能、图像分析和健康文本分析。

使用 `tools` 附加包安装：

```bash pip theme={null}
pip install -U "langchain-azure-ai[tools]"
```

```bash uv theme={null}
uv add "langchain-azure-ai[tools]"
```

查看 [Microsoft Foundry 工具指南](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/tools/azure_ai_services.md)。

```python theme={null}
from langchain_azure_ai.tools import AzureAIDocumentIntelligenceTool
```

### 图像生成工具

Microsoft Foundry Models 目录中有多个模型可用于图像生成。

查看 [Microsoft Foundry 工具指南](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/tools/azure_ai.md)。

```python theme={null}
from langchain_azure_ai.tools import AzureOpenAIModelImageGenTool
```

### 转录工具

Microsoft Foundry Models 目录中有 Whisper 模型可用于语音转文本转录。

查看 [Microsoft Foundry 工具指南](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/tools/azure_ai.md)。

```python theme={null}
from langchain_azure_ai.tools import AzureOpenAITranscriptionsTool
```

### 代码解释工具（服务器端）

使用代码解释工具在沙盒容器中服务器端运行 Python 代码。

查看 [Microsoft Foundry 工具指南](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/tools/azure_ai.md)。

```python theme={null}
from langchain_azure_ai.tools.builtin import CodeInterpreterTool
```

### 网络搜索工具（服务器端）

搜索互联网以获取当前信息和来源。

查看 [Microsoft Foundry 工具指南](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/tools/azure_ai.md)。

```python theme={null}
from langchain_azure_ai.tools.builtin import WebSearchTool
```

### 文件搜索工具（服务器端）

搜索向量存储以获取相关文档内容。

查看 [Microsoft Foundry 工具指南](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/tools/azure_ai.md)。

```python theme={null}
from langchain_azure_ai.tools.builtin import FileSearchTool
```

### 图像生成工具（服务器端）

使用 GPT 图像模型在 Azure AI Foundry 服务器端生成或编辑图像。

查看 [Microsoft Foundry 工具指南](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/tools/azure_ai.md)。

```python theme={null}
from langchain_azure_ai.tools.builtin import ImageGenerationTool
```

### MCP 工具（服务器端）

访问外部模型上下文协议 (MCP) 服务器。

查看 [Microsoft Foundry 工具指南](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/tools/azure_ai.md)。

```python theme={null}
from langchain_azure_ai.tools.builtin import McpTool
```

### Azure Container Apps 动态会话

我们需要从 Azure Container Apps 服务获取 `POOL_MANAGEMENT_ENDPOINT` 环境变量。
查看 [Azure 动态会话设置说明](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/tools/azure_dynamic_sessions.md#设置)。

我们需要安装一个 Python 包。

```bash pip theme={null}
pip install langchain-azure-dynamic-sessions
```

```bash uv theme={null}
uv add langchain-azure-dynamic-sessions
```

查看 [使用示例](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/tools/azure_dynamic_sessions.md)。

```python theme={null}
from langchain_azure_dynamic_sessions import SessionsPythonREPLTool
```

### Azure Logic Apps

触发 Azure Logic Apps 工作流以自动化业务流程和集成。

使用 `tools` 附加包安装：

```bash pip theme={null}
pip install -U "langchain-azure-ai[tools]"
```

```bash uv theme={null}
uv add "langchain-azure-ai[tools]"
```

查看 [Azure Logic Apps 集成指南](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/tools/azure_logic_apps.md)。

```python theme={null}
from langchain_azure_ai.tools import AzureLogicAppTool
```

## 工具包

### Microsoft Foundry 项目工具箱

通过模型上下文协议 (MCP) 动态从 Azure AI Foundry 工具箱加载工具。

使用 `tools` 附加包安装：

```bash pip theme={null}
pip install -U "langchain-azure-ai[tools]" langchain-mcp-adapters httpx
```

```bash uv theme={null}
uv add "langchain-azure-ai[tools]" langchain-mcp-adapters httpx
```

查看 [Azure AI Foundry 工具箱指南](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/tools/azure_ai.md#azureaiprojecttoolbox)。

```python theme={null}
from langchain_azure_ai.tools import AzureAIProjectToolbox
```

### Microsoft Foundry 工具（原 Azure AI 服务）

安装集成包：

```bash pip theme={null}
pip install -U "langchain-azure-ai[tools]"
```

```bash uv theme={null}
uv add "langchain-azure-ai[tools]"
```

查看 [使用示例](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/tools/azure_ai_services.md)。

```python theme={null}
from langchain_azure_ai.tools import AzureAIServicesToolkit
```

The `AzureAIServicesToolkit` 工具包包含以下工具：

* 图像分析：[AzureAIImageAnalysisTool](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/tools/azure_ai_services.md#azureaiimageanalysistool)
* 文档智能：[AzureAIDocumentIntelligenceTool](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/tools/azure_ai_services.md#azureaidocumentintelligencetool)
* 语音转文本：[AzureAISpeechToTextTool](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/tools/azure_ai_services.md#azureaispeechtotexttool)
* 文本转语音：[AzureAITextToSpeechTool](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/tools/azure_ai_services.md#azureaitexttospeechtool)
* 健康文本分析：[AzureAITextAnalyticsHealthTool](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/tools/azure_ai_services.md#azureaitextanalyticshealthtool)

## 运行时

### 微软工厂托管智能体

[微软工厂托管智能体](https://learn.microsoft.com/en-us/azure/foundry/how-to/develop/langchain-hosted-agents)在一个托管运行时中运行自定义 LangGraph 代码。使用 `langchain_azure_ai.agents.hosting` 包来暴露编译后的 LangGraph 图，同时由工厂管理运行时、会话、扩展、身份和协议端点。

> [!NOTE]
>
> LangGraph 托管支持需要 `langchain-azure-ai[hosting]>=1.2.8`。

开始之前，您需要一个 Azure 订阅、一个工厂项目、一个部署的对话模型、Python 3.10 或更高版本，以及 Azure CLI 身份验证。部署智能体还需要在项目上具有工厂项目管理员角色。

根据客户端如何与智能体交互，选择托管协议：

| 协议 | 运行参数 | SDK 主机类 | 端点 | 使用场景 |
| - | - | - | - | - |
| 响应 | `--protocol responses` | `ResponsesHostServer` | `/responses` | 您需要兼容 OpenAI 的聊天、流式输出、响应历史记录或对话线程。大多数对话智能体从这里开始。 |
| 调用 | `--protocol invocations` | `InvocationsHostServer` | `/invocations` | 您需要一个自定义的 JSON 形状、一个 webhook 风格的端点或非对话处理。 |

> [!NOTE]
>
> 对于使用基于 `BaseChatOpenAI` 模型的响应 API 的托管图，使用 `output_version="responses/v1"`。在 `langchain-openai` 1.0.0 或更高版本中，您可以省略此设置，除非被 `LC_OUTPUT_VERSION` 覆盖。此指导适用于响应和调用托管协议。

查看 [响应协议](https://github.com/microsoft-foundry/foundry-samples/tree/main/samples/python/hosted-agents/langgraph/responses/10-run) 和 [调用协议](https://github.com/microsoft-foundry/foundry-samples/tree/main/samples/python/hosted-agents/langgraph/invocations/03-run) 的完整运行示例。

#### 使用配置驱动的运行器

如果您的智能体已经使用 LangGraph CLI 运行，请使用 `langchain_azure_ai.agents.hosting.run` 工具从同一项目目录。运行器使用现有的 `langgraph.json` 配置来加载编译后的图，因此无需代码更改。

设置工厂项目端点和模型部署名称，然后在启动主机时选择协议：

> [tab] Responses
>
> ```bash theme={null}
> export FOUNDRY_PROJECT_ENDPOINT="https://<account>.services.ai.azure.com/api/projects/<project>"
> export AZURE_AI_MODEL_DEPLOYMENT_NAME="<model-deployment-name>"
> python -m langchain_azure_ai.agents.hosting.run --protocol responses
> ```

> [tab] Invocations
>
> ```bash theme={null}
> export FOUNDRY_PROJECT_ENDPOINT="https://<account>.services.ai.azure.com/api/projects/<project>"
> export AZURE_AI_MODEL_DEPLOYMENT_NAME="<model-deployment-name>"
> python -m langchain_azure_ai.agents.hosting.run --protocol invocations
> ```

对于部署，在 `azure.yaml` 中的智能体服务上设置 `codeConfiguration.entryPoint` 为相同的运行器和协议。保留现有的项目路径、运行时和依赖解析设置：

> [tab] Responses
>
> ```yaml theme={null}
> services:
>     my-agent:
>         codeConfiguration:
>             entryPoint: '-m langchain_azure_ai.agents.hosting.run --protocol responses'
> ```

> [tab] Invocations
>
> ```yaml theme={null}
> services:
>     my-agent:
>         codeConfiguration:
>             entryPoint: '-m langchain_azure_ai.agents.hosting.run --protocol invocations'
> ...
> ```

#### 使用 SDK 主机类

当您需要自定义服务器构建、直接控制服务器生命周期或实现高级托管行为（如自定义路由或处理器）时，使用 SDK 主机类：

> [tab] Responses
>
> ```python theme={null}
> from langchain_azure_ai.agents.hosting import ResponsesHostServer
>
> ResponsesHostServer(graph).run()
> ```

> [tab] Invocations
>
> ```python theme={null}
> from langchain_azure_ai.agents.hosting import InvocationsHostServer
>
> InvocationsHostServer(graph).run()
> ```

要部署任何方法，使用 `azd ai agent init` 初始化托管智能体项目，使用 `azd ai agent run` 本地测试，并使用 `azd deploy` 部署。仅在需要创建工厂项目或其他 Azure 资源时，首先运行 `azd provision`。您也可以使用工厂工具包 Visual Studio Code 扩展部署。

微软学习指南包含两个协议的完整示例、对话状态、人工参与流程、测试、部署和故障排除。

***

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


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