-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.ts
107 lines (93 loc) · 2.52 KB
/
main.ts
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
import OpenAI from 'openai';
import { config } from './config.js';
import { ImageGenerateParams } from 'openai/resources/index.js';
const API_KEY = 'API_KEY';
interface ConnectorResponse {
Completions: { Content: string | ErrorCompletion; TokenUsage: undefined }[];
ModelType: string;
}
interface ErrorCompletion {
choices: Array<{
message: {
content: string;
};
}>;
error: string;
model: string;
usage: undefined;
}
const mapToResponse = (
outputs: Array<string[] | ErrorCompletion>,
model: string,
): ConnectorResponse => {
return {
Completions: outputs.map((output) => {
if (Array.isArray(output)) {
return {
Content: output.join('\n\n'),
TokenUsage: undefined,
};
}
return {
Content: output,
TokenUsage: undefined,
Error: output.error,
};
}),
ModelType: model,
};
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const mapErrorToCompletion = (error: any, model: string): ErrorCompletion => {
const errorMessage = error.message || JSON.stringify(error);
return {
choices: [],
error: errorMessage,
model,
usage: undefined,
};
};
async function main(
model: string,
prompts: string[],
properties: Record<string, unknown>,
settings: Record<string, unknown>,
) {
const { size, style, n, quality, response_format } =
properties as unknown as ImageGenerateParams;
const openai = new OpenAI({
apiKey: settings?.[API_KEY] as string,
});
const total = prompts.length;
const outputs: Array<string[] | ErrorCompletion> = [];
try {
for (let index = 0; index < total; index++) {
try {
const userPrompt = prompts[index];
const imageResponse: OpenAI.Images.ImagesResponse =
await openai.images.generate({
model,
prompt: userPrompt,
n,
size,
style,
quality,
response_format,
});
const responseToMarkdown = imageResponse.data.map(
(res) => `![${res.revised_prompt || userPrompt}](${res.url})`,
);
console.log(responseToMarkdown);
outputs.push(responseToMarkdown);
} catch (error) {
const completionWithError = mapErrorToCompletion(error, model);
outputs.push(completionWithError);
}
}
return mapToResponse(outputs, model);
} catch (error) {
console.error('Error in main function:', error);
return { Error: error, ModelType: model };
}
}
export { main, config };