forked from devforth/adminforth-bulk-vision
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.ts
More file actions
1130 lines (1048 loc) · 49.8 KB
/
index.ts
File metadata and controls
1130 lines (1048 loc) · 49.8 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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { AdminForthFilterOperators, AdminForthPlugin, Filters } from "adminforth";
import type { IAdminForth, IHttpServer, AdminForthComponentDeclaration, AdminForthResource } from "adminforth";
import { suggestIfTypo, filtersTools } from "adminforth";
import type { PluginOptions } from './types.js';
import Handlebars from 'handlebars';
import { RateLimiter } from "adminforth";
import { randomUUID } from "crypto";
const STUB_MODE = false;
const jobs = new Map();
export default class BulkAiFlowPlugin extends AdminForthPlugin {
options: PluginOptions;
uploadPlugin: AdminForthPlugin;
totalCalls: number;
totalDuration: number;
rateLimiters: Record<string, RateLimiter> = {};
constructor(options: PluginOptions) {
super(options, import.meta.url);
this.options = options;
// for calculating average time
this.totalCalls = 0;
this.totalDuration = 0;
}
// Compile Handlebars templates in outputFields using record fields as context
private async compileTemplates<T extends Record<string, any>>(
source: T,
record: any,
valueSelector: (value: T[keyof T]) => string
): Promise<Record<string, string>> {
if (this.options.provideAdditionalContextForRecord) {
const additionalFields = await this.options.provideAdditionalContextForRecord({ record, adminUser: null, resource: this.resourceConfig });
record = { ...record, ...additionalFields };
}
const compiled: Record<string, string> = {};
for (const [key, value] of Object.entries(source)) {
const templateStr = valueSelector(value);
try {
const tpl = Handlebars.compile(templateStr);
compiled[key] = tpl(record);
} catch {
compiled[key] = templateStr;
}
}
return compiled;
}
private async compileOutputFieldsTemplates(record: any, customPrompt? : string) {
return await this.compileTemplates(customPrompt ? JSON.parse(customPrompt) :this.options.fillFieldsFromImages, record, v => String(v));
}
private async compileOutputFieldsTemplatesNoImage(record: any, customPrompt? : string) {
return await this.compileTemplates(customPrompt ? JSON.parse(customPrompt) : this.options.fillPlainFields, record, v => String(v));
}
private async compileGenerationFieldTemplates(record: any, customPrompt? : string) {
return await this.compileTemplates(customPrompt ? JSON.parse(customPrompt) : this.options.generateImages, record, v => String(customPrompt ? v : v.prompt));
}
private removeFromPromptFilledFields(compiledOutputFields: Record<string, string>, record: Record<string, any>): Record<string, string> {
const newCompiledOutputFields: Record<string, string> = {};
for (const [key, value] of Object.entries(record)) {
if (compiledOutputFields[key]) {
if (value !== null && value !== undefined && value !== '') {
continue;
}
newCompiledOutputFields[key] = compiledOutputFields[key];
}
}
return newCompiledOutputFields;
}
private async checkRateLimit(field: string, fieldNameRateLimit: string | undefined, headers: Record<string, string | string[] | undefined>): Promise<void | { error?: string; }> {
if (fieldNameRateLimit) {
// rate limit
// const { error } = RateLimiter.checkRateLimit(
// field,
// fieldNameRateLimit,
// this.adminforth.auth.getClientIp(headers),
// );
if (!this.rateLimiters[field]) {
this.rateLimiters[field] = new RateLimiter(fieldNameRateLimit);
}
if (!await this.rateLimiters[field].consume(`${field}-${this.adminforth.auth.getClientIp(headers)}`)) {
return { error: "Rate limit exceeded" };
}
}
}
private getPromptForImageAnalysis(compiledOutputFields: Record<string, string>) {
const prompt = `Analyze the following image(s) and return a single JSON in format like: {'param1': 'value1', 'param2': 'value2'}.
Do NOT return array of objects. Do NOT include any Markdown, code blocks, explanations, or extra text. Only return valid JSON.
Only return valid JSON. Do NOT wrap in \`\`\` or \`\`\`json. Do not add any extra text. Do not return prompt in response
Each object must contain the following fields: ${JSON.stringify(compiledOutputFields)} Use the exact field names. If it's number field - return only number.
Image URLs:`;
return prompt;
}
private getPromptForPlainFields(compiledOutputFields: Record<string, string>){
const prompt = `Generate the values of fields in object by using next prompts (key is field name, value is prompt):
${JSON.stringify(compiledOutputFields)} In output object use the same field names (keys) as in input.
Return a single valid passable JSON object in format like: {"meta_title": "generated_value"}.
Do NOT include any Markdown, code blocks, explanations, or extra text. Only return valid JSON.
Do NOT wrap in \`\`\` or \`\`\`json. Do not add any extra text. Do not return prompt in response`;
return prompt;
}
private async analyze_image(jobId: string, recordId: string, adminUser: any, headers: Record<string, string | string[] | undefined>, customPrompt? : string, filterFilledFields: boolean = true) {
const selectedId = recordId;
let isError = false;
// Fetch the record using the provided ID
const primaryKeyColumn = this.resourceConfig.columns.find((col) => col.primaryKey);
const record = await this.adminforth.resource(this.resourceConfig.resourceId).get([Filters.EQ(primaryKeyColumn.name, selectedId)] );
//recieve image URLs to analyze
const attachmentFiles = await this.options.attachFiles({ record: record });
if (STUB_MODE) {
await new Promise((resolve) => setTimeout(resolve, Math.floor(Math.random() * 8000) + 1000));
const fakeError = Math.random() < 0.5; // 50% chance of error
if (attachmentFiles.length === 0) {
jobs.set(jobId, { status: 'failed', error: 'No source images found' });
} else if (!fakeError) {
jobs.set(jobId, { status: 'completed', result: {} });
} else {
jobs.set(jobId, { status: 'failed', error: 'AI provider refused to analyze images' });
}
return {};
} else if (attachmentFiles.length !== 0) {
try {
for (const fileUrl of attachmentFiles) {
new URL(fileUrl);
}
} catch (e) {
jobs.set(jobId, { status: 'failed', error: 'One of the image URLs is not valid' });
return { ok: false, error: 'One of the image URLs is not valid' };
}
//create prompt for OpenAI
const compiledOutputFields = await this.compileOutputFieldsTemplates(record, customPrompt);
const filteredCompiledOutputFields = filterFilledFields ? this.removeFromPromptFilledFields(compiledOutputFields, record) : compiledOutputFields;
if (Object.keys(filteredCompiledOutputFields).length === 0) {
jobs.set(jobId, { status: 'completed', result: {} });
return { ok: true };
}
const prompt = this.getPromptForImageAnalysis(filteredCompiledOutputFields);
//send prompt to OpenAI and get response
let chatResponse;
try {
chatResponse = await this.options.visionAdapter.generate({ prompt, inputFileUrls: attachmentFiles });
} catch (e) {
isError = true;
jobs.set(jobId, { status: 'failed', error: 'AI provider refused to analyze images' });
return { ok: false, error: 'AI provider refused to analyze images' };
}
if (!isError) {
const resp: any = (chatResponse as any).response;
const topLevelError = (chatResponse as any).error;
if (topLevelError || resp?.error) {
jobs.set(jobId, { status: 'failed', error: `ERROR: ${JSON.stringify(topLevelError.message || resp?.error.message)}` });
return { ok: false, error: `ERROR: ${JSON.stringify(topLevelError.message || resp?.error.message)}` };
}
const textOutput = resp?.output?.[1]?.content?.[0]?.text ?? resp?.output?.[0]?.content?.[0]?.text ?? resp?.output_text ?? resp?.choices?.[0]?.message?.content ?? resp.output?.[0]?.content?.[1]?.text;
if (!textOutput || typeof textOutput !== 'string') {
jobs.set(jobId, { status: 'failed', error: 'Unexpected AI response format' });
}
//parse response and update record
let resData;
try {
resData = JSON.parse(textOutput);
} catch (e) {
jobs.set(jobId, { status: 'failed', error: 'AI response is not valid JSON. Probably attached invalid image URL', aiResponse: textOutput });
return { ok: false, error: 'AI response is not valid JSON. Probably attached invalid image URL', aiResponse: textOutput };
}
const result = resData;
jobs.set(jobId, { status: 'completed', result });
return { ok: true };
}
} else {
jobs.set(jobId, { status: 'failed', error: "No source images found" });
return { ok: false, error: "No source images found" };
}
}
private async analyzeNoImages(jobId: string, recordId: string, adminUser: any, headers: Record<string, string | string[] | undefined>, customPrompt? : string, filterFilledFields: boolean = true) {
const selectedId = recordId;
let isError = false;
if (STUB_MODE) {
const fakeError = Math.random() < 0.005; // 0.05% chance of error
// await new Promise((resolve) => setTimeout(resolve, Math.floor(Math.random() * 20000) + 1000));
if (fakeError) {
jobs.set(jobId, { status: 'failed', error: `ERROR: test error` });
return { ok: false, error: 'test error' };
} else {
jobs.set(jobId, { status: 'completed', result: {description: 'test description', price: 99999999, engine_power: 999} });
return { ok: true };
}
} else {
const primaryKeyColumn = this.resourceConfig.columns.find((col) => col.primaryKey);
const record = await this.adminforth.resource(this.resourceConfig.resourceId).get( [Filters.EQ(primaryKeyColumn.name, selectedId)] );
const compiledOutputFields = await this.compileOutputFieldsTemplatesNoImage(record, customPrompt);
const filteredCompiledOutputFields = filterFilledFields ? this.removeFromPromptFilledFields(compiledOutputFields, record) : compiledOutputFields;
if (Object.keys(filteredCompiledOutputFields).length === 0) {
jobs.set(jobId, { status: 'completed', result: {} });
return { ok: true };
}
const prompt = this.getPromptForPlainFields(filteredCompiledOutputFields);
//send prompt to OpenAI and get response
const numberOfTokens = this.options.fillPlainFieldsMaxTokens ? this.options.fillPlainFieldsMaxTokens : 1000;
let resp: any;
try {
const { content: chatResponse, error: topLevelError } = await this.options.textCompleteAdapter.complete(prompt, [], numberOfTokens);
// resp = (chatResponse as any).response;
if (topLevelError || resp?.error) {
isError = true;
jobs.set(jobId, { status: 'failed', error: `ERROR: ${JSON.stringify(topLevelError)}` });
return { ok: false, error: `ERROR: ${JSON.stringify(topLevelError)}` };
}
resp = chatResponse
} catch (e) {
isError = true;
jobs.set(jobId, { status: 'failed', error: `AI provider refused to fill fields: ${e}` });
return { ok: false, error: `AI provider refused to fill fields: ${e}` };
}
let resData;
try {
resData = JSON.parse(resp);
} catch (e) {
jobs.set(jobId, { status: 'failed', error: 'AI response is not valid JSON', aiResponse: resp });
return { ok: false, error: 'AI response is not valid JSON', aiResponse: resp };
}
const result = resData;
jobs.set(jobId, { status: 'completed', result });
return { ok: true };
}
}
private async initialImageGenerate(jobId: string, recordId: string, adminUser: any, headers: Record<string, string | string[] | undefined>, customPrompt? : string, filterFilledFields: boolean = true) {
const selectedId = recordId;
let isError = false;
const start = +new Date();
const record = await this.adminforth.resource(this.resourceConfig.resourceId).get([Filters.EQ(this.resourceConfig.columns.find(c => c.primaryKey)?.name, selectedId)]);
let attachmentFiles
if(!this.options.attachFiles){
attachmentFiles = [];
} else {
attachmentFiles = await this.options.attachFiles({ record });
try {
for (const fileUrl of attachmentFiles) {
new URL(fileUrl);
}
} catch (e) {
jobs.set(jobId, { status: 'failed', error: 'One of the image URLs is not valid' });
return { ok: false, error: 'One of the image URLs is not valid' };
}
}
const fieldTasks = Object.keys(this.options?.generateImages || {}).map(async (key) => {
if ( record[key] && filterFilledFields ) {
const plugin = this.adminforth.activatedPlugins.find(p =>
p.resourceConfig!.resourceId === this.resourceConfig.resourceId &&
p.pluginOptions.pathColumnName === key
);
const image_url = await plugin.pluginOptions.storageAdapter.getDownloadUrl(record[key]);
return {
key,
images: [image_url],
meta: {
skippedToNotOverwrite: true,
originalImage: image_url,
}
};
}
const prompt = (await this.compileGenerationFieldTemplates(record, customPrompt))[key];
let images;
if (this.options.attachFiles && attachmentFiles.length === 0) {
isError = true;
jobs.set(jobId, { status: 'failed', error: "No source images found" });
return { key, images: [] };
} else {
if (STUB_MODE) {
await new Promise((resolve) => setTimeout(resolve, Math.floor(Math.random() * 20000) + 1000));
const fakeError = Math.random() < 0.5; // 50% chance of error
if (!fakeError) {
images = `https://pic.re/image`;
} else {
isError = true;
jobs.set(jobId, { status: 'failed', error: 'AI provider refused to generate image' });
}
} else {
let generationAdapter;
if (this.options.generateImages[key].adapter) {
generationAdapter = this.options.generateImages[key].adapter;
} else {
generationAdapter = this.options.imageGenerationAdapter;
}
let resp;
try {
resp = await generationAdapter.generate(
{
prompt,
inputFiles: attachmentFiles,
n: 1,
size: this.options.generateImages[key].outputSize,
}
)
if (resp.error) {
isError = true;
jobs.set(jobId, { status: 'failed', error: `AI provider refused to generate image: ${JSON.stringify(resp.error)}` });
return { key, images: [] };
}
} catch (e) {
jobs.set(jobId, { status: 'failed', error: "AI provider refused to generate image" });
isError = true;
return { key, images: [] };
}
images = resp.imageURLs[0];
}
return { key, images };
}
});
const fieldResults = await Promise.all(fieldTasks);
const recordResult: Record<string, any> = {};
const recordMeta: Record<string, any> = {};
fieldResults.forEach(({ key, images, meta }) => {
recordResult[key] = images;
if (meta) {
recordMeta[`${key}_meta`] = meta;
}
});
const result = recordResult;
if (!isError) {
this.totalCalls++;
this.totalDuration += (+new Date() - start) / 1000;
jobs.set(jobId, { status: 'completed', result, recordMeta });
return { ok: true }
} else {
return { ok: false, error: 'Error during image generation' };
}
}
private async regenerateImage(jobId: string, recordId: string, fieldName: string, prompt: string, adminUser: any, headers: Record<string, string | string[] | undefined>) {
const Id = recordId;
let isError = false;
if (await this.checkRateLimit(fieldName, this.options.generateImages[fieldName].rateLimit, headers)) {
jobs.set(jobId, { status: 'failed', error: "Rate limit exceeded" });
return { error: "Rate limit exceeded" };
}
const start = +new Date();
const record = await this.adminforth.resource(this.resourceConfig.resourceId).get([Filters.EQ(this.resourceConfig.columns.find(c => c.primaryKey)?.name, Id)]);
let attachmentFiles
if(!this.options.attachFiles){
attachmentFiles = [];
} else {
attachmentFiles = await this.options.attachFiles({ record });
}
const images = await Promise.all(
(new Array(this.options.generateImages[fieldName].countToGenerate)).fill(0).map(async () => {
if (this.options.attachFiles && attachmentFiles.length === 0) {
isError = true;
jobs.set(jobId, { status: 'failed', error: "No source images found" });
return null;
}
if (STUB_MODE) {
await new Promise((resolve) => setTimeout(resolve, 2000));
jobs.set(jobId, { status: 'completed', result: {} });
return `https://pic.re/image`;
}
let generationAdapter;
if (this.options.generateImages[fieldName].adapter) {
generationAdapter = this.options.generateImages[fieldName].adapter;
} else {
generationAdapter = this.options.imageGenerationAdapter;
}
let resp;
try {
resp = await generationAdapter.generate(
{
prompt,
inputFiles: attachmentFiles,
n: 1,
size: this.options.generateImages[fieldName].outputSize,
}
)
if (resp.error) {
isError = true;
jobs.set(jobId, { status: 'failed', error: `AI provider refused to generate image: ${JSON.stringify(resp.error)}` });
return [];
}
} catch (e) {
jobs.set(jobId, { status: 'failed', error: "AI provider refused to generate image" });
isError = true;
return [];
}
return resp.imageURLs[0]
})
);
if (!isError) {
this.totalCalls++;
this.totalDuration += (+new Date() - start) / 1000;
jobs.set(jobId, { status: 'completed', result: { [fieldName]: images } });
return { ok: true };
} else {
return { ok: false, error: 'Error during image generation' };
}
}
private async regenerateCell(jobId, fieldToRegenerate, recordId, actionType, prompt) {
if (!fieldToRegenerate || !recordId || !actionType ) {
jobs.set(jobId, { status: 'failed', error: 'Missing parameters' });
//return { ok: false, error: "Missing parameters" };
}
if ( !prompt ) {
if (actionType === 'analyze') {
prompt = this.options.fillFieldsFromImages ? (this.options.fillFieldsFromImages as any)[fieldToRegenerate] : null;
} else if (actionType === 'analyze_no_images') {
prompt = this.options.fillPlainFields ? (this.options.fillPlainFields as any)[fieldToRegenerate] : null;
}
}
const primaryKeyColumn = this.resourceConfig.columns.find((col) => col.primaryKey);
const record = await this.adminforth.resource(this.resourceConfig.resourceId).get( [Filters.EQ(primaryKeyColumn.name, recordId)] );
let promptToPass = JSON.stringify({[fieldToRegenerate]: prompt});
if (STUB_MODE) {
await new Promise((resolve) => setTimeout(resolve, Math.floor(Math.random() * 20000) + 1000));
// return { ok: true, result: {[fieldToRegenerate]: "stub value"} };
jobs.set(jobId, { status: 'completed', result: {[fieldToRegenerate]: "stub value"} });
} else {
if ( actionType === 'analyze') {
const compiledPropmt = await this.compileOutputFieldsTemplates(record, promptToPass);
const finalPrompt = this.getPromptForImageAnalysis(compiledPropmt);
const attachmentFiles = await this.options.attachFiles({ record: record });
if (attachmentFiles.length === 0) {
// return { ok: false, error: "No source images found" };
jobs.set(jobId, { status: 'failed', error: "No source images found" });
}
let visionAdapterResponse;
try {
visionAdapterResponse = await this.options.visionAdapter.generate({ prompt: finalPrompt, inputFileUrls: attachmentFiles });
} catch (e) {
// return { ok: false, error: 'AI provider refused to analyze images' };
jobs.set(jobId, { status: 'failed', error: 'AI provider refused to analyze images' });
}
const resp: any = (visionAdapterResponse as any).response;
const topLevelError = (visionAdapterResponse as any).error;
if (topLevelError || resp?.error) {
// return { ok: false, error: `ERROR: ${JSON.stringify(topLevelError.message || resp?.error.message)}` };
jobs.set(jobId, { status: 'failed', error: `ERROR: ${JSON.stringify(topLevelError.message || resp?.error.message)}` });
}
const textOutput = resp?.output?.[0]?.content?.[0]?.text ?? resp?.output_text ?? resp?.choices?.[0]?.message?.content;
if (!textOutput || typeof textOutput !== 'string') {
// return { ok: false, error: 'AI response is not valid text' };
jobs.set(jobId, { status: 'failed', error: 'AI response is not valid text' });
}
let resData;
try {
resData = JSON.parse(textOutput);
} catch (e) {
jobs.set(jobId, { status: 'failed', error: 'AI response is not valid JSON. Probably attached invalid image URL', aiResponse: textOutput });
}
// return { ok: true, result: resData };
jobs.set(jobId, { status: 'completed', result: resData });
} else if ( actionType === 'analyze_no_images') {
const compiledPropmt = await this.compileOutputFieldsTemplatesNoImage(record, promptToPass);
const finalPrompt = this.getPromptForPlainFields(compiledPropmt);
const numberOfTokens = this.options.fillPlainFieldsMaxTokens ? this.options.fillPlainFieldsMaxTokens : 1000;
let resp;
try {
const { content: chatResponse, error: topLevelError } = await this.options.textCompleteAdapter.complete(finalPrompt, [], numberOfTokens);
if (topLevelError) {
// return { ok: false, error: `ERROR: ${JSON.stringify(topLevelError)}` };
jobs.set(jobId, { status: 'failed', error: `ERROR: ${JSON.stringify(topLevelError)}` });
}
resp = chatResponse;
} catch (e) {
// return { ok: false, error: 'AI provider refused to analyze plain fields' };
jobs.set(jobId, { status: 'failed', error: 'AI provider refused to analyze plain fields' });
}
let resData;
try {
resData = JSON.parse(resp);
} catch (e) {
jobs.set(jobId, { status: 'failed', error: 'AI response is not valid JSON', aiResponse: resp });
}
// return { ok: true, result: resData };
jobs.set(jobId, { status: 'completed', result: resData });
}
}
}
async modifyResourceConfig(adminforth: IAdminForth, resourceConfig: AdminForthResource) {
super.modifyResourceConfig(adminforth, resourceConfig);
//check if options names are provided
const columns = this.resourceConfig.columns;
let columnEnums = [];
if (this.options.fillFieldsFromImages) {
for (const [key, value] of Object.entries((this.options.fillFieldsFromImages ))) {
const column = columns.find(c => c.name.toLowerCase() === key.toLowerCase());
if (column && column.enum) {
(this.options.fillFieldsFromImages as any)[key] = `${value} Select ${key} from the list (USE ONLY VALUE FIELD. USE ONLY VALUES FROM THIS LIST): ${JSON.stringify(column.enum)}`;
columnEnums.push({
name: key,
enum: column.enum,
});
}
}
}
if (this.options.fillPlainFields) {
for (const [key, value] of Object.entries((this.options.fillPlainFields))) {
const column = columns.find(c => c.name.toLowerCase() === key.toLowerCase());
if (column && column.enum) {
(this.options.fillPlainFields as any)[key] = `${value} Select ${key} from the list (USE ONLY VALUE FIELD. USE ONLY VALUES FROM THIS LIST): ${JSON.stringify(column.enum)}`;
columnEnums.push({
name: key,
enum: column.enum,
});
}
}
}
const outputImageFields = [];
if (this.options.generateImages) {
for (const [key, value] of Object.entries(this.options.generateImages)) {
outputImageFields.push(key);
}
}
const outputPlainFields = [];
if (this.options.fillPlainFields) {
for (const [key, value] of Object.entries(this.options.fillPlainFields)) {
outputPlainFields.push(key);
}
}
const outputFieldsForAnalizeFromImages = [];
if (this.options.fillFieldsFromImages) {
for (const [key, value] of Object.entries(this.options.fillFieldsFromImages)) {
outputFieldsForAnalizeFromImages.push(key);
}
}
const outputImagesPluginInstanceIds = {};
//check if Upload plugin is installed on all attachment fields
if (this.options.generateImages) {
for (const [key, value] of Object.entries(this.options.generateImages)) {
const plugin = adminforth.activatedPlugins.find(p =>
p.resourceConfig!.resourceId === this.resourceConfig.resourceId &&
p.pluginOptions.pathColumnName === key
);
if (!plugin) {
throw new Error(`Plugin for attachment field '${key}' not found in resource '${this.resourceConfig.resourceId}', please check if Upload Plugin is installed on the field ${key}`);
}
if (!plugin.pluginOptions.storageAdapter.objectCanBeAccesedPublicly()) {
throw new Error(`Upload Plugin for attachment field '${key}' in resource '${this.resourceConfig.resourceId}'
uses adapter which is not configured to store objects in public way, so it will produce only signed private URLs which can not be used in HTML text of blog posts.
Please configure adapter in such way that it will store objects publicly (e.g. for S3 use 'public-read' ACL).
`);
}
outputImagesPluginInstanceIds[key] = plugin.pluginInstanceId;
}
}
const outputFields = {
...this.options.fillFieldsFromImages,
...this.options.fillPlainFields,
...(this.options.generateImages || {})
};
const primaryKeyColumn = this.resourceConfig.columns.find((col) => col.primaryKey);
// Map of column technical names to their display labels from resource config
const columnLabels: Record<string, string> = Object.fromEntries(
(this.resourceConfig.columns || []).map((c: any) => [c.name, c.label || c.name])
);
const pageInjection = {
file: this.componentPath('VisionAction.vue'),
meta: {
pluginInstanceId: this.pluginInstanceId,
outputFields: outputFields,
actionName: this.options.actionName,
columnEnums: columnEnums,
columnLabels: columnLabels,
outputImageFields: outputImageFields,
outputFieldsForAnalizeFromImages: outputFieldsForAnalizeFromImages,
outputPlainFields: outputPlainFields,
primaryKey: primaryKeyColumn.name,
outputImagesPluginInstanceIds: outputImagesPluginInstanceIds,
isFieldsForAnalizeFromImages: this.options.fillFieldsFromImages ? Object.keys(this.options.fillFieldsFromImages).length > 0 : false,
isFieldsForAnalizePlain: this.options.fillPlainFields ? Object.keys(this.options.fillPlainFields).length > 0 : false,
isImageGeneration: this.options.generateImages ? Object.keys(this.options.generateImages).length > 0 : false,
isAttachFiles: this.options.attachFiles ? true : false,
disabledWhenNoCheckboxes: this.options.recordSelector === 'filtered' ? false : true,
refreshRates: {
fillFieldsFromImages: this.options.refreshRates?.fillFieldsFromImages || 2_000,
fillPlainFields: this.options.refreshRates?.fillPlainFields || 1_000,
generateImages: this.options.refreshRates?.generateImages || 5_000,
regenerateImages: this.options.refreshRates?.regenerateImages || 5_000,
},
askConfirmationBeforeGenerating: this.options.askConfirmationBeforeGenerating || false,
concurrencyLimit: this.options.concurrencyLimit || 10,
recordSelector: this.options.recordSelector || 'checkbox',
askConfirmation: this.options.askConfirmation || [],
generationPrompts: {
plainFieldsPrompts: this.options.fillPlainFields || {},
imageFieldsPrompts: this.options.fillFieldsFromImages || {},
imageGenerationPrompts: this.options.generateImages || {},
}
}
}
if (!resourceConfig.options.pageInjections) {
resourceConfig.options.pageInjections = {};
}
if (!resourceConfig.options.pageInjections.list) {
resourceConfig.options.pageInjections.list = {};
}
if (!resourceConfig.options.pageInjections.list.threeDotsDropdownItems) {
resourceConfig.options.pageInjections.list.threeDotsDropdownItems = [];
}
(resourceConfig.options.pageInjections.list.threeDotsDropdownItems as AdminForthComponentDeclaration[]).push(pageInjection);
}
validateConfigAfterDiscover(adminforth: IAdminForth, resourceConfig: AdminForthResource) {
const columns = this.resourceConfig.columns;
if (this.options.fillFieldsFromImages) {
if (!this.options.attachFiles) {
throw new Error('⚠️ attachFiles function must be provided when fillFieldsFromImages is used');
}
if (!this.options.visionAdapter) {
throw new Error('⚠️ visionAdapter must be provided when fillFieldsFromImages is used');
}
for (const key of Object.keys(this.options.fillFieldsFromImages)) {
const column = columns.find(c => c.name.toLowerCase() === key.toLowerCase());
if (!column) {
throw new Error(`⚠️ No column found for key "${key}"`);
}
}
}
if (this.options.fillPlainFields) {
if (!this.options.textCompleteAdapter) {
throw new Error('⚠️ textCompleteAdapter must be provided when fillPlainFields is used');
}
for (const key of Object.keys(this.options.fillPlainFields)) {
const column = columns.find(c => c.name.toLowerCase() === key.toLowerCase());
if (!column) {
throw new Error(`⚠️ No column found for key "${key}"`);
}
}
}
if (this.options.generateImages) {
for (const key of Object.keys(this.options.generateImages)) {
const column = columns.find(c => c.name.toLowerCase() === key.toLowerCase());
if (!column) {
throw new Error(`⚠️ No column found for key "${key}"`);
}
const perKeyAdapter = this.options.generateImages[key].adapter;
if (!perKeyAdapter && !this.options.imageGenerationAdapter) {
throw new Error(`⚠️ No image generation adapter provided for key "${key}"`);
}
const plugin = adminforth.activatedPlugins.find(p =>
p.resourceConfig!.resourceId === this.resourceConfig.resourceId &&
p.pluginOptions.pathColumnName === key
);
if (!plugin) {
throw new Error(`Plugin for attachment field '${key}' not found in resource '${this.resourceConfig.resourceId}', please check if Upload Plugin is installed on the field ${key}`);
}
if (!plugin.pluginOptions || !plugin.pluginOptions.storageAdapter) {
throw new Error(`Upload Plugin for attachment field '${key}' in resource '${this.resourceConfig.resourceId}' is missing a storageAdapter configuration.`);
}
if (typeof plugin.pluginOptions.storageAdapter.objectCanBeAccesedPublicly !== 'function') {
throw new Error(`Upload Plugin for attachment field '${key}' in resource '${this.resourceConfig.resourceId}' uses a storage adapter without 'objectCanBeAccesedPublicly' method.`);
}
if (!plugin.pluginOptions.storageAdapter.objectCanBeAccesedPublicly()) {
throw new Error(`Upload Plugin for attachment field '${key}' in resource '${this.resourceConfig.resourceId}'
uses adapter which is not configured to store objects in public way, so it will produce only signed private URLs which can not be used in HTML text of blog posts.
Please configure adapter in such way that it will store objects publicly (e.g. for S3 use 'public-read' ACL).
`);
}
}
}
if ((this.options.fillFieldsFromImages || this.options.fillPlainFields || this.options.generateImages) && !this.options.provideAdditionalContextForRecord) {
let matches: string[] = [];
const regex = /{{(.*?)}}/g;
if (this.options.fillFieldsFromImages) {
for (const [key, value] of Object.entries((this.options.fillFieldsFromImages ))) {
const template = value;
const templateMatches = template.match(regex);
if (templateMatches) {
matches.push(...templateMatches);
}
}
}
if (this.options.fillPlainFields) {
for (const [key, value] of Object.entries((this.options.fillPlainFields))) {
const template = value;
const templateMatches = template.match(regex);
if (templateMatches) {
matches.push(...templateMatches);
}
}
}
if (this.options.generateImages) {
for (const [key, value] of Object.entries((this.options.generateImages ))) {
const template = value.prompt;
const templateMatches = template.match(regex);
if (templateMatches) {
matches.push(...templateMatches);
}
}
}
if (matches) {
matches.forEach((match) => {
const field = match.replace(/{{|}}/g, '').trim();
if (!resourceConfig.columns.find((column: any) => column.name === field)) {
const similar = suggestIfTypo(resourceConfig.columns.map((column: any) => column.name), field);
throw new Error(`Field "${field}" specified in generationPrompt not found in resource "${resourceConfig.label}". ${similar ? `Did you mean "${similar}"?` : ''}`);
} else {
let column = resourceConfig.columns.find((column: any) => column.name === field);
if (column.backendOnly === true) {
throw new Error(`Field "${field}" specified in generationPrompt is marked as backendOnly in resource "${resourceConfig.label}". Please remove backendOnly or choose another field.`);
}
}
});
}
}
}
instanceUniqueRepresentation(pluginOptions: any) : string {
return `${this.pluginOptions.actionName}`;
}
setupEndpoints(server: IHttpServer) {
server.endpoint({
method: 'POST',
path: `/plugin/${this.pluginInstanceId}/get_records`,
handler: async ( body ) => {
let records = [];
const primaryKeyColumn = this.resourceConfig.columns.find((col) => col.primaryKey);
records = await this.adminforth.resource(this.resourceConfig.resourceId).list([Filters.IN(primaryKeyColumn.name, body.body.record)]);
for( const [index, record] of records.entries() ) {
records[index]._label = this.resourceConfig.recordLabel(records[index]);
}
const order = Object.fromEntries(body.body.record.map((id, i) => [id, i]));
const sortedRecords = records.sort(
(a, b) => order[a.id] - order[b.id]
);
return {
records: sortedRecords,
};
}
});
server.endpoint({
method: 'POST',
path: `/plugin/${this.pluginInstanceId}/get_old_data`,
handler: async ({ body }) => {
const recordId = body.recordId;
if (recordId === undefined || recordId === null) {
return { ok: false, error: "Missing recordId" };
}
const primaryKeyColumn = this.resourceConfig.columns.find((col) => col.primaryKey);
const record = await this.adminforth.resource(this.resourceConfig.resourceId)
.get([Filters.EQ(primaryKeyColumn.name, recordId)]);
if (!record) {
return { ok: false, error: "Record not found" };
}
record._label = this.resourceConfig.recordLabel(record);
return { ok: true, record };
}
});
server.endpoint({
method: 'POST',
path: `/plugin/${this.pluginInstanceId}/get_images`,
handler: async ( body ) => {
let images = [];
if(body.body.record){
for( const record of body.body.record ) {
if (this.options.attachFiles) {
images.push(await this.options.attachFiles({ record: record }));
}
}
}
return {
images,
};
}
});
server.endpoint({
method: 'POST',
path: `/plugin/${this.pluginInstanceId}/update_fields`,
handler: async ({ body, adminUser, headers }) => {
let isAllowedToSave: any = { ok: true, error: '' };
if(this.options.isAllowedToSave) {
isAllowedToSave = await this.options.isAllowedToSave({ record: {}, adminUser: adminUser, resource: this.resourceConfig });
}
if (isAllowedToSave.ok !== false) {
const selectedIds = body.selectedIds || [];
const fieldsToUpdate = body.fields || {};
const saveImages = body.saveImages;
const outputImageFields = [];
if (this.options.generateImages) {
for (const [key, value] of Object.entries(this.options.generateImages)) {
outputImageFields.push(key);
}
}
const primaryKeyColumn = this.resourceConfig.columns.find((col) => col.primaryKey);
const decimalFieldsArray = this.resourceConfig.columns.filter(c => c.type === 'decimal').map(c => c.name);
const integerFieldsArray = this.resourceConfig.columns.filter(c => c.type === 'integer').map(c => c.name);
const floatFieldsArray = this.resourceConfig.columns.filter(c => c.type === 'float').map(c => c.name);
const updates = selectedIds.map(async (ID, idx) => {
const oldRecord = await this.adminforth.resource(this.resourceConfig.resourceId).get( [Filters.EQ(primaryKeyColumn.name, ID)] );
for (const [key, value] of Object.entries(outputImageFields)) {
const columnPlugin = this.adminforth.activatedPlugins.find(p =>
p.resourceConfig!.resourceId === this.resourceConfig.resourceId &&
p.pluginOptions.pathColumnName === value
);
if (columnPlugin && saveImages) {
if(columnPlugin.pluginOptions.storageAdapter.objectCanBeAccesedPublicly()) {
if (oldRecord[value]) {
// put tag to delete old file
try {
if (columnPlugin.pluginOptions.storageAdapter.markKeyForDeletion !== undefined) {
await columnPlugin.pluginOptions.storageAdapter.markKeyForDeletion(oldRecord[value]);
} else {
await columnPlugin.pluginOptions.storageAdapter.markKeyForDeletation(oldRecord[value]);
}
} catch (e) {
// file might be e.g. already deleted, so we catch error
console.error(`Error setting tag to true for object ${oldRecord[value]}. File will not be auto-cleaned up`);
}
}
if (fieldsToUpdate[idx][value] && fieldsToUpdate[idx][value] !== null) {
// remove tag from new file
// in this case we let it crash if it fails: this is a new file which just was uploaded.
if (columnPlugin.pluginOptions.storageAdapter.markKeyForNotDeletion !== undefined) {
await columnPlugin.pluginOptions.storageAdapter.markKeyForNotDeletion(fieldsToUpdate[idx][value]);
} else {
await columnPlugin.pluginOptions.storageAdapter.markKeyForNotDeletation(fieldsToUpdate[idx][value]);
}
}
}
}
}
// Convert decimal fields to numbers
if (decimalFieldsArray.length > 0) {
for (const fieldName of decimalFieldsArray) {
if (fieldsToUpdate[idx].hasOwnProperty(fieldName)) {
fieldsToUpdate[idx][fieldName] = `${fieldsToUpdate[idx][fieldName]}`;
}
}
}
if (integerFieldsArray.length > 0) {
for (const fieldName of integerFieldsArray) {
if (fieldsToUpdate[idx].hasOwnProperty(fieldName)) {
fieldsToUpdate[idx][fieldName] = parseInt(fieldsToUpdate[idx][fieldName], 10);
}
}
}
if (floatFieldsArray.length > 0) {
for (const fieldName of floatFieldsArray) {
if (fieldsToUpdate[idx].hasOwnProperty(fieldName)) {
fieldsToUpdate[idx][fieldName] = parseFloat(fieldsToUpdate[idx][fieldName]);
}
}
}
const newRecord = {
...oldRecord,
...fieldsToUpdate[idx]
};
return this.adminforth.updateResourceRecord({
resource: this.resourceConfig,
recordId: ID,
oldRecord: oldRecord,
updates: newRecord,
adminUser: adminUser,
})
});
try {
await Promise.all(updates);
} catch (error) {
return { ok: false, error: `Error updating records, because of unprocesseble data for record ID ${selectedIds}` };
}
return { ok: true };
} else {
return { ok: false, error: isAllowedToSave.error };
}
}
});
server.endpoint({
method: 'POST',
path: `/plugin/${this.pluginInstanceId}/get_image_generation_prompts`,
handler: async ({ body, headers }) => {
const Id = body.recordId || [];
const customPrompt = body.customPrompt || null;
const record = await this.adminforth.resource(this.resourceConfig.resourceId).get([Filters.EQ(this.resourceConfig.columns.find(c => c.primaryKey)?.name, Id)]);
const compiledGenerationOptions = await this.compileGenerationFieldTemplates(record, JSON.stringify({"prompt": customPrompt}));
return compiledGenerationOptions;
}
});
server.endpoint({
method: 'GET',
path: `/plugin/${this.pluginInstanceId}/averageDuration`,
handler: async () => {
return {
totalCalls: this.totalCalls,
totalDuration: this.totalDuration,
averageDuration: this.totalCalls ? this.totalDuration / this.totalCalls : null,
};
}
});
server.endpoint({
method: 'POST',
path: `/plugin/${this.pluginInstanceId}/create-job`,
handler: async ({ body, adminUser, headers }) => {
const { actionType, recordId, customPrompt, filterFilledFields } = body;
const jobId = randomUUID();
jobs.set(jobId, { status: "in_progress" });
if (!actionType) {
jobs.set(jobId, { status: "failed", error: "Missing action type" });
//return { error: "Missing action type" };
}
else if (!recordId && typeof recordId !== 'number') {
jobs.set(jobId, { status: "failed", error: "Missing record id" });
//return { error: "Missing record id" };
} else {
switch(actionType) {
case 'generate_images':
this.initialImageGenerate(jobId, recordId, adminUser, headers, customPrompt, filterFilledFields);
break;
case 'analyze_no_images':
this.analyzeNoImages(jobId, recordId, adminUser, headers, customPrompt, filterFilledFields);
break;
case 'analyze':
this.analyze_image(jobId, recordId, adminUser, headers, customPrompt, filterFilledFields);
break;
case 'regenerate_images':
if (!body.prompt || !body.fieldName) {
jobs.set(jobId, { status: "failed", error: "Missing prompt or field name" });
break;
}
this.regenerateImage(jobId, recordId, body.fieldName, body.prompt, adminUser, headers);
break;
case 'regenerate_cell':
const fieldToRegenerate = body.fieldToRegenerate;
this.regenerateCell(jobId, fieldToRegenerate, recordId, body.action, body.prompt);
break;
default:
jobs.set(jobId, { status: "failed", error: "Unknown action type" });
}
}
setTimeout(() => jobs.delete(jobId), 1_800_000);
setTimeout(() => jobs.set(jobId, { status: "failed", error: "Job timed out" }), 180_000);
return { ok: true, jobId };
}
});
server.endpoint({
method: 'POST',
path: `/plugin/${this.pluginInstanceId}/get-job-status`,
handler: async ({ body, adminUser, headers }) => {
const jobId = body.jobId;
if (!jobId) {