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

376 lines
15 KiB
C#
Raw Normal View History

2024-06-26 03:38:01 +00:00
using OpenAI.Chat;
2023-06-17 02:42:35 +00:00
2024-06-27 17:14:42 +00:00
namespace BotSharp.Plugin.AzureOpenAI.Providers.Chat;
2023-06-19 18:32:49 +00:00
public class ChatCompletionProvider : IChatCompletion
2023-06-17 02:42:35 +00:00
{
2024-03-25 23:14:14 +00:00
protected readonly AzureOpenAiSettings _settings;
protected readonly IServiceProvider _services;
protected readonly ILogger _logger;
2023-06-17 02:42:35 +00:00
2024-03-25 23:14:14 +00:00
protected string _model;
public virtual string Provider => "azure-openai";
2023-09-09 15:37:38 +00:00
2024-06-27 17:14:42 +00:00
public ChatCompletionProvider(AzureOpenAiSettings settings,
2023-08-20 20:33:35 +00:00
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
}
2024-01-14 04:48:26 +00:00
public async Task<RoleDialogModel> GetChatCompletions(Agent agent, List<RoleDialogModel> conversations)
{
2023-11-29 23:23:14 +00:00
var contentHooks = _services.GetServices<IContentGeneratingHook>().ToList();
2023-10-16 20:07:07 +00:00
// Before chat completion hook
2023-12-01 17:31:45 +00:00
foreach (var hook in contentHooks)
{
2024-01-14 04:48:26 +00:00
await hook.BeforeGenerating(agent, conversations);
2023-12-01 17:31:45 +00:00
}
2023-10-16 20:07:07 +00:00
2024-03-25 23:14:14 +00:00
var client = ProviderHelper.GetClient(Provider, _model, _services);
2024-06-26 03:38:01 +00:00
var chatClient = client.GetChatClient(_model);
var (prompt, messages, options) = PrepareOptions(agent, conversations);
2024-06-26 03:38:01 +00:00
var response = chatClient.CompleteChat(messages, options);
var value = response.Value;
var reason = value.FinishReason;
var content = value.Content;
2024-06-26 05:01:05 +00:00
var text = content.FirstOrDefault()?.Text ?? string.Empty;
2024-06-26 03:38:01 +00:00
RoleDialogModel responseMessage;
if (reason == ChatFinishReason.FunctionCall)
{
2024-06-26 05:01:05 +00:00
responseMessage = new RoleDialogModel(AgentRole.Function, text)
{
CurrentAgentId = agent.Id,
2023-10-30 16:48:18 +00:00
MessageId = conversations.Last().MessageId,
2024-06-26 03:38:01 +00:00
FunctionName = value.FunctionCall.FunctionName,
FunctionArgs = value.FunctionCall.FunctionArguments
};
// Somethings LLM will generate a function name with agent name.
2023-10-30 16:48:18 +00:00
if (!string.IsNullOrEmpty(responseMessage.FunctionName))
{
2023-10-30 16:48:18 +00:00
responseMessage.FunctionName = responseMessage.FunctionName.Split('.').Last();
}
}
2024-06-26 03:38:01 +00:00
else if (reason == ChatFinishReason.ToolCalls)
2024-05-02 22:07:12 +00:00
{
2024-06-26 03:38:01 +00:00
var toolCall = value.ToolCalls.FirstOrDefault();
2024-06-26 05:01:05 +00:00
responseMessage = new RoleDialogModel(AgentRole.Function, text)
2024-05-02 22:07:12 +00:00
{
CurrentAgentId = agent.Id,
MessageId = conversations.Last().MessageId,
2024-06-26 03:38:01 +00:00
FunctionName = toolCall?.FunctionName,
FunctionArgs = toolCall?.FunctionArguments
2024-05-02 22:07:12 +00:00
};
}
else
{
2024-06-26 05:01:05 +00:00
responseMessage = new RoleDialogModel(AgentRole.Assistant, text)
2024-05-02 22:07:12 +00:00
{
CurrentAgentId = agent.Id,
MessageId = conversations.Last().MessageId
};
}
2023-10-16 20:07:07 +00:00
// After chat completion hook
2024-06-27 17:14:42 +00:00
foreach (var hook in contentHooks)
2023-12-01 17:31:45 +00:00
{
2024-01-14 04:48:26 +00:00
await hook.AfterGenerated(responseMessage, new TokenStatsModel
{
2023-10-30 16:48:18 +00:00
Prompt = prompt,
2023-12-13 18:12:25 +00:00
Provider = Provider,
2023-10-16 20:07:07 +00:00
Model = _model,
2024-06-26 03:38:01 +00:00
PromptCount = response.Value.Usage.InputTokens,
CompletionCount = response.Value.Usage.OutputTokens
2024-01-14 04:48:26 +00:00
});
2023-12-01 17:31:45 +00:00
}
2023-10-30 16:48:18 +00:00
return responseMessage;
}
2024-06-27 17:14:42 +00:00
public async Task<bool> GetChatCompletionsAsync(Agent agent,
List<RoleDialogModel> conversations,
2023-08-18 04:27:07 +00:00
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
2023-12-01 17:31:45 +00:00
foreach (var hook in hooks)
{
await hook.BeforeGenerating(agent, conversations);
}
2023-10-16 20:07:07 +00:00
2024-03-25 23:14:14 +00:00
var client = ProviderHelper.GetClient(Provider, _model, _services);
2024-06-26 03:38:01 +00:00
var chatClient = client.GetChatClient(_model);
var (prompt, messages, options) = PrepareOptions(agent, conversations);
2023-07-27 21:56:57 +00:00
2024-06-26 03:38:01 +00:00
var response = await chatClient.CompleteChatAsync(messages, options);
var value = response.Value;
var reason = value.FinishReason;
var content = value.Content;
2024-06-26 05:01:05 +00:00
var text = content.FirstOrDefault()?.Text ?? string.Empty;
2023-07-27 21:56:57 +00:00
2024-06-26 05:01:05 +00:00
var msg = new RoleDialogModel(AgentRole.Assistant, text)
2023-09-26 03:04:04 +00:00
{
2023-10-16 20:07:07 +00:00
CurrentAgentId = agent.Id
};
// After chat completion hook
2023-12-01 17:31:45 +00:00
foreach (var hook in hooks)
{
await hook.AfterGenerated(msg, new TokenStatsModel
2023-10-16 20:07:07 +00:00
{
2023-10-30 16:48:18 +00:00
Prompt = prompt,
2023-12-13 18:12:25 +00:00
Provider = Provider,
2023-10-16 20:07:07 +00:00
Model = _model,
2024-06-26 03:38:01 +00:00
PromptCount = response.Value.Usage.InputTokens,
CompletionCount = response.Value.Usage.OutputTokens
2023-12-01 17:31:45 +00:00
});
}
2023-09-04 02:21:53 +00:00
2024-06-26 03:38:01 +00:00
if (reason == ChatFinishReason.FunctionCall)
2023-07-27 21:56:57 +00:00
{
2024-06-26 03:38:01 +00:00
_logger.LogInformation($"[{agent.Name}]: {value.FunctionCall.FunctionName}({value.FunctionCall.FunctionArguments})");
2024-06-26 05:01:05 +00:00
var funcContextIn = new RoleDialogModel(AgentRole.Function, text)
2023-08-18 04:27:07 +00:00
{
CurrentAgentId = agent.Id,
2024-06-27 17:14:42 +00:00
FunctionName = value.FunctionCall?.FunctionName,
FunctionArgs = value.FunctionCall?.FunctionArguments
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
{
2024-03-25 23:14:14 +00:00
var client = ProviderHelper.GetClient(Provider, _model, _services);
2024-06-26 03:38:01 +00:00
var chatClient = client.GetChatClient(_model);
var (prompt, messages, options) = PrepareOptions(agent, conversations);
var response = chatClient.CompleteChatStreamingAsync(messages, options);
2023-06-17 02:42:35 +00:00
2023-11-13 17:19:25 +00:00
await foreach (var choice in response)
2023-06-17 02:42:35 +00:00
{
2024-06-26 03:38:01 +00:00
if (choice.FinishReason == ChatFinishReason.FunctionCall)
{
2024-06-26 03:38:01 +00:00
Console.Write(choice.FunctionCallUpdate?.FunctionArgumentsUpdate);
2024-06-27 17:14:42 +00:00
2024-06-26 03:38:01 +00:00
await onMessageReceived(new RoleDialogModel(AgentRole.Assistant, choice.FunctionCallUpdate?.FunctionArgumentsUpdate));
2023-07-27 21:56:57 +00:00
continue;
}
2024-06-26 03:38:01 +00:00
if (choice.ContentUpdate.IsNullOrEmpty()) continue;
2024-06-26 05:01:05 +00:00
_logger.LogInformation(choice.ContentUpdate[0]?.Text);
2024-06-26 05:01:05 +00:00
await onMessageReceived(new RoleDialogModel(choice.Role.ToString(), choice.ContentUpdate[0]?.Text ?? string.Empty));
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
2024-06-26 03:38:01 +00:00
protected (string, IEnumerable<ChatMessage>, ChatCompletionOptions) PrepareOptions(Agent agent, List<RoleDialogModel> conversations)
2023-06-17 02:42:35 +00:00
{
2023-10-28 20:59:26 +00:00
var agentService = _services.GetRequiredService<IAgentService>();
2024-05-13 21:53:41 +00:00
var fileService = _services.GetRequiredService<IBotSharpFileService>();
var state = _services.GetRequiredService<IConversationStateService>();
var settingsService = _services.GetRequiredService<ILlmProviderService>();
var settings = settingsService.GetSetting(Provider, _model);
2024-05-14 16:51:39 +00:00
var allowMultiModal = settings != null && settings.MultiModal;
2024-05-13 21:53:41 +00:00
2024-06-26 03:38:01 +00:00
var messages = new List<ChatMessage>();
var temperature = float.Parse(state.GetState("temperature", "0.0"));
var maxTokens = int.Parse(state.GetState("max_tokens", "1024"));
var options = new ChatCompletionOptions()
{
Temperature = temperature,
MaxTokens = maxTokens
};
foreach (var function in agent.Functions)
{
if (!agentService.RenderFunction(agent, function)) continue;
var property = agentService.RenderFunctionProperty(agent, function);
options.Tools.Add(ChatTool.CreateFunctionTool(
functionName: function.Name,
functionDescription: function.Description,
functionParameters: BinaryData.FromObjectAsJson(property)));
}
2023-06-29 23:14:57 +00:00
if (!string.IsNullOrEmpty(agent.Instruction))
2023-06-17 02:42:35 +00:00
{
2023-10-28 20:59:26 +00:00
var instruction = agentService.RenderedInstruction(agent);
2024-06-26 03:38:01 +00:00
messages.Add(new SystemChatMessage(instruction));
2023-06-29 23:14:57 +00:00
}
2023-06-17 02:42:35 +00:00
2023-06-29 23:14:57 +00:00
if (!string.IsNullOrEmpty(agent.Knowledges))
{
2024-06-26 03:38:01 +00:00
messages.Add(new SystemChatMessage(agent.Knowledges));
2023-06-29 23:14:57 +00:00
}
2023-10-09 22:28:17 +00:00
var samples = ProviderHelper.GetChatSamples(agent.Samples);
2024-06-26 03:38:01 +00:00
foreach (var sample in samples)
2023-06-17 02:42:35 +00:00
{
2024-06-26 03:38:01 +00:00
messages.Add(sample.Role == AgentRole.User ? new UserChatMessage(sample.Content) : new AssistantChatMessage(sample.Content));
2023-07-26 21:05:30 +00:00
}
2023-06-17 02:42:35 +00:00
foreach (var message in conversations)
{
2024-06-26 03:38:01 +00:00
if (message.Role == AgentRole.Function)
{
2024-06-26 03:38:01 +00:00
messages.Add(new AssistantChatMessage(string.Empty)
2024-02-21 04:31:09 +00:00
{
2024-06-26 03:38:01 +00:00
FunctionCall = new ChatFunctionCall(message.FunctionName, message.FunctionArgs ?? string.Empty)
});
2024-06-26 03:38:01 +00:00
messages.Add(new FunctionChatMessage(message.FunctionName, message.Content));
2023-12-18 20:14:14 +00:00
}
2024-06-26 03:38:01 +00:00
else if (message.Role == AgentRole.User)
2023-12-18 20:14:14 +00:00
{
2024-05-11 03:04:59 +00:00
var text = !string.IsNullOrWhiteSpace(message.Payload) ? message.Payload : message.Content;
2024-06-26 04:45:52 +00:00
var textPart = ChatMessageContentPart.CreateTextMessageContentPart(text);
var chat = new UserChatMessage(textPart)
2024-06-26 03:38:01 +00:00
{
ParticipantName = message.FunctionName
};
2024-03-08 13:19:13 +00:00
2024-05-15 19:34:57 +00:00
if (allowMultiModal)
2024-03-08 13:19:13 +00:00
{
2024-05-15 19:34:57 +00:00
if (!message.Files.IsNullOrEmpty())
{
foreach (var file in message.Files)
2024-05-14 16:51:39 +00:00
{
2024-05-15 19:34:57 +00:00
if (!string.IsNullOrEmpty(file.FileUrl))
{
var uri = new Uri(file.FileUrl);
2024-06-26 03:38:01 +00:00
var contentPart = ChatMessageContentPart.CreateImageMessageContentPart(uri, ImageChatMessageContentPartDetail.Low);
2024-06-26 05:01:05 +00:00
chat = new UserChatMessage(textPart, contentPart) { ParticipantName = message.FunctionName };
2024-05-15 19:34:57 +00:00
}
else if (!string.IsNullOrEmpty(file.FileData))
{
var (contentType, bytes) = fileService.GetFileInfoFromData(file.FileData);
2024-06-26 03:38:01 +00:00
var contentPart = ChatMessageContentPart.CreateImageMessageContentPart(BinaryData.FromBytes(bytes), contentType, ImageChatMessageContentPartDetail.Low);
2024-06-26 05:01:05 +00:00
chat = new UserChatMessage(textPart, contentPart) { ParticipantName = message.FunctionName };
2024-05-15 19:34:57 +00:00
}
2024-06-06 18:30:39 +00:00
else if (!string.IsNullOrEmpty(file.FileStorageUrl))
{
2024-06-26 03:38:01 +00:00
var contentType = fileService.GetFileContentType(file.FileStorageUrl);
2024-06-06 18:30:39 +00:00
using var stream = File.OpenRead(file.FileStorageUrl);
2024-06-26 03:38:01 +00:00
var contentPart = ChatMessageContentPart.CreateImageMessageContentPart(BinaryData.FromStream(stream), contentType, ImageChatMessageContentPartDetail.Low);
2024-06-26 05:01:05 +00:00
chat = new UserChatMessage(textPart, contentPart) { ParticipantName = message.FunctionName };
2024-06-06 18:30:39 +00:00
}
2024-05-14 16:51:39 +00:00
}
}
2024-05-15 19:34:57 +00:00
}
2024-06-26 03:38:01 +00:00
messages.Add(chat);
}
2024-06-26 03:38:01 +00:00
else if (message.Role == AgentRole.Assistant)
{
2024-06-26 03:38:01 +00:00
messages.Add(new AssistantChatMessage(message.Content));
}
2023-06-17 02:42:35 +00:00
}
2024-06-26 03:38:01 +00:00
var prompt = GetPrompt(messages, options);
return (prompt, messages, options);
2023-10-30 16:48:18 +00:00
}
2024-06-26 03:38:01 +00:00
private string GetPrompt(IEnumerable<ChatMessage> messages, ChatCompletionOptions options)
2023-10-30 16:48:18 +00:00
{
var prompt = string.Empty;
2024-06-26 03:38:01 +00:00
if (!messages.IsNullOrEmpty())
2023-10-30 16:48:18 +00:00
{
// System instruction
2024-06-26 03:38:01 +00:00
var verbose = string.Join("\r\n", messages
.Select(x => x as SystemChatMessage)
.Where(x => x != null)
.Select(x =>
2023-10-30 16:48:18 +00:00
{
2024-06-26 03:38:01 +00:00
if (!string.IsNullOrEmpty(x.ParticipantName))
2024-01-24 23:47:57 +00:00
{
// To display Agent name in log
2024-06-26 05:01:05 +00:00
return $"[{x.ParticipantName}]: {x.Content.FirstOrDefault()?.Text ?? string.Empty}";
2024-01-24 23:47:57 +00:00
}
2024-06-26 05:01:05 +00:00
return $"{AgentRole.System}: {x.Content.FirstOrDefault()?.Text ?? string.Empty}";
2023-10-30 16:48:18 +00:00
}));
2023-11-01 01:48:12 +00:00
prompt += $"{verbose}\r\n";
2023-10-30 16:48:18 +00:00
2024-05-05 22:18:34 +00:00
prompt += "\r\n[CONVERSATION]";
2024-06-26 03:38:01 +00:00
verbose = string.Join("\r\n", messages
2024-06-27 17:14:42 +00:00
.Where(x => x as SystemChatMessage == null)
2024-06-26 03:38:01 +00:00
.Select(x =>
2023-10-20 03:47:14 +00:00
{
2024-06-26 03:38:01 +00:00
var fnMessage = x as FunctionChatMessage;
if (fnMessage != null)
2023-12-18 20:14:14 +00:00
{
2024-06-26 05:01:05 +00:00
return $"{AgentRole.Function}: {fnMessage.Content.FirstOrDefault()?.Text ?? string.Empty}";
2023-12-18 20:14:14 +00:00
}
2024-06-26 03:38:01 +00:00
var userMessage = x as UserChatMessage;
if (userMessage != null)
2023-12-18 20:14:14 +00:00
{
2024-06-26 05:01:05 +00:00
var content = x.Content.FirstOrDefault()?.Text ?? string.Empty;
2024-06-26 03:38:01 +00:00
return !string.IsNullOrEmpty(userMessage.ParticipantName) && userMessage.ParticipantName != "route_to_agent" ?
$"{userMessage.ParticipantName}: {content}" :
$"{AgentRole.User}: {content}";
2023-12-18 20:14:14 +00:00
}
2024-06-26 03:38:01 +00:00
var assistMessage = x as AssistantChatMessage;
if (assistMessage != null)
2023-12-18 20:14:14 +00:00
{
2024-06-26 03:38:01 +00:00
return assistMessage.FunctionCall != null ?
$"{AgentRole.Assistant}: Call function {assistMessage.FunctionCall.FunctionName}({assistMessage.FunctionCall.FunctionArguments})" :
2024-06-26 05:01:05 +00:00
$"{AgentRole.Assistant}: {assistMessage.Content.FirstOrDefault()?.Text ?? string.Empty}";
2023-12-18 20:14:14 +00:00
}
2024-06-26 03:38:01 +00:00
return string.Empty;
2023-10-20 03:47:14 +00:00
}));
2023-11-01 01:48:12 +00:00
prompt += $"\r\n{verbose}\r\n";
2023-10-30 16:48:18 +00:00
}
2023-09-28 03:31:58 +00:00
2024-06-26 03:38:01 +00:00
if (!options.Tools.IsNullOrEmpty())
2023-10-30 16:48:18 +00:00
{
2024-06-26 03:38:01 +00:00
var functions = string.Join("\r\n", options.Tools.Select(fn =>
2023-09-28 03:31:58 +00:00
{
2024-06-26 03:38:01 +00:00
return $"\r\n{fn.FunctionName}: {fn.FunctionDescription}\r\n{fn.FunctionParameters}";
2023-10-30 16:48:18 +00:00
}));
2024-05-05 22:18:34 +00:00
prompt += $"\r\n[FUNCTIONS]{functions}\r\n";
2023-08-20 20:33:35 +00:00
}
2023-10-30 16:48:18 +00:00
return prompt;
2023-06-17 02:42:35 +00:00
}
public void SetModelName(string model)
{
_model = model;
}
2023-06-17 02:42:35 +00:00
}