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

使用检索操作或 MCP 端点来查询知识库

注意

Foundry IQ (Azure AI 搜索) 提供直接索引和查询 API 以及用于托管检索的高级知识库和知识库 API。 使用 Azure 门户、REST API 或 Azure SDK 配置这些功能,或将代理连接到 Microsoft Foundry 门户中的知识库。

重要

本文中标记为(预览)的功能为公共预览版,受Microsoft Azure预览版补充使用条款的约束。 有关 Foundry IQ(Azure AI 搜索)特有的预览术语,请参阅预览功能。

在代理检索管道中, 检索操作 从知识库调用并行查询处理。 可以使用搜索服务 REST API 或Azure SDK直接调用检索操作。 每个知识库还公开一个模型上下文协议(MCP)终结点,供 MCP 兼容的代理使用。

若要设置一个通过 MCP 将 Foundry IQ(Azure AI 搜索)连接到 Foundry 代理服务的管道,请参阅教程:构建端到端智能体检索解决方案。

使用支持

Azure 门户 Microsoft Foundry 门户 .NET SDK Python SDK Java SDK JavaScript SDK REST API
✔️ ✔️ ✔️ ✔️ ✔️ ✔️ ✔️

先决条件

  • 如果通过 Azure OpenAI 响应 API 调用 MCP 终结点,则需要:

    • 在 Foundry 资源上部署的 LLM 和认知服务 OpenAI 用户角色(或 API 密钥)。 可以重复使用知识库中指定的 LLM 和资源(如果适用)。

    • Azure.AI.OpenAI 包:dotnet add package Azure.AI.OpenAI

  • Azure.Identity中列出的 Azure.Search.Documents 和 软件包。 使用最新的稳定 2026-10-01 包。 预览 SDK 示例使用最新预览版包及其默认 2026-11-01-preview 约定。

  • 如果通过 Azure OpenAI 响应 API 调用 MCP 终结点,则需要:

    • 在 Foundry 资源上部署的 LLM 和认知服务 OpenAI 用户角色(或 API 密钥)。 可以重复使用知识库中指定的 LLM 和资源(如果适用)。

    • openai 包:pip install openai

  • azure-identity中列出的 azure-search-documents 和 软件包。 使用最新的稳定 2026-10-01 包。 预览 SDK 示例使用最新预览版包及其默认 2026-11-01-preview 约定。

  • 所需的搜索服务 REST API 版本:

    • 对于预览功能: 2026-11-01-preview

    • 对于此处所述的 GA 合同: 2026-10-01 以下 2026-04-01 示例仍遵循支持范围较窄的 API 协定。

  • 对于无密钥身份验证,请在每个 HTTP 请求的标头中包含AuthorizationMicrosoft Entra ID令牌。

Limitations

对于搜索索引知识源,在启用重新排序时,检索会使用该知识源的语义配置。 基础索引 defaultScoringProfile 可能会影响第一阶段候选选择,但不依赖于任意索引 评分配置文件 来控制最终知识库语义排名。 检索响应也不呈现 @search.rerankerBoostedScore。

调用检索操作

在知识库上指定检索操作。 请求正文包括查询输入以及可选的各来源参数。 这些参数配置附加源;省略条目不会排除该源。

正式版 2026-10-01 REST 协定支持最低(minimal)、低(low)和中等(medium)三种检索推理强度,以及基于模型的规划、答案合成、引用和服务器发送事件(SSE)。 较早的 2026-04-01 协定仅支持意图和最低推理强度的抽取式检索。 正式版协定不接受仅在预览版中提供的字段。

使用 2026-10-01 REST 进行检索

首先,使用已有数据的现有搜索索引知识源创建无需模型的知识库。 使用经授权可检索内容的相同 {{knowledge-source-name}} 和凭据。 将问题替换为与源相关的问题。

POST {{search-endpoint}}/knowledgebases('core-minimal-kb')/retrieve?api-version=2026-10-01
Content-Type: application/json
Accept: application/json
Authorization: Bearer {{search-token}}

{
  "intents": [
    { "type": "semantic", "search": "What is the return policy?" }
  ],
  "retrievalReasoningEffort": { "kind": "minimal" },
  "outputMode": "extractiveData",
  "includeActivity": true,
  "maxRuntimeInSeconds": 30,
  "maxOutputDocuments": 3,
  "maxOutputSizeInTokens": 5000,
  "knowledgeSourceParams": [
    {
      "knowledgeSourceName": "{{knowledge-source-name}}",
      "kind": "searchIndex",
      "alwaysQuerySource": true,
      "failOnError": true,
      "includeReferences": true,
      "includeReferenceSourceData": true,
      "maxOutputDocuments": 50
    }
  ]
}

参考:知识检索 - 检索

检查 response、references 和 activity。 此请求使用一个完整的语义意图,无需聊天模型。 普通的最小检索拒绝 messages。 对于 low 或 medium 规划,请配置 受支持的模型 并提供消息或语义意向,但不能同时提供两者。

在模型驱动选择期间,仅显式 alwaysQuerySource: true 使源成为必需项。 普通的最小检索选择所有候选源,而不考虑此标志。 false 或省略并不等于排除。 如果某个选定的源在检索或后处理时失败,failOnError 会使整个请求失败。

GA 请求设置 边界和行为
maxRuntimeInSeconds 10 到 600 秒。 系统的回退值为 90 秒。省略该值时,实际采用的值可能受已保存的默认设置影响。
顶层 maxOutputDocuments 先应用各个源的限制,再将此限制应用于去重后的文档,可设范围为 1 至 200 个文档。 重复条目不使用另一个文档分配,因此此值不是引用数组长度限制。
按源 maxOutputDocuments 50 到 200。 影响候选大小设定、页面大小设定和按源最终剪枝。
maxOutputSizeInTokens 至少 5,000 个令牌。 控制溯源输出裁剪,不保证合成答案长度。 回退预算因工作量、启用的功能和配置而异。
rerankerThreshold 0 到 4。 根据需要为各个源分别设置分数阈值,不要假定所有源都采用同一默认阈值。
includeReferences、includeReferenceSourceData 分别控制引用及其源数据。 要返回源数据,必须启用引用。 按配置的默认设置,引用已启用,源数据已禁用。

每个 knowledgeSourceParams 条目都必须包含 knowledgeSourceName 以及与该源匹配的 kind。 对于搜索索引源,filterAddOn 会与任何已存储的 searchIndexParameters.baseFilter 使用 AND 组合;它不会替换已存储的筛选器。

对于 Web 源,请求中的language、market、count 和 freshness 会覆盖已存储的 webParameters 值。 此后,仍未指定的值采用系统默认值,即 en、en-US,以及默认计数 20。 语言和市场必须是受支持的值;count 接受 1 到 50 之间的值。 时效性参数接受 Day、Week、Month、一个有效日期,或按起止顺序指定的 YYYY-MM-DD..YYYY-MM-DD 范围。

将存储的源属性、知识库成员关系和请求参数彼此分开。 查询提示和resultsProcessing不属于2026-10-01。 有关存储的配置,请参阅 知识源设置。

使用 2026-10-01 Python 进行检索

使用 无模型知识库 及其现有的、已填充的搜索索引知识源。 在环境中将 SEARCH_API_KEY 和 SEARCH_ENDPOINT 设置为服务终结点和授权的 API 密钥。 将知识库名称和 source_name 替换为你自己的值,并选择与源内容相关的问题。

按顺序运行这些块。

import os
from azure.core.credentials import AzureKeyCredential
from azure.search.documents.knowledgebases import KnowledgeBaseRetrievalClient
from azure.search.documents.knowledgebases.models import (
    KnowledgeBaseRetrievalRequest,
    KnowledgeBaseSearchIndexReference,
    KnowledgeRetrievalMinimalReasoningEffort,
    KnowledgeRetrievalSemanticIntent,
    SearchIndexKnowledgeSourceParams,
)

endpoint = os.environ["SEARCH_ENDPOINT"]
credential = AzureKeyCredential(os.environ["SEARCH_API_KEY"])
source_name = "<existing-search-index-source>"
question = "What is the return policy?"
kb_client = KnowledgeBaseRetrievalClient(
    endpoint=endpoint,
    credential=credential,
    api_version="2026-10-01",
    knowledge_base_name="<knowledge-base-name>",
)

参考:KnowledgeBaseRetrievalClient

创建一个使用单个语义意图、最低推理强度和抽取式输出的请求。 顶层输出上限为 3 个文档,每个源的上限设为 50 个文档。 该请求分别启用引用及其源数据。

baseline_request = KnowledgeBaseRetrievalRequest(
    intents=[KnowledgeRetrievalSemanticIntent(search=question)],
    retrieval_reasoning_effort=KnowledgeRetrievalMinimalReasoningEffort(),
    output_mode="extractiveData",
    include_activity=True,
    max_runtime_in_seconds=30,
    max_output_documents=3,
    max_output_size_in_tokens=6000,
    knowledge_source_params=[
        SearchIndexKnowledgeSourceParams(
            knowledge_source_name=source_name,
            include_references=True,
            include_reference_source_data=True,
            always_query_source=True,
            fail_on_error=False,
            max_output_documents=50,
        )
    ],
)
baseline_response = kb_client.retrieve(baseline_request)
for message in baseline_response.response:
    for content in message.content:
        print(content.text)

activities_by_id = {
    activity.id: activity for activity in baseline_response.activity or []
}
for activity in baseline_response.activity or []:
    print(activity.id, activity.type)
for reference in baseline_response.references or []:
    if not isinstance(reference, KnowledgeBaseSearchIndexReference):
        continue
    activity = activities_by_id.get(reference.activity_source)
    if getattr(activity, "knowledge_source_name", None) != source_name:
        continue
    print(reference.id, reference.doc_key, reference.activity_source)
    print(reference.source_data)
    print(reference.citation_url)

参考:KnowledgeBaseRetrievalClient

检查用作回答依据的内容,查找来自已填充数据的知识源的信息。 此响应不是合成答案。

SDK 和早期版本示例

预览版 SDK 示例使用最新的预览包及其默认 2026-11-01-preview 协定。

将无模型知识库与现有且已填充的搜索索引知识源一起使用。 在环境中将 SEARCH_API_KEY 和 SEARCH_ENDPOINT 设置为服务终结点和授权的 API 密钥。 将知识库名称和 sourceName 替换为你自己的值,并选择与源内容相关的问题。

按顺序运行以下设置和请求块。 后续的 C# 无模型示例将在此客户端的基础上继续展开。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Azure;
using Azure.Search.Documents.Indexes.Models;
using Azure.Search.Documents.KnowledgeBases;
using Azure.Search.Documents.KnowledgeBases.Models;
using Azure.Search.Documents.Models;

var endpoint = new Uri(Environment.GetEnvironmentVariable("SEARCH_ENDPOINT"));
var key = Environment.GetEnvironmentVariable("SEARCH_API_KEY");
var credential = new AzureKeyCredential(key);
var knowledgeBaseName = "<knowledge-base-name>";
var sourceName = "<existing-search-index-source>";
var question = "What is the return policy?";
var kbClient = new KnowledgeBaseRetrievalClient(
    endpoint, knowledgeBaseName, credential);

参考:KnowledgeBaseRetrievalClient

基线使用一个语义意图、最小工作量、抽取式输出、活动,以及带有源数据的源引用。 源文档设置独立于请求范围的文档限制。

KnowledgeBaseRetrievalRequest previewRetrievalRequest = new()
{
    RetrievalReasoningEffort = new KnowledgeRetrievalMinimalReasoningEffort(),
    OutputMode = KnowledgeRetrievalOutputMode.ExtractiveData,
    IncludeActivity = true,
    MaxRuntimeInSeconds = 30,
    MaxOutputDocuments = 5
};
previewRetrievalRequest.Intents.Add(
    new KnowledgeRetrievalSemanticIntent(question));
previewRetrievalRequest.KnowledgeSourceParams.Add(
    new SearchIndexKnowledgeSourceParams(sourceName)
    {
        IncludeReferences = true,
        IncludeReferenceSourceData = true,
        MaxOutputDocuments = 50
    });
var previewResult = await kbClient.RetrieveAsync(
    previewRetrievalRequest, cancellationToken: CancellationToken.None);
KnowledgeBaseRetrievalResponse baselineResponse = previewResult.Value;
Console.WriteLine(
    ((KnowledgeBaseMessageTextContent)baselineResponse.Response[0].Content[0]).Text);

参考:KnowledgeBaseRetrievalClient, KnowledgeBaseRetrievalRequest

检查返回的提取内容以获取来自已填充源的信息。 响应返回用作回答依据的数据,不包含由模型合成的答案。 不要根据引用数组的长度断定返回了多少个文档。

from azure.identity import DefaultAzureCredential
from azure.search.documents.knowledgebases import KnowledgeBaseRetrievalClient
from azure.search.documents.knowledgebases.models import (
    KnowledgeBaseMessage,
    KnowledgeBaseMessageTextContent,
    KnowledgeBaseRetrievalRequest,
    SearchIndexKnowledgeSourceParams,
)

# Create knowledge base retrieval client
kb_client = KnowledgeBaseRetrievalClient(
    endpoint="<search-endpoint>",
    knowledge_base_name="<knowledge-base-name>",
    credential=DefaultAzureCredential(),
)

request = KnowledgeBaseRetrievalRequest(
    messages=[
        KnowledgeBaseMessage(
            role="assistant",
            content=[
                KnowledgeBaseMessageTextContent(
                    text="You can answer questions about the Earth at night. "
                    "Sources have a JSON format with a ref_id that must be cited in the answer. "
                    "If you do not have the answer, respond with 'I do not know'."
                )
            ],
        ),
        KnowledgeBaseMessage(
            role="user",
            content=[
                KnowledgeBaseMessageTextContent(
                    text="Why is the Phoenix nighttime street grid so sharply visible from space, "
                    "whereas large stretches of the interstate between midwestern cities remain comparatively dim?"
                )
            ],
        ),
    ],
    knowledge_source_params=[
        SearchIndexKnowledgeSourceParams(
            knowledge_source_name="earth-at-night-blob-ks",
        )
    ],
)

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

参考:KnowledgeBaseRetrievalClient, KnowledgeBaseRetrievalRequest

@search-endpoint = <search-endpoint> // Example: https://my-service.search.windows.net
@search-access-token = <search-access-token> // Run: az account get-access-token --scope https://search.azure.com/.default --query accessToken -o tsv

POST {{search-endpoint}}/knowledgebases/{{knowledge-base-name}}/retrieve?api-version=2026-11-01-preview
Content-Type: application/json
Authorization: Bearer {{search-access-token}}

{
    "messages": [
        {
            "role": "assistant",
            "content": [
                {
                    "type": "text",
                    "text": "You can answer questions about the Earth at night. Sources have a JSON format with a ref_id that must be cited in the answer. If you do not have the answer, respond with 'I do not know'."
                }
            ]
        },
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "Why is the Phoenix nighttime street grid so sharply visible from space, whereas large stretches of the interstate between midwestern cities remain comparatively dim?"
                }
            ]
        }
    ],
    "knowledgeSourceParams": [
        {
            "knowledgeSourceName": "earth-at-night-blob-ks",
            "kind": "searchIndex"
        }
    ]
}

参考:知识检索 - 检索

提供图像以进行答案综合生成(预览版)

对于配置了资产存储的 blob、已编制索引的 OneLake 和 已编制索引的 SharePoint 知识源,可以将文档中嵌入的图像连同文本一起提供给下游答案合成模型。 在匹配项上设置 enableImageServing 以替代知识库定义上设置的默认项 knowledgeSourceParams 。 检索响应不包括提供给模型的单个图像路径或图像字节的专用字段。

映像服务仅在 outputMode 为answerSynthesis 时运行,并且不支持为配置ingestionPermissionOptions的知识源启用此服务。 有关设置步骤、优先级表以及如何检查图像提供统计信息,请参阅在智能体检索中显示文档嵌入的图像(预览版)。

禁用知识源的重新排序(预览版)

从 2026-08-01-preview API 版本开始,在 "resultsProcessing": "none" 条目上设置 knowledgeSourceParams,即可绕过针对特定知识源的重新排序,并保留其底层结果顺序。 您还可以将 resultsProcessing 作为默认值存储在知识源中。 所有知识源类型都支持此属性。

以下示例在一次检索请求中绕过了对 product-catalog-ks 的重排序。

using System;
using System.Linq;
using Azure.Identity;
using Azure.Search.Documents.Indexes.Models;
using Azure.Search.Documents.KnowledgeBases;
using Azure.Search.Documents.KnowledgeBases.Models;

var client = new KnowledgeBaseRetrievalClient(
    new Uri("<search-endpoint>"),
    "product-catalog-kb",
    new DefaultAzureCredential());

var request = new KnowledgeBaseRetrievalRequest
{
    IncludeActivity = true
};
request.Intents.Add(
    new KnowledgeRetrievalSemanticIntent(
        "Find the power adapter for SKU 88421."));
request.KnowledgeSourceParams.Add(
    new SearchIndexKnowledgeSourceParams("product-catalog-ks")
    {
        AlwaysQuerySource = true,
        IncludeReferences = true,
        ResultsProcessing = KnowledgeSourceResultsProcessing.None
    });

var result = await client.RetrieveAsync(request);
Console.WriteLine(
    $"References with a reranker score: "
    + $"{result.Value.References.Count(x => x.RerankerScore.HasValue)}");

参考:KnowledgeBaseRetrievalClient、 SearchIndexKnowledgeSourceParams

from azure.identity import DefaultAzureCredential
from azure.search.documents.knowledgebases import (
    KnowledgeBaseRetrievalClient,
)
from azure.search.documents.knowledgebases.models import (
    KnowledgeBaseRetrievalRequest,
    KnowledgeRetrievalSemanticIntent,
    SearchIndexKnowledgeSourceParams,
)

client = KnowledgeBaseRetrievalClient(
    endpoint="<search-endpoint>",
    knowledge_base_name="product-catalog-kb",
    credential=DefaultAzureCredential(),
)

request = KnowledgeBaseRetrievalRequest(
    intents=[
        KnowledgeRetrievalSemanticIntent(
            search="Find the power adapter for SKU 88421."
        )
    ],
    include_activity=True,
    knowledge_source_params=[
        SearchIndexKnowledgeSourceParams(
            knowledge_source_name="product-catalog-ks",
            always_query_source=True,
            include_references=True,
            results_processing="none",
        )
    ],
)

result = client.retrieve(request)
reranked_count = sum(
    reference.reranker_score is not None
    for reference in result.references
)
print("References with a reranker score:", reranked_count)

参考:KnowledgeBaseRetrievalClient、 SearchIndexKnowledgeSourceParams

@search-endpoint = <search-endpoint>
@search-access-token = <search-access-token> // Run: az account get-access-token --scope https://search.azure.com/.default --query accessToken -o tsv
@knowledge-base-name = product-catalog-kb

POST {{search-endpoint}}/knowledgebases/{{knowledge-base-name}}/retrieve?api-version=2026-11-01-preview
Content-Type: application/json
Authorization: Bearer {{search-access-token}}

{
  "intents": [
    {
      "type": "semantic",
      "search": "Find the power adapter for SKU 88421."
    }
  ],
  "includeActivity": true,
  "knowledgeSourceParams": [
    {
      "knowledgeSourceName": "product-catalog-ks",
      "kind": "searchIndex",
      "alwaysQuerySource": true,
      "includeReferences": true,
      "resultsProcessing": "none"
    }
  ]
}

参考:知识检索 - 检索

设置 "resultsProcessing": "rerank",或在不存在已存储的默认值时省略它,以使用重排序管道。 Foundry IQ 按以下顺序确定每个源的生效值:

  1. 检索请求的 knowledgeSourceParams 中指定的 resultsProcessing。
  2. 知识源中存储的 resultsProcessing。
  3. 两个属性都不存在时,使用 rerank。

对于 MCP 服务器知识源, resultsProcessing 在单个工具上设置的值优先于请求和存储的值。

Tip

resultsProcessing 改变的是结果的处理方式,而不是查询哪些来源。 如果必须查询知识源,请将true设置为alwaysQuerySource。

有效值为 none:

  • 来自知识源的引用会省略 rerankerScore,结果在该源的检索活动中保留其原有顺序。
  • 只要有一个源跳过重新排序,Foundry IQ 就会按照知识源的声明顺序,在各项活动之间轮流分配最终结果。 重新排序后的活动按分数顺序保持排列。
  • 重复数据删除和按源、文档和令牌限制仍然适用,因此并非每个检索到的结果都会出现在响应中。

Foundry IQ 按以下顺序进行验证 rerankerThreshold :

  1. 搜索会从检索请求和存储的知识源值中解析出 resultsProcessing。
  2. 如果解析的值是 none 且请求包含 rerankerThreshold,则搜索将 400 Bad Request返回。
  3. 对于 MCP 服务器工具,搜索在验证请求后应用工具级 resultsProcessing 值。

因此,MCP 工具设置不会更改请求是否通过验证。 工具级none值不会导致阈值错误,当请求或存储的值解析为none时,工具级rerank值不会阻止错误。

若要确认哪个模式已运行,请检查知识源的引用是否包括 rerankerScore。 不要依赖 semanticConfigurationName,因为它可能是 null,而不是被省略。

搜索索引行为

对于面向搜索索引的知识源,隐式查询类型为 semantic,并且没有搜索模式。 执行重新排序时,查询执行使用 semanticConfigurationName。 其他源设置(包括 searchFields 和 sourceDataFields)在两种模式下都适用。

代理检索不接受 scoringProfile 或 scoringParameters 输入。 基础索引 defaultScoringProfile 可能会影响第一阶段候选选择,但它不会为知识库检索建立任意配置文件的最终语义排名协定。 如果您需要让已索引的知识源具有时效性偏向,请使用 时效性感知检索(预览),而不是索引评分配置。

如果索引包含矢量字段,则需要有效的向量器定义,以便代理检索引擎可以向量化查询输入。 否则,将忽略向量字段。

有关详细信息,请参阅 创建索引进行代理检索。

流式传输检索结果

从 2026-08-01-preview API 版本开始,retrieve 支持服务器发送事件(SSE)。 GA 2026-10-01 REST 合约中也提供 SSE。 流式传输报告活动和已完成的输出,不会逐个令牌返回答案的增量内容。

使用 2026-10-01 REST 进行流式传输

使用与 GA JSON 请求相同的知识库、填充的源和授权凭据。 请求正文无需更改,显式指定 Accept: text/event-stream 即可启用流式传输。 不要添加正文流式处理开关或 _overload 查询参数。

POST {{search-endpoint}}/knowledgebases('core-minimal-kb')/retrieve?api-version=2026-10-01
Content-Type: application/json
Accept: text/event-stream
Authorization: Bearer {{search-token}}

{
  "intents": [
    { "type": "semantic", "search": "What is the return policy?" }
  ],
  "retrievalReasoningEffort": { "kind": "minimal" },
  "outputMode": "extractiveData",
  "includeActivity": true,
  "maxRuntimeInSeconds": 30,
  "maxOutputDocuments": 3,
  "maxOutputSizeInTokens": 5000,
  "knowledgeSourceParams": [
    {
      "knowledgeSourceName": "{{knowledge-source-name}}",
      "kind": "searchIndex",
      "alwaysQuerySource": true,
      "failOnError": true,
      "includeReferences": true,
      "includeReferenceSourceData": true,
      "maxOutputDocuments": 50
    }
  ]
}

参考:知识检索 - 检索

以下示例演示了流式响应,有效负载缩短,以提高可读性。

event: retrieval.started
data: {"requestId":"<request-id>","outputMode":"extractiveData"}

event: activity.started
data: {"id":0,"type":"searchIndex","startedAt":"<timestamp>"}

: heartbeat

event: activity.completed
data: {"id":0,"startedAt":"<start>","completedAt":"<end>"}

event: references.completed
data: [{"type":"searchIndex","id":"0","activitySource":0}]

event: response.completed
data: {"statusCode":200,"response":{}}

早期版本流式处理示例

以下 SDK 和 REST 示例保留其预览版契约,包括仅预览版提供的结果处理选项。

从 11 月预览版 C# 客户端设置 继续,并内联创建流式处理请求。

KnowledgeBaseRetrievalRequest streamRequest = new()
{
    RetrievalReasoningEffort = new KnowledgeRetrievalMinimalReasoningEffort(),
    OutputMode = KnowledgeRetrievalOutputMode.ExtractiveData,
    IncludeActivity = true,
    MaxRuntimeInSeconds = 30,
    MaxOutputDocuments = 5
};
streamRequest.Intents.Add(new KnowledgeRetrievalSemanticIntent(question));
streamRequest.KnowledgeSourceParams.Add(
    new SearchIndexKnowledgeSourceParams(sourceName)
    {
        IncludeReferences = true,
        IncludeReferenceSourceData = true,
        MaxOutputDocuments = 50
    });
var eventCounts = new Dictionary<string, int>();

参考:KnowledgeBaseRetrievalClient

对流式处理的事件类型进行计数。

await foreach (var item in kbClient.RetrieveStreamAsync(
    streamRequest, cancellationToken: CancellationToken.None))
{
    eventCounts.TryGetValue(item.EventType, out var count);
    eventCounts[item.EventType] = count + 1;
}

foreach (var (eventType, count) in eventCounts)
{
    Console.WriteLine($"{eventType}: {count}");
}

参考:KnowledgeBaseRetrievalClient

from collections import Counter

from azure.identity import DefaultAzureCredential
from azure.search.documents.indexes.models import (
    KnowledgeSourceResultsProcessing,
)
from azure.search.documents.knowledgebases import (
    KnowledgeBaseRetrievalClient,
)
from azure.search.documents.knowledgebases.models import (
    KnowledgeBaseRetrievalRequest,
    KnowledgeRetrievalMinimalReasoningEffort,
    KnowledgeRetrievalOutputMode,
    KnowledgeRetrievalSemanticIntent,
    SearchIndexKnowledgeSourceParams,
)


client = KnowledgeBaseRetrievalClient(
    endpoint="<search-endpoint>",
    knowledge_base_name="<knowledge-base-name>",
    credential=DefaultAzureCredential(),
)

request = KnowledgeBaseRetrievalRequest(
    intents=[
        KnowledgeRetrievalSemanticIntent(
            search="What is the return policy?"
        )
    ],
    output_mode=KnowledgeRetrievalOutputMode.EXTRACTIVE_DATA,
    retrieval_reasoning_effort=KnowledgeRetrievalMinimalReasoningEffort(),
    include_activity=True,
    knowledge_source_params=[
        SearchIndexKnowledgeSourceParams(
            knowledge_source_name="<knowledge-source-name>",
            results_processing=KnowledgeSourceResultsProcessing.NONE,
            include_references=True,
        )
    ],
)

event_counts = Counter()

with client.retrieve_stream(request) as stream:
    for event in stream:
        event_counts[event.event_type] += 1

for event_type, count in event_counts.items():
    print(f"{event_type}: {count}")

参考:KnowledgeBaseRetrievalClient

若要启用流式传输,请在检索请求中包含 Accept: text/event-stream 标头。 如果没有此标头,检索操作将返回其标准 JSON 响应。

POST {{search-endpoint}}/knowledgebases/{{knowledge-base-name}}/retrieve?api-version=2026-11-01-preview
Content-Type: application/json
Accept: text/event-stream
Authorization: Bearer {{search-access-token}}

{
    "intents": [
        {
            "type": "semantic",
            "search": "What is the return policy?"
        }
    ],
    "outputMode": "extractiveData",
    "retrievalReasoningEffort": {
        "kind": "minimal"
    },
    "includeActivity": true,
    "knowledgeSourceParams": [
        {
            "knowledgeSourceName": "{{knowledge-source-name}}",
            "kind": "searchIndex",
            "resultsProcessing": "none",
            "includeReferences": true
        }
    ]
}

参考:知识检索 - 检索

事件生命周期

服务不返回单个响应,而是保持一个 HTTP 连接处于打开状态,内容类型为 text/event-stream; charset=utf-8。 命名事件使用 UTF-8 编码和 LF 行结尾:一行 event:、一行包含 JSON 的 data:,以及一个空行。 服务会将每个事件或心跳注释立即发送给客户端。

一个成功的流遵循以下生命周期:

Event 发送时间 它包含的内容
retrieval.started 准备和验证均成功且流打开后的第一个事件。 应用默认设置后确定的 requestId、knowledgeBaseName、outputMode 和 reasoningEffort。 该字段是reasoningEffort,不是retrievalReasoningEffort。 预览版中的 auto仅报告初始推理强度,不反映后续的强度提升。
activity.started 查询规划、源或模型活动开始时。 活动可以交错。 包含 id、type、startedAt 以及可选 knowledgeSourceName 的直接负载,而不是活动包装器。 当 false 为 includeActivity 时被抑制。
activity.completed 当该活动结束时。 使用 id关联事件。 直接返回已完成的活动记录,无外层包装。 当 false 为 includeActivity 时被抑制。
answer.completed 当 outputMode 为 answerSynthesis 时,每条响应消息对应一个事件。 messageIndex 和完整 message。 没有逐个令牌的增量事件。
references.completed 在所有引用都解析完成后。 事件数据是完整的references 数组,没有对象包装器。
response.completed 成功或部分成功流的终止事件。 具有 statusCode (200 或 206) 且 response 包含完整检索响应的对象。 请参阅 “检索操作疑难解答”。
error 当流打开后检索失败时,不要执行 references.completed 和 response.completed。 错误信息以及在故障发生前已完成的所有活动记录。

事件按顺序到达。 每个 activity.started 事件都先于具有相同 id 的 activity.completed 事件发生,但活动可以交错进行。 已完成的活动记录还包括 startedAt 和 completedAt 时间戳。 当流处于空闲状态时,服务器大约每 15 秒发送一条 : heartbeat 注释,以使连接保持打开状态。 SSE 客户端可以忽略这些注释。

处理错误、取消和回退

  • 预检失败:如果在流打开前请求验证失败(例如对于格式不正确的请求正文),检索操作将返回标准 JSON 错误响应,并且永远不会打开流。

  • 中流检索失败:报告的检索异常生成终端 error 而不是正常完成。 其有效负载包含 error 和可选已完成 activity。 流打开后,HTTP 状态仍为200。 序列化或传输失败可能导致流被截断,且不会发出终止错误事件。

  • 取消或断开连接:客户端取消请求时,流会结束,不会发出最终事件。 缺少 response.completed 的流应视为不完整,包括因传输或序列化问题而被截断的流。

  • JSON 回退:使用 2026-10-01 或 2026-11-01-preview 时,如果缺少 Accept 标头,或其值为 application/json、*/*、text/* 或 text/event-stream;q=0 等,服务将返回标准 JSON。 若要启用流式传输,必须显式包含 text/event-stream 成员(不区分大小写),且其质量权重(q 值)必须大于 0。 在不支持该功能的版本上显式指定 SSE 会返回 406 Not Acceptable。

在查询时筛选搜索索引知识源

从搜索索引知识源检索时,可以在查询时应用 OData 筛选器 ,将结果缩小到特定文档或字段。 筛选器表达式使用 OData 语法,并通过 filterAddOn 参数传递。

筛选语法和示例

该 filterAddOn 参数接受 OData 筛选器表达式。 示例模式包括:

  • 元数据字段: city eq 'Phoenix'、status eq 'active'
  • 日期范围: publishDate ge 2024-01-01 and publishDate le 2024-12-31
  • 数值范围: price ge 100 and price le 5000
  • 文本匹配:substringof('climate', description),indexof(title, 'urgent') ge 0
  • 逻辑运算符: (category eq 'News' or category eq 'Analysis') and status eq 'published'

完成 11 月预览版 C# 示例中的客户端和请求设置后,继续执行后续步骤。 此变体需要在后备索引中包含一个可Canada筛选字段,其值例如 美国 和 country。 使用与内容匹配的新请求和筛选器。 存储的基础筛选器仍与 FilterAddOn 使用 AND 结合使用;更改此请求不会更改存储的筛选器。

KnowledgeBaseRetrievalRequest filteredRequest = new()
{
    RetrievalReasoningEffort = new KnowledgeRetrievalMinimalReasoningEffort(),
    OutputMode = KnowledgeRetrievalOutputMode.ExtractiveData,
    IncludeActivity = true,
    MaxRuntimeInSeconds = 30,
    MaxOutputDocuments = 5
};
filteredRequest.Intents.Add(new KnowledgeRetrievalSemanticIntent(question));
filteredRequest.KnowledgeSourceParams.Add(
    new SearchIndexKnowledgeSourceParams(sourceName)
    {
        IncludeReferences = true,
        IncludeReferenceSourceData = true,
        MaxOutputDocuments = 50,
        FilterAddOn = "country eq 'Canada'"
    });
KnowledgeBaseRetrievalResponse filteredResponse = (await kbClient.RetrieveAsync(
    filteredRequest, cancellationToken: CancellationToken.None)).Value;
Console.WriteLine(
    ((KnowledgeBaseMessageTextContent)filteredResponse.Response[0].Content[0]).Text);

参考:SearchIndexKnowledgeSourceParams

使用其客户端和导入,基于 使用 2026-10-01 Python 进行检索 继续。 本示例假定存在一个可筛选的 id 字段和一个键为 ca-leave 的文档。 将该值替换为源中的某个值。

filtered_request = KnowledgeBaseRetrievalRequest(
    intents=[KnowledgeRetrievalSemanticIntent(search=question)],
    retrieval_reasoning_effort=KnowledgeRetrievalMinimalReasoningEffort(),
    output_mode="extractiveData",
    include_activity=True,
    max_runtime_in_seconds=30,
    max_output_documents=3,
    max_output_size_in_tokens=6000,
    knowledge_source_params=[
        SearchIndexKnowledgeSourceParams(
            knowledge_source_name=source_name,
            include_references=True,
            include_reference_source_data=True,
            always_query_source=True,
            fail_on_error=False,
            max_output_documents=50,
            filter_add_on="id eq 'ca-leave'",
        )
    ],
)
filtered_response = kb_client.retrieve(filtered_request)
for message in filtered_response.response:
    for content in message.content:
        print(content.text)

参考:SearchIndexKnowledgeSourceParams

请求筛选器与存储的基础筛选器使用 AND 组合。 例如,对于可 country 筛选的字段和存储的 country eq 'CA' 筛选器,包含 filter_add_on="country eq 'US'" 的新请求可能返回不到匹配的内容。

POST {{search-endpoint}}/knowledgebases/{{knowledge-base-name}}/retrieve?api-version=2026-11-01-preview
Content-Type: application/json
Authorization: Bearer {{search-access-token}}

{
    "messages": [
        {
            "role": "assistant",
            "content": [
                {
                    "type": "text",
                    "text": "You are a support agent. Answer questions based on published documentation. If you don't know the answer, say so."
                }
            ]
        },
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "What is the process for submitting an expense report?"
                }
            ]
        }
    ],
    "knowledgeSourceParams": [
        {
            "knowledgeSourceName": "internal-documentation-ks",
            "kind": "searchIndex",
            "filterAddOn": "status eq 'published'"
        }
    ]
}

多筛选器示例

可以合并多个筛选器以进一步优化结果。

searchIndexParams.FilterAddOn = "(status eq 'published' or status eq 'internal') and created ge 2025-01-01";
filter_add_on="(status eq 'published' or status eq 'internal') and created ge 2025-01-01"
{
    "knowledgeSourceName": "internal-documentation-ks",
    "kind": "searchIndex",
    "filterAddOn": "(status eq 'published' or status eq 'internal') and created ge 2025-01-01"
}

在查询时覆盖已存储的查询提示(预览)

从 2026-08-01-preview API 版本开始,您可以通过在其 knowledgeSourceParams 条目上设置 queryHintOverrides,为单个检索请求覆盖存储在搜索索引知识源上的查询提示。

覆盖会替换整个已存储的 queryHints 对象,而不是按条目逐一合并,因此请包含你想要应用的每一项提示。 省略 queryHintOverrides 即可使用已存储的提示。

当检索推理工作量不为 minimal 时,HTTP 400 响应取决于存储的筛选提示,而不是覆盖内容或提升类型。 在应用 queryHintOverrides之前,服务会根据知识库模型验证存储的筛选器提示。 因此,即使覆盖项为空或仅包含增强项,GPT-4o 或 GPT-4.1 系列模型也会拒绝该请求。 仅存储提升不会触发此验证。 请使用兼容的模型,或先删除已存储的筛选提示。

以下示例将所有已存储的提示替换为一个用于日语内容的 fieldValue 增强。 该服务不会对此请求应用任何已存储的筛选条件或其他已存储的提升设置。

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

var endpoint = new Uri("<search-endpoint>");
var retrievalClient = new KnowledgeBaseRetrievalClient(
    endpoint,
    "product-kb",
    new DefaultAzureCredential());

var languageBoost =
    new SearchIndexKnowledgeSourceFieldValueBoost(
        "language",
        2.0);
languageBoost.FieldValues.Add("ja-JP");
var queryHintOverrides =
    new SearchIndexKnowledgeSourceQueryHints();
queryHintOverrides.Boosts.Add(languageBoost);

var request = new KnowledgeBaseRetrievalRequest
{
    RetrievalReasoningEffort =
        new KnowledgeRetrievalLowReasoningEffort(),
    IncludeActivity = true
};
request.Messages.Add(
    new KnowledgeBaseMessage([
        new KnowledgeBaseMessageTextContent(
            "Find Japanese service guidance for Model-X200.")
    ])
    {
        Role = "user"
    });
request.KnowledgeSourceParams.Add(
    new SearchIndexKnowledgeSourceParams(
        "product-docs-ks")
    {
        QueryHintOverrides = queryHintOverrides
    });

var result = await retrievalClient.RetrieveAsync(request);

参考:KnowledgeBaseRetrievalClient、 SearchIndexKnowledgeSourceParams

from azure.identity import DefaultAzureCredential
from azure.search.documents.indexes.models import (
    SearchIndexKnowledgeSourceFieldValueBoost,
    SearchIndexKnowledgeSourceQueryHints,
)
from azure.search.documents.knowledgebases import (
    KnowledgeBaseRetrievalClient,
)
from azure.search.documents.knowledgebases.models import (
    KnowledgeBaseMessage,
    KnowledgeBaseMessageTextContent,
    KnowledgeBaseRetrievalRequest,
    KnowledgeRetrievalLowReasoningEffort,
    SearchIndexKnowledgeSourceParams,
)

retrieval_client = KnowledgeBaseRetrievalClient(
    endpoint="<search-endpoint>",
    credential=DefaultAzureCredential(),
    knowledge_base_name="product-kb",
)

query_hint_overrides = SearchIndexKnowledgeSourceQueryHints(
    boosts=[
        SearchIndexKnowledgeSourceFieldValueBoost(
            field="language",
            field_values=["ja-JP"],
            boost=2.0,
        )
    ]
)

request = KnowledgeBaseRetrievalRequest(
    messages=[
        KnowledgeBaseMessage(
            role="user",
            content=[
                KnowledgeBaseMessageTextContent(
                    text="Find Japanese service guidance for Model-X200."
                )
            ],
        )
    ],
    knowledge_source_params=[
        SearchIndexKnowledgeSourceParams(
            knowledge_source_name="product-docs-ks",
            query_hint_overrides=query_hint_overrides,
        )
    ],
    retrieval_reasoning_effort=(
        KnowledgeRetrievalLowReasoningEffort()
    ),
    include_activity=True,
)

result = retrieval_client.retrieve(request)

参考:KnowledgeBaseRetrievalClient、 SearchIndexKnowledgeSourceParams

POST {{search-endpoint}}/knowledgebases('product-kb')/retrieve?api-version=2026-11-01-preview
Content-Type: application/json
Authorization: Bearer {{search-access-token}}

{
  "messages": [{
    "role": "user",
    "content": [{
      "type": "text",
      "text": "Find Japanese service guidance for Model-X200."
    }]
  }],
  "knowledgeSourceParams": [{
    "knowledgeSourceName": "product-docs-ks",
    "kind": "searchIndex",
    "queryHintOverrides": {
      "boosts": [{
        "kind": "fieldValue",
        "field": "language",
        "fieldValues": ["ja-JP"],
        "boost": 2.0
      }]
    }
  }],
  "retrievalReasoningEffort": {"kind": "low"},
  "includeActivity": true
}

参考:知识检索 - 检索

若要确认服务是否应用了你的覆盖设置,请在请求中设置 includeActivity,并检查返回的 searchIndex 活动。 其 queryHintProcessing 对象报告模型生成的内容。 在此示例中,它包含一个用于语言提升的 generatedBoost,但没有 generatedFilter,因为覆盖替换了存储的筛选器提示。 由于查询提示仅是尽力而为,因此应将这一操作视为确认,而不是检查是否存在完全精确的表达式。

{
  "type": "searchIndex",
  "queryHintProcessing": {
    "generatedBoost": "language:(ja\\-JP)^2"
  },
  "searchIndexArguments": {
    "queryType": "full"
  }
}

有关存储的定义、支持的提示类型和具有确定性筛选器的组合,请参阅“配置查询提示”(预览版)。

在查询时强制实施权限(预览版)

你在 2026-11-01-preview 之外设置的访问权限变更,可能需要一段时间才能显示在 2026-11-01-preview 的检索结果中。

如果知识源包含受权限保护的内容,请在检索请求中传递最终用户的标识,以便每个用户仅看到他们有权访问的内容。 对于启用了本机权限筛选的搜索索引,省略 x-ms-query-source-authorization 仅保留公共 all 授权;它不返回未筛选的结果或匹配存储 RBAC 范围。 仍需要操作授权。 远程源还使用来自检索请求的授权,但在源中强制实施权限,并且可能需要特定于源的令牌和标头。

REST API 2026-10-01 已正式支持引入 ADLS Gen2 所支持的 ACL/RBAC 权限和标准 Blob 容器的 RBAC 权限,并在查询时按这些权限筛选结果。 有关正式版的配置方法,请参见Blob/ADLS 权限配置。 其他源类型、Purview 和独立检索预览控件仍保持文档中所述的可用性。

权限控制的实施有两个部分:

  • 摄取时:仅对于已编入索引的知识源,设置 ingestionPermissionOptions 以在摄取内容的同时引入权限元数据。

  • 查询时:在知识源要求的标头中传递用户的授权信息。 大多数源都使用 x-ms-query-source-authorization。 例外的是 Work IQ,它使用 x-ms-query-work-iq-source-authorization。

引入时间配置

下表显示了哪些知识源需要引入时间配置以及每个源如何强制实施权限。

知识源 需要 ingestionPermissionOptions 如何执行权限
Blob 或 ADLS Gen2 ✅ 根据用户标识匹配的 RBAC 作用域、ACL 或 Microsoft Purview。
OneLake ✅ 使用索引的源位置和查询时 OneLake 授权()引入 Microsoft Purview 敏感度标签或 2026-11-01-preview。
已编入索引的 SharePoint ✅ 已引入的、与用户标识匹配的 SharePoint ACL 或 Microsoft Purview 敏感度标签。
远程SharePoint ❌ Copilot检索API使用用户的令牌直接查询SharePoint。
Fabric数据代理 ❌ 检索引擎将用户的令牌交换为 Microsoft Fabric 作用域令牌,并代表用户向数据智能体发出查询。
Fabric本体 ❌ 检索引擎将用户的令牌交换为 Microsoft Fabric 作用域令牌,并代表用户向本体项发出查询。
Work IQ ❌ 检索引擎使用从 x-ms-query-work-iq-source-authorization 获得的面向应用受众的用户断言来换取 Work IQ 作用域令牌。

对于依赖 ingestionPermissionOptions 的自动生成索引,如果省略该配置,系统就不会引入权限元数据。 源标识标头无法补偿缺少的元数据。 这独立于本机权限筛选的搜索索引,其权限字段已存在于索引中。

查询时授权

对于 Work IQ 以外的知识源,使用 https://search.azure.com/.default 请求用于访问搜索服务的委托用户访问令牌,并在 x-ms-query-source-authorization 中传递该令牌。 此令牌表示对其内容访问进行评估的用户;它不需要搜索角色分配。

Authorization 中的调用方令牌单独授权搜索操作。 它可以表示具有所需搜索角色的应用程序服务主体或托管标识。 支持某个主体作为调用方,并不表示也支持将其用作文档权限主体。请参见查询时的令牌角色和权限流。

对于工作 IQ 知识源,本部分不适用。 使用 在查询时强制实施权限 中所述的 Work IQ 特定的用户断言流程。

使用已正式发布的提升权限读取功能开展管理调查时,请直接查询底层搜索索引。 2026-10-01检索 REST API 不声明x-ms-enable-elevated-read标头。

在 .NET SDK 中,将令牌作为 querySourceAuthorization 上的 RetrieveAsync 参数传递:

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

// Service credential: Authenticates to the search service
var serviceCredential = new DefaultAzureCredential();

// User identity token: Represents the end user for document-level permissions filtering
var userTokenContext = new Azure.Core.TokenRequestContext(
    new[] { "https://search.azure.com/.default" }
);
string userToken = (await serviceCredential.GetTokenAsync(userTokenContext)).Token;

// Create the retrieval client with the service credential
var kbClient = new KnowledgeBaseRetrievalClient(
    endpoint: new Uri("<search-endpoint>"),
    knowledgeBaseName: "<knowledge-base-name>",
    credential: serviceCredential
);

var request = new KnowledgeBaseRetrievalRequest();
request.Messages.Add(
    new KnowledgeBaseMessage(
        content: new[] {
            new KnowledgeBaseMessageTextContent(
                "What companies are in the financial sector?")
        }
    ) { Role = "user" }
);

// Pass the user identity token for permissions filtering
var result = await kbClient.RetrieveAsync(
    request, querySourceAuthorization: userToken);

var text = (result.Value.Response[0].Content[0] as KnowledgeBaseMessageTextContent)!.Text;
Console.WriteLine(text);

参考:KnowledgeBaseRetrievalClient, KnowledgeBaseRetrievalRequest

在 Python SDK 中,在 query_source_authorization 上将令牌作为 retrieve 参数传递:

from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from azure.search.documents.knowledgebases import KnowledgeBaseRetrievalClient
from azure.search.documents.knowledgebases.models import (
    KnowledgeBaseMessage, KnowledgeBaseMessageTextContent,
    KnowledgeBaseRetrievalRequest,
)

# Service credential: Authenticates to the search service
service_credential = DefaultAzureCredential()

# User identity token: Represents the end user for document-level permissions filtering
user_token_provider = get_bearer_token_provider(
    service_credential, "https://search.azure.com/.default")
user_token = user_token_provider()

# Create the retrieval client with the service credential
kb_client = KnowledgeBaseRetrievalClient(
    endpoint="<search-endpoint>",
    knowledge_base_name="<knowledge-base-name>",
    credential=service_credential,
)

request = KnowledgeBaseRetrievalRequest(
    messages=[
        KnowledgeBaseMessage(
            role="user",
            content=[KnowledgeBaseMessageTextContent(
                text="What companies are in the financial sector?")],
        )
    ]
)

# Pass the user identity token for permissions filtering
result = kb_client.retrieve(
    retrieval_request=request, query_source_authorization=user_token)
print(result.response[0].content[0].text)

参考:KnowledgeBaseRetrievalClient, KnowledgeBaseRetrievalRequest

在 REST API 中,包含 x-ms-query-source-authorization 具有用户访问令牌的标头:

@search-endpoint = <search-endpoint>
@search-access-token = <search-access-token> // Service credential
@user-access-token = <user-access-token> // User identity token

POST {{search-endpoint}}/knowledgebases/{{knowledge-base-name}}/retrieve?api-version=2026-11-01-preview
Authorization: Bearer {{search-access-token}}
Content-Type: application/json
x-ms-query-source-authorization: {{user-access-token}}

{
    "messages": [
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "What companies are in the financial sector?"
                }
            ]
        }
    ]
}

参考:知识检索 - 检索

查看响应

检索操作返回三个主要组件:

在 2026-10-01 中,这些组件包括 response、可选的 activity 以及可选的 references。 outputMode用于选择返回抽取式数据,还是由模型合成答案。 以下选项卡保留其早期版本示例。

提取的响应

提取的响应是单个统一字符串,通常传递给 LLM。 LLM 使用字符串作为基础数据,并使用它来生成回复。 对 LLM 的 API 请求包括用于模型的统一字符串和说明,例如是否使用该依据作为唯一参考还是补充。

响应正文以聊天消息样式格式进行结构化,内容序列化为 JSON。

"response": [
    {
        "role": "assistant",
        "content": [
            {
                "type": "text",
                "text": "[{\"ref_id\":\"0\",\"title\":\"Urban Structure\",\"terms\":\"Location of Phoenix, Grid of City Blocks, Phoenix Metropolitan Area at Night\",\"content\":\"<content chunk redacted>\"}]"
            }
        ]
    }
]

要点:

  • content.type 具有一个有效值: text.

  • content.text 是一个 JSON 编码的字符串,其中包含在搜索索引中找到的最相关的文档(或区块),给定查询和聊天历史记录输入。 此字符串是 LLM 用于制定用户问题响应的基础数据。

    • 最终内容受每个源和请求范围的文档和令牌限制的约束。 重新调整的结果也使用有效的源阈值。

    • 该字符串以区块的引用 ID(用于引文目的)和目标索引的语义配置中指定的任何字段开头。 在此示例中,假定目标索引中的语义配置具有“title”字段、“terms”字段和“content”字段。

  • 检索响应中未包含 @search.rerankerBoostedScore。

  • 请求的令牌预算决定如何裁剪输出中用作回答依据的数据。 在 2026-10-01 中使用 maxOutputSizeInTokens;较早的预览示例使用 maxOutputSize。

    • 对于由于超出输出预算而省略的文档,请参阅 空响应。

活动数组

包含诊断信息时,活动数组会报告规划、源查询和模型操作。 当206 Partial Content反映已记录的源故障时,请检查该活动的错误。 其他部分结果(如可恢复的最小检索超时)需要单独的解释。 响应 502 Bad Gateway 可能仅在顶级错误中提供失败详细信息。

在 2026-10-01,活动的可选 warning 是一个字符串,不同于 error。 多个警告通过换行符连接在一起。 例如,活动可以警告:由于其最相关的文档对于上下文窗口来说太大,最终输出中没有文档保留。 仅凭警告无法确定 HTTP 状态。

活动数组包括以下组件:

章节 描述
特定于源的活动 对于查询中包含的每个知识源,本节将报告已用的时间以及查询中使用的参数,包括语义排名器。 知识源类型包括 searchIndex、 azureBlob支持的其他 知识源。
agenticReasoning 本部分报告检索期间代理推理的令牌消耗情况,具体取决于指定的检索推理工作(预览版)。
modelQueryPlanning 对于使用 LLM 进行查询规划的知识库,本节报告输入所用的令牌数以及子查询的令牌数。 它包含一个 model 字段,其中有一个 modelName 字段,包含运行该活动的模型的公开模型名称,而不是其部署名称。
modelAnswerSynthesis 对于使用 答案合成(预览)的知识库,本部分报告用于制定答案的令牌计数和答案输出的令牌计数。 它包含一个 model 字段,其中有一个 modelName 字段,包含运行该活动的模型的公开模型名称,而不是其部署名称。
modelWebSummarization 对于使用 Web 摘要的知识库,本部分报告用于汇总 Web 结果的令牌消耗情况。 它包含一个 model 字段,其中有一个 modelName 字段,包含运行该活动的模型的公开模型名称,而不是其部署名称。
model 对于模型支持的活动记录,本部分标识用于执行活动的模型。 仅当您将 includeActivity 设置为 true 时,才会显示本节。
imageServing 对于启用了图像服务(预览版)的知识源,本部分显示imagesRetrieved、imagesSentToModel、totalImageSizeBytes以及索引时verbalizationUsed是否已启用。 分别检查imagesSentToModel和verbalizationUsed。 响应可以将 verbalizationUsed 报告为 true,同时仍向下游模型发送图像。 若要查找已删除的图像数,请从imagesSentToModel中减去imagesRetrieved。

以下示例显示了活动数组。

  "activity": [
    {
      "type": "modelQueryPlanning",
      "id": 0,
      "inputTokens": 2302,
      "outputTokens": 109,
      "elapsedMs": 2396
    },
    {
      "type": "searchIndex",
      "id": 1,
      "knowledgeSourceName": "demo-financials-ks",
      "queryTime": "2025-11-04T19:25:23.683Z",
      "count": 26,
      "elapsedMs": 1137,
      "searchIndexArguments": {
        "search": "List of companies in the financial sector according to SEC GICS classification",
        "filter": null,
        "sourceDataFields": [ ],
        "searchFields": [ ],
        "semanticConfigurationName": "en-semantic-config"
      }
    },
    {
      "type": "searchIndex",
      "id": 2,
      "knowledgeSourceName": "demo-healthcare-ks",
      "queryTime": "2025-11-04T19:25:24.186Z",
      "count": 17,
      "elapsedMs": 494,
      "searchIndexArguments": {
        "search": "List of companies in the financial sector according to SEC GICS classification",
        "filter": null,
        "sourceDataFields": [ ],
        "searchFields": [ ],
        "semanticConfigurationName": "en-semantic-config"
      }
    },
    {
      "type": "agenticReasoning",
      "id": 3,
      "retrievalReasoningEffort": {
        "kind": "low"
      },
      "reasoningTokens": 103368
    },
    {
      "type": "modelAnswerSynthesis",
      "id": 4,
      "inputTokens": 5821,
      "outputTokens": 344,
      "elapsedMs": 3837
    }
  ]

引用数组

可选的引用数组仅描述最终保留的、用作回答依据的数据,不会列出找到或参与排序的所有候选项。 每个源的 includeReferences 设置控制是否包含引用,includeReferenceSourceData 则单独控制是否包含这些引用的源数据。 重复数据删除和最终修剪意味着文档上限不是对引用数量的保证。

在 2026-10-01 中,已编入索引的引用可包含可选的 citationUrl。 它指向底层索引文档,而不是原始文件或 Web 文档。 本文中的早期版本选项卡保留其原始响应形状。

引用数组包括以下组件:

领域 描述
type 生成引用的知识源类型,例如 searchIndex。
id 响应中某一项的引用 ID。 它不是搜索索引中的文档键。 使用它来提供引文。
activitySource 交叉引用生成该引用的活动条目的 id,这对于引文链接很有用。
docKey 对于索引引用,文档键位于底层搜索索引中。
sourceData 用于生成响应的依据数据。 对于已编制索引的引用,字段可以包括一个 id 字段以及语义字段,例如 title、terms 和 content。 形状因引用类型而异。
citationUrl (预览版) 由服务生成的只读 URL,指向底层索引中该引用对应的文档。 仅对已编入索引的知识源返回。 若要跟踪 URL,请参阅使用引文 URL 查找文档(预览版)。

以下示例显示了引用数组。

  "references": [
    {
      "type": "searchIndex",
      "id": "0",
      "activitySource": 2,
      "docKey": "policy=aug-2026",
      "citationUrl": "https://my-search-service.search.windows.net/indexes/my-index/docs/policy%3Daug-2026?$select=title%2Ccontent%2Ccategory%2Cid%2Clanguage&api-version=2026-11-01-preview",
      "sourceData": null
    },
    {
      "type": "searchIndex",
      "id": "1",
      "activitySource": 2,
      "docKey": "2",
      "citationUrl": "https://my-search-service.search.windows.net/indexes/my-index/docs/2?$select=title%2Ccontent%2Ccategory%2Cid%2Clanguage&api-version=2026-11-01-preview",
      "sourceData": null
    }
  ]

使用引文 URL 查找文档

从 2026-08-01-preview API 版本开始,来自索引知识源的引用可以包括在 citationUrl 检索响应中。 使用此 URL 提取该引用的索引字段,例如 title , content这样,您可以呈现引文预览,其中显示答案的来源,而无需打开原始源文档。 citationUrl这是对后盾索引的经过身份验证的查找,独立于源docUrl和 blobUrl。

2026-10-01 也支持用于 indexedSharePoint、file、searchIndex、azureBlob、indexedOneLake 和 indexedSql 引用的引文 URL。 它们不需要答案合成。 必须为源启用引用,并且当无法解析支持索引或文档键时,可以省略 URL。 所选字段遵循解析的源选择;通配符或未指定选择不会添加 $select 限制。

原样使用返回的 URL,包括其 API 版本和转义。 以下示例使用 2026-11-01-preview 协定。

以下示例显示了清理的引文 URL。

"citationUrl": "https://my-search-service.search.windows.net/indexes/my-index/docs/policy%3Daug-2026?$select=title%2Ccontent%2Ccategory%2Cid%2Clanguage&api-version=2026-11-01-preview"

所选字段及其顺序取决于索引源和检索配置。

重要

按照响应的完整 URL 逐字执行,并在应用中呈现返回的 JSON 字段。 不要构造、分析或规范化 URL。

访问引用 URL 时,会对底层索引执行 Documents-Get(获取文档)操作。 它需要文档读取授权,例如 搜索索引数据读取器,独立于 KB 定义访问。 原生文档权限仍然适用。如果调用方无权访问文档,或文档不存在,该操作可能返回 404。 以下示例对 Foundry IQ 服务的 HTTP GET 进行身份验证。

Azure AI 搜索 SDK 文档查找方法需要终结点、索引名称、文档密钥、所选字段和 API 版本作为单独的输入。 它们不接受绝对引文 URL。 这些示例使用经过身份验证的 HTTP GET 来保留完整的服务生成的 URL。

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using Azure.Core;
using Azure.Identity;

// citationUrl comes from a retrieve response
string citationUrl = "<citation-url>";

var credential = new DefaultAzureCredential();
AccessToken token = await credential.GetTokenAsync(
    new TokenRequestContext(
        new[] { "https://search.azure.com/.default" }));

using var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", token.Token);

string document = await httpClient.GetStringAsync(citationUrl);
Console.WriteLine(document);

参考:DefaultAzureCredential

import json
from urllib.request import Request, urlopen

from azure.identity import DefaultAzureCredential

# citation_url comes from a retrieve response
citation_url = "<citation-url>"

credential = DefaultAzureCredential()
token = credential.get_token("https://search.azure.com/.default")
document_request = Request(
    citation_url,
    headers={"Authorization": f"Bearer {token.token}"},
)
with urlopen(document_request) as response:
    document = json.load(response)

print(json.dumps(document, indent=2))

参考:DefaultAzureCredential

GET {{citation-url}}
Authorization: Bearer {{search-access-token}}

参考:文档 - 获取

文档查找将所选索引字段作为 JSON 返回:

{
  "id": "policy=aug-2026",
  "title": "Escaped citation key",
  "content": "Citation interoperability uses an escaped document key for the August preview.",
  "category": "release",
  "language": "en-US"
}

使用引文 URL 时,请记住以下几点:

  • 在渲染引用之前,检查是否存在 citationUrl。 如果响应省略引用,或者服务无法解析支持索引或文档键,则不存在此情况。

  • 对于原生文档权限筛选,请在查找时提供相应用户的 x-ms-query-source-authorization 令牌以及已获授权的服务凭据。

  • 处理应用程序中的查找失败,而不是将 URL 视为永久或独立授权的下载链接。

检查响应中的敏感度标签元数据(预览版)

此处同样适用在查询时强制执行权限中所述的时序行为:对在2026-11-01-preview和2026-11-01-preview之外设置的访问权限所做的更改,可能需要一些时间才会显示在2026-11-01-preview检索响应中。

查询引入Microsoft Purview敏感度标签的知识库时,检索响应包含两个级别的标签元数据:

位置 领域 描述
根据参考 sensitivityLabelInfo 应用于 references 数组中返回的每个文档的敏感度标签。
响应 metadata.responseSensitivityLabelInfo 一种聚合标签,表示响应中所有被引用文档的最高优先级敏感性标签。 适用于客户端横幅显示和策略执行。

Microsoft Graph使用 Microsoft Purview 标签继承规则从每个引用标签计算响应级别标签。 通常,最严格的标签会获胜。

以下示例显示了一个检索响应,其中包含两个引用的文档(一个 Confidential、一个 Internal)和生成的响应级别标签。

{
  "response": [
    {
      "role": "assistant",
      "content": [
        { "type": "text", "text": "[ ... grounding data ... ]" }
      ]
    }
  ],
  "references": [
    {
      "type": "azureBlob",
      "id": "0",
      "activitySource": 1,
      "docKey": "contract-2026.pdf",
      "sensitivityLabelInfo": {
        "labelId": "<label-guid>",
        "labelName": "Confidential",
        "color": "#FF0000",
        "tooltip": "Confidential — Recipients can read but not forward.",
        "isEncrypted": true,
        "priority": 3
      },
      "sourceData": null
    },
    {
      "type": "azureBlob",
      "id": "1",
      "activitySource": 1,
      "docKey": "policy-overview.pdf",
      "sensitivityLabelInfo": {
        "labelId": "<label-guid>",
        "labelName": "Internal",
        "color": "#FFA500",
        "tooltip": "For internal use only.",
        "isEncrypted": false,
        "priority": 1
      },
      "sourceData": null
    }
  ],
  "metadata": {
    "responseSensitivityLabelInfo": {
      "labelId": "<label-guid>",
      "labelName": "Confidential",
      "color": "#FF0000",
      "tooltip": "Confidential — Recipients can read but not forward.",
      "isEncrypted": true,
      "priority": 3
    }
  }
}

显示敏感度标签的引用类型

标签元数据的字段名称和可用性取决于生成每个引用的知识源类型。

请参考 type 标签字段 何时可用...
azureBlob sensitivityLabelInfo Blob 知识来源包括 sensitivityLabel 中的 ingestionPermissionOptions。
indexedOneLake sensitivityLabelInfo OneLake 知识源在 sensitivityLabel 中包括 ingestionPermissionOptions。
indexedSharePoint sensitivityLabelInfo SharePoint 索引知识来源包括 sensitivityLabel 中的 ingestionPermissionOptions。
searchIndex sensitivityLabelInfo 基础索引已 purviewEnabled 设置为 true ,并且具有标记 sensitivityLabelId: true的字段。

显示和审核建议

  • 如果您需要附加属性(例如策略控件或权限),请使用 sensitivityLabelInfo.labelId 通过 Microsoft Graph 敏感度标签 API 查找标签的完整定义。

  • 使用 metadata.responseSensitivityLabelInfo 来呈现响应级敏感度横幅,或对整个答案应用策略控制,例如禁用复制和共享。

  • 如果知识源指向的是分块索引(例如通过集成向量化或自定义“文本拆分”技能填充的索引),请确保技能集将敏感度标签投影到每个分块行。 如果没有此映射,则查询时不会正确筛选区块级引用。

  • 若要以可审计的方式管理访问带标签的内容,请使用用于管理调查的提升权限读取功能查询底层搜索索引。

MCP 服务器行为

每个知识库公开的 MCP 终结点会显示与 REST API 相同的敏感度标签字段。 当兼容 MCP 的客户端调用 knowledge_base_retrieve 工具时,工具结果包含本节前文所述的相同的每个引用对应的 sensitivityLabelInfo 和响应级别的 metadata.responseSensitivityLabelInfo。 MCP 客户端基于这些字段强制实施标签感知显示和策略控制。

检索操作示例(预览版)

REST 示例使用最新的预览 API; 2026-11-01-previewSDK 示例保留其现有的预览包协定。 它们包括不属于 2026-10-01的仅限预览的选项。 有关 GA 请求形状,请参阅 使用 2026-10-01 REST 检索。

查看活动日志中的模型名称

将 true 设置为 includeActivity,以返回基于模型的活动记录中的模型标识字段。 使用这些字段可以确认在检索请求期间哪个配置的模型处理了查询规划、答案合成或 Web 摘要。 以下示例替代请求上所选源的存储结果处理。

在 2026-11-01-preview中,将配置类型 microsoftRetriever1 与活动模型名称 microsoft-retriever-1区分开来。 使用 includeActivity: true,检查实际由模型支持的规划活动,而不是从 KB 定义推断执行。 Microsoft Retriever 1 仅计划检索。 如果外部模型合成答案,请检查单独的 modelAnswerSynthesis 活动以识别该模型。

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

var kbClient = new KnowledgeBaseRetrievalClient(
    new Uri("<search-endpoint>"),
    "<knowledge-base-name>",
    new DefaultAzureCredential()
);

var retrievalRequest = new KnowledgeBaseRetrievalRequest();
retrievalRequest.Messages.Add(
    new KnowledgeBaseMessage(
        content: new[]
        {
            new KnowledgeBaseMessageTextContent(
                "Which policy applies to returns?"
            )
        }
    ) { Role = "user" }
);
retrievalRequest.IncludeActivity = true;
retrievalRequest.KnowledgeSourceParams.Add(
    new SearchIndexKnowledgeSourceParams(
        "<knowledge-source-name>"
    )
    {
        ResultsProcessing = KnowledgeSourceResultsProcessing.None
    }
);

var result = await kbClient.RetrieveAsync(retrievalRequest);
foreach (var activity in result.Value.Activity)
{
    KnowledgeBaseActivityRecordModel? model = activity switch
    {
        KnowledgeBaseModelQueryPlanningActivityRecord queryPlanning =>
            queryPlanning.Model,
        KnowledgeBaseModelAnswerSynthesisActivityRecord answerSynthesis =>
            answerSynthesis.Model,
        KnowledgeBaseModelWebSummarizationActivityRecord webSummarization =>
            webSummarization.Model,
        _ => null
    };

    if (model is not null)
    {
        Console.WriteLine(
            $"modelName={model.ModelName}, deploymentId={model.DeploymentId}");
    }
}

参考:KnowledgeBaseRetrievalClient, KnowledgeBaseRetrievalRequest

from azure.identity import DefaultAzureCredential
from azure.search.documents.knowledgebases import (
    KnowledgeBaseRetrievalClient,
)
from azure.search.documents.knowledgebases.models import (
    KnowledgeBaseMessage,
    KnowledgeBaseMessageTextContent,
    KnowledgeBaseModelAnswerSynthesisActivityRecord,
    KnowledgeBaseModelQueryPlanningActivityRecord,
    KnowledgeBaseModelWebSummarizationActivityRecord,
    KnowledgeBaseRetrievalRequest,
    SearchIndexKnowledgeSourceParams,
)

kb_client = KnowledgeBaseRetrievalClient(
    "<search-endpoint>",
    DefaultAzureCredential(),
    knowledge_base_name="<knowledge-base-name>",
)

model_activity_types = (
    KnowledgeBaseModelQueryPlanningActivityRecord,
    KnowledgeBaseModelAnswerSynthesisActivityRecord,
    KnowledgeBaseModelWebSummarizationActivityRecord,
)

request = KnowledgeBaseRetrievalRequest(
    messages=[
        KnowledgeBaseMessage(
            role="user",
            content=[
                KnowledgeBaseMessageTextContent(
                    text="Which policy applies to returns?"
                )
            ],
        )
    ],
    include_activity=True,
    knowledge_source_params=[
        SearchIndexKnowledgeSourceParams(
            knowledge_source_name="<knowledge-source-name>",
            results_processing="none",
        )
    ],
)

result = kb_client.retrieve(request)
for entry in result.activity or []:
    if isinstance(entry, model_activity_types) and entry.model:
        print(
            "modelName=", entry.model.model_name,
            "deploymentId=", entry.model.deployment_id,
        )

参考:KnowledgeBaseRetrievalClient, KnowledgeBaseRetrievalRequest

POST {{search-endpoint}}/knowledgebases/{{knowledge-base-name}}/retrieve?api-version=2026-11-01-preview
Authorization: Bearer {{search-access-token}}
Content-Type: application/json

{
    "messages": [
        {
            "role": "user",
            "content": [
                { "type": "text", "text": "Which policy applies to returns?" }
            ]
        }
    ],
    "includeActivity": true,
    "knowledgeSourceParams": [
        {
            "knowledgeSourceName": "{{knowledge-source-name}}",
            "kind": "searchIndex",
            "resultsProcessing": "none"
        }
    ]
}

参考:知识检索 - 检索

以下响应摘录显示了嵌套模型标识:

{
  "activity": [
    {
      "type": "modelQueryPlanning",
      "id": 0,
      "model": {
        "modelName": "gpt-5-mini",
        "deploymentId": "gpt-5-mini-deployment"
      },
      "inputTokens": 1842,
      "outputTokens": 87,
      "elapsedMs": 1923
    },
    {
      "type": "searchIndex",
      "id": 1,
      "knowledgeSourceName": "operations-ks",
      "count": 12,
      "elapsedMs": 234
    },
    {
      "type": "modelAnswerSynthesis",
      "id": 2,
      "model": {
        "modelName": "gpt-5-mini",
        "deploymentId": "gpt-5-mini-deployment"
      },
      "inputTokens": 2418,
      "outputTokens": 179,
      "elapsedMs": 931
    }
  ]
}

从请求中排除知识源

从 2026-08-01-preview API 版本开始,对于要从检索请求中排除的每个知识源,将 neverQuerySource 设置为 true。 请求时的 neverQuerySource 会覆盖该请求的已存储 alwaysQuerySource 值,而不会更改已存储的值。

在 2026-10-01 中不支持此排除标志。 在支持预览版协议中,相同的请求条目不能同时将 neverQuerySource 和 alwaysQuerySource 设为 true,并且请求不能排除每个源。

以下示例查询一个包含 product-docs-ks 和 troubleshooting-ks 的知识库,且请求中排除了 troubleshooting-ks。

对于 C# 示例,请在完成 11 月预览版的客户端设置后继续。 提供另一个现有的附加搜索索引源,以排除,不同于 sourceName。 NeverQuerySource仅影响此次预览版请求,不会更改知识库中已保存的知识源成员列表。

var excludedSourceName = "<second-attached-search-index-source>";
KnowledgeBaseRetrievalRequest excludedRequest = new()
{
    RetrievalReasoningEffort = new KnowledgeRetrievalMinimalReasoningEffort(),
    OutputMode = KnowledgeRetrievalOutputMode.ExtractiveData,
    IncludeActivity = true,
    MaxRuntimeInSeconds = 30,
    MaxOutputDocuments = 5
};
excludedRequest.Intents.Add(new KnowledgeRetrievalSemanticIntent(question));
excludedRequest.KnowledgeSourceParams.Add(
    new SearchIndexKnowledgeSourceParams(sourceName)
    {
        IncludeReferences = true,
        IncludeReferenceSourceData = true,
        MaxOutputDocuments = 50
    });
excludedRequest.KnowledgeSourceParams.Add(
    new SearchIndexKnowledgeSourceParams(excludedSourceName)
    {
        NeverQuerySource = true
    });

KnowledgeBaseRetrievalResponse excludedResponse = (await kbClient.RetrieveAsync(
    excludedRequest, cancellationToken: CancellationToken.None)).Value;
Console.WriteLine(
    ((KnowledgeBaseMessageTextContent)excludedResponse.Response[0].Content[0]).Text);

参考:SearchIndexKnowledgeSourceParams

request = KnowledgeBaseRetrievalRequest(
    messages=[
        KnowledgeBaseMessage(
            role="user",
            content=[
                KnowledgeBaseMessageTextContent(
                    text="Explain the official SSO provisioning steps."
                )
            ],
        )
    ],
    knowledge_source_params=[
        SearchIndexKnowledgeSourceParams(
            knowledge_source_name="product-docs-ks",
        ),
        SearchIndexKnowledgeSourceParams(
            knowledge_source_name="troubleshooting-ks",
            never_query_source=True,
        ),
    ],
)

result = kb_client.retrieve(request)

参考:SearchIndexKnowledgeSourceParams

POST {{search-endpoint}}/knowledgebases/{{knowledge-base-name}}/retrieve?api-version=2026-11-01-preview
Authorization: Bearer {{search-access-token}}
Content-Type: application/json

{
    "messages": [
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "Explain the official SSO provisioning steps."
                }
            ]
        }
    ],
    "knowledgeSourceParams": [
        {
            "knowledgeSourceName": "product-docs-ks",
            "kind": "searchIndex"
        },
        {
            "knowledgeSourceName": "troubleshooting-ks",
            "kind": "searchIndex",
            "neverQuerySource": true
        }
    ]
}

参考:知识检索 - 检索

让服务选择推理强度

auto设置为retrievalReasoningEffort.kind在检索请求中以替代知识库默认值。 有关自动推理的详细信息,请参阅设置检索推理工作(预览版)。

{
  "retrievalReasoningEffort": {
    "kind": "auto"
  }
}

参考:知识检索 - 检索

对检索操作进行故障排除

在 2026-10-01中,区分部分检索、源故障和服务器超时。 对于 SSE,这些结果会在流打开后的终止事件数据中出现,而不是出现在其初始 HTTP 状态中。

地位 Meaning
200 OK 检索成功。 如果文档内容超过输出预算,仍可省略文档。 有关详细信息,请参阅 空响应。
400 Bad Request 检索请求在检索开始之前验证失败。
206 Partial Content 即使未配置要求终止请求的失败处理策略,系统也会在收尾阶段记录源检索或后处理失败的情况。 在服务器超时后,普通的最小提取检索也可以返回累积结果。
502 Bad Gateway 所有检索活动均失败,且没有任何活动返回最终保留的结果,或者标记为 failOnError: true 的源在检索或后处理时失败。
504 Gateway Timeout 在一般最小检索中,服务器超时且没有可恢复的提取结果属于硬超时。 客户端取消是单独的结果。

400 Bad Request

使用顶级错误标识无效的请求属性。 常见原因包括:

  • knowledgeSourceName中的knowledgeSourceParams未关联到知识库,或者其kind与已关联的源不匹配。
  • 请求值超出其支持的范围,或者一个选项需要另一个未启用的选项。 例如,includeReferenceSourceData 要求 includeReferences。
  • retrievalReasoningEffort.kind 是 auto,但请求使用不支持它的协定,包括 2026-10-01。
  • 请求使用 auto, low或 medium,但知识库未定义 受支持的模型。
  • 对于请求时源排除(预览版),同一条目会将alwaysQuerySource和neverQuerySource都设置为true,或者排除所有附加的知识源。

206 Partial Content

检查每个包含 activity 的error条目。 源检索活动标识失败的知识源,模型活动标识失败的处理阶段。 响应正文仍包含已成功的结果。

对于源检索活动错误,常见原因包括:

  • 查询时输入无效,例如格式不正确的 filterAddOn 表达式。
  • 知识源或索引配置偏移,例如重命名的字段、缺少 语义配置或无效 的向量器。
  • 缺少或无效的依赖项授权,或用于查询源的标识没有足够的权限。
  • 依赖项限制、超时或暂时的可用性故障。

对于模型活动错误,请使用活动 type 标识失败的处理阶段。 例如,错误 modelWebSummarization 指示 Web 结果汇总 失败。

如果应用程序允许部分结果,请处理成功的结果并记录每个失败的源或模型阶段。

对于必须选中且必须成功的受支持源,请同时设置 alwaysQuerySource 和 failOnError。 选择和失败策略是独立的。 failOnError适用于已记录的源检索和后处理失败,不是适用于所有模型活动失败的通用策略。

502 Bad Gateway

顶层错误描述了两种硬失败路径中的一种:

  • 每个检索活动都失败,但未保留结果: 成功的零匹配检索不是失败的活动。 检查已记录的失败,查看是否存在共享配置、授权、依赖项或可用性问题。
  • failOnError源失败:所选源存在已记录的检索或后处理失败。 其他源可能已成功,但源的失败策略会阻止部分结果。

有关常见的源检索错误,请参阅 206 部分内容。

硬性502响应可能会省略activity数组,并且仅在顶层错误消息中提供源名称和底层故障信息。

空白响应

搜索可以找到无法进入最终输出的匹配项,因为它们的有依据的内容超出了令牌预算。 具有匹配但没有幸存的文档的活动可以包含警告字符串,“没有返回任何结果,因为最相关的文档太大,无法容纳在上下文窗口中。此警告本身不会分配 206 或其他状态。 若要保留更多内容,请增加请求令牌预算: maxOutputSizeInTokens 在 GA 2026-10-01中,或在 maxOutputSize 前面的预览示例中。

为了避免此行为,请使用稳定标识符和源元数据将大型源文档作为较小的区块编制索引。 这尤其适用于较长的手册、策略或知识库文章。

调用 MCP 终结点

Warning

MCP 实现容易受到攻击、级联失败和人员监督损失等风险的影响。 你可以通过对 MCP 服务器的安全性和可靠性进行审查,遵循Microsoft 建议的做法和行业最佳实践,并实施审批机制以及监控级联行为,来降低这些风险。

MCP 是一种开放协议,用于标准化 AI 应用程序如何连接到外部数据源和工具。

在 Foundry IQ 中,每个知识库都是提供 knowledge_base_retrieve 工具的独立 MCP 服务器。 任何与 MCP 兼容的客户端(包括 Foundry Agent Service、GitHub Copilot、Claude 和 Cursor)都可以调用此工具来查询知识库。

通过使用 2026-11-01-preview,同一终结点还会公开 自定义知识库检索工具。

向 MCP 终结点进行身份验证

每个知识库都有一个位于以下 URL 的 MCP 终结点:

https://<search-service-name>.search.windows.net/knowledgebases/<knowledge-base-name>/mcp?api-version=<api-version>

指定的 API 版本确定连接返回的内容。 如果底层知识库已配置受支持的模型和兼容的推理强度,使用 2026-11-01-preview 即可让知识库返回合成的答案。 通过使用 2026-04-01,检索始终保持最小化且仅为提取式,连接仅返回依据数据。

对此终结点进行身份验证的方式取决于你使用的 MCP 客户端。 当您将 Azure OpenAI Responses API 与 knowledge_base_retrieve MCP 工具配合使用时,您需要同时对发往 Azure OpenAI 的 Responses API 调用和发往 Foundry IQ 的 MCP 请求进行身份验证。 如果 MCP 客户端直接调用此终结点,则只需对 Foundry IQ 进行身份验证。

对于 Foundry IQ 身份验证,请使用以下方法之一:

注意

MCP 客户端以不同的方式配置自定义标头。 例如,Foundry 代理服务通过项目连接注入标头,而客户端(如GitHub Copilot)需要 MCP 服务器 JSON 中的标头。

使用持有者令牌进行 MCP 身份验证

MCP 身份验证的建议方法是持有者令牌,可避免将敏感密钥存储在配置文件中。 必须在 Foundry IQ 服务上为令牌所代表的标识分配搜索索引数据读取者角色。 有关详细信息,请参阅 使用标识将应用连接到 Foundry IQ。

#pragma warning disable OPENAI001

using Azure.AI.OpenAI;
using Azure.Core;
using Azure.Identity;
using OpenAI.Responses;
using System;
using System.Collections.Generic;

string openAiEndpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")!; // Example: https://<resource-name>.openai.azure.com
string mcpServerUrl = Environment.GetEnvironmentVariable("AZURE_SEARCH_MCP_ENDPOINT")!; // Example: https://<search-service-name>.search.windows.net/knowledgebases/<knowledge-base-name>/mcp?api-version=<api-version>
DefaultAzureCredential credential = new();

// Create the Azure OpenAI Responses client
AzureOpenAIClient azureClient = new(new Uri(openAiEndpoint), credential);
ResponsesClient openAIClient = azureClient.GetResponsesClient();

// Get a bearer token for Azure AI Search
string searchToken = credential.GetToken(
    new TokenRequestContext(new[] { "https://search.azure.com/.default" })
).Token;

// Configure the MCP tool for knowledge base retrieval
McpTool mcpTool = ResponseTool.CreateMcpTool(
    serverLabel: "search_kb",
    serverUri: new Uri(mcpServerUrl),
    headers: new Dictionary<string, string>
    {
        ["Authorization"] = $"Bearer {searchToken}",
    },
    allowedTools: new McpToolFilter { ToolNames = { "knowledge_base_retrieve" } },
    toolCallApprovalPolicy: new McpToolCallApprovalPolicy(
        GlobalMcpToolCallApprovalPolicy.NeverRequireApproval)
);

// Build the response request with the MCP tool attached
CreateResponseOptions options = new()
{
    Model = "MODEL_NAME",
    InputItems =
    {
        ResponseItem.CreateUserMessageItem(
            "What causes the strongest nighttime brightness patterns in this dataset?")
    },
    Tools = { mcpTool }
};

ResponseResult response = await openAIClient.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());

参考:使用 Azure OpenAI 响应 API

import os
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from openai import AzureOpenAI

openai_endpoint = os.environ["AZURE_OPENAI_ENDPOINT"] # Example: https://<resource-name>.openai.azure.com
mcp_server_url = os.environ["AZURE_SEARCH_MCP_ENDPOINT"] # Example: https://<search-service-name>.search.windows.net/knowledgebases/<knowledge-base-name>/mcp?api-version=<api-version>
credential = DefaultAzureCredential()

# Create token providers for Azure OpenAI and Azure AI Search
openai_token_provider = get_bearer_token_provider(
    credential, "https://cognitiveservices.azure.com/.default"
)
search_token_provider = get_bearer_token_provider(
    credential, "https://search.azure.com/.default"
)

# Create the Azure OpenAI client
client = AzureOpenAI(
    azure_endpoint=openai_endpoint,
    azure_ad_token_provider=openai_token_provider,
    api_version=os.environ["OPENAI_API_VERSION"], # Example: 2025-04-01-preview
)

# Create a response using the MCP tool configuration
response = client.responses.create(
    model="MODEL_NAME",
    input="What causes the strongest nighttime brightness patterns in this dataset?",
    tools=[
        {
            "type": "mcp",
            "server_label": "search_kb",
            "server_url": mcp_server_url,
            "allowed_tools": ["knowledge_base_retrieve"],
            "headers": {
                "Authorization": f"Bearer {search_token_provider()}"
            },
            "require_approval": "never",
        }
    ],
)

print(response.output_text)

参考:使用 Azure OpenAI 响应 API

// This code snippet is currently unavailable.

使用管理密钥进行 MCP 身份验证

管理员密钥授予对 Foundry IQ 服务的完整读写访问权限,因此仅在开发环境中或持有者令牌不可用时使用它。 有关详细信息,请参阅 使用 API 密钥连接到 Foundry IQ。

Tip

以下示例仅显示与持有者令牌示例不同的标头。 有关完整设置,请参阅 使用持有者令牌进行 MCP 身份验证。

#pragma warning disable OPENAI001

using OpenAI.Responses;
using System;
using System.Collections.Generic;

string mcpServerUrl = Environment.GetEnvironmentVariable("AZURE_SEARCH_MCP_ENDPOINT")!; // Example: https://<search-service-name>.search.windows.net/knowledgebases/<knowledge-base-name>/mcp?api-version=<api-version>
string searchAdminKey = Environment.GetEnvironmentVariable("AZURE_SEARCH_ADMIN_KEY")!; // Example: <search-api-key>

McpTool mcpTool = ResponseTool.CreateMcpTool(
    serverLabel: "search_kb",
    serverUri: new Uri(mcpServerUrl),
    headers: new Dictionary<string, string> { ["api-key"] = searchAdminKey },
    allowedTools: new McpToolFilter { ToolNames = { "knowledge_base_retrieve" } },
    toolCallApprovalPolicy: new McpToolCallApprovalPolicy(
        GlobalMcpToolCallApprovalPolicy.NeverRequireApproval)
);

参考:使用 Azure OpenAI 响应 API

import os

mcp_server_url = os.environ["AZURE_SEARCH_MCP_ENDPOINT"] # Example: https://<search-service-name>.search.windows.net/knowledgebases/<knowledge-base-name>/mcp?api-version=<api-version>
search_admin_key = os.environ["AZURE_SEARCH_ADMIN_KEY"] # Example: <search-api-key>

tools = [
    {
        "type": "mcp",
        "server_label": "search_kb",
        "server_url": mcp_server_url,
        "allowed_tools": ["knowledge_base_retrieve"],
        "headers": {"api-key": search_admin_key},
        "require_approval": "never",
    }
]

参考:使用 Azure OpenAI 响应 API

// This code snippet is currently unavailable.

查看 MCP 响应

当 MCP 客户端调用 knowledge_base_retrieve 时,它收到的是 MCP 工具结果,而不是 retrieve 操作的 response、activity 和 references 封装。 许多 MCP 客户端会将该工具结果显示在顶层 result 对象下,因此你应当期望的负载是 result.content[]。

{
  "result": {
    "content": [
      {
        "type": "text",
        "text": "[{\"ref_id\":\"0\",\"title\":\"Urban Structure\",\"terms\":\"Location of Phoenix, Grid of City Blocks, Phoenix Metropolitan Area at Night\",\"content\":\"<content chunk redacted>\"}]"
      }
    ]
  }
}

要点:

  • result.content[] 包含知识库返回的 MCP 工具输出。

  • result.content[].type 是 text.

  • result.content[].text以 JSON 编码字符串的形式包含检索到的、用作回答依据的数据。

  • 与检索操作不同,当前 MCP 响应不会返回单独的 activity 或 references 数组,也不会填充 resource 返回内容的条目。