Open History to see the last commit
1import { BaseEmbeddingAdapter } from '@tanstack/ai/adapters'
2import { toRunErrorPayload } from '@tanstack/ai/adapter-internals'
3import { requireTextOnlyEmbeddingInput } from '@tanstack/ai'
4import {
5 createGeminiClient,
6 generateId,
7 getGeminiApiKeyFromEnv,
8} from '../utils'
9import type { EmbeddingOptions, EmbeddingResult } from '@tanstack/ai'
10import type { EmbedContentConfig, GoogleGenAI } from '@google/genai'
11import type {
12 GeminiEmbeddingModel,
13 GeminiEmbeddingModelInputModalitiesByName,
14 GeminiEmbeddingModelProviderOptionsByName,
15} from '../model-meta'
16import type { GeminiEmbeddingProviderOptions } from '../embedding/embedding-provider-options'
17import type { GeminiClientConfig } from '../utils/client'
18
19/**
20 * Configuration for Gemini Embedding adapter
21 */
22export interface GeminiEmbeddingConfig extends GeminiClientConfig {}
23
24/**
25 * Gemini Embedding Adapter
26 *
27 * Tree-shakeable adapter for Gemini text embeddings.
28 * Supports gemini-embedding-001.
29 *
30 * Features:
31 * - Batch embedding (one request for the whole input array)
32 * - Matryoshka dimension reduction via the top-level `dimensions` option
33 * (mapped to the SDK's `outputDimensionality`)
34 * - Task-type hints (`taskType`, `title`) via provider options
35 */
36export class GeminiEmbeddingAdapter<
37 TModel extends GeminiEmbeddingModel,
38> extends BaseEmbeddingAdapter<
39 TModel,
40 GeminiEmbeddingProviderOptions,
41 GeminiEmbeddingModelProviderOptionsByName,
42 GeminiEmbeddingModelInputModalitiesByName
43> {
44 readonly name = 'gemini' as const
45
46 protected client: GoogleGenAI
47
48 constructor(config: GeminiEmbeddingConfig, model: TModel) {
49 super(model, {})
50 this.client = createGeminiClient(config)
51 }
52
53 async createEmbeddings(
54 options: EmbeddingOptions<GeminiEmbeddingProviderOptions>,
55 ): Promise<EmbeddingResult> {
56 const { model, logger, modelOptions } = options
57 const texts = requireTextOnlyEmbeddingInput(options.input, this.name, model)
58
59 try {
60 // Build the config incrementally so possibly-undefined values are never
61 // assigned to optional fields (exactOptionalPropertyTypes).
62 const config: EmbedContentConfig = {}
63 if (options.dimensions !== undefined) {
64 config.outputDimensionality = options.dimensions
65 }
66 if (modelOptions?.taskType !== undefined) {
67 config.taskType = modelOptions.taskType
68 }
69 if (modelOptions?.title !== undefined) {
70 config.title = modelOptions.title
71 }
72
73 logger.request(
74 `activity=embed provider=${this.name} model=${model} inputs=${texts.length}`,
75 { provider: this.name, model },
76 )
77
78 const response = await this.client.models.embedContent({
79 model,
80 contents: texts,
81 config,
82 })
83
84 const embeddings = response.embeddings
85 if (!embeddings || embeddings.length !== texts.length) {
86 throw new Error(
87 `Gemini embedContent returned ${embeddings ? embeddings.length : 'no'} embeddings for ${texts.length} inputs (model: ${model}).`,
88 )
89 }
90
91 // The Gemini embedding API does not report token usage, so `usage` is
92 // omitted from the result.
93 return {
94 id: generateId(this.name),
95 model,
96 embeddings: embeddings.map((embedding, index) => ({
97 vector: embedding.values ?? [],
98 index,
99 })),
100 }
101 } catch (error: unknown) {
102 logger.errors(`${this.name}.createEmbeddings fatal`, {
103 error: toRunErrorPayload(error, `${this.name}.createEmbeddings failed`),
104 source: `${this.name}.createEmbeddings`,
105 })
106 throw error
107 }
108 }
109}
110
111/**
112 * Creates a Gemini embedding adapter with explicit API key.
113 * Type resolution happens here at the call site.
114 *
115 * @param model - The model name (e.g., 'gemini-embedding-001')
116 * @param apiKey - Your Google API key
117 * @param config - Optional additional configuration
118 * @returns Configured Gemini embedding adapter instance with resolved types
119 *
120 * @example
121 * ```typescript
122 * const adapter = createGeminiEmbedding('gemini-embedding-001', "your-api-key");
123 *
124 * const result = await embed({
125 * adapter,
126 * input: 'a red guitar'
127 * });
128 * ```
129 */
130export function createGeminiEmbedding<TModel extends GeminiEmbeddingModel>(
131 model: TModel,
132 apiKey: string,
133 config?: Omit<GeminiEmbeddingConfig, 'apiKey'>,
134): GeminiEmbeddingAdapter<TModel> {
135 // Put apiKey LAST so caller-supplied config can't silently override the
136 // explicit argument.
137 return new GeminiEmbeddingAdapter({ ...config, apiKey }, model)
138}
139
140/**
141 * Creates a Gemini embedding adapter with automatic API key detection from environment variables.
142 * Type resolution happens here at the call site.
143 *
144 * Looks for `GOOGLE_API_KEY` or `GEMINI_API_KEY` in:
145 * - `process.env` (Node.js)
146 * - `window.env` (Browser with injected env)
147 *
148 * @param model - The model name (e.g., 'gemini-embedding-001')
149 * @param config - Optional configuration (excluding apiKey which is auto-detected)
150 * @returns Configured Gemini embedding adapter instance with resolved types
151 * @throws Error if GOOGLE_API_KEY or GEMINI_API_KEY is not found in environment
152 *
153 * @example
154 * ```typescript
155 * // Automatically uses GOOGLE_API_KEY from environment
156 * const adapter = geminiEmbedding('gemini-embedding-001');
157 *
158 * const result = await embed({
159 * adapter,
160 * input: ['a red guitar', 'a blue drum kit'],
161 * dimensions: 1536
162 * });
163 *
164 * console.log(result.embeddings[0].vector)
165 * ```
166 */
167export function geminiEmbedding<TModel extends GeminiEmbeddingModel>(
168 model: TModel,
169 config?: Omit<GeminiEmbeddingConfig, 'apiKey'>,
170): GeminiEmbeddingAdapter<TModel> {
171 const apiKey = getGeminiApiKeyFromEnv()
172 return createGeminiEmbedding(model, apiKey, config)
173}