2023-06-17 02:42:35 +00:00
|
|
|
using Azure.AI.OpenAI;
|
|
|
|
|
using Azure;
|
|
|
|
|
using BotSharp.Abstraction.MLTasks;
|
|
|
|
|
using System;
|
|
|
|
|
using System.Threading.Tasks;
|
2023-06-19 18:32:49 +00:00
|
|
|
using BotSharp.Plugin.AzureOpenAI.Settings;
|
2023-08-07 10:21:31 +00:00
|
|
|
using Microsoft.Extensions.Logging;
|
2023-06-17 02:42:35 +00:00
|
|
|
|
2023-06-17 13:32:39 +00:00
|
|
|
namespace BotSharp.Plugin.AzureOpenAI.Providers;
|
2023-06-17 02:42:35 +00:00
|
|
|
|
|
|
|
|
public class TextCompletionProvider : ITextCompletion
|
|
|
|
|
{
|
|
|
|
|
private readonly AzureOpenAiSettings _settings;
|
2023-08-07 10:21:31 +00:00
|
|
|
private readonly ILogger _logger;
|
2023-06-17 02:42:35 +00:00
|
|
|
bool _useAzureOpenAI = true;
|
|
|
|
|
|
2023-08-07 10:21:31 +00:00
|
|
|
public TextCompletionProvider(AzureOpenAiSettings settings, ILogger<TextCompletionProvider> logger)
|
2023-06-17 02:42:35 +00:00
|
|
|
{
|
|
|
|
|
_settings = settings;
|
2023-08-07 10:21:31 +00:00
|
|
|
_logger = logger;
|
2023-06-17 02:42:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task<string> GetCompletion(string text)
|
|
|
|
|
{
|
|
|
|
|
var client = GetOpenAIClient();
|
|
|
|
|
var completionsOptions = new CompletionsOptions()
|
|
|
|
|
{
|
|
|
|
|
Prompts =
|
|
|
|
|
{
|
|
|
|
|
text
|
|
|
|
|
},
|
2023-08-09 21:49:55 +00:00
|
|
|
Temperature = 0.7f,
|
2023-08-07 10:21:31 +00:00
|
|
|
MaxTokens = 256
|
2023-06-17 02:42:35 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
var response = await client.GetCompletionsAsync(
|
2023-06-19 18:32:49 +00:00
|
|
|
deploymentOrModelName: _settings.DeploymentModel.TextCompletionModel,
|
2023-06-17 02:42:35 +00:00
|
|
|
completionsOptions);
|
|
|
|
|
|
|
|
|
|
// OpenAI
|
|
|
|
|
var completion = "";
|
|
|
|
|
foreach (var t in response.Value.Choices)
|
|
|
|
|
{
|
|
|
|
|
completion += t.Text;
|
|
|
|
|
};
|
|
|
|
|
|
2023-08-07 10:21:31 +00:00
|
|
|
_logger.LogInformation(text + completion);
|
|
|
|
|
|
2023-06-27 19:17:53 +00:00
|
|
|
return completion.Trim();
|
2023-06-17 02:42:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private OpenAIClient GetOpenAIClient()
|
|
|
|
|
{
|
|
|
|
|
OpenAIClient client = _useAzureOpenAI
|
|
|
|
|
? new OpenAIClient(
|
|
|
|
|
new Uri(_settings.Endpoint),
|
|
|
|
|
new AzureKeyCredential(_settings.ApiKey))
|
|
|
|
|
: new OpenAIClient("your-api-key-from-platform.openai.com");
|
|
|
|
|
return client;
|
|
|
|
|
}
|
|
|
|
|
}
|