SemanticKernel介绍
Semantic Kernel是一个SDK,它将OpenAI、Azure OpenAI和Hugging Face等大型语言模型(LLMs)与C#、Python和Java等传统编程语言集成在一起。Semantic Kernel通过允许您定义插件来实现这一点,这些插件可以通过几行代码链接在一起。
为什么需要添加插件?
大语言模型虽然具有强大的自然语言理解和生成能力,但它们通常是基于预训练的模型,其功能受限于训练时所接触的数据和任务。为大语言模型添加插件是为了扩展其功能、提高其灵活性和实用性。比如你问一个大语言模型今天是几号?它无法提供实时信息甚至会出现幻觉,这时候插件就派上用场了。
实践
插件分为提示词插件与本地函数插件,本次示例用的是本地函数。创建一个Time@R_928_4045@ion类:
public class Time@R_928_4045@ion
{
[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<Time@R_928_4045@ion>();
var kernel = builder.Build();
现在来试试效果:
// Example 1. Invoke the kernel with a prompt that asks the AI for @R_928_4045@ion 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("现在时间是 {{Time@R_928_404[email protected]}},还有多少天到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";
效果如下所示:
参考
2、Understanding AI plugins in Semantic Kernel and beyond | Microsoft Learn
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。