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

# Azure AI Search integration

> Integrate with the Azure AI Search retriever using LangChain Python.

[Azure AI Search](https://learn.microsoft.com/azure/search/search-what-is-azure-search) (formerly known as `Azure Cognitive Search`) is a Microsoft cloud search service that gives developers infrastructure, APIs, and tools for information retrieval of vector, keyword, and hybrid queries at scale.

`AzureAISearchRetriever` returns documents from an unstructured query. It sends the query as a full-text `search` request to the 2023-11-01 stable REST API version of Azure AI Search. It does not embed the query or run a vector query. For vector or hybrid retrieval, use `AzureSearch.as_retriever()` from the [vector store integration](https://docs.langchain.com/oss/python/integrations/vectorstores/azuresearch).

This guide shows how to get started with the Azure AI Search [retriever](https://docs.langchain.com/oss/python/langchain/retrieval.md). For all `AzureAISearchRetriever` features and configurations, see the [API reference](https://reference.langchain.com/python/langchain-azure-ai).

## Setup

To use this module, you need:

* An Azure AI Search service. You can [create one](https://learn.microsoft.com/azure/search/search-create-service-portal) for free if you sign up for the Azure trial. A free service has lower quotas, but it's sufficient for running the code in this notebook.

* An existing index with a searchable text field that matches `content_key`. The [vector store module](https://docs.langchain.com/oss/python/integrations/vectorstores/azuresearch) creates an index that works with this retriever. You can also [create an index with the Azure AI Search REST APIs](https://learn.microsoft.com/azure/search/search-get-started-vector).

* An API key or Azure AD Token.
  * API keys are generated when you create the search service. If you're just querying an index, you can use the query API key, otherwise use an admin API key. See [Find your API keys](https://learn.microsoft.com/azure/search/search-security-api-keys?tabs=rest-use%2Cportal-find%2Cportal-query#find-existing-keys) for details.
  * Azure AD Token can be used with Azure Managed Identity. See [Connect your app to Azure AI Search using identities](https://learn.microsoft.com/en-us/azure/search/keyless-connections?tabs=python%2Cazure-cli) for details.

Set the search service name, index name, and API key as environment variables, or pass them as arguments to `AzureAISearchRetriever`. The search index provides the searchable content.

With an API Key

```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>"
```

With an Azure AD Token

```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>"
```

If you want to get automated tracing from individual queries, you can also set your [LangSmith](https://docs.langchain.com/langsmith/observability.md) API key by uncommenting below:

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

os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
os.environ["LANGSMITH_TRACING"] = "true"
```

### Installation

This retriever ships in the [`langchain-azure-ai`](https://pypi.org/project/langchain-azure-ai/) package, which also installs `langchain-openai`, `azure-search-documents`, and `azure-identity`:

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

```bash uv theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
uv add langchain-azure-ai
```

## Instantiation

For `AzureAISearchRetriever`, provide an `index_name`, `content_key`, and `top_k` set to the number of results you'd like to retrieve. If you don't set `top_k`, the request omits `$top` and Azure AI Search applies its default page size.

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

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

## Usage

Now you can use it to retrieve documents from Azure AI Search.
Call `invoke` to retrieve documents. It returns up to `top_k` documents that match the query.

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

## Example

This section demonstrates using the retriever over built-in sample data. You can skip this step if you already have a vector index on your search service.

Start by providing the endpoints and keys. Because this step creates a vector index, specify a text embedding model to get a vector representation of the text. This example assumes Azure OpenAI with a deployment of text-embedding-3-small. Because this step creates an index, be sure to use an admin API key for your search service.

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

from langchain_azure_ai.retrievers import AzureAISearchRetriever
from langchain_azure_ai.vectorstores import AzureSearch
from langchain_openai import AzureOpenAIEmbeddings

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-3-small"
```

Use an embedding model from Azure OpenAI to turn the documents into embeddings stored in the Azure AI Search vector store. Setting the index name to `langchain-vector-demo` creates a new vector store associated with that index name.

```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=f"https://{os.environ['AZURE_AI_SEARCH_SERVICE_NAME']}.search.windows.net",
    azure_search_key=os.getenv("AZURE_AI_SEARCH_API_KEY"),
    index_name="langchain-vector-demo",
)
```

Next, load data into the new vector store. This example loads the `state_of_the_union.txt` file and splits the text into 400-character chunks with no overlap. The chunks are then added to the vector store as embeddings.

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

from langchain_text_splitters import CharacterTextSplitter

text = Path("state_of_the_union.txt").read_text(encoding="utf-8")
text_splitter = CharacterTextSplitter(chunk_size=400, chunk_overlap=0)
docs = text_splitter.create_documents([text])

vector_store.add_documents(documents=docs)
```

Next, create a retriever. The current `index_name` variable is `langchain-vector-demo` from the last step. If you skipped vector store creation, provide your index name in the parameter. In this query, the top result is returned.

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

Now retrieve the data that is relevant to the query from the uploaded documents.

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

## Use within a chain

```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-5.4-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 reference

For detailed documentation of all `AzureAISearchRetriever` features and configurations head to the [API reference](https://reference.langchain.com/python/langchain-azure-ai).

***

[Connect these docs](https://docs.langchain.com/use-these-docs.md) to your agent of choice via MCP for real-time answers.

[Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/oss/python/integrations/retrievers/azure_ai_search.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
