SemanticKernel:添加插件

SemanticKernel介绍

Semantic Kernel是一个SDK,它将OpenAI、Azure OpenAI和Hugging Face等大型语言模型(LLMs)与C#、Python和Java等传统编程语言集成在一起。Semantic Kernel通过允许您定义插件来实现这一点,这些插件可以通过几行代码链接在一起。

image-20240606090229088

为什么需要添加插件?

大语言模型虽然具有强大的自然语言理解和生成能力,但它们通常是基于预训练的模型,其功能受限于训练时所接触的数据和任务。为大语言模型添加插件是为了扩展其功能、提高其灵活性和实用性。比如你问一个大语言模型今天是几号?它无法提供实时信息甚至会出现幻觉,这时候插件就派上用场了。

Semantic Kernel can orchestrate AI plugins from any provider

实践

插件分为提示词插件与本地函数插件,本次示例用的是本地函数。创建一个TimeInformation类:

 public class TimeInformation
 {
     [KernelFunction]
     [Description("Retrieves the current time in UTC.")]
     public string GetCurrentUtcTime() => DateTime.UtcNow.ToString("R");

 }

[KernelFunction]SemanticKernel中的一个特性,表示指定导入为插件的类中的方法应作为 Microsoft.SemanticKernel.KernelFunction 包含在生成的 Microsoft.SemanticKernel.KernelPlugin 中。 [Description]特性用于为类、方法、属性等添加描述信息。

在kernel中加入这个插件:

builder.Plugins.AddFromType<TimeInformation>();
var kernel = builder.Build();

现在来试试效果:

// Example 1. Invoke the kernel with a prompt that asks the AI for information it cannot provide and may hallucinate
Text += "问:还有多少天到7月1号?\r\n";
Text += "答:" + await kernel.InvokePromptAsync("还有多少天到7月1号?") + "\r\n";

// Example 2. Invoke the kernel with a templated prompt that invokes a plugin and display the result       
Text += "问:还有多少天到7月1号?\r\n";
Text += "答:" + await kernel.InvokePromptAsync("现在时间是 {{TimeInformation.GetCurrentUtcTime}},还有多少天到7月1号?") + "\r\n";

// Example 3. Invoke the kernel with a prompt and allow the AI to automatically invoke functions
OpenAIPromptExecutionSettings settings = new() { ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions };       
Text += "问:还有多少天到7月1号?\r\n";
Text += "答:" + await kernel.InvokePromptAsync("还有多少天到7月1号,请解释一下你的思考?", new(settings)) + "\r\n";

效果如下所示:

image-20240606092641539

第一个回答没有使用插件,大语言模型出现幻觉了。

第二个回答通过使用模板化的提示来调用插件,回答正确。

第三个回答通过自动调用插件,回答正确。

参考

1、microsoft/semantic-kernel: Integrate cutting-edge LLM technology quickly and easily into your apps (github.com)

2、Understanding AI plugins in Semantic Kernel and beyond | Microsoft Learn

3、semantic-kernel/dotnet/samples/GettingStarted/Step2_Add_Plugins.cs at main · microsoft/semantic-kernel (github.com)

posted @ 2024-06-06 10:05  mingupupup  阅读(145)  评论(0编辑  收藏  举报