forked from getomni-ai/benchmark
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgemini.ts
More file actions
233 lines (192 loc) · 6.8 KB
/
gemini.ts
File metadata and controls
233 lines (192 loc) · 6.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
import { GoogleGenerativeAI } from '@google/generative-ai';
import { ModelProvider } from './base';
import {
IMAGE_EXTRACTION_SYSTEM_PROMPT,
JSON_EXTRACTION_SYSTEM_PROMPT,
OCR_SYSTEM_PROMPT,
} from './shared/prompt';
import { calculateTokenCost } from './shared/tokenCost';
import { getMimeType } from '../utils';
import { JsonSchema } from '../types';
export class GeminiProvider extends ModelProvider {
private client: GoogleGenerativeAI;
constructor(model: string) {
super(model);
const apiKey = process.env.GOOGLE_GENERATIVE_AI_API_KEY;
if (!apiKey) {
throw new Error('Missing required Google Generative AI configuration');
}
this.client = new GoogleGenerativeAI(apiKey);
}
async ocr(imagePath: string) {
try {
const start = performance.now();
const model = this.client.getGenerativeModel({
model: this.model,
generationConfig: { temperature: 0 },
});
// read image and convert to base64
const response = await fetch(imagePath);
const imageBuffer = await response.arrayBuffer();
const base64Image = Buffer.from(imageBuffer).toString('base64');
const imagePart = {
inlineData: {
data: base64Image,
mimeType: getMimeType(imagePath),
},
};
const ocrResult = await model.generateContent([OCR_SYSTEM_PROMPT, imagePart]);
const text = ocrResult.response.text();
const end = performance.now();
const ocrInputTokens = ocrResult.response.usageMetadata.promptTokenCount;
const ocrOutputTokens = ocrResult.response.usageMetadata.candidatesTokenCount;
const inputCost = calculateTokenCost(this.model, 'input', ocrInputTokens);
const outputCost = calculateTokenCost(this.model, 'output', ocrOutputTokens);
return {
text,
usage: {
duration: end - start,
inputTokens: ocrInputTokens,
outputTokens: ocrOutputTokens,
totalTokens: ocrInputTokens + ocrOutputTokens,
inputCost,
outputCost,
totalCost: inputCost + outputCost,
},
};
} catch (error) {
console.error('Google Generative AI OCR Error:', error);
throw error;
}
}
// FIXME: JSON output might not be 100% correct yet, because Gemini uses a subset of OpenAPI 3.0 schema
// https://sdk.vercel.ai/providers/ai-sdk-providers/google-generative-ai#schema-limitations
async extractFromText(text: string, schema: JsonSchema) {
const filteredSchema = this.convertSchemaForGemini(schema);
const start = performance.now();
const model = this.client.getGenerativeModel({
model: this.model,
generationConfig: {
temperature: 0,
responseMimeType: 'application/json',
responseSchema: filteredSchema,
},
});
const result = await model.generateContent([JSON_EXTRACTION_SYSTEM_PROMPT, text]);
const json = JSON.parse(result.response.text());
const end = performance.now();
const inputTokens = result.response.usageMetadata.promptTokenCount;
const outputTokens = result.response.usageMetadata.candidatesTokenCount;
const inputCost = calculateTokenCost(this.model, 'input', inputTokens);
const outputCost = calculateTokenCost(this.model, 'output', outputTokens);
return {
json,
usage: {
duration: end - start,
inputTokens,
outputTokens,
totalTokens: inputTokens + outputTokens,
inputCost,
outputCost,
totalCost: inputCost + outputCost,
},
};
}
// FIXME: JSON output might not be 100% correct yet, because Gemini uses a subset of OpenAPI 3.0 schema
// https://sdk.vercel.ai/providers/ai-sdk-providers/google-generative-ai#schema-limitations
async extractFromImage(imagePath: string, schema: JsonSchema) {
const filteredSchema = this.convertSchemaForGemini(schema);
// read image and convert to base64
const response = await fetch(imagePath);
const imageBuffer = await response.arrayBuffer();
const base64Image = Buffer.from(imageBuffer).toString('base64');
const start = performance.now();
const model = this.client.getGenerativeModel({
model: this.model,
generationConfig: {
temperature: 0,
responseMimeType: 'application/json',
responseSchema: filteredSchema,
},
});
const imagePart = {
inlineData: {
data: base64Image,
mimeType: getMimeType(imagePath),
},
};
const result = await model.generateContent([
IMAGE_EXTRACTION_SYSTEM_PROMPT,
imagePart,
]);
const json = JSON.parse(result.response.text());
const end = performance.now();
const inputTokens = result.response.usageMetadata.promptTokenCount;
const outputTokens = result.response.usageMetadata.candidatesTokenCount;
const inputCost = calculateTokenCost(this.model, 'input', inputTokens);
const outputCost = calculateTokenCost(this.model, 'output', outputTokens);
return {
json,
usage: {
duration: end - start,
inputTokens,
outputTokens,
totalTokens: inputTokens + outputTokens,
inputCost,
outputCost,
totalCost: inputCost + outputCost,
},
};
}
convertSchemaForGemini(schema) {
// Deep clone the schema to avoid modifying the original
const newSchema = JSON.parse(JSON.stringify(schema));
function processSchemaNode(node) {
if (!node || typeof node !== 'object') return node;
// Fix enum type definition
if (node.type === 'enum' && node.enum) {
node.type = 'string';
}
// Handle case where enum array exists but type isn't specified
if (node.enum && !node.type) {
node.type = 'string';
}
// Remove additionalProperties constraints
if ('additionalProperties' in node) {
delete node.additionalProperties;
}
// Handle 'not' validation keyword
if (node.not) {
if (node.not.type === 'null') {
delete node.not;
node.nullable = false;
} else {
processSchemaNode(node.not);
}
}
// Handle arrays
if (node.type === 'array' && node.items) {
// Move required fields to items level
if (node.required) {
if (!node.items.required) {
node.items.required = node.required;
} else {
node.items.required = [
...new Set([...node.items.required, ...node.required]),
];
}
delete node.required;
}
processSchemaNode(node.items);
}
// Handle objects with properties
if (node.properties) {
Object.entries(node.properties).forEach(([key, prop]) => {
node.properties[key] = processSchemaNode(prop);
});
}
return node;
}
return processSchemaNode(newSchema);
}
}