【Semantic Kernel】5、ITextCompletion、IChatCompletion
ChatGPT
//chatGPT
{
var chatGPT = kernel.GetService<IChatCompletion>();
var chatHistory = chatGPT.CreateNewChat("你是图书管理员");
Console.WriteLine("请提问:");
while (true)
{
var ask = Console.ReadLine();
chatHistory.AddUserMessage(ask);
string reply = await chatGPT.GenerateMessageAsync(chatHistory);
chatHistory.AddAssistantMessage(reply);
await MessageOutputAsync(chatHistory);
}
}
Task MessageOutputAsync(ChatHistory chatHistory)
{
var message = chatHistory.Messages.Last();
Console.WriteLine($"{message.Role}: {message.Content}");
Console.WriteLine("------------------------");
return Task.CompletedTask;
}
生成多个结果
案例1:
var excuseFunction = kernel.CreateSemanticFunction(FunctionDefinition, maxTokens: 100, temperature: 1, topP: 1);
var textResult = await excuseFunction.InvokeAsync("I missed the F1 final race",
new CompleteRequestSettings { ResultsPerPrompt = 3 });
Console.WriteLine(textResult.ModelResults.Select(result => result.GetOpenAITextResult()).AsJson());
案例2:
//textCompletion:返回多个结果
{
var textCompletion = kernel.GetService<ITextCompletion>();
var textResults = await textCompletion.GetCompletionsAsync("帮我起个名字,类似烈焰骑士、狂风战神、急速飞鹰",
new CompleteRequestSettings {
ResultsPerPrompt = 3, //结果数量
TopP = 0.5,//多样性
Temperature = 1, //随机度
FrequencyPenalty = 0,//降低模型逐字重复同一行的可能性。
});
foreach (var textResult in textResults)
{
Console.WriteLine(await textResult.GetCompletionAsync());
}
}
案例3:
//chatCompletion:返回多个结果
{
var chatCompletion = kernel.GetService<IChatCompletion>();
var chatHistory = chatCompletion.CreateNewChat("You are a librarian, expert about books");
// First user message
chatHistory.AddUserMessage("Hi, I'm looking for book 3 different book suggestions about sci-fi");
await MessageOutputAsync(chatHistory);
var chatRequestSettings = new ChatRequestSettings
{
MaxTokens = 1024,
ResultsPerPrompt = 2,
Temperature = 1,
TopP = 0.5,
FrequencyPenalty = 0,//降低模型逐字重复同一行的可能性。
};
// First bot assistant message
foreach (IChatResult chatCompletionResult in await chatCompletion.GetChatCompletionsAsync(chatHistory, chatRequestSettings))
{
ChatMessageBase chatMessage = await chatCompletionResult.GetChatMessageAsync();
chatHistory.Add(chatMessage);
await MessageOutputAsync(chatHistory);
}
}