Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

bedrock.md

400 lines16.9 KB

1---
2title: Amazon Bedrock
3id: bedrock-adapter
4order: 7
5description: "Use Amazon Bedrock with TanStack AI — the Converse API is the default, reaching Claude, Nova, Llama, Mistral, DeepSeek, and more. Opt into OpenAI-compatible Chat Completions or Responses for open-weight and gpt-oss models. Supports streaming, tools, reasoning, and API-key or SigV4 auth."
6keywords:
7 - tanstack ai
8 - amazon bedrock
9 - aws
10 - bedrock
11 - converse api
12 - openai compatible
13 - chat completions
14 - responses api
15 - sigv4
16 - claude
17 - nova
18 - llama
19 - adapter
20---
21​
22The Bedrock adapter connects TanStack AI to [Amazon Bedrock](https://aws.amazon.com/bedrock/) with three API paths:
23​
24- **Converse** (default) — Bedrock's model-agnostic API built on `@aws-sdk/client-bedrock-runtime`. Reaches the broad chat catalog including Anthropic Claude, Amazon Nova, Meta Llama, Mistral, DeepSeek, Cohere, AI21, and OpenAI gpt-oss models.
25- **Chat Completions** (`api: 'chat'`) — Bedrock's OpenAI-compatible Chat Completions endpoint. Reaches open-weight models only (gpt-oss, DeepSeek V3.x, Gemma, Qwen, Mistral open models, GLM, etc.). Does NOT reach Claude, Nova, or Llama.
26- **Responses** (`api: 'responses'`) — Bedrock's OpenAI-compatible Responses API, mantle-only. Currently gpt-oss and Gemma 4.
27​
28All paths support streaming and client-side tool calling. Reasoning output is
29surfaced when the model emits it (e.g. DeepSeek R1, gpt-oss); on the Converse
30path, request-side enablement of extended thinking (e.g. a Claude thinking
31budget) is not yet wired, so only models that reason by default surface it.
32​
33## Installation
34​
35<!-- ::start:tabs variant="package-manager" mode="install" -->
36​
37react: @tanstack/ai-bedrock
38vue: @tanstack/ai-bedrock
39solid: @tanstack/ai-bedrock
40svelte: @tanstack/ai-bedrock
41preact: @tanstack/ai-bedrock
42angular: @tanstack/ai-bedrock
43vanilla: @tanstack/ai-bedrock
44octane: @tanstack/ai-bedrock
45​
46<!-- ::end:tabs -->
47​
48No additional packages are required. SigV4 authentication is handled by `@aws-sdk/client-bedrock-runtime`, which is a direct dependency.
49​
50## Quick Start (Converse — default)
51​
52The default `bedrockText` call uses the Converse API and reaches the broad model catalog:
53​
54```typescript ignore
55// ignore: iterating a chat() stream and reading chunk.type/chunk.delta needs the
56// AG-UI base event fields, which come from @ag-ui/core. It's a transitive dep of
57// @tanstack/ai, so kiira (resolving @tanstack/ai from source under the dist->src
58// heuristic) can't follow it and those base fields drop off StreamChunk. The code
59// is correct (the same pattern is used throughout ai-client); see
60// getting-started/quick-start-server for the type-checked consumption shape.
61import { bedrockText } from '@tanstack/ai-bedrock'
62import { chat } from '@tanstack/ai'
63​
64const adapter = bedrockText('us.anthropic.claude-haiku-4-5-20251001-v1:0', {
65 region: 'us-east-1',
66})
67​
68for await (const chunk of chat({
69 adapter,
70 messages: [{ role: 'user', content: 'What is the capital of France?' }],
71})) {
72 if (chunk.type === 'TEXT_MESSAGE_CONTENT') process.stdout.write(chunk.delta ?? '')
74```
75​
76Equivalent to passing `{ api: 'converse' }` explicitly. Returns a `bedrock-converse` adapter.
77​
78## Authentication
79​
80Bedrock supports two authentication modes.
81​
82### API Key
83​
84Bedrock issues API keys from the AWS Console. See the [Bedrock API keys guide](https://docs.aws.amazon.com/bedrock/latest/userguide/api-keys.html) for instructions.
85​
86Set one of the following environment variables and the adapter picks it up automatically:
87​
88```bash
89BEDROCK_API_KEY=your-bedrock-api-key
90# or the legacy name:
91AWS_BEARER_TOKEN_BEDROCK=your-bedrock-api-key
92```
93​
94### SigV4 (AWS credential chain)
95​
96For workloads using IAM roles, instance profiles, or `~/.aws/credentials`, set `auth: 'sigv4'` (or leave it as `'auto'` with no API key in the environment). SigV4 works out of the box via `@aws-sdk/client-bedrock-runtime` — no additional packages required.
97​
98```bash
99AWS_ACCESS_KEY_ID=...
100AWS_SECRET_ACCESS_KEY=...
101AWS_SESSION_TOKEN=... # optional, for temporary credentials
102```
103​
104### Auth resolution order (`auth: 'auto'`, the default)
105​
1061. Explicit `apiKey` passed to the factory
1072. `BEDROCK_API_KEY` environment variable
1083. `AWS_BEARER_TOKEN_BEDROCK` environment variable
1094. SigV4 via the standard AWS credential chain
110​
111## Configuration
112​
113`BedrockClientConfig` accepts the following options:
114​
115| Option | Type | Default | Description |
116|--------|------|---------|-------------|
117| `api` | `'converse' \| 'chat' \| 'responses'` | `'converse'` | Bedrock API to use |
118| `region` | `string` | `'us-east-1'` | AWS region string (e.g. `'us-west-2'`) |
119| `auth` | `'apikey' \| 'sigv4' \| 'auto'` | `'auto'` | Authentication mode |
120| `apiKey` | `string` | — | Explicit API key (overrides env vars) |
121| `baseURL` | `string` | — | Override the computed base URL entirely |
122| `defaultHeaders` | `Record<string, string>` | none | Headers sent with every request |
123| `endpoint` | `'runtime' \| 'mantle'` | `'runtime'` | Bedrock endpoint to target (Chat Completions path only) |
124​
125The `endpoint` option only applies when `api: 'chat'`. The `runtime` endpoint (`bedrock-runtime`) hosts the broad open-weight catalog; `mantle` is an alternative. On mantle, the adapter reads the path from the Bedrock API compatibility config (`/openai/v1` for Gemma 4, `/v1` for other models). An explicit `baseURL` still wins. The Responses API always targets mantle.
126​
127## Behind a proxy
128​
129Route every request through a gateway, such as Cloudflare AI Gateway or a corporate proxy, with `baseURL` and `defaultHeaders`. These two option names are the same on every TanStack AI adapter, so one gateway config works for all of them.
130​
131```typescript
132import { createBedrockText } from "@tanstack/ai-bedrock";
133​
134const adapter = createBedrockText("us.amazon.nova-pro-v1:0", process.env.BEDROCK_API_KEY!, {
135 baseURL: "https://gateway.example.com/aws-bedrock",
136 defaultHeaders: { "cf-aig-authorization": `Bearer ${process.env.GATEWAY_TOKEN}` },
137});
138```
139​
140All three Bedrock APIs accept these options. On the Converse API the headers are added before SigV4 signing, so a signed request still includes them.
141​
142## Converse API (default)
143​
144`bedrockText(model)` or `bedrockText(model, { api: 'converse' })` returns a `bedrock-converse` adapter backed by `@aws-sdk/client-bedrock-runtime`. This is Bedrock's model-agnostic conversational API and is the recommended path for most use cases.
145​
146**Model scope:** Anthropic Claude, Amazon Nova, Meta Llama, Mistral, DeepSeek, Cohere, AI21, OpenAI gpt-oss, and other models accessible in your account. See [Model availability](#model-availability) below.
147​
148```typescript
149import { bedrockText } from '@tanstack/ai-bedrock'
150import { chat } from '@tanstack/ai'
151​
152// Claude via Converse
153const claudeAdapter = bedrockText('us.anthropic.claude-haiku-4-5-20251001-v1:0', {
154 region: 'us-east-1',
155})
156​
157// Amazon Nova via Converse
158const novaAdapter = bedrockText('us.amazon.nova-pro-v1:0', {
159 region: 'us-east-1',
160})
161​
162// Meta Llama via Converse
163const llamaAdapter = bedrockText('us.meta.llama4-maverick-17b-instruct-v1:0', {
164 region: 'us-east-1',
165})
166```
167​
168### Explicit API key (Converse)
169​
170```typescript
171import { createBedrockText } from '@tanstack/ai-bedrock'
172​
173const adapter = createBedrockText(
174 'us.anthropic.claude-haiku-4-5-20251001-v1:0',
175 'your-bedrock-api-key',
176 { region: 'us-west-2' },
178```
179​
180### Prompt caching
181​
182Add a `cachePoint` to make a prompt prefix eligible for caching. Later requests can read matching tokens at the reduced cache rate. Bedrock bills cache misses at the standard input rate.
183​
184Explicit prompt caching is model-dependent. Use `cachePoint` only with a model that AWS lists as supporting it. The minimum checkpoint size and the TTL options also vary by model.
185​
186Set `metadata.cachePoint` on the item that ends the stable part of your prompt. The adapter places a `cachePoint` block right after it:
187​
188```typescript
189import { bedrockText } from '@tanstack/ai-bedrock'
190import { chat } from '@tanstack/ai'
191​
192const stream = chat({
193 adapter: bedrockText('us.anthropic.claude-sonnet-4-5-20250929-v1:0', {
194 region: 'us-east-1',
195 }),
196 systemPrompts: [
197 {
198 content: 'Long, stable instructions...',
199 metadata: { cachePoint: { type: 'default' } },
200 },
201 ],
202 messages: [
203 // An older turn. Its cachePoint was removed when the new turn was added.
204 { role: 'user', content: 'Summarize the report.' },
205 { role: 'assistant', content: 'The report says...' },
206 {
207 role: 'user',
208 content: [
209 {
210 type: 'text',
211 content: 'What changed since yesterday?',
212 // Only the newest message has a checkpoint.
213 // It caches the conversation up to here for the next round.
214 metadata: { cachePoint: { type: 'default' } },
215 },
216 ],
217 },
218 ],
219})
220```
221​
222Keep one message checkpoint, on the newest message. Before you send the next turn, remove `cachePoint` from the older message and add it to the new message. The metadata stays in the message history. If you do not remove it, the checkpoints add up, and the request can go over the Bedrock limit of four.
223​
224Tools take the same metadata. Pass `metadata: { cachePoint: { type: 'default' } }` to `toolDefinition()` for the last tool in the list to cache the tool definitions.
225​
226- Bedrock accepts up to four checkpoints per request.
227- Add `ttl: '1h'` to keep an entry for one hour. The default is 5 minutes, and a read refreshes the timer. Bedrock processes tool checkpoints first, then system prompt checkpoints, and then message checkpoints. If a request mixes both TTLs, place every `1h` checkpoint before the first `5m` checkpoint in that combined order.
228- A checkpoint below the model's minimum size is ignored. The request still succeeds, and nothing is cached.
229​
230### Token usage
231​
232`onUsage` and `RUN_FINISHED.usage` report Bedrock's counts as `promptTokens`, `completionTokens`, and `totalTokens`. When a request hits or writes a prompt cache, the cache counts arrive on `promptTokensDetails.cachedTokens` and `promptTokensDetails.cacheWriteTokens`. Bedrock counts only the uncached part of the input in `promptTokens`, so add the two cache counts to it to get the full input size.
233​
234## Chat Completions API (`api: 'chat'`)
235​
236Set `api: 'chat'` to use Bedrock's OpenAI-compatible Chat Completions endpoint. Returns a `bedrock` adapter.
237​
238**Model scope:** Open-weight models only — gpt-oss, DeepSeek V3.x, Gemma, Qwen, Mistral open models, GLM, and similar. Claude, Nova, and Llama are NOT available on this endpoint. See the [AWS API compatibility matrix](https://docs.aws.amazon.com/bedrock/latest/userguide/models-api-compatibility.html) for the current list.
239​
240```typescript ignore
241// ignore: see the Converse quick-start above — iterating a chat() stream and
242// reading chunk.type/chunk.delta needs @ag-ui/core base fields kiira can't
243// resolve transitively through @tanstack/ai source.
244import { bedrockText } from '@tanstack/ai-bedrock'
245import { chat } from '@tanstack/ai'
246​
247const adapter = bedrockText('openai.gpt-oss-20b-1:0', {
248 region: 'us-east-1',
249 api: 'chat',
250})
251​
252for await (const chunk of chat({
253 adapter,
254 messages: [{ role: 'user', content: 'What is the capital of France?' }],
255})) {
256 if (chunk.type === 'TEXT_MESSAGE_CONTENT') process.stdout.write(chunk.delta ?? '')
258```
259​
260## Responses API (`api: 'responses'`)
261​
262Set `api: 'responses'` to use Bedrock's OpenAI-compatible Responses API. Returns a `bedrock-responses` adapter. This API is mantle-only.
263​
264**Model scope:** Currently gpt-oss and Gemma 4. The Responses API is stateful — pass `previous_response_id` and `store` through `modelOptions` to continue a conversation server-side.
265​
266**Reasoning:** Reasoning deltas stream as thinking content. Mantle-served models may still emit the pre-July-2025 event name `response.reasoning.delta` (removed from the OpenAI spec in favor of `response.reasoning_text.delta`); the adapter recognizes both and maps them identically.
267​
268```typescript ignore
269// ignore: see the Converse quick-start above — iterating a chat() stream and
270// reading chunk.type/chunk.delta needs @ag-ui/core base fields kiira can't
271// resolve transitively through @tanstack/ai source.
272import { bedrockText } from '@tanstack/ai-bedrock'
273import { chat } from '@tanstack/ai'
274​
275const adapter = bedrockText('openai.gpt-oss-120b-1:0', {
276 region: 'us-east-1',
277 api: 'responses',
278})
279​
280for await (const chunk of chat({
281 adapter,
282 messages: [{ role: 'user', content: 'Summarize the Bedrock pricing page.' }],
283})) {
284 if (chunk.type === 'TEXT_MESSAGE_CONTENT') process.stdout.write(chunk.delta ?? '')
286```
287​
288## Embeddings
289​
290Generate embedding vectors with Titan or Cohere embedding models via `InvokeModel`:
291​
292```typescript
293import { embed } from "@tanstack/ai";
294import { bedrockEmbedding } from "@tanstack/ai-bedrock";
295​
296const result = await embed({
297 adapter: bedrockEmbedding("amazon.titan-embed-text-v2:0"),
298 input: ["a red guitar", "a blue drum kit"],
299 dimensions: 512, // 256 | 512 | 1024
300});
301​
302console.log(result.embeddings[0]?.vector);
303```
304​
305Titan Multimodal embeds text and images — alone or fused into a single vector. Fuse parts by nesting them in an array (the same `Array<ContentPart>` shape a chat message's `content` uses); the outer array is the item list, so this embeds one fused item:
306​
307```typescript
308import { embed } from "@tanstack/ai";
309import { bedrockEmbedding } from "@tanstack/ai-bedrock";
310​
311const productPhoto = "iVBORw0KGgo..."; // base64 image data
312​
313const result = await embed({
314 adapter: bedrockEmbedding("amazon.titan-embed-image-v1"),
315 input: [
316 [
317 { type: "text", content: "a red guitar" },
318 {
319 type: "image",
320 source: {
321 type: "data",
322 value: productPhoto,
323 mimeType: "image/png",
324 },
325 },
326 ],
327 ],
328 dimensions: 1024, // 256 | 384 | 1024
329});
330```
331​
332Cohere Embed v3 on Bedrock is also supported (text-only, batched, requires `inputType`):
333​
334```typescript
335import { embed } from "@tanstack/ai";
336import { bedrockEmbedding } from "@tanstack/ai-bedrock";
337​
338const result = await embed({
339 adapter: bedrockEmbedding("cohere.embed-english-v3"),
340 input: ["a red guitar", "a blue drum kit"],
341 modelOptions: { inputType: "search_document" },
342});
343```
344​
345> Titan models have no batch API — a batch of N items runs as N `InvokeModel`
346> calls under a small concurrency cap. Titan Multimodal does not fetch remote
347> image URLs; pass base64 data (or a `data:` URI).
348​
349See the [Embeddings guide](../embeddings.md) for the full API.
350​
351## Model Availability
352​
353The adapter ships with a hand-seeded snapshot catalog (`src/model-catalog.generated.ts`) of confirmed model IDs. This catalog can be refreshed by the maintainer script `scripts/fetch-bedrock-models.ts`, which calls `ListFoundationModels` with AWS credentials.
354​
355**Actual model availability depends on your AWS account's model access configuration and the region you are targeting.** Enable model access in the [Amazon Bedrock console](https://console.aws.amazon.com/bedrock/home#/modelaccess) before use.
356​
357For the full list of models and which API endpoints they support, see the [AWS API compatibility matrix](https://docs.aws.amazon.com/bedrock/latest/userguide/models-api-compatibility.html).
358​
359## Supported Capabilities
360​
361- Streaming chat completions
362- Client-side tool calling
363- Reasoning output (extended thinking surfaced when the model emits it; request-side enablement on Converse is not yet wired)
364- Multimodal input (text, images, documents — model-dependent)
365- JSON schema / structured output
366​
367## API Reference
368​
369### `bedrockText(model, config?)`
370​
371Creates a Bedrock adapter using environment-variable auth.
372​
373- `model` — Model ID (e.g. `'us.anthropic.claude-haiku-4-5-20251001-v1:0'`)
374- `config.api` — `'converse'` (default), `'chat'`, or `'responses'`
375- `config.region` — AWS region string (default `'us-east-1'`)
376- `config.auth` — `'auto'` (default), `'apikey'`, or `'sigv4'`
377- `config.apiKey` — Explicit API key (overrides env vars)
378- `config.baseURL` — Override base URL
379- `config.endpoint` — `'runtime'` (default) or `'mantle'` (Chat Completions path only)
380​
381Returns a chat adapter for use with `chat()` or `generate()`.
382​
383| `api` value | Adapter name | Underlying SDK |
384|---|---|---|
385| `'converse'` (default) | `bedrock-converse` | `@aws-sdk/client-bedrock-runtime` |
386| `'chat'` | `bedrock` | `openai` (OpenAI-compatible) |
387| `'responses'` | `bedrock-responses` | `openai` (OpenAI-compatible) |
388​
389### `createBedrockText(model, apiKey, config?)`
390​
391Creates a Bedrock adapter with an explicit API key, bypassing the environment-variable lookup.
392​
393## Next Steps
394​
395- [Amazon Bedrock API keys](https://docs.aws.amazon.com/bedrock/latest/userguide/api-keys.html) — Create and manage API keys
396- [Amazon Bedrock model access](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html) — Enable models in your account
397- [AWS API compatibility matrix](https://docs.aws.amazon.com/bedrock/latest/userguide/models-api-compatibility.html) — Which models work with which APIs
398- [Converse API reference](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) — Native Converse API docs
399- [Streaming Guide](../chat/streaming) — Learn about streaming responses
400- [Tools Guide](../tools/tools) — Learn about tool calling