Create a knowledge base in Azure AI Search

Note

Azure AI Search is available through the Azure portal, REST APIs, and Azure SDKs.

Important

Features, capabilities, or properties marked (preview) aren't covered by a service-level agreement, aren't recommended for production workloads, and might change or be constrained before they become generally available. The Azure AI Search preview terms apply to all preview functionality, whether it's standalone or part of a generally available feature.

Important

These features and functionality are part of the 2026-08-01-preview REST API. The 2026-08-01-preview is licensed to you as part of your Azure subscription and is subject to the terms applicable to "Previews" in the Microsoft Product Terms, the Microsoft Products and Services Data Protection Addendum ("DPA"), and the Supplemental Terms of Use for Azure Previews.

The 2026-08-01-preview supports connections to other Microsoft services and third-party services. Use of these services is subject to their respective terms and might result in data processing or storage outside of the Azure compliance boundary, as well as data flowing into the Azure compliance boundary.

It's your responsibility to manage whether your data will flow outside of your organization's compliance and geographic boundaries and any related implications, and that appropriate permissions, boundaries, and approvals are provisioned.

You're responsible for carefully reviewing and testing applications you build in the context of your specific use cases and making all appropriate decisions and customizations. This includes implementing your own responsible AI mitigations, such as metaprompts, content filters, or other safety systems, and ensuring your applications meet appropriate quality, reliability, security, and trustworthiness standards.

In Azure AI Search, a knowledge base is a top-level object that orchestrates agentic retrieval. It defines which knowledge sources to query and the default behavior for retrieval operations. At query time, the retrieve method targets the knowledge base to run the configured retrieval pipeline.

A knowledge base specifies:

  • One or more knowledge sources that point to searchable content.

  • An optional LLM for query planning, answer synthesis, or web content summarization. Supported tasks vary by API version and knowledge source type.

  • Custom properties that control routing, source selection, and object encryption.

Usage support

Azure portal .NET SDK Python SDK Java SDK JavaScript SDK REST API
✔️ ✔️ ✔️ ✔️ ✔️ ✔️
  • Required Azure.Search.Documents package:

    • For 2026-08-01-preview features, the latest preview package: dotnet add package Azure.Search.Documents --prerelease

    • For 2026-04-01 features, the latest stable package: dotnet add package Azure.Search.Documents

  • For keyless authentication, the Azure.Identity package: dotnet add package Azure.Identity

  • Required azure-search-documents package:

    • For 2026-08-01-preview features, the latest preview package: pip install --pre azure-search-documents

    • For 2026-04-01 features, the latest stable package: pip install azure-search-documents

  • For keyless authentication, the azure-identity package: pip install azure-identity

Configure access

Azure AI Search needs access to the LLM from Azure AI services. We recommend Microsoft Entra ID for authentication and role-based access for authorization. To assign roles, you must be an Owner or User Access Administrator. If you can't use roles, use key-based authentication instead.

  1. Enable role-based access control on Azure AI Search.

  2. Configure Azure AI Search to use a managed identity.

  3. On your model provider, assign Cognitive Services User to the managed identity of your search service. If you're testing locally, assign the same role to your user account.

  4. For local testing, follow the steps in Quickstart: Connect without keys to sign in to a specific subscription and tenant. Use DefaultAzureCredential instead of AzureKeyCredential in each request, which should be similar to the following example.

    // Authenticate using roles
    using Azure.Search.Documents.Indexes;
    using Azure.Identity;
    
    var indexClient = new SearchIndexClient(new Uri(searchEndpoint), new DefaultAzureCredential());
    
  1. Enable role-based access control on Azure AI Search.

  2. Configure Azure AI Search to use a managed identity.

  3. On your model provider, assign Cognitive Services User to the managed identity of your search service. If you're testing locally, assign the same role to your user account.

  4. For local testing, follow the steps in Quickstart: Connect without keys to sign in to a specific subscription and tenant. Use DefaultAzureCredential instead of AzureKeyCredential in each request, which should be similar to the following example.

    # Authenticate using roles
    from azure.identity import DefaultAzureCredential
    index_client = SearchIndexClient(endpoint = "<search-endpoint>", credential = DefaultAzureCredential())
    
  1. Enable role-based access control on Azure AI Search.

  2. Configure Azure AI Search to use a managed identity.

  3. On your model provider, assign Cognitive Services User to the managed identity of your search service. If you're testing locally, assign the same role to your user account.

  4. For local testing, follow the steps in Quickstart: Connect without keys to get a personal access token for a specific subscription and tenant. Specify your access token in each request, which should be similar to the following example.

    # List indexes using roles
    GET {{search-endpoint}}/indexes?api-version=2026-04-01
    Content-Type: application/json
    Authorization: Bearer {{search-access-token}}
    

Important

The code snippets in this article use keyless authentication. To use an API key instead, update each request accordingly. In a request that specifies both approaches, the API key takes precedence.

Check for existing knowledge bases

A knowledge base is a top-level, reusable object. Knowing about existing knowledge bases is helpful for either reuse or naming new objects.

Run the following code to list existing knowledge bases by name. The list includes all knowledge bases on your search service, regardless of which API version you used to create them.

// List knowledge bases by name
using Azure.Search.Documents.Indexes;

var indexClient = new SearchIndexClient(new Uri(searchEndpoint), credential);
var knowledgeBases = indexClient.GetKnowledgeBasesAsync();

Console.WriteLine("Knowledge Bases:");

await foreach (var kb in knowledgeBases)
{
    Console.WriteLine($"  - {kb.Name}");
}

Reference: SearchIndexClient

# List knowledge bases by name
from azure.identity import DefaultAzureCredential
from azure.search.documents.indexes import SearchIndexClient

index_client = SearchIndexClient(endpoint = "<search-endpoint>", credential = DefaultAzureCredential())

for kb in index_client.list_knowledge_bases():
    print(f"  - {kb.name}")

Reference: SearchIndexClient

# List knowledge bases
GET {{search-endpoint}}/knowledgebases?api-version={{api-version}}&$select=name
Content-Type: application/json
Authorization: Bearer {{search-access-token}}

Reference: Knowledge Bases - List

You can also return a single knowledge base by name to review its JSON definition.

using Azure.Search.Documents.Indexes;
using System.Text.Json;

var indexClient = new SearchIndexClient(new Uri(searchEndpoint), credential);

// Specify the knowledge base name to retrieve
string kbNameToGet = "earth-knowledge-base";

// Get a specific knowledge base definition
var knowledgeBaseResponse = await indexClient.GetKnowledgeBaseAsync(kbNameToGet);
var kb = knowledgeBaseResponse.Value;

// Serialize to JSON for display
string json = JsonSerializer.Serialize(kb, new JsonSerializerOptions { WriteIndented = true });
Console.WriteLine(json);

Reference: SearchIndexClient

# Get a knowledge base definition
from azure.identity import DefaultAzureCredential
from azure.search.documents.indexes import SearchIndexClient
import json

index_client = SearchIndexClient(endpoint = "<search-endpoint>", credential = DefaultAzureCredential())

kb = index_client.get_knowledge_base("<knowledge-base-name>")
print(json.dumps(kb.as_dict(), indent = 2))

Reference: SearchIndexClient

# Get knowledge base
GET {{search-endpoint}}/knowledgebases/{{knowledge-base-name}}?api-version={{api-version}}
Content-Type: application/json
Authorization: Bearer {{search-access-token}}

Reference: Knowledge Bases - Get

The following JSON is an example response for a knowledge base.

{
  "name": "my-kb",
  "description": "A sample knowledge base.",
  "retrievalInstructions": null,
  "answerInstructions": null,
  "outputMode": null,
  "knowledgeSources": [
    {
      "name": "my-blob-ks"
    }
  ],
  "models": [],
  "encryptionKey": null,
  "retrievalReasoningEffort": {
    "kind": "low"
  }
}

Note

The response schema reflects the API version you used to create the knowledge base. A knowledge base created with the generally available 2026-04-01 API version returns a narrower definition than the 2026-08-01-preview. For more information about which properties each version supports, see Create a knowledge base.

Create a knowledge base

Important

The 2026-04-01 API version only accepts generally available knowledge source types and supports minimal, extractive retrieval. It doesn't support preview-only capabilities, such as query planning, answer synthesis, and configurable reasoning effort. For full functionality, use the 2026-08-01-preview.

After you create a knowledge base, you can update its properties at any time. If the knowledge base is in use, updates take effect on the next retrieval.

// Create a knowledge base
using Azure.Search.Documents.Indexes;
using Azure.Search.Documents.Indexes.Models;
using Azure.Search.Documents.KnowledgeBases.Models;
using Azure.Identity;

var indexClient = new SearchIndexClient(new Uri(searchEndpoint), new DefaultAzureCredential());

var aoaiParams = new AzureAIservicesVectorizerParameters
{
    ResourceUri = new Uri(aoaiEndpoint),
    DeploymentName = aoaiGptDeployment,
    ModelName = aoaiGptModel,
};

var knowledgeBase = new KnowledgeBase(
    name: "my-kb",
    knowledgeSources: new KnowledgeSourceReference[]
    {
        new KnowledgeSourceReference("hotels-ks"),
        new KnowledgeSourceReference("earth-at-night-ks")
    }
)
{
    Description = "This knowledge base handles questions directed at two unrelated sample indexes.",
    RetrievalInstructions = "Use the hotels knowledge source for queries about where to stay, otherwise use the earth at night knowledge source.",
    AnswerInstructions = "Answer in two concise sentences.",
    OutputMode = KnowledgeRetrievalOutputMode.AnswerSynthesis,
    Models = { new KnowledgeBaseAzureAIservicesModel(AzureAIservicesParameters: aoaiParams) },
    RetrievalReasoningEffort = new KnowledgeRetrievalLowReasoningEffort()
};

await indexClient.CreateOrUpdateKnowledgeBaseAsync(knowledgeBase);
Console.WriteLine($"Knowledge base '{knowledgeBase.Name}' created or updated successfully.");

Reference: SearchIndexClient, KnowledgeBase

# Create a knowledge base
from azure.identity import DefaultAzureCredential
from azure.search.documents.indexes import SearchIndexClient
from azure.search.documents.indexes.models import (
    KnowledgeBase,
    KnowledgeSourceReference,
)
from azure.search.documents.knowledgebases.models import (
    KnowledgeRetrievalAutoReasoningEffort,
    KnowledgeRetrievalOutputMode,
)

index_client = SearchIndexClient(endpoint = "<search-endpoint>", credential = DefaultAzureCredential())

aoai_params = AzureAIservicesVectorizerParameters(
    resource_url = "<aoai-endpoint>",
    deployment_name = "<aoai-gpt-deployment>",
    model_name = "<aoai-gpt-model>",
)

knowledge_base = KnowledgeBase(
    name = "my-kb",
    description = "This knowledge base handles questions directed at two unrelated sample indexes.",
    retrieval_instructions = "Use the hotels knowledge source for queries about where to stay, otherwise use the earth at night knowledge source.",
    answer_instructions = "Answer in two concise sentences.",
    output_mode = KnowledgeRetrievalOutputMode.ANSWER_SYNTHESIS,
    knowledge_sources = [
        KnowledgeSourceReference(name = "hotels-ks"),
        KnowledgeSourceReference(name = "earth-at-night-ks"),
    ],
    models = [KnowledgeBaseAzureAIservicesModel(azure_open_ai_parameters = aoai_params)],
    encryption_key = None,
    retrieval_reasoning_effort = KnowledgeRetrievalAutoReasoningEffort(),
)

index_client.create_or_update_knowledge_base(knowledge_base)
print(f"Knowledge base '{knowledge_base.name}' created or updated successfully.")

Reference: SearchIndexClient, KnowledgeBase

# Create a knowledge base
PUT {{search-endpoint}}/knowledgebases/my-kb?api-version=2026-08-01-preview
Content-Type: application/json
Authorization: Bearer {{search-access-token}}

{
    "name" : "my-kb",
    "description": "This knowledge base handles questions directed at two unrelated sample indexes.",
    "retrievalInstructions": "Use the hotels knowledge source for queries about where to stay, otherwise use the earth at night knowledge source.",
    "answerInstructions": "Answer in two concise sentences.",
    "outputMode": "answerSynthesis",
    "knowledgeSources": [
        {
            "name": "hotels-ks"
        },
        {
            "name": "earth-at-night-ks"
        }
    ],
    "models" : [ 
        {
            "kind": "AzureAIservices",
            "AzureAIservicesParameters": {
                "resourceUri": "{{model-provider-url}}",
                "apiKey": "{{model-api-key}}",
                "deploymentId": "gpt-5.4-mini",
                "modelName": "gpt-5.4-mini"
            }
        }
    ],
    "encryptionKey": null,
    "retrievalReasoningEffort": {
        "kind": "auto"
    }
}

Reference: Knowledge Bases - Create or Update

Configure CORS for browser-based retrieve calls (preview)

Important

Cross-origin resource sharing (CORS) allows browser-based applications to request data directly from the service. Depending on your CORS configuration, external web pages might access or invoke the service and its data by using the user's browser context. This access can create security threats. Enabling CORS is at your own risk.

Starting with the 2026-05-01-preview API version, a knowledge base can define corsOptions for browser-based applications that call the retrieve action directly from JavaScript. The CORS policy identifies which browser origins can send retrieve requests to the knowledge base.

When you omit corsOptions, the knowledge base has no CORS policy, and browsers block cross-origin retrieve requests.

The following example creates a knowledge base that allows retrieve requests from one browser origin.

using Azure.Identity;
using Azure.Search.Documents.Indexes;
using Azure.Search.Documents.Indexes.Models;

var indexClient = new SearchIndexClient(new Uri(searchEndpoint), new DefaultAzureCredential());

var knowledgeBase = new KnowledgeBase(
    name: "browser-chat-kb",
    knowledgeSources: new[] { new KnowledgeSourceReference("product-docs-ks") }
)
{
    Description = "A knowledge base that allows one browser app origin.",
    CorsOptions = new CorsOptions(new[] { "https://myapp.example.com" })
    {
        MaxAgeInSeconds = 300
    }
};

await indexClient.CreateOrUpdateKnowledgeBaseAsync(knowledgeBase);

Reference: CorsOptions, KnowledgeBase

from azure.identity import DefaultAzureCredential
from azure.search.documents.indexes import SearchIndexClient
from azure.search.documents.indexes.models import (
    CorsOptions,
    KnowledgeBase,
    KnowledgeSourceReference,
)

index_client = SearchIndexClient(endpoint="<search-endpoint>", credential=DefaultAzureCredential())

knowledge_base = KnowledgeBase(
    name="browser-chat-kb",
    description="A knowledge base that allows one browser app origin.",
    knowledge_sources=[KnowledgeSourceReference(name="product-docs-ks")],
    cors_options=CorsOptions(
        allowed_origins=["https://myapp.example.com"],
        max_age_in_seconds=300,
    ),
)

index_client.create_or_update_knowledge_base(knowledge_base)

Reference: CorsOptions, KnowledgeBase

PUT {{search-endpoint}}/knowledgebases/browser-chat-kb?api-version=2026-08-01-preview
Content-Type: application/json
Authorization: Bearer {{search-access-token}}

{
  "name": "browser-chat-kb",
  "description": "A knowledge base that allows one browser app origin.",
  "knowledgeSources": [
    {
      "name": "product-docs-ks"
    }
  ],
  "corsOptions": {
    "allowedOrigins": [
      "https://myapp.example.com"
    ],
    "maxAgeInSeconds": 300
  }
}

Query a knowledge base

After you create a knowledge base, call the retrieve action or MCP endpoint to query it.

Delete a knowledge base

If you no longer need the knowledge base or need to rebuild it on your search service, run the following code to delete the object.

// Delete a knowledge base
using Azure.Search.Documents.Indexes;
var indexClient = new SearchIndexClient(new Uri(searchEndpoint), credential);

await indexClient.DeleteKnowledgeBaseAsync(knowledgeBaseName);
System.Console.WriteLine($"Knowledge base '{knowledgeBaseName}' deleted successfully.");

Reference: SearchIndexClient

# Delete a knowledge base
from azure.identity import DefaultAzureCredential
from azure.search.documents.indexes import SearchIndexClient

index_client = SearchIndexClient(endpoint = "<search-endpoint>", credential = DefaultAzureCredential())
index_client.delete_knowledge_base("<knowledge-base-name>")
print(f"Knowledge base deleted successfully.")

Reference: SearchIndexClient

# Delete a knowledge base
DELETE {{search-endpoint}}/knowledgebases/{{knowledge-base-name}}?api-version={{api-version}}
Authorization: Bearer {{search-access-token}}

Reference: Knowledge Bases - Delete