Semantie Kernel中对话请求默认是发送到OpenAI去的:
其他与OpenAI对话请求接口兼任的模型平台,一般只需要修改host即可,如下所示:
default:uriBuilder = new UriBuilder(request.RequestUri){// 这里是你要修改的 URLScheme = "https",Host = host,Path = "v1/chat/completions",};request.RequestUri = uriBuilder.Uri;break;
但是智谱AI的对话接口地址如下:
在python中这样就可以用,但SemanticKernel中好像还没有base_url的设置。
有两种方式可以实现。
一种是想和之前其他模型用相同的方式,把智普平台作为一种特殊的方式处理。
在appsettings.json中添加一个Platform字段,请求接口完全兼容OpenAI的可以不写:
创建Kernel是这样的:
var builder = Kernel.CreateBuilder().AddOpenAIChatCompletion(modelId: OpenAIOption.ChatModel,apiKey: OpenAIOption.Key,httpClient: new HttpClient(handler));
_kernel = builder.Build();
然后在OpenAIHttpClientHandler为智谱平台做一下不同的处理:
public class OpenAIHttpClientHandler : HttpClientHandler
{protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken){UriBuilder uriBuilder;string url = OpenAIOption.Endpoint;string platform = OpenAIOption.Platform;Uri uri = new Uri(url);string host = uri.Host;switch (request.RequestUri?.LocalPath){case "/v1/chat/completions":switch(platform){case "ZhiPu":uriBuilder = new UriBuilder(request.RequestUri){// 这里是你要修改的 URLScheme = "https",Host = host,Path = "api/paas/v4/chat/completions",};request.RequestUri = uriBuilder.Uri;break;default:uriBuilder = new UriBuilder(request.RequestUri){// 这里是你要修改的 URLScheme = "https",Host = host,Path = "v1/chat/completions",};request.RequestUri = uriBuilder.Uri;break;}break;}HttpResponseMessage response = await base.SendAsync(request, cancellationToken);return response;}
}
尝试是否成功:
另一种方式更加简单,只需要在appsettings.json中这样写:
使用这种方式创建Kernel即可:
尝试是否成功:
在AvaloniaChat中为了和其他平台保持统一的使用方式,我选择第一种方式。
OpenAIHttpClientHandler可以在此处查看:https://github.com/Ming-jiayou/AvaloniaChat/blob/main/src/AvaloniaChat/Model/OpenAIHttpClientHandler.cs
创建Kernel的两种方式可以在此处查看:https://github.com/Ming-jiayou/AvaloniaChat/blob/main/src/AvaloniaChat/ViewModels/MainViewModel.cs