在SK中内置了一些服务,这些服务可以让我们的应用,简单的实例化调用,便拥有AI能力。
以OpenAI为例,SK中内置的OpenAI服务有:
内容生成服务:OpenAITextGenerationService
聊天服务:OpenAIChatCompletionService
文本转图片服务:OpenAITextToImageService
声音转文本服务:OpenAIAudioToTextService
文本转声音服务:OpenAITextToAudioService
文本嵌入向量服务:OpenAITextEmbeddingGenerationService
using Microsoft.Extensions.Logging;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using System.Text.Json;
var chatModelId = "gpt-3.5-turbo-instruct";
var key = File.ReadAllText(@"C:\GPT\key.txt");
var settings = new PromptExecutionSettings
{
ExtensionData = new Dictionary<string, object>
{
["max_tokens"] = 1000,
["temperature"] = 0.2,
["top_p"] = 0.8,
["presence_penalty"] = 0.0,
["frequency_penalty"] = 0.0
}
};
Console.WriteLine("---------------非流式---------------");
var textGenerationService = new OpenAITextGenerationService(chatModelId, key);
var textContents = await textGenerationService.GetTextContentsAsync("用50个字描述一下.NET", settings);
foreach (var textContent in textContents)
{
var usage = textContent?.Metadata?["Usage"] as Azure.AI.OpenAI.CompletionsUsage;
if (usage != null)
{
var tokenStr = @$"====================Tokens==================
提示词Tokens数:{usage.PromptTokens}
返回内容Tokens数:{usage.CompletionTokens}
总Tokens数:{usage.TotalTokens}
===========================================";
Console.WriteLine(tokenStr);
}
Console.WriteLine(textContent.Text);
}
Console.WriteLine("---------------流式---------------");
var streamTextContents = textGenerationService.GetStreamingTextContentsAsync("用50个字描述一下C#");
await foreach (var textContent in streamTextContents)
{
Console.Write(textContent.Text);
}