Open History to see the last commit
1import { BaseEmbeddingAdapter } from '@tanstack/ai/adapters'
2import { toRunErrorPayload } from '@tanstack/ai/adapter-internals'
3import {
4 isFileSource,
5 requireTextOnlyEmbeddingInput,
6 resolveEmbeddingInput,
7 unsupportedFileSourceError,
8} from '@tanstack/ai'
9import { resolveBedrockAuth } from '../utils/auth'
10import { BEDROCK_EMBEDDING_MODELS } from '../model-meta'
11import type * as BedrockRuntime from '@aws-sdk/client-bedrock-runtime'
12import type {
13 BedrockRuntimeClient,
14 BedrockRuntimeClientConfig,
15} from '@aws-sdk/client-bedrock-runtime'
16import type {
17 EmbeddingOptions,
18 EmbeddingResult,
19 ImagePart,
20 TokenUsage,
21} from '@tanstack/ai'
22import type { ResolvedBedrockAuth } from '../utils/auth'
23import type { BedrockClientConfig } from '../utils/client'
24import type {
25 BedrockEmbeddingModel,
26 BedrockEmbeddingModelInputModalitiesByName,
27 BedrockEmbeddingModelProviderOptionsByName,
28 ResolveEmbeddingProviderOptions,
29} from '../model-meta'
30
31/**
32 * Config for the Bedrock embedding adapter — the same auth surface as the
33 * other Bedrock adapters (apiKey → env → SigV4 via `resolveBedrockAuth`),
34 * minus the OpenAI-compat client options that don't apply to `InvokeModel`.
35 */
36export interface BedrockEmbeddingConfig extends Pick<
37 BedrockClientConfig,
38 'apiKey' | 'region' | 'auth' | 'baseURL'
39> {}
40
41/** InvokeModel calls issued concurrently during a per-item fan-out. */
42const MAX_CONCURRENT_INVOCATIONS = 5
43
44/** Valid `dimensions` for `amazon.titan-embed-text-v2:0`. */
45const TITAN_TEXT_DIMENSIONS: ReadonlyArray<number> = [256, 512, 1024]
46
47/** Valid `dimensions` (outputEmbeddingLength) for `amazon.titan-embed-image-v1`. */
48const TITAN_IMAGE_DIMENSIONS: ReadonlyArray<number> = [256, 384, 1024]
49const TITAN_IMAGE_DEFAULT_DIMENSIONS = 1024
50
51/** Cohere embed accepts at most 96 texts per InvokeModel call. */
52const COHERE_MAX_BATCH_SIZE = 96
53
54/**
55 * Bedrock Embedding Adapter
56 *
57 * Tree-shakeable adapter for embeddings served through Bedrock's native
58 * `InvokeModel` API (embedding models have no Converse surface). Each model
59 * family has its own JSON body dialect:
60 *
61 * - `amazon.titan-embed-text-v2:0` — text-only, ONE text per call; the batch
62 * is fanned out with a small concurrency cap and per-call
63 * `inputTextTokenCount`s are summed into usage.
64 * - `amazon.titan-embed-image-v1` — MULTIMODAL: text, image, or a fused
65 * text+image item embedded into a single vector; one item per call.
66 * - `cohere.embed-english-v3` / `cohere.embed-multilingual-v3` — text-only,
67 * batched natively (chunked at 96 texts per call). `inputType` is required.
68 *
69 * The SDK call lives behind a protected `invokeModel` seam so tests can
70 * subclass and inject canned response bodies without a real AWS request, and
71 * the AWS SDK itself is imported lazily (it's Node/server-only).
72 */
73export class BedrockEmbeddingAdapter<
74 TModel extends BedrockEmbeddingModel,
75 // Same rationale as the text adapters: the base parameterises
76 // `TProviderOptions extends object`, and the per-model options interfaces
77 // lack implicit index signatures — `Record<string, any>` (not `unknown`)
78 // accepts them. Confined to the generic constraint; no value cast.
79 TProviderOptions extends Record<string, any> =
80 ResolveEmbeddingProviderOptions<TModel>,
81> extends BaseEmbeddingAdapter<
82 TModel,
83 TProviderOptions,
84 BedrockEmbeddingModelProviderOptionsByName,
85 BedrockEmbeddingModelInputModalitiesByName
86> {
87 readonly name = 'bedrock' as const
88 private clientPromise?: Promise<BedrockRuntimeClient>
89 private readonly clientConfig: BedrockEmbeddingConfig
90
91 constructor(config: BedrockEmbeddingConfig, model: TModel) {
92 super(model, {})
93 // Defer client construction and auth resolution: the AWS SDK is Node/
94 // server-only, so we must not pull it into the static graph here. The
95 // client (and its dynamic import) is built lazily on first SDK call.
96 this.clientConfig = config
97 }
98
99 /**
100 * Dynamically import `@aws-sdk/client-bedrock-runtime`. The specifier is
101 * held in a variable (not a string literal) so bundler dep scanners cannot
102 * statically discover the AWS SDK and try to pre-bundle it for the browser.
103 * Same pattern as the Converse text adapter.
104 */
105 protected importBedrockRuntime(): Promise<typeof BedrockRuntime> {
106 const mod = '@aws-sdk/client-bedrock-runtime'
107 return import(/* @vite-ignore */ mod) as Promise<typeof BedrockRuntime>
108 }
109
110 /**
111 * Lazily construct the `BedrockRuntimeClient`, deferring
112 * `resolveBedrockAuth` until a real request is made.
113 */
114 protected async getClient(): Promise<BedrockRuntimeClient> {
115 if (!this.clientPromise) {
116 this.clientPromise = (async () => {
117 const { BedrockRuntimeClient } = await this.importBedrockRuntime()
118 const region = this.clientConfig.region ?? 'us-east-1'
119 const resolved = resolveBedrockAuth(
120 {
121 apiKey: this.clientConfig.apiKey,
122 region,
123 auth: this.clientConfig.auth,
124 },
125 'runtime',
126 )
127 return new BedrockRuntimeClient(
128 this.buildClientConfig(resolved, region, this.clientConfig.baseURL),
129 )
130 })().catch((error: unknown) => {
131 // Don't cache a rejected promise — clear it so a later call can retry
132 // (e.g. after a transient import failure or fixed auth config).
133 this.clientPromise = undefined
134 throw error
135 })
136 }
137 return this.clientPromise
138 }
139
140 /**
141 * Map resolved auth + endpoint to a `BedrockRuntimeClientConfig`. Bearer
142 * auth needs `authSchemePreference` pinned or the SDK still tries SigV4
143 * first — same reasoning as the Converse text adapter.
144 */
145 protected buildClientConfig(
146 resolved: ResolvedBedrockAuth,
147 region: string,
148 endpoint: string | undefined,
149 ): BedrockRuntimeClientConfig {
150 if (resolved.kind === 'bearer') {
151 return {
152 region,
153 token: { token: resolved.token },
154 authSchemePreference: ['httpBearerAuth'],
155 ...(endpoint ? { endpoint } : {}),
156 }
157 }
158 return {
159 region: resolved.region,
160 credentials: resolved.credentials,
161 ...(endpoint ? { endpoint } : {}),
162 }
163 }
164
165 // ---------------------------------------------------------------------------
166 // SDK seam (overridden in tests so no real AWS call happens)
167 // ---------------------------------------------------------------------------
168
169 /** Send one InvokeModel call and parse its JSON response body. */
170 protected async invokeModel(
171 modelId: string,
172 body: Record<string, unknown>,
173 ): Promise<unknown> {
174 const { InvokeModelCommand } = await this.importBedrockRuntime()
175 const client = await this.getClient()
176 const response = await client.send(
177 new InvokeModelCommand({
178 modelId,
179 contentType: 'application/json',
180 accept: 'application/json',
181 body: JSON.stringify(body),
182 }),
183 )
184 return JSON.parse(new TextDecoder().decode(response.body))
185 }
186
187 // ---------------------------------------------------------------------------
188 // Public adapter surface
189 // ---------------------------------------------------------------------------
190
191 async createEmbeddings(
192 options: EmbeddingOptions<TProviderOptions>,
193 ): Promise<EmbeddingResult> {
194 const { model, logger } = options
195 try {
196 logger.request(
197 `activity=embed provider=${this.name} model=${model} inputs=${options.input.length}`,
198 { provider: this.name, model },
199 )
200 switch (model) {
201 case 'amazon.titan-embed-text-v2:0':
202 return await this.embedTitanText(options)
203 case 'amazon.titan-embed-image-v1':
204 return await this.embedTitanImage(options)
205 case 'cohere.embed-english-v3':
206 case 'cohere.embed-multilingual-v3':
207 return await this.embedCohere(options)
208 default:
209 throw new Error(
210 `Unknown Bedrock embedding model "${model}". Supported models: ` +
211 `${BEDROCK_EMBEDDING_MODELS.join(', ')}.`,
212 )
213 }
214 } catch (error: unknown) {
215 logger.errors(`${this.name}.createEmbeddings fatal`, {
216 error: toRunErrorPayload(error, `${this.name}.createEmbeddings failed`),
217 source: `${this.name}.createEmbeddings`,
218 })
219 throw error
220 }
221 }
222
223 // ---------------------------------------------------------------------------
224 // Per-model request mapping
225 // ---------------------------------------------------------------------------
226
227 /**
228 * `amazon.titan-embed-text-v2:0` — one text per InvokeModel call, fanned
229 * out with a concurrency cap; result order matches input order and per-call
230 * `inputTextTokenCount`s are summed into usage.
231 */
232 private async embedTitanText(
233 options: EmbeddingOptions<TProviderOptions>,
234 ): Promise<EmbeddingResult> {
235 const { model, dimensions } = options
236 if (
237 dimensions !== undefined &&
238 !TITAN_TEXT_DIMENSIONS.includes(dimensions)
239 ) {
240 throw new Error(
241 `${model} supports dimensions 256, 512, or 1024; got ${dimensions}`,
242 )
243 }
244 const normalize: boolean | undefined = options.modelOptions?.normalize
245 const texts = requireTextOnlyEmbeddingInput(options.input, this.name, model)
246
247 const responses = await mapWithConcurrency(
248 texts,
249 MAX_CONCURRENT_INVOCATIONS,
250 async (text) => {
251 // Built incrementally: exactOptionalPropertyTypes is on, and Titan
252 // rejects explicit nulls/undefined for absent optional fields.
253 const body: Record<string, unknown> = { inputText: text }
254 if (dimensions !== undefined) body.dimensions = dimensions
255 if (normalize !== undefined) body.normalize = normalize
256 return readTitanEmbeddingBody(
257 await this.invokeModel(model, body),
258 `${this.name} ${model}`,
259 )
260 },
261 )
262
263 return this.toTitanResult(model, responses)
264 }
265
266 /**
267 * `amazon.titan-embed-image-v1` (Titan Multimodal) — one item per
268 * InvokeModel call. An item may carry text, an image, or both (a fused
269 * item embedded into a single vector). Titan accepts at most one image per
270 * request and never fetches remote URLs.
271 */
272 private async embedTitanImage(
273 options: EmbeddingOptions<TProviderOptions>,
274 ): Promise<EmbeddingResult> {
275 const { model, dimensions } = options
276 const outputEmbeddingLength = dimensions ?? TITAN_IMAGE_DEFAULT_DIMENSIONS
277 if (!TITAN_IMAGE_DIMENSIONS.includes(outputEmbeddingLength)) {
278 throw new Error(
279 `${model} supports dimensions 256, 384, or 1024; got ${outputEmbeddingLength}`,
280 )
281 }
282 const items = resolveEmbeddingInput(options.input)
283
284 const responses = await mapWithConcurrency(
285 items,
286 MAX_CONCURRENT_INVOCATIONS,
287 async (item, index) => {
288 if (item.images.length > 1) {
289 throw new Error(
290 `${model} accepts at most one image per input item; input item ` +
291 `at index ${index} contains ${item.images.length} images. ` +
292 `Pass them as separate input items (one vector each).`,
293 )
294 }
295 const body: Record<string, unknown> = {
296 embeddingConfig: { outputEmbeddingLength },
297 }
298 if (item.texts.length > 0) body.inputText = item.texts.join('\n')
299 const image = item.images[0]
300 if (image) body.inputImage = toTitanInputImage(image, model)
301 return readTitanEmbeddingBody(
302 await this.invokeModel(model, body),
303 `${this.name} ${model}`,
304 )
305 },
306 )
307
308 return this.toTitanResult(model, responses)
309 }
310
311 /**
312 * `cohere.embed-*-v3` — natively batched (chunked at 96 texts per call,
313 * order preserved across chunks). `inputType` is required by the Cohere
314 * API; output dimensionality is fixed, so `dimensions` is rejected.
315 */
316 private async embedCohere(
317 options: EmbeddingOptions<TProviderOptions>,
318 ): Promise<EmbeddingResult> {
319 const { model, dimensions } = options
320 if (dimensions !== undefined) {
321 throw new Error(
322 `${model} does not support the dimensions option; its output size is fixed`,
323 )
324 }
325 const inputType: string | undefined = options.modelOptions?.inputType
326 if (inputType === undefined) {
327 throw new Error(
328 `${model} requires modelOptions.inputType ('search_document' | ` +
329 `'search_query' | 'classification' | 'clustering')`,
330 )
331 }
332 const truncate: string | undefined = options.modelOptions?.truncate
333 const texts = requireTextOnlyEmbeddingInput(options.input, this.name, model)
334 const batches = chunk(texts, COHERE_MAX_BATCH_SIZE)
335
336 const responses = await mapWithConcurrency(
337 batches,
338 MAX_CONCURRENT_INVOCATIONS,
339 async (batch) => {
340 const body: Record<string, unknown> = {
341 texts: batch,
342 input_type: inputType,
343 }
344 if (truncate !== undefined) body.truncate = truncate
345 return readCohereEmbeddingBody(
346 await this.invokeModel(model, body),
347 `${this.name} ${model}`,
348 )
349 },
350 )
351
352 return {
353 id: this.generateId(),
354 model,
355 embeddings: responses.flat().map((vector, index) => ({ vector, index })),
356 }
357 }
358
359 /** Assemble an EmbeddingResult from per-item Titan responses. */
360 private toTitanResult(
361 model: string,
362 responses: Array<TitanEmbeddingBody>,
363 ): EmbeddingResult {
364 let promptTokens = 0
365 const embeddings = responses.map((response, index) => {
366 promptTokens += response.inputTextTokenCount
367 return { vector: response.embedding, index }
368 })
369 const usage: TokenUsage = {
370 promptTokens,
371 completionTokens: 0,
372 totalTokens: promptTokens,
373 }
374 return { id: this.generateId(), model, embeddings, usage }
375 }
376}
377
378// ---------------------------------------------------------------------------
379// Response-body narrowing (SDK JSON boundary)
380// ---------------------------------------------------------------------------
381
382interface TitanEmbeddingBody {
383 embedding: Array<number>
384 /** 0 when the response omits it (e.g. image-only Titan Multimodal calls). */
385 inputTextTokenCount: number
386}
387
388function isRecord(value: unknown): value is Record<string, unknown> {
389 return typeof value === 'object' && value !== null
390}
391
392/** Narrow a Titan InvokeModel JSON body: `{ embedding, inputTextTokenCount? }`. */
393function readTitanEmbeddingBody(
394 raw: unknown,
395 context: string,
396): TitanEmbeddingBody {
397 const embedding =
398 isRecord(raw) && Array.isArray(raw.embedding) ? raw.embedding : undefined
399 if (!embedding) {
400 throw new Error(
401 `${context}: response body is missing the "embedding" array`,
402 )
403 }
404 const inputTextTokenCount =
405 isRecord(raw) && typeof raw.inputTextTokenCount === 'number'
406 ? raw.inputTextTokenCount
407 : 0
408 return { embedding, inputTextTokenCount }
409}
410
411/** Narrow a Cohere InvokeModel JSON body: `{ embeddings: number[][] }` (float). */
412function readCohereEmbeddingBody(
413 raw: unknown,
414 context: string,
415): Array<Array<number>> {
416 const embeddings =
417 isRecord(raw) && Array.isArray(raw.embeddings) ? raw.embeddings : undefined
418 if (!embeddings) {
419 throw new Error(
420 `${context}: response body is missing the "embeddings" array`,
421 )
422 }
423 return embeddings
424}
425
426// ---------------------------------------------------------------------------
427// Input mapping helpers
428// ---------------------------------------------------------------------------
429
430/**
431 * Map an ImagePart to Titan's `inputImage` (RAW base64, no data: prefix).
432 * Accepts `data` sources as-is and `url` sources ONLY when the value is a
433 * `data:` URI; Titan cannot fetch remote http(s) URLs.
434 */
435function toTitanInputImage(image: ImagePart, model: string): string {
436 const source = image.source
437 if (isFileSource(source)) throw unsupportedFileSourceError('bedrock')
438 if (source.type === 'data') {
439 return source.value
440 }
441 if (source.value.startsWith('data:')) {
442 const comma = source.value.indexOf(',')
443 if (comma !== -1) {
444 return source.value.slice(comma + 1)
445 }
446 }
447 throw new Error(
448 `Bedrock Titan does not fetch remote image URLs; pass base64 data ` +
449 `(a { type: 'data' } source or a data: URI) for ${model}.`,
450 )
451}
452
453/** Split into runs of at most `size`, preserving order. */
454function chunk<T>(items: Array<T>, size: number): Array<Array<T>> {
455 const chunks: Array<Array<T>> = []
456 for (let i = 0; i < items.length; i += size) {
457 chunks.push(items.slice(i, i + size))
458 }
459 return chunks
460}
461
462/**
463 * Map `fn` over `items` with at most `limit` calls in flight, returning
464 * results in input order (result[i] corresponds to items[i] regardless of
465 * completion order). Rejects with the first error.
466 */
467async function mapWithConcurrency<T, TResult>(
468 items: ReadonlyArray<T>,
469 limit: number,
470 fn: (item: T, index: number) => Promise<TResult>,
471): Promise<Array<TResult>> {
472 const results = new Array<TResult>(items.length)
473 let next = 0
474 const worker = async (): Promise<void> => {
475 while (next < items.length) {
476 const index = next++
477 const item = items[index]
478 if (item === undefined) continue // unreachable: index < length
479 results[index] = await fn(item, index)
480 }
481 }
482 const workerCount = Math.max(1, Math.min(limit, items.length))
483 await Promise.all(Array.from({ length: workerCount }, () => worker()))
484 return results
485}
486
487// ---------------------------------------------------------------------------
488// Factories
489// ---------------------------------------------------------------------------
490
491/**
492 * Creates a Bedrock embedding adapter with an explicit API key (bearer).
493 * Type resolution happens here at the call site.
494 *
495 * @param model - The model name (e.g., 'amazon.titan-embed-text-v2:0')
496 * @param apiKey - Your Bedrock API key
497 * @param config - Optional additional configuration (region, baseURL, ...)
498 * @returns Configured Bedrock embedding adapter instance with resolved types
499 *
500 * @example
501 * ```typescript
502 * const adapter = createBedrockEmbedding(
503 * 'amazon.titan-embed-text-v2:0',
504 * 'bedrock-api-key',
505 * );
506 *
507 * const result = await embed({
508 * adapter,
509 * input: 'a red guitar',
510 * });
511 * ```
512 */
513export function createBedrockEmbedding<TModel extends BedrockEmbeddingModel>(
514 model: TModel,
515 apiKey: string,
516 config?: Omit<BedrockEmbeddingConfig, 'apiKey'>,
517): BedrockEmbeddingAdapter<TModel> {
518 // Explicit apiKey is authoritative — spread config first so it can't override.
519 return new BedrockEmbeddingAdapter({ ...config, apiKey }, model)
520}
521
522/**
523 * Creates a Bedrock embedding adapter using the ambient auth cascade:
524 * `config.apiKey` → `BEDROCK_API_KEY` → `AWS_BEARER_TOKEN_BEDROCK` → SigV4
525 * (AWS credential provider chain). Auth resolves lazily on the first
526 * request, so `auth: 'sigv4'` never requires an API key.
527 *
528 * @param model - The model name (e.g., 'cohere.embed-english-v3')
529 * @param config - Optional configuration (region, auth, baseURL, ...)
530 * @returns Configured Bedrock embedding adapter instance with resolved types
531 *
532 * @example
533 * ```typescript
534 * const adapter = bedrockEmbedding('cohere.embed-english-v3');
535 *
536 * const result = await embed({
537 * adapter,
538 * input: ['a red guitar', 'a blue drum kit'],
539 * modelOptions: { inputType: 'search_document' },
540 * });
541 *
542 * console.log(result.embeddings[0].vector)
543 * ```
544 */
545export function bedrockEmbedding<TModel extends BedrockEmbeddingModel>(
546 model: TModel,
547 config?: BedrockEmbeddingConfig,
548): BedrockEmbeddingAdapter<TModel> {
549 return new BedrockEmbeddingAdapter(config ?? {}, model)
550}