@tanstack/ai-bedrock 0.1.6 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"embedding.js","names":[],"sources":["../../../src/adapters/embedding.ts"],"sourcesContent":["import { BaseEmbeddingAdapter } from '@tanstack/ai/adapters'\nimport { toRunErrorPayload } from '@tanstack/ai/adapter-internals'\nimport {\n requireTextOnlyEmbeddingInput,\n resolveEmbeddingInput,\n} from '@tanstack/ai'\nimport { resolveBedrockAuth } from '../utils/auth'\nimport { BEDROCK_EMBEDDING_MODELS } from '../model-meta'\nimport type * as BedrockRuntime from '@aws-sdk/client-bedrock-runtime'\nimport type {\n BedrockRuntimeClient,\n BedrockRuntimeClientConfig,\n} from '@aws-sdk/client-bedrock-runtime'\nimport type {\n EmbeddingOptions,\n EmbeddingResult,\n ImagePart,\n TokenUsage,\n} from '@tanstack/ai'\nimport type { ResolvedBedrockAuth } from '../utils/auth'\nimport type { BedrockClientConfig } from '../utils/client'\nimport type {\n BedrockEmbeddingModel,\n BedrockEmbeddingModelInputModalitiesByName,\n BedrockEmbeddingModelProviderOptionsByName,\n ResolveEmbeddingProviderOptions,\n} from '../model-meta'\n\n/**\n * Config for the Bedrock embedding adapter — the same auth surface as the\n * other Bedrock adapters (apiKey → env → SigV4 via `resolveBedrockAuth`),\n * minus the OpenAI-compat client options that don't apply to `InvokeModel`.\n */\nexport interface BedrockEmbeddingConfig extends Pick<\n BedrockClientConfig,\n 'apiKey' | 'region' | 'auth' | 'baseURL'\n> {}\n\n/** InvokeModel calls issued concurrently during a per-item fan-out. */\nconst MAX_CONCURRENT_INVOCATIONS = 5\n\n/** Valid `dimensions` for `amazon.titan-embed-text-v2:0`. */\nconst TITAN_TEXT_DIMENSIONS: ReadonlyArray<number> = [256, 512, 1024]\n\n/** Valid `dimensions` (outputEmbeddingLength) for `amazon.titan-embed-image-v1`. */\nconst TITAN_IMAGE_DIMENSIONS: ReadonlyArray<number> = [256, 384, 1024]\nconst TITAN_IMAGE_DEFAULT_DIMENSIONS = 1024\n\n/** Cohere embed accepts at most 96 texts per InvokeModel call. */\nconst COHERE_MAX_BATCH_SIZE = 96\n\n/**\n * Bedrock Embedding Adapter\n *\n * Tree-shakeable adapter for embeddings served through Bedrock's native\n * `InvokeModel` API (embedding models have no Converse surface). Each model\n * family has its own JSON body dialect:\n *\n * - `amazon.titan-embed-text-v2:0` — text-only, ONE text per call; the batch\n * is fanned out with a small concurrency cap and per-call\n * `inputTextTokenCount`s are summed into usage.\n * - `amazon.titan-embed-image-v1` — MULTIMODAL: text, image, or a fused\n * text+image item embedded into a single vector; one item per call.\n * - `cohere.embed-english-v3` / `cohere.embed-multilingual-v3` — text-only,\n * batched natively (chunked at 96 texts per call). `inputType` is required.\n *\n * The SDK call lives behind a protected `invokeModel` seam so tests can\n * subclass and inject canned response bodies without a real AWS request, and\n * the AWS SDK itself is imported lazily (it's Node/server-only).\n */\nexport class BedrockEmbeddingAdapter<\n TModel extends BedrockEmbeddingModel,\n // Same rationale as the text adapters: the base parameterises\n // `TProviderOptions extends object`, and the per-model options interfaces\n // lack implicit index signatures — `Record<string, any>` (not `unknown`)\n // accepts them. Confined to the generic constraint; no value cast.\n TProviderOptions extends Record<string, any> =\n ResolveEmbeddingProviderOptions<TModel>,\n> extends BaseEmbeddingAdapter<\n TModel,\n TProviderOptions,\n BedrockEmbeddingModelProviderOptionsByName,\n BedrockEmbeddingModelInputModalitiesByName\n> {\n readonly name = 'bedrock' as const\n private clientPromise?: Promise<BedrockRuntimeClient>\n private readonly clientConfig: BedrockEmbeddingConfig\n\n constructor(config: BedrockEmbeddingConfig, model: TModel) {\n super(model, {})\n // Defer client construction and auth resolution: the AWS SDK is Node/\n // server-only, so we must not pull it into the static graph here. The\n // client (and its dynamic import) is built lazily on first SDK call.\n this.clientConfig = config\n }\n\n /**\n * Dynamically import `@aws-sdk/client-bedrock-runtime`. The specifier is\n * held in a variable (not a string literal) so bundler dep scanners cannot\n * statically discover the AWS SDK and try to pre-bundle it for the browser.\n * Same pattern as the Converse text adapter.\n */\n protected importBedrockRuntime(): Promise<typeof BedrockRuntime> {\n const mod = '@aws-sdk/client-bedrock-runtime'\n return import(/* @vite-ignore */ mod) as Promise<typeof BedrockRuntime>\n }\n\n /**\n * Lazily construct the `BedrockRuntimeClient`, deferring\n * `resolveBedrockAuth` until a real request is made.\n */\n protected async getClient(): Promise<BedrockRuntimeClient> {\n if (!this.clientPromise) {\n this.clientPromise = (async () => {\n const { BedrockRuntimeClient } = await this.importBedrockRuntime()\n const region = this.clientConfig.region ?? 'us-east-1'\n const resolved = resolveBedrockAuth(\n {\n apiKey: this.clientConfig.apiKey,\n region,\n auth: this.clientConfig.auth,\n },\n 'runtime',\n )\n return new BedrockRuntimeClient(\n this.buildClientConfig(resolved, region, this.clientConfig.baseURL),\n )\n })().catch((error: unknown) => {\n // Don't cache a rejected promise — clear it so a later call can retry\n // (e.g. after a transient import failure or fixed auth config).\n this.clientPromise = undefined\n throw error\n })\n }\n return this.clientPromise\n }\n\n /**\n * Map resolved auth + endpoint to a `BedrockRuntimeClientConfig`. Bearer\n * auth needs `authSchemePreference` pinned or the SDK still tries SigV4\n * first — same reasoning as the Converse text adapter.\n */\n protected buildClientConfig(\n resolved: ResolvedBedrockAuth,\n region: string,\n endpoint: string | undefined,\n ): BedrockRuntimeClientConfig {\n if (resolved.kind === 'bearer') {\n return {\n region,\n token: { token: resolved.token },\n authSchemePreference: ['httpBearerAuth'],\n ...(endpoint ? { endpoint } : {}),\n }\n }\n return {\n region: resolved.region,\n credentials: resolved.credentials,\n ...(endpoint ? { endpoint } : {}),\n }\n }\n\n // ---------------------------------------------------------------------------\n // SDK seam (overridden in tests so no real AWS call happens)\n // ---------------------------------------------------------------------------\n\n /** Send one InvokeModel call and parse its JSON response body. */\n protected async invokeModel(\n modelId: string,\n body: Record<string, unknown>,\n ): Promise<unknown> {\n const { InvokeModelCommand } = await this.importBedrockRuntime()\n const client = await this.getClient()\n const response = await client.send(\n new InvokeModelCommand({\n modelId,\n contentType: 'application/json',\n accept: 'application/json',\n body: JSON.stringify(body),\n }),\n )\n return JSON.parse(new TextDecoder().decode(response.body))\n }\n\n // ---------------------------------------------------------------------------\n // Public adapter surface\n // ---------------------------------------------------------------------------\n\n async createEmbeddings(\n options: EmbeddingOptions<TProviderOptions>,\n ): Promise<EmbeddingResult> {\n const { model, logger } = options\n try {\n logger.request(\n `activity=embed provider=${this.name} model=${model} inputs=${options.input.length}`,\n { provider: this.name, model },\n )\n switch (model) {\n case 'amazon.titan-embed-text-v2:0':\n return await this.embedTitanText(options)\n case 'amazon.titan-embed-image-v1':\n return await this.embedTitanImage(options)\n case 'cohere.embed-english-v3':\n case 'cohere.embed-multilingual-v3':\n return await this.embedCohere(options)\n default:\n throw new Error(\n `Unknown Bedrock embedding model \"${model}\". Supported models: ` +\n `${BEDROCK_EMBEDDING_MODELS.join(', ')}.`,\n )\n }\n } catch (error: unknown) {\n logger.errors(`${this.name}.createEmbeddings fatal`, {\n error: toRunErrorPayload(error, `${this.name}.createEmbeddings failed`),\n source: `${this.name}.createEmbeddings`,\n })\n throw error\n }\n }\n\n // ---------------------------------------------------------------------------\n // Per-model request mapping\n // ---------------------------------------------------------------------------\n\n /**\n * `amazon.titan-embed-text-v2:0` — one text per InvokeModel call, fanned\n * out with a concurrency cap; result order matches input order and per-call\n * `inputTextTokenCount`s are summed into usage.\n */\n private async embedTitanText(\n options: EmbeddingOptions<TProviderOptions>,\n ): Promise<EmbeddingResult> {\n const { model, dimensions } = options\n if (\n dimensions !== undefined &&\n !TITAN_TEXT_DIMENSIONS.includes(dimensions)\n ) {\n throw new Error(\n `${model} supports dimensions 256, 512, or 1024; got ${dimensions}`,\n )\n }\n const normalize: boolean | undefined = options.modelOptions?.normalize\n const texts = requireTextOnlyEmbeddingInput(options.input, this.name, model)\n\n const responses = await mapWithConcurrency(\n texts,\n MAX_CONCURRENT_INVOCATIONS,\n async (text) => {\n // Built incrementally: exactOptionalPropertyTypes is on, and Titan\n // rejects explicit nulls/undefined for absent optional fields.\n const body: Record<string, unknown> = { inputText: text }\n if (dimensions !== undefined) body.dimensions = dimensions\n if (normalize !== undefined) body.normalize = normalize\n return readTitanEmbeddingBody(\n await this.invokeModel(model, body),\n `${this.name} ${model}`,\n )\n },\n )\n\n return this.toTitanResult(model, responses)\n }\n\n /**\n * `amazon.titan-embed-image-v1` (Titan Multimodal) — one item per\n * InvokeModel call. An item may carry text, an image, or both (a fused\n * item embedded into a single vector). Titan accepts at most one image per\n * request and never fetches remote URLs.\n */\n private async embedTitanImage(\n options: EmbeddingOptions<TProviderOptions>,\n ): Promise<EmbeddingResult> {\n const { model, dimensions } = options\n const outputEmbeddingLength = dimensions ?? TITAN_IMAGE_DEFAULT_DIMENSIONS\n if (!TITAN_IMAGE_DIMENSIONS.includes(outputEmbeddingLength)) {\n throw new Error(\n `${model} supports dimensions 256, 384, or 1024; got ${outputEmbeddingLength}`,\n )\n }\n const items = resolveEmbeddingInput(options.input)\n\n const responses = await mapWithConcurrency(\n items,\n MAX_CONCURRENT_INVOCATIONS,\n async (item, index) => {\n if (item.images.length > 1) {\n throw new Error(\n `${model} accepts at most one image per input item; input item ` +\n `at index ${index} contains ${item.images.length} images. ` +\n `Pass them as separate input items (one vector each).`,\n )\n }\n const body: Record<string, unknown> = {\n embeddingConfig: { outputEmbeddingLength },\n }\n if (item.texts.length > 0) body.inputText = item.texts.join('\\n')\n const image = item.images[0]\n if (image) body.inputImage = toTitanInputImage(image, model)\n return readTitanEmbeddingBody(\n await this.invokeModel(model, body),\n `${this.name} ${model}`,\n )\n },\n )\n\n return this.toTitanResult(model, responses)\n }\n\n /**\n * `cohere.embed-*-v3` — natively batched (chunked at 96 texts per call,\n * order preserved across chunks). `inputType` is required by the Cohere\n * API; output dimensionality is fixed, so `dimensions` is rejected.\n */\n private async embedCohere(\n options: EmbeddingOptions<TProviderOptions>,\n ): Promise<EmbeddingResult> {\n const { model, dimensions } = options\n if (dimensions !== undefined) {\n throw new Error(\n `${model} does not support the dimensions option; its output size is fixed`,\n )\n }\n const inputType: string | undefined = options.modelOptions?.inputType\n if (inputType === undefined) {\n throw new Error(\n `${model} requires modelOptions.inputType ('search_document' | ` +\n `'search_query' | 'classification' | 'clustering')`,\n )\n }\n const truncate: string | undefined = options.modelOptions?.truncate\n const texts = requireTextOnlyEmbeddingInput(options.input, this.name, model)\n const batches = chunk(texts, COHERE_MAX_BATCH_SIZE)\n\n const responses = await mapWithConcurrency(\n batches,\n MAX_CONCURRENT_INVOCATIONS,\n async (batch) => {\n const body: Record<string, unknown> = {\n texts: batch,\n input_type: inputType,\n }\n if (truncate !== undefined) body.truncate = truncate\n return readCohereEmbeddingBody(\n await this.invokeModel(model, body),\n `${this.name} ${model}`,\n )\n },\n )\n\n return {\n id: this.generateId(),\n model,\n embeddings: responses.flat().map((vector, index) => ({ vector, index })),\n }\n }\n\n /** Assemble an EmbeddingResult from per-item Titan responses. */\n private toTitanResult(\n model: string,\n responses: Array<TitanEmbeddingBody>,\n ): EmbeddingResult {\n let promptTokens = 0\n const embeddings = responses.map((response, index) => {\n promptTokens += response.inputTextTokenCount\n return { vector: response.embedding, index }\n })\n const usage: TokenUsage = {\n promptTokens,\n completionTokens: 0,\n totalTokens: promptTokens,\n }\n return { id: this.generateId(), model, embeddings, usage }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Response-body narrowing (SDK JSON boundary)\n// ---------------------------------------------------------------------------\n\ninterface TitanEmbeddingBody {\n embedding: Array<number>\n /** 0 when the response omits it (e.g. image-only Titan Multimodal calls). */\n inputTextTokenCount: number\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n\n/** Narrow a Titan InvokeModel JSON body: `{ embedding, inputTextTokenCount? }`. */\nfunction readTitanEmbeddingBody(\n raw: unknown,\n context: string,\n): TitanEmbeddingBody {\n const embedding =\n isRecord(raw) && Array.isArray(raw.embedding) ? raw.embedding : undefined\n if (!embedding) {\n throw new Error(\n `${context}: response body is missing the \"embedding\" array`,\n )\n }\n const inputTextTokenCount =\n isRecord(raw) && typeof raw.inputTextTokenCount === 'number'\n ? raw.inputTextTokenCount\n : 0\n return { embedding, inputTextTokenCount }\n}\n\n/** Narrow a Cohere InvokeModel JSON body: `{ embeddings: number[][] }` (float). */\nfunction readCohereEmbeddingBody(\n raw: unknown,\n context: string,\n): Array<Array<number>> {\n const embeddings =\n isRecord(raw) && Array.isArray(raw.embeddings) ? raw.embeddings : undefined\n if (!embeddings) {\n throw new Error(\n `${context}: response body is missing the \"embeddings\" array`,\n )\n }\n return embeddings\n}\n\n// ---------------------------------------------------------------------------\n// Input mapping helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Map an ImagePart to Titan's `inputImage` (RAW base64, no data: prefix).\n * Accepts `data` sources as-is and `url` sources ONLY when the value is a\n * `data:` URI; Titan cannot fetch remote http(s) URLs.\n */\nfunction toTitanInputImage(image: ImagePart, model: string): string {\n const source = image.source\n if (source.type === 'data') {\n return source.value\n }\n if (source.value.startsWith('data:')) {\n const comma = source.value.indexOf(',')\n if (comma !== -1) {\n return source.value.slice(comma + 1)\n }\n }\n throw new Error(\n `Bedrock Titan does not fetch remote image URLs; pass base64 data ` +\n `(a { type: 'data' } source or a data: URI) for ${model}.`,\n )\n}\n\n/** Split into runs of at most `size`, preserving order. */\nfunction chunk<T>(items: Array<T>, size: number): Array<Array<T>> {\n const chunks: Array<Array<T>> = []\n for (let i = 0; i < items.length; i += size) {\n chunks.push(items.slice(i, i + size))\n }\n return chunks\n}\n\n/**\n * Map `fn` over `items` with at most `limit` calls in flight, returning\n * results in input order (result[i] corresponds to items[i] regardless of\n * completion order). Rejects with the first error.\n */\nasync function mapWithConcurrency<T, TResult>(\n items: ReadonlyArray<T>,\n limit: number,\n fn: (item: T, index: number) => Promise<TResult>,\n): Promise<Array<TResult>> {\n const results = new Array<TResult>(items.length)\n let next = 0\n const worker = async (): Promise<void> => {\n while (next < items.length) {\n const index = next++\n const item = items[index]\n if (item === undefined) continue // unreachable: index < length\n results[index] = await fn(item, index)\n }\n }\n const workerCount = Math.max(1, Math.min(limit, items.length))\n await Promise.all(Array.from({ length: workerCount }, () => worker()))\n return results\n}\n\n// ---------------------------------------------------------------------------\n// Factories\n// ---------------------------------------------------------------------------\n\n/**\n * Creates a Bedrock embedding adapter with an explicit API key (bearer).\n * Type resolution happens here at the call site.\n *\n * @param model - The model name (e.g., 'amazon.titan-embed-text-v2:0')\n * @param apiKey - Your Bedrock API key\n * @param config - Optional additional configuration (region, baseURL, ...)\n * @returns Configured Bedrock embedding adapter instance with resolved types\n *\n * @example\n * ```typescript\n * const adapter = createBedrockEmbedding(\n * 'amazon.titan-embed-text-v2:0',\n * 'bedrock-api-key',\n * );\n *\n * const result = await embed({\n * adapter,\n * input: 'a red guitar',\n * });\n * ```\n */\nexport function createBedrockEmbedding<TModel extends BedrockEmbeddingModel>(\n model: TModel,\n apiKey: string,\n config?: Omit<BedrockEmbeddingConfig, 'apiKey'>,\n): BedrockEmbeddingAdapter<TModel> {\n // Explicit apiKey is authoritative — spread config first so it can't override.\n return new BedrockEmbeddingAdapter({ ...config, apiKey }, model)\n}\n\n/**\n * Creates a Bedrock embedding adapter using the ambient auth cascade:\n * `config.apiKey` → `BEDROCK_API_KEY` → `AWS_BEARER_TOKEN_BEDROCK` → SigV4\n * (AWS credential provider chain). Auth resolves lazily on the first\n * request, so `auth: 'sigv4'` never requires an API key.\n *\n * @param model - The model name (e.g., 'cohere.embed-english-v3')\n * @param config - Optional configuration (region, auth, baseURL, ...)\n * @returns Configured Bedrock embedding adapter instance with resolved types\n *\n * @example\n * ```typescript\n * const adapter = bedrockEmbedding('cohere.embed-english-v3');\n *\n * const result = await embed({\n * adapter,\n * input: ['a red guitar', 'a blue drum kit'],\n * modelOptions: { inputType: 'search_document' },\n * });\n *\n * console.log(result.embeddings[0].vector)\n * ```\n */\nexport function bedrockEmbedding<TModel extends BedrockEmbeddingModel>(\n model: TModel,\n config?: BedrockEmbeddingConfig,\n): BedrockEmbeddingAdapter<TModel> {\n return new BedrockEmbeddingAdapter(config ?? {}, model)\n}\n"],"mappings":";;;;;;;AAuCA,IAAM,6BAA6B;;AAGnC,IAAM,wBAA+C;CAAC;CAAK;CAAK;AAAI;;AAGpE,IAAM,yBAAgD;CAAC;CAAK;CAAK;AAAI;AACrE,IAAM,iCAAiC;;AAGvC,IAAM,wBAAwB;;;;;;;;;;;;;;;;;;;;AAqB9B,IAAa,0BAAb,cAQU,qBAKR;CACA,OAAgB;CAChB;CACA;CAEA,YAAY,QAAgC,OAAe;EACzD,MAAM,OAAO,CAAC,CAAC;EAIf,KAAK,eAAe;CACtB;;;;;;;CAQA,uBAAiE;EAE/D,OAAO;;GAA0B;;CACnC;;;;;CAMA,MAAgB,YAA2C;EACzD,IAAI,CAAC,KAAK,eACR,KAAK,iBAAiB,YAAY;GAChC,MAAM,EAAE,yBAAyB,MAAM,KAAK,qBAAqB;GACjE,MAAM,SAAS,KAAK,aAAa,UAAU;GAC3C,MAAM,WAAW,mBACf;IACE,QAAQ,KAAK,aAAa;IAC1B;IACA,MAAM,KAAK,aAAa;GAC1B,GACA,SACF;GACA,OAAO,IAAI,qBACT,KAAK,kBAAkB,UAAU,QAAQ,KAAK,aAAa,OAAO,CACpE;EACF,EAAA,CAAG,CAAC,CAAC,OAAO,UAAmB;GAG7B,KAAK,gBAAgB,KAAA;GACrB,MAAM;EACR,CAAC;EAEH,OAAO,KAAK;CACd;;;;;;CAOA,kBACE,UACA,QACA,UAC4B;EAC5B,IAAI,SAAS,SAAS,UACpB,OAAO;GACL;GACA,OAAO,EAAE,OAAO,SAAS,MAAM;GAC/B,sBAAsB,CAAC,gBAAgB;GACvC,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;EACjC;EAEF,OAAO;GACL,QAAQ,SAAS;GACjB,aAAa,SAAS;GACtB,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;EACjC;CAC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
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Provider options for the Bedrock embedding models.
3
+ *
4
+ * `dimensions` is deliberately absent from every options shape: it's a
5
+ * first-class top-level option on `embed()`. The adapter maps it onto each
6
+ * model's native field (Titan Text `dimensions`, Titan Multimodal
7
+ * `embeddingConfig.outputEmbeddingLength`) and rejects it for the Cohere
8
+ * models, whose output size is fixed.
9
+ */
10
+ /** Options for `amazon.titan-embed-text-v2:0`. */
11
+ export interface BedrockTitanTextEmbeddingProviderOptions {
12
+ /**
13
+ * Normalize the output embedding to unit length. Titan's service-side
14
+ * default is `true`; leave unset to use it.
15
+ */
16
+ normalize?: boolean;
17
+ }
18
+ /**
19
+ * Options for `amazon.titan-embed-image-v1` (Titan Multimodal Embeddings).
20
+ * The model has no per-request options beyond the top-level `dimensions`
21
+ * (mapped onto `embeddingConfig.outputEmbeddingLength`).
22
+ */
23
+ export type BedrockTitanImageEmbeddingProviderOptions = Record<string, never>;
24
+ /**
25
+ * Cohere embed input types. Cohere REQUIRES the caller to say what the
26
+ * embeddings are for; there is no service-side default.
27
+ */
28
+ export type BedrockCohereEmbeddingInputType = 'search_document' | 'search_query' | 'classification' | 'clustering';
29
+ /** Options for `cohere.embed-english-v3` / `cohere.embed-multilingual-v3`. */
30
+ export interface BedrockCohereEmbeddingProviderOptions {
31
+ /**
32
+ * What the embeddings will be used for (required by the Cohere API; sent
33
+ * as `input_type`). Use `search_document` when indexing, `search_query`
34
+ * when querying, `classification` / `clustering` for those downstream
35
+ * tasks. Because this field is required, `modelOptions` is required at the
36
+ * `embed()` call site for the Cohere models.
37
+ */
38
+ inputType: BedrockCohereEmbeddingInputType;
39
+ /**
40
+ * How to handle inputs longer than the model's maximum token length.
41
+ * `NONE` (the API default) returns an error, `START` / `END` truncate
42
+ * from that side.
43
+ */
44
+ truncate?: 'NONE' | 'START' | 'END';
45
+ }
46
+ /**
47
+ * Broad union used as the adapter's base `TProviderOptions` fallback when
48
+ * the model isn't statically known. Per-model narrowing happens via
49
+ * `BedrockEmbeddingModelProviderOptionsByName`.
50
+ */
51
+ export type BedrockEmbeddingProviderOptions = BedrockTitanTextEmbeddingProviderOptions | BedrockTitanImageEmbeddingProviderOptions | BedrockCohereEmbeddingProviderOptions;
@@ -23,7 +23,9 @@ export declare function bedrockText<TModel extends BedrockResponsesModels>(model
23
23
  export { BedrockTextAdapter, createBedrockChat, type BedrockTextConfig, type BedrockTextProviderOptions, } from './adapters/text.js';
24
24
  export { BedrockResponsesTextAdapter, createBedrockResponsesText, type BedrockResponsesConfig, type BedrockResponsesProviderOptions, } from './adapters/responses-text.js';
25
25
  export { BedrockConverseTextAdapter, createBedrockConverse, type BedrockConverseConfig, } from './adapters/converse-text.js';
26
+ export { BedrockEmbeddingAdapter, bedrockEmbedding, createBedrockEmbedding, type BedrockEmbeddingConfig, } from './adapters/embedding.js';
27
+ export type { BedrockCohereEmbeddingInputType, BedrockCohereEmbeddingProviderOptions, BedrockEmbeddingProviderOptions, BedrockTitanImageEmbeddingProviderOptions, BedrockTitanTextEmbeddingProviderOptions, } from './embedding/embedding-provider-options.js';
26
28
  export type { BedrockConverseProviderOptions } from './converse/provider-options.js';
27
29
  export { resolveBedrockAuth, withBedrockDefaults, type BedrockClientConfig, type BedrockEndpoint, type ResolvedBedrockAuth, } from './utils/client.js';
28
- export { BEDROCK_CHAT_MODELS, BEDROCK_RESPONSES_MODELS, BEDROCK_CONVERSE_MODELS, type BedrockChatModels, type BedrockResponsesModels, type BedrockConverseModels, type BedrockChatModelProviderOptionsByName, type BedrockChatModelToolCapabilitiesByName, type BedrockModelInputModalitiesByName, } from './model-meta.js';
30
+ export { BEDROCK_CHAT_MODELS, BEDROCK_RESPONSES_MODELS, BEDROCK_CONVERSE_MODELS, BEDROCK_EMBEDDING_MODELS, type BedrockEmbeddingModel, type BedrockEmbeddingModelProviderOptionsByName, type BedrockEmbeddingModelInputModalitiesByName, type BedrockChatModels, type BedrockResponsesModels, type BedrockConverseModels, type BedrockChatModelProviderOptionsByName, type BedrockChatModelToolCapabilitiesByName, type BedrockModelInputModalitiesByName, } from './model-meta.js';
29
31
  export type { BedrockMessageMetadataByModality, BedrockTextMetadata, BedrockImageMetadata, BedrockAudioMetadata, BedrockVideoMetadata, BedrockDocumentMetadata, } from './message-types.js';
package/dist/esm/index.js CHANGED
@@ -3,7 +3,8 @@ import { withBedrockDefaults } from "./utils/client.js";
3
3
  import { BedrockTextAdapter, createBedrockChat } from "./adapters/text.js";
4
4
  import { BedrockResponsesTextAdapter, createBedrockResponsesText } from "./adapters/responses-text.js";
5
5
  import { BedrockConverseTextAdapter, createBedrockConverse } from "./adapters/converse-text.js";
6
- import { BEDROCK_CHAT_MODELS, BEDROCK_CONVERSE_MODELS, BEDROCK_RESPONSES_MODELS } from "./model-meta.js";
6
+ import { BEDROCK_CHAT_MODELS, BEDROCK_CONVERSE_MODELS, BEDROCK_EMBEDDING_MODELS, BEDROCK_RESPONSES_MODELS } from "./model-meta.js";
7
+ import { BedrockEmbeddingAdapter, bedrockEmbedding, createBedrockEmbedding } from "./adapters/embedding.js";
7
8
  //#region src/index.ts
8
9
  /**
9
10
  * @module @tanstack/ai-bedrock
@@ -56,6 +57,6 @@ function bedrockText(model, config) {
56
57
  return build(model, config);
57
58
  }
58
59
  //#endregion
59
- export { BEDROCK_CHAT_MODELS, BEDROCK_CONVERSE_MODELS, BEDROCK_RESPONSES_MODELS, BedrockConverseTextAdapter, BedrockResponsesTextAdapter, BedrockTextAdapter, bedrockText, createBedrockChat, createBedrockConverse, createBedrockResponsesText, createBedrockText, resolveBedrockAuth, withBedrockDefaults };
60
+ export { BEDROCK_CHAT_MODELS, BEDROCK_CONVERSE_MODELS, BEDROCK_EMBEDDING_MODELS, BEDROCK_RESPONSES_MODELS, BedrockConverseTextAdapter, BedrockEmbeddingAdapter, BedrockResponsesTextAdapter, BedrockTextAdapter, bedrockEmbedding, bedrockText, createBedrockChat, createBedrockConverse, createBedrockEmbedding, createBedrockResponsesText, createBedrockText, resolveBedrockAuth, withBedrockDefaults };
60
61
 
61
62
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/index.ts"],"sourcesContent":["/**\n * @module @tanstack/ai-bedrock\n *\n * Amazon Bedrock adapter for TanStack AI via Bedrock's OpenAI-compatible APIs\n * and the native Converse API. The public `bedrockText` / `createBedrockText`\n * factory branches between the Converse adapter (DEFAULT), the Chat Completions\n * adapter (`api: 'chat'`), and the Responses adapter (`api: 'responses'`).\n */\nimport { BedrockTextAdapter } from './adapters/text'\nimport { BedrockResponsesTextAdapter } from './adapters/responses-text'\nimport { BedrockConverseTextAdapter } from './adapters/converse-text'\nimport { BEDROCK_CHAT_MODELS, BEDROCK_RESPONSES_MODELS } from './model-meta'\nimport type { BedrockTextConfig } from './adapters/text'\nimport type { BedrockResponsesConfig } from './adapters/responses-text'\nimport type { BedrockConverseConfig } from './adapters/converse-text'\nimport type { BedrockClientConfig } from './utils/client'\nimport type {\n BedrockChatModels,\n BedrockConverseModels,\n BedrockResponsesModels,\n} from './model-meta'\n\n/** Config for the branching factory's converse mode (default, or api: 'converse'). */\nexport type BedrockConverseApiConfig = BedrockConverseConfig & {\n api?: 'converse'\n}\n/** Config for the branching factory's chat mode (api: 'chat' required). */\nexport type BedrockChatApiConfig = BedrockTextConfig & {\n api: 'chat'\n}\n/** Config for the branching factory's responses mode (api: 'responses' required). */\nexport type BedrockResponsesApiConfig = BedrockResponsesConfig & {\n api: 'responses'\n}\n\ntype AnyBedrockAdapter =\n | BedrockConverseTextAdapter<BedrockConverseModels>\n | BedrockTextAdapter<BedrockChatModels>\n | BedrockResponsesTextAdapter<BedrockResponsesModels>\n\n/** Cast-free runtime guard: is this model in the Responses-capable subset? */\nfunction isResponsesModel(model: string): model is BedrockResponsesModels {\n return BEDROCK_RESPONSES_MODELS.some((m) => m === model)\n}\n\n/** Cast-free runtime guard: is this model in the Chat-capable subset? */\nfunction isChatModel(model: string): model is BedrockChatModels {\n return BEDROCK_CHAT_MODELS.some((m) => m === model)\n}\n\n/** Strip the `api` discriminator from a config without an unused-var lint error. */\nfunction stripApi<T extends { api?: unknown }>(config: T): Omit<T, 'api'> {\n const { api, ...rest } = config\n void api\n return rest\n}\n\n/**\n * Shared branching used by both public factories. Constructs the adapter\n * classes directly so their constructors run the full auth cascade lazily\n * (config.apiKey → BEDROCK_API_KEY → AWS_BEARER_TOKEN_BEDROCK → SigV4). No\n * eager env-key fetch here, so `auth: 'sigv4'` never throws for a missing key.\n *\n * Default path → Converse adapter; opt-in via `api: 'chat'` or `api: 'responses'`.\n */\nfunction build(\n model: BedrockConverseModels,\n config?: BedrockClientConfig & { api?: 'converse' | 'chat' | 'responses' },\n): AnyBedrockAdapter {\n if (config?.api === 'responses') {\n const rest = stripApi(config)\n if (!isResponsesModel(model)) {\n throw new Error(\n `Model \"${model}\" is not available on the Bedrock Responses API. ` +\n `Responses-capable models: ${BEDROCK_RESPONSES_MODELS.join(', ')}.`,\n )\n }\n return new BedrockResponsesTextAdapter(rest, model)\n }\n if (config?.api === 'chat') {\n if (!isChatModel(model)) {\n throw new Error(\n `Model \"${model}\" is not available on the Bedrock Chat Completions API. ` +\n `Chat-capable models: ${BEDROCK_CHAT_MODELS.join(', ')}.`,\n )\n }\n return new BedrockTextAdapter(stripApi(config), model)\n }\n // Default + explicit 'converse'\n return new BedrockConverseTextAdapter(config ? stripApi(config) : {}, model)\n}\n\n// --- createBedrockText: explicit key, overloaded on `api` ---\nexport function createBedrockText<TModel extends BedrockConverseModels>(\n model: TModel,\n apiKey: string,\n config?: BedrockConverseApiConfig,\n): BedrockConverseTextAdapter<TModel>\nexport function createBedrockText<TModel extends BedrockChatModels>(\n model: TModel,\n apiKey: string,\n config: BedrockChatApiConfig,\n): BedrockTextAdapter<TModel>\nexport function createBedrockText<TModel extends BedrockResponsesModels>(\n model: TModel,\n apiKey: string,\n config: BedrockResponsesApiConfig,\n): BedrockResponsesTextAdapter<TModel>\nexport function createBedrockText(\n model: BedrockConverseModels,\n apiKey: string,\n config?:\n | BedrockConverseApiConfig\n | BedrockChatApiConfig\n | BedrockResponsesApiConfig,\n): AnyBedrockAdapter {\n // Explicit apiKey is authoritative — spread config first so it can't override.\n return build(model, { ...config, apiKey })\n}\n\n// --- bedrockText: env-key counterpart, same overloads ---\nexport function bedrockText<TModel extends BedrockConverseModels>(\n model: TModel,\n config?: BedrockConverseApiConfig,\n): BedrockConverseTextAdapter<TModel>\nexport function bedrockText<TModel extends BedrockChatModels>(\n model: TModel,\n config: BedrockChatApiConfig,\n): BedrockTextAdapter<TModel>\nexport function bedrockText<TModel extends BedrockResponsesModels>(\n model: TModel,\n config: BedrockResponsesApiConfig,\n): BedrockResponsesTextAdapter<TModel>\nexport function bedrockText(\n model: BedrockConverseModels,\n config?:\n | BedrockConverseApiConfig\n | BedrockChatApiConfig\n | BedrockResponsesApiConfig,\n): AnyBedrockAdapter {\n // No eager env-key fetch: the adapter constructor resolves auth lazily so\n // SigV4 (and the env-key fallback) work without a forced API key here.\n return build(model, config)\n}\n\n// --- Re-exports ---\nexport {\n BedrockTextAdapter,\n createBedrockChat,\n type BedrockTextConfig,\n type BedrockTextProviderOptions,\n} from './adapters/text'\nexport {\n BedrockResponsesTextAdapter,\n createBedrockResponsesText,\n type BedrockResponsesConfig,\n type BedrockResponsesProviderOptions,\n} from './adapters/responses-text'\nexport {\n BedrockConverseTextAdapter,\n createBedrockConverse,\n type BedrockConverseConfig,\n} from './adapters/converse-text'\nexport type { BedrockConverseProviderOptions } from './converse/provider-options'\nexport {\n resolveBedrockAuth,\n withBedrockDefaults,\n type BedrockClientConfig,\n type BedrockEndpoint,\n type ResolvedBedrockAuth,\n} from './utils/client'\nexport {\n BEDROCK_CHAT_MODELS,\n BEDROCK_RESPONSES_MODELS,\n BEDROCK_CONVERSE_MODELS,\n type BedrockChatModels,\n type BedrockResponsesModels,\n type BedrockConverseModels,\n type BedrockChatModelProviderOptionsByName,\n type BedrockChatModelToolCapabilitiesByName,\n type BedrockModelInputModalitiesByName,\n} from './model-meta'\nexport type {\n BedrockMessageMetadataByModality,\n BedrockTextMetadata,\n BedrockImageMetadata,\n BedrockAudioMetadata,\n BedrockVideoMetadata,\n BedrockDocumentMetadata,\n} from './message-types'\n"],"mappings":";;;;;;;;;;;;;;;;AAyCA,SAAS,iBAAiB,OAAgD;CACxE,OAAO,yBAAyB,MAAM,MAAM,MAAM,KAAK;AACzD;;AAGA,SAAS,YAAY,OAA2C;CAC9D,OAAO,oBAAoB,MAAM,MAAM,MAAM,KAAK;AACpD;;AAGA,SAAS,SAAsC,QAA2B;CACxE,MAAM,EAAE,KAAK,GAAG,SAAS;CAEzB,OAAO;AACT;;;;;;;;;AAUA,SAAS,MACP,OACA,QACmB;CACnB,IAAI,QAAQ,QAAQ,aAAa;EAC/B,MAAM,OAAO,SAAS,MAAM;EAC5B,IAAI,CAAC,iBAAiB,KAAK,GACzB,MAAM,IAAI,MACR,UAAU,MAAM,6EACe,yBAAyB,KAAK,IAAI,EAAE,EACrE;EAEF,OAAO,IAAI,4BAA4B,MAAM,KAAK;CACpD;CACA,IAAI,QAAQ,QAAQ,QAAQ;EAC1B,IAAI,CAAC,YAAY,KAAK,GACpB,MAAM,IAAI,MACR,UAAU,MAAM,+EACU,oBAAoB,KAAK,IAAI,EAAE,EAC3D;EAEF,OAAO,IAAI,mBAAmB,SAAS,MAAM,GAAG,KAAK;CACvD;CAEA,OAAO,IAAI,2BAA2B,SAAS,SAAS,MAAM,IAAI,CAAC,GAAG,KAAK;AAC7E;AAkBA,SAAgB,kBACd,OACA,QACA,QAImB;CAEnB,OAAO,MAAM,OAAO;EAAE,GAAG;EAAQ;CAAO,CAAC;AAC3C;AAeA,SAAgB,YACd,OACA,QAImB;CAGnB,OAAO,MAAM,OAAO,MAAM;AAC5B"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/index.ts"],"sourcesContent":["/**\n * @module @tanstack/ai-bedrock\n *\n * Amazon Bedrock adapter for TanStack AI via Bedrock's OpenAI-compatible APIs\n * and the native Converse API. The public `bedrockText` / `createBedrockText`\n * factory branches between the Converse adapter (DEFAULT), the Chat Completions\n * adapter (`api: 'chat'`), and the Responses adapter (`api: 'responses'`).\n */\nimport { BedrockTextAdapter } from './adapters/text'\nimport { BedrockResponsesTextAdapter } from './adapters/responses-text'\nimport { BedrockConverseTextAdapter } from './adapters/converse-text'\nimport { BEDROCK_CHAT_MODELS, BEDROCK_RESPONSES_MODELS } from './model-meta'\nimport type { BedrockTextConfig } from './adapters/text'\nimport type { BedrockResponsesConfig } from './adapters/responses-text'\nimport type { BedrockConverseConfig } from './adapters/converse-text'\nimport type { BedrockClientConfig } from './utils/client'\nimport type {\n BedrockChatModels,\n BedrockConverseModels,\n BedrockResponsesModels,\n} from './model-meta'\n\n/** Config for the branching factory's converse mode (default, or api: 'converse'). */\nexport type BedrockConverseApiConfig = BedrockConverseConfig & {\n api?: 'converse'\n}\n/** Config for the branching factory's chat mode (api: 'chat' required). */\nexport type BedrockChatApiConfig = BedrockTextConfig & {\n api: 'chat'\n}\n/** Config for the branching factory's responses mode (api: 'responses' required). */\nexport type BedrockResponsesApiConfig = BedrockResponsesConfig & {\n api: 'responses'\n}\n\ntype AnyBedrockAdapter =\n | BedrockConverseTextAdapter<BedrockConverseModels>\n | BedrockTextAdapter<BedrockChatModels>\n | BedrockResponsesTextAdapter<BedrockResponsesModels>\n\n/** Cast-free runtime guard: is this model in the Responses-capable subset? */\nfunction isResponsesModel(model: string): model is BedrockResponsesModels {\n return BEDROCK_RESPONSES_MODELS.some((m) => m === model)\n}\n\n/** Cast-free runtime guard: is this model in the Chat-capable subset? */\nfunction isChatModel(model: string): model is BedrockChatModels {\n return BEDROCK_CHAT_MODELS.some((m) => m === model)\n}\n\n/** Strip the `api` discriminator from a config without an unused-var lint error. */\nfunction stripApi<T extends { api?: unknown }>(config: T): Omit<T, 'api'> {\n const { api, ...rest } = config\n void api\n return rest\n}\n\n/**\n * Shared branching used by both public factories. Constructs the adapter\n * classes directly so their constructors run the full auth cascade lazily\n * (config.apiKey → BEDROCK_API_KEY → AWS_BEARER_TOKEN_BEDROCK → SigV4). No\n * eager env-key fetch here, so `auth: 'sigv4'` never throws for a missing key.\n *\n * Default path → Converse adapter; opt-in via `api: 'chat'` or `api: 'responses'`.\n */\nfunction build(\n model: BedrockConverseModels,\n config?: BedrockClientConfig & { api?: 'converse' | 'chat' | 'responses' },\n): AnyBedrockAdapter {\n if (config?.api === 'responses') {\n const rest = stripApi(config)\n if (!isResponsesModel(model)) {\n throw new Error(\n `Model \"${model}\" is not available on the Bedrock Responses API. ` +\n `Responses-capable models: ${BEDROCK_RESPONSES_MODELS.join(', ')}.`,\n )\n }\n return new BedrockResponsesTextAdapter(rest, model)\n }\n if (config?.api === 'chat') {\n if (!isChatModel(model)) {\n throw new Error(\n `Model \"${model}\" is not available on the Bedrock Chat Completions API. ` +\n `Chat-capable models: ${BEDROCK_CHAT_MODELS.join(', ')}.`,\n )\n }\n return new BedrockTextAdapter(stripApi(config), model)\n }\n // Default + explicit 'converse'\n return new BedrockConverseTextAdapter(config ? stripApi(config) : {}, model)\n}\n\n// --- createBedrockText: explicit key, overloaded on `api` ---\nexport function createBedrockText<TModel extends BedrockConverseModels>(\n model: TModel,\n apiKey: string,\n config?: BedrockConverseApiConfig,\n): BedrockConverseTextAdapter<TModel>\nexport function createBedrockText<TModel extends BedrockChatModels>(\n model: TModel,\n apiKey: string,\n config: BedrockChatApiConfig,\n): BedrockTextAdapter<TModel>\nexport function createBedrockText<TModel extends BedrockResponsesModels>(\n model: TModel,\n apiKey: string,\n config: BedrockResponsesApiConfig,\n): BedrockResponsesTextAdapter<TModel>\nexport function createBedrockText(\n model: BedrockConverseModels,\n apiKey: string,\n config?:\n | BedrockConverseApiConfig\n | BedrockChatApiConfig\n | BedrockResponsesApiConfig,\n): AnyBedrockAdapter {\n // Explicit apiKey is authoritative — spread config first so it can't override.\n return build(model, { ...config, apiKey })\n}\n\n// --- bedrockText: env-key counterpart, same overloads ---\nexport function bedrockText<TModel extends BedrockConverseModels>(\n model: TModel,\n config?: BedrockConverseApiConfig,\n): BedrockConverseTextAdapter<TModel>\nexport function bedrockText<TModel extends BedrockChatModels>(\n model: TModel,\n config: BedrockChatApiConfig,\n): BedrockTextAdapter<TModel>\nexport function bedrockText<TModel extends BedrockResponsesModels>(\n model: TModel,\n config: BedrockResponsesApiConfig,\n): BedrockResponsesTextAdapter<TModel>\nexport function bedrockText(\n model: BedrockConverseModels,\n config?:\n | BedrockConverseApiConfig\n | BedrockChatApiConfig\n | BedrockResponsesApiConfig,\n): AnyBedrockAdapter {\n // No eager env-key fetch: the adapter constructor resolves auth lazily so\n // SigV4 (and the env-key fallback) work without a forced API key here.\n return build(model, config)\n}\n\n// --- Re-exports ---\nexport {\n BedrockTextAdapter,\n createBedrockChat,\n type BedrockTextConfig,\n type BedrockTextProviderOptions,\n} from './adapters/text'\nexport {\n BedrockResponsesTextAdapter,\n createBedrockResponsesText,\n type BedrockResponsesConfig,\n type BedrockResponsesProviderOptions,\n} from './adapters/responses-text'\nexport {\n BedrockConverseTextAdapter,\n createBedrockConverse,\n type BedrockConverseConfig,\n} from './adapters/converse-text'\nexport {\n BedrockEmbeddingAdapter,\n bedrockEmbedding,\n createBedrockEmbedding,\n type BedrockEmbeddingConfig,\n} from './adapters/embedding'\nexport type {\n BedrockCohereEmbeddingInputType,\n BedrockCohereEmbeddingProviderOptions,\n BedrockEmbeddingProviderOptions,\n BedrockTitanImageEmbeddingProviderOptions,\n BedrockTitanTextEmbeddingProviderOptions,\n} from './embedding/embedding-provider-options'\nexport type { BedrockConverseProviderOptions } from './converse/provider-options'\nexport {\n resolveBedrockAuth,\n withBedrockDefaults,\n type BedrockClientConfig,\n type BedrockEndpoint,\n type ResolvedBedrockAuth,\n} from './utils/client'\nexport {\n BEDROCK_CHAT_MODELS,\n BEDROCK_RESPONSES_MODELS,\n BEDROCK_CONVERSE_MODELS,\n BEDROCK_EMBEDDING_MODELS,\n type BedrockEmbeddingModel,\n type BedrockEmbeddingModelProviderOptionsByName,\n type BedrockEmbeddingModelInputModalitiesByName,\n type BedrockChatModels,\n type BedrockResponsesModels,\n type BedrockConverseModels,\n type BedrockChatModelProviderOptionsByName,\n type BedrockChatModelToolCapabilitiesByName,\n type BedrockModelInputModalitiesByName,\n} from './model-meta'\nexport type {\n BedrockMessageMetadataByModality,\n BedrockTextMetadata,\n BedrockImageMetadata,\n BedrockAudioMetadata,\n BedrockVideoMetadata,\n BedrockDocumentMetadata,\n} from './message-types'\n"],"mappings":";;;;;;;;;;;;;;;;;AAyCA,SAAS,iBAAiB,OAAgD;CACxE,OAAO,yBAAyB,MAAM,MAAM,MAAM,KAAK;AACzD;;AAGA,SAAS,YAAY,OAA2C;CAC9D,OAAO,oBAAoB,MAAM,MAAM,MAAM,KAAK;AACpD;;AAGA,SAAS,SAAsC,QAA2B;CACxE,MAAM,EAAE,KAAK,GAAG,SAAS;CAEzB,OAAO;AACT;;;;;;;;;AAUA,SAAS,MACP,OACA,QACmB;CACnB,IAAI,QAAQ,QAAQ,aAAa;EAC/B,MAAM,OAAO,SAAS,MAAM;EAC5B,IAAI,CAAC,iBAAiB,KAAK,GACzB,MAAM,IAAI,MACR,UAAU,MAAM,6EACe,yBAAyB,KAAK,IAAI,EAAE,EACrE;EAEF,OAAO,IAAI,4BAA4B,MAAM,KAAK;CACpD;CACA,IAAI,QAAQ,QAAQ,QAAQ;EAC1B,IAAI,CAAC,YAAY,KAAK,GACpB,MAAM,IAAI,MACR,UAAU,MAAM,+EACU,oBAAoB,KAAK,IAAI,EAAE,EAC3D;EAEF,OAAO,IAAI,mBAAmB,SAAS,MAAM,GAAG,KAAK;CACvD;CAEA,OAAO,IAAI,2BAA2B,SAAS,SAAS,MAAM,IAAI,CAAC,GAAG,KAAK;AAC7E;AAkBA,SAAgB,kBACd,OACA,QACA,QAImB;CAEnB,OAAO,MAAM,OAAO;EAAE,GAAG;EAAQ;CAAO,CAAC;AAC3C;AAeA,SAAgB,YACd,OACA,QAImB;CAGnB,OAAO,MAAM,OAAO,MAAM;AAC5B"}
@@ -1,6 +1,7 @@
1
1
  import { GENERATED_BEDROCK_MODELS } from './model-catalog.generated.js';
2
2
  import { BedrockTextProviderOptions } from './text/text-provider-options.js';
3
3
  import { BedrockConverseProviderOptions } from './converse/provider-options.js';
4
+ import { BedrockCohereEmbeddingProviderOptions, BedrockEmbeddingProviderOptions, BedrockTitanImageEmbeddingProviderOptions, BedrockTitanTextEmbeddingProviderOptions } from './embedding/embedding-provider-options.js';
4
5
  type Entry = (typeof GENERATED_BEDROCK_MODELS)[number];
5
6
  /**
6
7
  * Type-level per-API filter over the generated catalog. Because the catalog is
@@ -35,4 +36,34 @@ export type BedrockChatModelToolCapabilitiesByName = {
35
36
  export type ResolveProviderOptions<TModel extends string> = TModel extends keyof BedrockChatModelProviderOptionsByName ? BedrockChatModelProviderOptionsByName[TModel] : BedrockTextProviderOptions;
36
37
  export type ResolveConverseProviderOptions<TModel extends string> = TModel extends keyof BedrockConverseModelProviderOptionsByName ? BedrockConverseModelProviderOptionsByName[TModel] : BedrockConverseProviderOptions;
37
38
  export type ResolveInputModalities<TModel extends string> = TModel extends keyof BedrockModelInputModalitiesByName ? BedrockModelInputModalitiesByName[TModel] : readonly ['text'];
39
+ /**
40
+ * Embedding models reachable through Bedrock's `InvokeModel` API. These are
41
+ * not part of the generated Converse catalog (embedding models have no
42
+ * conversational surface), so they're maintained by hand here.
43
+ */
44
+ export declare const BEDROCK_EMBEDDING_MODELS: readonly ["amazon.titan-embed-text-v2:0", "amazon.titan-embed-image-v1", "cohere.embed-english-v3", "cohere.embed-multilingual-v3"];
45
+ export type BedrockEmbeddingModel = (typeof BEDROCK_EMBEDDING_MODELS)[number];
46
+ /**
47
+ * Type-only map from embedding model name to its provider options type.
48
+ * The Cohere models make `modelOptions` REQUIRED at the `embed()` call site
49
+ * because `inputType` is a required field.
50
+ */
51
+ export type BedrockEmbeddingModelProviderOptionsByName = {
52
+ 'amazon.titan-embed-text-v2:0': BedrockTitanTextEmbeddingProviderOptions;
53
+ 'amazon.titan-embed-image-v1': BedrockTitanImageEmbeddingProviderOptions;
54
+ 'cohere.embed-english-v3': BedrockCohereEmbeddingProviderOptions;
55
+ 'cohere.embed-multilingual-v3': BedrockCohereEmbeddingProviderOptions;
56
+ };
57
+ /**
58
+ * Per-model input modalities for embedding models. Titan Multimodal accepts
59
+ * text and/or images (including fused text+image items embedded into one
60
+ * vector); the rest are text-only, so image inputs fail at compile time.
61
+ */
62
+ export type BedrockEmbeddingModelInputModalitiesByName = {
63
+ 'amazon.titan-embed-text-v2:0': readonly ['text'];
64
+ 'amazon.titan-embed-image-v1': readonly ['text', 'image'];
65
+ 'cohere.embed-english-v3': readonly ['text'];
66
+ 'cohere.embed-multilingual-v3': readonly ['text'];
67
+ };
68
+ export type ResolveEmbeddingProviderOptions<TModel extends string> = TModel extends keyof BedrockEmbeddingModelProviderOptionsByName ? BedrockEmbeddingModelProviderOptionsByName[TModel] : BedrockEmbeddingProviderOptions;
38
69
  export {};
@@ -4,7 +4,18 @@ import { GENERATED_BEDROCK_MODELS } from "./model-catalog.generated.js";
4
4
  var BEDROCK_CONVERSE_MODELS = GENERATED_BEDROCK_MODELS.map((m) => m.id);
5
5
  var BEDROCK_CHAT_MODELS = GENERATED_BEDROCK_MODELS.filter((m) => m.apis.chat).map((m) => m.id);
6
6
  var BEDROCK_RESPONSES_MODELS = GENERATED_BEDROCK_MODELS.filter((m) => m.apis.responses).map((m) => m.id);
7
+ /**
8
+ * Embedding models reachable through Bedrock's `InvokeModel` API. These are
9
+ * not part of the generated Converse catalog (embedding models have no
10
+ * conversational surface), so they're maintained by hand here.
11
+ */
12
+ var BEDROCK_EMBEDDING_MODELS = [
13
+ "amazon.titan-embed-text-v2:0",
14
+ "amazon.titan-embed-image-v1",
15
+ "cohere.embed-english-v3",
16
+ "cohere.embed-multilingual-v3"
17
+ ];
7
18
  //#endregion
8
- export { BEDROCK_CHAT_MODELS, BEDROCK_CONVERSE_MODELS, BEDROCK_RESPONSES_MODELS };
19
+ export { BEDROCK_CHAT_MODELS, BEDROCK_CONVERSE_MODELS, BEDROCK_EMBEDDING_MODELS, BEDROCK_RESPONSES_MODELS };
9
20
 
10
21
  //# sourceMappingURL=model-meta.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"model-meta.js","names":[],"sources":["../../src/model-meta.ts"],"sourcesContent":["import { GENERATED_BEDROCK_MODELS } from './model-catalog.generated.js'\nimport type { BedrockTextProviderOptions } from './text/text-provider-options'\nimport type { BedrockConverseProviderOptions } from './converse/provider-options'\n\ntype Entry = (typeof GENERATED_BEDROCK_MODELS)[number]\n\n/**\n * Type-level per-API filter over the generated catalog. Because the catalog is\n * `as const`, `Extract` preserves literal `id` unions (no widening to `string`).\n */\ntype IdsWhere<TApi extends 'converse' | 'chat' | 'responses'> = Extract<\n Entry,\n { apis: Record<TApi, true> }\n>['id']\n\nexport type BedrockConverseModels = IdsWhere<'converse'>\nexport type BedrockChatModels = IdsWhere<'chat'>\nexport type BedrockResponsesModels = IdsWhere<'responses'>\n\n/** Runtime catalogs. Cast-free narrowing via a type predicate (the ai-bedrock pattern). */\n// Every catalog entry advertises `converse: true` (Converse is the universal\n// Bedrock surface), so the id list is the full catalog — no runtime filter needed.\nexport const BEDROCK_CONVERSE_MODELS: ReadonlyArray<BedrockConverseModels> =\n GENERATED_BEDROCK_MODELS.map((m) => m.id)\n\nexport const BEDROCK_CHAT_MODELS: ReadonlyArray<BedrockChatModels> =\n GENERATED_BEDROCK_MODELS.filter(\n (m): m is Extract<Entry, { apis: { chat: true } }> => m.apis.chat,\n ).map((m) => m.id)\n\nexport const BEDROCK_RESPONSES_MODELS: ReadonlyArray<BedrockResponsesModels> =\n GENERATED_BEDROCK_MODELS.filter(\n (m): m is Extract<Entry, { apis: { responses: true } }> => m.apis.responses,\n ).map((m) => m.id)\n\n/** Per-model input modalities (drives type-safe multimodal content). Covers ALL models. */\nexport type BedrockModelInputModalitiesByName = {\n [E in Entry as E['id']]: E['input']\n}\n\n/** Provider options per model. Same options for every model; keyed over the full catalog. */\nexport type BedrockChatModelProviderOptionsByName = {\n [E in Entry as E['id']]: BedrockTextProviderOptions\n}\n\n/** Converse provider options per model (narrower than the Chat Completions set). */\nexport type BedrockConverseModelProviderOptionsByName = {\n [E in Entry as E['id']]: BedrockConverseProviderOptions\n}\n\n/** No provider-specific tools — empty tuple makes cross-provider ProviderTool a compile error. */\nexport type BedrockChatModelToolCapabilitiesByName = {\n [E in Entry as E['id']]: readonly []\n}\n\nexport type ResolveProviderOptions<TModel extends string> =\n TModel extends keyof BedrockChatModelProviderOptionsByName\n ? BedrockChatModelProviderOptionsByName[TModel]\n : BedrockTextProviderOptions\n\nexport type ResolveConverseProviderOptions<TModel extends string> =\n TModel extends keyof BedrockConverseModelProviderOptionsByName\n ? BedrockConverseModelProviderOptionsByName[TModel]\n : BedrockConverseProviderOptions\n\nexport type ResolveInputModalities<TModel extends string> =\n TModel extends keyof BedrockModelInputModalitiesByName\n ? BedrockModelInputModalitiesByName[TModel]\n : readonly ['text']\n"],"mappings":";;;AAsBA,IAAa,0BACX,yBAAyB,KAAK,MAAM,EAAE,EAAE;AAE1C,IAAa,sBACX,yBAAyB,QACtB,MAAqD,EAAE,KAAK,IAC/D,CAAC,CAAC,KAAK,MAAM,EAAE,EAAE;AAEnB,IAAa,2BACX,yBAAyB,QACtB,MAA0D,EAAE,KAAK,SACpE,CAAC,CAAC,KAAK,MAAM,EAAE,EAAE"}
1
+ {"version":3,"file":"model-meta.js","names":[],"sources":["../../src/model-meta.ts"],"sourcesContent":["import { GENERATED_BEDROCK_MODELS } from './model-catalog.generated.js'\nimport type { BedrockTextProviderOptions } from './text/text-provider-options'\nimport type { BedrockConverseProviderOptions } from './converse/provider-options'\nimport type {\n BedrockCohereEmbeddingProviderOptions,\n BedrockEmbeddingProviderOptions,\n BedrockTitanImageEmbeddingProviderOptions,\n BedrockTitanTextEmbeddingProviderOptions,\n} from './embedding/embedding-provider-options'\n\ntype Entry = (typeof GENERATED_BEDROCK_MODELS)[number]\n\n/**\n * Type-level per-API filter over the generated catalog. Because the catalog is\n * `as const`, `Extract` preserves literal `id` unions (no widening to `string`).\n */\ntype IdsWhere<TApi extends 'converse' | 'chat' | 'responses'> = Extract<\n Entry,\n { apis: Record<TApi, true> }\n>['id']\n\nexport type BedrockConverseModels = IdsWhere<'converse'>\nexport type BedrockChatModels = IdsWhere<'chat'>\nexport type BedrockResponsesModels = IdsWhere<'responses'>\n\n/** Runtime catalogs. Cast-free narrowing via a type predicate (the ai-bedrock pattern). */\n// Every catalog entry advertises `converse: true` (Converse is the universal\n// Bedrock surface), so the id list is the full catalog — no runtime filter needed.\nexport const BEDROCK_CONVERSE_MODELS: ReadonlyArray<BedrockConverseModels> =\n GENERATED_BEDROCK_MODELS.map((m) => m.id)\n\nexport const BEDROCK_CHAT_MODELS: ReadonlyArray<BedrockChatModels> =\n GENERATED_BEDROCK_MODELS.filter(\n (m): m is Extract<Entry, { apis: { chat: true } }> => m.apis.chat,\n ).map((m) => m.id)\n\nexport const BEDROCK_RESPONSES_MODELS: ReadonlyArray<BedrockResponsesModels> =\n GENERATED_BEDROCK_MODELS.filter(\n (m): m is Extract<Entry, { apis: { responses: true } }> => m.apis.responses,\n ).map((m) => m.id)\n\n/** Per-model input modalities (drives type-safe multimodal content). Covers ALL models. */\nexport type BedrockModelInputModalitiesByName = {\n [E in Entry as E['id']]: E['input']\n}\n\n/** Provider options per model. Same options for every model; keyed over the full catalog. */\nexport type BedrockChatModelProviderOptionsByName = {\n [E in Entry as E['id']]: BedrockTextProviderOptions\n}\n\n/** Converse provider options per model (narrower than the Chat Completions set). */\nexport type BedrockConverseModelProviderOptionsByName = {\n [E in Entry as E['id']]: BedrockConverseProviderOptions\n}\n\n/** No provider-specific tools — empty tuple makes cross-provider ProviderTool a compile error. */\nexport type BedrockChatModelToolCapabilitiesByName = {\n [E in Entry as E['id']]: readonly []\n}\n\nexport type ResolveProviderOptions<TModel extends string> =\n TModel extends keyof BedrockChatModelProviderOptionsByName\n ? BedrockChatModelProviderOptionsByName[TModel]\n : BedrockTextProviderOptions\n\nexport type ResolveConverseProviderOptions<TModel extends string> =\n TModel extends keyof BedrockConverseModelProviderOptionsByName\n ? BedrockConverseModelProviderOptionsByName[TModel]\n : BedrockConverseProviderOptions\n\nexport type ResolveInputModalities<TModel extends string> =\n TModel extends keyof BedrockModelInputModalitiesByName\n ? BedrockModelInputModalitiesByName[TModel]\n : readonly ['text']\n\n// ============================================================================\n// Embedding models\n// ============================================================================\n\n/**\n * Embedding models reachable through Bedrock's `InvokeModel` API. These are\n * not part of the generated Converse catalog (embedding models have no\n * conversational surface), so they're maintained by hand here.\n */\nexport const BEDROCK_EMBEDDING_MODELS = [\n 'amazon.titan-embed-text-v2:0',\n 'amazon.titan-embed-image-v1',\n 'cohere.embed-english-v3',\n 'cohere.embed-multilingual-v3',\n] as const\n\nexport type BedrockEmbeddingModel = (typeof BEDROCK_EMBEDDING_MODELS)[number]\n\n/**\n * Type-only map from embedding model name to its provider options type.\n * The Cohere models make `modelOptions` REQUIRED at the `embed()` call site\n * because `inputType` is a required field.\n */\nexport type BedrockEmbeddingModelProviderOptionsByName = {\n 'amazon.titan-embed-text-v2:0': BedrockTitanTextEmbeddingProviderOptions\n 'amazon.titan-embed-image-v1': BedrockTitanImageEmbeddingProviderOptions\n 'cohere.embed-english-v3': BedrockCohereEmbeddingProviderOptions\n 'cohere.embed-multilingual-v3': BedrockCohereEmbeddingProviderOptions\n}\n\n/**\n * Per-model input modalities for embedding models. Titan Multimodal accepts\n * text and/or images (including fused text+image items embedded into one\n * vector); the rest are text-only, so image inputs fail at compile time.\n */\nexport type BedrockEmbeddingModelInputModalitiesByName = {\n 'amazon.titan-embed-text-v2:0': readonly ['text']\n 'amazon.titan-embed-image-v1': readonly ['text', 'image']\n 'cohere.embed-english-v3': readonly ['text']\n 'cohere.embed-multilingual-v3': readonly ['text']\n}\n\nexport type ResolveEmbeddingProviderOptions<TModel extends string> =\n TModel extends keyof BedrockEmbeddingModelProviderOptionsByName\n ? BedrockEmbeddingModelProviderOptionsByName[TModel]\n : BedrockEmbeddingProviderOptions\n"],"mappings":";;;AA4BA,IAAa,0BACX,yBAAyB,KAAK,MAAM,EAAE,EAAE;AAE1C,IAAa,sBACX,yBAAyB,QACtB,MAAqD,EAAE,KAAK,IAC/D,CAAC,CAAC,KAAK,MAAM,EAAE,EAAE;AAEnB,IAAa,2BACX,yBAAyB,QACtB,MAA0D,EAAE,KAAK,SACpE,CAAC,CAAC,KAAK,MAAM,EAAE,EAAE;;;;;;AA8CnB,IAAa,2BAA2B;CACtC;CACA;CACA;CACA;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/ai-bedrock",
3
- "version": "0.1.6",
3
+ "version": "0.2.1",
4
4
  "type": "module",
5
5
  "description": "Amazon Bedrock adapter for TanStack AI — OpenAI-compatible chat, responses, tools, and reasoning.",
6
6
  "author": "",
@@ -40,7 +40,7 @@
40
40
  },
41
41
  "peerDependencies": {
42
42
  "zod": "^4.0.0",
43
- "@tanstack/ai": "0.43.1"
43
+ "@tanstack/ai": "^0.44.0"
44
44
  },
45
45
  "dependencies": {
46
46
  "@aws-crypto/sha256-js": "^5.2.0",
@@ -49,7 +49,7 @@
49
49
  "@smithy/signature-v4": "^5.4.5",
50
50
  "@smithy/types": "^4.14.2",
51
51
  "openai": "^6.41.0",
52
- "@tanstack/openai-base": "0.9.10"
52
+ "@tanstack/openai-base": "^0.9.12"
53
53
  },
54
54
  "scripts": {
55
55
  "build": "vite build",
@@ -261,9 +261,17 @@ export class BedrockConverseTextAdapter<
261
261
  `${this.name}.structuredOutput: response contained no forced-tool output`,
262
262
  )
263
263
  }
264
+ const usage = res.usage
264
265
  return {
265
266
  data: structured,
266
267
  rawText: JSON.stringify(structured),
268
+ ...(usage && {
269
+ usage: {
270
+ promptTokens: usage.inputTokens ?? 0,
271
+ completionTokens: usage.outputTokens ?? 0,
272
+ totalTokens: usage.totalTokens ?? 0,
273
+ },
274
+ }),
267
275
  }
268
276
  } catch (error: unknown) {
269
277
  chatOptions.logger.errors(`${this.name}.structuredOutput fatal`, {