This repository was archived by the owner on Aug 21, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.ts
More file actions
179 lines (155 loc) · 6.52 KB
/
index.ts
File metadata and controls
179 lines (155 loc) · 6.52 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
import { AdminForthPlugin, Filters } from "adminforth";
import type { IAdminForth, IHttpServer, AdminForthResourcePages, AdminForthResourceColumn, AdminForthDataTypes, AdminForthResource } from "adminforth";
import type { PluginOptions } from './types.js';
import { json } from "stream/consumers";
import Handlebars from 'handlebars';
export default class BulkVisionPlugin extends AdminForthPlugin {
options: PluginOptions;
constructor(options: PluginOptions) {
super(options, import.meta.url);
this.options = options;
}
// Compile Handlebars templates in outputFields using record fields as context
private compileOutputFieldsTemplates(record: any): Record<string, string>[] {
return this.options.outputFields.map((fieldObj) => {
const compiled: Record<string, string> = {};
for (const [key, templateStr] of Object.entries(fieldObj)) {
try {
const tpl = Handlebars.compile(String(templateStr));
compiled[key] = tpl(record);
} catch {
compiled[key] = String(templateStr);
}
}
return compiled;
});
}
async modifyResourceConfig(adminforth: IAdminForth, resourceConfig: AdminForthResource) {
super.modifyResourceConfig(adminforth, resourceConfig);
//check if options names are provided
const columns = this.resourceConfig.columns;
let columnEnums = [];
for (const field of this.options.outputFields) {
for (const [key, value] of Object.entries(field)) {
const column = columns.find(c => c.name.toLowerCase() === key.toLowerCase());
if (column) {
if(column.enum){
(field 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,
});
}
} else {
throw new Error(`⚠️ No column found for key "${key}"`);
}
}
}
const pageInjection = {
file: this.componentPath('visionAction.vue'),
meta: {
pluginInstanceId: this.pluginInstanceId,
outputFields: this.options.outputFields,
actionName: this.options.actionName,
confirmMessage: this.options.confirmMessage,
columnEnums: columnEnums,
}
}
if (!this.resourceConfig.options.pageInjections) {
this.resourceConfig.options.pageInjections = {};
}
if (!this.resourceConfig.options.pageInjections.list) {
this.resourceConfig.options.pageInjections.list = {};
}
this.resourceConfig.options.pageInjections.list.threeDotsDropdownItems = [pageInjection];
}
validateConfigAfterDiscover(adminforth: IAdminForth, resourceConfig: AdminForthResource) {
// optional method where you can safely check field types after database discovery was performed
}
instanceUniqueRepresentation(pluginOptions: any) : string {
// optional method to return unique string representation of plugin instance.
// Needed if plugin can have multiple instances on one resource
return `single`;
}
setupEndpoints(server: IHttpServer) {
server.endpoint({
method: 'POST',
path: `/plugin/${this.pluginInstanceId}/analyze`,
handler: async ({ body, adminUser, headers }) => {
const selectedIds = body.selectedIds || [];
const tasks = selectedIds.map(async (ID) => {
// Fetch the record using the provided ID
const record = await this.adminforth.resource(this.resourceConfig.resourceId).get( [Filters.EQ('id', ID)] );
//recieve image URLs to analyze
const attachmentFiles = await this.options.attachFiles({ record: record });
//create prompt for OpenAI
const compiledOutputFields = this.compileOutputFieldsTemplates(record);
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.
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:`;
//send prompt to OpenAI and get response
const chatResponse = await this.options.adapter.generate({ prompt, inputFileUrls: attachmentFiles });
const resp: any = (chatResponse as any).response;
const topLevelError = (chatResponse as any).error;
if (topLevelError || resp?.error) {
throw new Error(`ERROR: ${JSON.stringify(topLevelError || resp?.error)}`);
}
const textOutput = resp?.output?.[0]?.content?.[0]?.text ?? resp?.output_text ?? resp?.choices?.[0]?.message?.content;
if (!textOutput || typeof textOutput !== 'string') {
throw new Error('Unexpected AI response format');
}
//parse response and update record
const resData = JSON.parse(textOutput);
return resData;
});
const result = await Promise.all(tasks);
return { result };
}
});
server.endpoint({
method: 'POST',
path: `/plugin/${this.pluginInstanceId}/get_records`,
handler: async ( body ) => {
let records = [];
for( const record of body.body.record ) {
records.push(await this.adminforth.resource(this.resourceConfig.resourceId).get( [Filters.EQ('id', record)] ));
records[records.length - 1]._label = this.resourceConfig.recordLabel(records[records.length - 1]);
}
return {
records,
};
}
});
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 ) {
images.push(await this.options.attachFiles({ record: record }));
}
}
return {
images,
};
}
});
server.endpoint({
method: 'POST',
path: `/plugin/${this.pluginInstanceId}/update_fields`,
handler: async ( body ) => {
const selectedIds = body.body.selectedIds || [];
const fieldsToUpdate = body.body.fields || {};
const updates = selectedIds.map((ID, idx) =>
this.adminforth
.resource(this.resourceConfig.resourceId)
.update(ID, fieldsToUpdate[idx])
);
await Promise.all(updates);
return { ok: true };
}
});
}
}