使用 retrieve 動作或 MCP 端點查詢知識庫

註

Foundry IQ(Azure AI 搜尋服務)提供直接的索引與查詢 API,並搭配高階知識來源與知識庫 API 用於受控檢索。 使用 Azure 入口網站、REST API 或 Azure SDK 來設定這些功能,或將代理連線到 Microsoft Foundry 入口網站 中的知識庫。

重要

本文中標示為(預覽)的功能或特性目前處於公開預覽狀態,並受 Microsoft Azure 預覽版補充使用條款的約束。

如需瞭解 Foundry IQ(Azure AI 搜尋服務)特定的預覽條款,請參閱預覽功能。

在代理檢索管線中, 檢索動作 會從知識庫中呼叫平行查詢處理。 你可以直接使用 Search Service REST API 或 Azure SDK 呼叫這個擷取動作。 每個知識庫也會暴露一個模型上下文協定(MCP)端點,供相容的代理使用。

若要設定一條將 Foundry IQ(Azure AI 搜尋服務)透過 MCP 連接至 Foundry Agent Service 的管線,請參閱教學:建立端對端代理擷取解決方案。

使用支援

Azure portal Microsoft Foundry 入口網站 .NET SDK Python SDK Java SDK JavaScript SDK REST API
✔️ ✔️ ✔️ ✔️ ✔️ ✔️ ✔️

先決條件

  • 一個具備 知識庫的 Foundry IQ 服務。

  • 請求查詢知識庫的權限。 建議設定無金鑰驗證,並將 Search Index Data Reader 角色指派給您的使用者帳戶,或使用 查詢 API 金鑰。

  • 如果你透過 Azure OpenAI 回應 API 呼叫 MCP 端點,你需要:

    • 已部署的 LLM,以及 Foundry 資源上的認知服務 OpenAI 使用者角色 (或 API 金鑰)。 如果適用,你可以重用知識庫中指定的 LLM 和資源。

    • Azure.AI.OpenAI 套件:dotnet add package Azure.AI.OpenAI

  • Azure.Search.Documents 建立知識庫中列出的 和 Azure.Identity package。 請使用適用於 2026-10-01 的最新穩定套件。 預覽版 SDK 範例使用最新的預覽套件及其預設 2026-11-01-preview 合約。

  • 如果你透過 Azure OpenAI 回應 API 呼叫 MCP 端點,你需要:

    • 已部署的 LLM,以及 Foundry 資源上的認知服務 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 例子保留了較窄的契約。

  • 對於無金鑰認證,請在Authorization每個 HTTP 請求的標頭中加入 Microsoft Entra ID 令牌。

Limitations

對於搜尋索引知識來源,啟用重新排序時,檢索會使用知識來源的語意配置。 基礎索引 defaultScoringProfile 可能會影響第一階段候選人的選擇,但不應依賴任意的索引 評分設定檔 來控制最終知識庫的語意排名。 擷取回應也不會呈現 @search.rerankerBoostedScore。

呼叫取回動作

你在知識庫中指定擷取動作。 請求主體包含查詢輸入以及可選的每個來源參數。 這些參數用來設定附加的來源;省略某條目並不排除該來源。

GA 2026-10-01 REST 契約支援最小、低與中等工作量、模型支援規劃、答案合成、引用及 SSE。 舊 2026-04-01 契約只支援意圖和最小化的擷取式檢索。 僅供預覽的欄位不被 GA 合約接受。

使用 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。 規劃lowmedium時,設定支援的模型並提供訊息或語意意圖,但不可兩者兼具。

只有明確的 alwaysQuerySource: true 會在模型驅動選擇期間使來源成為必要條件。 一般最小檢索會選擇所有候選來源,不論此標記為何。 false 或遺漏不等於排除。 若所選來源在檢索或後處理失敗,failOnError 會導致整個要求失敗。

GA 請求設定 限制與行為
maxRuntimeInSeconds 10 到 600 秒。 實作備援時間為 90 秒;持久化的預設值可能會影響被遺漏的值。
頂層 maxOutputDocuments 第 1 至 200 份獨特文件,依來源限制後套用。 重複的條目不會消耗其他文件配置,因此此值並非參考陣列長度限制。
按來源計算 maxOutputDocuments 50到200。 影響候選尺寸、頁面大小及每個來源的最終剪枝。
maxOutputSizeInTokens 至少 5,000 個代幣。 控制 grounding 輸出修剪,而非保證的合成答案長度。 備援預算會依工作量、啟用的功能及設定而有所不同。
rerankerThreshold 0 到 4。 需要時依來源設定;不要假設有普遍的預設分數門檻。
includeReferences,includeReferenceSourceData 分別控制參考及其來源資料。 來源資料需要參考。 由設定支援的預設值為啟用參考資料,而停用來源資料。

每個 knowledgeSourceParams 條目都需要 knowledgeSourceName 和 來源的匹配 kind。 對於搜尋索引來源, filterAddOn 會與任何使用 AND 儲存 searchIndexParameters.baseFilter 的來源結合;它不會取代已儲存的篩選器。

對於網頁來源,請求 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_ENDPOINT 和 SEARCH_API_KEY 設為服務端點和授權的 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

建立一個請求,使用單一語意意圖、最少的努力與萃取輸出。 頂層輸出上限為三份文件;每個來源的設定為 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_ENDPOINT 和 SEARCH_API_KEY 分別設為服務端點和授權的 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、indexed OneLake 和 indexed SharePoint 知識來源,你可以將內嵌於文件中的影像連同文字一併提供給下游答案合成模型。 在匹配的條目enableImageServing上設定knowledgeSourceParams,以覆蓋知識庫定義中預設的設定。 擷取回應不包含專門欄位來顯示模型所提供的個別影像路徑或影像位元組。

影像服務僅會在 outputMode 為 ingestionPermissionOptions 時執行,且不支援已設定 answerSynthesis 的知識來源。 如需設定步驟、優先順序資料表,以及檢查影像服務統計資料的方法,請參閱在代理式擷取中呈現文件內嵌影像 (預覽版)。

關閉知識來源的重新排序(預覽)

從 2026-08-01-preview API 版本開始,在 knowledgeSourceParams 項目上設定 "resultsProcessing": "none",即可略過特定知識來源的重新排序,並保留其原始結果順序。 你也可以將 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. resultsProcessing 參與 knowledgeSourceParams 取回請求。
  2. resultsProcessing 儲存在知識來源中。
  3. rerank 會在兩者都不存在時使用。

對於 MCP 伺服器的知識來源, resultsProcessing 單一工具上的值設定優先於請求與儲存值。

Tip

resultsProcessing 會變更結果的處理方式,而非查詢哪些來源。 若必須查詢知識來源,則設alwaysQuerySource為 。true

當有效值為 none時:

  • 來自知識來源的參考資料不包含 rerankerScore,而結果會保留其在來源檢索活動中的原有順序。
  • 當任何來源跳過重新排序時,Foundry IQ 會依照知識來源宣告順序,將最終結果以輪轉順序分配到各活動。 重新排序的活動仍依分數排序。
  • 重複刪除及按來源、文件和令牌限制仍然適用,因此並非所有檢索結果都會出現在回應中。

Foundry IQ 依照下列順序驗證 rerankerThreshold:

  1. 搜尋會根據擷取要求和儲存的知識來源值來解析 resultsProcessing。
  2. 若解析值為 none 且請求包含 rerankerThreshold,則搜尋返回 400 Bad Request。
  3. 對於 MCP 伺服器工具,Search 會在驗證請求後套用工具層級 resultsProcessing 的值。

因此,MCP 工具設定不會改變請求是否通過驗證。 工具層級none值不會造成閾值錯誤,且當請求或儲存值解析為 none時,工具層級rerank值也無法防止錯誤。

要確認執行的模式是哪一種,請檢查知識來源的參考文獻是否包含 rerankerScore。 不要依賴 semanticConfigurationName,因為它可能會是 null,而不是被省略。

搜尋索引行為

對於針對搜尋索引的知識來源,隱含查詢類型為 semantic,且沒有搜尋模式。 在重新排序執行時,查詢執行會使用 semanticConfigurationName。 其他來源設定,包括 searchFields 和 sourceDataFields,兩種模式皆適用。

代理式擷取不接受 scoringProfile 或 scoringParameters 輸入。 基礎索引的 defaultScoringProfile 可能會影響第一階段候選項的選取,但它不會為知識庫檢索建立任意設定檔的最終語意排序機制。 如果你需要對索引知識來源進行新近偏差,請使用 新鮮度感知檢索(預覽) 取代索引評分設定檔。

如果索引包含向量場,你需要一個有效的向量化器定義,讓代理檢索引擎能向量化查詢輸入。 否則,向量場會被忽略。

欲了解更多資訊,請參閱 建立代理檢索索引。

串流擷取結果

從 2026-08-01-preview API 版本開始,擷取支援伺服器傳送事件(SSE)。 GA 2026-10-01 REST 合約也提供 SSE。 串流會報告活動與已完成的輸出,而非逐個令牌的回應差異。

使用 2026-10-01 REST 進行串流

使用與 GA JSON 請求相同的知識庫、已填入內容的來源資料及授權憑證。 本文未變;明確 Accept: text/event-stream 選擇加入。 不要新增 body streaming 切換器或 _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: 行、一 data: 行包含 JSON 的行,以及一行空白。 服務會傳送每個事件或心跳留言。

成功的串流會遵循以下生命週期:

Event 傳送的時間 包含的内容
retrieval.started 準備與驗證成功且串流開啟後的第一個事件。 requestId、knowledgeBaseName、outputMode,以及 reasoningEffort 會在預設值解析完成後發生。 域為 reasoningEffort,非 retrievalReasoningEffort。 預覽 auto 會回報最初的作業量,而非後續的升高。
activity.started 當查詢規劃、來源或模型活動開始時。 活動可以交錯進行。 直接承載資料,包含 id、type、startedAt及可選的 knowledgeSourceName,而非活動包裝器。 當 includeActivity 為 false時被抑制。
activity.completed 當該活動結束時。 依據 id 建立關聯。 已完成的 活動記錄 會直接顯示,無需包裝。 當 includeActivity 為 false時被抑制。
answer.completed 對於每則回應訊息,當 outputMode 是 answerSynthesis時。 messageIndex 以及完整的 message。 沒有逐個代幣的 delta 事件。
references.completed 在所有參照都已解析完成後。 事件資料是完整的 參考陣列,沒有物件包裝器。
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 成員,且其品質值為正。 在不支援 SSE 的版本中明確指定 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'

從十一月預覽版 C# 用戶端和要求設定繼續。 此變體需要在支援索引中有一個可 country 篩選的欄位,其值例如 Canada 和 美國。 使用全新請求並搭配符合你內容的篩選條件。 儲存的基礎篩選器仍會與 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 boost。 服務不會將任何已儲存的篩選條件或其他已儲存的加權套用至此要求。

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 範圍。 仍需取得操作授權。 遠端來源也會使用擷取請求的授權,但會強制執行來源權限,並可能需要特定來源的令牌與標頭。

支援 ADLS Gen2 的 ACL/RBAC 以及標準 Blob 容器的 RBAC 匯入與查詢過濾功能已在 REST API 2026-10-01中正式推出。 如需 GA 路徑,請參閱 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 ✅ 匯入的 Microsoft Purview 敏感度標籤,或使用 索引來源位置及查詢時 OneLake 授權的 OneLake 來源權限 (2026-11-01-preview)。
已建立索引的 SharePoint ✅ 已擷取並匯入的 SharePoint ACL 或 Microsoft Purview 敏感度標籤,會根據使用者身分進行比對。
遠端 SharePoint ❌ Copilot Retrieval API 直接使用使用者的憑證查詢 SharePoint。
Fabric 資料代理程式 ❌ 擷取引擎會將使用者的權杖交換為 Microsoft Fabric 範圍的權杖,並代表使用者查詢 Data Agent。
Fabric 本體論 ❌ 擷取引擎會將使用者的權杖交換為 Microsoft Fabric 範圍的權杖,並代表使用者查詢 Ontology 項目。
Work IQ ❌ 擷取引擎會將 x-ms-query-work-iq-source-authorization 中以應用程式為對象的使用者判斷提示,交換成範圍限定為 Work IQ 的權杖。

對於依賴 ingestionPermissionOptions的產生索引,省略該設定不會匯入權限元資料。 來源身份標頭無法補償缺少的元資料。 這與原生權限篩選的搜尋索引是不同的,後者的權限欄位已可存在於索引中。

查詢時授權

對於非 Work IQ 知識來源,請請求一個供 Search 使用的委派使用者存取權杖 https://search.azure.com/.default,並將其傳入 x-ms-query-source-authorization。 此代幣代表被評估內容存取權的使用者;它不需要搜尋角色指派。

在 Authorization 中的呼叫者權杖會另外授權 Search 作業。 它可以代表具有所需搜尋角色的應用程式服務主體或受管理身份。 呼叫端支援並不會建立文件權限主體支援;請參閱 查詢時的權杖角色與權限流程。

對於工作智商(Work IQ)的知識來源,此部分不適用。 使用 在查詢時強制執行權限 中所述的 Work IQ 專用使用者聲明流程。

對於具有 GA 提升的讀取權限的管理調查,請直接查詢底層搜尋索引。 2026-10-01擷取 REST API 並未宣告 x-ms-enable-elevated-read 標頭。

在 .NET SDK 中,將 token 作為 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,Large Language Model)。 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(用於引用目的)及目標索引語意配置中指定的欄位開始。 在此範例中,假設目標索引的語意配置有「標題」欄位、「術語」欄位和「內容」欄位。

  • 擷取回應不會包含 @search.rerankerBoostedScore。

  • 請求的代幣預算控制著 grounding 輸出修剪。 在 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 對於使用網頁摘要的知識庫,本節報告用於摘要網頁結果的代幣消耗情況。 它包含一個 model 欄位,該 modelName 欄位包含執行該活動的模型的公開模型名稱,而非部署名稱。
model 對於模型支持的活動記錄,本節會標示用於執行該活動的模型。 這個區塊只有在你設定 includeActivity 為 true時才會出現。
imageServing 對於已啟用 影像服務(預覽) 的知識來源,本節會顯示 imagesRetrieved、imagesSentToModel、totalImageSizeBytes,以及建立索引時是否啟用 verbalizationUsed。 分別檢查 verbalizationUsed 和 imagesSentToModel。 回應可以回報 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。 它指向的是後備索引文件,而非原始檔案或網頁文件。 本文中的早期版本分頁保留了其原始的回應形狀。

參考陣列包含以下組件:

Field 描述
type 產生參考的知識來源類型,例如 searchIndex。
id 回應中項目的參考 ID。 它不是搜尋索引中的文件鍵。 用它來提供引用。
activitySource 交互參照產生該參照之活動項目的 id,這有助於連結引用。
docKey 對於已編製索引的參照,此為後端搜尋索引中的文件索引鍵。
sourceData 用於生成回應的依據資料。 對於索引參考,欄位可以包含 id 和 語意欄位,例如 title、 terms、 content和 。 形狀依參考類型而異。
citationUrl (預覽) 由服務產生的唯讀 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。 使用此網址取得該參考的索引欄位,例如 title 和 content,這樣你就能在不打開原始原始文件的情況下,呈現出答案來源的引用預覽。 這是 citationUrl 對支持索引的認證查詢,與來源 docUrl 和 blobUrl分開。

2026-10-01 也支援引用網址,用於 searchIndex、azureBlob、indexedSql、indexedOneLake、indexedSharePoint 及 file 參照。 它們不需要答案合成。 必須啟用來源的參考資料,當無法解析後方索引或文件鍵時,可以省略 URL。 所選欄位會遵循已解析的來源選取;萬用字元或未指定選取不會增加 $select 限制。

請保留未更改的回傳 URL,包括其 API 版本及轉義。 以下範例使用了該 2026-11-01-preview 合約。

以下範例展示了經過消毒的引用網址。

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

所選欄位及其順序取決於索引來源與檢索配置。

重要

照著回應的完整網址,然後在你的應用程式中渲染回傳的 JSON 欄位。 不要建構、解析或正規化 URL。

依循引用 URL,即是對該後端索引執行 Documents-Get 作業。 它需要文件讀取授權,例如 搜尋索引資料讀取器,與 KB 定義存取分開。 原生文件權限仍然適用;未經授權或遺失的文件可能會傳回 404。 以下範例對 Foundry IQ 服務的 HTTP GET 要求進行驗證。

Azure AI 搜尋服務 SDK 的文件查詢方法需要端點、索引名稱、文件鍵、選取欄位和 API 版本作為獨立輸入。 他們不接受絕對引用網址。 這些範例使用經過認證的 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}}

參考:Documents - Get

文件查詢會以 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"
}

當你使用引用網址時,請記得以下幾點:

  • 在顯示引用之前,請先檢查是否有 citationUrl。 如果回應遺漏參考,或服務無法解析後盾索引或文件鍵,則可能不存在。

  • 對於原生文件權限篩選,請在查詢時一併提供適當使用者的 x-ms-query-source-authorization 權杖,以及已獲授權的服務憑證。

  • 處理應用程式中的查詢失敗,而非將 URL 視為永久或獨立授權的下載連結。

檢查回應中的敏感性標籤元資料(預覽)

此處也適用 Enforce permissions at query time 中所述的相同時間行為:在 2026-11-01-preview 之外設定的存取權限變更,可能需要一些時間才會顯示在 2026-11-01-preview 擷取回應中。

當你查詢一個匯入Microsoft Purview敏感度標籤的知識庫時,檢索回應會在兩個層級包含標籤元資料:

地點 Field 描述
根據參考資料 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 的欄位。

顯示和稽核建議

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 擷取。

檢視活動記錄中的模型名稱

設 includeActivity 為 true 以回傳模型支援活動記錄中的模型身份欄位。 利用這些欄位確認在檢索請求時,哪個已設定的模型負責查詢規劃、答案綜合或網頁摘要。 以下範例覆蓋了請求中所選來源的儲存結果處理。

在 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# 變體,請從 November 預覽 用戶端設定中繼續操作。 提供第二個既有的附加搜尋索引來源以排除,不同於 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
        }
    ]
}

參考資料:知識擷取 - 擷取

讓服務決定推理強度

在擷取請求中設定 retrievalReasoningEffort.kind 為 , auto 以覆蓋知識庫預設值。 欲了解更多自動推理的資訊,請參閱 設定檢索推理努力(預覽)。

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

參考資料:知識檢索 - 擷取

針對擷取動作進行疑難排解

在 2026-10-01中,區分部分擷取、來源故障與伺服器逾時。 對 SSE 而言,這些結果會出現在串流開啟後的最終事件資料中,而不是出現在串流開始時的 HTTP 狀態碼中。

狀態 Meaning
200 OK 回收成功了。 如果文件內容超過輸出預算,仍可被省略。 更多資訊請參見 空回答。
400 Bad Request 檢索請求在檢索開始前驗證失敗。
206 Partial Content Finalization 會記錄來源擷取或後處理失敗,而不採用終止失敗策略。 一般最小擷取式擷取也能在伺服器逾時後回傳累積結果。
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,但知識庫並未定義 支援的模型。
  • 對於要求時間來源排除(預覽),同一個項目會同時將 neverQuerySource 和 alwaysQuerySource 設為 true,否則所有已附加的知識來源都會遭到排除。

206 Partial Content

檢查每個包含 activity 的 error 條目。 來源檢索活動識別失敗的知識來源,模型活動識別失敗的處理階段。 回應本文仍包含成功的結果。

對於來源檢索活動錯誤,常見原因包括:

  • 查詢時輸入無效,例如表達式格式錯誤 filterAddOn 。
  • 知識來源或索引配置漂移,例如欄位被重新命名、語 意配置缺失,或無效 的向量器。
  • 相依性授權遺失或無效,或用於查詢來源的身分識別權限不足。
  • 相依性發生節流、逾時或暫時性可用性失敗。

對於模型活動錯誤,利用該活動 type 來識別失敗的處理階段。 例如,錯誤 modelWebSummarization 表示 網頁結果摘要 失敗。

若您的應用程式允許部分結果,請處理成功結果並記錄每個失敗的來源或模型階段。

對於必須被選取且必須成功的支援來源,請同時設定 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 中,每個知識庫都是獨立的 MCP 伺服器,用來暴露 knowledge_base_retrieve 工具。 任何相容 MCP 的用戶端,包括 Foundry Agent Service、GitHub Copilot、Claude,以及 Cursor,都可以調用此工具查詢知識庫。

透過使用 2026-11-01-preview,同一端點同時也會提供 自訂的知識庫檢索工具。

認證至 MCP 端點

每個知識庫在以下網址都有一個 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 回應 API 搭配 knowledge_base_retrieve MCP 工具時,您同時驗證了對 Azure OpenAI 的回應 API 呼叫以及對 Foundry IQ 的 MCP 請求。 如果您的 MCP 用戶端直接呼叫此端點,您僅向 Foundry IQ 進行驗證。

對於 Foundry IQ 驗證,請使用下列其中一種方法:

註

MCP 用戶端會以不同的方式配置自訂標頭。 例如,Foundry Agent Service 透過專案連線注入標頭,而像 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 工具結果,而不是擷取作業的 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 編碼字串的形式包含擷取的 grounding 資料。

  • 與擷取動作不同,目前的 MCP 回應不會回傳分開 activity 或 references 陣列,也不會為回傳的內容填入 resource 條目。