using BotSharp.Abstraction.Routing; namespace BotSharp.Plugin.FileHandler.Functions; public class ReadImageFn : IFunctionCallback { public string Name => "util-file-read_image"; public string Indication => "Reading images"; private readonly IServiceProvider _services; private readonly ILogger _logger; public ReadImageFn( IServiceProvider services, ILogger logger) { _services = services; _logger = logger; } public async Task Execute(RoleDialogModel message) { var args = JsonSerializer.Deserialize(message.FunctionArgs); var conv = _services.GetRequiredService(); var routingCtx = _services.GetRequiredService(); var agentService = _services.GetRequiredService(); Agent? fromAgent = null; if (!string.IsNullOrEmpty(message.CurrentAgentId)) { fromAgent = await agentService.GetAgent(message.CurrentAgentId); } var agent = new Agent { Id = BuiltInAgentId.UtilityAssistant, Name = "Utility Agent", Instruction = fromAgent?.Instruction ?? args?.UserRequest ?? "Please describe the image(s).", TemplateDict = new Dictionary() }; var wholeDialogs = routingCtx.GetDialogs(); if (wholeDialogs.IsNullOrEmpty()) { wholeDialogs = conv.GetDialogHistory(); } var dialogs = AssembleFiles(conv.ConversationId, args?.ImageUrls, wholeDialogs); var response = await GetChatCompletion(agent, dialogs); message.Content = response; return true; } private List AssembleFiles(string conversationId, IEnumerable? imageUrls, List dialogs) { if (dialogs.IsNullOrEmpty()) { return new List(); } var fileStorage = _services.GetRequiredService(); var messageIds = dialogs.Select(x => x.MessageId).Distinct().ToList(); var images = fileStorage.GetMessageFiles(conversationId, messageIds, FileSourceType.User, new List { MediaTypeNames.Image.Png, MediaTypeNames.Image.Jpeg }); foreach (var dialog in dialogs) { var found = images.Where(x => x.MessageId == dialog.MessageId).ToList(); if (found.IsNullOrEmpty()) continue; dialog.Files = found.Select(x => new BotSharpFile { ContentType = x.ContentType, FileUrl = x.FileUrl, FileStorageUrl = x.FileStorageUrl }).ToList(); } if (!imageUrls.IsNullOrEmpty()) { var lastDialog = dialogs.LastOrDefault(x => x.Role == AgentRole.User) ?? 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; } return dialogs; } private async Task GetChatCompletion(Agent agent, List dialogs) { try { var provider = "openai"; var model = "gpt-5-mini"; var completion = CompletionProvider.GetChatCompletion(_services, provider: provider, model: model); var response = await completion.GetChatCompletions(agent, dialogs); return response.Content; } catch (Exception ex) { var error = $"Error when analyzing images."; _logger.LogWarning(ex, $"{error}"); return error; } } }