题意:“我在 C# OpenAI 库中遇到 HttpClient.Timeout
错误。”
问题背景:
I am using the OpenAI library in my c# project, but I get the following error if it does not receive a response for more than 100 seconds. I cannot add a custom httpclient element. how can I solve this problem. Thanks in advance.
“我在 C# 项目中使用 OpenAI 库,但如果超过 100 秒未收到响应,我就会遇到以下错误。我无法添加自定义的 HttpClient 元素。如何解决这个问题?提前感谢。”
‘system Threading Tasks.TaskCanceledException: The request was canceled due to the configured HttpClient.Timeout of 100 seconds elapsing,‘
“‘系统抛出 Threading.Tasks.TaskCanceledException
:请求由于配置的 100 秒 HttpClient 超时而被取消,’”
The library I use: https://github.com/OkGoDoIt/OpenAI-API-dotnet
“我使用的库:https://github.com/OkGoDoIt/OpenAI-API-dotnet
”
my code: 我的代码:
OpenAIAPI api = new OpenAIAPI(apiKey);
var result = await api.Chat.CreateChatCompletionAsync(new ChatRequest()
{
Model = Model.ChatGPTTurbo,
Temperature = 0.5,
Messages = new ChatMessage[]
{
new ChatMessage(ChatMessageRole.System, ""),
new ChatMessage(ChatMessageRole.User, prompt)
}
});
问题解决:
Solution for those who have other problems:
“针对那些遇到其他问题的解决方案:”
using System.Net.Http;
public class CustomHttpClientFactory : IHttpClientFactory
{
public HttpClient CreateClient(string name)
{
var httpClient = new HttpClient();
httpClient.Timeout = TimeSpan.FromSeconds(200);
return httpClient;
}
}
OpenAIAPI api = new OpenAIAPI(apiKey);
api.HttpClientFactory = new CustomHttpClientFactory();
var result = await api.Chat.CreateChatCompletionAsync(new ChatRequest()
{
Model = Model.ChatGPTTurbo,
Temperature = 0.5,
Messages = new ChatMessage[]
{
new ChatMessage(ChatMessageRole.System, ""),
new ChatMessage(ChatMessageRole.User, prompt)
}
});