@aeye/google 0.0.0-stage → 0.11.0

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/dist/google.js ADDED
@@ -0,0 +1,1366 @@
1
+ /**
2
+ * Google Provider
3
+ *
4
+ * Provider for the Gemini API (generativelanguage.googleapis.com), and Vertex
5
+ * AI through the same SDK: chat with tools, structured output, thinking,
6
+ * multimodal input and Google's hosted tools; image generation and editing
7
+ * (Gemini image models, and Imagen on Vertex AI); speech; transcription;
8
+ * embeddings; decisions; batches; token counting and context caching.
9
+ */
10
+ import { embeddingInputs, embeddingTexts, isEmbeddingImage, isModelInfo, supportedRequest } from '@aeye/ai';
11
+ import { describeTool, getModel, getResponseFromChunks, planRequest, prepareRequest, deliverSchema, replaysTo, SchemaRejectedError, schemaRejection, sentOutput, sentTools, toBase64, toText, } from '@aeye/core';
12
+ import { GoogleGenAI, } from '@google/genai';
13
+ import { createHash } from 'crypto';
14
+ import { candidateParts, endChunk, extensionOf, GOOGLE_PROVIDER, isFileUri, mimeTypeOf, pickMimeType, replayReasoning, ResponseState, responseChunks, SKIP_SIGNATURE, toHostedTool, toThinkingConfig, toUsage, } from './convert';
15
+ import { decisionUsage, toDecisionAnswer, toDecisionQuestion } from './decisions';
16
+ import { bytesStream, captions, imageSize, isWav, nearestAspectRatio, pcmToWav, pixelSize, sampleRate, seconds, wavToPcm } from './media';
17
+ import { bareModelId, defaultGoogleModel, googleOptions, isUsableModel, toModelInfo } from './models';
18
+ import { errorDetails, isContextWindowError, toGoogleError, withRetry } from './retry';
19
+ import { GoogleContextWindowError, GoogleError, GoogleSafetyError } from './types';
20
+ /**
21
+ * Models used when neither the request, the context, nor the config names one.
22
+ */
23
+ const DEFAULT_MODELS = {
24
+ imageGenerate: 'gemini-nano-banana-2.1',
25
+ imageEdit: 'gemini-nano-banana-2.1',
26
+ imageAnalyze: 'gemini-3.5-flash-lite',
27
+ transcription: 'gemini-3.5-transcribe',
28
+ speech: 'gemini-3.8-flash-lite-tts',
29
+ embedding: 'gemini-embedding-2',
30
+ decision: 'gemini-decision-1',
31
+ };
32
+ /**
33
+ * Default upload threshold: parts above 20 MB go through the Files API.
34
+ */
35
+ const UPLOAD_THRESHOLD = 20 * 1024 * 1024;
36
+ /**
37
+ * Request `extra` keys the provider reads itself, which aren't config.
38
+ */
39
+ const PROVIDER_EXTRA = new Set(['retry', 'retryEvents']);
40
+ /**
41
+ * Text in a tool result that should be the function response object.
42
+ */
43
+ function toolResponse(text, failed) {
44
+ if (failed)
45
+ return { error: text };
46
+ try {
47
+ const parsed = JSON.parse(text);
48
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : { output: parsed };
49
+ }
50
+ catch {
51
+ return { output: text };
52
+ }
53
+ }
54
+ /**
55
+ * Parse tool call arguments, keeping raw text that isn't JSON.
56
+ */
57
+ function toArgs(args) {
58
+ try {
59
+ const parsed = JSON.parse(args || '{}');
60
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : { input: parsed };
61
+ }
62
+ catch {
63
+ return { _raw: args };
64
+ }
65
+ }
66
+ /**
67
+ * Labels Gemini takes: lowercase letters, digits, `_` and `-`, at most 63.
68
+ */
69
+ function toLabels(metadata) {
70
+ if (!metadata)
71
+ return undefined;
72
+ const clean = (s) => s.toLowerCase().replace(/[^a-z0-9_-]/g, '_').slice(0, 63);
73
+ const entries = Object.entries(metadata).map(([k, v]) => [clean(k).replace(/^[^a-z]+/, 'k'), clean(String(v))]);
74
+ return entries.length ? Object.fromEntries(entries) : undefined;
75
+ }
76
+ /**
77
+ * The contents after a prefix of them, or undefined when the prefix isn't
78
+ * one (contents of one role are merged, so the prefix may end inside a
79
+ * content).
80
+ */
81
+ function splitAfter(contents, prefix) {
82
+ if (!prefix.length || prefix.length > contents.length)
83
+ return undefined;
84
+ const same = (x, y) => JSON.stringify(x) === JSON.stringify(y);
85
+ const last = prefix.length - 1;
86
+ for (let i = 0; i < last; i++) {
87
+ if (!same(contents[i], prefix[i]))
88
+ return undefined;
89
+ }
90
+ const head = prefix[last].parts ?? [];
91
+ const parts = contents[last].parts ?? [];
92
+ if (contents[last].role !== prefix[last].role || !same(parts.slice(0, head.length), head))
93
+ return undefined;
94
+ const rest = parts.slice(head.length);
95
+ return [...(rest.length ? [{ role: contents[last].role, parts: rest }] : []), ...contents.slice(last + 1)];
96
+ }
97
+ // ============================================================================
98
+ // Google Provider
99
+ // ============================================================================
100
+ /**
101
+ * Google Gemini provider for @aeye.
102
+ *
103
+ * @example
104
+ * ```typescript
105
+ * import { AI } from '@aeye/ai';
106
+ * import { GoogleProvider } from '@aeye/google';
107
+ * import { googleModels } from '@aeye/models';
108
+ *
109
+ * const google = new GoogleProvider({ apiKey: process.env.GEMINI_API_KEY! });
110
+ * const ai = AI.with().providers({ google }).create({ models: googleModels });
111
+ * const response = await ai.chat.get([{ role: 'user', content: 'Hello!' }], { metadata: { model: 'gemini-3.8-flash' } });
112
+ * ```
113
+ */
114
+ export class GoogleProvider {
115
+ name = GOOGLE_PROVIDER;
116
+ config;
117
+ defaultMetadata;
118
+ // Models used when nothing names one
119
+ defaults = DEFAULT_MODELS;
120
+ // Explicit caches by prefix hash, and prefixes the API wouldn't cache
121
+ caches = new Map();
122
+ uncacheable = new Set();
123
+ constructor(config = {}) {
124
+ this.config = config;
125
+ }
126
+ // ==========================================================================
127
+ // Client
128
+ // ==========================================================================
129
+ /**
130
+ * The SDK client for a config. The SDK never retries (no
131
+ * `retryOptions`); `withRetry` does.
132
+ */
133
+ createClient(config) {
134
+ const apiKey = config.apiKey ?? (config.vertexai ? undefined : process.env.GEMINI_API_KEY ?? process.env.GOOGLE_API_KEY);
135
+ return new GoogleGenAI({
136
+ apiKey,
137
+ vertexai: config.vertexai,
138
+ project: config.project,
139
+ location: config.location,
140
+ googleAuthOptions: config.googleAuthOptions,
141
+ // The Gemini API's v1beta has every feature (explicit caching, the
142
+ // Decisions API and Files are beta); the SDK defaults to v1
143
+ apiVersion: config.apiVersion ?? (config.vertexai ? undefined : 'v1beta'),
144
+ httpOptions: {
145
+ baseUrl: config.baseURL,
146
+ headers: config.headers,
147
+ timeout: config.timeout,
148
+ fetch: config.fetch,
149
+ },
150
+ });
151
+ }
152
+ /**
153
+ * Families of schemas this provider sends (`@aeye/schema` profiles).
154
+ */
155
+ supportedStrictFamilies = new Set(['google']);
156
+ /**
157
+ * The schema rules of a model whose data has none: Gemini's JSON Schema
158
+ * dialect (`@aeye/schema` base `google`).
159
+ */
160
+ schemaDefaults = { base: 'google' };
161
+ /** The options schemas are planned with: the families sent, and the default rules. */
162
+ planOptions() {
163
+ return { speaks: this.supportedStrictFamilies, defaults: this.schemaDefaults };
164
+ }
165
+ /** The model a call's schemas are planned for: its data. */
166
+ schemaModel(run) {
167
+ return this.infoOf(run);
168
+ }
169
+ /**
170
+ * Model info for an id: the configured model info (`config.modelInfo`,
171
+ * e.g. `@aeye/models` `googleModels`), else the documented default
172
+ * (`defaultGoogleModel`). No rules are applied to the id.
173
+ */
174
+ modelInfoFor(id, config = this.config) {
175
+ const bare = bareModelId(id);
176
+ return config.modelInfo?.find(m => m.id === bare) ?? defaultGoogleModel(bare, this.name);
177
+ }
178
+ /** The data of a call's model. */
179
+ infoOf(run) {
180
+ return run.modelInfo ?? this.modelInfoFor(run.model.id, run.config);
181
+ }
182
+ // ==========================================================================
183
+ // Models
184
+ // ==========================================================================
185
+ /**
186
+ * Models the API serves that @aeye can call, with what the rules and the
187
+ * API say about each, merged with `config.modelInfo` (prices and the docs'
188
+ * capabilities) where it has the model.
189
+ */
190
+ async listModels(config) {
191
+ const effective = { ...this.config, ...config };
192
+ const client = this.createClient(effective);
193
+ try {
194
+ const pager = await withRetry(() => client.models.list({ config: { pageSize: 1000 } }), { operation: 'list models', provider: this.name, startTime: Date.now() }, effective.retry);
195
+ const models = [];
196
+ for await (const model of pager) {
197
+ models.push(model);
198
+ }
199
+ // With a catalog configured, a model it has no data for isn't offered (nothing says what it is)
200
+ return models
201
+ .filter(m => isUsableModel(m))
202
+ .filter(m => !effective.modelInfo || effective.modelInfo.some(k => k.id === bareModelId(m.name ?? '')))
203
+ .map(m => this.convertModel(m, effective));
204
+ }
205
+ catch (error) {
206
+ throw toGoogleError(error);
207
+ }
208
+ }
209
+ /**
210
+ * A models.list entry as ModelInfo, merged with configured model info.
211
+ */
212
+ convertModel(model, config) {
213
+ const info = toModelInfo(model, this.name);
214
+ const known = config.modelInfo?.find(m => m.id === info.id);
215
+ if (!known)
216
+ return info;
217
+ return {
218
+ ...info,
219
+ ...known,
220
+ provider: this.name,
221
+ contextWindow: info.contextWindow || known.contextWindow,
222
+ maxOutputTokens: info.maxOutputTokens ?? known.maxOutputTokens,
223
+ capabilities: new Set([...known.capabilities]),
224
+ metadata: { ...info.metadata, ...known.metadata },
225
+ providerOptions: { ...info.providerOptions, ...known.providerOptions, google: { ...googleOptions(info), ...googleOptions(known) } },
226
+ };
227
+ }
228
+ /**
229
+ * Whether the API answers with these credentials.
230
+ */
231
+ async checkHealth(config) {
232
+ try {
233
+ const pager = await this.createClient({ ...this.config, ...config }).models.list({ config: { pageSize: 1 } });
234
+ void pager.page;
235
+ return true;
236
+ }
237
+ catch {
238
+ return false;
239
+ }
240
+ }
241
+ // ==========================================================================
242
+ // Calls
243
+ // ==========================================================================
244
+ /**
245
+ * Resolve what one call needs: config and client, model, retries.
246
+ */
247
+ prepare(operation, request, ctx, metadata, config, signal, defaultModel) {
248
+ const effectiveConfig = { ...this.config, ...config };
249
+ const model = getModel(request.model || ctx.metadata?.model || metadata?.model ||
250
+ effectiveConfig.defaultModels?.[defaultModel] || this.defaults[defaultModel]);
251
+ if (!model) {
252
+ throw new GoogleError(`Model is required for ${this.name} ${operation} requests`);
253
+ }
254
+ const id = bareModelId(model.id);
255
+ const normalized = id === model.id ? model : { ...model, id };
256
+ const retryConfig = { ...effectiveConfig.retry, ...request.extra?.retry };
257
+ const retryEvents = request.extra?.retryEvents || effectiveConfig.retryEvents || {};
258
+ const retryContext = { operation, model: id, provider: this.name, startTime: Date.now() };
259
+ const effectiveSignal = signal || ctx.signal;
260
+ const selected = [metadata?.model, ctx.metadata?.model, isModelInfo(model) ? model : undefined]
261
+ .find((m) => !!m && isModelInfo(m) && bareModelId(m.id) === id);
262
+ return {
263
+ config: effectiveConfig,
264
+ client: this.createClient(effectiveConfig),
265
+ ctx,
266
+ metadata,
267
+ model: normalized,
268
+ modelInfo: selected ?? effectiveConfig.modelInfo?.find(m => m.id === id),
269
+ signal: effectiveSignal,
270
+ retry: (call) => withRetry(call, retryContext, retryConfig, retryEvents, effectiveSignal),
271
+ };
272
+ }
273
+ /**
274
+ * Send one call with retries, around the before and error hooks. Failures
275
+ * become the provider's errors.
276
+ */
277
+ async send(op, run, request, params, call) {
278
+ const hooks = run.config.hooks?.[op];
279
+ await hooks?.beforeRequest?.(request, params, run.ctx, run.metadata);
280
+ try {
281
+ return await run.retry(call);
282
+ }
283
+ catch (e) {
284
+ const error = toGoogleError(e);
285
+ await hooks?.onError?.(request, params, error, run.ctx, run.metadata);
286
+ throw error;
287
+ }
288
+ }
289
+ /**
290
+ * Report a response to the after hook and return it.
291
+ */
292
+ async finish(op, run, request, params, response) {
293
+ const hooks = run.config.hooks?.[op];
294
+ await hooks?.afterRequest?.(request, params, response, run.ctx, run.metadata);
295
+ return response;
296
+ }
297
+ /**
298
+ * The schema a 400 rejected: Gemini names a function declaration by index
299
+ * (`tools[0].function_declarations[3]`) or the response schema.
300
+ */
301
+ rejectedSchema(request, error) {
302
+ const { message } = errorDetails(error);
303
+ const declaration = /function_?declarations\[(\d+)\]/i.exec(message);
304
+ if (declaration) {
305
+ const sent = sentTools(request)[Number(declaration[1])];
306
+ const name = sent?.definition?.name;
307
+ return new SchemaRejectedError(name ? { kind: 'tool', name } : { kind: 'tools' }, message, error);
308
+ }
309
+ if (/response_?(json_?)?schema|responseJsonSchema|generation_?config\.response/i.test(message) && typeof request.responseFormat === 'object') {
310
+ return new SchemaRejectedError({ kind: 'output' }, message, error);
311
+ }
312
+ return schemaRejection(request, error, message);
313
+ }
314
+ /**
315
+ * Send a chat call. A context window overflow ends as `length` so the
316
+ * prompt can trim and retry; a rejected schema becomes a
317
+ * SchemaRejectedError.
318
+ */
319
+ async sendChat(run, request, params, call) {
320
+ try {
321
+ return { result: await this.send('chat', run, request, params, call) };
322
+ }
323
+ catch (e) {
324
+ if (e instanceof GoogleContextWindowError || isContextWindowError(e)) {
325
+ const window = e instanceof GoogleContextWindowError ? e.contextWindow : undefined;
326
+ const overflow = { content: '', toolCalls: [], finishReason: 'length', model: run.model, usage: { text: { input: window } } };
327
+ return { overflow: await this.finish('chat', run, request, params, overflow) };
328
+ }
329
+ const status = e.status;
330
+ throw (status === 400 && e instanceof Error && this.rejectedSchema(request, e)) || e;
331
+ }
332
+ }
333
+ // ==========================================================================
334
+ // Content
335
+ // ==========================================================================
336
+ /**
337
+ * Upload bytes through the Files API and wait until the file is usable
338
+ * (videos are processed first).
339
+ *
340
+ * @param data - The bytes
341
+ * @param mimeType - Their type
342
+ * @param run - The call, for its client and signal
343
+ * @param displayName - A name to show
344
+ * @returns The file's URI and type
345
+ */
346
+ async uploadFile(data, mimeType, run, displayName) {
347
+ const client = run?.client ?? this.createClient(this.config);
348
+ const retry = run?.retry ?? ((call) => withRetry(call, { operation: 'upload', provider: this.name, startTime: Date.now() }, this.config.retry));
349
+ const blob = data instanceof Blob ? data : new Blob([data], { type: mimeType });
350
+ let file = await retry((signal) => client.files.upload({ file: blob, config: { mimeType, displayName, abortSignal: signal } }));
351
+ for (let wait = 1000; file.state === 'PROCESSING' && wait < 5 * 60 * 1000; wait *= 1.5) {
352
+ await new Promise(resolve => setTimeout(resolve, Math.min(wait, 10000)));
353
+ if (run?.signal?.aborted)
354
+ throw new GoogleError('Upload aborted');
355
+ file = await retry((signal) => client.files.get({ name: file.name, config: { abortSignal: signal } }));
356
+ }
357
+ if (file.state === 'FAILED') {
358
+ throw new GoogleError(`File processing failed: ${file.error?.message ?? file.name}`);
359
+ }
360
+ return { uri: file.uri, mimeType: file.mimeType ?? mimeType, name: file.name };
361
+ }
362
+ /**
363
+ * Delete a file uploaded through the Files API.
364
+ */
365
+ async deleteFile(name, config) {
366
+ const client = this.createClient({ ...this.config, ...config });
367
+ await client.files.delete({ name });
368
+ }
369
+ /**
370
+ * One media resource as a Gemini part: files, Cloud Storage objects,
371
+ * YouTube and other URLs of known type go by reference (`fileData`); bytes
372
+ * go inline, or through the Files API above the upload threshold.
373
+ */
374
+ async convertMedia(part, run) {
375
+ const defaults = { image: 'image/png', audio: 'audio/mp3', video: 'video/mp4', file: 'application/pdf' };
376
+ const content = part.content;
377
+ const uri = content instanceof URL ? content.href
378
+ : typeof content === 'string' && /^(https?|gs):\/\//.test(content) ? content
379
+ : typeof content === 'object' && content && 'url' in content && typeof content.url === 'function' ? content.url()
380
+ : undefined;
381
+ if (uri) {
382
+ const mimeType = pickMimeType(part.format, extensionOf(part.name), extensionOf(uri));
383
+ if (isFileUri(uri) || mimeType) {
384
+ return this.withResolution({ fileData: { fileUri: uri, mimeType: /youtu/.test(uri) ? undefined : mimeType ?? defaults[part.type] } }, part, run);
385
+ }
386
+ }
387
+ const dataUrl = await toBase64(content, mimeTypeOf(part.format));
388
+ const [, dataMime, data = ''] = /^data:([^;,]+)?(?:;[^,]*)?,(.*)$/s.exec(dataUrl) ?? [];
389
+ const mimeType = pickMimeType(part.format, dataMime, extensionOf(part.name)) ?? defaults[part.type] ?? 'application/octet-stream';
390
+ const size = Math.floor(data.length * 3 / 4);
391
+ if (size > (run.config.uploadThreshold ?? UPLOAD_THRESHOLD)) {
392
+ const file = await this.uploadFile(Buffer.from(data, 'base64'), mimeType, run, part.name);
393
+ return this.withResolution({ fileData: { fileUri: file.uri, mimeType: file.mimeType } }, part, run);
394
+ }
395
+ return this.withResolution({ inlineData: { data, mimeType } }, part, run);
396
+ }
397
+ /**
398
+ * A part with its media resolution, from the content's `detail` (Gemini 3
399
+ * and later; earlier models take only a request-wide resolution).
400
+ */
401
+ withResolution(part, content, run) {
402
+ const level = content.detail === 'low' ? 'MEDIA_RESOLUTION_LOW'
403
+ : content.detail === 'high' ? 'MEDIA_RESOLUTION_HIGH'
404
+ : content.detail === 'original' ? 'MEDIA_RESOLUTION_ULTRA_HIGH'
405
+ : undefined;
406
+ return level && googleOptions(this.infoOf(run)).partMediaResolution ? { ...part, mediaResolution: { level: level } } : part;
407
+ }
408
+ /**
409
+ * Message content as parts. Media that can't be read becomes a note.
410
+ */
411
+ async convertContent(content, name, run) {
412
+ if (typeof content === 'string') {
413
+ return content ? [{ text: content }] : [];
414
+ }
415
+ const parts = await Promise.all(content.map(async (part) => {
416
+ if (part.type === 'text') {
417
+ const text = await toText(part.content).catch(() => `Text content sent by ${name} could not be read.`);
418
+ return text ? [{ text }] : [];
419
+ }
420
+ try {
421
+ return [await this.convertMedia(part, run)];
422
+ }
423
+ catch (e) {
424
+ return [{ text: `${part.type[0].toUpperCase()}${part.type.slice(1)} content sent by ${name} could not be read and was left out.` }];
425
+ }
426
+ }));
427
+ return parts.flat();
428
+ }
429
+ /**
430
+ * Messages as Gemini contents and a system instruction.
431
+ *
432
+ * - System messages become the system instruction.
433
+ * - Assistant turns become `model` contents with their text and function
434
+ * calls, and the thought signatures and server-side tool parts Gemini
435
+ * gave them (only Gemini's own reasoning is replayed). A function call
436
+ * Gemini 3+ needs signed but that has no signature (history from another
437
+ * model) gets the validator-skip signature.
438
+ * - Tool results become `functionResponse` parts, named after their call;
439
+ * images and files in them ride inside the response on Gemini 3 and
440
+ * later, and as user parts after it before that.
441
+ * - Consecutive contents of one role are merged, so parallel calls are
442
+ * answered in one turn.
443
+ */
444
+ async convertMessages(request, run) {
445
+ const callNames = new Map();
446
+ for (const message of request.messages) {
447
+ for (const call of message.toolCalls ?? [])
448
+ callNames.set(call.id, call.name);
449
+ }
450
+ const options = googleOptions(this.infoOf(run));
451
+ const mediaInResponse = !!options.functionResponseParts;
452
+ const replayed = new Set();
453
+ const system = [];
454
+ const raw = [];
455
+ for (const message of request.messages) {
456
+ switch (message.role) {
457
+ case 'system':
458
+ system.push(...(await this.convertContent(message.content, message.name || 'system', run)).filter(p => p.text !== undefined));
459
+ break;
460
+ case 'user':
461
+ raw.push({ role: 'user', parts: await this.convertContent(message.content, message.name || 'user', run) });
462
+ break;
463
+ case 'assistant':
464
+ raw.push({ role: 'model', parts: await this.convertAssistant(message, replayed, !!options.thoughtSignatures, run) });
465
+ break;
466
+ case 'tool': {
467
+ const parts = await this.convertContent(message.content, message.name || 'tool', run);
468
+ const text = parts.filter(p => p.text !== undefined).map(p => p.text).join('\n');
469
+ const media = parts.filter(p => p.inlineData || p.fileData);
470
+ const id = message.toolCallId;
471
+ const name = (id && callNames.get(id)) || message.name || 'tool';
472
+ const response = {
473
+ functionResponse: {
474
+ id,
475
+ name,
476
+ response: toolResponse(text, !!message.failure),
477
+ ...(mediaInResponse && media.length ? { parts: media.map(p => ({ inlineData: p.inlineData, fileData: p.fileData })) } : {}),
478
+ },
479
+ };
480
+ raw.push({ role: 'user', parts: [response, ...(!mediaInResponse ? media : [])] });
481
+ break;
482
+ }
483
+ }
484
+ }
485
+ const contents = [];
486
+ for (const content of raw) {
487
+ if (!content.parts?.length)
488
+ continue;
489
+ const last = contents[contents.length - 1];
490
+ if (last && last.role === content.role) {
491
+ // Function responses go before any media that came with them
492
+ const parts = [...(last.parts ?? []), ...content.parts];
493
+ last.parts = content.role === 'user' && parts.some(p => p.functionResponse)
494
+ ? [...parts.filter(p => p.functionResponse), ...parts.filter(p => !p.functionResponse)]
495
+ : parts;
496
+ }
497
+ else {
498
+ contents.push({ role: content.role, parts: [...content.parts] });
499
+ }
500
+ }
501
+ if (!contents.length) {
502
+ contents.push({ role: 'user', parts: [{ text: 'Perform the requested operation.' }] });
503
+ }
504
+ return { contents, systemInstruction: system.length ? { parts: system } : undefined };
505
+ }
506
+ /**
507
+ * An assistant message as model parts.
508
+ */
509
+ async convertAssistant(message, replayed, signed, run) {
510
+ const reasoning = message.reasoning && !replayed.has(message.reasoning) && replaysTo(message.reasoning, GOOGLE_PROVIDER) ? message.reasoning : undefined;
511
+ if (message.reasoning)
512
+ replayed.add(message.reasoning);
513
+ const replay = replayReasoning(reasoning?.details);
514
+ const content = await this.convertContent(message.content, message.name || 'assistant', run);
515
+ const text = content.filter(p => p.text !== undefined && p.text !== '');
516
+ const media = content.filter(p => p.inlineData || p.fileData);
517
+ if (replay.text && text.length) {
518
+ text[text.length - 1] = { ...text[text.length - 1], thoughtSignature: replay.text };
519
+ }
520
+ const calls = (message.toolCalls ?? []).map((call) => {
521
+ const signature = replay.calls.get(call.id);
522
+ return { functionCall: { id: call.id, name: call.name, args: toArgs(call.arguments) }, ...(signature ? { thoughtSignature: signature } : {}) };
523
+ });
524
+ if (signed && calls.length && !calls[0].thoughtSignature) {
525
+ calls[0] = { ...calls[0], thoughtSignature: SKIP_SIGNATURE };
526
+ }
527
+ return [...replay.serverParts, ...text, ...media, ...calls];
528
+ }
529
+ /**
530
+ * Tools as function declarations, in the plan's rendering
531
+ * (`parametersJsonSchema`, Gemini's JSON Schema dialect), and hosted tools.
532
+ */
533
+ convertTools(request, vertex = false) {
534
+ const sent = sentTools(request);
535
+ const declarations = sent.map(tool => ({
536
+ name: tool.name,
537
+ description: (tool.definition ? describeTool(tool.definition) : tool.description) ?? '',
538
+ parametersJsonSchema: tool.parameters,
539
+ }));
540
+ const tools = [
541
+ ...(declarations.length ? [{ functionDeclarations: declarations }] : []),
542
+ ...(request.hostedTools ?? []).map(tool => toHostedTool(tool, vertex)),
543
+ ];
544
+ return { tools: tools.length ? tools : undefined, strict: sent.some(tool => tool.strict) };
545
+ }
546
+ /**
547
+ * The tool choice as a function calling config:
548
+ *
549
+ * - `auto`: AUTO, or VALIDATED (constrained calls) when any tool was
550
+ * rendered strict
551
+ * - `required`: ANY; `{ tool }`: ANY limited to it
552
+ * - `{ allowed }`: VALIDATED (or ANY when required) limited to them, with
553
+ * every tool still sent
554
+ * - `none`: NONE
555
+ */
556
+ convertToolChoice(request, strict, hasFunctions) {
557
+ if (!hasFunctions)
558
+ return undefined;
559
+ const choice = request.toolChoice;
560
+ const mode = (m) => m;
561
+ if (choice === 'none')
562
+ return { mode: mode('NONE') };
563
+ if (choice === 'required')
564
+ return { mode: mode('ANY') };
565
+ if (typeof choice === 'object' && 'tool' in choice)
566
+ return { mode: mode('ANY'), allowedFunctionNames: [choice.tool] };
567
+ if (typeof choice === 'object')
568
+ return { mode: mode(choice.required ? 'ANY' : 'VALIDATED'), allowedFunctionNames: choice.allowed };
569
+ return strict ? { mode: mode('VALIDATED') } : choice === 'auto' ? { mode: mode('AUTO') } : undefined;
570
+ }
571
+ /**
572
+ * generateContent parameters for a chat request.
573
+ *
574
+ * @param request - The request, prepared (`prepareRequest`)
575
+ * @param run - The resolved call
576
+ */
577
+ async buildChatParams(request, run) {
578
+ const modelId = run.model.id;
579
+ const info = this.infoOf(run);
580
+ const options = googleOptions(info);
581
+ // Only what the model's data says it takes goes on the wire
582
+ let sent = supportedRequest(request.plan ? request : { ...request, plan: planRequest(request, this.schemaModel(run), this.planOptions()) }, info).request;
583
+ // A model that can't combine function calling with a response schema gets the schema as prompt text
584
+ if (!options.toolsWithOutput && sent.tools?.length && sentOutput(sent)) {
585
+ sent = deliverSchema(sent, 'prompt');
586
+ }
587
+ const { contents, systemInstruction } = await this.convertMessages(sent, run);
588
+ const { tools, strict } = this.convertTools(sent, run.config.vertexai);
589
+ const hasFunctions = !!tools?.some(t => t.functionDeclarations?.length);
590
+ const functionCallingConfig = this.convertToolChoice(sent, strict, hasFunctions);
591
+ const serverTools = !!sent.hostedTools?.length;
592
+ const invocations = serverTools && hasFunctions && !!options.serverToolInvocations;
593
+ const toolConfig = functionCallingConfig || invocations
594
+ ? { functionCallingConfig, ...(invocations ? { includeServerSideToolInvocations: true } : {}) }
595
+ : undefined;
596
+ const format = sent.responseFormat;
597
+ const output = sentOutput(sent);
598
+ const json = format === 'json' || !!output;
599
+ const modalities = sent.modalities ?? [];
600
+ const audio = modalities.includes('audio');
601
+ const image = modalities.includes('image');
602
+ const stop = sent.stop === undefined ? undefined : (Array.isArray(sent.stop) ? sent.stop : [sent.stop]).slice(0, 5);
603
+ const tier = sent.serviceTier === 'flex' ? 'flex' : sent.serviceTier === 'fast' ? 'priority' : sent.serviceTier === 'default' ? 'standard' : undefined;
604
+ const extra = Object.fromEntries(Object.entries(sent.extra ?? {}).filter(([key]) => !PROVIDER_EXTRA.has(key)));
605
+ const config = {
606
+ systemInstruction,
607
+ tools,
608
+ toolConfig,
609
+ temperature: sent.temperature,
610
+ topP: sent.topP,
611
+ maxOutputTokens: sent.maxTokens,
612
+ stopSequences: stop,
613
+ seed: sent.seed,
614
+ presencePenalty: sent.presencePenalty,
615
+ frequencyPenalty: sent.frequencyPenalty,
616
+ responseMimeType: json ? 'application/json' : undefined,
617
+ responseJsonSchema: output?.schema,
618
+ thinkingConfig: toThinkingConfig(options.thinking, sent.reason, info.reasoningEfforts, sent.maxTokens),
619
+ responseModalities: audio ? ['AUDIO'] : image ? ['TEXT', 'IMAGE'] : undefined,
620
+ speechConfig: audio && sent.audio?.voice ? this.voiceConfig(info, sent.audio.voice) : undefined,
621
+ serviceTier: tier,
622
+ labels: run.config.vertexai ? toLabels(sent.metadata) : undefined,
623
+ safetySettings: run.config.safetySettings,
624
+ ...extra,
625
+ };
626
+ if (config.cachedContent) {
627
+ // A cache holds the system instruction and tools itself
628
+ delete config.systemInstruction;
629
+ delete config.tools;
630
+ delete config.toolConfig;
631
+ }
632
+ for (const key of Object.keys(config)) {
633
+ if (config[key] === undefined)
634
+ delete config[key];
635
+ }
636
+ const params = { model: modelId, contents, config };
637
+ return this.withExplicitCache(params, sent, run);
638
+ }
639
+ /**
640
+ * The parameters with the prefix the last cache breakpoint ends cached
641
+ * explicitly, when explicit caching is on and the model has it: the
642
+ * system instruction, tools and contents through the breakpoint go in a
643
+ * cache (made once and reused while it lives), and the call sends the
644
+ * rest. A prefix the API won't cache (too small) is sent whole from then on.
645
+ */
646
+ async withExplicitCache(params, request, run) {
647
+ const setting = run.config.explicitCaching;
648
+ const config = params.config ?? {};
649
+ if (!setting || config.cachedContent || !googleOptions(this.infoOf(run)).explicitCaching) {
650
+ return params;
651
+ }
652
+ const nonSystem = request.messages.filter(m => m.role !== 'system');
653
+ const breakAt = nonSystem.map(m => Array.isArray(m.content) && m.content.some(p => p.cacheBreakpoint)).lastIndexOf(true);
654
+ if (breakAt < 0)
655
+ return params;
656
+ // The contents of the messages through the breakpoint
657
+ const prefixRequest = { ...request, messages: [...request.messages.filter(m => m.role === 'system'), ...nonSystem.slice(0, breakAt + 1)] };
658
+ const { contents: prefix } = await this.convertMessages(prefixRequest, run);
659
+ const contents = params.contents;
660
+ const suffix = splitAfter(contents, prefix);
661
+ if (!suffix?.length)
662
+ return params;
663
+ const key = createHash('sha256').update(JSON.stringify({ model: params.model, prefix, system: config.systemInstruction, tools: config.tools, toolConfig: config.toolConfig })).digest('hex');
664
+ if (this.uncacheable.has(key))
665
+ return params;
666
+ let cache = this.caches.get(key);
667
+ if (!cache || cache.expires < Date.now() + 10_000) {
668
+ const ttl = (typeof setting === 'object' && setting.ttl) || '3600s';
669
+ try {
670
+ const created = await run.retry((signal) => run.client.caches.create({
671
+ model: params.model,
672
+ config: { contents: prefix, systemInstruction: config.systemInstruction, tools: config.tools, toolConfig: config.toolConfig, ttl, abortSignal: signal },
673
+ }));
674
+ cache = { name: created.name, expires: created.expireTime ? Date.parse(created.expireTime) : Date.now() + parseFloat(ttl) * 1000 };
675
+ this.caches.set(key, cache);
676
+ }
677
+ catch {
678
+ this.uncacheable.add(key);
679
+ return params;
680
+ }
681
+ }
682
+ const { systemInstruction, tools, toolConfig, ...rest } = config;
683
+ return { ...params, contents: suffix, config: { ...rest, cachedContent: cache.name } };
684
+ }
685
+ /**
686
+ * Create an explicit cache of contents to reference with
687
+ * `extra.cachedContent` (Gemini 2.5 and 3; Gemini 4 caches implicitly only).
688
+ *
689
+ * @param request - The messages (and tools) to cache
690
+ * @param options - Model and time to live
691
+ * @returns The cache's name and expiry
692
+ */
693
+ async createCache(request, options = {}, config) {
694
+ const run = this.prepare('create cache', { model: options.model ?? request.model }, {}, undefined, config, undefined, 'chat');
695
+ const sent = await prepareRequest(request, this.schemaModel(run), this.planOptions());
696
+ const { contents, systemInstruction } = await this.convertMessages(sent, run);
697
+ const { tools } = this.convertTools(sent);
698
+ try {
699
+ return await run.retry((signal) => run.client.caches.create({
700
+ model: run.model.id,
701
+ config: { contents, systemInstruction, tools, ttl: options.ttl ?? '3600s', displayName: options.displayName, abortSignal: signal },
702
+ }));
703
+ }
704
+ catch (error) {
705
+ throw toGoogleError(error);
706
+ }
707
+ }
708
+ /**
709
+ * Delete an explicit cache.
710
+ */
711
+ async deleteCache(name, config) {
712
+ try {
713
+ await this.createClient({ ...this.config, ...config }).caches.delete({ name });
714
+ }
715
+ catch (error) {
716
+ throw toGoogleError(error);
717
+ }
718
+ for (const [key, cache] of this.caches) {
719
+ if (cache.name === name)
720
+ this.caches.delete(key);
721
+ }
722
+ }
723
+ /**
724
+ * Count the tokens a chat request's prompt takes, without generating.
725
+ * The Gemini API counts the whole request (system instruction and tools
726
+ * too) through `generateContentRequest`.
727
+ *
728
+ * @returns Total prompt tokens and any cached ones
729
+ */
730
+ async countTokens(request, config) {
731
+ const run = this.prepare('count tokens', request, {}, undefined, config, undefined, 'chat');
732
+ const sent = await prepareRequest(request, this.schemaModel(run), this.planOptions());
733
+ const params = await this.buildChatParams(sent, run);
734
+ const { systemInstruction, tools, toolConfig } = params.config ?? {};
735
+ try {
736
+ if (run.config.vertexai) {
737
+ const result = await run.retry((signal) => run.client.models.countTokens({ model: run.model.id, contents: params.contents, config: { systemInstruction, tools: tools, abortSignal: signal } }));
738
+ return { totalTokens: result.totalTokens ?? 0, cachedContentTokenCount: result.cachedContentTokenCount };
739
+ }
740
+ // The SDK refuses system instructions and tools here on the Gemini
741
+ // API, so the whole request goes as `generateContentRequest`
742
+ const result = await run.retry((signal) => run.client.models.countTokens({
743
+ model: run.model.id,
744
+ contents: params.contents,
745
+ config: {
746
+ abortSignal: signal,
747
+ httpOptions: systemInstruction || tools ? { extraBody: { generateContentRequest: { model: `models/${run.model.id}`, contents: params.contents, systemInstruction, tools, toolConfig } } } : undefined,
748
+ },
749
+ }));
750
+ return { totalTokens: result.totalTokens ?? 0, cachedContentTokenCount: result.cachedContentTokenCount };
751
+ }
752
+ catch (error) {
753
+ throw toGoogleError(error);
754
+ }
755
+ }
756
+ /**
757
+ * The speech config for a voice: a model whose data says it takes any
758
+ * voice id (`speech.voices: 'any'`, Gemini 3.8 TTS) gets it as `voice`
759
+ * (prebuilt, designed `voice_...`, replicated `voicekey_...`); others
760
+ * take prebuilt voice names, unless the voice is a designed or replicated one.
761
+ */
762
+ voiceConfig(info, voice) {
763
+ const modern = googleOptions(info).speech?.voices === 'any' || /^voice(key)?_/.test(voice);
764
+ return { voiceConfig: modern ? { voice } : { prebuiltVoiceConfig: { voiceName: voice } } };
765
+ }
766
+ // ==========================================================================
767
+ // Chat
768
+ // ==========================================================================
769
+ /**
770
+ * Run a chat request.
771
+ */
772
+ async complete(request, run) {
773
+ const params = await this.buildChatParams(request, run);
774
+ const sent = await this.sendChat(run, request, params, (signal) => run.client.models.generateContent({ ...params, config: { ...params.config, abortSignal: signal } }));
775
+ if ('overflow' in sent)
776
+ return sent.overflow;
777
+ const state = new ResponseState();
778
+ const chunks = [...responseChunks(sent.result, state), endChunk(state, candidateParts(sent.result))];
779
+ const response = getResponseFromChunks(chunks, run.model);
780
+ return this.finish('chat', run, request, params, response);
781
+ }
782
+ /**
783
+ * Stream a chat request.
784
+ */
785
+ async *completeStream(request, run) {
786
+ const params = await this.buildChatParams(request, run);
787
+ const sent = await this.sendChat(run, request, params, (signal) => run.client.models.generateContentStream({ ...params, config: { ...params.config, abortSignal: signal } }));
788
+ if ('overflow' in sent)
789
+ return sent.overflow;
790
+ const state = new ResponseState();
791
+ const received = [];
792
+ const parts = [];
793
+ let response;
794
+ try {
795
+ for await (const raw of sent.result) {
796
+ if (run.signal?.aborted)
797
+ throw new GoogleError('Request aborted');
798
+ parts.push(...candidateParts(raw));
799
+ for (const chunk of responseChunks(raw, state)) {
800
+ received.push(chunk);
801
+ yield chunk;
802
+ }
803
+ }
804
+ const end = endChunk(state, parts);
805
+ received.push(end);
806
+ yield end;
807
+ }
808
+ catch (e) {
809
+ throw toGoogleError(e);
810
+ }
811
+ finally {
812
+ response = getResponseFromChunks(received, run.model);
813
+ await this.finish('chat', run, request, params, response);
814
+ }
815
+ return response;
816
+ }
817
+ /**
818
+ * Create an executor for chat requests.
819
+ */
820
+ createExecutor(config) {
821
+ return async (request, ctx, metadata, signal) => {
822
+ const run = this.prepare('chat', request, ctx, metadata, config, signal, 'chat');
823
+ const sent = await prepareRequest(request, this.schemaModel(run), this.planOptions());
824
+ return this.complete(sent, run);
825
+ };
826
+ }
827
+ /**
828
+ * Create a streamer for chat requests.
829
+ */
830
+ createStreamer(config) {
831
+ const provider = this;
832
+ return async function* (request, ctx, metadata, signal) {
833
+ const run = provider.prepare('streaming chat', request, ctx, metadata, config, signal, 'chat');
834
+ const sent = await prepareRequest(request, provider.schemaModel(run), { speaks: provider.supportedStrictFamilies });
835
+ return yield* provider.completeStream(sent, run);
836
+ };
837
+ }
838
+ // ==========================================================================
839
+ // Images
840
+ // ==========================================================================
841
+ /**
842
+ * generateContent parameters for image generation or editing with a
843
+ * Gemini image model: the prompt (after any images), image output only,
844
+ * and an aspect ratio and size from the requested size and quality.
845
+ */
846
+ imageParams(request, run, images) {
847
+ const image = googleOptions(this.infoOf(run)).image;
848
+ const aspectRatio = request.size && request.size !== 'auto' ? nearestAspectRatio(request.size, image?.aspectRatios) : undefined;
849
+ const size = imageSize(request, image?.sizes);
850
+ const outputMimeType = request.outputFormat ? `image/${request.outputFormat}` : undefined;
851
+ const imageConfig = aspectRatio || size || (outputMimeType && run.config.vertexai)
852
+ ? { aspectRatio, imageSize: size, ...(run.config.vertexai ? { outputMimeType, outputCompressionQuality: request.outputCompression } : {}) }
853
+ : undefined;
854
+ const extra = Object.fromEntries(Object.entries(request.extra ?? {}).filter(([key]) => !PROVIDER_EXTRA.has(key)));
855
+ return {
856
+ model: run.model.id,
857
+ contents: [{ role: 'user', parts: [...images, { text: request.prompt }] }],
858
+ config: {
859
+ responseModalities: ['IMAGE'],
860
+ ...(imageConfig ? { imageConfig } : {}),
861
+ ...(request.seed !== undefined ? { seed: request.seed } : {}),
862
+ ...(run.config.safetySettings ? { safetySettings: run.config.safetySettings } : {}),
863
+ ...extra,
864
+ },
865
+ };
866
+ }
867
+ /**
868
+ * Run image generation or editing: `n` calls with a Gemini image model
869
+ * (each makes one image), or one Imagen call.
870
+ */
871
+ async makeImages(op, request, run, images) {
872
+ const image = googleOptions(this.infoOf(run)).image;
873
+ if (googleOptions(this.infoOf(run)).kind === 'imagen') {
874
+ if (!run.config.vertexai) {
875
+ throw new GoogleError('Imagen is served on Vertex AI only (it was shut down on the Gemini API); use a Gemini image model such as gemini-nano-banana-2.1');
876
+ }
877
+ if (op === 'imageEdit') {
878
+ throw new GoogleError('Imagen editing is not supported; edit with a Gemini image model');
879
+ }
880
+ const params = {
881
+ model: run.model.id,
882
+ prompt: request.prompt,
883
+ config: {
884
+ numberOfImages: request.n ?? 1,
885
+ aspectRatio: request.size && request.size !== 'auto' ? nearestAspectRatio(request.size, image?.aspectRatios) : undefined,
886
+ imageSize: imageSize(request, image?.sizes),
887
+ outputMimeType: request.outputFormat ? `image/${request.outputFormat}` : undefined,
888
+ outputCompressionQuality: request.outputCompression,
889
+ seed: request.seed,
890
+ ...request.extra,
891
+ },
892
+ };
893
+ const result = await this.send(op, run, request, params, (signal) => run.client.models.generateImages({ ...params, config: { ...params.config, abortSignal: signal } }));
894
+ const generated = (result.generatedImages ?? []).flatMap(g => g.image?.imageBytes ? [{ b64_json: g.image.imageBytes, revisedPrompt: g.enhancedPrompt }] : []);
895
+ return this.finish(op, run, request, params, { images: generated, model: run.model, usage: { image: { output: [{ quality: 'standard', size: pixelSize(params.config.aspectRatio, params.config.imageSize), count: generated.length }] } } });
896
+ }
897
+ const params = this.imageParams(request, run, images);
898
+ const count = Math.max(1, Math.min(request.n ?? 1, 8));
899
+ const results = await Promise.all(Array.from({ length: count }, () => this.send(op, run, request, params, (signal) => run.client.models.generateContent({ ...params, config: { ...params.config, abortSignal: signal } }))));
900
+ const usage = {};
901
+ const generated = results.flatMap(result => {
902
+ const state = new ResponseState();
903
+ const chunks = [...responseChunks(result, state), endChunk(state)];
904
+ const response = getResponseFromChunks(chunks, run.model);
905
+ for (const [k, v] of Object.entries(response.usage ?? {})) {
906
+ usage[k] = { ...usage[k] };
907
+ for (const [field, n] of Object.entries(v)) {
908
+ usage[k][field] = (usage[k][field] ?? 0) + n;
909
+ }
910
+ }
911
+ if (!response.images?.length && response.finishReason === 'content_filter') {
912
+ throw new GoogleSafetyError(response.refusal ?? 'The image was blocked', result.candidates?.[0]?.finishReason);
913
+ }
914
+ return (response.images ?? []).map(img => ({ ...img, revisedPrompt: response.content || undefined }));
915
+ });
916
+ return this.finish(op, run, request, params, { images: generated, model: run.model, usage });
917
+ }
918
+ /**
919
+ * Generate images: Gemini image models (Nano Banana) through
920
+ * generateContent, Imagen (Vertex AI) through generateImages.
921
+ */
922
+ generateImage = async (request, ctx, config) => {
923
+ const run = this.prepare('generate image', request, ctx, undefined, config, undefined, 'imageGenerate');
924
+ return this.makeImages('imageGenerate', request, run, []);
925
+ };
926
+ /**
927
+ * Edit or combine images with a prompt: the image, its references, and a
928
+ * mask (described to the model, which has no mask input) go before the
929
+ * prompt.
930
+ */
931
+ editImage = async (request, ctx, config) => {
932
+ const run = this.prepare('edit image', request, ctx, undefined, config, undefined, 'imageEdit');
933
+ const images = await this.editImages(request, run);
934
+ return this.makeImages('imageEdit', request, run, images);
935
+ };
936
+ /**
937
+ * The image parts of an edit.
938
+ */
939
+ async editImages(request, run) {
940
+ const parts = await Promise.all([request.image, ...request.references ?? []].map(image => this.convertMedia({ type: 'image', content: image }, run)));
941
+ if (request.mask) {
942
+ parts.push({ text: 'The next image is a mask: change only the areas of the first image where the mask is transparent or white.' });
943
+ parts.push(await this.convertMedia({ type: 'image', content: request.mask }, run));
944
+ }
945
+ return parts;
946
+ }
947
+ /**
948
+ * Stream image generation: the model's draft ("thought") images as
949
+ * progress, then each final image.
950
+ */
951
+ generateImageStream = async function* (request, ctx, config) {
952
+ const run = this.prepare('generate image stream', request, ctx, undefined, config, undefined, 'imageGenerate');
953
+ yield* this.imageStream('imageGenerate', request, run, []);
954
+ };
955
+ /**
956
+ * Stream image editing.
957
+ */
958
+ editImageStream = async function* (request, ctx, config) {
959
+ const run = this.prepare('edit image stream', request, ctx, undefined, config, undefined, 'imageEdit');
960
+ yield* this.imageStream('imageEdit', request, run, await this.editImages(request, run));
961
+ };
962
+ /**
963
+ * Stream one image call, with draft images as progress.
964
+ */
965
+ async *imageStream(op, request, run, images) {
966
+ if (googleOptions(this.infoOf(run)).kind === 'imagen') {
967
+ const result = await this.makeImages(op, request, run, images);
968
+ for (const image of result.images)
969
+ yield { image, done: true, progress: 1, model: run.model, usage: result.usage };
970
+ return;
971
+ }
972
+ const params = this.imageParams(request, run, images);
973
+ const stream = await this.send(op, run, request, params, (signal) => run.client.models.generateContentStream({ ...params, config: { ...params.config, abortSignal: signal } }));
974
+ const done = [];
975
+ let drafts = 0;
976
+ let last;
977
+ for await (const chunk of stream) {
978
+ if (run.signal?.aborted)
979
+ throw new GoogleError('Request aborted');
980
+ last = chunk;
981
+ for (const part of candidateParts(chunk)) {
982
+ const data = part.inlineData?.data;
983
+ if (!data || !(part.inlineData?.mimeType ?? '').startsWith('image/'))
984
+ continue;
985
+ const image = { b64_json: data, url: `data:${part.inlineData.mimeType};base64,${data}` };
986
+ if (part.thought) {
987
+ drafts++;
988
+ yield { image, done: false, progress: Math.min(0.9, drafts / (drafts + 1)), model: run.model };
989
+ }
990
+ else {
991
+ done.push(image);
992
+ yield { image, done: true, progress: 1, model: run.model, usage: toUsage(chunk.usageMetadata) };
993
+ }
994
+ }
995
+ }
996
+ if (!done.length && last?.candidates?.[0]?.finishReason && last.candidates[0].finishReason !== 'STOP') {
997
+ throw new GoogleSafetyError(`No image was made (${last.candidates[0].finishReason})`, last.candidates[0].finishReason);
998
+ }
999
+ await this.finish(op, run, request, params, { images: done, model: run.model, usage: toUsage(last?.usageMetadata) });
1000
+ }
1001
+ // ==========================================================================
1002
+ // Speech
1003
+ // ==========================================================================
1004
+ /**
1005
+ * Generate speech with a Gemini TTS model. Gemini speaks 24 kHz 16-bit
1006
+ * mono PCM, returned as WAV (the default) or raw PCM; other encodings
1007
+ * aren't offered and come back as WAV (`responseFormat` says which).
1008
+ * `instructions` and `speed` become the turn's speaking style
1009
+ * (`speechMetadata.style` on Gemini 3.8 TTS, a spoken direction before).
1010
+ */
1011
+ speech = async (request, ctx, config) => {
1012
+ const run = this.prepare('speech', request, ctx, undefined, config, undefined, 'speech');
1013
+ const info = this.infoOf(run);
1014
+ const modern = googleOptions(info).speech?.style === 'metadata';
1015
+ const pace = request.speed === undefined || Math.abs(request.speed - 1) < 0.1 ? undefined
1016
+ : request.speed < 1 ? `speaking slowly (${request.speed}x)` : `speaking quickly (${request.speed}x)`;
1017
+ const style = [request.instructions, pace].filter(Boolean).join(', ') || undefined;
1018
+ const part = modern
1019
+ ? { text: request.text, ...(style ? { speechMetadata: { style } } : {}) }
1020
+ : { text: style ? `Say in this style (${style}): ${request.text}` : request.text };
1021
+ const extra = Object.fromEntries(Object.entries(request.extra ?? {}).filter(([key]) => !PROVIDER_EXTRA.has(key)));
1022
+ const params = {
1023
+ model: run.model.id,
1024
+ contents: [{ role: 'user', parts: [part] }],
1025
+ config: { responseModalities: ['AUDIO'], speechConfig: this.voiceConfig(info, request.voice ?? 'Kore'), ...extra },
1026
+ };
1027
+ const result = await this.send('speech', run, request, params, (signal) => run.client.models.generateContent({ ...params, config: { ...params.config, abortSignal: signal } }));
1028
+ const inline = candidateParts(result).find(p => p.inlineData?.data)?.inlineData;
1029
+ if (!inline?.data) {
1030
+ throw new GoogleError(`Speech response had no audio (${result.candidates?.[0]?.finishReason ?? result.promptFeedback?.blockReason ?? 'unknown'})`);
1031
+ }
1032
+ const bytes = Buffer.from(inline.data, 'base64');
1033
+ const wav = isWav(bytes);
1034
+ const format = request.responseFormat === 'pcm' ? 'pcm' : 'wav';
1035
+ const audio = format === 'pcm' ? (wav ? wavToPcm(bytes) : bytes) : (wav ? bytes : pcmToWav(bytes, sampleRate(inline.mimeType)));
1036
+ return this.finish('speech', run, request, params, { model: run.model, audio: bytesStream(audio), responseFormat: format, usage: toUsage(result.usageMetadata) });
1037
+ };
1038
+ // ==========================================================================
1039
+ // Transcription
1040
+ // ==========================================================================
1041
+ /**
1042
+ * Transcription parameters: Gemini Transcribe models take an
1043
+ * `audioTranscriptionConfig` (languages, custom vocabulary from the
1044
+ * prompt, diarization and word timestamps for the formats that show
1045
+ * them); other Gemini models are asked to transcribe.
1046
+ */
1047
+ async transcriptionParams(request, run) {
1048
+ const audio = await this.convertMedia({ type: 'audio', content: request.audio }, run);
1049
+ const extra = Object.fromEntries(Object.entries(request.extra ?? {}).filter(([key]) => !PROVIDER_EXTRA.has(key)));
1050
+ if (googleOptions(this.infoOf(run)).kind === 'transcribe') {
1051
+ const format = request.responseFormat;
1052
+ const diarization = format === 'diarized_json' || undefined;
1053
+ const wordTimestamp = format === 'srt' || format === 'vtt' || (format === 'verbose_json' && !!request.timestampGranularities?.length) || diarization || undefined;
1054
+ // Custom vocabulary can't be combined with diarization or timestamps
1055
+ const customVocabulary = !diarization && !wordTimestamp && request.prompt
1056
+ ? request.prompt.split(/[,\n]/).map(term => term.trim()).filter(Boolean).slice(0, 1000)
1057
+ : undefined;
1058
+ return {
1059
+ model: run.model.id,
1060
+ contents: [{ role: 'user', parts: [audio] }],
1061
+ config: {
1062
+ audioTranscriptionConfig: {
1063
+ ...(request.language ? { languageCodes: [request.language] } : {}),
1064
+ ...(customVocabulary?.length ? { customVocabulary } : {}),
1065
+ ...(diarization ? { diarization } : {}),
1066
+ ...(wordTimestamp ? { wordTimestamp } : {}),
1067
+ ...extra.audioTranscriptionConfig,
1068
+ },
1069
+ ...Object.fromEntries(Object.entries(extra).filter(([key]) => key !== 'audioTranscriptionConfig')),
1070
+ },
1071
+ };
1072
+ }
1073
+ const instruction = [
1074
+ 'Transcribe the speech in this audio verbatim. Reply with only the transcript.',
1075
+ request.language ? `The language is ${request.language}.` : '',
1076
+ request.prompt ? `Context: ${request.prompt}` : '',
1077
+ ].filter(Boolean).join(' ');
1078
+ return {
1079
+ model: run.model.id,
1080
+ contents: [{ role: 'user', parts: [audio, { text: instruction }] }],
1081
+ config: { ...(request.temperature !== undefined ? { temperature: request.temperature } : {}), ...extra },
1082
+ };
1083
+ }
1084
+ /**
1085
+ * Transcript text and timed segments from a response.
1086
+ */
1087
+ transcript(result) {
1088
+ const segments = [];
1089
+ const texts = [];
1090
+ for (const part of candidateParts(result)) {
1091
+ const t = part.audioTranscription;
1092
+ if (t) {
1093
+ const words = t.words ?? [];
1094
+ const text = t.text ?? words.map(w => w.word).join(' ');
1095
+ if (text)
1096
+ texts.push(text);
1097
+ if (words.length || t.startOffset) {
1098
+ segments.push({
1099
+ id: String(segments.length),
1100
+ start: seconds(t.startOffset ?? words[0]?.startOffset),
1101
+ end: seconds(t.endOffset ?? words[words.length - 1]?.endOffset),
1102
+ text,
1103
+ speaker: t.speakerLabel,
1104
+ });
1105
+ }
1106
+ }
1107
+ else if (part.text && !part.thought) {
1108
+ texts.push(part.text);
1109
+ }
1110
+ }
1111
+ return { text: texts.join(segments.length ? ' ' : ''), segments };
1112
+ }
1113
+ /**
1114
+ * Transcribe audio. SRT and WebVTT are built from word timestamps.
1115
+ */
1116
+ transcribe = async (request, ctx, config) => {
1117
+ const run = this.prepare('transcribe', request, ctx, undefined, config, undefined, 'transcription');
1118
+ const params = await this.transcriptionParams(request, run);
1119
+ const result = await this.send('transcribe', run, request, params, (signal) => run.client.models.generateContent({ ...params, config: { ...params.config, abortSignal: signal } }));
1120
+ const { text, segments } = this.transcript(result);
1121
+ const format = request.responseFormat;
1122
+ return this.finish('transcribe', run, request, params, {
1123
+ text: (format === 'srt' || format === 'vtt') && segments.length ? captions(segments, format) : text.trim(),
1124
+ segments: segments.length ? segments : undefined,
1125
+ model: run.model,
1126
+ usage: toUsage(result.usageMetadata),
1127
+ });
1128
+ };
1129
+ /**
1130
+ * Transcribe audio, streaming text as it's recognized.
1131
+ */
1132
+ transcribeStream = async function* (request, ctx, config) {
1133
+ const run = this.prepare('transcribe stream', request, ctx, undefined, config, undefined, 'transcription');
1134
+ const params = await this.transcriptionParams(request, run);
1135
+ const stream = await this.send('transcribe', run, request, params, (signal) => run.client.models.generateContentStream({ ...params, config: { ...params.config, abortSignal: signal } }));
1136
+ let text = '';
1137
+ let usage;
1138
+ for await (const chunk of stream) {
1139
+ if (run.signal?.aborted)
1140
+ throw new GoogleError('Request aborted');
1141
+ usage = toUsage(chunk.usageMetadata) ?? usage;
1142
+ const { text: delta, segments } = this.transcript(chunk);
1143
+ if (delta) {
1144
+ const piece = text && !text.endsWith(' ') && segments.length ? ` ${delta}` : delta;
1145
+ text += piece;
1146
+ yield { delta: piece };
1147
+ }
1148
+ for (const segment of segments)
1149
+ yield { segment };
1150
+ }
1151
+ yield { text: text.trim(), usage, model: run.model };
1152
+ };
1153
+ // ==========================================================================
1154
+ // Embeddings
1155
+ // ==========================================================================
1156
+ /**
1157
+ * Task prefixes Gemini Embedding 2 reads in place of a task type
1158
+ * (/docs/embeddings "Task types with Embeddings 2").
1159
+ */
1160
+ static TASK_PREFIXES = {
1161
+ RETRIEVAL_QUERY: (t) => `task: search result | query: ${t}`,
1162
+ QUESTION_ANSWERING: (t) => `task: question answering | query: ${t}`,
1163
+ FACT_VERIFICATION: (t) => `task: fact checking | query: ${t}`,
1164
+ CODE_RETRIEVAL_QUERY: (t) => `task: code retrieval | query: ${t}`,
1165
+ CLASSIFICATION: (t) => `task: classification | query: ${t}`,
1166
+ CLUSTERING: (t) => `task: clustering | query: ${t}`,
1167
+ SEMANTIC_SIMILARITY: (t) => `task: sentence similarity | query: ${t}`,
1168
+ RETRIEVAL_DOCUMENT: (t, title) => `title: ${title ?? 'none'} | text: ${t}`,
1169
+ };
1170
+ /**
1171
+ * Embed texts, and images with Gemini Embedding 2. Each input is its own
1172
+ * content, so each gets its own vector. `extra.taskType` sets the task
1173
+ * (gemini-embedding-001) or the task prefix (Gemini Embedding 2);
1174
+ * `dimensions` is the output dimensionality.
1175
+ */
1176
+ embed = async (request, ctx, config) => {
1177
+ const run = this.prepare('embed', request, ctx, undefined, config, undefined, 'embedding');
1178
+ const inputs = embeddingInputs(request);
1179
+ const multimodal = !!googleOptions(this.infoOf(run)).embedding?.multimodal;
1180
+ if (!multimodal)
1181
+ embeddingTexts(request, run.model.id);
1182
+ const { taskType, title, ...extra } = Object.fromEntries(Object.entries(request.extra ?? {}).filter(([key]) => !PROVIDER_EXTRA.has(key)));
1183
+ const prefix = multimodal && typeof taskType === 'string' ? GoogleProvider.TASK_PREFIXES[taskType] : undefined;
1184
+ const contents = await Promise.all(inputs.map(async (input) => isEmbeddingImage(input)
1185
+ ? { parts: [await this.convertMedia({ type: 'image', content: input.image, format: input.mimeType }, run)] }
1186
+ : { parts: [{ text: prefix ? prefix(input, title) : input }] }));
1187
+ const params = {
1188
+ model: run.model.id,
1189
+ contents,
1190
+ config: {
1191
+ outputDimensionality: request.dimensions,
1192
+ ...(!multimodal && taskType ? { taskType } : {}),
1193
+ ...(!multimodal && title ? { title } : {}),
1194
+ ...extra,
1195
+ },
1196
+ };
1197
+ const result = await this.send('embed', run, request, params, (signal) => run.client.models.embedContent({ ...params, config: { ...params.config, abortSignal: signal } }));
1198
+ const embeddings = (result.embeddings ?? []).map((e, index) => ({ embedding: e.values ?? [], index }));
1199
+ if (embeddings.length !== inputs.length) {
1200
+ throw new GoogleError(`Expected ${inputs.length} embeddings from ${run.model.id}, got ${embeddings.length}`);
1201
+ }
1202
+ const images = inputs.filter(isEmbeddingImage).length;
1203
+ const tokens = result.usageMetadata?.promptTokenCount;
1204
+ return this.finish('embed', run, request, params, {
1205
+ embeddings,
1206
+ model: run.model,
1207
+ usage: { embeddings: { count: embeddings.length, ...(tokens ? { tokens } : {}), ...(images ? { images } : {}) } },
1208
+ });
1209
+ };
1210
+ // ==========================================================================
1211
+ // Decisions
1212
+ // ==========================================================================
1213
+ /**
1214
+ * Typed answers about an input with Gemini Decision 1. A conversation is
1215
+ * serialized as text (the API takes no turns); images go as image blocks.
1216
+ * A blocked input answers every question with a refusal.
1217
+ */
1218
+ decide = async (request, ctx, config) => {
1219
+ const run = this.prepare('decide', request, ctx, undefined, config, undefined, 'decision');
1220
+ const text = typeof request.input === 'string'
1221
+ ? request.input
1222
+ : (await Promise.all(request.input.map(async (m) => `${m.role}: ${typeof m.content === 'string' ? m.content : (await Promise.all(m.content.filter(p => p.type === 'text').map(p => toText(p.content)))).join('\n')}`))).join('\n\n');
1223
+ const media = [];
1224
+ const resources = [
1225
+ ...(request.images ?? []).map(image => ({ type: 'image', content: image })),
1226
+ ...(typeof request.input === 'string' ? [] : request.input.flatMap(m => typeof m.content === 'string' ? [] : m.content.filter(p => p.type !== 'text'))),
1227
+ ];
1228
+ for (const resource of resources) {
1229
+ const part = await this.convertMedia(resource, run);
1230
+ const type = (resource.type === 'file' ? 'document' : resource.type);
1231
+ media.push(part.inlineData
1232
+ ? { type, data: part.inlineData.data, mime_type: part.inlineData.mimeType }
1233
+ : { type, uri: part.fileData?.fileUri, mime_type: part.fileData?.mimeType ?? 'image/png' });
1234
+ }
1235
+ const params = {
1236
+ model: run.model.id,
1237
+ input: media.length ? [{ type: 'text', text }, ...media] : text,
1238
+ questions: Object.fromEntries(Object.entries(request.questions).map(([name, q]) => [name, toDecisionQuestion(q)])),
1239
+ ...request.extra,
1240
+ };
1241
+ const refusals = () => Object.fromEntries(Object.keys(request.questions).map(name => [name, { type: 'refusal' }]));
1242
+ let result;
1243
+ try {
1244
+ result = await this.send('decide', run, request, params, (signal) => run.client.decisions.create(params, { signal }));
1245
+ }
1246
+ catch (e) {
1247
+ const { status, body, message } = errorDetails(e.cause ?? e);
1248
+ const code = body?.code;
1249
+ if (status === 400 && (typeof code === 'string' || /safety|blocked|prohibited/i.test(message))) {
1250
+ return this.finish('decide', run, request, params, { answers: refusals(), model: run.model });
1251
+ }
1252
+ throw e;
1253
+ }
1254
+ if (result.prompt_feedback?.block_reason) {
1255
+ return this.finish('decide', run, request, params, { answers: refusals(), model: run.model, usage: decisionUsage(result.usage) });
1256
+ }
1257
+ const answers = Object.fromEntries(Object.entries(request.questions).map(([name, q]) => [name, toDecisionAnswer(result.answers?.[name], q.type === 'score' ? q.levels.length : 0)]));
1258
+ return this.finish('decide', run, request, params, { answers, model: run.model, usage: decisionUsage(result.usage) });
1259
+ };
1260
+ // ==========================================================================
1261
+ // Batches
1262
+ // ==========================================================================
1263
+ /**
1264
+ * Run chat requests as one batch on one model (half price, results
1265
+ * within a day). Each request is the call a direct request would make.
1266
+ */
1267
+ submitBatch = async (requests, ctx, config) => {
1268
+ const [first] = requests;
1269
+ if (!first)
1270
+ throw new GoogleError('A batch needs at least one request');
1271
+ const run = this.prepare('submit batch', first, ctx, undefined, { ...config, explicitCaching: false }, undefined, 'chat');
1272
+ const inlined = await Promise.all(requests.map(async (request) => {
1273
+ const sent = await prepareRequest(request, this.schemaModel(run), this.planOptions());
1274
+ const params = await this.buildChatParams(sent, run);
1275
+ return { contents: params.contents, config: params.config };
1276
+ }));
1277
+ try {
1278
+ const job = await run.retry((signal) => run.client.batches.create({ model: run.model.id, src: inlined, config: { abortSignal: signal } }));
1279
+ return this.batchJob(job, run);
1280
+ }
1281
+ catch (error) {
1282
+ throw toGoogleError(error);
1283
+ }
1284
+ };
1285
+ /**
1286
+ * A batch as it stands, with its results once it completes.
1287
+ */
1288
+ getBatch = async (job, ctx, config) => {
1289
+ const run = this.prepare('get batch', { model: job.model }, ctx, undefined, config, undefined, 'chat');
1290
+ try {
1291
+ const batch = await run.retry((signal) => run.client.batches.get({ name: job.id, config: { abortSignal: signal } }));
1292
+ const result = this.batchJob(batch, run);
1293
+ if (result.status !== 'completed')
1294
+ return result;
1295
+ const results = (batch.dest?.inlinedResponses ?? []).map((line) => {
1296
+ if (line.error || !line.response)
1297
+ return { error: line.error?.message ?? 'No result' };
1298
+ const state = new ResponseState();
1299
+ return { response: getResponseFromChunks([...responseChunks(line.response, state), endChunk(state, candidateParts(line.response))], run.model) };
1300
+ });
1301
+ return { ...result, results };
1302
+ }
1303
+ catch (error) {
1304
+ throw toGoogleError(error);
1305
+ }
1306
+ };
1307
+ /**
1308
+ * A batch job as @aeye reports it.
1309
+ */
1310
+ batchJob(batch, run) {
1311
+ const states = {
1312
+ JOB_STATE_QUEUED: 'validating', JOB_STATE_PENDING: 'validating', JOB_STATE_RUNNING: 'in_progress', JOB_STATE_UPDATING: 'in_progress',
1313
+ JOB_STATE_PAUSED: 'in_progress', JOB_STATE_SUCCEEDED: 'completed', JOB_STATE_PARTIALLY_SUCCEEDED: 'completed',
1314
+ JOB_STATE_FAILED: 'failed', JOB_STATE_CANCELLING: 'cancelling', JOB_STATE_CANCELLED: 'cancelled', JOB_STATE_EXPIRED: 'expired',
1315
+ BATCH_STATE_PENDING: 'validating', BATCH_STATE_RUNNING: 'in_progress', BATCH_STATE_SUCCEEDED: 'completed', BATCH_STATE_FAILED: 'failed',
1316
+ BATCH_STATE_CANCELLED: 'cancelled', BATCH_STATE_EXPIRED: 'expired',
1317
+ };
1318
+ const stats = batch.completionStats;
1319
+ const completed = Number(stats?.successfulCount ?? 0);
1320
+ const failed = Number(stats?.failedCount ?? 0);
1321
+ return {
1322
+ id: batch.name ?? '',
1323
+ provider: this.name,
1324
+ model: run.model.id,
1325
+ status: states[batch.state ?? ''] ?? 'in_progress',
1326
+ counts: stats ? { total: completed + failed + Number(stats.incompleteCount ?? 0), completed, failed } : undefined,
1327
+ error: batch.error?.message,
1328
+ };
1329
+ }
1330
+ // ==========================================================================
1331
+ // Image analysis
1332
+ // ==========================================================================
1333
+ /**
1334
+ * An image analysis request as a chat request.
1335
+ */
1336
+ analysisChat(request, config) {
1337
+ const chat = {
1338
+ model: request.model,
1339
+ messages: [{
1340
+ role: 'user',
1341
+ content: [
1342
+ { type: 'text', content: request.prompt },
1343
+ ...request.images.map((image) => ({ type: 'image', content: image })),
1344
+ ],
1345
+ }],
1346
+ temperature: request.temperature,
1347
+ maxTokens: request.maxTokens,
1348
+ };
1349
+ return [chat, { model: config?.defaultModels?.imageAnalyze ?? this.config.defaultModels?.imageAnalyze ?? this.defaults.imageAnalyze }];
1350
+ }
1351
+ /**
1352
+ * Analyze images with a vision model, as chat.
1353
+ */
1354
+ analyzeImage = (request, ctx, config) => {
1355
+ const [chat, metadata] = this.analysisChat(request, config);
1356
+ return this.createExecutor(config)(chat, ctx, metadata);
1357
+ };
1358
+ /**
1359
+ * Analyze images, streaming the answer.
1360
+ */
1361
+ analyzeImageStream = (request, ctx, config) => {
1362
+ const [chat, metadata] = this.analysisChat(request, config);
1363
+ return this.createStreamer(config)(chat, ctx, metadata);
1364
+ };
1365
+ }
1366
+ //# sourceMappingURL=google.js.map