using BotSharp.Abstraction.Agents.Enums; using BotSharp.Abstraction.Files.Enums; using BotSharp.Abstraction.Files.Models; using BotSharp.Abstraction.Files; using BotSharp.Abstraction.MLTasks; using BotSharp.Core.Infrastructures; using Microsoft.Extensions.Logging; namespace BotSharp.Plugin.FileHandler.Functions; public class ReadPdfFn : IFunctionCallback { public string Name => "read_pdf"; public string Indication => "Reading pdf"; private readonly IServiceProvider _services; private readonly ILogger _logger; private const string DEFAULT_PDF = "pdf"; public ReadPdfFn( 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 agentService = _services.GetRequiredService(); var wholeDialogs = conv.GetDialogHistory(); var dialogs = await AssembleFiles(conv.ConversationId, wholeDialogs); var agent = await agentService.LoadAgent(BuiltInAgentId.UtilityAssistant); var fileAgent = new Agent { Id = agent?.Id ?? Guid.Empty.ToString(), Name = agent?.Name ?? "Unkown", Instruction = !string.IsNullOrWhiteSpace(args?.UserRequest) ? args.UserRequest : "Please describe the pdf file(s).", TemplateDict = new Dictionary() }; var response = await GetChatCompletion(fileAgent, dialogs); message.Content = response; return true; } private async Task> AssembleFiles(string conversationId, List dialogs) { if (dialogs.IsNullOrEmpty()) { return new List(); } var fileService = _services.GetRequiredService(); var files = await fileService.GetChatImages(conversationId, FileSourceType.User, new List { "pdf" }, dialogs); foreach (var dialog in dialogs) { var found = files.Where(x => x.MessageId == dialog.MessageId).ToList(); if (found.IsNullOrEmpty()) continue; dialog.Files = found.Select(x => new BotSharpFile { ContentType = x.ContentType, FileStorageUrl = x.FileStorageUrl }).ToList(); } return dialogs; } private async Task GetChatCompletion(Agent agent, List dialogs) { try { var llmProviderService = _services.GetRequiredService(); 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) { var error = $"Error when analyzing pdf file(s)."; _logger.LogWarning($"{error} {ex.Message}"); return error; } } }