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

创建远程 SharePoint 知识源

注释

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

远程 SharePoint 知识源使用 Copilot 检索 API 直接从 Microsoft 365 中的 SharePoint 查询文本内容,并将结果返回到代理检索引擎以进行合并、排名和响应表述。 此知识源不使用搜索索引,只查询文本内容。

在查询时,远程 SharePoint 知识源代表用户标识调用 Copilot 检索 API,因此知识源定义中不需要连接字符串。 用户有权访问的所有内容都属于知识检索的范围。 若要限制网站或限制搜索,请设置 筛选器表达式。 Azure 租户和 Microsoft 365 租户必须使用相同的 Microsoft Entra ID 租户,并且调用方的身份必须被这两个租户识别。

  • 可以使用筛选器按 URL、日期范围、文件类型和其他元数据来限定搜索范围。

  • SharePoint 权限和 Purview 标签在内容请求中受到遵守。

  • 使用情况通过 Microsoft 365 和 Copilot 许可证计费。

与任何其他知识源一样,在 知识库 中指定远程 SharePoint 知识源,并在代理或聊天机器人在查询时调用 检索操作 时将结果用作基础数据。

先决条件

  • 提供代理检索功能的任何区域内的 Azure AI 搜索。 必须 启用语义排名器

  • Microsoft 365 租户中的 SharePoint 位于与 Azure 相同的 Microsoft Entra ID 租户下。

  • 用于本地开发的个人访问令牌或客户端应用程序中的用户标识。

  • 适用于 .NET SDK 的 Azure.Search.Documents 客户端库 的最新预览版本。

  • 在 Azure AI 搜索中创建和使用对象的权限。 我们建议 使用基于角色的访问,但如果角色分配不可行,则可以使用 API 密钥

对于本地开发,代理检索引擎使用访问令牌代表你调用 SharePoint。 有关对请求使用个人访问令牌的详细信息,请参阅 “连接到 Azure AI 搜索”。

局限性

Copilot 检索 API 中的以下限制适用于远程 SharePoint 知识源。

  • 不支持 Copilot 连接器或 OneDrive 内容。 仅从 SharePoint 网站检索内容。

  • 每个用户每小时 200 个请求的限制。

  • 查询字符限制为 1,500 个字符。

  • 混合查询仅支持以下文件扩展名:.doc、.docx、.pptx、.pdf、.aspx 和 .one。

  • 不支持多模式检索(非文本内容,包括表、图像和图表)。

  • 查询中最多 25 个结果。

  • 结果由 Copilot 检索 API 无序返回。

  • 无效的关键字查询语言(KQL)筛选器表达式会被忽略,查询将在没有该筛选器的情况下继续执行。

检查现有知识来源

知识来源是顶级可重用对象。 了解现有知识源有助于重复使用或命名新对象。

运行以下代码,按名称和类型列出知识源。

// List knowledge sources by name and type
using Azure.Search.Documents.Indexes;

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

Console.WriteLine("Knowledge Sources:");

await foreach (var ks in knowledgeSources)
{
    Console.WriteLine($"  Name: {ks.Name}, Type: {ks.GetType().Name}");
}

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

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

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

// Specify the knowledge source name to retrieve
string ksNameToGet = "earth-knowledge-source";

// Get its definition
var knowledgeSourceResponse = await indexClient.GetKnowledgeSourceAsync(ksNameToGet);
var ks = knowledgeSourceResponse.Value;

// Serialize to JSON for display
var jsonOptions = new JsonSerializerOptions 
{ 
    WriteIndented = true,
    DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.Never
};
Console.WriteLine(JsonSerializer.Serialize(ks, ks.GetType(), jsonOptions));

以下 JSON 是远程 SharePoint 知识源的示例响应。

{
  "name": "my-sharepoint-ks",
  "kind": "remoteSharePoint",
  "description": "A sample remote SharePoint knowledge source",
  "encryptionKey": null,
  "remoteSharePointParameters": {
    "filterExpression": "filetype:docx",
    "containerTypeId": null,
    "resourceMetadata": [
      "Author",
      "Title"
    ]
  }
}

创建知识来源

运行以下代码以创建远程 SharePoint 知识源。

API 密钥 用于与 Azure AI 搜索和 Azure OpenAI 的客户端连接。 Azure AI 搜索使用你的访问令牌代表你在 Microsoft 365 中连接到 SharePoint。 只能检索你有权访问的内容。 有关获取个人访问令牌和其他值的详细信息,请参阅 “连接到 Azure AI 搜索”。

注释

如果 为每个资源设置了角色分配,还可以使用个人访问令牌来访问 Azure AI 搜索和 Azure OpenAI。 使用 API 密钥可以省略此示例中的此步骤。

// Create a remote SharePoint knowledge source
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), credential);

var knowledgeSource = new RemoteSharePointKnowledgeSource(name: "my-remote-sharepoint-ks")
{
    Description = "This knowledge source queries .docx files in a trusted Microsoft 365 tenant.",
    RemoteSharePointParameters = new RemoteSharePointKnowledgeSourceParameters()
    {
        FilterExpression = "filetype:docx",
        ResourceMetadata = { "Author", "Title" }
    }
};

await indexClient.CreateOrUpdateKnowledgeSourceAsync(knowledgeSource);
Console.WriteLine($"Knowledge source '{knowledgeSource.Name}' created or updated successfully.");

特定于源的属性

可以传递以下属性来创建远程 SharePoint 知识源。

Name Description 类型 可编辑 必选
name 知识源的名称,该名称在知识源集合中必须是唯一的,并遵循 Azure AI 搜索中对象的 命名准则 String 是的
description 知识源的说明。 String 是的
encryptionKey 客户 管理的密钥 ,用于加密知识源中的敏感信息。 物体 是的
remoteSharePointParameters 特定于远程 SharePoint 知识源的参数: filterExpressionresourceMetadatacontainerTypeId 物体
filterExpression 用 SharePoint KQL 编写的表达式,用于指定网站和内容的路径。 String 是的
resourceMetadata 标准元数据字段的逗号分隔列表:作者、文件名、创建日期、内容类型和文件类型。 Array 是的
containerTypeId 用于 SharePoint Embedded 连接的容器 ID。 如果未指定,则使用 SharePoint Online。 String 是的

筛选器表达式示例

并非所有 SharePoint 属性在 filterExpression 中都受支持。 有关支持的属性列表,请参阅 API 参考。 下面是有关可在筛选器中使用的可查询属性的一些详细信息: 可查询属性

在语法参考中了解有关 KQL 筛选器 的详细信息。

Example 筛选器表达式
按 ID 筛选特定站点 "filterExpression": "SiteID:\"00aa00aa-bb11-cc22-dd33-44ee44ee44ee\""
按 ID 筛选到多个站点 "filterExpression": "SiteID:\"00aa00aa-bb11-cc22-dd33-44ee44ee44ee\" OR SiteID:\"11bb11bb-cc22-dd33-ee44-55ff55ff55ff\""
筛选特定路径下的文件 "filterExpression": "Path:\"https://my-demo.sharepoint.com/sites/mysite/Shared Documents/en/mydocs\""
筛选到特定日期范围 "filterExpression": "LastModifiedTime >= 2024-07-22 AND LastModifiedTime <= 2025-01-08"
筛选特定类型的文件 "filterExpression": "FileExtension:\"docx\" OR FileExtension:\"pdf\" OR FileExtension:\"pptx\""
筛选具有特定信息保护标签的文件 "filterExpression": "InformationProtectionLabelId:\"f0ddcc93-d3c0-4993-b5cc-76b0a283e252\""

分配给知识库

如果对知识源感到满意,请继续执行下一步:在 知识库中指定知识库中的知识源。

配置知识库后,使用 检索作 查询知识源。

查询知识库

知识库上的检索操作提供授权访问 Microsoft 365 中内容的用户身份信息。

Azure AI 搜索使用访问令牌代表用户标识调用 Copilot 检索 API。 访问令牌以 HTTP 标头的形式 xMsQuerySourceAuthorization 在检索终结点中提供。

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

// Get access token
var credential = new DefaultAzureCredential();
var tokenRequestContext = new Azure.Core.TokenRequestContext(new[] { "https://search.azure.com/.default" });
var accessToken = await credential.GetTokenAsync(tokenRequestContext);
string token = accessToken.Token;

// Create knowledge base retrieval client
var baseClient = new KnowledgeBaseRetrievalClient(
    endpoint: new Uri(searchEndpoint),
    knowledgeBaseName: knowledgeBaseName,
    credential: new AzureKeyCredential()
);

var spMessages = new List<Dictionary<string, string>>
{
    new Dictionary<string, string>
    {
        { "role", "user" },
        { "content", @"contoso product planning" }
    }
};

// Create retrieval request
var retrievalRequest = new KnowledgeBaseRetrievalRequest();
foreach (Dictionary<string, string> message in spMessages) {
    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, xMsQuerySourceAuthorization: token);

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

响应可能如下所示:

Contoso's product planning for the NextGen Camera includes a 2019 launch with a core package design and minor modifications for three product versions, featuring Wi-Fi enabled technology and a new mobile app for photo organization and sharing, aiming for 100,000 users within six months [ref_id:0][ref_id:1]. Research and forecasting are central to their planning, with phase two research focusing on feedback from a diverse user group to shape deliverables and milestones [ref_id:0][ref_id:1].

如果要在查询时应用约束,检索请求也会采用 KQL 筛选器filterExpressionAddOn)。 如果在知识源和知识库检索操作上同时指定 filterExpressionAddOn ,筛选器将通过 AND 操作结合在一起。

询问有关内容本身的查询比有关文件所在位置或上次更新文件时的问题更有效。 例如,如果询问“Ignite 2024 的主旨文档在哪里”,你可能会获得“找不到查询的相关内容”,因为内容本身不会透露其位置。 元数据过滤器是解决文件位置或日期相关查询的更好方案。

更好的问题是,“Ignite 2024 的主旨文档是什么”。 响应包括合成的答案、查询活动和令牌计数,以及 URL 和其他元数据。

{
    "resourceMetadata": {
        "Author": "Nuwan Amarathunga;Nurul Izzati",
        "Title": "Ignite 2024 Keynote Address"
    }
},
"rerankerScore": 2.489522,
"webUrl": "https://contoso-my.sharepoint.com/keynotes/nuamarth_contoso_com/Documents/Keynote-Ignite-2024.docx",
"searchSensitivityLabelInfo": {
        "displayName": "Confidential\\Contoso Extended",
        "sensitivityLabelId": "aaaaaaaa-0b0b-1c1c-2d2d-333333333333",
        "tooltip": "Data is classified and protected. Contoso Full Time Employees (FTE) and non-employees can edit, reply, forward and print. Recipient can unprotect content with the right justification.",
        "priority": 5,
        "color": "#FF8C00",
        "isEncrypted": true
    }

删除知识来源

在删除知识库之前,必须删除引用它的任何知识库或更新知识库定义以删除引用。 对于生成索引和索引器管道的数据源,也会删除所有生成的对象。 但是,如果使用现有索引创建知识源,则不会删除索引。

如果尝试删除正在使用的知识源,该作将失败并返回受影响的知识库列表。

要删除知识源,请执行以下步骤:

  1. 获取搜索服务上所有知识库的列表。

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

    示例响应可能如下所示:

     Knowledge Bases:
       - earth-knowledge-base
       - hotels-sample-knowledge-base
       - my-demo-knowledge-base
    
  2. 获取单个知识库定义以检查知识源引用。

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

    示例响应可能如下所示:

     {
       "Name": "earth-knowledge-base",
       "KnowledgeSources": [
         {
           "Name": "earth-knowledge-source"
         }
       ],
       "Models": [
         {}
       ],
       "RetrievalReasoningEffort": {},
       "OutputMode": {},
       "ETag": "\u00220x8DE278629D782B3\u0022",
       "EncryptionKey": null,
       "Description": null,
       "RetrievalInstructions": null,
       "AnswerInstructions": null
     }
    
  3. 删除知识库或 更新知识库 以删除知识库(如果有多个源)。 此示例显示删除。

    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.");
    
  4. 删除知识来源。

    await indexClient.DeleteKnowledgeSourceAsync(knowledgeSourceName);
    System.Console.WriteLine($"Knowledge source '{knowledgeSourceName}' deleted successfully.");
    

注释

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

远程 SharePoint 知识源使用 Copilot 检索 API 直接从 Microsoft 365 中的 SharePoint 查询文本内容,并将结果返回到代理检索引擎以进行合并、排名和响应表述。 此知识源不使用搜索索引,只查询文本内容。

在查询时,远程 SharePoint 知识源代表用户标识调用 Copilot 检索 API,因此知识源定义中不需要连接字符串。 用户有权访问的所有内容都属于知识检索的范围。 若要限制网站或限制搜索,请设置 筛选器表达式。 Azure 租户和 Microsoft 365 租户必须使用相同的 Microsoft Entra ID 租户,并且调用方的身份必须被这两个租户识别。

  • 可以使用筛选器按 URL、日期范围、文件类型和其他元数据来限定搜索范围。

  • SharePoint 权限和 Purview 标签在内容请求中受到遵守。

  • 使用情况通过 Microsoft 365 和 Copilot 许可证计费。

与任何其他知识源一样,在 知识库 中指定远程 SharePoint 知识源,并在代理或聊天机器人在查询时调用 检索操作 时将结果用作基础数据。

先决条件

  • 提供代理检索功能的任何区域内的 Azure AI 搜索。 必须 启用语义排名器

  • Microsoft 365 租户中的 SharePoint 位于与 Azure 相同的 Microsoft Entra ID 租户下。

  • 用于本地开发的个人访问令牌或客户端应用程序中的用户标识。

  • 适用于 Python 的 azure-search-documents 客户端库 的最新预览版。

  • 在 Azure AI 搜索中创建和使用对象的权限。 我们建议 使用基于角色的访问,但如果角色分配不可行,则可以使用 API 密钥

对于本地开发,代理检索引擎使用访问令牌代表你调用 SharePoint。 有关对请求使用个人访问令牌的详细信息,请参阅 “连接到 Azure AI 搜索”。

局限性

Copilot 检索 API 中的以下限制适用于远程 SharePoint 知识源。

  • 不支持 Copilot 连接器或 OneDrive 内容。 仅从 SharePoint 网站检索内容。

  • 每个用户每小时 200 个请求的限制。

  • 查询字符限制为 1,500 个字符。

  • 混合查询仅支持以下文件扩展名:.doc、.docx、.pptx、.pdf、.aspx 和 .one。

  • 不支持多模式检索(非文本内容,包括表、图像和图表)。

  • 查询中最多 25 个结果。

  • 结果由 Copilot 检索 API 无序返回。

  • 无效的关键字查询语言(KQL)筛选器表达式会被忽略,查询将在没有该筛选器的情况下继续执行。

检查现有知识来源

知识来源是顶级可重用对象。 了解现有知识源有助于重复使用或命名新对象。

运行以下代码,按名称和类型列出知识源。

# List knowledge sources by name and type
import requests
import json

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

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

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

# Get a knowledge source definition
import requests
import json

endpoint = "{search_url}/knowledgesources/{knowledge_source_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 是远程 SharePoint 知识源的示例响应。

{
  "name": "my-sharepoint-ks",
  "kind": "remoteSharePoint",
  "description": "A sample remote SharePoint knowledge source",
  "encryptionKey": null,
  "remoteSharePointParameters": {
    "filterExpression": "filetype:docx",
    "containerTypeId": null,
    "resourceMetadata": [
      "Author",
      "Title"
    ]
  }
}

创建知识来源

运行以下代码以创建远程 SharePoint 知识源。

API 密钥 用于与 Azure AI 搜索和 Azure OpenAI 的客户端连接。 Azure AI 搜索使用你的访问令牌代表你在 Microsoft 365 中连接到 SharePoint。 只能检索你有权访问的内容。 有关获取个人访问令牌和其他值的详细信息,请参阅 “连接到 Azure AI 搜索”。

注释

如果 为每个资源设置了角色分配,还可以使用个人访问令牌来访问 Azure AI 搜索和 Azure OpenAI。 使用 API 密钥可以省略此示例中的此步骤。

# Create a remote SharePoint knowledge source
from azure.core.credentials import AzureKeyCredential
from azure.search.documents.indexes import SearchIndexClient
from azure.search.documents.indexes.models import RemoteSharePointKnowledgeSource, RemoteSharePointKnowledgeSourceParameters

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

knowledge_source = RemoteSharePointKnowledgeSource(
    name = "my-remote-sharepoint-ks",
    description= "This knowledge source queries .docx files in a trusted Microsoft 365 tenant.",
    encryption_key = None,
    remote_share_point_parameters = RemoteSharePointKnowledgeSourceParameters(
        filter_expression = "filetype:docx",
        resource_metadata = ["Author", "Title"],
        container_type_id = None
    )
)

index_client.create_or_update_knowledge_source(knowledge_source)
print(f"Knowledge source '{knowledge_source.name}' created or updated successfully.")

特定于源的属性

可以传递以下属性来创建远程 SharePoint 知识源。

Name Description 类型 可编辑 必选
name 知识源的名称,该名称在知识源集合中必须是唯一的,并遵循 Azure AI 搜索中对象的 命名准则 String 是的
description 知识源的说明。 String 是的
encryption_key 客户 管理的密钥 ,用于加密知识源中的敏感信息。 物体 是的
remote_share_point_parameters 特定于远程 SharePoint 知识源的参数: filter_expressionresource_metadatacontainer_type_id 物体
filter_expression 用 SharePoint KQL 编写的表达式,用于指定网站和内容的路径。 String 是的
resource_metadata 标准元数据字段的逗号分隔列表:作者、文件名、创建日期、内容类型和文件类型。 Array 是的
container_type_id 用于 SharePoint Embedded 连接的容器 ID。 如果未指定,则使用 SharePoint Online。 String 是的

筛选器表达式示例

并非所有 SharePoint 属性在 filterExpression 中都受支持。 有关支持的属性列表,请参阅 API 参考。 下面是有关可在筛选器中使用的可查询属性的一些详细信息: 可查询属性

在语法参考中了解有关 KQL 筛选器 的详细信息。

Example 筛选器表达式
按 ID 筛选特定站点 "filterExpression": "SiteID:\"00aa00aa-bb11-cc22-dd33-44ee44ee44ee\""
按 ID 筛选到多个站点 "filterExpression": "SiteID:\"00aa00aa-bb11-cc22-dd33-44ee44ee44ee\" OR SiteID:\"11bb11bb-cc22-dd33-ee44-55ff55ff55ff\""
筛选特定路径下的文件 "filterExpression": "Path:\"https://my-demo.sharepoint.com/sites/mysite/Shared Documents/en/mydocs\""
筛选到特定日期范围 "filterExpression": "LastModifiedTime >= 2024-07-22 AND LastModifiedTime <= 2025-01-08"
筛选特定类型的文件 "filterExpression": "FileExtension:\"docx\" OR FileExtension:\"pdf\" OR FileExtension:\"pptx\""
筛选具有特定信息保护标签的文件 "filterExpression": "InformationProtectionLabelId:\"f0ddcc93-d3c0-4993-b5cc-76b0a283e252\""

分配给知识库

如果对知识源感到满意,请继续执行下一步:在 知识库中指定知识库中的知识源。

配置知识库后,使用 检索作 查询知识源。

查询知识库

知识库上的检索操作提供授权访问 Microsoft 365 中内容的用户身份信息。

Azure AI 搜索使用访问令牌代表用户标识调用 Copilot 检索 API。 访问令牌以 HTTP 标头的形式 x-ms-query-source-authorization 在检索终结点中提供。

from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from azure.core.credentials import AzureKeyCredential
from azure.search.documents.knowledgebases import KnowledgeBaseRetrievalClient
from azure.search.documents.knowledgebases.models import KnowledgeBaseMessage, KnowledgeBaseMessageTextContent, KnowledgeBaseRetrievalRequest, RemoteSharePointKnowledgeSourceParams

# Get access token
identity_token_provider = get_bearer_token_provider(DefaultAzureCredential(), "https://search.azure.com/.default")
token = identity_token_provider()

# Create knowledge base retrieval client
kb_client = KnowledgeBaseRetrievalClient(endpoint = "search_url", knowledge_base_name = "knowledge_base_name", credential = AzureKeyCredential("api_key"))

# Create retrieval request
request = KnowledgeBaseRetrievalRequest(
    include_activity = True,
    messages = [
        KnowledgeBaseMessage(role = "user", content = [KnowledgeBaseMessageTextContent(text = "What was covered in the keynote doc for Ignite 2024?")])
    ],
    knowledge_source_params = [
        RemoteSharePointKnowledgeSourceParams(
            knowledge_source_name = "my-remote-sharepoint-ks",
            filter_expression_add_on = "ModifiedBy:\"Adele Vance\"",
            include_references = True,
            include_reference_source_data = True
        )
    ]
)

# Pass access token to retrieve from knowledge base
result = kb_client.retrieve(retrieval_request = request, x_ms_query_source_authorization = token)
print(result.response[0].content[0].text)

如果要在查询时应用约束,检索请求也会采用 KQL 筛选器filter_expression_add_on)。 如果在知识源和知识库检索操作上同时指定 filter_expression_add_on ,筛选器将通过 AND 操作结合在一起。

询问有关内容本身的查询比有关文件所在位置或上次更新文件时的问题更有效。 例如,如果询问“Ignite 2024 的主旨文档在哪里”,你可能会获得“找不到查询的相关内容”,因为内容本身不会透露其位置。 元数据过滤器是解决文件位置或日期相关查询的更好方案。

更好的问题是,“Ignite 2024 的主旨文档是什么”。 响应包括合成的答案、查询活动和令牌计数,以及 URL 和其他元数据。

{
    "resourceMetadata": {
        "Author": "Nuwan Amarathunga;Nurul Izzati",
        "Title": "Ignite 2024 Keynote Address"
    }
},
"rerankerScore": 2.489522,
"webUrl": "https://contoso-my.sharepoint.com/keynotes/nuamarth_contoso_com/Documents/Keynote-Ignite-2024.docx",
"searchSensitivityLabelInfo": {
        "displayName": "Confidential\\Contoso Extended",
        "sensitivityLabelId": "aaaaaaaa-0b0b-1c1c-2d2d-333333333333",
        "tooltip": "Data is classified and protected. Contoso Full Time Employees (FTE) and non-employees can edit, reply, forward and print. Recipient can unprotect content with the right justification.",
        "priority": 5,
        "color": "#FF8C00",
        "isEncrypted": true
    }

删除知识来源

在删除知识库之前,必须删除引用它的任何知识库或更新知识库定义以删除引用。 对于生成索引和索引器管道的数据源,也会删除所有生成的对象。 但是,如果使用现有索引创建知识源,则不会删除索引。

如果尝试删除正在使用的知识源,该作将失败并返回受影响的知识库列表。

要删除知识源,请执行以下步骤:

  1. 获取搜索服务上所有知识库的列表。

    # Get knowledge bases
    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))
    

    示例响应可能如下所示:

     {
         "@odata.context": "https://my-search-service.search.windows.net/$metadata#knowledgebases(name)",
         "value": [
         {
             "name": "my-kb"
         },
         {
             "name": "my-kb-2"
         }
         ]
     }
    
  2. 获取单个知识库定义以检查知识源引用。

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

    示例响应可能如下所示:

     {
       "name": "my-kb",
       "description": null,
       "retrievalInstructions": null,
       "answerInstructions": null,
       "outputMode": null,
       "knowledgeSources": [
         {
           "name": "my-blob-ks",
         }
       ],
       "models": [],
       "encryptionKey": null,
       "retrievalReasoningEffort": {
         "kind": "low"
       }
     }
    
  3. 删除知识库或 更新知识库 以删除知识库(如果有多个源)。 此示例显示删除。

    # 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.")
    
  4. 删除知识来源。

    # Delete a knowledge source
    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_source("knowledge_source_name")
    print(f"Knowledge source deleted successfully.")
    

注释

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

远程 SharePoint 知识源使用 Copilot 检索 API 直接从 Microsoft 365 中的 SharePoint 查询文本内容,并将结果返回到代理检索引擎以进行合并、排名和响应表述。 此知识源不使用搜索索引,只查询文本内容。

在查询时,远程 SharePoint 知识源代表用户标识调用 Copilot 检索 API,因此知识源定义中不需要连接字符串。 用户有权访问的所有内容都属于知识检索的范围。 若要限制网站或限制搜索,请设置 筛选器表达式。 Azure 租户和 Microsoft 365 租户必须使用相同的 Microsoft Entra ID 租户,并且调用方的身份必须被这两个租户识别。

  • 可以使用筛选器按 URL、日期范围、文件类型和其他元数据来限定搜索范围。

  • SharePoint 权限和 Purview 标签在内容请求中受到遵守。

  • 使用情况通过 Microsoft 365 和 Copilot 许可证计费。

与任何其他知识源一样,在 知识库 中指定远程 SharePoint 知识源,并在代理或聊天机器人在查询时调用 检索操作 时将结果用作基础数据。

先决条件

  • 提供代理检索功能的任何区域内的 Azure AI 搜索。 必须 启用语义排名器

  • Microsoft 365 租户中的 SharePoint 位于与 Azure 相同的 Microsoft Entra ID 租户下。

  • 用于本地开发的个人访问令牌或客户端应用程序中的用户标识。

  • 搜索服务 REST API 的 2025-11-01 预览版

  • 在 Azure AI 搜索中创建和使用对象的权限。 我们建议 使用基于角色的访问,但如果角色分配不可行,则可以使用 API 密钥

对于本地开发,代理检索引擎使用访问令牌代表你调用 SharePoint。 有关对请求使用个人访问令牌的详细信息,请参阅 “连接到 Azure AI 搜索”。

局限性

Copilot 检索 API 中的以下限制适用于远程 SharePoint 知识源。

  • 不支持 Copilot 连接器或 OneDrive 内容。 仅从 SharePoint 网站检索内容。

  • 每个用户每小时 200 个请求的限制。

  • 查询字符限制为 1,500 个字符。

  • 混合查询仅支持以下文件扩展名:.doc、.docx、.pptx、.pdf、.aspx 和 .one。

  • 不支持多模式检索(非文本内容,包括表、图像和图表)。

  • 查询中最多 25 个结果。

  • 结果由 Copilot 检索 API 无序返回。

  • 无效的关键字查询语言(KQL)筛选器表达式会被忽略,查询将在没有该筛选器的情况下继续执行。

检查现有知识来源

知识来源是顶级可重用对象。 了解现有知识源有助于重复使用或命名新对象。

使用 知识源 - 获取(REST API) 按名称和类型列出知识源。

### List knowledge sources by name and type
GET {{search-url}}/knowledgesources?api-version=2025-11-01-preview&$select=name,kind
api-key: {{api-key}}

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

### Get a knowledge source definition
GET {{search-url}}/knowledgesources/{{knowledge-source-name}}?api-version=2025-11-01-preview
api-key: {{api-key}}

以下 JSON 是远程 SharePoint 知识源的示例响应。

{
  "name": "my-sharepoint-ks",
  "kind": "remoteSharePoint",
  "description": "A sample remote SharePoint knowledge source",
  "encryptionKey": null,
  "remoteSharePointParameters": {
    "filterExpression": "filetype:docx",
    "containerTypeId": null,
    "resourceMetadata": [
      "Author",
      "Title"
    ]
  }
}

创建知识来源

使用 知识源 - 创建或更新 (REST API) 创建远程 SharePoint 知识源。

API 密钥 用于与 Azure AI 搜索和 Azure OpenAI 的客户端连接。 Azure AI 搜索使用你的访问令牌代表你在 Microsoft 365 中连接到 SharePoint。 只能检索你有权访问的内容。 有关获取个人访问令牌和其他值的详细信息,请参阅 “连接到 Azure AI 搜索”。

注释

如果 为每个资源设置了角色分配,还可以使用个人访问令牌来访问 Azure AI 搜索和 Azure OpenAI。 使用 API 密钥可以省略此示例中的此步骤。

POST {{search-url}}/knowledgesources/my-remote-sharepoint-ks?api-version=2025-11-01-preview
api-key: {{api-key}}
Content-Type: application/json

{
    "name": "my-remote-sharepoint-ks",
    "kind": "remoteSharePoint",
    "description": "This knowledge source queries .docx files in a trusted Microsoft 365 tenant.",
    "encryptionKey": null,
    "remoteSharePointParameters": {
        "filterExpression": "filetype:docx",
        "resourceMetadata": [ "Author", "Title" ],
        "containerTypeId": null
    }
}

特定于源的属性

可以传递以下属性来创建远程 SharePoint 知识源。

Name Description 类型 可编辑 必选
name 知识源的名称,该名称在知识源集合中必须是唯一的,并遵循 Azure AI 搜索中对象的 命名准则 String 是的
kind 知识源的类型,其为remoteSharePoint在本例中。 String 是的
description 知识源的说明。 String 是的
encryptionKey 客户 管理的密钥 ,用于加密知识源中的敏感信息。 物体 是的
remoteSharePointParameters 特定于远程 SharePoint 知识源的参数: filterExpressionresourceMetadatacontainerTypeId 物体
filterExpression 用 SharePoint KQL 编写的表达式,用于指定网站和内容的路径。 String 是的
resourceMetadata 标准元数据字段的逗号分隔列表:作者、文件名、创建日期、内容类型和文件类型。 Array 是的
containerTypeId 用于 SharePoint Embedded 连接的容器 ID。 如果未指定,则使用 SharePoint Online。 String 是的

筛选器表达式示例

并非所有 SharePoint 属性在 filterExpression 中都受支持。 有关支持的属性列表,请参阅 API 参考。 下面是有关可在筛选器中使用的可查询属性的一些详细信息: 可查询属性

在语法参考中了解有关 KQL 筛选器 的详细信息。

Example 筛选器表达式
按 ID 筛选特定站点 "filterExpression": "SiteID:\"00aa00aa-bb11-cc22-dd33-44ee44ee44ee\""
按 ID 筛选到多个站点 "filterExpression": "SiteID:\"00aa00aa-bb11-cc22-dd33-44ee44ee44ee\" OR SiteID:\"11bb11bb-cc22-dd33-ee44-55ff55ff55ff\""
筛选特定路径下的文件 "filterExpression": "Path:\"https://my-demo.sharepoint.com/sites/mysite/Shared Documents/en/mydocs\""
筛选到特定日期范围 "filterExpression": "LastModifiedTime >= 2024-07-22 AND LastModifiedTime <= 2025-01-08"
筛选特定类型的文件 "filterExpression": "FileExtension:\"docx\" OR FileExtension:\"pdf\" OR FileExtension:\"pptx\""
筛选具有特定信息保护标签的文件 "filterExpression": "InformationProtectionLabelId:\"f0ddcc93-d3c0-4993-b5cc-76b0a283e252\""

分配给知识库

如果对知识源感到满意,请继续执行下一步:在 知识库中指定知识库中的知识源。

配置知识库后,使用 检索作 查询知识源。

查询知识库

知识库上的检索操作提供授权访问 Microsoft 365 中内容的用户身份信息。

Azure AI 搜索使用访问令牌代表用户标识调用 Copilot 检索 API。 访问令牌以 HTTP 标头的形式 x-ms-query-source-authorization 在检索终结点中提供。

请确保为具有搜索服务的租户 生成访问令牌

POST {{search-url}}/knowledgebases/remote-sp-kb/retrieve?api-version={{api-version}}
api-key: {{api-key}}
Content-Type: application/json
x-ms-query-source-authorization: {{access-token}}

{
    "messages": [
        {
            "role": "user",
            "content": [
                { "type": "text", "text": "What was covered in the keynote doc for Ignite 2024?" }
            ]
        }
    ],
    "includeActivity": true,
    "knowledgeSourceParams": [
        {
            "filterExpressionAddOn": "ModifiedBy:\"Adele Vance\"",
            "knowledgeSourceName": "my-remote-sharepoint-ks",
            "kind": "remoteSharePoint",
            "includeReferences": true,
            "includeReferenceSourceData": true
        }
    ]
}

如果要在查询时应用约束,检索请求也会采用 KQL 筛选器filterExpressionAddOn)。 如果在知识源和知识库检索操作上同时指定 filterExpressionAddOn ,筛选器将通过 AND 操作结合在一起。

询问有关内容本身的查询比有关文件所在位置或上次更新文件时的问题更有效。 例如,如果询问“Ignite 2024 的主旨文档在哪里”,你可能会获得“找不到查询的相关内容”,因为内容本身不会透露其位置。 元数据过滤器是解决文件位置或日期相关查询的更好方案。

更好的问题是,“Ignite 2024 的主旨文档是什么”。 响应包括合成的答案、查询活动和令牌计数,以及 URL 和其他元数据。

{
    "resourceMetadata": {
        "Author": "Nuwan Amarathunga;Nurul Izzati",
        "Title": "Ignite 2024 Keynote Address"
    }
},
"rerankerScore": 2.489522,
"webUrl": "https://contoso-my.sharepoint.com/keynotes/nuamarth_contoso_com/Documents/Keynote-Ignite-2024.docx",
"searchSensitivityLabelInfo": {
        "displayName": "Confidential\\Contoso Extended",
        "sensitivityLabelId": "aaaaaaaa-0b0b-1c1c-2d2d-333333333333",
        "tooltip": "Data is classified and protected. Contoso Full Time Employees (FTE) and non-employees can edit, reply, forward and print. Recipient can unprotect content with the right justification.",
        "priority": 5,
        "color": "#FF8C00",
        "isEncrypted": true
    }

删除知识来源

在删除知识库之前,必须删除引用它的任何知识库或更新知识库定义以删除引用。 对于生成索引和索引器管道的数据源,也会删除所有生成的对象。 但是,如果使用现有索引创建知识源,则不会删除索引。

如果尝试删除正在使用的知识源,该作将失败并返回受影响的知识库列表。

要删除知识源,请执行以下步骤:

  1. 获取搜索服务上所有知识库的列表。

    ### Get knowledge bases
    GET {{search-endpoint}}/knowledgebases?api-version=2025-11-01-preview&$select=name
    api-key: {{api-key}}
    

    示例响应可能如下所示:

     {
         "@odata.context": "https://my-search-service.search.windows.net/$metadata#knowledgebases(name)",
         "value": [
         {
             "name": "my-kb"
         },
         {
             "name": "my-kb-2"
         }
         ]
     }
    
  2. 获取单个知识库定义以检查知识源引用。

    ### Get a knowledge base definition
    GET {{search-endpoint}}/knowledgebases/{{knowledge-base-name}}?api-version=2025-11-01-preview
    api-key: {{api-key}}
    

    示例响应可能如下所示:

     {
       "name": "my-kb",
       "description": null,
       "retrievalInstructions": null,
       "answerInstructions": null,
       "outputMode": null,
       "knowledgeSources": [
         {
           "name": "my-blob-ks",
         }
       ],
       "models": [],
       "encryptionKey": null,
       "retrievalReasoningEffort": {
         "kind": "low"
       }
     }
    
  3. 如果有多个源,您可以选择删除知识库,或者通过删除知识源来更新知识库。 此示例显示删除。

    ### Delete a knowledge base
    DELETE {{search-endpoint}}/knowledgebases/{{knowledge-base-name}}?api-version=2025-11-01-preview
    api-key: {{api-key}}
    
  4. 删除知识来源。

    ### Delete a knowledge source
    DELETE {{search-endpoint}}/knowledgesources/{{knowledge-source-name}}?api-version=2025-11-01-preview
    api-key: {{api-key}}