BotSharp/src/Plugins/BotSharp.Plugin.FileHandler/Functions/ReadImageFn.cs

104 lines
3.9 KiB
C#
Raw Normal View History

2024-07-16 19:13:29 +00:00
namespace BotSharp.Plugin.FileHandler.Functions;
2024-06-06 18:30:39 +00:00
2024-07-16 19:13:29 +00:00
public class ReadImageFn : IFunctionCallback
2024-06-06 18:30:39 +00:00
{
2024-12-04 22:12:02 +00:00
public string Name => "util-file-read_image";
2024-07-16 19:13:29 +00:00
public string Indication => "Reading images";
2024-06-06 18:30:39 +00:00
private readonly IServiceProvider _services;
2024-07-16 19:13:29 +00:00
private readonly ILogger<ReadImageFn> _logger;
2024-06-06 18:30:39 +00:00
2024-07-16 19:13:29 +00:00
public ReadImageFn(
2024-06-06 18:30:39 +00:00
IServiceProvider services,
2024-07-16 19:13:29 +00:00
ILogger<ReadImageFn> logger)
2024-06-06 18:30:39 +00:00
{
_services = services;
_logger = logger;
}
public async Task<bool> Execute(RoleDialogModel message)
{
2024-07-16 19:13:29 +00:00
var args = JsonSerializer.Deserialize<LlmContextIn>(message.FunctionArgs);
2024-06-06 18:30:39 +00:00
var conv = _services.GetRequiredService<IConversationService>();
var agentService = _services.GetRequiredService<IAgentService>();
2024-07-16 19:13:29 +00:00
2024-06-06 18:30:39 +00:00
var wholeDialogs = conv.GetDialogHistory();
2024-12-12 23:20:27 +00:00
var dialogs = AssembleFiles(conv.ConversationId, args?.ImageUrls, wholeDialogs);
2024-12-12 23:22:11 +00:00
var agentId = !string.IsNullOrWhiteSpace(message.CurrentAgentId) ? message.CurrentAgentId : BuiltInAgentId.UtilityAssistant;
var agent = await agentService.LoadAgent(agentId);
2024-06-06 18:30:39 +00:00
var fileAgent = new Agent
{
2024-06-24 21:39:08 +00:00
Id = agent?.Id ?? Guid.Empty.ToString(),
Name = agent?.Name ?? "Unkown",
2024-07-16 19:13:29 +00:00
Instruction = !string.IsNullOrWhiteSpace(args?.UserRequest) ? args.UserRequest : "Please describe the image(s).",
2024-06-06 18:30:39 +00:00
TemplateDict = new Dictionary<string, object>()
};
var response = await GetChatCompletion(fileAgent, dialogs);
message.Content = response;
return true;
}
2024-12-12 23:20:27 +00:00
private List<RoleDialogModel> AssembleFiles(string conversationId, IEnumerable<string>? imageUrls, List<RoleDialogModel> dialogs)
2024-06-06 18:30:39 +00:00
{
if (dialogs.IsNullOrEmpty())
{
return new List<RoleDialogModel>();
}
2024-08-08 01:56:29 +00:00
var fileStorage = _services.GetRequiredService<IFileStorageService>();
2024-08-08 18:34:50 +00:00
var messageIds = dialogs.Select(x => x.MessageId).Distinct().ToList();
var images = fileStorage.GetMessageFiles(conversationId, messageIds, FileSourceType.User, new List<string>
{
MediaTypeNames.Image.Png,
MediaTypeNames.Image.Jpeg
});
2024-06-06 18:30:39 +00:00
foreach (var dialog in dialogs)
{
2024-07-16 19:13:29 +00:00
var found = images.Where(x => x.MessageId == dialog.MessageId).ToList();
2024-06-06 18:30:39 +00:00
if (found.IsNullOrEmpty()) continue;
dialog.Files = found.Select(x => new BotSharpFile
{
ContentType = x.ContentType,
2024-08-08 01:56:29 +00:00
FileUrl = x.FileUrl,
2024-06-06 18:30:39 +00:00
FileStorageUrl = x.FileStorageUrl
}).ToList();
}
2024-12-12 23:20:27 +00:00
if (!imageUrls.IsNullOrEmpty())
{
var lastDialog = dialogs.Last();
var files = lastDialog.Files ?? [];
var addnFiles = imageUrls.Select(x => x?.Trim())
.Where(x => !string.IsNullOrWhiteSpace(x))
.Select(x => new BotSharpFile { FileUrl = x }).ToList();
files.AddRange(addnFiles);
lastDialog.Files = files;
}
2024-06-06 18:30:39 +00:00
return dialogs;
}
private async Task<string> GetChatCompletion(Agent agent, List<RoleDialogModel> dialogs)
{
try
{
var llmProviderService = _services.GetRequiredService<ILlmProviderService>();
var provider = llmProviderService.GetProviders().FirstOrDefault(x => x == "openai");
var model = llmProviderService.GetProviderModel(provider: provider, id: "gpt-4", multiModal: true);
var completion = CompletionProvider.GetChatCompletion(_services, provider: provider, model: model.Name);
var response = await completion.GetChatCompletions(agent, dialogs);
return response.Content;
}
catch (Exception ex)
{
2024-07-16 19:13:29 +00:00
var error = $"Error when analyzing images.";
2024-07-16 22:09:54 +00:00
_logger.LogWarning($"{error} {ex.Message}\r\n{ex.InnerException}");
2024-06-06 18:30:39 +00:00
return error;
}
}
}