Open History to see the last commit
1import OpenAI from 'openai'
2import { BaseEmbeddingAdapter } from '@tanstack/ai/adapters'
3import { toRunErrorPayload } from '@tanstack/ai/adapter-internals'
4import { generateId } from '@tanstack/ai-utils'
5import { requireTextOnlyEmbeddingInput } from '@tanstack/ai'
6import {
7 getVercelGatewayApiKeyFromEnv,
8 withVercelGatewayDefaults,
9} from '../utils/client'
10import { mapGatewayModelOptions } from '../utils/map-gateway-options'
11import type {
12 EmbeddingOptions,
13 EmbeddingResult,
14 TokenUsage,
15} from '@tanstack/ai'
16import type OpenAI_SDK from 'openai'
17import type {
18 VercelGatewayEmbeddingModel,
19 VercelGatewayEmbeddingModelInputModalitiesByName,
20 VercelGatewayEmbeddingModelProviderOptionsByName,
21} from '../model-meta'
22import type { VercelGatewayEmbeddingProviderOptions } from '../embedding/embedding-provider-options'
23import type { VercelGatewayClientConfig } from '../utils/client'
24
25export interface VercelGatewayEmbeddingConfig extends VercelGatewayClientConfig {}
26
27/**
28 * Vercel AI Gateway embedding adapter.
29 *
30 * Talks to `POST /v1/embeddings` on the public OpenAI-compatible Gateway API.
31 */
32export class VercelGatewayEmbeddingAdapter<
33 TModel extends VercelGatewayEmbeddingModel,
34> extends BaseEmbeddingAdapter<
35 TModel,
36 VercelGatewayEmbeddingProviderOptions,
37 VercelGatewayEmbeddingModelProviderOptionsByName,
38 VercelGatewayEmbeddingModelInputModalitiesByName
39> {
40 readonly name = 'vercel-gateway' as const
41
42 protected client: OpenAI
43
44 constructor(config: VercelGatewayEmbeddingConfig, model: TModel) {
45 super(model, {})
46 this.client = new OpenAI(withVercelGatewayDefaults(config))
47 }
48
49 async createEmbeddings(
50 options: EmbeddingOptions<VercelGatewayEmbeddingProviderOptions>,
51 ): Promise<EmbeddingResult> {
52 const { model, logger } = options
53 const texts = requireTextOnlyEmbeddingInput(options.input, this.name, model)
54 const mapped = mapGatewayModelOptions(
55 options.modelOptions as Record<string, unknown> | undefined,
56 )
57
58 try {
59 const request: OpenAI_SDK.EmbeddingCreateParams = {
60 ...mapped,
61 model,
62 input: texts,
63 encoding_format: 'float',
64 }
65 if (options.dimensions !== undefined) {
66 request.dimensions = options.dimensions
67 }
68
69 logger.request(
70 `activity=embed provider=${this.name} model=${model} inputs=${texts.length}`,
71 { provider: this.name, model },
72 )
73
74 const response = await this.client.embeddings.create(request)
75
76 const usage: TokenUsage = {
77 promptTokens: response.usage.prompt_tokens,
78 completionTokens: 0,
79 totalTokens: response.usage.total_tokens,
80 }
81
82 return {
83 id: generateId(this.name),
84 model,
85 embeddings: response.data.map((item) => ({
86 vector: item.embedding,
87 index: item.index,
88 })),
89 usage,
90 }
91 } catch (error: unknown) {
92 logger.errors(`${this.name}.createEmbeddings fatal`, {
93 error: toRunErrorPayload(error, `${this.name}.createEmbeddings failed`),
94 source: `${this.name}.createEmbeddings`,
95 })
96 throw error
97 }
98 }
99}
100
101export function createVercelGatewayEmbedding<
102 TModel extends VercelGatewayEmbeddingModel,
103>(
104 model: TModel,
105 apiKey: string,
106 config?: Omit<VercelGatewayEmbeddingConfig, 'apiKey'>,
107): VercelGatewayEmbeddingAdapter<TModel> {
108 return new VercelGatewayEmbeddingAdapter({ apiKey, ...config }, model)
109}
110
111export function vercelGatewayEmbedding<
112 TModel extends VercelGatewayEmbeddingModel,
113>(
114 model: TModel,
115 config?: Omit<VercelGatewayEmbeddingConfig, 'apiKey'>,
116): VercelGatewayEmbeddingAdapter<TModel> {
117 return createVercelGatewayEmbedding(
118 model,
119 getVercelGatewayApiKeyFromEnv(),
120 config,
121 )
122}