@tanstack/ai-gemini 0.18.1 → 0.18.3
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/esm/adapters/audio.d.ts +92 -0
- package/dist/esm/adapters/audio.js +66 -0
- package/dist/esm/adapters/audio.js.map +1 -0
- package/dist/esm/adapters/image.d.ts +101 -0
- package/dist/esm/adapters/image.js +253 -0
- package/dist/esm/adapters/image.js.map +1 -0
- package/dist/esm/adapters/summarize.d.ts +33 -0
- package/dist/esm/adapters/summarize.js +18 -0
- package/dist/esm/adapters/summarize.js.map +1 -0
- package/dist/esm/adapters/text.d.ts +85 -0
- package/dist/esm/adapters/text.js +658 -0
- package/dist/esm/adapters/text.js.map +1 -0
- package/dist/esm/adapters/tts.d.ts +165 -0
- package/dist/esm/adapters/tts.js +192 -0
- package/dist/esm/adapters/tts.js.map +1 -0
- package/dist/esm/adapters/video.d.ts +108 -0
- package/dist/esm/adapters/video.js +227 -0
- package/dist/esm/adapters/video.js.map +1 -0
- package/dist/esm/experimental/index.d.ts +6 -0
- package/dist/esm/experimental/index.js +7 -0
- package/dist/esm/experimental/index.js.map +1 -0
- package/dist/esm/experimental/text-interactions/adapter.d.ts +75 -0
- package/dist/esm/experimental/text-interactions/adapter.js +1052 -0
- package/dist/esm/experimental/text-interactions/adapter.js.map +1 -0
- package/dist/esm/experimental/text-interactions/events.d.ts +147 -0
- package/dist/esm/experimental/text-interactions/provider-options.d.ts +15 -0
- package/dist/esm/image/image-provider-options.d.ts +181 -0
- package/dist/esm/image/image-provider-options.js +67 -0
- package/dist/esm/image/image-provider-options.js.map +1 -0
- package/dist/esm/index.d.ts +33 -0
- package/dist/esm/index.js +38 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/message-types.d.ts +104 -0
- package/dist/esm/model-meta.d.ts +242 -0
- package/dist/esm/model-meta.js +159 -0
- package/dist/esm/model-meta.js.map +1 -0
- package/dist/esm/text/text-provider-options.d.ts +196 -0
- package/dist/esm/tools/code-execution-tool.d.ts +10 -0
- package/dist/esm/tools/code-execution-tool.js +18 -0
- package/dist/esm/tools/code-execution-tool.js.map +1 -0
- package/dist/esm/tools/computer-use-tool.d.ts +13 -0
- package/dist/esm/tools/computer-use-tool.js +33 -0
- package/dist/esm/tools/computer-use-tool.js.map +1 -0
- package/dist/esm/tools/file-search-tool.d.ts +10 -0
- package/dist/esm/tools/file-search-tool.js +19 -0
- package/dist/esm/tools/file-search-tool.js.map +1 -0
- package/dist/esm/tools/function-declaration-tool.d.ts +5 -0
- package/dist/esm/tools/function-declaration-tool.js +28 -0
- package/dist/esm/tools/function-declaration-tool.js.map +1 -0
- package/dist/esm/tools/google-maps-tool.d.ts +10 -0
- package/dist/esm/tools/google-maps-tool.js +19 -0
- package/dist/esm/tools/google-maps-tool.js.map +1 -0
- package/dist/esm/tools/google-search-retriveal-tool.d.ts +10 -0
- package/dist/esm/tools/google-search-retriveal-tool.js +19 -0
- package/dist/esm/tools/google-search-retriveal-tool.js.map +1 -0
- package/dist/esm/tools/google-search-tool.d.ts +10 -0
- package/dist/esm/tools/google-search-tool.js +19 -0
- package/dist/esm/tools/google-search-tool.js.map +1 -0
- package/dist/esm/tools/index.d.ts +18 -0
- package/dist/esm/tools/index.js +21 -0
- package/dist/esm/tools/index.js.map +1 -0
- package/dist/esm/tools/tool-converter.d.ts +22 -0
- package/dist/esm/tools/tool-converter.js +66 -0
- package/dist/esm/tools/tool-converter.js.map +1 -0
- package/dist/esm/tools/url-context-tool.d.ts +10 -0
- package/dist/esm/tools/url-context-tool.js +18 -0
- package/dist/esm/tools/url-context-tool.js.map +1 -0
- package/dist/esm/usage.d.ts +67 -0
- package/dist/esm/usage.js +94 -0
- package/dist/esm/usage.js.map +1 -0
- package/dist/esm/utils/client.d.ts +17 -0
- package/dist/esm/utils/client.js +30 -0
- package/dist/esm/utils/client.js.map +1 -0
- package/dist/esm/utils/index.d.ts +1 -0
- package/dist/esm/video/video-provider-options.d.ts +90 -0
- package/dist/esm/video/video-provider-options.js +15 -0
- package/dist/esm/video/video-provider-options.js.map +1 -0
- package/package.json +4 -4
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { BaseAudioAdapter } from '@tanstack/ai/adapters';
|
|
2
|
+
import { GEMINI_AUDIO_MODELS } from '../model-meta.js';
|
|
3
|
+
import { AudioGenerationOptions, AudioGenerationResult } from '@tanstack/ai';
|
|
4
|
+
import { GeminiClientConfig } from '../utils.js';
|
|
5
|
+
/**
|
|
6
|
+
* Provider options for Gemini Lyria music generation.
|
|
7
|
+
*
|
|
8
|
+
* Notes on the Lyria 3 surface area:
|
|
9
|
+
* - `lyria-3-clip-preview` always returns MP3 (30-second clips). It does
|
|
10
|
+
* not accept `responseMimeType`, and duration is fixed at 30 seconds —
|
|
11
|
+
* the generic `duration` option on `AudioActivityOptions` is ignored.
|
|
12
|
+
* - `lyria-3-pro-preview` returns MP3 by default. Duration is controlled
|
|
13
|
+
* via the natural-language prompt, not a separate SDK field, so the
|
|
14
|
+
* generic `duration` option is similarly ignored.
|
|
15
|
+
* - `negativePrompt` is NOT accepted by `GenerateContentConfig` and has
|
|
16
|
+
* therefore been removed from this surface to avoid giving callers a
|
|
17
|
+
* silently-dropped knob.
|
|
18
|
+
*
|
|
19
|
+
* @see https://ai.google.dev/gemini-api/docs/music-generation
|
|
20
|
+
*/
|
|
21
|
+
export interface GeminiAudioProviderOptions {
|
|
22
|
+
/**
|
|
23
|
+
* Seed for deterministic generation.
|
|
24
|
+
*/
|
|
25
|
+
seed?: number;
|
|
26
|
+
}
|
|
27
|
+
export interface GeminiAudioConfig extends GeminiClientConfig {
|
|
28
|
+
}
|
|
29
|
+
/** Model type for Gemini Lyria audio generation */
|
|
30
|
+
export type GeminiAudioModel = (typeof GEMINI_AUDIO_MODELS)[number];
|
|
31
|
+
/**
|
|
32
|
+
* Gemini Lyria Music Generation Adapter.
|
|
33
|
+
*
|
|
34
|
+
* Tree-shakeable adapter for Google Lyria music generation via the Gemini API.
|
|
35
|
+
*
|
|
36
|
+
* Models:
|
|
37
|
+
* - `lyria-3-pro-preview` — flagship model, full-length songs with verses,
|
|
38
|
+
* choruses, and bridges. Outputs MP3 or WAV at 48 kHz stereo.
|
|
39
|
+
* - `lyria-3-clip-preview` — 30-second clips in MP3.
|
|
40
|
+
*
|
|
41
|
+
* @see https://ai.google.dev/gemini-api/docs/music-generation
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* ```typescript
|
|
45
|
+
* const adapter = geminiAudio('lyria-3-pro-preview')
|
|
46
|
+
* const result = await generateAudio({
|
|
47
|
+
* adapter,
|
|
48
|
+
* prompt: 'An upbeat jazz track with saxophone and drums',
|
|
49
|
+
* })
|
|
50
|
+
* ```
|
|
51
|
+
*/
|
|
52
|
+
export declare class GeminiAudioAdapter<TModel extends GeminiAudioModel> extends BaseAudioAdapter<TModel, GeminiAudioProviderOptions> {
|
|
53
|
+
readonly name: "gemini";
|
|
54
|
+
private readonly client;
|
|
55
|
+
constructor(config: GeminiAudioConfig, model: TModel);
|
|
56
|
+
generateAudio(options: AudioGenerationOptions<GeminiAudioProviderOptions>): Promise<AudioGenerationResult>;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Creates a Gemini Lyria audio adapter with an explicit API key.
|
|
60
|
+
*
|
|
61
|
+
* @param model - The Lyria model name (e.g., 'lyria-3-pro-preview')
|
|
62
|
+
* @param apiKey - Your Google API key
|
|
63
|
+
* @param config - Optional additional configuration
|
|
64
|
+
*
|
|
65
|
+
* @example
|
|
66
|
+
* ```typescript
|
|
67
|
+
* const adapter = createGeminiAudio('lyria-3-pro-preview', 'your-api-key')
|
|
68
|
+
* const result = await generateAudio({
|
|
69
|
+
* adapter,
|
|
70
|
+
* prompt: 'Ambient electronic music with soft pads',
|
|
71
|
+
* })
|
|
72
|
+
* ```
|
|
73
|
+
*/
|
|
74
|
+
export declare function createGeminiAudio<TModel extends GeminiAudioModel>(model: TModel, apiKey: string, config?: Omit<GeminiAudioConfig, 'apiKey'>): GeminiAudioAdapter<TModel>;
|
|
75
|
+
/**
|
|
76
|
+
* Creates a Gemini Lyria audio adapter with automatic API key detection.
|
|
77
|
+
*
|
|
78
|
+
* Looks for `GOOGLE_API_KEY` or `GEMINI_API_KEY` in the environment.
|
|
79
|
+
*
|
|
80
|
+
* @param model - The Lyria model name (e.g., 'lyria-3-pro-preview')
|
|
81
|
+
* @param config - Optional configuration (excluding apiKey)
|
|
82
|
+
*
|
|
83
|
+
* @example
|
|
84
|
+
* ```typescript
|
|
85
|
+
* const adapter = geminiAudio('lyria-3-pro-preview')
|
|
86
|
+
* const result = await generateAudio({
|
|
87
|
+
* adapter,
|
|
88
|
+
* prompt: 'An orchestral piece with strings and brass',
|
|
89
|
+
* })
|
|
90
|
+
* ```
|
|
91
|
+
*/
|
|
92
|
+
export declare function geminiAudio<TModel extends GeminiAudioModel>(model: TModel, config?: Omit<GeminiAudioConfig, 'apiKey'>): GeminiAudioAdapter<TModel>;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { BaseAudioAdapter } from "@tanstack/ai/adapters";
|
|
2
|
+
import { createGeminiClient, generateId, getGeminiApiKeyFromEnv } from "../utils/client.js";
|
|
3
|
+
import { buildGeminiUsage } from "../usage.js";
|
|
4
|
+
class GeminiAudioAdapter extends BaseAudioAdapter {
|
|
5
|
+
name = "gemini";
|
|
6
|
+
client;
|
|
7
|
+
constructor(config, model) {
|
|
8
|
+
super(model, config);
|
|
9
|
+
this.client = createGeminiClient(config);
|
|
10
|
+
}
|
|
11
|
+
async generateAudio(options) {
|
|
12
|
+
const { model, prompt, modelOptions, logger } = options;
|
|
13
|
+
logger.request(`activity=generateAudio provider=gemini model=${model}`, {
|
|
14
|
+
provider: "gemini",
|
|
15
|
+
model
|
|
16
|
+
});
|
|
17
|
+
try {
|
|
18
|
+
const response = await this.client.models.generateContent({
|
|
19
|
+
model,
|
|
20
|
+
contents: [{ role: "user", parts: [{ text: prompt }] }],
|
|
21
|
+
config: {
|
|
22
|
+
responseModalities: ["AUDIO", "TEXT"],
|
|
23
|
+
...modelOptions?.seed != null ? { seed: modelOptions.seed } : {}
|
|
24
|
+
}
|
|
25
|
+
});
|
|
26
|
+
const parts = response.candidates?.[0]?.content?.parts ?? [];
|
|
27
|
+
const audioPart = parts.find(
|
|
28
|
+
(part) => part.inlineData?.mimeType?.startsWith("audio/")
|
|
29
|
+
);
|
|
30
|
+
if (!audioPart?.inlineData?.data) {
|
|
31
|
+
throw new Error("No audio data in Gemini Lyria response");
|
|
32
|
+
}
|
|
33
|
+
const contentType = audioPart.inlineData.mimeType;
|
|
34
|
+
return {
|
|
35
|
+
id: generateId(this.name),
|
|
36
|
+
model,
|
|
37
|
+
audio: {
|
|
38
|
+
b64Json: audioPart.inlineData.data,
|
|
39
|
+
...contentType !== void 0 && { contentType }
|
|
40
|
+
},
|
|
41
|
+
// Surface token usage (with per-modality breakdown) when Gemini reports
|
|
42
|
+
// it. Spread conditionally for exactOptionalPropertyTypes.
|
|
43
|
+
...response.usageMetadata ? { usage: buildGeminiUsage(response.usageMetadata) } : {}
|
|
44
|
+
};
|
|
45
|
+
} catch (error) {
|
|
46
|
+
logger.errors("gemini.generateAudio fatal", {
|
|
47
|
+
error,
|
|
48
|
+
source: "gemini.generateAudio"
|
|
49
|
+
});
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function createGeminiAudio(model, apiKey, config) {
|
|
55
|
+
return new GeminiAudioAdapter({ ...config, apiKey }, model);
|
|
56
|
+
}
|
|
57
|
+
function geminiAudio(model, config) {
|
|
58
|
+
const apiKey = getGeminiApiKeyFromEnv();
|
|
59
|
+
return createGeminiAudio(model, apiKey, config);
|
|
60
|
+
}
|
|
61
|
+
export {
|
|
62
|
+
GeminiAudioAdapter,
|
|
63
|
+
createGeminiAudio,
|
|
64
|
+
geminiAudio
|
|
65
|
+
};
|
|
66
|
+
//# sourceMappingURL=audio.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"audio.js","sources":["../../../src/adapters/audio.ts"],"sourcesContent":["import { BaseAudioAdapter } from '@tanstack/ai/adapters'\nimport {\n createGeminiClient,\n generateId,\n getGeminiApiKeyFromEnv,\n} from '../utils'\nimport { buildGeminiUsage } from '../usage'\nimport type { GEMINI_AUDIO_MODELS } from '../model-meta'\nimport type {\n AudioGenerationOptions,\n AudioGenerationResult,\n} from '@tanstack/ai'\nimport type { GoogleGenAI } from '@google/genai'\nimport type { GeminiClientConfig } from '../utils'\n\n/**\n * Provider options for Gemini Lyria music generation.\n *\n * Notes on the Lyria 3 surface area:\n * - `lyria-3-clip-preview` always returns MP3 (30-second clips). It does\n * not accept `responseMimeType`, and duration is fixed at 30 seconds —\n * the generic `duration` option on `AudioActivityOptions` is ignored.\n * - `lyria-3-pro-preview` returns MP3 by default. Duration is controlled\n * via the natural-language prompt, not a separate SDK field, so the\n * generic `duration` option is similarly ignored.\n * - `negativePrompt` is NOT accepted by `GenerateContentConfig` and has\n * therefore been removed from this surface to avoid giving callers a\n * silently-dropped knob.\n *\n * @see https://ai.google.dev/gemini-api/docs/music-generation\n */\nexport interface GeminiAudioProviderOptions {\n /**\n * Seed for deterministic generation.\n */\n seed?: number\n}\n\nexport interface GeminiAudioConfig extends GeminiClientConfig {}\n\n/** Model type for Gemini Lyria audio generation */\nexport type GeminiAudioModel = (typeof GEMINI_AUDIO_MODELS)[number]\n\n/**\n * Gemini Lyria Music Generation Adapter.\n *\n * Tree-shakeable adapter for Google Lyria music generation via the Gemini API.\n *\n * Models:\n * - `lyria-3-pro-preview` — flagship model, full-length songs with verses,\n * choruses, and bridges. Outputs MP3 or WAV at 48 kHz stereo.\n * - `lyria-3-clip-preview` — 30-second clips in MP3.\n *\n * @see https://ai.google.dev/gemini-api/docs/music-generation\n *\n * @example\n * ```typescript\n * const adapter = geminiAudio('lyria-3-pro-preview')\n * const result = await generateAudio({\n * adapter,\n * prompt: 'An upbeat jazz track with saxophone and drums',\n * })\n * ```\n */\nexport class GeminiAudioAdapter<\n TModel extends GeminiAudioModel,\n> extends BaseAudioAdapter<TModel, GeminiAudioProviderOptions> {\n readonly name = 'gemini' as const\n\n private readonly client: GoogleGenAI\n\n constructor(config: GeminiAudioConfig, model: TModel) {\n super(model, config)\n this.client = createGeminiClient(config)\n }\n\n async generateAudio(\n options: AudioGenerationOptions<GeminiAudioProviderOptions>,\n ): Promise<AudioGenerationResult> {\n const { model, prompt, modelOptions, logger } = options\n\n logger.request(`activity=generateAudio provider=gemini model=${model}`, {\n provider: 'gemini',\n model,\n })\n\n try {\n // FIXME (SDK audit): Lyria 3 music generation may not belong on\n // generateContent at all — @google/genai exposes a `LiveMusicSession`\n // (`ai.live.music.connect`) with a `musicGenerationConfig` object.\n // `seed` is valid on GenerateContentConfig, and Lyria always returns\n // MP3 today, so we don't forward `responseMimeType` either.\n // The runtime test `emits only GenerateContentConfig-valid fields`\n // asserts the config shape so a later SDK audit can catch regressions.\n const response = await this.client.models.generateContent({\n model,\n contents: [{ role: 'user', parts: [{ text: prompt }] }],\n config: {\n responseModalities: ['AUDIO', 'TEXT'],\n ...(modelOptions?.seed != null ? { seed: modelOptions.seed } : {}),\n },\n })\n\n const parts = response.candidates?.[0]?.content?.parts ?? []\n const audioPart = parts.find((part: any) =>\n part.inlineData?.mimeType?.startsWith('audio/'),\n )\n\n if (!audioPart?.inlineData?.data) {\n throw new Error('No audio data in Gemini Lyria response')\n }\n\n // audioPart was selected because mimeType.startsWith('audio/') was\n // truthy, so the mime type is guaranteed to be a string here. Trust the\n // value Gemini returned rather than inventing a non-standard\n // `audio/mp3` fallback (IANA is `audio/mpeg`).\n const contentType = audioPart.inlineData.mimeType\n\n return {\n id: generateId(this.name),\n model,\n audio: {\n b64Json: audioPart.inlineData.data,\n ...(contentType !== undefined && { contentType }),\n },\n // Surface token usage (with per-modality breakdown) when Gemini reports\n // it. Spread conditionally for exactOptionalPropertyTypes.\n ...(response.usageMetadata\n ? { usage: buildGeminiUsage(response.usageMetadata) }\n : {}),\n }\n } catch (error) {\n logger.errors('gemini.generateAudio fatal', {\n error,\n source: 'gemini.generateAudio',\n })\n throw error\n }\n }\n}\n\n/**\n * Creates a Gemini Lyria audio adapter with an explicit API key.\n *\n * @param model - The Lyria model name (e.g., 'lyria-3-pro-preview')\n * @param apiKey - Your Google API key\n * @param config - Optional additional configuration\n *\n * @example\n * ```typescript\n * const adapter = createGeminiAudio('lyria-3-pro-preview', 'your-api-key')\n * const result = await generateAudio({\n * adapter,\n * prompt: 'Ambient electronic music with soft pads',\n * })\n * ```\n */\nexport function createGeminiAudio<TModel extends GeminiAudioModel>(\n model: TModel,\n apiKey: string,\n config?: Omit<GeminiAudioConfig, 'apiKey'>,\n): GeminiAudioAdapter<TModel> {\n // Put apiKey LAST so caller-supplied config can't silently override the\n // explicit argument.\n return new GeminiAudioAdapter({ ...config, apiKey }, model)\n}\n\n/**\n * Creates a Gemini Lyria audio adapter with automatic API key detection.\n *\n * Looks for `GOOGLE_API_KEY` or `GEMINI_API_KEY` in the environment.\n *\n * @param model - The Lyria model name (e.g., 'lyria-3-pro-preview')\n * @param config - Optional configuration (excluding apiKey)\n *\n * @example\n * ```typescript\n * const adapter = geminiAudio('lyria-3-pro-preview')\n * const result = await generateAudio({\n * adapter,\n * prompt: 'An orchestral piece with strings and brass',\n * })\n * ```\n */\nexport function geminiAudio<TModel extends GeminiAudioModel>(\n model: TModel,\n config?: Omit<GeminiAudioConfig, 'apiKey'>,\n): GeminiAudioAdapter<TModel> {\n const apiKey = getGeminiApiKeyFromEnv()\n return createGeminiAudio(model, apiKey, config)\n}\n"],"names":[],"mappings":";;;AAgEO,MAAM,2BAEH,iBAAqD;AAAA,EACpD,OAAO;AAAA,EAEC;AAAA,EAEjB,YAAY,QAA2B,OAAe;AACpD,UAAM,OAAO,MAAM;AACnB,SAAK,SAAS,mBAAmB,MAAM;AAAA,EACzC;AAAA,EAEA,MAAM,cACJ,SACgC;AAChC,UAA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B;AAC5B,QAAM,SAAS,uBAAA;AACf,SAAO,kBAAkB,OAAO,QAAQ,MAAM;AAChD;"}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { BaseImageAdapter } from '@tanstack/ai/adapters';
|
|
2
|
+
import { GEMINI_IMAGE_MODELS } from '../model-meta.js';
|
|
3
|
+
import { GeminiImageModelInputModalitiesByName, GeminiImageModelProviderOptionsByName, GeminiImageModelSizeByName, GeminiImageProviderOptions } from '../image/image-provider-options.js';
|
|
4
|
+
import { ImageGenerationOptions, ImageGenerationResult } from '@tanstack/ai';
|
|
5
|
+
import { GeminiClientConfig } from '../utils.js';
|
|
6
|
+
/**
|
|
7
|
+
* Configuration for Gemini image adapter
|
|
8
|
+
*/
|
|
9
|
+
export interface GeminiImageConfig extends GeminiClientConfig {
|
|
10
|
+
}
|
|
11
|
+
/** Model type for Gemini Image */
|
|
12
|
+
export type GeminiImageModel = (typeof GEMINI_IMAGE_MODELS)[number];
|
|
13
|
+
/**
|
|
14
|
+
* Gemini Image Generation Adapter
|
|
15
|
+
*
|
|
16
|
+
* Tree-shakeable adapter for Gemini image generation functionality.
|
|
17
|
+
* Supports Imagen 3/4 models (via generateImages API) and Gemini native
|
|
18
|
+
* image models like Nano Banana 2 (via generateContent API).
|
|
19
|
+
*
|
|
20
|
+
* Features:
|
|
21
|
+
* - Aspect ratio-based image sizing
|
|
22
|
+
* - Person generation controls
|
|
23
|
+
* - Safety filtering
|
|
24
|
+
* - Watermark options
|
|
25
|
+
* - Extended resolution tiers (Nano Banana 2)
|
|
26
|
+
*/
|
|
27
|
+
export declare class GeminiImageAdapter<TModel extends GeminiImageModel> extends BaseImageAdapter<TModel, GeminiImageProviderOptions, GeminiImageModelProviderOptionsByName, GeminiImageModelSizeByName, GeminiImageModelInputModalitiesByName> {
|
|
28
|
+
readonly kind: "image";
|
|
29
|
+
readonly name: "gemini";
|
|
30
|
+
'~types': {
|
|
31
|
+
providerOptions: GeminiImageProviderOptions;
|
|
32
|
+
modelProviderOptionsByName: GeminiImageModelProviderOptionsByName;
|
|
33
|
+
modelSizeByName: GeminiImageModelSizeByName;
|
|
34
|
+
modelInputModalitiesByName: GeminiImageModelInputModalitiesByName;
|
|
35
|
+
};
|
|
36
|
+
private readonly client;
|
|
37
|
+
constructor(config: GeminiImageConfig, model: TModel);
|
|
38
|
+
generateImages(options: ImageGenerationOptions<GeminiImageProviderOptions>): Promise<ImageGenerationResult>;
|
|
39
|
+
private isGeminiImageModel;
|
|
40
|
+
private generateWithGeminiApi;
|
|
41
|
+
/**
|
|
42
|
+
* Build the multimodal `contents` payload. Text-only prompts pass through
|
|
43
|
+
* as a plain string (the SDK accepts it directly); prompts with image
|
|
44
|
+
* parts become a single user `Content` whose `parts` mirror the prompt's
|
|
45
|
+
* interleaved order — position is meaningful to Gemini ("not like this
|
|
46
|
+
* *(image)*, more like this *(image)*").
|
|
47
|
+
*
|
|
48
|
+
* The generateContent API has no numberOfImages parameter, so when more
|
|
49
|
+
* than one image is requested a trailing instruction is appended.
|
|
50
|
+
*/
|
|
51
|
+
private buildContents;
|
|
52
|
+
private imagePartToGeminiPart;
|
|
53
|
+
private transformGeminiResponse;
|
|
54
|
+
private buildImagenConfig;
|
|
55
|
+
private transformImagenResponse;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Creates a Gemini image adapter with explicit API key.
|
|
59
|
+
* Type resolution happens here at the call site.
|
|
60
|
+
*
|
|
61
|
+
* @param model - The model name (e.g., 'imagen-3.0-generate-002')
|
|
62
|
+
* @param apiKey - Your Google API key
|
|
63
|
+
* @param config - Optional additional configuration
|
|
64
|
+
* @returns Configured Gemini image adapter instance with resolved types
|
|
65
|
+
*
|
|
66
|
+
* @example
|
|
67
|
+
* ```typescript
|
|
68
|
+
* const adapter = createGeminiImage('imagen-3.0-generate-002', "your-api-key");
|
|
69
|
+
*
|
|
70
|
+
* const result = await generateImage({
|
|
71
|
+
* adapter,
|
|
72
|
+
* prompt: 'A cute baby sea otter'
|
|
73
|
+
* });
|
|
74
|
+
* ```
|
|
75
|
+
*/
|
|
76
|
+
export declare function createGeminiImage<TModel extends GeminiImageModel>(model: TModel, apiKey: string, config?: Omit<GeminiImageConfig, 'apiKey'>): GeminiImageAdapter<TModel>;
|
|
77
|
+
/**
|
|
78
|
+
* Creates a Gemini image adapter with automatic API key detection from environment variables.
|
|
79
|
+
* Type resolution happens here at the call site.
|
|
80
|
+
*
|
|
81
|
+
* Looks for `GOOGLE_API_KEY` or `GEMINI_API_KEY` in:
|
|
82
|
+
* - `process.env` (Node.js)
|
|
83
|
+
* - `window.env` (Browser with injected env)
|
|
84
|
+
*
|
|
85
|
+
* @param model - The model name (e.g., 'imagen-4.0-generate-001')
|
|
86
|
+
* @param config - Optional configuration (excluding apiKey which is auto-detected)
|
|
87
|
+
* @returns Configured Gemini image adapter instance with resolved types
|
|
88
|
+
* @throws Error if GOOGLE_API_KEY or GEMINI_API_KEY is not found in environment
|
|
89
|
+
*
|
|
90
|
+
* @example
|
|
91
|
+
* ```typescript
|
|
92
|
+
* // Automatically uses GOOGLE_API_KEY from environment
|
|
93
|
+
* const adapter = geminiImage('imagen-4.0-generate-001');
|
|
94
|
+
*
|
|
95
|
+
* const result = await generateImage({
|
|
96
|
+
* adapter,
|
|
97
|
+
* prompt: 'A beautiful sunset over mountains'
|
|
98
|
+
* });
|
|
99
|
+
* ```
|
|
100
|
+
*/
|
|
101
|
+
export declare function geminiImage<TModel extends GeminiImageModel>(model: TModel, config?: Omit<GeminiImageConfig, 'apiKey'>): GeminiImageAdapter<TModel>;
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import { resolveMediaPrompt } from "@tanstack/ai";
|
|
2
|
+
import { BaseImageAdapter } from "@tanstack/ai/adapters";
|
|
3
|
+
import { arrayBufferToBase64 } from "@tanstack/ai-utils";
|
|
4
|
+
import { createGeminiClient, generateId, getGeminiApiKeyFromEnv } from "../utils/client.js";
|
|
5
|
+
import { buildGeminiUsage } from "../usage.js";
|
|
6
|
+
import { validatePrompt, validateImageSize, validateNumberOfImages, parseNativeImageSize, sizeToAspectRatio } from "../image/image-provider-options.js";
|
|
7
|
+
class GeminiImageAdapter extends BaseImageAdapter {
|
|
8
|
+
kind = "image";
|
|
9
|
+
name = "gemini";
|
|
10
|
+
client;
|
|
11
|
+
constructor(config, model) {
|
|
12
|
+
super(model, config);
|
|
13
|
+
this.client = createGeminiClient(config);
|
|
14
|
+
}
|
|
15
|
+
async generateImages(options) {
|
|
16
|
+
const { model, logger } = options;
|
|
17
|
+
logger.request(
|
|
18
|
+
`activity=generateImage provider=gemini model=${this.model}`,
|
|
19
|
+
{
|
|
20
|
+
provider: "gemini",
|
|
21
|
+
model: this.model
|
|
22
|
+
}
|
|
23
|
+
);
|
|
24
|
+
try {
|
|
25
|
+
const resolved = resolveMediaPrompt(options.prompt);
|
|
26
|
+
if (resolved.images.length === 0) {
|
|
27
|
+
validatePrompt({ prompt: resolved.text, model });
|
|
28
|
+
}
|
|
29
|
+
if (resolved.videos.length > 0) {
|
|
30
|
+
throw new Error(
|
|
31
|
+
`${this.name}.generateImages does not support video prompt parts (model: ${model}).`
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
if (resolved.audios.length > 0) {
|
|
35
|
+
throw new Error(
|
|
36
|
+
`${this.name}.generateImages does not support audio prompt parts (model: ${model}).`
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
if (this.isGeminiImageModel(model)) {
|
|
40
|
+
return await this.generateWithGeminiApi(options, resolved);
|
|
41
|
+
}
|
|
42
|
+
if (resolved.images.length > 0) {
|
|
43
|
+
throw new Error(
|
|
44
|
+
`${this.name}: model "${model}" (Imagen) does not support image prompt parts. Use a Gemini-native image model (e.g. gemini-2.5-flash-image, "nano-banana") for image-conditioned generation.`
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
validateImageSize(model, options.size);
|
|
48
|
+
validateNumberOfImages(model, options.numberOfImages);
|
|
49
|
+
const config = this.buildImagenConfig(options);
|
|
50
|
+
const response = await this.client.models.generateImages({
|
|
51
|
+
model,
|
|
52
|
+
prompt: resolved.text,
|
|
53
|
+
config
|
|
54
|
+
});
|
|
55
|
+
return this.transformImagenResponse(model, response);
|
|
56
|
+
} catch (error) {
|
|
57
|
+
logger.errors("gemini.generateImage fatal", {
|
|
58
|
+
error,
|
|
59
|
+
source: "gemini.generateImage"
|
|
60
|
+
});
|
|
61
|
+
throw error;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
isGeminiImageModel(model) {
|
|
65
|
+
return model.startsWith("gemini-");
|
|
66
|
+
}
|
|
67
|
+
async generateWithGeminiApi(options, resolved) {
|
|
68
|
+
const { model, size, numberOfImages, modelOptions } = options;
|
|
69
|
+
const parsedSize = size ? parseNativeImageSize(size) : void 0;
|
|
70
|
+
const nativeConfig = {};
|
|
71
|
+
if (modelOptions?.seed !== void 0) {
|
|
72
|
+
nativeConfig.seed = modelOptions.seed;
|
|
73
|
+
}
|
|
74
|
+
const config = {
|
|
75
|
+
...nativeConfig,
|
|
76
|
+
// Include TEXT so the model can interleave descriptions between images.
|
|
77
|
+
// IMPORTANT: responseModalities is a protected default — set it AFTER
|
|
78
|
+
// nativeConfig so nothing can silently disable image output.
|
|
79
|
+
responseModalities: ["TEXT", "IMAGE"],
|
|
80
|
+
...parsedSize && {
|
|
81
|
+
imageConfig: {
|
|
82
|
+
...parsedSize.aspectRatio && {
|
|
83
|
+
aspectRatio: parsedSize.aspectRatio
|
|
84
|
+
},
|
|
85
|
+
...parsedSize.resolution && {
|
|
86
|
+
imageSize: parsedSize.resolution
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
const contents = await this.buildContents(resolved, numberOfImages);
|
|
92
|
+
const response = await this.client.models.generateContent({
|
|
93
|
+
model,
|
|
94
|
+
contents,
|
|
95
|
+
config
|
|
96
|
+
});
|
|
97
|
+
return this.transformGeminiResponse(model, response);
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Build the multimodal `contents` payload. Text-only prompts pass through
|
|
101
|
+
* as a plain string (the SDK accepts it directly); prompts with image
|
|
102
|
+
* parts become a single user `Content` whose `parts` mirror the prompt's
|
|
103
|
+
* interleaved order — position is meaningful to Gemini ("not like this
|
|
104
|
+
* *(image)*, more like this *(image)*").
|
|
105
|
+
*
|
|
106
|
+
* The generateContent API has no numberOfImages parameter, so when more
|
|
107
|
+
* than one image is requested a trailing instruction is appended.
|
|
108
|
+
*/
|
|
109
|
+
async buildContents(resolved, numberOfImages) {
|
|
110
|
+
const countInstruction = numberOfImages && numberOfImages > 1 ? `Generate ${numberOfImages} distinct images.` : void 0;
|
|
111
|
+
if (resolved.images.length === 0) {
|
|
112
|
+
return countInstruction ? `${resolved.text} ${countInstruction}` : resolved.text;
|
|
113
|
+
}
|
|
114
|
+
const parts = await Promise.all(
|
|
115
|
+
resolved.parts.map((part) => {
|
|
116
|
+
if (part.type === "text") {
|
|
117
|
+
return Promise.resolve({ text: part.content });
|
|
118
|
+
}
|
|
119
|
+
if (part.type === "image") {
|
|
120
|
+
return this.imagePartToGeminiPart(part);
|
|
121
|
+
}
|
|
122
|
+
throw new Error(
|
|
123
|
+
`gemini: unsupported prompt part type "${part.type}" in image generation.`
|
|
124
|
+
);
|
|
125
|
+
})
|
|
126
|
+
);
|
|
127
|
+
if (countInstruction) {
|
|
128
|
+
parts.push({ text: countInstruction });
|
|
129
|
+
}
|
|
130
|
+
return [{ role: "user", parts }];
|
|
131
|
+
}
|
|
132
|
+
async imagePartToGeminiPart(part) {
|
|
133
|
+
if (part.source.type === "data") {
|
|
134
|
+
return {
|
|
135
|
+
inlineData: {
|
|
136
|
+
mimeType: part.source.mimeType || "image/png",
|
|
137
|
+
data: part.source.value
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
if (part.source.value.startsWith("gs://") || /^https?:\/\/generativelanguage\.googleapis\.com\//.test(
|
|
142
|
+
part.source.value
|
|
143
|
+
)) {
|
|
144
|
+
return {
|
|
145
|
+
fileData: {
|
|
146
|
+
fileUri: part.source.value,
|
|
147
|
+
...part.source.mimeType && { mimeType: part.source.mimeType }
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
const response = await fetch(part.source.value);
|
|
152
|
+
if (!response.ok) {
|
|
153
|
+
throw new Error(
|
|
154
|
+
`Failed to fetch image input (${response.status} ${response.statusText}): ${part.source.value}`
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
const blob = await response.blob();
|
|
158
|
+
const buffer = await blob.arrayBuffer();
|
|
159
|
+
const base64 = arrayBufferToBase64(buffer);
|
|
160
|
+
return {
|
|
161
|
+
inlineData: {
|
|
162
|
+
mimeType: part.source.mimeType || blob.type || "image/png",
|
|
163
|
+
data: base64
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
transformGeminiResponse(model, response) {
|
|
168
|
+
const images = [];
|
|
169
|
+
const textParts = [];
|
|
170
|
+
const parts = response.candidates?.[0]?.content?.parts ?? [];
|
|
171
|
+
for (const part of parts) {
|
|
172
|
+
if (part.inlineData?.data && typeof part.inlineData.data === "string" && part.inlineData.data.length > 0) {
|
|
173
|
+
images.push({ b64Json: part.inlineData.data });
|
|
174
|
+
} else if (typeof part.text === "string" && part.text.length > 0) {
|
|
175
|
+
textParts.push(part.text);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
if (images.length === 0) {
|
|
179
|
+
const reason = textParts.length > 0 ? `: ${textParts.join(" ").trim()}` : " (no inline image or text parts were returned).";
|
|
180
|
+
throw new Error(`Gemini ${model} returned no images${reason}`);
|
|
181
|
+
}
|
|
182
|
+
return {
|
|
183
|
+
id: generateId(this.name),
|
|
184
|
+
model,
|
|
185
|
+
images,
|
|
186
|
+
// Surface token usage (with per-modality breakdown) when the model
|
|
187
|
+
// reports it (e.g. Nano Banana via generateContent). Conditionally spread
|
|
188
|
+
// to satisfy exactOptionalPropertyTypes — only include usage when
|
|
189
|
+
// present. See #330.
|
|
190
|
+
...response.usageMetadata ? { usage: buildGeminiUsage(response.usageMetadata) } : {}
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
buildImagenConfig(options) {
|
|
194
|
+
const { size, numberOfImages, modelOptions } = options;
|
|
195
|
+
const sizeAspectRatio = size ? sizeToAspectRatio(size) : void 0;
|
|
196
|
+
return {
|
|
197
|
+
numberOfImages: numberOfImages ?? 1,
|
|
198
|
+
// Map size to aspect ratio if provided (modelOptions.aspectRatio will override)
|
|
199
|
+
...sizeAspectRatio !== void 0 && { aspectRatio: sizeAspectRatio },
|
|
200
|
+
...modelOptions
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
transformImagenResponse(model, response) {
|
|
204
|
+
const entries = response.generatedImages ?? [];
|
|
205
|
+
const images = [];
|
|
206
|
+
const filterReasons = [];
|
|
207
|
+
for (const item of entries) {
|
|
208
|
+
const b64Json = item.image?.imageBytes;
|
|
209
|
+
if (b64Json) {
|
|
210
|
+
images.push({
|
|
211
|
+
b64Json,
|
|
212
|
+
...item.enhancedPrompt !== void 0 && {
|
|
213
|
+
revisedPrompt: item.enhancedPrompt
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
const reason = item.raiFilteredReason;
|
|
219
|
+
if (reason) {
|
|
220
|
+
filterReasons.push(reason);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
if (entries.length > 0 && images.length === 0) {
|
|
224
|
+
const joined = filterReasons.length > 0 ? filterReasons.join("; ") : "";
|
|
225
|
+
throw new Error(
|
|
226
|
+
`Imagen ${model} returned no images: all ${entries.length} generated image(s) were filtered by Responsible-AI${joined ? ` (${joined})` : ""}.`
|
|
227
|
+
);
|
|
228
|
+
}
|
|
229
|
+
if (filterReasons.length > 0 && typeof console !== "undefined") {
|
|
230
|
+
console.warn(
|
|
231
|
+
`[gemini-image] ${filterReasons.length} of ${entries.length} images from ${model} were filtered by Responsible-AI: ${filterReasons.join("; ")}`
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
return {
|
|
235
|
+
id: generateId(this.name),
|
|
236
|
+
model,
|
|
237
|
+
images
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
function createGeminiImage(model, apiKey, config) {
|
|
242
|
+
return new GeminiImageAdapter({ apiKey, ...config }, model);
|
|
243
|
+
}
|
|
244
|
+
function geminiImage(model, config) {
|
|
245
|
+
const apiKey = getGeminiApiKeyFromEnv();
|
|
246
|
+
return createGeminiImage(model, apiKey, config);
|
|
247
|
+
}
|
|
248
|
+
export {
|
|
249
|
+
GeminiImageAdapter,
|
|
250
|
+
createGeminiImage,
|
|
251
|
+
geminiImage
|
|
252
|
+
};
|
|
253
|
+
//# sourceMappingURL=image.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"image.js","sources":["../../../src/adapters/image.ts"],"sourcesContent":["import { resolveMediaPrompt } from '@tanstack/ai'\nimport { BaseImageAdapter } from '@tanstack/ai/adapters'\nimport { arrayBufferToBase64 } from '@tanstack/ai-utils'\nimport {\n createGeminiClient,\n generateId,\n getGeminiApiKeyFromEnv,\n} from '../utils'\nimport { buildGeminiUsage } from '../usage'\nimport {\n parseNativeImageSize,\n sizeToAspectRatio,\n validateImageSize,\n validateNumberOfImages,\n validatePrompt,\n} from '../image/image-provider-options'\nimport type { GEMINI_IMAGE_MODELS } from '../model-meta'\nimport type {\n GeminiImageModelInputModalitiesByName,\n GeminiImageModelProviderOptionsByName,\n GeminiImageModelSizeByName,\n GeminiImageProviderOptions,\n} from '../image/image-provider-options'\nimport type {\n GeneratedImage,\n ImageGenerationOptions,\n ImageGenerationResult,\n ImagePart,\n MediaInputMetadata,\n ResolvedMediaPrompt,\n} from '@tanstack/ai'\nimport type {\n Content,\n GenerateContentConfig,\n GenerateContentResponse,\n GenerateImagesConfig,\n GenerateImagesResponse,\n GoogleGenAI,\n Part,\n} from '@google/genai'\nimport type { GeminiClientConfig } from '../utils'\n\n/**\n * Configuration for Gemini image adapter\n */\nexport interface GeminiImageConfig extends GeminiClientConfig {}\n\n/** Model type for Gemini Image */\nexport type GeminiImageModel = (typeof GEMINI_IMAGE_MODELS)[number]\n\n/**\n * Gemini Image Generation Adapter\n *\n * Tree-shakeable adapter for Gemini image generation functionality.\n * Supports Imagen 3/4 models (via generateImages API) and Gemini native\n * image models like Nano Banana 2 (via generateContent API).\n *\n * Features:\n * - Aspect ratio-based image sizing\n * - Person generation controls\n * - Safety filtering\n * - Watermark options\n * - Extended resolution tiers (Nano Banana 2)\n */\nexport class GeminiImageAdapter<\n TModel extends GeminiImageModel,\n> extends BaseImageAdapter<\n TModel,\n GeminiImageProviderOptions,\n GeminiImageModelProviderOptionsByName,\n GeminiImageModelSizeByName,\n GeminiImageModelInputModalitiesByName\n> {\n override readonly kind = 'image' as const\n readonly name = 'gemini' as const\n\n // Type-only property - never assigned at runtime\n declare '~types': {\n providerOptions: GeminiImageProviderOptions\n modelProviderOptionsByName: GeminiImageModelProviderOptionsByName\n modelSizeByName: GeminiImageModelSizeByName\n modelInputModalitiesByName: GeminiImageModelInputModalitiesByName\n }\n\n private readonly client: GoogleGenAI\n\n constructor(config: GeminiImageConfig, model: TModel) {\n super(model, config)\n this.client = createGeminiClient(config)\n }\n\n async generateImages(\n options: ImageGenerationOptions<GeminiImageProviderOptions>,\n ): Promise<ImageGenerationResult> {\n const { model, logger } = options\n\n logger.request(\n `activity=generateImage provider=gemini model=${this.model}`,\n {\n provider: 'gemini',\n model: this.model,\n },\n )\n\n try {\n const resolved = resolveMediaPrompt(options.prompt)\n\n // Image-only prompts are allowed (the image inputs carry the intent);\n // a prompt with neither text nor images is always an error.\n if (resolved.images.length === 0) {\n validatePrompt({ prompt: resolved.text, model })\n }\n\n if (resolved.videos.length > 0) {\n throw new Error(\n `${this.name}.generateImages does not support video prompt parts (model: ${model}).`,\n )\n }\n if (resolved.audios.length > 0) {\n throw new Error(\n `${this.name}.generateImages does not support audio prompt parts (model: ${model}).`,\n )\n }\n\n if (this.isGeminiImageModel(model)) {\n return await this.generateWithGeminiApi(options, resolved)\n }\n\n // Imagen does not accept image inputs — it's strictly text-to-image.\n if (resolved.images.length > 0) {\n throw new Error(\n `${this.name}: model \"${model}\" (Imagen) does not support image prompt parts. ` +\n `Use a Gemini-native image model (e.g. gemini-2.5-flash-image, \"nano-banana\") for image-conditioned generation.`,\n )\n }\n\n // Imagen models path (generateImages API)\n validateImageSize(model, options.size)\n validateNumberOfImages(model, options.numberOfImages)\n\n const config = this.buildImagenConfig(options)\n\n const response = await this.client.models.generateImages({\n model,\n prompt: resolved.text,\n config,\n })\n\n return this.transformImagenResponse(model, response)\n } catch (error) {\n logger.errors('gemini.generateImage fatal', {\n error,\n source: 'gemini.generateImage',\n })\n throw error\n }\n }\n\n private isGeminiImageModel(model: string): boolean {\n return model.startsWith('gemini-')\n }\n\n private async generateWithGeminiApi(\n options: ImageGenerationOptions<GeminiImageProviderOptions>,\n resolved: ResolvedMediaPrompt,\n ): Promise<ImageGenerationResult> {\n const { model, size, numberOfImages, modelOptions } = options\n\n const parsedSize = size ? parseNativeImageSize(size) : undefined\n\n // GeminiImageProviderOptions is Imagen-shaped — most fields\n // (personGeneration, safetyFilterLevel, addWatermark, outputMimeType,\n // outputCompressionQuality, guidanceScale, enhancePrompt,\n // includeSafetyAttributes, includeRaiReason, outputGcsUri, labels,\n // negativePrompt, language) are only valid on GenerateImagesConfig and\n // would be rejected by the Gemini-native generateContent path. Pick only\n // the fields that are valid on GenerateContentConfig instead of spreading\n // the whole options object.\n const nativeConfig: GenerateContentConfig = {}\n if (modelOptions?.seed !== undefined) {\n nativeConfig.seed = modelOptions.seed\n }\n\n const config: GenerateContentConfig = {\n ...nativeConfig,\n // Include TEXT so the model can interleave descriptions between images.\n // IMPORTANT: responseModalities is a protected default — set it AFTER\n // nativeConfig so nothing can silently disable image output.\n responseModalities: ['TEXT', 'IMAGE'],\n ...(parsedSize && {\n imageConfig: {\n ...(parsedSize.aspectRatio && {\n aspectRatio: parsedSize.aspectRatio,\n }),\n ...(parsedSize.resolution && {\n imageSize: parsedSize.resolution,\n }),\n },\n }),\n }\n\n const contents = await this.buildContents(resolved, numberOfImages)\n\n const response = await this.client.models.generateContent({\n model,\n contents,\n config,\n })\n\n return this.transformGeminiResponse(model, response)\n }\n\n /**\n * Build the multimodal `contents` payload. Text-only prompts pass through\n * as a plain string (the SDK accepts it directly); prompts with image\n * parts become a single user `Content` whose `parts` mirror the prompt's\n * interleaved order — position is meaningful to Gemini (\"not like this\n * *(image)*, more like this *(image)*\").\n *\n * The generateContent API has no numberOfImages parameter, so when more\n * than one image is requested a trailing instruction is appended.\n */\n private async buildContents(\n resolved: ResolvedMediaPrompt,\n numberOfImages: number | undefined,\n ): Promise<string | Array<Content>> {\n const countInstruction =\n numberOfImages && numberOfImages > 1\n ? `Generate ${numberOfImages} distinct images.`\n : undefined\n\n if (resolved.images.length === 0) {\n return countInstruction\n ? `${resolved.text} ${countInstruction}`\n : resolved.text\n }\n\n const parts: Array<Part> = await Promise.all(\n resolved.parts.map((part) => {\n if (part.type === 'text') {\n return Promise.resolve<Part>({ text: part.content })\n }\n if (part.type === 'image') {\n return this.imagePartToGeminiPart(part)\n }\n // Video / audio parts were rejected in generateImages above.\n throw new Error(\n `gemini: unsupported prompt part type \"${part.type}\" in image generation.`,\n )\n }),\n )\n if (countInstruction) {\n parts.push({ text: countInstruction })\n }\n return [{ role: 'user', parts }]\n }\n\n private async imagePartToGeminiPart(\n part: ImagePart<MediaInputMetadata>,\n ): Promise<Part> {\n if (part.source.type === 'data') {\n return {\n inlineData: {\n mimeType: part.source.mimeType || 'image/png',\n data: part.source.value,\n },\n }\n }\n // For URL sources, prefer passing the URL through as `fileData` when it\n // looks like a Google Files API URI; otherwise fetch and inline as base64.\n if (\n part.source.value.startsWith('gs://') ||\n /^https?:\\/\\/generativelanguage\\.googleapis\\.com\\//.test(\n part.source.value,\n )\n ) {\n return {\n fileData: {\n fileUri: part.source.value,\n ...(part.source.mimeType && { mimeType: part.source.mimeType }),\n },\n }\n }\n const response = await fetch(part.source.value)\n if (!response.ok) {\n throw new Error(\n `Failed to fetch image input (${response.status} ${response.statusText}): ${part.source.value}`,\n )\n }\n const blob = await response.blob()\n const buffer = await blob.arrayBuffer()\n const base64 = arrayBufferToBase64(buffer)\n return {\n inlineData: {\n mimeType: part.source.mimeType || blob.type || 'image/png',\n data: base64,\n },\n }\n }\n\n private transformGeminiResponse(\n model: string,\n response: GenerateContentResponse,\n ): ImageGenerationResult {\n const images: Array<GeneratedImage> = []\n const textParts: Array<string> = []\n const parts = response.candidates?.[0]?.content?.parts ?? []\n\n for (const part of parts) {\n if (\n part.inlineData?.data &&\n typeof part.inlineData.data === 'string' &&\n part.inlineData.data.length > 0\n ) {\n images.push({ b64Json: part.inlineData.data })\n } else if (typeof part.text === 'string' && part.text.length > 0) {\n textParts.push(part.text)\n }\n }\n\n // If the model returned only text parts (for example a safety refusal\n // or a \"can't do that\" message), surface the text instead of silently\n // resolving to an empty images array — otherwise callers can't tell a\n // generation failure apart from a genuine empty response.\n if (images.length === 0) {\n const reason =\n textParts.length > 0\n ? `: ${textParts.join(' ').trim()}`\n : ' (no inline image or text parts were returned).'\n throw new Error(`Gemini ${model} returned no images${reason}`)\n }\n\n return {\n id: generateId(this.name),\n model,\n images,\n // Surface token usage (with per-modality breakdown) when the model\n // reports it (e.g. Nano Banana via generateContent). Conditionally spread\n // to satisfy exactOptionalPropertyTypes — only include usage when\n // present. See #330.\n ...(response.usageMetadata\n ? { usage: buildGeminiUsage(response.usageMetadata) }\n : {}),\n }\n }\n\n private buildImagenConfig(\n options: ImageGenerationOptions<GeminiImageProviderOptions>,\n ): GenerateImagesConfig {\n const { size, numberOfImages, modelOptions } = options\n\n // Build with conditional spreads — under exactOptionalPropertyTypes the\n // vendor `GenerateImagesConfig` fields are `field?: T` (no `| undefined`),\n // so we can only assign the property when we actually have a value.\n const sizeAspectRatio = size ? sizeToAspectRatio(size) : undefined\n return {\n numberOfImages: numberOfImages ?? 1,\n // Map size to aspect ratio if provided (modelOptions.aspectRatio will override)\n ...(sizeAspectRatio !== undefined && { aspectRatio: sizeAspectRatio }),\n ...modelOptions,\n }\n }\n\n private transformImagenResponse(\n model: string,\n response: GenerateImagesResponse,\n ): ImageGenerationResult {\n const entries = response.generatedImages ?? []\n const images: Array<GeneratedImage> = []\n const filterReasons: Array<string> = []\n\n for (const item of entries) {\n const b64Json = item.image?.imageBytes\n if (b64Json) {\n images.push({\n b64Json,\n ...(item.enhancedPrompt !== undefined && {\n revisedPrompt: item.enhancedPrompt,\n }),\n })\n continue\n }\n // Imagen can drop individual entries with a raiFilteredReason when\n // Responsible-AI filters fire. Preserve the reason so callers can\n // surface it instead of silently getting back fewer images.\n const reason = (item as { raiFilteredReason?: string }).raiFilteredReason\n if (reason) {\n filterReasons.push(reason)\n }\n }\n\n // Every entry was filtered — no usable images to return. Throw rather\n // than resolve to an empty array so the caller is forced to handle the\n // failure mode explicitly.\n if (entries.length > 0 && images.length === 0) {\n const joined = filterReasons.length > 0 ? filterReasons.join('; ') : ''\n throw new Error(\n `Imagen ${model} returned no images: all ${entries.length} generated image(s) were filtered by Responsible-AI${joined ? ` (${joined})` : ''}.`,\n )\n }\n\n // Partial filter: surface via console.warn since ImageGenerationResult\n // has no warnings field. Callers that care can still inspect the count\n // mismatch between requested and returned images.\n if (filterReasons.length > 0 && typeof console !== 'undefined') {\n console.warn(\n `[gemini-image] ${filterReasons.length} of ${entries.length} images from ${model} were filtered by Responsible-AI: ${filterReasons.join('; ')}`,\n )\n }\n\n return {\n id: generateId(this.name),\n model,\n images,\n }\n }\n}\n\n/**\n * Creates a Gemini image adapter with explicit API key.\n * Type resolution happens here at the call site.\n *\n * @param model - The model name (e.g., 'imagen-3.0-generate-002')\n * @param apiKey - Your Google API key\n * @param config - Optional additional configuration\n * @returns Configured Gemini image adapter instance with resolved types\n *\n * @example\n * ```typescript\n * const adapter = createGeminiImage('imagen-3.0-generate-002', \"your-api-key\");\n *\n * const result = await generateImage({\n * adapter,\n * prompt: 'A cute baby sea otter'\n * });\n * ```\n */\nexport function createGeminiImage<TModel extends GeminiImageModel>(\n model: TModel,\n apiKey: string,\n config?: Omit<GeminiImageConfig, 'apiKey'>,\n): GeminiImageAdapter<TModel> {\n return new GeminiImageAdapter({ apiKey, ...config }, model)\n}\n\n/**\n * Creates a Gemini image adapter with automatic API key detection from environment variables.\n * Type resolution happens here at the call site.\n *\n * Looks for `GOOGLE_API_KEY` or `GEMINI_API_KEY` in:\n * - `process.env` (Node.js)\n * - `window.env` (Browser with injected env)\n *\n * @param model - The model name (e.g., 'imagen-4.0-generate-001')\n * @param config - Optional configuration (excluding apiKey which is auto-detected)\n * @returns Configured Gemini image adapter instance with resolved types\n * @throws Error if GOOGLE_API_KEY or GEMINI_API_KEY is not found in environment\n *\n * @example\n * ```typescript\n * // Automatically uses GOOGLE_API_KEY from environment\n * const adapter = geminiImage('imagen-4.0-generate-001');\n *\n * const result = await generateImage({\n * adapter,\n * prompt: 'A beautiful sunset over mountains'\n * });\n * ```\n */\nexport function geminiImage<TModel extends GeminiImageModel>(\n model: TModel,\n config?: Omit<GeminiImageConfig, 'apiKey'>,\n): GeminiImageAdapter<TModel> {\n const apiKey = getGeminiApiKeyFromEnv()\n return createGeminiImage(model, apiKey, config)\n}\n"],"names":[],"mappings":";;;;;;AAgEO,MAAM,2BAEH,iBAMR;AAAA,EACkB,OAAO;AAAA,EAChB,OAAO;AAAA,EAUC;AAAA,EAEjB,YAAY,QAA2B,OAAe;AACpD,UAAM,OAAO,MAAM;AACnB,SAAK,SAAS,mBAAmB,MAAM;AAAA,EACzC;AAAA,EAEA,MAAM,eACJ,SACgC;AAChC,UAAM,EAAE,OAAO,OAAA,IAAW;AAE1B,WAAO;AAAA,MACL,gDAAgD,KAAK,KAAK;AAAA,MAC1D;AAAA,QACE,UAAU;AAAA,QACV,OAAO,K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;AAAA,IACF;AAKA,QAAI,QAAQ,SAAS,KAAK,OAAO,WAAW,GAAG;AAC7C,YAAM,SAAS,cAAc,SAAS,IAAI,cAAc,KAAK,IAAI,IAAI;AACrE,YAAM,IAAI;AAAA,QACR,UAAU,KAAK,4BAA4B,QAAQ,MAAM,sDAAsD,SAAS,KAAK,MAAM,MAAM,EAAE;AAAA,MAAA;AAAA,IAE/I;AAKA,QAAI,cAAc,SAAS,KAAK,OAAO,YAAY,aAAa;AAC9D,cAAQ;AAAA,QACN,kBAAkB,cAAc,MAAM,OAAO,QAAQ,MAAM,gBAAgB,KAAK,qCAAqC,cAAc,KAAK,IAAI,CAAC;AAAA,MAAA;AAAA,IAEjJ;AAEA,WAAO;AAAA,MACL,IAAI,WAAW,KAAK,IAAI;AAAA,MACxB;AAAA,MACA;AAAA,IAAA;AAAA,EAEJ;AACF;AAqBO,SAAS,kBACd,OACA,QACA,QAC4B;AAC5B,SAAO,IAAI,mBAAmB,EAAE,QAAQ,GAAG,OAAA,GAAU,KAAK;AAC5D;AA0BO,SAAS,YACd,OACA,QAC4B;AAC5B,QAAM,SAAS,uBAAA;AACf,SAAO,kBAAkB,OAAO,QAAQ,MAAM;AAChD;"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { ChatStreamSummarizeAdapter, InferTextProviderOptions } from '@tanstack/ai/adapters';
|
|
2
|
+
import { GeminiTextAdapter } from './text.js';
|
|
3
|
+
import { GEMINI_MODELS } from '../model-meta.js';
|
|
4
|
+
import { GeminiClientConfig } from '../utils.js';
|
|
5
|
+
/**
|
|
6
|
+
* Configuration for Gemini summarize adapter
|
|
7
|
+
*/
|
|
8
|
+
export interface GeminiSummarizeConfig extends GeminiClientConfig {
|
|
9
|
+
}
|
|
10
|
+
export type GeminiSummarizeModel = (typeof GEMINI_MODELS)[number];
|
|
11
|
+
/**
|
|
12
|
+
* Creates a Gemini summarize adapter with explicit API key and model.
|
|
13
|
+
*
|
|
14
|
+
* Note: keeps the historical (apiKey, model, config) argument order to
|
|
15
|
+
* avoid breaking existing callers.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```typescript
|
|
19
|
+
* const adapter = createGeminiSummarize('AIza...', 'gemini-2.5-flash');
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
export declare function createGeminiSummarize<TModel extends GeminiSummarizeModel>(apiKey: string, model: TModel, config?: Omit<GeminiSummarizeConfig, 'apiKey'>): ChatStreamSummarizeAdapter<TModel, InferTextProviderOptions<GeminiTextAdapter<TModel>>>;
|
|
23
|
+
/**
|
|
24
|
+
* Creates a Gemini summarize adapter with API key from `GOOGLE_API_KEY` /
|
|
25
|
+
* `GEMINI_API_KEY` environment variables.
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* ```typescript
|
|
29
|
+
* const adapter = geminiSummarize('gemini-2.5-flash');
|
|
30
|
+
* await summarize({ adapter, text: 'Long article text...' });
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
export declare function geminiSummarize<TModel extends GeminiSummarizeModel>(model: TModel, config?: Omit<GeminiSummarizeConfig, 'apiKey'>): ChatStreamSummarizeAdapter<TModel, InferTextProviderOptions<GeminiTextAdapter<TModel>>>;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { ChatStreamSummarizeAdapter } from "@tanstack/ai/adapters";
|
|
2
|
+
import { getGeminiApiKeyFromEnv } from "../utils/client.js";
|
|
3
|
+
import { GeminiTextAdapter } from "./text.js";
|
|
4
|
+
function createGeminiSummarize(apiKey, model, config) {
|
|
5
|
+
return new ChatStreamSummarizeAdapter(
|
|
6
|
+
new GeminiTextAdapter({ ...config, apiKey }, model),
|
|
7
|
+
model,
|
|
8
|
+
"gemini"
|
|
9
|
+
);
|
|
10
|
+
}
|
|
11
|
+
function geminiSummarize(model, config) {
|
|
12
|
+
return createGeminiSummarize(getGeminiApiKeyFromEnv(), model, config);
|
|
13
|
+
}
|
|
14
|
+
export {
|
|
15
|
+
createGeminiSummarize,
|
|
16
|
+
geminiSummarize
|
|
17
|
+
};
|
|
18
|
+
//# sourceMappingURL=summarize.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"summarize.js","sources":["../../../src/adapters/summarize.ts"],"sourcesContent":["import { ChatStreamSummarizeAdapter } from '@tanstack/ai/adapters'\nimport { getGeminiApiKeyFromEnv } from '../utils'\nimport { GeminiTextAdapter } from './text'\nimport type { InferTextProviderOptions } from '@tanstack/ai/adapters'\nimport type { GEMINI_MODELS } from '../model-meta'\nimport type { GeminiClientConfig } from '../utils'\n\n/**\n * Configuration for Gemini summarize adapter\n */\nexport interface GeminiSummarizeConfig extends GeminiClientConfig {}\n\nexport type GeminiSummarizeModel = (typeof GEMINI_MODELS)[number]\n\n/**\n * Creates a Gemini summarize adapter with explicit API key and model.\n *\n * Note: keeps the historical (apiKey, model, config) argument order to\n * avoid breaking existing callers.\n *\n * @example\n * ```typescript\n * const adapter = createGeminiSummarize('AIza...', 'gemini-2.5-flash');\n * ```\n */\nexport function createGeminiSummarize<TModel extends GeminiSummarizeModel>(\n apiKey: string,\n model: TModel,\n config?: Omit<GeminiSummarizeConfig, 'apiKey'>,\n): ChatStreamSummarizeAdapter<\n TModel,\n InferTextProviderOptions<GeminiTextAdapter<TModel>>\n> {\n return new ChatStreamSummarizeAdapter(\n new GeminiTextAdapter({ ...config, apiKey }, model),\n model,\n 'gemini',\n )\n}\n\n/**\n * Creates a Gemini summarize adapter with API key from `GOOGLE_API_KEY` /\n * `GEMINI_API_KEY` environment variables.\n *\n * @example\n * ```typescript\n * const adapter = geminiSummarize('gemini-2.5-flash');\n * await summarize({ adapter, text: 'Long article text...' });\n * ```\n */\nexport function geminiSummarize<TModel extends GeminiSummarizeModel>(\n model: TModel,\n config?: Omit<GeminiSummarizeConfig, 'apiKey'>,\n): ChatStreamSummarizeAdapter<\n TModel,\n InferTextProviderOptions<GeminiTextAdapter<TModel>>\n> {\n return createGeminiSummarize(getGeminiApiKeyFromEnv(), model, config)\n}\n"],"names":[],"mappings":";;;AAyBO,SAAS,sBACd,QACA,OACA,QAIA;AACA,SAAO,IAAI;AAAA,IACT,IAAI,kBAAkB,EAAE,GAAG,QAAQ,OAAA,GAAU,KAAK;AAAA,IAClD;AAAA,IACA;AAAA,EAAA;AAEJ;AAYO,SAAS,gBACd,OACA,QAIA;AACA,SAAO,sBAAsB,0BAA0B,OAAO,MAAM;AACtE;"}
|