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

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

实践
插件分为提示词插件与本地函数插件,本次示例用的是本地函数。创建一个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号?rn";
Text += "答:" + await kernel.InvokePromptAsync("还有多少天到7月1号?") + "rn";
// Example 2. Invoke the kernel with a templated prompt that invokes a plugin and display the result
Text += "问:还有多少天到7月1号?rn";
Text += "答:" + await kernel.InvokePromptAsync("现在时间是 {{TimeInformation.GetCurrentUtcTime}},还有多少天到7月1号?") + "rn";
// 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号?rn";
Text += "答:" + await kernel.InvokePromptAsync("还有多少天到7月1号,请解释一下你的思考?", new(settings)) + "rn";
效果如下所示:

第一个回答没有使用插件,大语言模型出现幻觉了。
第二个回答通过使用模板化的提示来调用插件,回答正确。
第三个回答通过自动调用插件,回答正确。
参考
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)
原文始发于微信公众号(DotNet学习交流):SemanticKernel:添加插件
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/293426.html