.NET 的语义内核概述
本文将探讨语义内核的核心概念和功能。 语义内核是在 .NET 应用程序中使用 AI 时推荐使用的一项强大功能。 在前面的部分中,你已了解:
- 如何将语义内核添加到项目
- 语义内核的核心概念
本文专门针对 .NET 上下文中的语义内核进行了介绍性概述。 有关语义内核的更全面信息和培训,请参阅以下资源:
将语义内核添加到 .NET 项目
语义内核 SDK 可作为 .NET 的 NuGet 包使用,并与标准应用配置集成。
使用以下命令安装 Microsoft.SemanticKernel
包:
dotnet add package Microsoft.SemanticKernel
注意
尽管 Microsoft.SemanticKernel
提供语义内核的核心功能,但其他功能需要安装其他包。 例如,Microsoft.SemanticKernel.Plugins.Memory
包提供与访问内存相关的功能。 有关更多信息,请参阅语义内核文档。
使用 KernelBuilder
类创建和配置 Kernel
实例以访问和使用语义内核。 Kernel
包含服务、数据和连接,以协调代码和 AI 模型之间的集成。
在 .NET 控制台应用中配置 Kernel
:
var builder = Kernel.CreateBuilder();
// Add builder configuration and services
var kernel = builder.Build();
在 ASP.NET Core 应用中配置内核:
var builder = WebApplication.CreateBuilder();
builder.Services.AddKernel();
// Add builder configuration and services
var app = builder.Build();
了解语义内核
语义内核是一个开源 SDK,它使用 C#、Python 和 Java 等传统编程语言来集成和编排 OpenAI、Azure OpenAI 和 Hugging Face 等 AI 模型和服务。
语义内核 SDK 以以下方式使企业开发人员受益:
- 简化将 AI 功能集成到现有应用程序中的过程,从而为企业产品提供统一的解决方案。
- 通过可降低复杂性的抽象,最大限度地缩短使用不同 AI 模型或服务的学习曲线。
- 通过减少 AI 模型提示和响应的不可预测行为来提高可靠性。 可以微调提示并计划任务,以创建可控且可预测的用户体验。
语义内核围绕几个核心概念构建:
- 连接:与外部 AI 服务和数据源交互。
- 插件:封装应用程序可以使用的功能。
- 规划器:根据用户行为编排执行计划和策略。
- 内存:抽象并简化 AI 应用程序的上下文管理。
以下部分将更详细地探讨这些构建块。
连接
语义内核 SDK 包含一组连接器,开发人员可以通过这些连接器将 LLM 和其他服务集成到其现有应用程序中。 这些连接器充当应用程序代码与 AI 模型或服务之间的桥梁。 语义内核可为你处理许多常见的连接问题和挑战,让你可以专注于构建自己的工作流程和功能。
以下代码片段创建了一个 Kernel
并添加了与 Azure OpenAI 模型的连接:
using Microsoft.SemanticKernel;
// Create kernel
var builder = Kernel.CreateBuilder();
// Add a chat completion service:
builder.Services.AddAzureOpenAIChatCompletion(
"your-resource-name",
"your-endpoint",
"your-resource-key",
"deployment-model");
var kernel = builder.Build();
插件
语义内核插件封装了标准语言函数,以供应用程序和 AI 模型使用。 可以创建自己的插件,也可以依赖 SDK 提供的插件。 这些插件简化了 AI 模型擅长处理的任务,并有效地将它们与更传统的 C# 方法相结合。 插件函数通常分为两类:语义函数和本机函数。
语义函数
语义函数本质上是代码中定义的 AI 提示,语义内核可以根据需要自定义和调用这些提示。 可以将这些提示模板化以使用变量、自定义提示和完成格式等。
以下代码片段定义并注册了一个语义函数:
var userInput = Console.ReadLine();
// Define semantic function inline.
string skPrompt = @"Summarize the provided unstructured text in a sentence that is easy to understand.
Text to summarize: {{$userInput}}";
// Register the function
kernel.CreateSemanticFunction(
promptTemplate: skPrompt,
functionName: "SummarizeText",
pluginName: "SemanticFunctions"
);
本机函数
本机函数是 Semantic Kernel 可以直接调用来操作或检索数据的 C# 方法。 它们执行更适合传统代码指令,而不是 LLM 提示的操作。
以下代码片段定义并注册了一个本机函数:
// Define native function
public class NativeFunctions {
[SKFunction, Description("Retrieve content from local file")]
public async Task<string> RetrieveLocalFile(string fileName, int maxSize = 5000)
{
string content = await File.ReadAllTextAsync(fileName);
if (content.Length <= maxSize) return content;
return content.Substring(0, maxSize);
}
}
//Import native function
string plugInName = "NativeFunction";
string functionName = "RetrieveLocalFile";
var nativeFunctions = new NativeFunctions();
kernel.ImportFunctions(nativeFunctions, plugInName);
Planner
规划器是语义内核的核心组件,它提供 AI 编排功能,以管理 AI 模型和插件之间的无缝集成。 该层根据用户请求制定执行策略,并动态编排插件,以通过 AI 辅助规划执行复杂的任务。
请思考以下伪代码片段:
// Native function definition and kernel configuration code omitted for brevity
// Configure and create the plan
string planDefinition = "Read content from a local file and summarize the content.";
SequentialPlanner sequentialPlanner = new SequentialPlanner(kernel);
string assetsFolder = @"../../assets";
string fileName = Path.Combine(assetsFolder,"docs","06_SemanticKernel", "aci_documentation.txt");
ContextVariables contextVariables = new ContextVariables();
contextVariables.Add("fileName", fileName);
var customPlan = await sequentialPlanner.CreatePlanAsync(planDefinition);
// Execute the plan
KernelResult kernelResult = await kernel.RunAsync(contextVariables, customPlan);
Console.WriteLine($"Summarization: {kernelResult.GetValue<string>()}");
上述代码创建了一个可执行的顺序计划,用于从本地文件读取内容并汇总内容。 该计划设置了使用本机函数读取文件,然后使用 AI 模型对其进行分析的指令。
内存
Semantic Kernel 的矢量存储提供对嵌入模型、矢量数据库和其他数据的抽象,以简化 AI 应用程序的上下文管理。 矢量存储与基础 LLM 或矢量数据库无关,提供统一的开发人员体验。 可以配置内存功能,将数据存储在各种源或服务中,包括 Azure AI 搜索和 Azure Cache for Redis。
请思考以下代码片段:
var facts = new Dictionary<string,string>();
facts.Add(
"Azure Machine Learning; https://learn.microsoft.com/en-us/azure/machine-learning/",
@"Azure Machine Learning is a cloud service for accelerating and
managing the machine learning project lifecycle. Machine learning professionals,
data scientists, and engineers can use it in their day-to-day workflows"
);
facts.Add(
"Azure SQL Service; https://learn.microsoft.com/en-us/azure/azure-sql/",
@"Azure SQL is a family of managed, secure, and intelligent products
that use the SQL Server database engine in the Azure cloud."
);
string memoryCollectionName = "SummarizedAzureDocs";
foreach (var fact in facts) {
await memoryBuilder.SaveReferenceAsync(
collection: memoryCollectionName,
description: fact.Key.Split(";")[1].Trim(),
text: fact.Value,
externalId: fact.Key.Split(";")[2].Trim(),
externalSourceName: "Azure Documentation"
);
}
上述代码将一组事实加载到内存中,以便在与 AI 模型交互和编排任务时可以使用这些数据。