-
-
Notifications
You must be signed in to change notification settings - Fork 133
Feat: embedding activities & gemini embedding adapter #291
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
nikas-belogolov
wants to merge
14
commits into
TanStack:main
Choose a base branch
from
nikas-belogolov:feat/embed-activity
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
7884f3c
Added embed/embedMany activites & Gemini embeddings adapter
nikas-belogolov e7b4087
added changeset
nikas-belogolov 8317f55
ci: apply automated fixes
autofix-ci[bot] bca129c
Update packages/typescript/ai/src/types.ts
nikas-belogolov c5d6b92
Update packages/typescript/ai/src/activities/embed/embed-many.ts
nikas-belogolov 36cc319
Update packages/typescript/ai/src/activities/embed/embed-many.ts
nikas-belogolov 8a00a48
moved createId into a utility module, added typing
nikas-belogolov 74d3d9c
ci: apply automated fixes
autofix-ci[bot] 704a4c6
Update packages/typescript/ai/src/activities/generateSpeech/index.ts
nikas-belogolov 55cb0a8
fixed event name
nikas-belogolov c3f49f4
derive TaskType type from VALID_TASK_TYPES
nikas-belogolov 3d6e104
Added gemini embedding adpter totalTokens count
nikas-belogolov f389f01
fixed gemini embedding adapter
nikas-belogolov 4d1ad0a
ci: apply automated fixes
autofix-ci[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| --- | ||
| '@tanstack/tests-adapters': minor | ||
| '@tanstack/preact-ai-devtools': minor | ||
| '@tanstack/react-ai-devtools': minor | ||
| '@tanstack/solid-ai-devtools': minor | ||
| '@tanstack/smoke-tests-e2e': minor | ||
| '@tanstack/ai-openrouter': minor | ||
| '@tanstack/ai-anthropic': minor | ||
| '@tanstack/ai-devtools-core': minor | ||
| '@tanstack/ai-react-ui': minor | ||
| '@tanstack/ai-solid-ui': minor | ||
| '@tanstack/ai-client': minor | ||
| '@tanstack/ai-gemini': minor | ||
| '@tanstack/ai-ollama': minor | ||
| '@tanstack/ai-openai': minor | ||
| '@tanstack/ai-preact': minor | ||
| '@tanstack/ai-svelte': minor | ||
| '@tanstack/ai-vue-ui': minor | ||
| '@tanstack/ai-react': minor | ||
| '@tanstack/ai-solid': minor | ||
| '@tanstack/ai-grok': minor | ||
| '@tanstack/ai-vue': minor | ||
| 'ts-svelte-chat': minor | ||
| '@tanstack/ai': minor | ||
| 'vanilla-chat': minor | ||
| 'ts-vue-chat': minor | ||
| --- | ||
|
|
||
| Added embed/embedMany activity and Gemini embeddings adapter |
165 changes: 165 additions & 0 deletions
165
packages/typescript/ai-gemini/src/adapters/embedding.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,165 @@ | ||
| import { BaseEmbeddingAdapter } from '@tanstack/ai/adapters' | ||
| import { | ||
| createGeminiClient, | ||
| generateId, | ||
| getGeminiApiKeyFromEnv, | ||
| } from '../utils' | ||
| import { | ||
| validateTaskType, | ||
| validateValue, | ||
| } from '../embedding/embedding-provider-options' | ||
| import type { GoogleGenAI } from '@google/genai' | ||
| import type { | ||
| EmbedManyOptions, | ||
| EmbedManyResult, | ||
| EmbedOptions, | ||
| EmbedResult, | ||
| } from '@tanstack/ai' | ||
| import type { GeminiEmbeddingModels } from '../model-meta' | ||
| import type { GeminiClientConfig } from '../utils' | ||
| import type { | ||
| GeminiEmbeddingModelProviderOptionsByName, | ||
| GeminiEmbeddingProviderOptions, | ||
| } from '../embedding/embedding-provider-options' | ||
|
|
||
| /** | ||
| * Configuration for Gemini embedding adapter | ||
| */ | ||
| export interface GeminiEmbeddingConfig extends GeminiClientConfig {} | ||
|
|
||
| export class GeminiEmbeddingAdapter< | ||
| TModel extends GeminiEmbeddingModels, | ||
| > extends BaseEmbeddingAdapter<TModel, GeminiEmbeddingProviderOptions> { | ||
| readonly kind = 'embedding' as const | ||
| readonly name = 'gemini' as const | ||
|
|
||
| // Type-only property - never assigned at runtime | ||
| declare '~types': { | ||
| providerOptions: GeminiEmbeddingProviderOptions | ||
| modelProviderOptionsByName: GeminiEmbeddingModelProviderOptionsByName | ||
| } | ||
|
|
||
| private client: GoogleGenAI | ||
|
|
||
| constructor(config: GeminiEmbeddingConfig, model: TModel) { | ||
| super({}, model) | ||
| this.client = createGeminiClient(config) | ||
| } | ||
|
|
||
| async embed( | ||
| options: EmbedOptions<GeminiEmbeddingProviderOptions>, | ||
| ): Promise<EmbedResult> { | ||
| const { model, value, modelOptions } = options | ||
|
|
||
| validateValue({ value, model }) | ||
| validateTaskType({ taskType: modelOptions?.taskType, model }) | ||
|
|
||
| const { totalTokens } = await this.client.models.countTokens({ | ||
| model, | ||
| contents: value, | ||
| }) | ||
|
|
||
| const { embeddings } = await this.client.models.embedContent({ | ||
| model, | ||
| contents: value, | ||
| config: { | ||
| ...modelOptions, | ||
| }, | ||
| }) | ||
|
|
||
| return { | ||
| embedding: embeddings?.[0]?.values || [], | ||
| id: generateId(this.name), | ||
| model, | ||
| usage: totalTokens ? { totalTokens } : undefined, | ||
| } | ||
| } | ||
|
|
||
| async embedMany( | ||
| options: EmbedManyOptions<GeminiEmbeddingProviderOptions>, | ||
| ): Promise<EmbedManyResult> { | ||
| const { model, values, modelOptions } = options | ||
|
|
||
| validateValue({ value: values, model }) | ||
| validateTaskType({ taskType: modelOptions?.taskType, model }) | ||
|
|
||
| const { totalTokens } = await this.client.models.countTokens({ | ||
| model, | ||
| contents: values, | ||
| }) | ||
|
|
||
| const { embeddings } = await this.client.models.embedContent({ | ||
| model, | ||
| contents: values, | ||
| config: { | ||
| ...modelOptions, | ||
| }, | ||
| }) | ||
|
|
||
| return { | ||
| embeddings: embeddings?.map((embedding) => embedding.values || []) || [], | ||
| id: generateId(this.name), | ||
| model, | ||
| usage: totalTokens ? { totalTokens } : undefined, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Creates a Gemini embedding adapter with explicit API key. | ||
| * Type resolution happens here at the call site. | ||
| * | ||
| * @param model - The model name (e.g., 'embedding-001') | ||
| * @param apiKey - Your Google API key | ||
| * @param config - Optional additional configuration | ||
| * @returns Configured Gemini embedding adapter instance with resolved types | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * const adapter = createGeminiEmbedding('embedding-001', "your-api-key"); | ||
| * | ||
| * const result = await embed({ | ||
| * adapter, | ||
| * value: 'Hello, world!' | ||
| * }); | ||
| * ``` | ||
| */ | ||
| export function createGeminiEmbedding<TModel extends GeminiEmbeddingModels>( | ||
| model: TModel, | ||
| apiKey: string, | ||
| config?: Omit<GeminiEmbeddingConfig, 'apiKey'>, | ||
| ): GeminiEmbeddingAdapter<TModel> { | ||
| return new GeminiEmbeddingAdapter({ apiKey, ...config }, model) | ||
| } | ||
|
|
||
| /** | ||
| * Creates a Gemini embedding adapter with automatic API key detection from environment variables. | ||
| * Type resolution happens here at the call site. | ||
| * | ||
| * Looks for `GOOGLE_API_KEY` or `GEMINI_API_KEY` in: | ||
| * - `process.env` (Node.js) | ||
| * - `window.env` (Browser with injected env) | ||
| * | ||
| * @param model - The model name (e.g., 'embedding-001') | ||
| * @param config - Optional configuration (excluding apiKey which is auto-detected) | ||
| * @returns Configured Gemini embedding adapter instance with resolved types | ||
| * @throws Error if GOOGLE_API_KEY or GEMINI_API_KEY is not found in environment | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * // Automatically uses GOOGLE_API_KEY from environment | ||
| * const adapter = geminiEmbedding('embedding-001'); | ||
| * | ||
| * const result = await embed({ | ||
| * adapter, | ||
| * value: 'Hello, world!' | ||
| * }); | ||
| * ``` | ||
| */ | ||
| export function geminiEmbedding<TModel extends GeminiEmbeddingModels>( | ||
| model: TModel, | ||
| config?: Omit<GeminiEmbeddingConfig, 'apiKey'>, | ||
| ): GeminiEmbeddingAdapter<TModel> { | ||
| const apiKey = getGeminiApiKeyFromEnv() | ||
| return createGeminiEmbedding(model, apiKey, config) | ||
| } |
80 changes: 80 additions & 0 deletions
80
packages/typescript/ai-gemini/src/embedding/embedding-provider-options.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| import type { HttpOptions } from '@google/genai' | ||
| import type { GeminiEmbeddingModels } from '../model-meta' | ||
|
|
||
| const VALID_TASK_TYPES = [ | ||
| 'SEMANTIC_SIMILARITY', | ||
| 'CLASSIFICATION', | ||
| 'CLUSTERING', | ||
| 'RETRIEVAL_DOCUMENT', | ||
| 'RETRIEVAL_QUERY', | ||
| 'CODE_RETRIEVAL_QUERY', | ||
| 'QUESTION_ANSWERING', | ||
| 'FACT_VERIFICATION', | ||
| ] as const | ||
|
|
||
| type TaskType = (typeof VALID_TASK_TYPES)[number] | ||
|
|
||
| export interface GeminiEmbeddingProviderOptions { | ||
| /** Used to override HTTP request options. */ | ||
| httpOptions?: HttpOptions | ||
| /** | ||
| * Type of task for which the embedding will be used. | ||
| */ | ||
| taskType?: TaskType | ||
| /** | ||
| * Title for the text. Only applicable when TaskType is `RETRIEVAL_DOCUMENT`. | ||
| */ | ||
| title?: string | ||
| /** | ||
| * Reduced dimension for the output embedding. If set, | ||
| * excessive values in the output embedding are truncated from the end. | ||
| * Supported by newer models since 2024 only. You cannot set this value if | ||
| * using the earlier model (`models/embedding-001`). | ||
| */ | ||
| outputDimensionality?: number | ||
| } | ||
|
|
||
| export type GeminiEmbeddingModelProviderOptionsByName = { | ||
| [K in GeminiEmbeddingModels]: GeminiEmbeddingProviderOptions | ||
| } | ||
|
|
||
| /** | ||
| * Validates the task type | ||
| */ | ||
| export function validateTaskType(options: { | ||
| taskType: TaskType | undefined | ||
| model: string | ||
| }) { | ||
| const { taskType, model } = options | ||
| if (!taskType) return | ||
|
|
||
| if (!VALID_TASK_TYPES.includes(taskType)) { | ||
| throw new Error(`Invalid task type "${taskType}" for model "${model}".`) | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Validates the value to embed is not empty | ||
| */ | ||
| export function validateValue(options: { | ||
| value: string | Array<string> | ||
| model: string | ||
| }): void { | ||
| const { value, model } = options | ||
| if (Array.isArray(value)) { | ||
| if (value.length === 0) { | ||
| throw new Error(`Value array cannot be empty for model "${model}".`) | ||
| } | ||
| for (const v of value) { | ||
| if (!v || v.trim().length === 0) { | ||
| throw new Error( | ||
| `Value array cannot contain empty values for model "${model}".`, | ||
| ) | ||
| } | ||
| } | ||
| } else { | ||
| if (!value || value.trim().length === 0) { | ||
| throw new Error(`Value cannot be empty for model "${model}".`) | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.