共用方式為


在 Azure AI Search 建立知識庫

備註

這項功能目前處於公開預覽狀態。 此預覽版在沒有服務等級協議的情況下提供,不建議用於生產工作負載。 可能不支援特定功能,或可能已經限制功能。 如需詳細資訊,請參閱 Microsoft Azure 預覽版增補使用條款

在 Azure AI Search 中, 知識庫 是一個頂層物件,負責協調 代理檢索。 它定義要查詢哪些知識來源,以及檢索操作的預設行為。 在查詢時, 檢索方法 會針對知識庫執行已設定的檢索管線。

你可以在 Microsoft Foundry(新)入口網站的 Foundry IQ 工作負載 中建立知識庫。 你也需要在使用 Azure AI Search API 建立的任何代理型解決方案中建立知識庫。

知識庫規定:

  • 一個或多個指向可搜尋內容的知識來源。
  • 一個選用的 LLM,用於提供查詢規劃與答案生成的推理能力。
  • 一種檢索推理作業,用以判斷是否會調用LLM,並管理成本、延遲與品質。
  • 自訂屬性控制路由、來源選擇、輸出格式及物件加密。

建立知識庫後,你可以隨時更新其屬性。 如果知識庫正在使用中,更新會在下一次檢索時生效。

這很重要

2025-11-01-preview 將 2025-08-01-preview 的「knowledge agent」重新命名為「knowledge base」。這是個突破性的改變。 建議您盡快將 現有程式碼移轉 至新的 API。

先決條件

支援的模型

使用下列其中一個 Azure OpenAI 的 LLM 或等效的開放原始碼模型。 部署說明請參見 「以 Microsoft Foundry 部署 Azure OpenAI 模型」。

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

設定存取權

Azure AI 搜尋服務需要能存取 Azure OpenAI 的 LLM。 建議您使用 Microsoft Entra ID 進行驗證,並使用角色型存取進行授權。 要指派角色,您必須是 擁有者或使用者存取管理員。 如果不能用角色,改用基於金鑰的認證。

  1. 設定 Azure AI 搜尋以使用受控識別

  2. 在您的模型提供者 (例如 Foundry Models) 上,將認知服務使用者指派給搜尋服務的受控識別。 如果你是在本地測試,請把同樣的角色分配給你的使用者帳號。

  3. 本地測試時,請依照 快速入門中的步驟操作:無需金鑰連接 以登入特定訂閱和租戶。 在 DefaultAzureCredential 每個請求中使用 代替 AzureKeyCredential ,這應該會像以下範例相似:

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

這很重要

本文中的程式碼片段使用 API 金鑰。 如果您使用基於角色的驗證,請相應地更新每個請求。 在指定兩種方式的請求中,API 金鑰會優先。

檢查現有的知識庫

了解現有的知識庫對於重用或命名新物件都很有幫助。 任何 2025-08-01-preview 版本的知識代理程式都會在知識庫集合中被回傳 (列出)。

執行以下程式碼,依名稱列出現有知識庫。

// List knowledge bases by name
  using Azure.Search.Documents.Indexes;
  
  var indexClient = new SearchIndexClient(new Uri(searchEndpoint), credential);
  var knowledgeBases = indexClient.GetKnowledgeBasesAsync();
  
  Console.WriteLine("Knowledge Bases:");
  
  await foreach (var kb in knowledgeBases)
  {
      Console.WriteLine($"  - {kb.Name}");
  }

你也可以以名稱回傳單一知識庫,來檢視其 JSON 定義。

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

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

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

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

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

以下 JSON 是一個知識庫的範例。

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

建立知識庫

知識庫驅動代理檢索流程。 在應用程式代碼中,其他代理或聊天機器人會稱呼它。

知識庫將知識來源(可搜尋內容)連結到 Azure OpenAI 的大型語言模型部署。 LLM 上的屬性建立連結,而知識來源的屬性則建立預設值,以指導查詢執行與回應。

執行以下程式碼建立知識庫。

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

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

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

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

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

var knowledgeBase = new KnowledgeBase(
    name: "my-kb",
    knowledgeSources: new KnowledgeSourceReference[] 
    { 
        new KnowledgeSourceReference("hotels-sample-knowledge-source"),
        new KnowledgeSourceReference("earth-knowledge-source")
    }
)
{
    Description = "This knowledge base handles questions directed at two unrelated sample indexes.",
    RetrievalInstructions = "Use the hotels knowledge source for queries about where to stay, otherwise use the earth at night knowledge source.",
    AnswerInstructions = "Provide a two sentence concise and informative answer based on the retrieved documents.",
    OutputMode = KnowledgeRetrievalOutputMode.AnswerSynthesis,
    Models = { new KnowledgeBaseAzureOpenAIModel(azureOpenAIParameters: aoaiParams) },
    RetrievalReasoningEffort = new KnowledgeRetrievalLowReasoningEffort()
};

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

知識庫屬性

傳遞以下屬性以建立知識庫。

名稱 Description 類型 為必填項目
name 知識庫的名稱。 它必須在知識庫集合中獨一無二,並遵循 Azure AI Search 中物件 命名指引 繩子 Yes
knowledgeSources 一個或多個 支持的知識來源 Array Yes
Description 這是知識庫的描述。 LLM 會使用描述來指導查詢規劃。 繩子
RetrievalInstructions 一個提示,讓大語言模型判斷某個知識來源是否應該被納入查詢的範圍。 當你有多個知識來源時,請加入這個提示。 此欄位會影響知識來源選取範圍和查詢制定。 例如,指示可以附加資訊或優先處理知識來源。 指令會直接傳遞給 LLM,因此有可能提供會破壞查詢規劃的指令,例如導致繞過重要知識來源的指令。 繩子 Yes
AnswerInstructions 自訂指令以塑造合成答案。 預設值是 null。 欲了解更多資訊,請參閱 使用答案綜合技術產生引用支持的回應 繩子 Yes
OutputMode 有效值是 AnswerSynthesis 代表大型語言模型(LLM)所制定的答案,或 ExtractedData 代表你可以作為後續處理步驟傳遞給大型語言模型的完整搜尋結果。 繩子 Yes
Models 用於答案生成或查詢規劃的受支援的 LLM 連線。 在此預覽版中, Models 只能包含一個模型,而且模型提供者必須是 Azure OpenAI。 可從 Foundry 入口網站或命令列請求取得模型資訊。 透過使用 KnowledgeBaseAzureOpenAIModel 類別提供參數。 您可以使用角色型存取控制來取代 Azure AI 搜索與模型連線的 API 金鑰。 欲了解更多資訊,請參閱 如何用 Foundry 部署 Azure OpenAI 模型 物體
RetrievalReasoningEffort 決定與 LLM 相關的查詢處理層級。 有效值為 minimal、( low 預設值)和 medium。 欲了解更多資訊,請參閱 設定檢索推理努力 物體

查詢知識庫

設定要傳送給 LLM 的指示和訊息。

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

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

在知識庫呼叫該 retrieve 動作來驗證 LLM 連線並回傳結果。 欲了解更多關於請求與回應結構的 retrieve 資訊,請參閱 Azure AI Search 中的「利用知識庫檢索資料」。

用一個對你的知識來源有效的查詢字串替換「海洋在哪裡看起來是綠色的?」。

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

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

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

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

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

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

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

關鍵點:

對範例查詢的回應可能如下範例:

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

刪除知識庫

如果你不再需要知識庫或需要在搜尋服務中重建,請使用此請求刪除該物件。

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

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

備註

這項功能目前處於公開預覽狀態。 此預覽版在沒有服務等級協議的情況下提供,不建議用於生產工作負載。 可能不支援特定功能,或可能已經限制功能。 如需詳細資訊,請參閱 Microsoft Azure 預覽版增補使用條款

在 Azure AI Search 中, 知識庫 是一個頂層物件,負責協調 代理檢索。 它定義要查詢哪些知識來源,以及檢索操作的預設行為。 在查詢時, 檢索方法 會針對知識庫執行已設定的檢索管線。

你可以在 Microsoft Foundry(新)入口網站的 Foundry IQ 工作負載 中建立知識庫。 你也需要在使用 Azure AI Search API 建立的任何代理型解決方案中建立知識庫。

知識庫規定:

  • 一個或多個指向可搜尋內容的知識來源。
  • 一個選用的 LLM,用於提供查詢規劃與答案生成的推理能力。
  • 一種檢索推理作業,用以判斷是否會調用LLM,並管理成本、延遲與品質。
  • 自訂屬性控制路由、來源選擇、輸出格式及物件加密。

建立知識庫後,你可以隨時更新其屬性。 如果知識庫正在使用中,更新會在下一次檢索時生效。

這很重要

2025-11-01-preview 將 2025-08-01-preview 的「knowledge agent」重新命名為「knowledge base」。這是個突破性的改變。 建議您盡快將 現有程式碼移轉 至新的 API。

先決條件

支援的模型

使用下列其中一個 Azure OpenAI 的 LLM 或等效的開放原始碼模型。 部署說明請參見 「以 Microsoft Foundry 部署 Azure OpenAI 模型」。

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

設定存取權

Azure AI 搜尋服務需要能存取 Azure OpenAI 的 LLM。 建議您使用 Microsoft Entra ID 進行驗證,並使用角色型存取進行授權。 您必須是 擁有者或使用者存取管理員 才能指派角色。 如果角色驗證不可行,請改用金鑰驗證。

  1. 設定 Azure AI 搜尋以使用受控識別

  2. 在您的模型提供者 (例如 Foundry Models) 上,將認知服務使用者指派給搜尋服務的受控識別。 如果你是在本地測試,請把同樣的角色分配給你的使用者帳號。

  3. 本地測試時,請依照 快速入門中的步驟操作:無需金鑰連接 以登入特定訂閱和租戶。 在 DefaultAzureCredential 每個請求中使用 代替 AzureKeyCredential ,這應該會像以下範例相似:

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

這很重要

本文中的程式碼片段使用 API 金鑰。 如果您使用基於角色的驗證,請相應地更新每個請求。 在指定兩種方式的請求中,API 金鑰會優先。

檢查現有的知識庫

了解現有的知識庫對於重用或命名新物件都很有幫助。 任何 2025-08-01-preview 版本的知識代理程式都會在知識庫集合中被回傳 (列出)。

執行以下程式碼,依名稱列出現有知識庫。

# List knowledge bases by name
import requests
import json

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

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

你也可以以名稱回傳單一知識庫,來檢視其 JSON 定義。

# Get a knowledge base definition
import requests
import json

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

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

以下 JSON 是一個知識庫的範例回應。

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

建立知識庫

知識庫驅動代理檢索流程。 在應用程式代碼中,其他代理或聊天機器人會稱呼它。

知識庫將知識來源(可搜尋內容)連結到 Azure OpenAI 的大型語言模型部署。 LLM 上的屬性建立連結,而知識來源的屬性則建立預設值,以指導查詢執行與回應。

執行以下程式碼建立知識庫。

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

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

aoai_params = AzureOpenAIVectorizerParameters(
    resource_url = "aoai_endpoint",
    api_key="aoai_api_key",
    deployment_name = "aoai_gpt_deployment",
    model_name = "aoai_gpt_model",
)

knowledge_base = KnowledgeBase(
    name = "my-kb",
    description = "This knowledge base handles questions directed at two unrelated sample indexes.",
    retrieval_instructions = "Use the hotels knowledge source for queries about where to stay, otherwise use the earth at night knowledge source.",
    answer_instructions = "Provide a two sentence concise and informative answer based on the retrieved documents.",
    output_mode = KnowledgeRetrievalOutputMode.ANSWER_SYNTHESIS,
    knowledge_sources = [
        KnowledgeSourceReference(name = "hotels-ks"),
        KnowledgeSourceReference(name = "earth-at-night-ks"),
    ],
    models = [KnowledgeBaseAzureOpenAIModel(azure_open_ai_parameters = aoai_params)],
    encryption_key = None,
    retrieval_reasoning_effort = KnowledgeRetrievalLowReasoningEffort,
)

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

知識庫屬性

傳遞以下屬性以建立知識庫。

名稱 Description 類型 為必填項目
name 知識庫的名稱。 它必須在知識庫集合中獨一無二,並遵循 Azure AI Search 中物件 命名指引 繩子 Yes
description 這是知識庫的描述。 LLM 會使用描述來指導查詢規劃。 繩子
retrieval_instructions 一個提示,讓大語言模型判斷某個知識來源是否應該被納入查詢的範圍。 當你有多個知識來源時,請加入這個提示。 此欄位會影響知識來源選取範圍和查詢制定。 例如,指示可以附加資訊或優先處理知識來源。 直接把指令傳給 LLM。 有可能提供破壞查詢規劃的指令,例如導致繞過重要知識來源的指令。 繩子 Yes
answer_instructions 自訂指令以塑造合成答案。 預設值是 null。 欲了解更多資訊,請參閱 使用答案綜合技術產生引用支持的回應 繩子 Yes
output_mode 有效值是 answer_synthesis 代表大型語言模型(LLM)所制定的答案,或 extracted_data 代表你可以作為後續處理步驟傳遞給大型語言模型的完整搜尋結果。 繩子 Yes
knowledge_sources 一個或多個 支持的知識來源 Array Yes
models 用於答案生成或查詢規劃的受支援的 LLM 連線。 在此預覽版中, models 只能包含一個模型,而且模型提供者必須是 Azure OpenAI。 可從 Foundry 入口網站或命令列請求取得模型資訊。 您可以使用角色型存取控制來取代 Azure AI 搜索與模型連線的 API 金鑰。 欲了解更多資訊,請參閱 如何用 Foundry 部署 Azure OpenAI 模型 物體
encryption_key 一個由客戶管理的金鑰,用於加密知識庫及生成物件中的敏感資訊。 物體
retrieval_reasoning_effort 決定與 LLM 相關的查詢處理層級。 有效值為 minimal、( low 預設值)和 medium。 欲了解更多資訊,請參閱 設定檢索推理努力 物體

查詢知識庫

在知識庫呼叫該 retrieve 動作來驗證 LLM 連線並回傳結果。 欲了解更多關於請求與回應結構的 retrieve 資訊,請參閱 Azure AI Search 中的「利用知識庫檢索資料」。

用一個對你的知識來源有效的查詢字串替換「海洋在哪裡看起來是綠色的?」。

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

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

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

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

關鍵點:

  • messages 是必須的,但你也可以只用 user 提供查詢的角色來執行這個範例。

  • knowledge_source_params 指定一個或多個查詢目標。 對於每個知識來源,你可以指定輸出中要包含多少資訊。

對範例查詢的回應可能如下範例:

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

刪除知識庫

如果你不再需要知識庫或需要在搜尋服務中重建,請使用此請求刪除該物件。

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

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

備註

這項功能目前處於公開預覽狀態。 此預覽版在沒有服務等級協議的情況下提供,不建議用於生產工作負載。 可能不支援特定功能,或可能已經限制功能。 如需詳細資訊,請參閱 Microsoft Azure 預覽版增補使用條款

在 Azure AI Search 中, 知識庫 是一個頂層物件,負責協調 代理檢索。 它定義要查詢哪些知識來源,以及檢索操作的預設行為。 在查詢時, 檢索方法 會針對知識庫執行已設定的檢索管線。

你可以在 Microsoft Foundry(新)入口網站的 Foundry IQ 工作負載 中建立知識庫。 你也需要在使用 Azure AI Search API 建立的任何代理型解決方案中建立知識庫。

知識庫規定:

  • 一個或多個指向可搜尋內容的知識來源。
  • 一個選用的 LLM,用於提供查詢規劃與答案生成的推理能力。
  • 一種檢索推理作業,用以判斷是否會調用LLM,並管理成本、延遲與品質。
  • 自訂屬性控制路由、來源選擇、輸出格式及物件加密。

建立知識庫後,你可以隨時更新其屬性。 如果知識庫正在使用中,更新會在下一次檢索時生效。

這很重要

2025-11-01-preview 將 2025-08-01-preview 的「knowledge agent」重新命名為「knowledge base」。這是個突破性的改變。 建議您盡快將 現有程式碼移轉 至新的 API。

先決條件

支援的模型

使用下列其中一個 Azure OpenAI 的 LLM 或等效的開放原始碼模型。 部署說明請參見 「以 Microsoft Foundry 部署 Azure OpenAI 模型」。

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

設定存取權

Azure AI 搜尋服務需要能存取 Azure OpenAI 的 LLM。 建議您使用 Microsoft Entra ID 進行驗證,並使用角色型存取進行授權。 要指派角色,您必須是 擁有者或使用者存取管理員。 如果不能用角色,改用基於金鑰的認證。

  1. 設定 Azure AI 搜尋以使用受控識別

  2. 在您的模型提供者 (例如 Foundry Models) 上,將認知服務使用者指派給搜尋服務的受控識別。 如果你是在本地測試,請把同樣的角色分配給你的使用者帳號。

  3. 本地測試時,請依照 快速啟動的步驟操作:無鑰匙連線 以獲得特定訂閱和租戶的個人存取權杖。 在每個請求中指定您的存取權杖,其格式應如下範例:

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

這很重要

本文中的程式碼片段使用 API 金鑰。 如果您使用基於角色的驗證,請相應地更新每個請求。 在指定兩種方式的請求中,API 金鑰會優先。

檢查現有的知識庫

知識庫是一個頂層且可重複使用的物件。 了解現有的知識庫對於重用或命名新物件都很有幫助。 任何 2025-08-01-preview 版本的知識代理程式都會在知識庫集合中被回傳 (列出)。

使用 Knowledge Bases - List (REST API) 來依名稱和類型列出知識庫。

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

你也可以以名稱回傳單一知識庫,來檢視其 JSON 定義。

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

以下 JSON 是一個知識庫的範例回應。

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

建立知識庫

知識庫驅動代理檢索流程。 在應用程式代碼中,其他代理或聊天機器人會稱呼它。

知識庫將知識來源(可搜尋內容)連結到 Azure OpenAI 的大型語言模型部署。 在 LLM 上的屬性建立連線,而在知識來源集合上的屬性則設定引導查詢執行與回應的預設值。

使用 knowledge bases - 建立或更新(REST API) 來表達請求。

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

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

知識庫屬性

傳遞以下屬性以建立知識庫。

名稱 Description 類型 為必填項目
name 知識庫的名稱。 它必須在知識庫集合中獨一無二,並遵循 Azure AI Search 中物件 命名指引 繩子 Yes
description 這是知識庫的描述。 LLM 會使用描述來指導查詢規劃。 繩子
retrievalInstructions 一個提示,讓大語言模型判斷某個知識來源是否應該被納入查詢的範圍。 當你有多個知識來源時,請加入這個提示。 此欄位會影響知識來源選取範圍和查詢制定。 例如,指示可以附加資訊或優先處理知識來源。 你可以直接將指令傳給大型語言模型,這意味著有可能提供導致破壞查詢規劃的指令,例如導致繞過重要知識來源的指令。 繩子 Yes
answerInstructions 自訂指令以塑造合成答案。 預設值是 null。 欲了解更多資訊,請參閱 使用答案綜合技術產生引用支持的回應 繩子 Yes
outputMode 有效值是 answerSynthesis 代表大型語言模型(LLM)所制定的答案,或 extractedData 代表你可以作為後續處理步驟傳遞給大型語言模型的完整搜尋結果。 繩子 Yes
knowledgeSources 一個或多個 支持的知識來源 Array Yes
models 用於答案生成或查詢規劃的受支援的 LLM 連線。 在此預覽版中, models 只能包含一個模型,而且模型提供者必須是 Azure OpenAI。 可從 Foundry 入口網站或命令列請求取得模型資訊。 您可以使用角色型存取控制來取代 Azure AI 搜索與模型連線的 API 金鑰。 欲了解更多資訊,請參閱 如何用 Foundry 部署 Azure OpenAI 模型 物體
encryptionKey 一個由客戶管理的金鑰,用於加密知識庫及生成物件中的敏感資訊。 物體
retrievalReasoningEffort.kind 決定與 LLM 相關的查詢處理層級。 有效值為 minimal、( low 預設值)和 medium。 欲了解更多資訊,請參閱 設定檢索推理努力 物體

查詢知識庫

在知識庫呼叫該 retrieve 動作來驗證 LLM 連線並回傳結果。 欲了解更多關於請求與回應結構的 retrieve 資訊,請參閱 Azure AI Search 中的「利用知識庫檢索資料」。

使用 Knowledge Retrieval - Retrieve(REST API) 來表達請求。 用一個對你的知識來源有效的查詢字串替換「海洋在哪裡看起來是綠色的?」。

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

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

關鍵點:

  • messages 是必須的,但你也可以只用 user 提供查詢的角色來執行這個範例。

  • knowledgeSourceParams 指定一個或多個查詢目標。 對於每個知識來源,你可以指定輸出中要包含多少資訊。

對範例查詢的回應可能如下範例:

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

刪除知識庫

如果你不再需要知識庫或需要在搜尋服務中重建,請使用此請求刪除該物件。

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