BotSharp/src/Plugins/BotSharp.Plugin.AzureOpenAI/Providers/ChatCompletionProvider.cs

278 lines
10 KiB
C#
Raw Normal View History

2023-06-17 02:42:35 +00:00
using Azure;
using Azure.AI.OpenAI;
2023-08-18 04:27:07 +00:00
using BotSharp.Abstraction.Agents.Enums;
2023-06-27 18:31:13 +00:00
using BotSharp.Abstraction.Agents.Models;
2023-09-14 01:41:51 +00:00
using BotSharp.Abstraction.Conversations;
2023-06-27 18:31:13 +00:00
using BotSharp.Abstraction.Conversations.Models;
2023-08-20 20:33:35 +00:00
using BotSharp.Abstraction.Conversations.Settings;
2023-06-19 18:32:49 +00:00
using BotSharp.Abstraction.MLTasks;
using BotSharp.Plugin.AzureOpenAI.Settings;
2023-08-20 20:33:35 +00:00
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
2023-06-17 02:42:35 +00:00
using System;
using System.Collections.Generic;
2023-08-07 22:37:32 +00:00
using System.Linq;
2023-06-17 02:42:35 +00:00
using System.Threading.Tasks;
2023-06-17 13:32:39 +00:00
namespace BotSharp.Plugin.AzureOpenAI.Providers;
2023-06-19 18:32:49 +00:00
public class ChatCompletionProvider : IChatCompletion
2023-06-17 02:42:35 +00:00
{
private readonly AzureOpenAiSettings _settings;
private readonly IServiceProvider _services;
private readonly ILogger _logger;
2023-10-16 20:07:07 +00:00
private string _model;
2023-06-17 02:42:35 +00:00
2023-10-08 20:46:42 +00:00
public string Provider => "azure-openai";
2023-09-09 15:37:38 +00:00
2023-08-20 20:33:35 +00:00
public ChatCompletionProvider(AzureOpenAiSettings settings,
ILogger<ChatCompletionProvider> logger,
2023-10-16 20:07:07 +00:00
IServiceProvider services)
2023-06-17 02:42:35 +00:00
{
_settings = settings;
_logger = logger;
2023-08-20 20:33:35 +00:00
_services = services;
2023-06-17 02:42:35 +00:00
}
public RoleDialogModel GetChatCompletions(Agent agent, List<RoleDialogModel> conversations)
{
2023-10-16 20:07:07 +00:00
var hooks = _services.GetServices<IContentGeneratingHook>().ToList();
// Before chat completion hook
Task.WaitAll(hooks.Select(hook =>
hook.BeforeGenerating(agent, conversations)).ToArray());
2023-10-09 22:28:17 +00:00
var (client, deploymentModel) = ProviderHelper.GetClient(_model, _settings);
var chatCompletionsOptions = PrepareOptions(agent, conversations);
var response = client.GetChatCompletions(deploymentModel, chatCompletionsOptions);
var choice = response.Value.Choices[0];
var message = choice.Message;
2023-10-16 20:07:07 +00:00
var msg = new RoleDialogModel(AgentRole.Assistant, message.Content)
{
2023-10-16 20:07:07 +00:00
CurrentAgentId = agent.Id
};
if (choice.FinishReason == CompletionsFinishReason.FunctionCall)
{
2023-10-09 22:28:17 +00:00
_logger.LogInformation($"[{agent.Name}]: {message.FunctionCall.Name}({message.FunctionCall.Arguments})");
2023-10-16 20:07:07 +00:00
msg = new RoleDialogModel(AgentRole.Function, message.Content)
{
CurrentAgentId = agent.Id,
FunctionName = message.FunctionCall.Name,
FunctionArgs = message.FunctionCall.Arguments
};
// Somethings LLM will generate a function name with agent name.
2023-10-16 20:07:07 +00:00
if (!string.IsNullOrEmpty(msg.FunctionName))
{
2023-10-16 20:07:07 +00:00
msg.FunctionName = msg.FunctionName.Split('.').Last();
}
}
2023-10-16 20:07:07 +00:00
// After chat completion hook
Task.WaitAll(hooks.Select(hook =>
hook.AfterGenerated(msg, new TokenStatsModel
{
2023-10-16 20:07:07 +00:00
Model = _model,
PromptCount = response.Value.Usage.PromptTokens,
CompletionCount = response.Value.Usage.CompletionTokens
})).ToArray());
2023-10-16 20:07:07 +00:00
return msg;
}
2023-08-18 04:27:07 +00:00
public async Task<bool> GetChatCompletionsAsync(Agent agent,
List<RoleDialogModel> conversations,
Func<RoleDialogModel, Task> onMessageReceived,
Func<RoleDialogModel, Task> onFunctionExecuting)
2023-07-27 21:56:57 +00:00
{
2023-10-16 20:07:07 +00:00
var hooks = _services.GetServices<IContentGeneratingHook>().ToList();
// Before chat completion hook
Task.WaitAll(hooks.Select(hook =>
hook.BeforeGenerating(agent, conversations)).ToArray());
2023-10-09 22:28:17 +00:00
var (client, deploymentModel) = ProviderHelper.GetClient(_model, _settings);
2023-07-27 21:56:57 +00:00
var chatCompletionsOptions = PrepareOptions(agent, conversations);
2023-09-09 15:37:38 +00:00
var response = await client.GetChatCompletionsAsync(deploymentModel, chatCompletionsOptions);
2023-07-27 21:56:57 +00:00
var choice = response.Value.Choices[0];
var message = choice.Message;
2023-10-16 20:07:07 +00:00
var msg = new RoleDialogModel(AgentRole.Assistant, message.Content)
2023-09-26 03:04:04 +00:00
{
2023-10-16 20:07:07 +00:00
CurrentAgentId = agent.Id
};
// After chat completion hook
Task.WaitAll(hooks.Select(hook =>
hook.AfterGenerated(msg, new TokenStatsModel
{
Model = _model,
PromptCount = response.Value.Usage.PromptTokens,
CompletionCount = response.Value.Usage.CompletionTokens
})).ToArray());
2023-09-04 02:21:53 +00:00
2023-07-27 21:56:57 +00:00
if (choice.FinishReason == CompletionsFinishReason.FunctionCall)
{
2023-10-09 22:28:17 +00:00
_logger.LogInformation($"[{agent.Name}]: {message.FunctionCall.Name}({message.FunctionCall.Arguments})");
2023-08-18 04:27:07 +00:00
var funcContextIn = new RoleDialogModel(AgentRole.Function, message.Content)
{
CurrentAgentId = agent.Id,
FunctionName = message.FunctionCall.Name,
2023-09-14 01:41:51 +00:00
FunctionArgs = message.FunctionCall.Arguments
2023-08-18 04:27:07 +00:00
};
2023-07-27 21:56:57 +00:00
// Somethings LLM will generate a function name with agent name.
if (!string.IsNullOrEmpty(funcContextIn.FunctionName))
{
funcContextIn.FunctionName = funcContextIn.FunctionName.Split('.').Last();
}
2023-08-18 04:27:07 +00:00
// Execute functions
await onFunctionExecuting(funcContextIn);
}
else
{
// Text response received
await onMessageReceived(msg);
2023-08-10 22:17:55 +00:00
}
2023-07-27 21:56:57 +00:00
return true;
}
public async Task<bool> GetChatCompletionsStreamingAsync(Agent agent, List<RoleDialogModel> conversations, Func<RoleDialogModel, Task> onMessageReceived)
2023-06-17 02:42:35 +00:00
{
var client = new OpenAIClient(new Uri(_settings.Endpoint), new AzureKeyCredential(_settings.ApiKey));
2023-06-27 18:31:13 +00:00
var chatCompletionsOptions = PrepareOptions(agent, conversations);
2023-06-17 02:42:35 +00:00
2023-06-19 18:32:49 +00:00
var response = await client.GetChatCompletionsStreamingAsync(_settings.DeploymentModel.ChatCompletionModel, chatCompletionsOptions);
2023-06-17 02:42:35 +00:00
using StreamingChatCompletions streaming = response.Value;
string output = "";
await foreach (var choice in streaming.GetChoicesStreaming())
{
if (choice.FinishReason == CompletionsFinishReason.FunctionCall)
{
2023-07-27 21:56:57 +00:00
var args = "";
await foreach (var message in choice.GetMessageStreaming())
{
if (message.FunctionCall == null || message.FunctionCall.Arguments == null)
continue;
Console.Write(message.FunctionCall.Arguments);
args += message.FunctionCall.Arguments;
}
await onMessageReceived(new RoleDialogModel(ChatRole.Assistant.ToString(), args));
continue;
}
2023-06-17 02:42:35 +00:00
await foreach (var message in choice.GetMessageStreaming())
{
if (message.Content == null)
continue;
Console.Write(message.Content);
output += message.Content;
_logger.LogInformation(message.Content);
await onMessageReceived(new RoleDialogModel(message.Role.ToString(), message.Content));
2023-06-17 02:42:35 +00:00
}
output = "";
2023-06-17 02:42:35 +00:00
}
return true;
2023-06-17 02:42:35 +00:00
}
2023-08-17 04:04:23 +00:00
2023-09-09 15:37:38 +00:00
protected ChatCompletionsOptions PrepareOptions(Agent agent, List<RoleDialogModel> conversations)
2023-06-17 02:42:35 +00:00
{
2023-06-29 23:14:57 +00:00
var chatCompletionsOptions = new ChatCompletionsOptions();
2023-08-17 04:04:23 +00:00
2023-06-29 23:14:57 +00:00
if (!string.IsNullOrEmpty(agent.Instruction))
2023-06-17 02:42:35 +00:00
{
2023-06-29 23:14:57 +00:00
chatCompletionsOptions.Messages.Add(new ChatMessage(ChatRole.System, agent.Instruction));
}
2023-06-17 02:42:35 +00:00
2023-06-29 23:14:57 +00:00
if (!string.IsNullOrEmpty(agent.Knowledges))
{
chatCompletionsOptions.Messages.Add(new ChatMessage(ChatRole.System, agent.Knowledges));
}
2023-10-09 22:28:17 +00:00
var samples = ProviderHelper.GetChatSamples(agent.Samples);
foreach (var message in samples)
2023-06-17 02:42:35 +00:00
{
2023-07-21 20:15:09 +00:00
chatCompletionsOptions.Messages.Add(new ChatMessage(message.Role, message.Content));
2023-06-17 02:42:35 +00:00
}
2023-09-27 20:49:44 +00:00
foreach (var function in agent.Functions)
2023-07-26 21:05:30 +00:00
{
chatCompletionsOptions.Functions.Add(new FunctionDefinition
{
Name = function.Name,
Description = function.Description,
Parameters = BinaryData.FromObjectAsJson(function.Parameters)
});
}
2023-06-17 02:42:35 +00:00
foreach (var message in conversations)
{
if (message.Role == ChatRole.Function)
{
chatCompletionsOptions.Messages.Add(new ChatMessage(message.Role, message.Content)
{
2023-08-07 22:37:32 +00:00
Name = message.FunctionName
});
}
else
{
chatCompletionsOptions.Messages.Add(new ChatMessage(message.Role, message.Content));
}
2023-06-17 02:42:35 +00:00
}
2023-08-17 04:04:23 +00:00
// https://community.openai.com/t/cheat-sheet-mastering-temperature-and-top-p-in-chatgpt-api-a-few-tips-and-tricks-on-controlling-the-creativity-deterministic-output-of-prompt-responses/172683
2023-09-14 01:41:51 +00:00
var state = _services.GetRequiredService<IConversationStateService>();
var temperature = float.Parse(state.GetState("temperature", "0.5"));
var samplingFactor = float.Parse(state.GetState("sampling_factor", "0.5"));
chatCompletionsOptions.Temperature = temperature;
chatCompletionsOptions.NucleusSamplingFactor = samplingFactor;
2023-09-23 21:33:05 +00:00
// chatCompletionsOptions.FrequencyPenalty = 0;
// chatCompletionsOptions.PresencePenalty = 0;
2023-08-17 04:04:23 +00:00
2023-08-20 20:33:35 +00:00
var convSetting = _services.GetRequiredService<ConversationSetting>();
if (convSetting.ShowVerboseLog)
2023-08-20 20:20:16 +00:00
{
2023-09-27 20:49:44 +00:00
_logger.LogInformation("VERBOSE COMPLETION MESSAGES");
2023-09-28 03:31:58 +00:00
var verbose = string.Join("\r\n", chatCompletionsOptions.Messages.Select(x =>
2023-08-20 20:20:16 +00:00
{
2023-08-20 20:33:35 +00:00
return x.Role == ChatRole.Function ?
2023-09-27 20:49:44 +00:00
$"{x.Role}: {x.Name} => {x.Content}" :
2023-08-20 20:33:35 +00:00
$"{x.Role}: {x.Content}";
}));
2023-09-23 21:33:05 +00:00
2023-08-20 20:33:35 +00:00
_logger.LogInformation(verbose);
2023-09-28 03:31:58 +00:00
_logger.LogInformation("VERBOSE FUNCTIONS");
verbose = string.Join("\r\n", chatCompletionsOptions.Functions.Select(x =>
{
return $"{x.Name}: {x.Description}\r\n{x.Parameters}";
}));
_logger.LogInformation(verbose);
2023-08-20 20:33:35 +00:00
}
2023-06-17 02:42:35 +00:00
return chatCompletionsOptions;
}
public void SetModelName(string model)
{
_model = model;
}
2023-06-17 02:42:35 +00:00
}