-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathopenai.ts
71 lines (61 loc) · 1.73 KB
/
openai.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
import OpenAI from 'openai';
import sharp from 'sharp';
import { ModelProvider } from './base';
import { Usage } from '../types';
import { calculateTokenCost, OCR_SYSTEM_PROMPT } from './shared';
export class OpenAIProvider extends ModelProvider {
private client: OpenAI;
constructor(model: string) {
super(model);
const apiKey = process.env.COMPATIBLE_OPENAI_API_KEY;
const baseURL = process.env.COMPATIBLE_OPENAI_BASE_URL;
if (!apiKey) {
throw new Error('Missing required API key');
}
this.client = new OpenAI({
baseURL,
apiKey,
});
}
async ocr(imagePath: string): Promise<{
text: string;
imageBase64s?: string[];
usage: Usage;
}> {
const start = performance.now();
const response = await this.client.chat.completions.create({
model: this.model,
messages: [
{
role: 'user',
content: [
{ type: 'text', text: OCR_SYSTEM_PROMPT },
{
type: 'image_url',
image_url: {
url: imagePath,
},
},
],
},
],
});
const end = performance.now();
const inputTokens = response.usage?.prompt_tokens || 0;
const outputTokens = response.usage?.completion_tokens || 0;
const inputCost = calculateTokenCost(this.model, 'input', inputTokens);
const outputCost = calculateTokenCost(this.model, 'output', outputTokens);
return {
text: response.choices[0].message.content || '',
usage: {
duration: end - start,
inputTokens,
outputTokens,
totalTokens: inputTokens + outputTokens,
inputCost,
outputCost,
totalCost: inputCost + outputCost,
},
};
}
}