(3)semantic-kernel对话提示中级教程
在平常使用Semantic Kernel
的时候我们需要利用Semantic Kernel
的更多的功能让我们的业务实现更加的简单和高效,下面我们通过一个案例来了解Semantic Kernel
的对话提示功能和一些高级的用法。
创建一个控制台的项目
-
打开
Visual Studio 2022
,然后创建一个名称为3_Chat_Prompts
的控制台项目 -
然后复制以下代码到
3_Chat_Prompts
项目文件中
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>_3_Chat_Prompts</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.SemanticKernel" Version="1.12.0" />
</ItemGroup>
</Project>
创建一个Kernel
- 然后复制上一个教程的
OpenAIHttpClientHandler.cs
到3_Chat_Prompts
项目文件中。 - 打开
Program.cs
示例显示使用纯文本的提示模板
using System.Diagnostics.CodeAnalysis;
using Microsoft.SemanticKernel;
using TokenAI;
#pragma warning disable SKEXP0001
namespace _3_Chat_Prompts;
internal static class Program
{
private static Kernel _kernel;
[Experimental("SKEXP0001")]
public static async Task Main(string[] args)
{
_kernel = Kernel.CreateBuilder()
.AddOpenAIChatCompletion(
modelId: "gpt-3.5-turbo",
apiKey: "这里填写在https://api.token-ai.cn/创建的令牌",
httpClient: new HttpClient(new OpenAIHttpClientHandler("https://api.token-ai.cn/")))
.Build();
await PlainTextAsync();
}
public static async Task PlainTextAsync()
{
string chatPrompt = """
<message role="user">北京是什么?</message>
""";
Console.WriteLine(await RenderPromptAsync(new PromptTemplateConfig(chatPrompt)));
Console.WriteLine(await _kernel.InvokePromptAsync(chatPrompt));
}
static readonly IPromptTemplateFactory _promptTemplateFactory = new KernelPromptTemplateFactory();
static Task<string> RenderPromptAsync(PromptTemplateConfig promptConfig, KernelArguments? arguments = null,
IPromptTemplateFactory? promptTemplateFactory = null)
{
promptTemplateFactory ??= _promptTemplateFactory;
var promptTemplate = promptTemplateFactory.Create(promptConfig);
return promptTemplate.RenderAsync(_kernel, arguments);
}
}
结果输出:
<message role="user">北京是什么?</message>
北京是中国的首都城市,也是中国的政治、文化和国际交往中心。北京具有悠久的历史和丰富的文化遗产,是中国历史上重要的古都之一。同时,北京也是一个现代化的大都市,拥有现代化的建筑、繁华的商业和繁荣的文化生活。
在上面的prompt中我们提问了北京是什么?
的问题,然后AI回复了相关的内容。在这个案例中我们使用了纯文本的提示模板,这样我们可以更加的方便的使用Semantic Kernel
的功能。
示例显示包含安全内容的输入变量
using System.Diagnostics.CodeAnalysis;
using Microsoft.SemanticKernel;
using TokenAI;
#pragma warning disable SKEXP0001
namespace _3_Chat_Prompts;
internal static class Program
{
private static Kernel _kernel;
[Experimental("SKEXP0001")]
public static async Task Main(string[] args)
{
_kernel = Kernel.CreateBuilder()
.AddOpenAIChatCompletion(
modelId: "gpt-3.5-turbo",
apiKey: "这里填写在https://api.token-ai.cn/创建的令牌",
httpClient: new HttpClient(new OpenAIHttpClientHandler("https://api.token-ai.cn/")))
.Build();
await SafeInputVariableAsync();
}
public static async Task SafeInputVariableAsync()
{
var kernelArguments = new KernelArguments()
{
["input"] = "什么是北京?",
};
var chatPrompt = """
<message role="user">{{$input}}</message>
""";
Console.WriteLine(await RenderPromptAsync(new PromptTemplateConfig(chatPrompt), kernelArguments));
Console.WriteLine(await _kernel.InvokePromptAsync(chatPrompt, kernelArguments));
}
static readonly IPromptTemplateFactory _promptTemplateFactory = new KernelPromptTemplateFactory();
static Task<string> RenderPromptAsync(PromptTemplateConfig promptConfig, KernelArguments? arguments = null,
IPromptTemplateFactory? promptTemplateFactory = null)
{
promptTemplateFactory ??= _promptTemplateFactory;
var promptTemplate = promptTemplateFactory.Create(promptConfig);
return promptTemplate.RenderAsync(_kernel, arguments);
}
}
结果输出:
<message role="user">什么是北京?</message>
北京是中国的首都,也是中国政治、经济、文化和教育中心,拥有悠久的历史和丰富的文化遗产。北京是一座国际化大都市,有着各种名胜古迹、现代建筑和丰富的文化活动,吸引着来自全球的游客和投资者。同时,北京也是中国的交通枢纽,拥有完善的交通网络,方便人们出行。
在上面的prompt中我们提问了什么是北京?
的问题,然后AI回复了相关的内容。在这个案例中我们使用了安全内容的输入变量,这样我们可以更加的方便的使用Semantic Kernel
的功能。
示例显示如何信任聊天提示符中的所有内容
using System.Diagnostics.CodeAnalysis;
using Microsoft.SemanticKernel;
using TokenAI;
#pragma warning disable SKEXP0001
namespace _3_Chat_Prompts;
internal static class Program
{
private static Kernel _kernel;
[Experimental("SKEXP0001")]
public static async Task Main(string[] args)
{
_kernel = Kernel.CreateBuilder()
.AddOpenAIChatCompletion(
modelId: "gpt-3.5-turbo",
apiKey: "这里填写在https://api.token-ai.cn/创建的令牌",
httpClient: new HttpClient(new OpenAIHttpClientHandler("https://api.token-ai.cn/")))
.Build();
await TrustedTemplateAsync();
}
/// <summary>
/// 可靠的模板
/// </summary>
public static async Task TrustedTemplateAsync()
{
var trustedMessageFunction = KernelFunctionFactory.CreateFromMethod(
() => "<message role=\"system\">你是一个很有帮助的助手,对中国的城市了如指掌</message>",
"TrustedMessageFunction");
var trustedContentFunction =
KernelFunctionFactory.CreateFromMethod(() => "<text>北京是什么?</text>", "TrustedContentFunction");
_kernel.ImportPluginFromFunctions("TrustedPlugin", [trustedMessageFunction, trustedContentFunction]);
var chatPrompt = """
{{TrustedPlugin.TrustedMessageFunction}}
<message role="user">{{$input}}</message>
<message role="user">{{TrustedPlugin.TrustedContentFunction}}</message>
""";
var promptConfig = new PromptTemplateConfig(chatPrompt);
var kernelArguments = new KernelArguments()
{
["input"] = "<text>深圳是什么?</text>",
};
var factory = new KernelPromptTemplateFactory() { AllowDangerouslySetContent = true };
var function = KernelFunctionFactory.CreateFromPrompt(promptConfig, factory);
Console.WriteLine(await RenderPromptAsync(promptConfig, kernelArguments, factory));
Console.WriteLine((await _kernel.InvokeAsync(function, kernelArguments)).GetValue<string>());
}
static readonly IPromptTemplateFactory _promptTemplateFactory = new KernelPromptTemplateFactory();
static Task<string> RenderPromptAsync(PromptTemplateConfig promptConfig, KernelArguments arguments,
IPromptTemplateFactory? promptTemplateFactory = null)
{
promptTemplateFactory ??= _promptTemplateFactory;
var promptTemplate = promptTemplateFactory.Create(promptConfig);
return promptTemplate.RenderAsync(_kernel, arguments);
}
}
结果输出:
<message role="system">你是一个很有帮助的助手,对中国的城市了如指掌</message>
<message role="user"><text>深圳是什么?</text></message>
<message role="user"><text>北京是什么?</text></message>
北京是中国的首都和政治中心,也是中国著名的历史文化名城。北京是中国现代化的代表城市之一,拥有众多著名的景点和文化遗产,如故宫、天安门广场、长城等。此外,北京还是中国重要的经济、科技和文化中心,吸引着大量国内外人才和投资。
在上面的prompt中我们提问了深圳是什么?
和北京是什么?
俩个问题,但是在北京是什么?
的Prompt中我们设置了参数AllowDangerouslySetContent = true
,那么它是可靠的,但是深圳是什么?
并且没有标记,但是他们都同样存在<text>
元素都可能存在攻击性的内容,北京是什么?
被认为是可靠的,而深圳是什么?
被认为是不可靠的,所以在结果输出的时候,深圳是什么?
的内容被过滤掉了,AI只回答了北京是什么?
的问题。