将检索增强生成 (RAG) 添加到语义内核代理

警告

语义内核代理 RAG 功能是实验性的,可能会发生更改,并且仅基于反馈和评估完成。

为 RAG 使用 TextSearchProvider

Microsoft.SemanticKernel.Data.TextSearchProvider 允许代理基于用户输入检索相关文档,并将其注入代理的上下文,以获取更明智的响应。 它将 Microsoft.SemanticKernel.Data.ITextSearch 实例与语义内核代理集成。 存在多个 ITextSearch 实现,支持矢量存储和搜索引擎集成上的相似性搜索。 可在此处找到详细信息。

我们还提供一个 Microsoft.SemanticKernel.Data.TextSearchStore,它为检索增强生成提供了简单、规范化的文本数据矢量存储。 TextSearchStore 具有用于在向量存储中存储和检索文本数据的内置架构。 如果要将自己的架构用于存储,请查看 VectorStoreTextSearch

设置文本搜索提供程序

TextSearchProvider可与VectorStoreTextSearchStore一起用于存储和搜索文本文档。

以下示例演示了如何设置和使用TextSearchProviderTextSearchStoreInMemoryVectorStore,使代理能够对文本执行简单的RAG。

// Create an embedding generator using Azure OpenAI.
var embeddingGenerator = new AzureOpenAIClient(new Uri("<Your_Azure_OpenAI_Endpoint>"), new AzureCliCredential())
    .GetEmbeddingClient("<Your_Deployment_Name>")
    .AsIEmbeddingGenerator(1536);

// Create a vector store to store documents.
var vectorStore = new InMemoryVectorStore(new() { EmbeddingGenerator = embeddingGenerator });

// Create a TextSearchStore for storing and searching text documents.
using var textSearchStore = new TextSearchStore<string>(vectorStore, collectionName: "FinancialData", vectorDimensions: 1536);

// Upsert documents into the store.
await textSearchStore.UpsertTextAsync(new[]
{
    "The financial results of Contoso Corp for 2024 is as follows:\nIncome EUR 154 000 000\nExpenses EUR 142 000 000",
    "The Contoso Corporation is a multinational business with its headquarters in Paris."
});

// Create an agent.
Kernel kernel = new Kernel();
ChatCompletionAgent agent = new()
{
    Name = "FriendlyAssistant",
    Instructions = "You are a friendly assistant",
    Kernel = kernel,
    // This setting must be set to true when using the on-demand RAG feature
    UseImmutableKernel = true
};

// Create an agent thread and add the TextSearchProvider.
ChatHistoryAgentThread agentThread = new();
var textSearchProvider = new TextSearchProvider(textSearchStore);
agentThread.AIContextProviders.Add(textSearchProvider);

// Use the agent with RAG capabilities.
ChatMessageContent response = await agent.InvokeAsync("Where is Contoso based?", agentThread).FirstAsync();
Console.WriteLine(response.Content);

高级功能:引文和筛选

支持 TextSearchStore 高级功能,例如按命名空间筛选结果,并在响应中包含引文。

包括引文

TextSearchStore 中的文档可以包含源名称和链接等元数据,从而支持在代理响应中生成引文。

await textSearchStore.UpsertDocumentsAsync(new[]
{
    new TextSearchDocument
    {
        Text = "The financial results of Contoso Corp for 2023 is as follows:\nIncome EUR 174 000 000\nExpenses EUR 152 000 000",
        SourceName = "Contoso 2023 Financial Report",
        SourceLink = "https://www.contoso.com/reports/2023.pdf",
        Namespaces = ["group/g2"]
    }
});

TextSearchProvider检索此文档时,默认情况下,它将在其响应中包含源名称和链接。

按命名空间筛选

在更新插入文档时,可以选择为每个文档提供一个或多个命名空间。 命名空间可以是定义文档范围的任何字符串。 然后,可以将搜索结果配置为 TextSearchStore 仅将搜索结果限制为与请求的命名空间匹配的记录。

using var textSearchStore = new TextSearchStore<string>(
    vectorStore,
    collectionName: "FinancialData",
    vectorDimensions: 1536,
    new() { SearchNamespace = "group/g2" }
);

自动与按需 RAG

可以在 TextSearchProvider 每次代理调用期间自动执行搜索,或者在代理需要其他信息时通过工具调用允许按需搜索。

默认设置是 BeforeAIInvoke,这意味着将使用传递给代理的消息在每个代理调用之前执行搜索。 这可以更改为 OnDemandFunctionCalling,这将允许代理进行工具调用,以使用代理自主选择的搜索字符串进行搜索。

var options = new TextSearchProviderOptions
{
    SearchTime = TextSearchProviderOptions.RagBehavior.OnDemandFunctionCalling,
};

var provider = new TextSearchProvider(mockTextSearch.Object, options: options);

警告

使用 TextSearchProviderOnDemandFunctionCalling 时,代理上的 UseImmutableKernel 设置必须设为 true,因为该功能要求在调用代理时克隆内核。 请注意,设置为UseImmutableKerneltrue意味着在代理调用期间完成的任何内核数据修改(例如插件)都不会在调用完成后保留。

TextSearchProvider 选项

TextSearchProvider可以使用各种选项来配置,以自定义其行为。 使用类 TextSearchProviderOptionsTextSearchProvider 构造函数提供选项。

顶部

指定要从相似性搜索返回的最大结果数。

  • 默认值:3

SearchTime

控制何时执行文本搜索。 选项包括:

  • BeforeAIInvoke:每次调用模型/代理之前都会进行搜索,并且会通过调用上下文将结果提供给模型/代理。
  • OnDemandFunctionCalling:可以通过函数调用按需由模型/代理执行搜索。

插件功能名称

SearchTime被设置为OnDemandFunctionCalling时,指定可供搜索的插件方法的名称。

  • 默认值:“搜索”

插件功能描述

提供插件方法的说明,该方法将可用于搜索(如果 SearchTime 设置为 OnDemandFunctionCalling)。

  • 默认值:“允许搜索其他信息以帮助回答用户问题。

ContextPrompt

在调用时向 AI 模型提供文本区块时,需要提示向 AI 模型指示文本区块的用途以及应如何使用它们。 此设置允许重写 TextSearchProvider 中内置的默认消息。

IncludeCitationsPrompt

在调用时向 AI 模型提供文本区块时,需要提示告知 AI 模型是否以及如何进行引文。 此设置允许重写 TextSearchProvider 中内置的默认消息。

ContextFormatter

此可选回调可用于完全自定义由 TextSearchProvider 生成的文本。 默认情况下,TextSearchProvider 将生成包含某些内容的文本。

  1. 提示告知 AI 模型文本区块的用途。
  2. 包含源链接和名称的文本区块列表。
  3. 一个提示,指示 AI 模型包含引文。

可以通过实现并提供此回调来编写自己的输出。

注意:如果提供了此委托,则不会使用 ContextPromptIncludeCitationsPrompt 设置。

将 RAG 与其他提供程序组合

TextSearchProvider可以与其他提供程序(例如mem0,或WhiteboardProvider)结合使用来创建具有内存和检索功能的代理。

// Add both mem0 and TextSearchProvider to the agent thread.
agentThread.AIContextProviders.Add(mem0Provider);
agentThread.AIContextProviders.Add(textSearchProvider);

// Use the agent with combined capabilities.
ChatMessageContent response = await agent.InvokeAsync("What was Contoso's income for 2023?", agentThread).FirstAsync();
Console.WriteLine(response.Content);

通过组合这些功能,代理可以提供更个性化和上下文感知的体验。

后续步骤

即将推出

更多信息即将推出。

即将推出

更多信息即将推出。