Repository navigation
Expand file tree
/
Copy pathvision.js
More file actions
203 lines (179 loc) · 7.69 KB
/
Copy pathvision.js
File metadata and controls
203 lines (179 loc) · 7.69 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
/**
* @module vision
* Shared Gemini Vision client for multi-modal payloads (Gemini 4 Argon ready).
*/
import { parseAIJson } from './json-parse.js';
import {
isGemini4Model,
normalizeThinkingLevel,
resolveMaxOutputTokens,
extractGeminiTextParts
} from './llm.js';
const GEMINI_BASE_URL = 'https://generativelanguage.googleapis.com/v1beta';
/**
* Send a prompt with one or more media files (image/video/pdf) to the Gemini model.
*
* @param {string} prompt - Instruction or prompt
* @param {string|null} [base64Data] - Primary Base64 encoded media data (optional when config.mediaItems is used)
* @param {string} [mimeType='image/png'] - MIME type of the primary media (e.g. image/png, image/jpeg, video/mp4)
* @param {object} [config={}] - Configuration
* @param {string} [config.apiKey] - Gemini API key (defaults to process.env.GEMINI_API_KEY)
* @param {string} [config.model='gemini-4-argon'] - Model name (defaults to gemini-4-argon; supports 'ARGON' and 'PRECISION' aliases)
* @param {Array<{base64Data: string, mimeType?: string, label?: string}>} [config.mediaItems] - Additional or multi-viewport media items
* @param {string} [config.mediaResolution] - e.g. 'high' or 'low'
* @param {number} [config.maxOutputTokens] - maximum output tokens
* @param {'low'|'medium'|'high'} [config.thinkingLevel] - thinking level for Gemini 4 models
* @param {boolean} [config.automaticContinuation=true] - Follow Gemini 4 continuationToken hops automatically
* @param {string} [config.continuationToken] - Initial continuation token to resume a long decode
* @param {number} [config.maxContinuationHops=8] - Maximum multi-hop continuation requests
* @param {object} [config.responseSchema] - Optional structured JSON schema
* @param {boolean} [config.returnFullResponse=false] - Return metadata, hops, and token usage alongside text
* @param {number} [config.timeoutMs] - request timeout in ms
* @returns {Promise<string|object>} text response (or full response object when config.returnFullResponse is true)
*/
export async function callGeminiMedia(prompt, base64Data, mimeType = 'image/png', config = {}) {
const apiKey = config.apiKey || process.env.GEMINI_API_KEY;
if (!apiKey) {
throw new Error('Gemini Vision: apiKey is required');
}
const modelName = config.model || 'gemini-4-argon';
// Support using "PRECISION", "ARGON", or other custom model aliases
const resolvedModel = modelName === 'PRECISION'
? 'gemini-2.5-pro'
: (modelName === 'ARGON' ? 'gemini-4-argon' : modelName);
const gemini4 = isGemini4Model(resolvedModel);
const timeoutMs = config.timeoutMs || (gemini4 ? 1200000 : 120000);
const baseUrl = config.apiUrl || GEMINI_BASE_URL;
const url = `${baseUrl}/models/${resolvedModel}:generateContent?key=${apiKey}`;
const inputParts = [{ text: prompt }];
if (base64Data) {
inputParts.push({
inlineData: {
mimeType: mimeType || 'image/png',
data: base64Data
}
});
}
if (Array.isArray(config.mediaItems)) {
for (const item of config.mediaItems) {
if (!item || !item.base64Data) continue;
if (item.label) {
inputParts.push({ text: `[Viewport: ${item.label}]` });
}
inputParts.push({
inlineData: {
mimeType: item.mimeType || 'image/png',
data: item.base64Data
}
});
}
}
const thinkingLevel = normalizeThinkingLevel(config.thinkingLevel, resolvedModel);
const maxOutputTokens = config.maxOutputTokens ?? resolveMaxOutputTokens(resolvedModel, {
...config,
maxTokens: config.maxOutputTokens ?? config.maxTokens
});
const generationConfig = {
...(!gemini4 && config.temperature != null ? { temperature: config.temperature } : {}),
...(maxOutputTokens ? { maxOutputTokens } : {}),
...(thinkingLevel ? { thinkingConfig: { thinkingLevel } } : {}),
...(config.responseSchema ? {
responseMimeType: 'application/json',
responseSchema: config.responseSchema
} : {})
};
const automaticContinuation = config.automaticContinuation !== false;
const maxHops = config.maxContinuationHops ?? 8;
let token = config.continuationToken || undefined;
const allParts = [];
let initialPromptTokens = undefined;
let inputTokens = 0;
let cachedTokens = 0;
let outputTokens = 0;
let thoughtTokens = 0;
let totalTokens = 0;
let finishReason = null;
let hops = 0;
while (hops < maxHops) {
hops += 1;
const payload = {
...(config.systemInstruction ? {
system_instruction: { parts: [{ text: config.systemInstruction }] }
} : {}),
contents: [
{
parts: inputParts
}
],
...(Object.keys(generationConfig).length > 0 ? { generationConfig } : {}),
...(token ? { continuationToken: token } : {})
};
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': apiKey
},
signal: AbortSignal.timeout(timeoutMs),
body: JSON.stringify(payload)
});
if (!response.ok) {
const errorBody = await response.text();
throw new Error(`Gemini Vision API ${response.status}: ${errorBody}`);
}
const data = await response.json();
const candidate = data.candidates?.[0];
if (candidate?.content?.parts) {
allParts.push(...candidate.content.parts);
}
const usageMeta = data.usageMetadata || {};
if (hops === 1 && usageMeta.promptTokenCount != null) {
initialPromptTokens = usageMeta.promptTokenCount;
}
inputTokens += usageMeta.promptTokenCount || 0;
cachedTokens += usageMeta.cachedContentTokenCount || 0;
outputTokens += usageMeta.candidatesTokenCount || 0;
thoughtTokens += usageMeta.thoughtsTokenCount || 0;
totalTokens += usageMeta.totalTokenCount || 0;
token = candidate?.continuationToken;
finishReason = candidate?.finishReason || null;
if (!automaticContinuation || finishReason !== 'CONTINUATION' || !token) {
break;
}
}
const text = extractGeminiTextParts(allParts).trim();
if (config.returnFullResponse) {
return {
text,
finishReason,
continuationToken: token || null,
hops,
model: resolvedModel,
usage: {
initialPromptTokens: initialPromptTokens ?? inputTokens,
inputTokens,
cachedTokens,
outputTokens,
thoughtTokens,
totalTokens: totalTokens || (inputTokens + outputTokens + thoughtTokens)
}
};
}
return text;
}
/**
* Send a prompt with media to Gemini Vision and parse the response as JSON.
*
* @param {string} prompt - Instruction or prompt requesting JSON output
* @param {string|null} [base64Data] - Primary Base64 encoded media data
* @param {string} [mimeType='image/png'] - MIME type of the media
* @param {object} [config={}] - Configuration passed to callGeminiMedia
* @returns {Promise<object|Array>} Parsed JSON object
*/
export async function callGeminiMediaJson(prompt, base64Data, mimeType = 'image/png', config = {}) {
const text = await callGeminiMedia(prompt, base64Data, mimeType, {
...config,
returnFullResponse: false
});
return parseAIJson(text, { allowPartial: true });
}