-
-
Notifications
You must be signed in to change notification settings - Fork 188
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 8 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 |
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,94 @@ | ||
| import { BaseEmbeddingAdapter } from '@tanstack/ai/adapters' | ||
| import { createGeminiClient, generateId } 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 { GEMINI_EMBEDDING_MODELS } 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 type GeminiEmbeddingModel = (typeof GEMINI_EMBEDDING_MODELS)[number] | ||
|
|
||
| export class GeminiEmbeddingAdapter< | ||
| TModel extends GeminiEmbeddingModel, | ||
| > 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 { embeddings } = await this.client.models.embedContent({ | ||
| model, | ||
| contents: value, | ||
| config: { | ||
| ...modelOptions, | ||
| }, | ||
| }) | ||
|
|
||
| return { | ||
| embedding: embeddings?.[0]?.values || [], | ||
| id: generateId(this.name), | ||
| model, | ||
| usage: undefined, | ||
| } | ||
| } | ||
|
|
||
| async embedMany( | ||
| options: EmbedManyOptions<GeminiEmbeddingProviderOptions>, | ||
| ): Promise<EmbedManyResult> { | ||
| const { model, values, modelOptions } = options | ||
|
|
||
| validateValue({ value: values, model }) | ||
| validateTaskType({ taskType: modelOptions?.taskType, model }) | ||
|
|
||
| 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: undefined, | ||
| } | ||
| } | ||
| } |
88 changes: 88 additions & 0 deletions
88
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,88 @@ | ||
| import type { HttpOptions } from '@google/genai' | ||
| import type { GeminiEmbeddingModels } from '../model-meta' | ||
|
|
||
| const VALID_TASK_TYPES = new Set([ | ||
| 'SEMANTIC_SIMILARITY', | ||
| 'CLASSIFICATION', | ||
| 'CLUSTERING', | ||
| 'RETRIEVAL_DOCUMENT', | ||
| 'RETRIEVAL_QUERY', | ||
| 'CODE_RETRIEVAL_QUERY', | ||
| 'QUESTION_ANSWERING', | ||
| 'FACT_VERIFICATION', | ||
| ]) | ||
|
|
||
| type TaskType = | ||
| | 'SEMANTIC_SIMILARITY' | ||
| | 'CLASSIFICATION' | ||
| | 'CLUSTERING' | ||
| | 'RETRIEVAL_DOCUMENT' | ||
| | 'RETRIEVAL_QUERY' | ||
| | 'CODE_RETRIEVAL_QUERY' | ||
| | 'QUESTION_ANSWERING' | ||
| | 'FACT_VERIFICATION' | ||
|
|
||
| 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.has(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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| import type { | ||
| EmbedManyOptions, | ||
| EmbedManyResult, | ||
| EmbedOptions, | ||
| EmbedResult, | ||
| } from '../../types' | ||
|
|
||
| // =========================== | ||
| // Activity Kind | ||
| // =========================== | ||
|
|
||
| /** The adapter kind this activity handles */ | ||
| export const kind = 'embedding' as const | ||
|
|
||
| export interface EmbeddingAdapterConfig { | ||
| apiKey?: string | ||
| baseUrl?: string | ||
| timeout?: number | ||
| maxRetries?: number | ||
| headers?: Record<string, string> | ||
| } | ||
|
|
||
| export interface EmbeddingAdapter< | ||
| TModel extends string = string, | ||
| TProviderOptions extends object = Record<string, unknown>, | ||
| > { | ||
| /** Discriminator for adapter kind - used to determine API shape */ | ||
| readonly kind: 'embedding' | ||
| /** Adapter name identifier */ | ||
| readonly name: string | ||
| /** The model this adapter is configured for */ | ||
| readonly model: TModel | ||
|
|
||
| /** | ||
| * @internal Type-only properties for inference. Not assigned at runtime. | ||
| */ | ||
| '~types': { | ||
| providerOptions: TProviderOptions | ||
| } | ||
|
|
||
| /** | ||
| * Generate embeddings for text | ||
| */ | ||
| embed: (options: EmbedOptions<TProviderOptions>) => Promise<EmbedResult> | ||
|
|
||
| /** | ||
| * Generate embeddings for multiple texts | ||
| */ | ||
| embedMany: ( | ||
| options: EmbedManyOptions<TProviderOptions>, | ||
| ) => Promise<EmbedManyResult> | ||
| } | ||
|
|
||
| /** | ||
| * A EmbeddingAdapter with any/unknown type parameters. | ||
| * Useful as a constraint in generic functions and interfaces. | ||
| */ | ||
| export type AnyEmbeddingAdapter = EmbeddingAdapter<any, any> | ||
|
|
||
| /** | ||
| * Abstract base class for embed adapters. | ||
| * Extend this class to implement an embed adapter for a specific provider. | ||
| * | ||
| * Generic parameters match EmbedAdapter - all pre-resolved by the provider function. | ||
| */ | ||
| export abstract class BaseEmbeddingAdapter< | ||
| TModel extends string = string, | ||
| TProviderOptions extends object = Record<string, unknown>, | ||
| > implements EmbeddingAdapter<TModel, TProviderOptions> { | ||
| readonly kind = 'embedding' as const | ||
| abstract readonly name: string | ||
| readonly model: TModel | ||
|
|
||
| // Type-only property - never assigned at runtime | ||
| declare '~types': { | ||
| providerOptions: TProviderOptions | ||
| } | ||
|
|
||
| protected config: EmbeddingAdapterConfig | ||
|
|
||
| constructor(config: EmbeddingAdapterConfig = {}, model: TModel) { | ||
| this.config = config | ||
| this.model = model | ||
| } | ||
|
|
||
| abstract embed(options: EmbedOptions<TProviderOptions>): Promise<EmbedResult> | ||
|
|
||
| abstract embedMany( | ||
| options: EmbedManyOptions<TProviderOptions>, | ||
| ): Promise<EmbedManyResult> | ||
| } |
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.