-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
226 lines (203 loc) · 5.44 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
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
import Anthropic from '@anthropic-ai/sdk';
import { config } from './config.js';
import { sleep } from './utils';
import * as fs from 'node:fs';
import * as path from 'node:path';
const API_KEY = 'API_KEY';
interface TextMessageContent {
type: 'text';
text: string;
}
type MediaType = 'image/jpeg' | 'image/png' | 'image/webp' | 'image/gif';
interface ImageContent {
type: 'image';
source: {
type: 'base64';
media_type: MediaType;
data: string;
};
}
interface Message {
role: 'user' | 'assistant';
content: (TextMessageContent | ImageContent)[];
}
interface Completion {
Content: string | null;
TokenUsage: number | undefined;
}
interface ConnectorResponse {
Completions: Completion[];
ModelType: string;
}
interface ChatCompletion {
output: string;
stats: { model: string; inputTokens: number; outputTokens: number };
}
interface AnthropicResponse {
content: { text: string; type: string }[];
id: string;
model: string;
role: string;
stop_reason: string;
stop_sequence: string | null;
type: string;
usage: {
input_tokens: number;
output_tokens: number;
};
}
interface ErrorCompletion {
output: '';
error: string;
model: string;
usage: undefined;
}
const mapToResponse = (
outputs: (ChatCompletion | ErrorCompletion)[],
model: string,
): ConnectorResponse => {
return {
Completions: outputs.map((output) => {
if ('error' in output) {
return {
Content: null,
TokenUsage: undefined,
Error: output.error,
};
}
return {
Content: output.output,
TokenUsage: output.stats.inputTokens + output.stats.outputTokens,
};
}),
ModelType: outputs.length
? 'error' in outputs[0]
? model
: outputs[0].stats.model
: 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 {
output: '',
error: errorMessage,
model,
usage: undefined,
};
};
async function main(
model: string,
prompts: string[],
properties: Record<string, unknown>,
settings: Record<string, unknown>,
) {
const total = prompts.length;
const { prompt, ...restProperties } = properties;
const anthropic = new Anthropic({ apiKey: settings?.[API_KEY] as string });
const systemPrompt = (prompt ||
config.properties.find((prop) => prop.id === 'prompt')?.value) as string;
const messageHistory: Message[] = [];
const outputs: (ChatCompletion | ErrorCompletion)[] = [];
try {
for (let index = 0; index < total; index++) {
const userPrompt = prompts[index];
const imageUrls = extractImageUrls(userPrompt);
const messageContent: Message['content'] = [
{ type: 'text', text: userPrompt } as TextMessageContent,
];
for (const imageUrl of imageUrls) {
const base64Image = encodeImage(imageUrl);
messageContent.push({
type: 'image',
source: {
type: 'base64',
media_type: base64Image.ext,
data: base64Image.data,
},
} as ImageContent);
}
messageHistory.push({ role: 'user', content: messageContent });
let retries = 3; // Maximum number of retries
let response;
do {
try {
response = (await anthropic.messages.create({
model: model,
system: systemPrompt,
max_tokens: 4096,
messages: messageHistory,
...restProperties,
})) as AnthropicResponse;
// Process the successful response
const assistantResponse = response.content
.map((content) => content.text)
.join('\n');
const inputTokens = response.usage.input_tokens;
const outputTokens = response.usage.output_tokens;
messageHistory.push({
role: 'assistant',
content: [
{
type: 'text',
text: assistantResponse,
},
],
});
outputs.push({
output: assistantResponse,
stats: { model, inputTokens, outputTokens },
});
console.log(`Response to prompt: ${prompt}`, assistantResponse);
break; // Exit the loop on success
} catch (error) {
if (error.status === 429 && retries > 0) {
// Rate limit error: Wait and retry
console.warn('Rate limit exceeded, retrying...');
await sleep(3000); // Wait for 3 seconds
retries--;
} else {
const completionWithError = mapErrorToCompletion(error, model);
outputs.push(completionWithError);
// Other errors or retries exhausted
console.error('Error:', error);
throw error;
}
}
} while (retries > 0);
}
return mapToResponse(outputs, model);
} catch (error) {
console.error('Error in main function:', error);
throw error;
}
}
function encodeImage(imagePath: string): {
ext: MediaType;
data: string;
} {
const ext = path.extname(imagePath).slice(1);
const imageBuffer = fs.readFileSync(imagePath);
return {
ext: `image/${ext}` as MediaType,
data: imageBuffer.toString('base64'),
};
}
function extractImageUrls(prompt: string): string[] {
const imageExtensions = ['.png', '.jpeg', '.jpg', '.webp', '.gif'];
// Updated regex to match both http and local file paths
const urlRegex =
/(https?:\/\/[^\s]+|[a-zA-Z]:\\[^:<>"|?\n]*|\/[^:<>"|?\n]*)/g;
const urls = prompt.match(urlRegex) || [];
return urls.filter((url) => {
const extensionIndex = url.lastIndexOf('.');
if (extensionIndex === -1) {
// If no extension found, return false.
return false;
}
const extension = url.slice(extensionIndex);
return imageExtensions.includes(extension.toLowerCase());
});
}
export { main, config };