目前C#调用Open AI有很多的开源库,本文使用的nuget包如下:
<PackageReference Include="DevExpressMvvm" Version="22.1.3" />
<PackageReference Include="Microsoft.CognitiveServices.Speech" Version="1.29.0" />
<PackageReference Include="OpenAI-DotNet" Version="6.8.7" />
<PackageReference Include="WPF-UI" Version="2.0.3" />
都有开源库,所以实现起来就比较简单了,主要难度可能还是注册账号,有能力的可以自己试试,在这儿贴出部分调用的主要代码,项目已开源,Github搜索JamesBaiJun/OpenAI-Azure,记得点个Star。
调用ChatGPT使用Nuget的OpenAI-DotNet库,代码如下:
static string key = string.Empty;
static OpenAIClient api = new OpenAIClient(这里填你的Key);
public static event Action<string> OnReceiveReply;
public static event Action<string> OnReceivePartial;
public static async Task AskAsync(List<Message> messages)
{
var chatRequest = new ChatRequest(messages, Model.GPT3_5_Turbo);
await foreach (var result in api.ChatEndpoint.StreamCompletionEnumerableAsync(chatRequest))
{
foreach (var choice in result.Choices.Where(choice => choice.Delta?.Content != null))
{
// Partial response content
//Debug.WriteLine(choice.Delta.Content);
OnReceivePartial?.Invoke(choice.Delta.Content);
}
foreach (var choice in result.Choices.Where(choice => choice.Message?.Content != null))
{
// Completed response content
//Debug.WriteLine($"{choice.Message.Role}: {choice.Message.Content}");
OnReceiveReply?.Invoke(choice.Message.Content);
}
}
}
软件截图如下,需要你填入自己的Key: