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

# Azure AI 搜索集成

> 使用 LangChain Python 与 Azure AI 搜索检索器集成。

[Azure AI 搜索](https://learn.microsoft.com/azure/search/search-what-is-azure-search)（以前称为 `Azure 认知搜索`）是一项 Microsoft 云搜索服务，它为开发人员提供基础设施、API 和工具，用于大规模地检索向量、关键词和混合查询的信息。

`AzureAISearchRetriever` 是一个集成模块，用于从非结构化查询中返回文档。它基于 `BaseRetriever` 类，并针对 Azure AI 搜索的 2023-11-01 稳定 REST API 版本，这意味着它支持向量索引和查询。

本指南将帮助您开始使用 Azure AI 搜索 [检索器](/oss/python/langchain/retrieval)。有关所有 `AzureAISearchRetriever` 功能和配置的详细文档，请前往 [API 参考](https://reference.langchain.com/python/langchain-community/retrievers/azure_ai_search/AzureAISearchRetriever)。

`AzureAISearchRetriever` 取代了 `AzureCognitiveSearchRetriever`，后者即将被弃用。我们建议切换到基于最新稳定版搜索 API 的新版本。

### 集成详情

<ItemTable category="document_retrievers" item="AzureAISearchRetriever" />

## 设置

要使用此模块，您需要：

* Azure AI 搜索服务。如果您注册 Azure 试用版，可以免费 [创建一个](https://learn.microsoft.com/azure/search/search-create-service-portal)。免费服务的配额较低，但足以运行此笔记本中的代码。

* 具有向量字段的现有索引。有几种方法可以创建索引，包括使用 [向量存储模块](../vectorstores/azuresearch.ipynb)。或者，[尝试 Azure AI 搜索 REST API](https://learn.microsoft.com/azure/search/search-get-started-vector)。

* API 密钥或 Azure AD 令牌。
  * API 密钥在创建搜索服务时生成。如果您只是查询索引，可以使用查询 API 密钥，否则请使用管理员 API 密钥。有关详细信息，请参阅 [查找您的 API 密钥](https://learn.microsoft.com/azure/search/search-security-api-keys?tabs=rest-use%2Cportal-find%2Cportal-query#find-existing-keys)。
  * Azure AD 令牌可与 Azure 托管标识一起使用。有关详细信息，请参阅 [使用标识将应用连接到 Azure AI 搜索](https://learn.microsoft.com/en-us/azure/search/keyless-connections?tabs=python%2Cazure-cli)。

然后，我们可以将搜索服务名称、索引名称和 API 密钥设置为环境变量（或者，您可以将它们作为参数传递给 `AzureAISearchRetriever`）。搜索索引提供可搜索的内容。

使用 API 密钥

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

os.environ["AZURE_AI_SEARCH_SERVICE_NAME"] = "<YOUR_SEARCH_SERVICE_NAME>"
os.environ["AZURE_AI_SEARCH_INDEX_NAME"] = "<YOUR_SEARCH_INDEX_NAME>"
os.environ["AZURE_AI_SEARCH_API_KEY"] = "<YOUR_API_KEY>"
```

使用 Azure AD 令牌

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

os.environ["AZURE_AI_SEARCH_SERVICE_NAME"] = "<YOUR_SEARCH_SERVICE_NAME>"
os.environ["AZURE_AI_SEARCH_INDEX_NAME"] = "<YOUR_SEARCH_INDEX_NAME>"
os.environ["AZURE_AI_SEARCH_AD_TOKEN"] = "<YOUR_AZURE_AD_TOKEN>"
```

如果您希望从单个查询中获得自动跟踪，您还可以通过取消注释以下内容来设置您的 [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"
```

### 安装

此检索器位于 `langchain-community` 包中。我们还需要一些额外的依赖项：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install -qU langchain-community
pip install -qU langchain-openai
pip install -qU  azure-search-documents>=11.4
pip install -qU  azure-identity
```

## 实例化

对于 `AzureAISearchRetriever`，请提供 `index_name`、`content_key` 和 `top_k`，其中 `top_k` 设置为您想要检索的结果数量。将 `top_k` 设置为零（默认值）将返回所有结果。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_community.retrievers import AzureAISearchRetriever

retriever = AzureAISearchRetriever(
    content_key="content", top_k=1, index_name="langchain-vector-demo"
)
```

## 用法

现在您可以使用它从 Azure AI 搜索检索文档。这是您要调用的方法。它将返回与查询相关的所有文档。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
retriever.invoke("here is my unstructured query string")
```

## 示例

本节演示如何使用内置样本数据使用检索器。如果您的搜索服务上已经有向量索引，可以跳过此步骤。

首先提供端点和密钥。由于我们在这一步中创建向量索引，因此请指定一个文本嵌入模型以获取文本的向量表示。此示例假设使用 Azure OpenAI 以及 text-embedding-ada-002 部署。因为此步骤会创建索引，请务必为您的搜索服务使用管理员 API 密钥。

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

from langchain_community.document_loaders import DirectoryLoader, TextLoader
from langchain_community.retrievers import AzureAISearchRetriever
from langchain_community.vectorstores import AzureSearch
from langchain_openai import AzureOpenAIEmbeddings, OpenAIEmbeddings
from langchain_text_splitters import TokenTextSplitter

os.environ["AZURE_AI_SEARCH_SERVICE_NAME"] = "<YOUR_SEARCH_SERVICE_NAME>"
os.environ["AZURE_AI_SEARCH_INDEX_NAME"] = "langchain-vector-demo"
os.environ["AZURE_AI_SEARCH_API_KEY"] = "<YOUR_SEARCH_SERVICE_ADMIN_API_KEY>"
azure_endpoint: str = "<YOUR_AZURE_OPENAI_ENDPOINT>"
azure_openai_api_key: str = "<YOUR_AZURE_OPENAI_API_KEY>"
azure_openai_api_version: str = "2023-05-15"
azure_deployment: str = "text-embedding-ada-002"
```

我们将使用来自 Azure OpenAI 的嵌入模型将我们的文档转换为存储在 Azure AI 搜索向量存储中的嵌入。我们还将索引名称设置为 `langchain-vector-demo`。这将创建一个与该索引名称关联的新向量存储。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
embeddings = AzureOpenAIEmbeddings(
    model=azure_deployment,
    azure_endpoint=azure_endpoint,
    openai_api_key=azure_openai_api_key,
)

vector_store: AzureSearch = AzureSearch(
    embedding_function=embeddings.embed_query,
    azure_search_endpoint=os.getenv("AZURE_AI_SEARCH_SERVICE_NAME"),
    azure_search_key=os.getenv("AZURE_AI_SEARCH_API_KEY"),
    index_name="langchain-vector-demo",
)
```

接下来，我们将数据加载到新创建的向量存储中。对于此示例，我们加载 `state_of_the_union.txt` 文件。我们将文本拆分为 400 个 token 的块，无重叠。最后，文档作为嵌入添加到我们的向量存储中。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_community.document_loaders import TextLoader
from langchain_text_splitters import CharacterTextSplitter

loader = TextLoader("../../how_to/state_of_the_union.txt", encoding="utf-8")

documents = loader.load()
text_splitter = CharacterTextSplitter(chunk_size=400, chunk_overlap=0)
docs = text_splitter.split_documents(documents)

vector_store.add_documents(documents=docs)
```

接下来，我们将创建一个检索器。当前的 `index_name` 变量是上一步中的 `langchain-vector-demo`。如果您跳过了向量存储创建，请在参数中提供您的索引名称。在此查询中，将返回顶部结果。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
retriever = AzureAISearchRetriever(
    content_key="content", top_k=1, index_name="langchain-vector-demo"
)
```

现在我们可以从上传的文档中检索与我们的查询相关的数据。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
retriever.invoke("does the president have a plan for covid-19?")
```

## 在链中使用

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_openai import ChatOpenAI

prompt = ChatPromptTemplate.from_template(
    """Answer the question based only on the context provided.

Context: {context}

Question: {question}"""
)

llm = ChatOpenAI(model="gpt-4.1-mini")


def format_docs(docs):
    return "\n\n".join(doc.page_content for doc in docs)


chain = (
    {"context": retriever | format_docs, "question": RunnablePassthrough()}
    | prompt
    | llm
    | StrOutputParser()
)
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
chain.invoke("does the president have a plan for covid-19?")
```

***

## API 参考

有关所有 `AzureAISearchRetriever` 功能和配置的详细文档，请前往 [API 参考](https://reference.langchain.com/python/langchain-community/retrievers/azure_ai_search/AzureAISearchRetriever)。

***

<div className="source-links">
  <Callout icon="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/i18n\zh-CN\oss\python\integrations\retrievers\azure_ai_search.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
  </Callout>

  <Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
  </Callout>
</div>
