@happyvertical/ai 0.79.0 → 0.80.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENT.md +1 -1
- package/dist/chunks/anthropic-DA8sdt12.js +438 -0
- package/dist/chunks/anthropic-DA8sdt12.js.map +1 -0
- package/dist/chunks/bedrock-DDiYFUw0.js +699 -0
- package/dist/chunks/bedrock-DDiYFUw0.js.map +1 -0
- package/dist/chunks/bifrost-fM9FpW_w.js +198 -0
- package/dist/chunks/bifrost-fM9FpW_w.js.map +1 -0
- package/dist/chunks/claude-cli-CnJh5KQT.js +498 -0
- package/dist/chunks/claude-cli-CnJh5KQT.js.map +1 -0
- package/dist/chunks/gateway-admin-CiKvHst7.js +283 -0
- package/dist/chunks/gateway-admin-CiKvHst7.js.map +1 -0
- package/dist/chunks/gemini-Bu7Fke7c.js +593 -0
- package/dist/chunks/gemini-Bu7Fke7c.js.map +1 -0
- package/dist/chunks/huggingface-B07_6wHW.js +295 -0
- package/dist/chunks/huggingface-B07_6wHW.js.map +1 -0
- package/dist/chunks/litellm-D_Oo9OQ_.js +185 -0
- package/dist/chunks/litellm-D_Oo9OQ_.js.map +1 -0
- package/dist/chunks/ollama-D4ksOTO8.js +626 -0
- package/dist/chunks/ollama-D4ksOTO8.js.map +1 -0
- package/dist/chunks/openai--F38QHiJ.js +691 -0
- package/dist/chunks/openai--F38QHiJ.js.map +1 -0
- package/dist/chunks/qwen-tts-DRRbOrhA.js +333 -0
- package/dist/chunks/qwen-tts-DRRbOrhA.js.map +1 -0
- package/dist/chunks/rate-limit-BwyPGXFW.js +199 -0
- package/dist/chunks/rate-limit-BwyPGXFW.js.map +1 -0
- package/dist/chunks/safety-CEnoJS6X.js +260 -0
- package/dist/chunks/safety-CEnoJS6X.js.map +1 -0
- package/dist/chunks/types-FHs-KbGL.js +117 -0
- package/dist/chunks/types-FHs-KbGL.js.map +1 -0
- package/dist/chunks/usage-C1Y1Nlg4.js +35 -0
- package/dist/chunks/usage-C1Y1Nlg4.js.map +1 -0
- package/dist/cli/claude-context.js +17 -17
- package/dist/cli/claude-context.js.map +1 -1
- package/dist/index.js +717 -23
- package/dist/index.js.map +1 -1
- package/metadata.json +1 -1
- package/package.json +5 -5
- package/dist/chunks/anthropic-2z-82zgr.js +0 -530
- package/dist/chunks/anthropic-2z-82zgr.js.map +0 -1
- package/dist/chunks/bedrock-Dc2eVPUD.js +0 -920
- package/dist/chunks/bedrock-Dc2eVPUD.js.map +0 -1
- package/dist/chunks/bifrost-CEnCsciy.js +0 -258
- package/dist/chunks/bifrost-CEnCsciy.js.map +0 -1
- package/dist/chunks/claude-cli-X1ONjE8K.js +0 -603
- package/dist/chunks/claude-cli-X1ONjE8K.js.map +0 -1
- package/dist/chunks/gateway-admin-BUhBzXZb.js +0 -359
- package/dist/chunks/gateway-admin-BUhBzXZb.js.map +0 -1
- package/dist/chunks/gemini-CS56gY0D.js +0 -768
- package/dist/chunks/gemini-CS56gY0D.js.map +0 -1
- package/dist/chunks/huggingface-wQSfO5xA.js +0 -411
- package/dist/chunks/huggingface-wQSfO5xA.js.map +0 -1
- package/dist/chunks/index-DCXO0nZA.js +0 -1293
- package/dist/chunks/index-DCXO0nZA.js.map +0 -1
- package/dist/chunks/litellm-BMFTYbWc.js +0 -245
- package/dist/chunks/litellm-BMFTYbWc.js.map +0 -1
- package/dist/chunks/ollama-DsGDrA-c.js +0 -962
- package/dist/chunks/ollama-DsGDrA-c.js.map +0 -1
- package/dist/chunks/openai-CJEo69jb.js +0 -882
- package/dist/chunks/openai-CJEo69jb.js.map +0 -1
- package/dist/chunks/qwen-tts-BLYZ6d9s.js +0 -365
- package/dist/chunks/qwen-tts-BLYZ6d9s.js.map +0 -1
- package/dist/chunks/usage-DMWiJ2oB.js +0 -21
- package/dist/chunks/usage-DMWiJ2oB.js.map +0 -1
|
@@ -0,0 +1,593 @@
|
|
|
1
|
+
import { c as extractTextContent, o as ModelNotFoundError, r as AuthenticationError, s as RateLimitError, t as AIError } from "./types-FHs-KbGL.js";
|
|
2
|
+
import { n as extractRetryAfterSeconds } from "./rate-limit-BwyPGXFW.js";
|
|
3
|
+
import { a as normalizeBaseAIOptions, c as prepareRequestControls, o as normalizeChatOptions, s as normalizeImageGenerationOptions } from "./safety-CEnoJS6X.js";
|
|
4
|
+
import { t as emitUsage } from "./usage-C1Y1Nlg4.js";
|
|
5
|
+
import crypto from "node:crypto";
|
|
6
|
+
//#region src/shared/providers/gemini.ts
|
|
7
|
+
/**
|
|
8
|
+
* Google Gemini provider implementation
|
|
9
|
+
*/
|
|
10
|
+
var GeminiProvider = class {
|
|
11
|
+
options;
|
|
12
|
+
client;
|
|
13
|
+
constructor(options) {
|
|
14
|
+
this.options = normalizeBaseAIOptions({
|
|
15
|
+
defaultModel: "gemini-2.5-flash",
|
|
16
|
+
...options
|
|
17
|
+
});
|
|
18
|
+
this.initializeClientSync();
|
|
19
|
+
}
|
|
20
|
+
initializeClientSync() {
|
|
21
|
+
try {
|
|
22
|
+
import("@google/genai").then(({ GoogleGenAI }) => {
|
|
23
|
+
this.client = new GoogleGenAI(this.buildClientConfig());
|
|
24
|
+
}).catch(() => {});
|
|
25
|
+
} catch (_error) {}
|
|
26
|
+
}
|
|
27
|
+
async ensureClient() {
|
|
28
|
+
if (!this.client) try {
|
|
29
|
+
const { GoogleGenAI } = await import("@google/genai");
|
|
30
|
+
this.client = new GoogleGenAI(this.buildClientConfig());
|
|
31
|
+
} catch (_error) {
|
|
32
|
+
throw new AIError("Failed to initialize Gemini client. Make sure @google/genai is installed.", "INITIALIZATION_ERROR", "gemini");
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Build the GoogleGenAI client configuration based on provided options.
|
|
37
|
+
* Supports both Google AI Studio (apiKey only) and Vertex AI (projectId + location).
|
|
38
|
+
*/
|
|
39
|
+
buildClientConfig() {
|
|
40
|
+
if (this.options.projectId && this.options.location) return {
|
|
41
|
+
vertexai: true,
|
|
42
|
+
project: this.options.projectId,
|
|
43
|
+
location: this.options.location,
|
|
44
|
+
apiKey: this.options.apiKey,
|
|
45
|
+
httpOptions: {
|
|
46
|
+
timeout: this.options.timeout,
|
|
47
|
+
retryOptions: { attempts: (this.options.maxRetries || 0) + 1 }
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
return {
|
|
51
|
+
apiKey: this.options.apiKey,
|
|
52
|
+
httpOptions: {
|
|
53
|
+
timeout: this.options.timeout,
|
|
54
|
+
retryOptions: { attempts: (this.options.maxRetries || 0) + 1 }
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
async chat(messages, options = {}) {
|
|
59
|
+
const startTime = Date.now();
|
|
60
|
+
let controls;
|
|
61
|
+
try {
|
|
62
|
+
await this.ensureClient();
|
|
63
|
+
const model = options.model || this.options.defaultModel;
|
|
64
|
+
options = normalizeChatOptions(this.options, options, "gemini", model);
|
|
65
|
+
controls = prepareRequestControls(this.options, options);
|
|
66
|
+
const requestConfig = {
|
|
67
|
+
model,
|
|
68
|
+
contents: this.messagesToGeminiFormat(messages),
|
|
69
|
+
config: this.buildGenerateContentConfig(options, controls)
|
|
70
|
+
};
|
|
71
|
+
const result = await this.client.models.generateContent(requestConfig);
|
|
72
|
+
let toolCalls;
|
|
73
|
+
const firstCandidate = result.candidates?.[0];
|
|
74
|
+
if (firstCandidate?.content?.parts) {
|
|
75
|
+
const functionCalls = firstCandidate.content.parts.filter((part) => part.functionCall);
|
|
76
|
+
if (functionCalls.length > 0) toolCalls = functionCalls.map((part) => ({
|
|
77
|
+
id: `call_${crypto.randomUUID()}`,
|
|
78
|
+
type: "function",
|
|
79
|
+
function: {
|
|
80
|
+
name: part.functionCall.name,
|
|
81
|
+
arguments: JSON.stringify(part.functionCall.args || {})
|
|
82
|
+
}
|
|
83
|
+
}));
|
|
84
|
+
}
|
|
85
|
+
let content = result.text || "";
|
|
86
|
+
if (options.responseFormat?.type === "json_object") content = this.stripMarkdownCodeBlock(content);
|
|
87
|
+
const usage = {
|
|
88
|
+
promptTokens: result.usageMetadata?.promptTokenCount || 0,
|
|
89
|
+
completionTokens: result.usageMetadata?.candidatesTokenCount || 0,
|
|
90
|
+
totalTokens: result.usageMetadata?.totalTokenCount || 0
|
|
91
|
+
};
|
|
92
|
+
emitUsage(this.options, "gemini", "chat", model, usage, startTime, options.usageTags);
|
|
93
|
+
return {
|
|
94
|
+
content,
|
|
95
|
+
model,
|
|
96
|
+
finishReason: this.mapFinishReason(result),
|
|
97
|
+
usage,
|
|
98
|
+
toolCalls: toolCalls && toolCalls.length > 0 ? toolCalls : void 0
|
|
99
|
+
};
|
|
100
|
+
} catch (error) {
|
|
101
|
+
if (controls?.didTimeout()) throw new AIError(`AI request timed out after ${controls.timeout}ms`, "AI_TIMEOUT", "gemini", options.model);
|
|
102
|
+
if (options.signal?.aborted) throw new AIError("AI request aborted by caller", "AI_ABORTED", "gemini", options.model);
|
|
103
|
+
throw this.mapError(error);
|
|
104
|
+
} finally {
|
|
105
|
+
controls?.cleanup();
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
async complete(prompt, options = {}) {
|
|
109
|
+
return this.chat([{
|
|
110
|
+
role: "user",
|
|
111
|
+
content: prompt
|
|
112
|
+
}], {
|
|
113
|
+
model: options.model,
|
|
114
|
+
maxTokens: options.maxTokens,
|
|
115
|
+
temperature: options.temperature,
|
|
116
|
+
topP: options.topP,
|
|
117
|
+
n: options.n,
|
|
118
|
+
stop: options.stop,
|
|
119
|
+
stream: options.stream,
|
|
120
|
+
onProgress: options.onProgress,
|
|
121
|
+
signal: options.signal,
|
|
122
|
+
timeout: options.timeout,
|
|
123
|
+
reasoning: options.reasoning,
|
|
124
|
+
usageTags: options.usageTags
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Simple message interface for single-turn interactions with optional history
|
|
129
|
+
*
|
|
130
|
+
* @param text - The message text to send
|
|
131
|
+
* @param options - Configuration options including history, model, etc.
|
|
132
|
+
* @returns Promise resolving to the response content string
|
|
133
|
+
*
|
|
134
|
+
* @example
|
|
135
|
+
* ```typescript
|
|
136
|
+
* // Simple usage
|
|
137
|
+
* const response = await provider.message('Hello!');
|
|
138
|
+
*
|
|
139
|
+
* // With history
|
|
140
|
+
* const response = await provider.message('What was my question?', {
|
|
141
|
+
* history: [
|
|
142
|
+
* { role: 'user', content: 'What is 2+2?' },
|
|
143
|
+
* { role: 'assistant', content: '4' }
|
|
144
|
+
* ]
|
|
145
|
+
* });
|
|
146
|
+
* ```
|
|
147
|
+
*/
|
|
148
|
+
async message(text, options = {}) {
|
|
149
|
+
const messages = [...options.history || [], {
|
|
150
|
+
role: options.role || "user",
|
|
151
|
+
content: text
|
|
152
|
+
}];
|
|
153
|
+
return (await this.chat(messages, {
|
|
154
|
+
model: options.model,
|
|
155
|
+
maxTokens: options.maxTokens,
|
|
156
|
+
temperature: options.temperature,
|
|
157
|
+
topP: options.topP,
|
|
158
|
+
stop: options.stop,
|
|
159
|
+
stream: options.stream,
|
|
160
|
+
frequencyPenalty: options.frequencyPenalty,
|
|
161
|
+
presencePenalty: options.presencePenalty,
|
|
162
|
+
responseFormat: options.responseFormat,
|
|
163
|
+
seed: options.seed,
|
|
164
|
+
tools: options.tools,
|
|
165
|
+
toolChoice: options.toolChoice,
|
|
166
|
+
onProgress: options.onProgress,
|
|
167
|
+
signal: options.signal,
|
|
168
|
+
timeout: options.timeout,
|
|
169
|
+
reasoning: options.reasoning,
|
|
170
|
+
usageTags: options.usageTags
|
|
171
|
+
})).content;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Generate embeddings for text using Gemini embedding models
|
|
175
|
+
* @param text - Single text string or array of texts to embed
|
|
176
|
+
* @param options - Optional configuration for embeddings
|
|
177
|
+
* @returns Promise resolving to embeddings response
|
|
178
|
+
*
|
|
179
|
+
* @example
|
|
180
|
+
* ```typescript
|
|
181
|
+
* const embedding = await provider.embed('Hello world');
|
|
182
|
+
* const embeddings = await provider.embed(['Text 1', 'Text 2']);
|
|
183
|
+
* ```
|
|
184
|
+
*/
|
|
185
|
+
async embed(text, options = {}) {
|
|
186
|
+
const startTime = Date.now();
|
|
187
|
+
try {
|
|
188
|
+
await this.ensureClient();
|
|
189
|
+
const model = options.model || "text-embedding-004";
|
|
190
|
+
const input = Array.isArray(text) ? text : [text];
|
|
191
|
+
const embeddings = [];
|
|
192
|
+
let totalTokens = 0;
|
|
193
|
+
for (const content of input) {
|
|
194
|
+
const config = {};
|
|
195
|
+
if (options.dimensions) config.outputDimensionality = options.dimensions;
|
|
196
|
+
const result = await this.client.models.embedContent({
|
|
197
|
+
model,
|
|
198
|
+
contents: content,
|
|
199
|
+
config: Object.keys(config).length > 0 ? config : void 0
|
|
200
|
+
});
|
|
201
|
+
if (result.embeddings?.[0]?.values) embeddings.push(result.embeddings[0].values);
|
|
202
|
+
if (result.metadata?.tokenCount) totalTokens += result.metadata.tokenCount;
|
|
203
|
+
}
|
|
204
|
+
const usage = totalTokens > 0 ? {
|
|
205
|
+
promptTokens: totalTokens,
|
|
206
|
+
completionTokens: 0,
|
|
207
|
+
totalTokens
|
|
208
|
+
} : void 0;
|
|
209
|
+
emitUsage(this.options, "gemini", "embed", model, usage, startTime, options.usageTags);
|
|
210
|
+
return {
|
|
211
|
+
embeddings,
|
|
212
|
+
model,
|
|
213
|
+
usage
|
|
214
|
+
};
|
|
215
|
+
} catch (error) {
|
|
216
|
+
throw this.mapError(error);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Convert an image to Gemini inline format
|
|
221
|
+
* @param image - Image as URL, base64 data URL, or Buffer
|
|
222
|
+
* @returns Gemini inline data format
|
|
223
|
+
* @private
|
|
224
|
+
*/
|
|
225
|
+
async imageToGeminiFormat(image, signal) {
|
|
226
|
+
let mimeType = "image/png";
|
|
227
|
+
let base64Data;
|
|
228
|
+
if (Buffer.isBuffer(image)) base64Data = image.toString("base64");
|
|
229
|
+
else if (image.startsWith("data:")) {
|
|
230
|
+
const match = image.match(/^data:([^;]+);base64,(.+)$/);
|
|
231
|
+
if (match) {
|
|
232
|
+
mimeType = match[1];
|
|
233
|
+
base64Data = match[2];
|
|
234
|
+
} else throw new AIError("Invalid base64 data URL format", "INVALID_INPUT", "gemini");
|
|
235
|
+
} else {
|
|
236
|
+
const response = await fetch(image, { signal });
|
|
237
|
+
if (!response.ok) throw new AIError(`Failed to fetch image: ${response.status} ${response.statusText}`, "IMAGE_FETCH_ERROR", "gemini");
|
|
238
|
+
const arrayBuffer = await response.arrayBuffer();
|
|
239
|
+
base64Data = Buffer.from(arrayBuffer).toString("base64");
|
|
240
|
+
mimeType = response.headers.get("content-type") || "image/png";
|
|
241
|
+
}
|
|
242
|
+
return { inlineData: {
|
|
243
|
+
mimeType,
|
|
244
|
+
data: base64Data
|
|
245
|
+
} };
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Generate a text description of an image
|
|
249
|
+
* @param image - Image as URL, base64 data URL, or Buffer
|
|
250
|
+
* @param prompt - Custom prompt for description (optional)
|
|
251
|
+
* @param options - Optional configuration
|
|
252
|
+
* @returns Promise resolving to the description string
|
|
253
|
+
*
|
|
254
|
+
* @example
|
|
255
|
+
* ```typescript
|
|
256
|
+
* const description = await provider.describeImage('https://example.com/image.jpg');
|
|
257
|
+
* ```
|
|
258
|
+
*/
|
|
259
|
+
async describeImage(image, prompt, options = {}) {
|
|
260
|
+
let controls;
|
|
261
|
+
try {
|
|
262
|
+
await this.ensureClient();
|
|
263
|
+
const defaultPrompt = "Describe this image for a search index. Include objects, mood, lighting, and any visible text.";
|
|
264
|
+
const model = options.model || this.options.defaultModel || "gemini-2.5-flash";
|
|
265
|
+
const normalized = normalizeChatOptions(this.options, {
|
|
266
|
+
...options,
|
|
267
|
+
maxTokens: options.maxTokens ?? 500
|
|
268
|
+
}, "gemini", model);
|
|
269
|
+
controls = prepareRequestControls(this.options, normalized);
|
|
270
|
+
const imageData = await this.imageToGeminiFormat(image, controls.signal);
|
|
271
|
+
return (await this.client.models.generateContent({
|
|
272
|
+
model,
|
|
273
|
+
contents: [{ text: prompt || defaultPrompt }, imageData],
|
|
274
|
+
config: this.buildGenerateContentConfig(normalized, controls)
|
|
275
|
+
})).text || "";
|
|
276
|
+
} catch (error) {
|
|
277
|
+
if (controls?.didTimeout()) throw new AIError(`AI request timed out after ${controls.timeout}ms`, "AI_TIMEOUT", "gemini", options.model);
|
|
278
|
+
if (options.signal?.aborted) throw new AIError("AI request aborted by caller", "AI_ABORTED", "gemini", options.model);
|
|
279
|
+
throw this.mapError(error);
|
|
280
|
+
} finally {
|
|
281
|
+
controls?.cleanup();
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* Generate embeddings for an image using native multimodal embeddings
|
|
286
|
+
* @param image - Image as URL, base64 data URL, or Buffer
|
|
287
|
+
* @param options - Optional configuration for image embeddings
|
|
288
|
+
* @returns Promise resolving to embeddings response
|
|
289
|
+
*
|
|
290
|
+
* @example
|
|
291
|
+
* ```typescript
|
|
292
|
+
* const embedding = await provider.embedImage('https://example.com/image.jpg');
|
|
293
|
+
* ```
|
|
294
|
+
*/
|
|
295
|
+
async embedImage(image, options = {}) {
|
|
296
|
+
try {
|
|
297
|
+
await this.ensureClient();
|
|
298
|
+
const model = options.model || "multimodalembedding@001";
|
|
299
|
+
const imageData = await this.imageToGeminiFormat(image);
|
|
300
|
+
const config = {};
|
|
301
|
+
if (options.dimensions) config.outputDimensionality = options.dimensions;
|
|
302
|
+
const result = await this.client.models.embedContent({
|
|
303
|
+
model,
|
|
304
|
+
contents: [imageData],
|
|
305
|
+
config: Object.keys(config).length > 0 ? config : void 0
|
|
306
|
+
});
|
|
307
|
+
return {
|
|
308
|
+
embeddings: result.embeddings?.[0]?.values ? [result.embeddings[0].values] : [],
|
|
309
|
+
model
|
|
310
|
+
};
|
|
311
|
+
} catch (error) {
|
|
312
|
+
throw this.mapError(error);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Generate an image from a text prompt using Imagen 3
|
|
317
|
+
* @param prompt - Text description of the image to generate
|
|
318
|
+
* @param options - Optional configuration for image generation
|
|
319
|
+
* @returns Promise resolving to generated image(s)
|
|
320
|
+
*
|
|
321
|
+
* @example
|
|
322
|
+
* ```typescript
|
|
323
|
+
* const result = await provider.generateImage('A sunset over mountains');
|
|
324
|
+
* fs.writeFileSync('image.png', result.images[0].data);
|
|
325
|
+
* ```
|
|
326
|
+
*/
|
|
327
|
+
async generateImage(prompt, options = {}) {
|
|
328
|
+
let controls;
|
|
329
|
+
try {
|
|
330
|
+
await this.ensureClient();
|
|
331
|
+
const model = options.model || "imagen-3.0-generate-002";
|
|
332
|
+
options = normalizeImageGenerationOptions(this.options, options, "gemini", model);
|
|
333
|
+
controls = prepareRequestControls(this.options, options);
|
|
334
|
+
const config = {
|
|
335
|
+
numberOfImages: options.n,
|
|
336
|
+
abortSignal: controls.signal,
|
|
337
|
+
httpOptions: {
|
|
338
|
+
timeout: controls.timeout,
|
|
339
|
+
retryOptions: { attempts: (this.options.maxRetries || 0) + 1 }
|
|
340
|
+
}
|
|
341
|
+
};
|
|
342
|
+
if (options.aspectRatio) config.aspectRatio = options.aspectRatio;
|
|
343
|
+
return {
|
|
344
|
+
images: ((await this.client.models.generateImages({
|
|
345
|
+
model,
|
|
346
|
+
prompt,
|
|
347
|
+
config
|
|
348
|
+
})).generatedImages || []).map((img) => {
|
|
349
|
+
let data;
|
|
350
|
+
const mimeType = "image/png";
|
|
351
|
+
const imageBytes = img.image?.imageBytes;
|
|
352
|
+
if (options.outputFormat === "base64") data = typeof imageBytes === "string" ? imageBytes : Buffer.from(imageBytes).toString("base64");
|
|
353
|
+
else if (options.outputFormat === "url") data = `data:${mimeType};base64,${typeof imageBytes === "string" ? imageBytes : Buffer.from(imageBytes).toString("base64")}`;
|
|
354
|
+
else data = typeof imageBytes === "string" ? Buffer.from(imageBytes, "base64") : Buffer.from(imageBytes);
|
|
355
|
+
return {
|
|
356
|
+
data,
|
|
357
|
+
mimeType
|
|
358
|
+
};
|
|
359
|
+
}),
|
|
360
|
+
model
|
|
361
|
+
};
|
|
362
|
+
} catch (error) {
|
|
363
|
+
if (controls?.didTimeout()) throw new AIError(`AI request timed out after ${controls.timeout}ms`, "AI_TIMEOUT", "gemini", options.model);
|
|
364
|
+
if (options.signal?.aborted) throw new AIError("AI request aborted by caller", "AI_ABORTED", "gemini", options.model);
|
|
365
|
+
throw this.mapError(error);
|
|
366
|
+
} finally {
|
|
367
|
+
controls?.cleanup();
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
async *stream(messages, options = {}) {
|
|
371
|
+
const startTime = Date.now();
|
|
372
|
+
let controls;
|
|
373
|
+
try {
|
|
374
|
+
await this.ensureClient();
|
|
375
|
+
const model = options.model || this.options.defaultModel;
|
|
376
|
+
options = normalizeChatOptions(this.options, options, "gemini", model);
|
|
377
|
+
controls = prepareRequestControls(this.options, options);
|
|
378
|
+
const stream = await this.client.models.generateContentStream({
|
|
379
|
+
model,
|
|
380
|
+
contents: this.messagesToGeminiFormat(messages),
|
|
381
|
+
config: this.buildGenerateContentConfig(options, controls)
|
|
382
|
+
});
|
|
383
|
+
let usage;
|
|
384
|
+
for await (const chunk of stream) {
|
|
385
|
+
if (chunk.usageMetadata) usage = {
|
|
386
|
+
promptTokens: chunk.usageMetadata.promptTokenCount || 0,
|
|
387
|
+
completionTokens: chunk.usageMetadata.candidatesTokenCount || 0,
|
|
388
|
+
totalTokens: chunk.usageMetadata.totalTokenCount || 0
|
|
389
|
+
};
|
|
390
|
+
const text = chunk.text || "";
|
|
391
|
+
if (!text) continue;
|
|
392
|
+
if (options.onProgress) options.onProgress(text);
|
|
393
|
+
yield text;
|
|
394
|
+
}
|
|
395
|
+
emitUsage(this.options, "gemini", "stream", model, usage, startTime, options.usageTags);
|
|
396
|
+
} catch (error) {
|
|
397
|
+
if (controls?.didTimeout()) throw new AIError(`AI request timed out after ${controls.timeout}ms`, "AI_TIMEOUT", "gemini", options.model);
|
|
398
|
+
if (options.signal?.aborted) throw new AIError("AI request aborted by caller", "AI_ABORTED", "gemini", options.model);
|
|
399
|
+
throw this.mapError(error);
|
|
400
|
+
} finally {
|
|
401
|
+
controls?.cleanup();
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
async countTokens(text) {
|
|
405
|
+
try {
|
|
406
|
+
await this.ensureClient();
|
|
407
|
+
const model = this.options.defaultModel || "gemini-2.5-flash";
|
|
408
|
+
return (await this.client.models.countTokens({
|
|
409
|
+
model,
|
|
410
|
+
contents: text
|
|
411
|
+
})).totalTokens || Math.ceil(text.length / 4);
|
|
412
|
+
} catch (error) {
|
|
413
|
+
throw this.mapError(error);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
async getModels() {
|
|
417
|
+
return [
|
|
418
|
+
{
|
|
419
|
+
id: "gemini-3-flash-preview",
|
|
420
|
+
name: "Gemini 3 Flash Preview",
|
|
421
|
+
description: "Preview of Gemini 3 Flash model. Available on Vertex AI in us-central1 only.",
|
|
422
|
+
contextLength: 1e6,
|
|
423
|
+
capabilities: [
|
|
424
|
+
"text",
|
|
425
|
+
"chat",
|
|
426
|
+
"vision",
|
|
427
|
+
"functions"
|
|
428
|
+
],
|
|
429
|
+
supportsFunctions: true,
|
|
430
|
+
supportsVision: true
|
|
431
|
+
},
|
|
432
|
+
{
|
|
433
|
+
id: "gemini-2.0-flash-001",
|
|
434
|
+
name: "Gemini 2.0 Flash",
|
|
435
|
+
description: "Latest fast and efficient Gemini model with function calling",
|
|
436
|
+
contextLength: 1e6,
|
|
437
|
+
capabilities: [
|
|
438
|
+
"text",
|
|
439
|
+
"chat",
|
|
440
|
+
"vision",
|
|
441
|
+
"functions"
|
|
442
|
+
],
|
|
443
|
+
supportsFunctions: true,
|
|
444
|
+
supportsVision: true
|
|
445
|
+
},
|
|
446
|
+
{
|
|
447
|
+
id: "gemini-2.5-flash",
|
|
448
|
+
name: "Gemini 2.5 Flash",
|
|
449
|
+
description: "Experimental next-generation Gemini model",
|
|
450
|
+
contextLength: 1e6,
|
|
451
|
+
capabilities: [
|
|
452
|
+
"text",
|
|
453
|
+
"chat",
|
|
454
|
+
"vision",
|
|
455
|
+
"functions"
|
|
456
|
+
],
|
|
457
|
+
supportsFunctions: true,
|
|
458
|
+
supportsVision: true
|
|
459
|
+
},
|
|
460
|
+
{
|
|
461
|
+
id: "gemini-1.5-pro",
|
|
462
|
+
name: "Gemini 1.5 Pro (Legacy)",
|
|
463
|
+
description: "Previous generation model (may not be available)",
|
|
464
|
+
contextLength: 2e6,
|
|
465
|
+
capabilities: [
|
|
466
|
+
"text",
|
|
467
|
+
"chat",
|
|
468
|
+
"vision",
|
|
469
|
+
"functions"
|
|
470
|
+
],
|
|
471
|
+
supportsFunctions: true,
|
|
472
|
+
supportsVision: true
|
|
473
|
+
}
|
|
474
|
+
];
|
|
475
|
+
}
|
|
476
|
+
async getCapabilities() {
|
|
477
|
+
return {
|
|
478
|
+
chat: true,
|
|
479
|
+
completion: true,
|
|
480
|
+
embeddings: true,
|
|
481
|
+
streaming: true,
|
|
482
|
+
functions: true,
|
|
483
|
+
vision: true,
|
|
484
|
+
fineTuning: false,
|
|
485
|
+
imageEmbeddings: true,
|
|
486
|
+
imageGeneration: true,
|
|
487
|
+
tts: false,
|
|
488
|
+
voiceCloning: false,
|
|
489
|
+
voiceDesign: false,
|
|
490
|
+
maxContextLength: 2e6,
|
|
491
|
+
supportedOperations: [
|
|
492
|
+
"chat",
|
|
493
|
+
"completion",
|
|
494
|
+
"embedding",
|
|
495
|
+
"streaming",
|
|
496
|
+
"functions",
|
|
497
|
+
"vision",
|
|
498
|
+
"image_embedding",
|
|
499
|
+
"image_generation"
|
|
500
|
+
]
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
async synthesizeSpeech(_text, _options) {
|
|
504
|
+
throw new AIError("TTS is not supported by Gemini provider. Use Qwen3-TTS provider.", "NOT_IMPLEMENTED", "gemini");
|
|
505
|
+
}
|
|
506
|
+
streamSpeech(_text, _options) {
|
|
507
|
+
const error = new AIError("TTS streaming is not supported by Gemini provider. Use Qwen3-TTS provider.", "NOT_IMPLEMENTED", "gemini");
|
|
508
|
+
return { [Symbol.asyncIterator]: () => ({ next: () => Promise.reject(error) }) };
|
|
509
|
+
}
|
|
510
|
+
async cloneVoice(_options) {
|
|
511
|
+
throw new AIError("Voice cloning is not supported by Gemini provider. Use Qwen3-TTS provider.", "NOT_IMPLEMENTED", "gemini");
|
|
512
|
+
}
|
|
513
|
+
async designVoice(_options) {
|
|
514
|
+
throw new AIError("Voice design is not supported by Gemini provider. Use Qwen3-TTS provider.", "NOT_IMPLEMENTED", "gemini");
|
|
515
|
+
}
|
|
516
|
+
async getVoices(_options) {
|
|
517
|
+
throw new AIError("Voice listing is not supported by Gemini provider. Use Qwen3-TTS provider.", "NOT_IMPLEMENTED", "gemini");
|
|
518
|
+
}
|
|
519
|
+
mapToolChoice(toolChoice) {
|
|
520
|
+
if (!toolChoice || toolChoice === "auto") return { functionCallingConfig: { mode: "AUTO" } };
|
|
521
|
+
if (toolChoice === "none") return { functionCallingConfig: { mode: "NONE" } };
|
|
522
|
+
if (typeof toolChoice === "object" && toolChoice.type === "function") return { functionCallingConfig: {
|
|
523
|
+
mode: "ANY",
|
|
524
|
+
allowedFunctionNames: [toolChoice.function.name]
|
|
525
|
+
} };
|
|
526
|
+
return { functionCallingConfig: { mode: "AUTO" } };
|
|
527
|
+
}
|
|
528
|
+
buildGenerateContentConfig(options, controls) {
|
|
529
|
+
const config = {
|
|
530
|
+
abortSignal: controls.signal,
|
|
531
|
+
httpOptions: {
|
|
532
|
+
timeout: controls.timeout,
|
|
533
|
+
retryOptions: { attempts: (this.options.maxRetries || 0) + 1 }
|
|
534
|
+
},
|
|
535
|
+
maxOutputTokens: options.maxTokens,
|
|
536
|
+
temperature: options.temperature,
|
|
537
|
+
topP: options.topP,
|
|
538
|
+
stopSequences: Array.isArray(options.stop) ? options.stop : options.stop ? [options.stop] : void 0,
|
|
539
|
+
responseMimeType: options.responseFormat?.type === "json_object" ? "application/json" : void 0,
|
|
540
|
+
frequencyPenalty: options.frequencyPenalty,
|
|
541
|
+
presencePenalty: options.presencePenalty,
|
|
542
|
+
seed: options.seed
|
|
543
|
+
};
|
|
544
|
+
if (options.tools && options.tools.length > 0) {
|
|
545
|
+
config.tools = [{ functionDeclarations: options.tools.map((tool) => ({
|
|
546
|
+
name: tool.function.name,
|
|
547
|
+
description: tool.function.description || "",
|
|
548
|
+
parameters: tool.function.parameters || { type: "object" }
|
|
549
|
+
})) }];
|
|
550
|
+
config.toolConfig = this.mapToolChoice(options.toolChoice);
|
|
551
|
+
}
|
|
552
|
+
const reasoning = options.reasoning;
|
|
553
|
+
if (reasoning?.maxTokens !== void 0 && reasoning.maxTokens > 0) config.thinkingConfig = {
|
|
554
|
+
thinkingBudget: reasoning.maxTokens,
|
|
555
|
+
includeThoughts: reasoning.includeThoughts
|
|
556
|
+
};
|
|
557
|
+
return Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0));
|
|
558
|
+
}
|
|
559
|
+
mapFinishReason(response) {
|
|
560
|
+
const firstCandidate = response.candidates?.[0];
|
|
561
|
+
if (firstCandidate?.content?.parts) {
|
|
562
|
+
if (firstCandidate.content.parts.some((part) => part.functionCall)) return "tool_calls";
|
|
563
|
+
}
|
|
564
|
+
return "stop";
|
|
565
|
+
}
|
|
566
|
+
messagesToGeminiFormat(messages) {
|
|
567
|
+
return messages.map((message) => {
|
|
568
|
+
const textContent = extractTextContent(message.content);
|
|
569
|
+
switch (message.role) {
|
|
570
|
+
case "system": return `Instructions: ${textContent}`;
|
|
571
|
+
case "user": return `Human: ${textContent}`;
|
|
572
|
+
case "assistant": return `Assistant: ${textContent}`;
|
|
573
|
+
default: return textContent;
|
|
574
|
+
}
|
|
575
|
+
}).join("\n\n");
|
|
576
|
+
}
|
|
577
|
+
stripMarkdownCodeBlock(text) {
|
|
578
|
+
const match = text.match(/^```(?:json|javascript|typescript)?\s*\n?([\s\S]*?)\n?```\s*$/);
|
|
579
|
+
return match ? match[1].trim() : text.trim();
|
|
580
|
+
}
|
|
581
|
+
mapError(error) {
|
|
582
|
+
if (error instanceof AIError) return error;
|
|
583
|
+
const message = error instanceof Error ? error.message : "Unknown Gemini error occurred";
|
|
584
|
+
if (message.includes("API_KEY_INVALID") || message.includes("401")) return new AuthenticationError("gemini");
|
|
585
|
+
if (message.includes("QUOTA_EXCEEDED") || message.includes("429")) return new RateLimitError("gemini", extractRetryAfterSeconds(error));
|
|
586
|
+
if (message.includes("MODEL_NOT_FOUND") || message.includes("404")) return new ModelNotFoundError(message, "gemini");
|
|
587
|
+
return new AIError(message, "UNKNOWN_ERROR", "gemini");
|
|
588
|
+
}
|
|
589
|
+
};
|
|
590
|
+
//#endregion
|
|
591
|
+
export { GeminiProvider };
|
|
592
|
+
|
|
593
|
+
//# sourceMappingURL=gemini-Bu7Fke7c.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"gemini-Bu7Fke7c.js","names":[],"sources":["../../src/shared/providers/gemini.ts"],"sourcesContent":["/**\n * Google Gemini provider implementation\n */\n\nimport crypto from 'node:crypto';\nimport { extractRetryAfterSeconds } from '../rate-limit';\nimport {\n normalizeBaseAIOptions,\n normalizeChatOptions,\n normalizeImageGenerationOptions,\n type PreparedRequestControls,\n prepareRequestControls,\n} from '../safety';\nimport type {\n AICapabilities,\n AIInterface,\n AIMessage,\n AIModel,\n AIResponse,\n ChatOptions,\n CompletionOptions,\n EmbeddingOptions,\n EmbeddingResponse,\n GeminiOptions,\n ImageDescriptionOptions,\n ImageEmbeddingOptions,\n ImageGenerationOptions,\n ImageGenerationResponse,\n MessageOptions,\n TokenUsage,\n TTSOptions,\n TTSResponse,\n Voice,\n VoiceCloneOptions,\n VoiceDesignOptions,\n VoiceListOptions,\n} from '../types';\nimport {\n AIError,\n AuthenticationError,\n extractTextContent,\n ModelNotFoundError,\n RateLimitError,\n} from '../types';\nimport { emitUsage } from './usage';\n\n// Note: This implementation uses the new @google/genai package\n// @google/generative-ai is deprecated - migrated to @google/genai\n\nexport class GeminiProvider implements AIInterface {\n private options: GeminiOptions;\n private client: any; // GoogleGenAI instance from @google/genai\n\n constructor(options: GeminiOptions) {\n this.options = normalizeBaseAIOptions({\n defaultModel: 'gemini-2.5-flash',\n ...options,\n });\n\n // Initialize Google Generative AI client\n this.initializeClientSync();\n }\n\n private initializeClientSync() {\n try {\n // Dynamic import in constructor - this will work if the package is installed\n import('@google/genai')\n .then(({ GoogleGenAI }) => {\n this.client = new GoogleGenAI(this.buildClientConfig());\n })\n .catch(() => {\n // Client will be null and we'll handle it in methods\n });\n } catch (_error) {\n // Client will be null and we'll handle it in methods\n }\n }\n\n private async ensureClient() {\n if (!this.client) {\n try {\n const { GoogleGenAI } = await import('@google/genai');\n this.client = new GoogleGenAI(this.buildClientConfig());\n } catch (_error) {\n throw new AIError(\n 'Failed to initialize Gemini client. Make sure @google/genai is installed.',\n 'INITIALIZATION_ERROR',\n 'gemini',\n );\n }\n }\n }\n\n /**\n * Build the GoogleGenAI client configuration based on provided options.\n * Supports both Google AI Studio (apiKey only) and Vertex AI (projectId + location).\n */\n private buildClientConfig(): Record<string, any> {\n // If projectId and location are provided, use Vertex AI mode\n if (this.options.projectId && this.options.location) {\n return {\n vertexai: true,\n project: this.options.projectId,\n location: this.options.location,\n apiKey: this.options.apiKey, // Optional for Vertex AI with ADC\n httpOptions: {\n timeout: this.options.timeout,\n retryOptions: { attempts: (this.options.maxRetries || 0) + 1 },\n },\n };\n }\n\n // Default to Google AI Studio mode with API key\n return {\n apiKey: this.options.apiKey,\n httpOptions: {\n timeout: this.options.timeout,\n retryOptions: { attempts: (this.options.maxRetries || 0) + 1 },\n },\n };\n }\n\n async chat(\n messages: AIMessage[],\n options: ChatOptions = {},\n ): Promise<AIResponse> {\n const startTime = Date.now();\n let controls: PreparedRequestControls | undefined;\n try {\n await this.ensureClient();\n\n const model = options.model || this.options.defaultModel;\n options = normalizeChatOptions(this.options, options, 'gemini', model);\n controls = prepareRequestControls(this.options, options);\n const requestConfig: Record<string, any> = {\n model,\n contents: this.messagesToGeminiFormat(messages),\n config: this.buildGenerateContentConfig(options, controls),\n };\n\n // Call new SDK API: ai.models.generateContent()\n const result = await this.client.models.generateContent(requestConfig);\n\n // Extract tool calls from response\n let toolCalls: AIResponse['toolCalls'];\n const firstCandidate = result.candidates?.[0];\n if (firstCandidate?.content?.parts) {\n const functionCalls = firstCandidate.content.parts.filter(\n (part: any) => part.functionCall,\n );\n if (functionCalls.length > 0) {\n toolCalls = functionCalls.map((part: any) => ({\n id: `call_${crypto.randomUUID()}`,\n type: 'function' as const,\n function: {\n name: part.functionCall.name,\n arguments: JSON.stringify(part.functionCall.args || {}),\n },\n }));\n }\n }\n\n // Clean content - remove markdown code blocks if JSON mode was requested\n let content = result.text || '';\n if (options.responseFormat?.type === 'json_object') {\n content = this.stripMarkdownCodeBlock(content);\n }\n\n const usage: TokenUsage = {\n promptTokens: result.usageMetadata?.promptTokenCount || 0,\n completionTokens: result.usageMetadata?.candidatesTokenCount || 0,\n totalTokens: result.usageMetadata?.totalTokenCount || 0,\n };\n emitUsage(\n this.options,\n 'gemini',\n 'chat',\n model!,\n usage,\n startTime,\n options.usageTags,\n );\n\n return {\n content,\n model,\n finishReason: this.mapFinishReason(result),\n usage,\n toolCalls: toolCalls && toolCalls.length > 0 ? toolCalls : undefined,\n };\n } catch (error) {\n if (controls?.didTimeout()) {\n throw new AIError(\n `AI request timed out after ${controls.timeout}ms`,\n 'AI_TIMEOUT',\n 'gemini',\n options.model,\n );\n }\n if (options.signal?.aborted) {\n throw new AIError(\n 'AI request aborted by caller',\n 'AI_ABORTED',\n 'gemini',\n options.model,\n );\n }\n throw this.mapError(error);\n } finally {\n controls?.cleanup();\n }\n }\n\n async complete(\n prompt: string,\n options: CompletionOptions = {},\n ): Promise<AIResponse> {\n return this.chat([{ role: 'user', content: prompt }], {\n model: options.model,\n maxTokens: options.maxTokens,\n temperature: options.temperature,\n topP: options.topP,\n n: options.n,\n stop: options.stop,\n stream: options.stream,\n onProgress: options.onProgress,\n signal: options.signal,\n timeout: options.timeout,\n reasoning: options.reasoning,\n usageTags: options.usageTags,\n });\n }\n\n /**\n * Simple message interface for single-turn interactions with optional history\n *\n * @param text - The message text to send\n * @param options - Configuration options including history, model, etc.\n * @returns Promise resolving to the response content string\n *\n * @example\n * ```typescript\n * // Simple usage\n * const response = await provider.message('Hello!');\n *\n * // With history\n * const response = await provider.message('What was my question?', {\n * history: [\n * { role: 'user', content: 'What is 2+2?' },\n * { role: 'assistant', content: '4' }\n * ]\n * });\n * ```\n */\n async message(text: string, options: MessageOptions = {}): Promise<string> {\n // Build messages array from history + current message\n const messages: AIMessage[] = [\n ...(options.history || []),\n { role: options.role || 'user', content: text },\n ];\n\n const response = await this.chat(messages, {\n model: options.model,\n maxTokens: options.maxTokens,\n temperature: options.temperature,\n topP: options.topP,\n stop: options.stop,\n stream: options.stream,\n frequencyPenalty: options.frequencyPenalty,\n presencePenalty: options.presencePenalty,\n responseFormat: options.responseFormat,\n seed: options.seed,\n tools: options.tools,\n toolChoice: options.toolChoice,\n onProgress: options.onProgress,\n signal: options.signal,\n timeout: options.timeout,\n reasoning: options.reasoning,\n usageTags: options.usageTags,\n });\n\n return response.content;\n }\n\n /**\n * Generate embeddings for text using Gemini embedding models\n * @param text - Single text string or array of texts to embed\n * @param options - Optional configuration for embeddings\n * @returns Promise resolving to embeddings response\n *\n * @example\n * ```typescript\n * const embedding = await provider.embed('Hello world');\n * const embeddings = await provider.embed(['Text 1', 'Text 2']);\n * ```\n */\n async embed(\n text: string | string[],\n options: EmbeddingOptions = {},\n ): Promise<EmbeddingResponse> {\n const startTime = Date.now();\n try {\n await this.ensureClient();\n\n const model = options.model || 'text-embedding-004';\n const input = Array.isArray(text) ? text : [text];\n\n const embeddings: number[][] = [];\n let totalTokens = 0;\n\n for (const content of input) {\n const config: Record<string, any> = {};\n if (options.dimensions) {\n config.outputDimensionality = options.dimensions;\n }\n\n const result = await this.client.models.embedContent({\n model,\n contents: content,\n config: Object.keys(config).length > 0 ? config : undefined,\n });\n\n if (result.embeddings?.[0]?.values) {\n embeddings.push(result.embeddings[0].values);\n }\n if (result.metadata?.tokenCount) {\n totalTokens += result.metadata.tokenCount;\n }\n }\n\n const usage: TokenUsage | undefined =\n totalTokens > 0\n ? {\n promptTokens: totalTokens,\n completionTokens: 0,\n totalTokens,\n }\n : undefined;\n emitUsage(\n this.options,\n 'gemini',\n 'embed',\n model,\n usage,\n startTime,\n options.usageTags,\n );\n\n return {\n embeddings,\n model,\n usage,\n };\n } catch (error) {\n throw this.mapError(error);\n }\n }\n\n /**\n * Convert an image to Gemini inline format\n * @param image - Image as URL, base64 data URL, or Buffer\n * @returns Gemini inline data format\n * @private\n */\n private async imageToGeminiFormat(\n image: string | Buffer,\n signal?: AbortSignal,\n ): Promise<{ inlineData: { mimeType: string; data: string } }> {\n let mimeType = 'image/png';\n let base64Data: string;\n\n if (Buffer.isBuffer(image)) {\n base64Data = image.toString('base64');\n } else if (image.startsWith('data:')) {\n // Parse data URL\n const match = image.match(/^data:([^;]+);base64,(.+)$/);\n if (match) {\n mimeType = match[1];\n base64Data = match[2];\n } else {\n throw new AIError(\n 'Invalid base64 data URL format',\n 'INVALID_INPUT',\n 'gemini',\n );\n }\n } else {\n // Fetch from URL\n const response = await fetch(image, { signal });\n if (!response.ok) {\n throw new AIError(\n `Failed to fetch image: ${response.status} ${response.statusText}`,\n 'IMAGE_FETCH_ERROR',\n 'gemini',\n );\n }\n const arrayBuffer = await response.arrayBuffer();\n base64Data = Buffer.from(arrayBuffer).toString('base64');\n mimeType = response.headers.get('content-type') || 'image/png';\n }\n\n return {\n inlineData: { mimeType, data: base64Data },\n };\n }\n\n /**\n * Generate a text description of an image\n * @param image - Image as URL, base64 data URL, or Buffer\n * @param prompt - Custom prompt for description (optional)\n * @param options - Optional configuration\n * @returns Promise resolving to the description string\n *\n * @example\n * ```typescript\n * const description = await provider.describeImage('https://example.com/image.jpg');\n * ```\n */\n async describeImage(\n image: string | Buffer,\n prompt?: string,\n options: ImageDescriptionOptions = {},\n ): Promise<string> {\n let controls: PreparedRequestControls | undefined;\n try {\n await this.ensureClient();\n\n const defaultPrompt =\n 'Describe this image for a search index. Include objects, mood, lighting, and any visible text.';\n\n const model =\n options.model || this.options.defaultModel || 'gemini-2.5-flash';\n const normalized = normalizeChatOptions(\n this.options,\n { ...options, maxTokens: options.maxTokens ?? 500 },\n 'gemini',\n model,\n );\n controls = prepareRequestControls(this.options, normalized);\n const imageData = await this.imageToGeminiFormat(image, controls.signal);\n\n const response = await this.client.models.generateContent({\n model,\n contents: [{ text: prompt || defaultPrompt }, imageData],\n config: this.buildGenerateContentConfig(normalized, controls),\n });\n\n return response.text || '';\n } catch (error) {\n if (controls?.didTimeout()) {\n throw new AIError(\n `AI request timed out after ${controls.timeout}ms`,\n 'AI_TIMEOUT',\n 'gemini',\n options.model,\n );\n }\n if (options.signal?.aborted) {\n throw new AIError(\n 'AI request aborted by caller',\n 'AI_ABORTED',\n 'gemini',\n options.model,\n );\n }\n throw this.mapError(error);\n } finally {\n controls?.cleanup();\n }\n }\n\n /**\n * Generate embeddings for an image using native multimodal embeddings\n * @param image - Image as URL, base64 data URL, or Buffer\n * @param options - Optional configuration for image embeddings\n * @returns Promise resolving to embeddings response\n *\n * @example\n * ```typescript\n * const embedding = await provider.embedImage('https://example.com/image.jpg');\n * ```\n */\n async embedImage(\n image: string | Buffer,\n options: ImageEmbeddingOptions = {},\n ): Promise<EmbeddingResponse> {\n try {\n await this.ensureClient();\n\n // Gemini uses multimodal embedding model\n const model = options.model || 'multimodalembedding@001';\n const imageData = await this.imageToGeminiFormat(image);\n\n const config: Record<string, any> = {};\n if (options.dimensions) {\n config.outputDimensionality = options.dimensions;\n }\n\n const result = await this.client.models.embedContent({\n model,\n contents: [imageData],\n config: Object.keys(config).length > 0 ? config : undefined,\n });\n\n return {\n embeddings: result.embeddings?.[0]?.values\n ? [result.embeddings[0].values]\n : [],\n model,\n };\n } catch (error) {\n throw this.mapError(error);\n }\n }\n\n /**\n * Generate an image from a text prompt using Imagen 3\n * @param prompt - Text description of the image to generate\n * @param options - Optional configuration for image generation\n * @returns Promise resolving to generated image(s)\n *\n * @example\n * ```typescript\n * const result = await provider.generateImage('A sunset over mountains');\n * fs.writeFileSync('image.png', result.images[0].data);\n * ```\n */\n async generateImage(\n prompt: string,\n options: ImageGenerationOptions = {},\n ): Promise<ImageGenerationResponse> {\n let controls: PreparedRequestControls | undefined;\n try {\n await this.ensureClient();\n\n const model = options.model || 'imagen-3.0-generate-002';\n options = normalizeImageGenerationOptions(\n this.options,\n options,\n 'gemini',\n model,\n );\n controls = prepareRequestControls(this.options, options);\n\n const config: Record<string, any> = {\n numberOfImages: options.n,\n abortSignal: controls.signal,\n httpOptions: {\n timeout: controls.timeout,\n retryOptions: { attempts: (this.options.maxRetries || 0) + 1 },\n },\n };\n\n if (options.aspectRatio) {\n config.aspectRatio = options.aspectRatio;\n }\n\n const response = await this.client.models.generateImages({\n model,\n prompt,\n config,\n });\n\n const images = (response.generatedImages || []).map((img: any) => {\n let data: Buffer | string;\n const mimeType = 'image/png';\n const imageBytes = img.image?.imageBytes;\n\n if (options.outputFormat === 'base64') {\n data =\n typeof imageBytes === 'string'\n ? imageBytes\n : Buffer.from(imageBytes).toString('base64');\n } else if (options.outputFormat === 'url') {\n // Gemini Imagen doesn't provide URLs, return as base64 data URL\n const b64 =\n typeof imageBytes === 'string'\n ? imageBytes\n : Buffer.from(imageBytes).toString('base64');\n data = `data:${mimeType};base64,${b64}`;\n } else {\n // Default: buffer\n data =\n typeof imageBytes === 'string'\n ? Buffer.from(imageBytes, 'base64')\n : Buffer.from(imageBytes);\n }\n\n return {\n data,\n mimeType,\n };\n });\n\n return {\n images,\n model,\n };\n } catch (error) {\n if (controls?.didTimeout()) {\n throw new AIError(\n `AI request timed out after ${controls.timeout}ms`,\n 'AI_TIMEOUT',\n 'gemini',\n options.model,\n );\n }\n if (options.signal?.aborted) {\n throw new AIError(\n 'AI request aborted by caller',\n 'AI_ABORTED',\n 'gemini',\n options.model,\n );\n }\n throw this.mapError(error);\n } finally {\n controls?.cleanup();\n }\n }\n\n async *stream(\n messages: AIMessage[],\n options: ChatOptions = {},\n ): AsyncIterable<string> {\n const startTime = Date.now();\n let controls: PreparedRequestControls | undefined;\n try {\n await this.ensureClient();\n\n const model = options.model || this.options.defaultModel;\n options = normalizeChatOptions(this.options, options, 'gemini', model);\n controls = prepareRequestControls(this.options, options);\n const stream = await this.client.models.generateContentStream({\n model,\n contents: this.messagesToGeminiFormat(messages),\n config: this.buildGenerateContentConfig(options, controls),\n });\n\n let usage: TokenUsage | undefined;\n\n for await (const chunk of stream) {\n if (chunk.usageMetadata) {\n usage = {\n promptTokens: chunk.usageMetadata.promptTokenCount || 0,\n completionTokens: chunk.usageMetadata.candidatesTokenCount || 0,\n totalTokens: chunk.usageMetadata.totalTokenCount || 0,\n };\n }\n\n const text = chunk.text || '';\n if (!text) {\n continue;\n }\n\n if (options.onProgress) {\n options.onProgress(text);\n }\n yield text;\n }\n\n emitUsage(\n this.options,\n 'gemini',\n 'stream',\n model!,\n usage,\n startTime,\n options.usageTags,\n );\n } catch (error) {\n if (controls?.didTimeout()) {\n throw new AIError(\n `AI request timed out after ${controls.timeout}ms`,\n 'AI_TIMEOUT',\n 'gemini',\n options.model,\n );\n }\n if (options.signal?.aborted) {\n throw new AIError(\n 'AI request aborted by caller',\n 'AI_ABORTED',\n 'gemini',\n options.model,\n );\n }\n throw this.mapError(error);\n } finally {\n controls?.cleanup();\n }\n }\n\n async countTokens(text: string): Promise<number> {\n try {\n await this.ensureClient();\n\n const model = this.options.defaultModel || 'gemini-2.5-flash';\n const response = await this.client.models.countTokens({\n model,\n contents: text,\n });\n\n return response.totalTokens || Math.ceil(text.length / 4);\n } catch (error) {\n throw this.mapError(error);\n }\n }\n\n async getModels(): Promise<AIModel[]> {\n // Return static list of known Gemini models\n return [\n {\n id: 'gemini-3-flash-preview',\n name: 'Gemini 3 Flash Preview',\n description:\n 'Preview of Gemini 3 Flash model. Available on Vertex AI in us-central1 only.',\n contextLength: 1000000,\n capabilities: ['text', 'chat', 'vision', 'functions'],\n supportsFunctions: true,\n supportsVision: true,\n },\n {\n id: 'gemini-2.0-flash-001',\n name: 'Gemini 2.0 Flash',\n description:\n 'Latest fast and efficient Gemini model with function calling',\n contextLength: 1000000,\n capabilities: ['text', 'chat', 'vision', 'functions'],\n supportsFunctions: true,\n supportsVision: true,\n },\n {\n id: 'gemini-2.5-flash',\n name: 'Gemini 2.5 Flash',\n description: 'Experimental next-generation Gemini model',\n contextLength: 1000000,\n capabilities: ['text', 'chat', 'vision', 'functions'],\n supportsFunctions: true,\n supportsVision: true,\n },\n {\n id: 'gemini-1.5-pro',\n name: 'Gemini 1.5 Pro (Legacy)',\n description: 'Previous generation model (may not be available)',\n contextLength: 2000000,\n capabilities: ['text', 'chat', 'vision', 'functions'],\n supportsFunctions: true,\n supportsVision: true,\n },\n ];\n }\n\n async getCapabilities(): Promise<AICapabilities> {\n return {\n chat: true,\n completion: true,\n embeddings: true,\n streaming: true,\n functions: true,\n vision: true,\n fineTuning: false,\n imageEmbeddings: true,\n imageGeneration: true,\n tts: false,\n voiceCloning: false,\n voiceDesign: false,\n maxContextLength: 2000000,\n supportedOperations: [\n 'chat',\n 'completion',\n 'embedding',\n 'streaming',\n 'functions',\n 'vision',\n 'image_embedding',\n 'image_generation',\n ],\n };\n }\n\n // ============================================================================\n // TTS Methods (Not supported - use Qwen3-TTS provider)\n // ============================================================================\n\n async synthesizeSpeech(\n _text: string,\n _options?: TTSOptions,\n ): Promise<TTSResponse> {\n throw new AIError(\n 'TTS is not supported by Gemini provider. Use Qwen3-TTS provider.',\n 'NOT_IMPLEMENTED',\n 'gemini',\n );\n }\n\n streamSpeech(_text: string, _options?: TTSOptions): AsyncIterable<Buffer> {\n const error = new AIError(\n 'TTS streaming is not supported by Gemini provider. Use Qwen3-TTS provider.',\n 'NOT_IMPLEMENTED',\n 'gemini',\n );\n return {\n [Symbol.asyncIterator]: () => ({\n next: () => Promise.reject(error),\n }),\n };\n }\n\n async cloneVoice(_options: VoiceCloneOptions): Promise<Voice> {\n throw new AIError(\n 'Voice cloning is not supported by Gemini provider. Use Qwen3-TTS provider.',\n 'NOT_IMPLEMENTED',\n 'gemini',\n );\n }\n\n async designVoice(_options: VoiceDesignOptions): Promise<Voice> {\n throw new AIError(\n 'Voice design is not supported by Gemini provider. Use Qwen3-TTS provider.',\n 'NOT_IMPLEMENTED',\n 'gemini',\n );\n }\n\n async getVoices(_options?: VoiceListOptions): Promise<Voice[]> {\n throw new AIError(\n 'Voice listing is not supported by Gemini provider. Use Qwen3-TTS provider.',\n 'NOT_IMPLEMENTED',\n 'gemini',\n );\n }\n\n private mapToolChoice(\n toolChoice?:\n | 'auto'\n | 'none'\n | { type: 'function'; function: { name: string } },\n ): any {\n if (!toolChoice || toolChoice === 'auto') {\n return { functionCallingConfig: { mode: 'AUTO' } };\n }\n\n if (toolChoice === 'none') {\n return { functionCallingConfig: { mode: 'NONE' } };\n }\n\n if (typeof toolChoice === 'object' && toolChoice.type === 'function') {\n return {\n functionCallingConfig: {\n mode: 'ANY',\n allowedFunctionNames: [toolChoice.function.name],\n },\n };\n }\n\n return { functionCallingConfig: { mode: 'AUTO' } };\n }\n\n private buildGenerateContentConfig(\n options: ChatOptions,\n controls: PreparedRequestControls,\n ): Record<string, any> {\n const config: Record<string, any> = {\n abortSignal: controls.signal,\n httpOptions: {\n timeout: controls.timeout,\n retryOptions: { attempts: (this.options.maxRetries || 0) + 1 },\n },\n maxOutputTokens: options.maxTokens,\n temperature: options.temperature,\n topP: options.topP,\n stopSequences: Array.isArray(options.stop)\n ? options.stop\n : options.stop\n ? [options.stop]\n : undefined,\n responseMimeType:\n options.responseFormat?.type === 'json_object'\n ? 'application/json'\n : undefined,\n frequencyPenalty: options.frequencyPenalty,\n presencePenalty: options.presencePenalty,\n seed: options.seed,\n };\n\n if (options.tools && options.tools.length > 0) {\n config.tools = [\n {\n functionDeclarations: options.tools.map((tool) => ({\n name: tool.function.name,\n description: tool.function.description || '',\n parameters: tool.function.parameters || { type: 'object' },\n })),\n },\n ];\n config.toolConfig = this.mapToolChoice(options.toolChoice);\n }\n\n const reasoning = options.reasoning;\n if (reasoning?.maxTokens !== undefined && reasoning.maxTokens > 0) {\n config.thinkingConfig = {\n thinkingBudget: reasoning.maxTokens,\n includeThoughts: reasoning.includeThoughts,\n };\n }\n\n return Object.fromEntries(\n Object.entries(config).filter(([, value]) => value !== undefined),\n );\n }\n\n private mapFinishReason(response: any): AIResponse['finishReason'] {\n // Check if response has function calls in any candidate\n const firstCandidate = response.candidates?.[0];\n if (firstCandidate?.content?.parts) {\n const hasFunctionCall = firstCandidate.content.parts.some(\n (part: any) => part.functionCall,\n );\n if (hasFunctionCall) {\n return 'tool_calls';\n }\n }\n\n // Gemini doesn't provide detailed finish reasons, default to 'stop'\n return 'stop';\n }\n\n private messagesToGeminiFormat(messages: AIMessage[]): string {\n // Convert messages to a simple text prompt\n // The new SDK expects a string for the contents field\n return messages\n .map((message) => {\n const textContent = extractTextContent(message.content);\n switch (message.role) {\n case 'system':\n return `Instructions: ${textContent}`;\n case 'user':\n return `Human: ${textContent}`;\n case 'assistant':\n return `Assistant: ${textContent}`;\n default:\n return textContent;\n }\n })\n .join('\\n\\n');\n }\n\n private stripMarkdownCodeBlock(text: string): string {\n // Remove markdown code blocks like ```json\\n...\\n```\n const codeBlockRegex =\n /^```(?:json|javascript|typescript)?\\s*\\n?([\\s\\S]*?)\\n?```\\s*$/;\n const match = text.match(codeBlockRegex);\n return match ? match[1].trim() : text.trim();\n }\n\n private mapError(error: unknown): AIError {\n if (error instanceof AIError) {\n return error;\n }\n\n // Map common Gemini error patterns\n const message =\n error instanceof Error ? error.message : 'Unknown Gemini error occurred';\n\n if (message.includes('API_KEY_INVALID') || message.includes('401')) {\n return new AuthenticationError('gemini');\n }\n\n if (message.includes('QUOTA_EXCEEDED') || message.includes('429')) {\n return new RateLimitError('gemini', extractRetryAfterSeconds(error));\n }\n\n if (message.includes('MODEL_NOT_FOUND') || message.includes('404')) {\n return new ModelNotFoundError(message, 'gemini');\n }\n\n return new AIError(message, 'UNKNOWN_ERROR', 'gemini');\n }\n}\n"],"mappings":";;;;;;;;;AAiDA,IAAa,iBAAb,MAAmD;CACjD;CACA;CAEA,YAAY,SAAwB;EAClC,KAAK,UAAU,uBAAuB;GACpC,cAAc;GACd,GAAG;EACL,CAAC;EAGD,KAAK,qBAAqB;CAC5B;CAEA,uBAA+B;EAC7B,IAAI;GAEF,OAAO,gBAAgB,CACpB,MAAM,EAAE,kBAAkB;IACzB,KAAK,SAAS,IAAI,YAAY,KAAK,kBAAkB,CAAC;GACxD,CAAC,CAAC,CACD,YAAY,CAEb,CAAC;EACL,SAAS,QAAQ,CAEjB;CACF;CAEA,MAAc,eAAe;EAC3B,IAAI,CAAC,KAAK,QACR,IAAI;GACF,MAAM,EAAE,gBAAgB,MAAM,OAAO;GACrC,KAAK,SAAS,IAAI,YAAY,KAAK,kBAAkB,CAAC;EACxD,SAAS,QAAQ;GACf,MAAM,IAAI,QACR,6EACA,wBACA,QACF;EACF;CAEJ;;;;;CAMA,oBAAiD;EAE/C,IAAI,KAAK,QAAQ,aAAa,KAAK,QAAQ,UACzC,OAAO;GACL,UAAU;GACV,SAAS,KAAK,QAAQ;GACtB,UAAU,KAAK,QAAQ;GACvB,QAAQ,KAAK,QAAQ;GACrB,aAAa;IACX,SAAS,KAAK,QAAQ;IACtB,cAAc,EAAE,WAAW,KAAK,QAAQ,cAAc,KAAK,EAAE;GAC/D;EACF;EAIF,OAAO;GACL,QAAQ,KAAK,QAAQ;GACrB,aAAa;IACX,SAAS,KAAK,QAAQ;IACtB,cAAc,EAAE,WAAW,KAAK,QAAQ,cAAc,KAAK,EAAE;GAC/D;EACF;CACF;CAEA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