forked from SciSharp/BotSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadImageFn.cs
More file actions
159 lines (134 loc) · 5.35 KB
/
ReadImageFn.cs
File metadata and controls
159 lines (134 loc) · 5.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
using BotSharp.Abstraction.Routing;
namespace BotSharp.Plugin.ImageHandler.Functions;
public class ReadImageFn : IFunctionCallback
{
public string Name => "util-image-read_image";
public string Indication => "Reading images";
private readonly IServiceProvider _services;
private readonly ILogger<ReadImageFn> _logger;
private readonly ImageHandlerSettings _settings;
private readonly IEnumerable<string> _imageContentTypes = new List<string>
{
MediaTypeNames.Image.Png,
MediaTypeNames.Image.Jpeg
};
public ReadImageFn(
IServiceProvider services,
ILogger<ReadImageFn> logger,
ImageHandlerSettings settings)
{
_services = services;
_logger = logger;
_settings = settings;
}
public async Task<bool> Execute(RoleDialogModel message)
{
var args = JsonSerializer.Deserialize<LlmContextIn>(message.FunctionArgs);
var agentService = _services.GetRequiredService<IAgentService>();
var conv = _services.GetRequiredService<IConversationService>();
var routingCtx = _services.GetRequiredService<IRoutingContext>();
var fromAgent = await agentService.GetAgent(message.CurrentAgentId);
var agent = new Agent
{
Id = fromAgent?.Id ?? BuiltInAgentId.FileAssistant,
Name = fromAgent?.Name ?? "File Assistant",
Instruction = fromAgent?.Instruction ?? args?.UserRequest ?? "Please describe the image(s).",
LlmConfig = fromAgent?.LlmConfig ?? new()
};
var wholeDialogs = routingCtx.GetDialogs();
if (wholeDialogs.IsNullOrEmpty())
{
wholeDialogs = await conv.GetDialogHistory();
}
var dialogs = AssembleFiles(conv.ConversationId, args?.ImageUrls, wholeDialogs);
var response = await GetChatCompletion(agent, dialogs);
dialogs.ForEach(x => x.Files = null);
message.Content = response;
return true;
}
private List<RoleDialogModel> AssembleFiles(string conversationId, IEnumerable<string>? imageUrls, List<RoleDialogModel> dialogs)
{
if (dialogs.IsNullOrEmpty())
{
return new List<RoleDialogModel>();
}
var fileStorage = _services.GetRequiredService<IFileStorageService>();
var messageIds = dialogs.Select(x => x.MessageId).Distinct().ToList();
var images = fileStorage.GetMessageFiles(conversationId, messageIds, options: new()
{
Sources = [FileSource.User, FileSource.Bot],
ContentTypes = _imageContentTypes
});
foreach (var dialog in dialogs)
{
var found = images.Where(x => x.MessageId == dialog.MessageId).ToList();
if (found.IsNullOrEmpty()) continue;
var targets = found;
if (dialog.IsFromUser)
{
targets = found.Where(x => x.FileSource.IsEqualTo(FileSource.User)).ToList();
}
else if (dialog.IsFromAssistant)
{
targets = found.Where(x => x.FileSource.IsEqualTo(FileSource.Bot)).ToList();
}
dialog.Files = targets.Select(x => new BotSharpFile
{
ContentType = x.ContentType,
FileUrl = x.FileUrl,
FileStorageUrl = x.FileStorageUrl,
FileName = x.FileName,
FileExtension = x.FileExtension
}).ToList();
}
if (!imageUrls.IsNullOrEmpty())
{
var lastDialog = dialogs.LastOrDefault(x => x.Role == AgentRole.User) ?? dialogs.Last();
lastDialog.Files ??= [];
var addnFiles = imageUrls.Select(x => x?.Trim())
.Where(x => !string.IsNullOrWhiteSpace(x))
.Select(x => new BotSharpFile { FileUrl = x }).ToList();
lastDialog.Files.AddRange(addnFiles);
}
return dialogs;
}
private async Task<string> GetChatCompletion(Agent agent, List<RoleDialogModel> dialogs)
{
try
{
var (provider, model) = GetLlmProviderModel();
SetImageDetailLevel();
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;
}
}
private (string, string) GetLlmProviderModel()
{
var provider = _settings?.Reading?.Provider;
var model = _settings?.Reading?.Model;
if (!string.IsNullOrEmpty(provider) && !string.IsNullOrEmpty(model))
{
return (provider, model);
}
provider = "openai";
model = "gpt-5-mini";
return (provider, model);
}
private void SetImageDetailLevel()
{
var state = _services.GetRequiredService<IConversationStateService>();
var key = "chat_image_detail_level";
var level = state.GetState(key);
if (string.IsNullOrWhiteSpace(level) && !string.IsNullOrWhiteSpace(_settings.Reading?.ImageDetailLevel))
{
state.SetState(key, _settings.Reading.ImageDetailLevel);
}
}
}