Код: Выделить всё
var fetchTasks = videos.Select(async item =>
{
try
{
var formattedItem = new VideoItem
{
Title = item.Title,
Subtitle = _extractService.GetCleanSubtitle(item.Subtitle ?? ""),
Description = _extractService.GetCleanSubtitle(item.Description ?? ""),
};
if (string.IsNullOrEmpty(formattedItem.Subtitle) && string.IsNullOrEmpty(formattedItem.Description))
{
_logger.LogWarning($"Video {item.Id} has empty subtitle or description. Marking as not processed.");
item.NotProcess = true;
return new { item, processStatus = true, request = string.Empty, response = (string)null };
}
else
{
var builder = new RequestBuilder(formattedItem).WithYamlFormatPath(yamlPath);
var yamlRequest = builder.Build();
_logger.LogInformation($"Built YAML request: {yamlRequest}");
var response = await _apiService.CallApiAsync(yamlRequest);
_logger.LogInformation($"Response for video {item.Id}: {response}");
return new { item, processStatus = true, request = yamlRequest, response };
}
}
catch (Exception ex)
{
_logger.LogError($"Error fetching details for video {item.Id}: {ex.Message}");
return null;
}
});
var fetchedDetails = (await Task.WhenAll(fetchTasks)).Where(result => result != null);
Код: Выделить всё
public async Task CallApiAsync(string response)
{
try
{
var completionResult = await _openAiService.ChatCompletion.CreateCompletion(new ChatCompletionCreateRequest
{
Messages = new List
{
ChatMessage.FromSystem("You are a helpful assistant."),
ChatMessage.FromUser(response)
},
Model = Models.Gpt_3_5_Turbo,
});
if (completionResult.Successful)
{
Console.WriteLine(completionResult.Choices.First().Message.Content);
return completionResult.Choices.First().Message.Content;
}
return "";
}
catch (Exception ex)
{
// Log or handle exception as neede
Console.WriteLine($"Error calling ChatGPT API: {ex.Message}");
throw;
}
}
Код: Выделить всё
foreach (var item in fetchedDetails)
{
var video = item.video;
var request = item.request;
var response = item.response;
var dbResponse = new Response
{
Request = request,
YtVideoId = item .Id,
Response = response
};
}
Как мне выполнить рефакторинг этого кода, чтобы он ждал внешнего вызова API, чтобы правильно получить ответ и обработать его параллельно? п>
Подробнее здесь: https://stackoverflow.com/questions/786 ... processing