你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

在 Azure AI 搜索中创建知识库

注释

此功能目前处于公开预览状态。 此预览版未随附服务级别协议,建议不要用于生产工作负载。 某些功能可能不受支持或者受限。 有关详细信息,请参阅 Microsoft Azure 预览版补充使用条款

在 Azure AI 搜索中, 知识库 是协调 代理检索的顶级对象。 它定义要查询的知识源以及用于检索作的默认行为。 在查询时, 检索方法 以知识库为目标,以运行配置的检索管道。

知识库指定:

  • 指向可搜索内容的一个或多个知识源。
  • 一个可选的 LLM,为查询规划和答案生成提供推理能力。
  • 用于确定是否调用 LLM 并管理成本、延迟和质量的检索推理工作。
  • 控制路由、源选择、输出格式和对象加密的自定义属性。

创建知识库后,可以随时更新其属性。 如果知识库正在使用中,更新将对下一次检索生效。

重要

2025-11-01-preview 将 2025-08-01-preview 知识代理 重命名为 知识库。 这是一项重大更改。 建议尽快将现有代码迁移到新的 API

先决条件

注释

尽管可以使用 Azure 门户创建知识库,但门户使用 2025-08-01-preview,该预览版使用以前的“知识代理”术语,不支持所有 2025-11-01-preview 功能。 如需中断性变更方面的帮助,请参阅迁移智能体检索代码

支持的模型

使用 Azure OpenAI 中的以下 LLM 之一或等效的开源模型。 有关部署说明,请参阅 使用 Microsoft Foundry 部署 Azure OpenAI 模型

  • gpt-4o
  • gpt-4o-mini
  • gpt-4.1
  • gpt-4.1-nano
  • gpt-4.1-mini
  • gpt-5
  • gpt-5-nano
  • gpt-5-mini

配置访问权限

Azure AI 搜索需要访问 Azure OpenAI 的 LLM。 我们建议使用 Microsoft Entra ID 进行身份验证,并使用基于角色的访问控制进行授权。 你必须是 所有者或用户访问管理员 才能分配角色。 如果角色不可行,请改用基于密钥的身份验证。

  1. 将 Azure AI 搜索配置为使用托管标识

  2. 在您的模型提供商(例如 Foundry 模型)中,将 认知服务用户 作为搜索服务的托管标识进行分配。 如果要在本地进行测试,请将相同的角色分配给用户帐户。

  3. 对于本地测试,请按照快速入门:在没有密钥的情况下连接中的步骤登录到特定订阅和租户。 应在每个请求中使用 DefaultAzureCredential 而不是 AzureKeyCredential,其格式应类似于以下示例:

    using Azure.Search.Documents.Indexes;
    using Azure.Identity;
    
    var indexClient = new SearchIndexClient(new Uri(searchEndpoint), new DefaultAzureCredential());
    

重要

本文中的代码片段使用 API 密钥。 如果使用基于角色的身份验证,请相应地更新每个请求。 在指定这两种方法的请求中,API 密钥优先。

检查现有知识库

了解现有知识库有助于重复使用或命名新对象。 任何 2025-08-01-preview 知识智能体会在知识库集合中返回。

运行以下代码,按名称列出现有知识库。

// 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}");
  }

还可以按名称返回单个知识库来查看其 JSON 定义。

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);

以下 JSON 是知识库的示例。

{
  "Name": "earth-knowledge-base",
  "KnowledgeSources": [
    {
      "Name": "earth-knowledge-source"
    }
  ],
  "Models": [
    {}
  ],
  "RetrievalReasoningEffort": {},
  "OutputMode": {},
  "ETag": "\u00220x8DE278629D782B3\u0022",
  "EncryptionKey": null,
  "Description": null,
  "RetrievalInstructions": null,
  "AnswerInstructions": null
}

创建知识库

知识库驱动代理检索管道。 在应用程序代码中,它由其他代理或聊天机器人调用。

知识库将知识库(可搜索内容)连接到 Azure OpenAI 中的 LLM 部署。 LLM 上的属性建立连接,而知识源上的属性建立默认值,用于通知查询执行和响应。

运行以下代码来创建知识库。

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

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

// Create a knowledge base
var knowledgeBase = new KnowledgeBase(
    name: knowledgeBaseName,
    knowledgeSources: new KnowledgeSourceReference[] { new KnowledgeSourceReference(knowledgeSourceName) }
)
{
    RetrievalReasoningEffort = new KnowledgeRetrievalLowReasoningEffort(),
    OutputMode = KnowledgeRetrievalOutputMode.AnswerSynthesis,
    Models = { model }
};
await indexClient.CreateOrUpdateKnowledgeBaseAsync(knowledgeBase);
Console.WriteLine($"Knowledge base '{knowledgeBaseName}' created or updated successfully.");
# Create a knowledge base
using Azure.Search.Documents.Indexes;
using Azure.Search.Documents.Indexes.Models;
using Azure.Search.Documents.KnowledgeBases.Models;
using Azure;

var indexClient = new SearchIndexClient(new Uri(searchEndpoint), new AzureKeyCredential(apiKey));

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

var knowledgeBase = new KnowledgeBase(
    name: "my-kb",
    knowledgeSources: new KnowledgeSourceReference[] 
    { 
        new KnowledgeSourceReference("hotels-sample-knowledge-source"),
        new KnowledgeSourceReference("earth-knowledge-source")
    }
)
{
    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 = "Provide a two sentence concise and informative answer based on the retrieved documents.",
    OutputMode = KnowledgeRetrievalOutputMode.AnswerSynthesis,
    Models = { new KnowledgeBaseAzureOpenAIModel(azureOpenAIParameters: aoaiParams) },
    RetrievalReasoningEffort = new KnowledgeRetrievalLowReasoningEffort()
};

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

知识库属性

可以传递以下属性来创建知识库。

Name Description 类型 必选
name 知识库的名称,该名称在知识库集合中必须是唯一的,并遵循 Azure AI 搜索中对象的 命名准则 String 是的
knowledgeSources 一个或多个 受支持的知识源 Array 是的
Description 知识库的说明。 LLM 使用该说明来指导查询规划。 String
RetrievalInstructions 向 LLM 发出的提示,用于确定某个知识来源是否应纳入查询范围,有多个知识来源时建议纳入。 此字段同时影响知识来源选择和查询表述。 例如,说明可以追加信息或确定知识来源的优先级。 指令直接传递到 LLM,这意味着可以提供破坏查询规划的说明,例如导致绕过关键知识源的说明。 String 是的
AnswerInstructions 自定义指令以定制合成答案。 默认值为 NULL。 有关详细信息,请参阅 如何使用答案合成生成有引文支持的响应 String 是的
OutputMode 有效值为 AnswerSynthesis,它用于 LLM 生成的答案;若希望获取完整搜索结果并将其作为下游步骤传递给 LLM,则有效值为 ExtractedData String 是的
Models 支持的 LLM 的连接,用于答案生成或查询规划。 在此预览版中, Models 只能包含一个模型,模型提供程序必须是 Azure OpenAI。 从 Foundry 门户或命令行请求获取模型信息。 使用 KnowledgeBaseAzureOpenAIModel 类提供参数。 可以使用基于角色的访问控制,而不是将 API 密钥用于与模型建立的 Azure AI 搜索连接。 有关详细信息,请参阅 如何使用 Foundry 部署 Azure OpenAI 模型 物体
RetrievalReasoningEffort 确定与 LLM 相关的查询处理级别。 有效值为 minimallow (默认值)和 medium。 有关详细信息,请参阅 设置检索推理工作 物体

查询知识库

设置要发送到 LLM 的指令和消息。

string instructions = @"
Use the earth at night index to answer the question. If you can't find relevant content, say you don't know.
";

var messages = new List<Dictionary<string, string>>
{
    new Dictionary<string, string>
    {
        { "role", "system" },
        { "content", instructions }
    }
};

retrieve 知识库上调用操作以验证 LLM 连接并返回结果。 有关请求和响应架构的详细信息 retrieve ,请参阅 在 Azure AI 搜索中使用知识库检索数据

将“海洋在何处看起来绿色?”替换为对知识源有效的查询字符串。

using Azure.Search.Documents.KnowledgeBases;
using Azure.Search.Documents.KnowledgeBases.Models;

var baseClient = new KnowledgeBaseRetrievalClient(
    endpoint: new Uri(searchEndpoint),
    knowledgeBaseName: knowledgeBaseName,
    tokenCredential: new DefaultAzureCredential()
);

messages.Add(new Dictionary<string, string>
{
    { "role", "user" },
    { "content", @"Where does the ocean look green?" }
});

var retrievalRequest = new KnowledgeBaseRetrievalRequest();
foreach (Dictionary<string, string> message in messages) {
    if (message["role"] != "system") {
        retrievalRequest.Messages.Add(new KnowledgeBaseMessage(content: new[] { new KnowledgeBaseMessageTextContent(message["content"]) }) { Role = message["role"] });
    }
}
retrievalRequest.RetrievalReasoningEffort = new KnowledgeRetrievalLowReasoningEffort();
var retrievalResult = await baseClient.RetrieveAsync(retrievalRequest);

messages.Add(new Dictionary<string, string>
{
    { "role", "assistant" },
    { "content", (retrievalResult.Value.Response[0].Content[0] as KnowledgeBaseMessageTextContent).Text }
});

(retrievalResult.Value.Response[0].Content[0] as KnowledgeBaseMessageTextContent).Text 

// Print the response, activity, and references
Console.WriteLine("Response:");
Console.WriteLine((retrievalResult.Value.Response[0].Content[0] as KnowledgeBaseMessageTextContent)!.Text);

要点

对示例查询的响应可能如以下示例所示:

  "response": [
    {
      "content": [
        {
          "type": "text",
          "text": "The ocean appears green off the coast of Antarctica due to phytoplankton flourishing in the water, particularly in Granite Harbor near Antarctica’s Ross Sea, where they can grow in large quantities during spring, summer, and even autumn under the right conditions [ref_id:0]. Additionally, off the coast of Namibia, the ocean can also look green due to blooms of phytoplankton and yellow-green patches of sulfur precipitating from bacteria in oxygen-depleted waters [ref_id:1]. In the Strait of Georgia, Canada, the waters turned bright green due to a massive bloom of coccolithophores, a type of phytoplankton [ref_id:5]. Furthermore, a milky green and blue bloom was observed off the coast of Patagonia, Argentina, where nutrient-rich waters from different currents converge [ref_id:6]. Lastly, a large bloom of cyanobacteria was captured in the Baltic Sea, which can also give the water a green appearance [ref_id:9]."
        }
      ]
    }
  ]

删除知识库

如果不再需要知识库或需要在搜索服务上重新生成它,请使用此请求删除该对象。

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.");

注释

此功能目前处于公开预览状态。 此预览版未随附服务级别协议,建议不要用于生产工作负载。 某些功能可能不受支持或者受限。 有关详细信息,请参阅 Microsoft Azure 预览版补充使用条款

在 Azure AI 搜索中, 知识库 是协调 代理检索的顶级对象。 它定义要查询的知识源以及用于检索作的默认行为。 在查询时, 检索方法 以知识库为目标,以运行配置的检索管道。

知识库指定:

  • 指向可搜索内容的一个或多个知识源。
  • 一个可选的 LLM,为查询规划和答案生成提供推理能力。
  • 用于确定是否调用 LLM 并管理成本、延迟和质量的检索推理工作。
  • 控制路由、源选择、输出格式和对象加密的自定义属性。

创建知识库后,可以随时更新其属性。 如果知识库正在使用中,更新将对下一次检索生效。

重要

2025-11-01-preview 将 2025-08-01-preview 知识代理 重命名为 知识库。 这是一项重大更改。 建议尽快将现有代码迁移到新的 API

先决条件

注释

尽管可以使用 Azure 门户创建知识库,但门户使用 2025-08-01-preview,该预览版使用以前的“知识代理”术语,不支持所有 2025-11-01-preview 功能。 如需中断性变更方面的帮助,请参阅迁移智能体检索代码

支持的模型

使用 Azure OpenAI 中的以下 LLM 之一或等效的开源模型。 有关部署说明,请参阅 使用 Microsoft Foundry 部署 Azure OpenAI 模型

  • gpt-4o
  • gpt-4o-mini
  • gpt-4.1
  • gpt-4.1-nano
  • gpt-4.1-mini
  • gpt-5
  • gpt-5-nano
  • gpt-5-mini

配置访问权限

Azure AI 搜索需要访问 Azure OpenAI 的 LLM。 我们建议使用 Microsoft Entra ID 进行身份验证,并使用基于角色的访问控制进行授权。 你必须是 所有者或用户访问管理员 才能分配角色。 如果角色不可行,请改用基于密钥的身份验证。

  1. 将 Azure AI 搜索配置为使用托管标识

  2. 在您的模型提供商(例如 Foundry 模型)中,将 认知服务用户 作为搜索服务的托管标识进行分配。 如果要在本地进行测试,请将相同的角色分配给用户帐户。

  3. 对于本地测试,请按照快速入门:在没有密钥的情况下连接中的步骤登录到特定订阅和租户。 应在每个请求中使用 DefaultAzureCredential 而不是 AzureKeyCredential,其格式应类似于以下示例:

    # Authenticate using roles
    from azure.identity import DefaultAzureCredential
    index_client = SearchIndexClient(endpoint = "search_url", credential = DefaultAzureCredential())
    

重要

本文中的代码片段使用 API 密钥。 如果使用基于角色的身份验证,请相应地更新每个请求。 在指定这两种方法的请求中,API 密钥优先。

检查现有知识库

了解现有知识库有助于重复使用或命名新对象。 任何 2025-08-01-preview 知识智能体会在知识库集合中返回。

运行以下代码,按名称列出现有知识库。

# List knowledge bases by name
import requests
import json

endpoint = "{search_url}/knowledgebases"
params = {"api-version": "2025-11-01-preview", "$select": "name"}
headers = {"api-key": "{api_key}"}

response = requests.get(endpoint, params = params, headers = headers)
print(json.dumps(response.json(), indent = 2))

还可以按名称返回单个知识库来查看其 JSON 定义。

# Get a knowledge base definition
import requests
import json

endpoint = "{search_url}/knowledgebases/{knowledge_base_name}"
params = {"api-version": "2025-11-01-preview"}
headers = {"api-key": "{api_key}"}

response = requests.get(endpoint, params = params, headers = headers)
print(json.dumps(response.json(), indent = 2))

以下 JSON 是知识库的示例响应。

{
  "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"
  }
}

创建知识库

知识库驱动代理检索管道。 在应用程序代码中,它由其他代理或聊天机器人调用。

知识库将知识库(可搜索内容)连接到 Azure OpenAI 中的 LLM 部署。 LLM 上的属性建立连接,而知识源上的属性建立默认值,用于通知查询执行和响应。

运行以下代码来创建知识库。

# Create a knowledge base
from azure.core.credentials import AzureKeyCredential
from azure.search.documents.indexes import SearchIndexClient
from azure.search.documents.indexes.models import KnowledgeBase, KnowledgeBaseAzureOpenAIModel, KnowledgeSourceReference, AzureOpenAIVectorizerParameters, KnowledgeRetrievalOutputMode, KnowledgeRetrievalLowReasoningEffort

index_client = SearchIndexClient(endpoint = "search_url", credential = AzureKeyCredential("api_key"))

aoai_params = AzureOpenAIVectorizerParameters(
    resource_url = "aoai_endpoint",
    api_key="aoai_api_key",
    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 = "Provide a two sentence concise and informative answer based on the retrieved documents.",
    output_mode = KnowledgeRetrievalOutputMode.ANSWER_SYNTHESIS,
    knowledge_sources = [
        KnowledgeSourceReference(name = "hotels-ks"),
        KnowledgeSourceReference(name = "earth-at-night-ks"),
    ],
    models = [KnowledgeBaseAzureOpenAIModel(azure_open_ai_parameters = aoai_params)],
    encryption_key = None,
    retrieval_reasoning_effort = KnowledgeRetrievalLowReasoningEffort,
)

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

知识库属性

可以传递以下属性来创建知识库。

Name Description 类型 必选
name 知识库的名称,该名称在知识库集合中必须是唯一的,并遵循 Azure AI 搜索中对象的 命名准则 String 是的
description 知识库的说明。 LLM 使用该说明来指导查询规划。 String
retrieval_instructions 向 LLM 发出的提示,用于确定某个知识来源是否应纳入查询范围,有多个知识来源时建议纳入。 此字段同时影响知识来源选择和查询表述。 例如,说明可以追加信息或确定知识来源的优先级。 指令直接传递到 LLM,这意味着可以提供破坏查询规划的说明,例如导致绕过关键知识源的说明。 String 是的
answer_instructions 自定义指令以定制合成答案。 默认值为 NULL。 有关详细信息,请参阅 如何使用答案合成生成有引文支持的响应 String 是的
output_mode 有效值为 answer_synthesis,它用于 LLM 生成的答案;若希望获取完整搜索结果并将其作为下游步骤传递给 LLM,则有效值为 extracted_data String 是的
knowledge_sources 一个或多个 受支持的知识源 Array 是的
models 支持的 LLM 的连接,用于答案生成或查询规划。 在此预览版中, models 只能包含一个模型,模型提供程序必须是 Azure OpenAI。 从 Foundry 门户或命令行请求获取模型信息。 可以使用基于角色的访问控制,而不是将 API 密钥用于与模型建立的 Azure AI 搜索连接。 有关详细信息,请参阅 如何使用 Foundry 部署 Azure OpenAI 模型 物体
encryption_key 客户 管理的密钥 ,用于加密知识库和生成的对象中的敏感信息。 物体
retrieval_reasoning_effort 确定与 LLM 相关的查询处理级别。 有效值为 minimallow (默认值)和 medium。 有关详细信息,请参阅 设置检索推理工作 物体

查询知识库

retrieve 知识库上调用操作以验证 LLM 连接并返回结果。 有关请求和响应架构的详细信息 retrieve ,请参阅 在 Azure AI 搜索中使用知识库检索数据

将“海洋在何处看起来绿色?”替换为对知识源有效的查询字符串。

# Send grounding request
from azure.core.credentials import AzureKeyCredential
from azure.search.documents.knowledgebases import KnowledgeBaseRetrievalClient
from azure.search.documents.knowledgebases.models import KnowledgeBaseMessage, KnowledgeBaseMessageTextContent, KnowledgeBaseRetrievalRequest, SearchIndexKnowledgeSourceParams

kb_client = KnowledgeBaseRetrievalClient(endpoint = "search_url", knowledge_base_name = "knowledge_base_name", credential = AzureKeyCredential("api_key"))

request = KnowledgeBaseRetrievalRequest(
    messages=[
        KnowledgeBaseMessage(
            role = "assistant",
            content = [KnowledgeBaseMessageTextContent(text = "Use the earth at night index to answer the question. If you can't find relevant content, say you don't know.")]
        ),
        KnowledgeBaseMessage(
            role = "user",
            content = [KnowledgeBaseMessageTextContent(text = "Where does the ocean look green?")]
        ),
    ],
    knowledge_source_params=[
        SearchIndexKnowledgeSourceParams(
            knowledge_source_name = "earth-at-night-ks",
            include_references = True,
            include_reference_source_data = True,
            always_query_source = False,
        )
    ],
    include_activity = True,
)

result = kb_client.retrieve(request)
print(result.response[0].content[0].text)

要点

  • messages 是必需的,但只能使用 user 提供查询的角色运行此示例。

  • knowledge_source_params 指定一个或多个查询目标。 对于每个知识源,可以指定要包含在输出中的信息量。

对示例查询的响应可能如以下示例所示:

  "response": [
    {
      "content": [
        {
          "type": "text",
          "text": "The ocean appears green off the coast of Antarctica due to phytoplankton flourishing in the water, particularly in Granite Harbor near Antarctica’s Ross Sea, where they can grow in large quantities during spring, summer, and even autumn under the right conditions [ref_id:0]. Additionally, off the coast of Namibia, the ocean can also look green due to blooms of phytoplankton and yellow-green patches of sulfur precipitating from bacteria in oxygen-depleted waters [ref_id:1]. In the Strait of Georgia, Canada, the waters turned bright green due to a massive bloom of coccolithophores, a type of phytoplankton [ref_id:5]. Furthermore, a milky green and blue bloom was observed off the coast of Patagonia, Argentina, where nutrient-rich waters from different currents converge [ref_id:6]. Lastly, a large bloom of cyanobacteria was captured in the Baltic Sea, which can also give the water a green appearance [ref_id:9]."
        }
      ]
    }
  ]

删除知识库

如果不再需要知识库或需要在搜索服务上重新生成它,请使用此请求删除该对象。

# Delete a knowledge base
from azure.core.credentials import AzureKeyCredential 
from azure.search.documents.indexes import SearchIndexClient

index_client = SearchIndexClient(endpoint = "search_url", credential = AzureKeyCredential("api_key"))
index_client.delete_knowledge_base("knowledge_base_name")
print(f"Knowledge base deleted successfully.")

注释

此功能目前处于公开预览状态。 此预览版未随附服务级别协议,建议不要用于生产工作负载。 某些功能可能不受支持或者受限。 有关详细信息,请参阅 Microsoft Azure 预览版补充使用条款

在 Azure AI 搜索中, 知识库 是协调 代理检索的顶级对象。 它定义要查询的知识源以及用于检索作的默认行为。 在查询时, 检索方法 以知识库为目标,以运行配置的检索管道。

知识库指定:

  • 指向可搜索内容的一个或多个知识源。
  • 一个可选的 LLM,为查询规划和答案生成提供推理能力。
  • 用于确定是否调用 LLM 并管理成本、延迟和质量的检索推理工作。
  • 控制路由、源选择、输出格式和对象加密的自定义属性。

创建知识库后,可以随时更新其属性。 如果知识库正在使用中,更新将对下一次检索生效。

重要

2025-11-01-preview 将 2025-08-01-preview 知识代理 重命名为 知识库。 这是一项重大更改。 建议尽快将现有代码迁移到新的 API

先决条件

注释

尽管可以使用 Azure 门户创建知识库,但门户使用 2025-08-01-preview,该预览版使用以前的“知识代理”术语,不支持所有 2025-11-01-preview 功能。 如需中断性变更方面的帮助,请参阅迁移智能体检索代码

支持的模型

使用 Azure OpenAI 中的以下 LLM 之一或等效的开源模型。 有关部署说明,请参阅 使用 Microsoft Foundry 部署 Azure OpenAI 模型

  • gpt-4o
  • gpt-4o-mini
  • gpt-4.1
  • gpt-4.1-nano
  • gpt-4.1-mini
  • gpt-5
  • gpt-5-nano
  • gpt-5-mini

配置访问权限

Azure AI 搜索需要访问 Azure OpenAI 的 LLM。 我们建议使用 Microsoft Entra ID 进行身份验证,并使用基于角色的访问控制进行授权。 你必须是 所有者或用户访问管理员 才能分配角色。 如果角色不可行,请改用基于密钥的身份验证。

  1. 将 Azure AI 搜索配置为使用托管标识

  2. 在您的模型提供商(例如 Foundry 模型)中,将 认知服务用户 作为搜索服务的托管标识进行分配。 如果要在本地进行测试,请将相同的角色分配给用户帐户。

  3. 对于本地测试,请按照《快速入门:在没有密钥的情况下连接》的步骤操作,以获取特定订阅和租户的个人访问令牌。 在每个请求中指定访问令牌,该令牌应类似于以下示例:

    # List indexes using roles
    GET https://{{search-url}}/indexes?api-version=2025-11-01-preview
    Content-Type: application/json
    Authorization: Bearer {{access-token}}
    

重要

本文中的代码片段使用 API 密钥。 如果使用基于角色的身份验证,请相应地更新每个请求。 在指定这两种方法的请求中,API 密钥优先。

检查现有知识库

知识库是顶级可重用对象。 了解现有知识库有助于重复使用或命名新对象。 任何 2025-08-01-preview 知识智能体会在知识库集合中返回。

使用 知识库 - 列表(REST API) 按名称和类型列出知识库。

# List knowledge bases
GET {{search-url}}/knowledgebases?api-version=2025-11-01-preview&$select=name
Content-Type: application/json
api-key: {{search-api-key}}

还可以按名称返回单个知识库来查看其 JSON 定义。

# Get knowledge base
GET {{search-url}}/knowledgebases/{{knowledge-base-name}}?api-version=2025-11-01-preview
Content-Type: application/json
api-key: {{search-api-key}}

以下 JSON 是知识库的示例响应。

{
  "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"
  }
}

创建知识库

知识库驱动代理检索管道。 在应用程序代码中,它由其他代理或聊天机器人调用。

知识库将知识库(可搜索内容)连接到 Azure OpenAI 中的 LLM 部署。 LLM 上的属性建立连接,而知识源上的属性建立默认值,用于通知查询执行和响应。

使用 知识库 - 创建或更新(REST API) 来制定请求。

# Create a knowledge base
PUT {{search-url}}/knowledgebases/{{knowledge-base-name}}?api-version=2025-11-01-preview
Content-Type: application/json
api-key: {{search-api-key}}

{
    "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": null,
    "outputMode": "answerSynthesis",
    "knowledgeSources": [
        {
            "name": "hotels-ks"
        },
        {
            "name": "earth-at-night-ks"
        }
    ],
    "models" : [ 
        {
            "kind": "azureOpenAI",
            "azureOpenAIParameters": {
                "resourceUri": "{{model-provider-url}}",
                "apiKey": "{{model-api-key}}",
                "deploymentId": "gpt-4.1-mini",
                "modelName": "gpt-4.1-mini"
            }
        }
    ],
    "encryptionKey": null,
    "retrievalReasoningEffort": {
        "kind": "low"
    }
}

知识库属性

可以传递以下属性来创建知识库。

Name Description 类型 必选
name 知识库的名称,该名称在知识库集合中必须是唯一的,并遵循 Azure AI 搜索中对象的 命名准则 String 是的
description 知识库的说明。 LLM 使用该说明来指导查询规划。 String
retrievalInstructions 向 LLM 发出的提示,用于确定某个知识来源是否应纳入查询范围,有多个知识来源时建议纳入。 此字段同时影响知识来源选择和查询表述。 例如,说明可以追加信息或确定知识来源的优先级。 指令直接传递到 LLM,这意味着可以提供破坏查询规划的说明,例如导致绕过关键知识源的说明。 String 是的
answerInstructions 自定义指令以定制合成答案。 默认值为 NULL。 有关详细信息,请参阅 如何使用答案合成生成有引文支持的响应 String 是的
outputMode 有效值为 answerSynthesis,它用于 LLM 生成的答案;若希望获取完整搜索结果并将其作为下游步骤传递给 LLM,则有效值为 extractedData String 是的
knowledgeSources 一个或多个 受支持的知识源 Array 是的
models 支持的 LLM 的连接,用于答案生成或查询规划。 在此预览版中, models 只能包含一个模型,模型提供程序必须是 Azure OpenAI。 从 Foundry 门户或命令行请求获取模型信息。 可以使用基于角色的访问控制,而不是将 API 密钥用于与模型建立的 Azure AI 搜索连接。 有关详细信息,请参阅 如何使用 Foundry 部署 Azure OpenAI 模型 物体
encryptionKey 客户 管理的密钥 ,用于加密知识库和生成的对象中的敏感信息。 物体
retrievalReasoningEffort.kind 确定与 LLM 相关的查询处理级别。 有效值为 minimallow (默认值)和 medium。 有关详细信息,请参阅 设置检索推理工作 物体

查询知识库

retrieve 知识库上调用操作以验证 LLM 连接并返回结果。 有关请求和响应架构的详细信息 retrieve ,请参阅 在 Azure AI 搜索中使用知识库检索数据

使用 知识检索 - 检索(REST API) 来构建请求。 将“海洋在何处看起来绿色?”替换为对知识源有效的查询字符串。

# Send grounding request
POST {{search-url}}/knowledgebases/{{knowledge-base-name}}/retrieve?api-version=2025-11-01-preview
Content-Type: application/json
api-key: {{search-api-key}}

{
    "messages" : [
        { "role" : "assistant",
                "content" : [
                  { "type" : "text", "text" : "Use the earth at night index to answer the question. If you can't find relevant content, say you don't know." }
                ]
        },
        {
            "role" : "user",
            "content" : [
                {
                    "text" : "Where does the ocean look green?",
                    "type" : "text"
                }
            ]
        }
    ],
    "includeActivity": true,
    "knowledgeSourceParams": [
        {
            "knowledgeSourceName": "earth-at-night-ks",
            "kind": "searchIndex",
            "includeReferences": true,
            "includeReferenceSourceData": true,
            "alwaysQuerySource": false
        }
  ]
}

要点

  • messages 是必需的,但只能使用 user 提供查询的角色运行此示例。

  • knowledgeSourceParams 指定一个或多个查询目标。 对于每个知识源,可以指定要包含在输出中的信息量。

对示例查询的响应可能如以下示例所示:

  "response": [
    {
      "content": [
        {
          "type": "text",
          "text": "The ocean appears green off the coast of Antarctica due to phytoplankton flourishing in the water, particularly in Granite Harbor near Antarctica’s Ross Sea, where they can grow in large quantities during spring, summer, and even autumn under the right conditions [ref_id:0]. Additionally, off the coast of Namibia, the ocean can also look green due to blooms of phytoplankton and yellow-green patches of sulfur precipitating from bacteria in oxygen-depleted waters [ref_id:1]. In the Strait of Georgia, Canada, the waters turned bright green due to a massive bloom of coccolithophores, a type of phytoplankton [ref_id:5]. Furthermore, a milky green and blue bloom was observed off the coast of Patagonia, Argentina, where nutrient-rich waters from different currents converge [ref_id:6]. Lastly, a large bloom of cyanobacteria was captured in the Baltic Sea, which can also give the water a green appearance [ref_id:9]."
        }
      ]
    }
  ]

删除知识库

如果不再需要知识库或需要在搜索服务上重新生成它,请使用此请求删除该对象。

# Delete a knowledge base
DELETE {{search-url}}/knowledgebases/{{knowledge-base-name}}?api-version=2025-11-01-preview
api-key: {{search-api-key}}