Semantie Kernel中对话请求默认是发送到OpenAI去的
其他与OpenAI对话请求接口兼容的模型平台,一般只需要修改host即可,path不需要修改,可以通过HttpClientHandler修改
接入智普AI
但是智谱AI的对话接口地址是api/paas/v4/chat/completions
,和OpenAI不同,所以需要修改host和path
智普官网
安装Nuget:
<PackageReference Include="Microsoft.SemanticKernel" Version="1.25.0" />
代码:
var builder = Kernel.CreateBuilder();
var httpClient = new HttpClient(new OpenAIHttpClientHandler());
builder = builder.AddOpenAIChatCompletion(modelId: "glm-4",
apiKey: "xxxxxxx", httpClient: httpClient);
var kernel = builder.Build();
var chatCompletionService = kernel.GetRequiredService<IChatCompletionService>();
var history = new ChatHistory();
string? userInput;
do
{
// Collect user input
Console.Write("User > ");
userInput = Console.ReadLine();
// Add user input
history.AddUserMessage(userInput);
// Get the response from the AI
var result = await chatCompletionService.GetChatMessageContentAsync(history, kernel: kernel);
// Print the results
Console.WriteLine("Assistant > " + result);
// Add the message from the agent to the chat history
history.AddMessage(result.Role, result.Content ?? string.Empty);
} while (userInput is not null);
使用HttpClientHandler修改host和path
public class OpenAIHttpClientHandler : HttpClientHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
switch (request.RequestUri?.LocalPath)
{
case "/v1/chat/completions":
var uriBuilder = new UriBuilder(request.RequestUri)
{
Scheme = "https",
Host = "open.bigmodel.cn",
Path = "api/paas/v4/chat/completions",//其他与OpenAI对话请求接口兼容的模型平台,一般只需要修改host即可,不需要修改path
};
request.RequestUri = uriBuilder.Uri;
break;
}
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
return response;
}
}
标签:Kernel,智普,semantic,kernel,AI,request,result,var,history
From: https://www.cnblogs.com/fanfan-90/p/18512262