打开Visual Studio 2022
,然后创建一个名称为TokenAI
的控制台项目
右键新建的项目,然后点击管理 NuGet 程序包
搜索Semantic Kernel
,并且选择包括预览版,然后选择安装Microsoft.SemanticKernel
,
HttpClientHandler
,下面我们创建一个OpenAIHttpClientHandler.cs
,然后提供以下实现
public class OpenAIHttpClientHandler : HttpClientHandler
{
private readonly string _uri;
public OpenAIHttpClientHandler(string uri) => _uri = uri.TrimEnd('/');
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
UriBuilder uriBuilder;
if (request.RequestUri?.LocalPath == "/v1/chat/completions")
{
uriBuilder = new UriBuilder(_uri + "/v1/chat/completions");
request.RequestUri = uriBuilder.Uri;
}
else if (request.RequestUri?.LocalPath == "/v1/embeddings")
{
uriBuilder = new UriBuilder(_uri + "/v1/embeddings");
request.RequestUri = uriBuilder.Uri;
}
return await base.SendAsync(request, cancellationToken);
}
}
打开Program.cs
using Microsoft.SemanticKernel;
using TokenAI;
var 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 foreach (var item in kernel.InvokePromptStreamingAsync("您好,我是TokenAI"))
{
Console.Write(item.ToString());
};
执行效果:
我们使用Kernel
的CreateBuilder
创建了一个Kernel
对象,并且在这个对象中存在InvokePromptStreamingAsync
方法,这个方法提供了OpenAI的一个Stream的对话接口,并且我们添加了AddOpenAIChatCompletion
添加了自定义的模型和我们的代理网站的key地址。
很好您已经初步入门我们的SK了!