Open History to see the last commit
1---
2title: Amazon Bedrock
3id: bedrock-adapter
4order: 7
5description: "Use Amazon Bedrock in TanStack AI with @tanstack/ai-bedrock: Claude, Nova, Llama, Mistral, DeepSeek, and gpt-oss through the Converse API or the OpenAI-compatible APIs, with 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 calls Claude, Nova, Llama, Mistral, DeepSeek, and gpt-oss in your AWS account. It supports streaming, tools, reasoning, and embeddings.
23
24## 1. Install
25
26<!-- ::start:tabs variant="package-manager" mode="install" -->
27
28react: @tanstack/ai-bedrock
29vue: @tanstack/ai-bedrock
30solid: @tanstack/ai-bedrock
31svelte: @tanstack/ai-bedrock
32preact: @tanstack/ai-bedrock
33angular: @tanstack/ai-bedrock
34vanilla: @tanstack/ai-bedrock
35octane: @tanstack/ai-bedrock
36
37<!-- ::end:tabs -->
38
39You need no other package. `@aws-sdk/client-bedrock-runtime` is a direct dependency, and it does the SigV4 signing.
40
41## 2. Set the credentials
42
43Bedrock takes an API key or your AWS credentials. Pick one.
44
45**API key.** Create a key in the AWS Console. See the [Bedrock API keys guide](https://docs.aws.amazon.com/bedrock/latest/userguide/api-keys.html). Then set one of these variables:
46
47```bash
48BEDROCK_API_KEY=your-bedrock-api-key
49# or the legacy name:
50AWS_BEARER_TOKEN_BEDROCK=your-bedrock-api-key
51```
52
53**SigV4 (AWS credential chain).** Use this for IAM roles, instance profiles, or `~/.aws/credentials`. With no API key in the environment, the adapter uses SigV4:
54
55```bash
56AWS_ACCESS_KEY_ID=...
57AWS_SECRET_ACCESS_KEY=...
58AWS_SESSION_TOKEN=... # optional, for temporary credentials
59```
60
61With `auth: 'auto'` (the default), the adapter uses the first of these that it finds:
62
631. An explicit `apiKey` passed to the factory.
642. The `BEDROCK_API_KEY` environment variable.
653. The `AWS_BEARER_TOKEN_BEDROCK` environment variable.
664. SigV4 through the standard AWS credential chain.
67
68Also enable access to the model in the [Amazon Bedrock console](https://console.aws.amazon.com/bedrock/home#/modelaccess). The models that you can use depend on your account and your region.
69
70## 3. Stream a chat from the server
71
72```typescript
73import {
74 chat,
75 chatParamsFromRequest,
76 toServerSentEventsResponse,
77} from "@tanstack/ai";
78import { bedrockText } from "@tanstack/ai-bedrock";
79
80export async function POST(request: Request) {
81 const { messages, threadId, runId } = await chatParamsFromRequest(request);
82
83 const stream = chat({
84 adapter: bedrockText("us.anthropic.claude-sonnet-4-5-20250929-v1:0", {
85 region: "us-east-1",
86 }),
87 messages,
88 threadId,
89 runId,
90 });
91
92 return toServerSentEventsResponse(stream);
93}
94```
95
96`bedrockText` uses the Converse API by default. Converse reaches the full chat catalog of Bedrock. For the other two APIs, see [Choose the API](#choose-the-api).
97
98## 4. Render the chat
99
100The client is the same for every provider. Point `useChat` at your route:
101
102```tsx
103import { useState } from "react";
104import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
105
106export function Chat() {
107 const [input, setInput] = useState("");
108 const { messages, sendMessage } = useChat({
109 connection: fetchServerSentEvents("/api/chat"),
110 threadId: "support-chat",
111 });
112
113 return (
114 <form
115 onSubmit={(event) => {
116 event.preventDefault();
117 sendMessage(input);
118 setInput("");
119 }}
120 >
121 {messages.map((message) => (
122 <p key={message.id}>
123 {message.parts
124 .map((part) => (part.type === "text" ? part.content : ""))
125 .join("")}
126 </p>
127 ))}
128 <input value={input} onChange={(event) => setInput(event.target.value)} />
129 </form>
130 );
131}
132```
133
134For Vue, Solid, Svelte, Angular, and the other frameworks, see [Quick Start](../getting-started/quick-start#3-render-the-chat).
135
136You now have a streaming chat on Bedrock. Client-side [tools](../tools/tools) work on all three APIs. Structured output and multimodal input (text, images, and documents) depend on the model.
137
138## Embeddings
139
140`bedrockEmbedding` calls the Titan and Cohere embedding models through `InvokeModel`:
141
142```typescript
143import { embed } from "@tanstack/ai";
144import { bedrockEmbedding } from "@tanstack/ai-bedrock";
145
146const result = await embed({
147 adapter: bedrockEmbedding("amazon.titan-embed-text-v2:0"),
148 input: ["a red guitar", "a blue drum kit"],
149 dimensions: 512, // 256 | 512 | 1024
150});
151
152console.log(result.embeddings[0]?.vector);
153```
154
155Titan Multimodal embeds text and images, alone or joined into one vector. To join parts, nest them in an array (the same `Array<ContentPart>` shape as the `content` of a chat message). The outer array is the list of items, so this embeds one joined item:
156
157```typescript
158import { embed } from "@tanstack/ai";
159import { bedrockEmbedding } from "@tanstack/ai-bedrock";
160
161const productPhoto = "iVBORw0KGgo..."; // base64 image data
162
163const result = await embed({
164 adapter: bedrockEmbedding("amazon.titan-embed-image-v1"),
165 input: [
166 [
167 { type: "text", content: "a red guitar" },
168 {
169 type: "image",
170 source: {
171 type: "data",
172 value: productPhoto,
173 mimeType: "image/png",
174 },
175 },
176 ],
177 ],
178 dimensions: 1024, // 256 | 384 | 1024
179});
180```
181
182Cohere Embed v3 on Bedrock is text only. It sends items in batches and requires `inputType`:
183
184```typescript
185import { embed } from "@tanstack/ai";
186import { bedrockEmbedding } from "@tanstack/ai-bedrock";
187
188const result = await embed({
189 adapter: bedrockEmbedding("cohere.embed-english-v3"),
190 input: ["a red guitar", "a blue drum kit"],
191 modelOptions: { inputType: "search_document" },
192});
193```
194
195- Titan models have no batch API. A batch of N items runs as N `InvokeModel` calls, with a small limit on calls at the same time.
196- Titan Multimodal does not fetch remote image URLs. Pass base64 data (or a `data:` URI).
197
198See the [Embeddings guide](../embeddings.md).
199
200## Models and options
201
202### Choose the API
203
204Bedrock has three chat APIs. Set `api` on the factory:
205
206| `api` | Adapter name | Models | SDK |
207|---|---|---|---|
208| `'converse'` (default) | `bedrock-converse` | The full catalog: Claude, Nova, Llama, Mistral, DeepSeek, Cohere, AI21, gpt-oss, and more | `@aws-sdk/client-bedrock-runtime` |
209| `'chat'` | `bedrock` | Open-weight models only: gpt-oss, DeepSeek V3.x, Gemma, Qwen, Mistral open models, GLM, and similar. No Claude, Nova, or Llama | `openai` (OpenAI-compatible Chat Completions) |
210| `'responses'` | `bedrock-responses` | gpt-oss and Gemma 4. Mantle only | `openai` (OpenAI-compatible Responses) |
211
212Use Converse unless you need the OpenAI wire format. For which models work with which API, see the [AWS API compatibility matrix](https://docs.aws.amazon.com/bedrock/latest/userguide/models-api-compatibility.html). Samples for `'chat'` and `'responses'` are in [Advanced](#chat-completions-api).
213
214### Reasoning
215
216Set `reasoning` on `chat()`. What goes to Bedrock depends on the API:
217
218- Converse (the default): only Claude gets thinking. A budget model gets `thinking` with a budget in `additionalModelRequestFields`, and `maxTokens` grows past the budget. `off` sends nothing.
219- Chat Completions (`api: 'chat'`): `reasoning_effort`.
220- Responses (`api: 'responses'`): `reasoning.effort`.
221
222```typescript
223import { chat } from "@tanstack/ai";
224import { bedrockText } from "@tanstack/ai-bedrock";
225
226const stream = chat({
227 adapter: bedrockText("us.anthropic.claude-haiku-4-5-20251001-v1:0", {
228 region: "us-east-1",
229 }),
230 messages: [{ role: "user", content: "Check this proof." }],
231 threadId: "thread-1",
232 reasoning: { level: "high", budgetTokens: 8000 },
233});
234```
235
236The levels of each model:
237
238- `us.anthropic.claude-haiku-4-5-*`, `us.anthropic.claude-sonnet-4-5-*`: `off`, `high`, with `budgetTokens`.
239- `openai.gpt-oss-120b-1:0`, `openai.gpt-oss-20b-1:0`: `low`, `medium`, `high`.
240- The `google.gemma-4` models: `off`, `high`.
241
242The other models take no `reasoning`. `us.deepseek.r1-v1:0` always thinks, and has no levels. When a model thinks by default, such as DeepSeek R1 or gpt-oss, the adapter streams its thinking.
243
244On Converse, structured output forces a tool, and Claude cannot think while a tool is forced. So the structured output call sends no thinking.
245
246### Models
247
248The package ships a catalog of confirmed model ids (`src/model-catalog.generated.ts`). The maintainer script `scripts/fetch-bedrock-models.ts` refreshes it with `ListFoundationModels`.
249
250| Group | Model ids |
251| --- | --- |
252| Anthropic Claude | `us.anthropic.claude-sonnet-4-5-20250929-v1:0`, `us.anthropic.claude-haiku-4-5-20251001-v1:0`, `us.anthropic.claude-3-7-sonnet-20250219-v1:0`, `us.anthropic.claude-3-5-sonnet-20241022-v2:0`, `us.anthropic.claude-3-5-haiku-20241022-v1:0` |
253| Amazon Nova | `us.amazon.nova-pro-v1:0`, `us.amazon.nova-lite-v1:0`, `us.amazon.nova-micro-v1:0` |
254| Meta Llama | `us.meta.llama4-maverick-17b-instruct-v1:0`, `us.meta.llama3-3-70b-instruct-v1:0` |
255| Other chat | `openai.gpt-oss-120b-1:0`, `openai.gpt-oss-20b-1:0`, `us.mistral.pixtral-large-2502-v1:0`, `us.deepseek.r1-v1:0`, `google.gemma-4-31b`, `google.gemma-4-26b-a4b`, `google.gemma-4-e2b` |
256| Embeddings | `amazon.titan-embed-text-v2:0`, `amazon.titan-embed-image-v1`, `cohere.embed-english-v3`, `cohere.embed-multilingual-v3` |
257
258`adapter.inputModalities` lists the input kinds of a model in the catalog. If this package does not know the model id, `bedrockText` and `createBedrockText` throw. `createBedrockChat`, `createBedrockResponsesText`, and `createBedrockConverse` return `undefined` for that id. See [Check what a model accepts](../advanced/extend-adapter#check-what-a-model-accepts).
259
260## Advanced
261
262### Configuration
263
264`BedrockClientConfig` takes these options:
265
266| Option | Type | Default | Description |
267|--------|------|---------|-------------|
268| `api` | `'converse' \| 'chat' \| 'responses'` | `'converse'` | The Bedrock API to use |
269| `region` | `string` | `'us-east-1'` | AWS region (for example `'us-west-2'`) |
270| `auth` | `'apikey' \| 'sigv4' \| 'auto'` | `'auto'` | Authentication mode |
271| `apiKey` | `string` | none | Explicit API key (wins over the environment variables) |
272| `baseURL` | `string` | none | Replaces the computed base URL |
273| `defaultHeaders` | `Record<string, string>` | none | Headers sent with every request |
274| `endpoint` | `'runtime' \| 'mantle'` | `'runtime'` | The Bedrock endpoint (Chat Completions only) |
275
276About `endpoint`:
277
278- It applies only when `api: 'chat'`.
279- `runtime` (`bedrock-runtime`) hosts the broad open-weight catalog. `mantle` is the other choice.
280- 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.
281- The Responses API always uses mantle.
282
283With an explicit API key:
284
285```typescript
286import { createBedrockText } from "@tanstack/ai-bedrock";
287
288const adapter = createBedrockText(
289 "us.anthropic.claude-haiku-4-5-20251001-v1:0",
290 "your-bedrock-api-key",
291 { region: "us-west-2" },
292);
293```
294
295### Behind a proxy
296
297Send 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.
298
299```typescript
300import { createBedrockText } from "@tanstack/ai-bedrock";
301
302const adapter = createBedrockText("us.amazon.nova-pro-v1:0", process.env.BEDROCK_API_KEY!, {
303 baseURL: "https://gateway.example.com/aws-bedrock",
304 defaultHeaders: { "cf-aig-authorization": `Bearer ${process.env.GATEWAY_TOKEN}` },
305});
306```
307
308- All three Bedrock APIs accept these options. On the Converse API, the adapter adds the headers before SigV4 signing, so a signed request still includes them.
309- Need more than a fixed header, such as a log of each model call? The Chat Completions API (`api: 'chat'`) and the Responses API (`api: 'responses'`) support [`wrapFetch`](../advanced/middleware#change-the-http-requests-of-a-call). The Converse API ignores it, because the AWS SDK does not send its requests through `fetch`.
310
311### Prompt caching
312
313`chat()` adds cache points for Claude models by default: one after the system prompt, and one at the end of the last user message. Pass `promptCache: 'long'` for the 1-hour cache, or `promptCache: 'none'` to turn it off. Other models get no automatic cache point. For the cost, see [Prompt Caching](../advanced/prompt-caching).
314
315To pick the places yourself, add a `cachePoint`. One cache point of your own turns the automatic ones off for that request. Later requests can read matching tokens at the lower cache rate. Bedrock bills cache misses at the standard input rate.
316
317Explicit prompt caching depends on the model. Use `cachePoint` only with a model that AWS lists as supporting it. The minimum checkpoint size and the TTL options also change by model.
318
319Set `metadata.cachePoint` on the item that ends the stable part of your prompt. The adapter puts a `cachePoint` block right after it:
320
321```typescript
322import { bedrockText } from "@tanstack/ai-bedrock";
323import { chat } from "@tanstack/ai";
324
325const stream = chat({
326 adapter: bedrockText("us.anthropic.claude-sonnet-4-5-20250929-v1:0", {
327 region: "us-east-1",
328 }),
329 systemPrompts: [
330 {
331 content: "Long, stable instructions...",
332 metadata: { cachePoint: { type: "default" } },
333 },
334 ],
335 messages: [
336 // An older turn. Its cachePoint was removed when the new turn was added.
337 { role: "user", content: "Summarize the report." },
338 { role: "assistant", content: "The report says..." },
339 {
340 role: "user",
341 content: [
342 {
343 type: "text",
344 content: "What changed since yesterday?",
345 // Only the newest message has a checkpoint.
346 // It caches the conversation up to here for the next round.
347 metadata: { cachePoint: { type: "default" } },
348 },
349 ],
350 },
351 ],
352 threadId: "thread-1",
353});
354```
355
356Keep 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.
357
358Tools take the same metadata. To cache the tool definitions, pass `metadata: { cachePoint: { type: 'default' } }` to `toolDefinition()` for the last tool in the list.
359
360- Bedrock accepts up to four checkpoints in one request.
361- Add `ttl: '1h'` to keep an entry for one hour. The default is 5 minutes, and a read starts the timer again.
362- Bedrock reads tool checkpoints first, then system prompt checkpoints, then message checkpoints. If a request mixes both TTLs, put every `1h` checkpoint before the first `5m` checkpoint in that order.
363- Bedrock ignores a checkpoint below the minimum size of the model. The request still succeeds, and nothing goes into the cache.
364
365### Token usage
366
367`onUsage` and `RUN_FINISHED.usage` report the counts of Bedrock as `promptTokens`, `completionTokens`, and `totalTokens`.
368
369- `promptTokens` is the full input, cached tokens included.
370- When a request reads or writes a prompt cache, the cache parts are also on `promptTokensDetails.cachedTokens` and `promptTokensDetails.cacheWriteTokens`.
371
372To read these counts, see [Token usage](../chat/stream-events#token-usage).
373
374### Chat Completions API
375
376Set `api: 'chat'` to use the OpenAI-compatible Chat Completions endpoint of Bedrock. It returns a `bedrock` adapter. Only open-weight models are on this endpoint.
377
378```typescript ignore
379// ignore: iterating a chat() stream and reading chunk.type/chunk.delta needs the
380// AG-UI base event fields, which come from @ag-ui/core. It's a transitive dep of
381// @tanstack/ai, so kiira (resolving @tanstack/ai from source under the dist->src
382// heuristic) can't follow it and those base fields drop off StreamChunk. The code
383// is correct (the same pattern is used throughout ai-client); see
384// getting-started/quick-start-server for the type-checked consumption shape.
385import { bedrockText } from '@tanstack/ai-bedrock'
386import { chat } from '@tanstack/ai'
387
388const adapter = bedrockText('openai.gpt-oss-20b-1:0', {
389 region: 'us-east-1',
390 api: 'chat',
391})
392
393for await (const chunk of chat({
394 adapter,
395 messages: [{ role: 'user', content: 'What is the capital of France?' }],
396 threadId: 'thread-1',
397})) {
398 if (chunk.type === 'TEXT_MESSAGE_CONTENT') process.stdout.write(chunk.delta ?? '')
399}
400```
401
402### Responses API
403
404Set `api: 'responses'` to use the OpenAI-compatible Responses API of Bedrock. It returns a `bedrock-responses` adapter. This API is mantle only.
405
406- The Responses API is stateful. To continue a conversation on the server, pass `previous_response_id` and `store` in `modelOptions`.
407- Reasoning deltas stream as thinking content. Models on mantle can still send the old event name `response.reasoning.delta`, which the OpenAI spec replaced with `response.reasoning_text.delta`. The adapter reads both names the same way.
408
409```typescript ignore
410// ignore: see the Chat Completions sample above. Iterating a chat() stream and
411// reading chunk.type/chunk.delta needs @ag-ui/core base fields kiira can't
412// resolve transitively through @tanstack/ai source.
413import { bedrockText } from '@tanstack/ai-bedrock'
414import { chat } from '@tanstack/ai'
415
416const adapter = bedrockText('openai.gpt-oss-120b-1:0', {
417 region: 'us-east-1',
418 api: 'responses',
419})
420
421for await (const chunk of chat({
422 adapter,
423 messages: [{ role: 'user', content: 'Summarize the Bedrock pricing page.' }],
424 threadId: 'thread-1',
425})) {
426 if (chunk.type === 'TEXT_MESSAGE_CONTENT') process.stdout.write(chunk.delta ?? '')
427}
428```
429
430### API reference
431
432| Factory | Creates |
433| --- | --- |
434| `bedrockText(model, config?)` | Chat adapter with auth from the environment. Returns the adapter of the `api` that you pick |
435| `createBedrockText(model, apiKey, config?)` | Chat adapter with an explicit API key. Skips the environment lookup |
436| `bedrockEmbedding(model, config?)` / `createBedrockEmbedding(model, apiKey, config?)` | Embedding adapter for Titan and Cohere models |
437
438`config` takes `api`, `region`, `auth`, `apiKey`, `baseURL`, `defaultHeaders`, and `endpoint`. See [Configuration](#configuration).
439
440More from AWS:
441
442- [Amazon Bedrock API keys](https://docs.aws.amazon.com/bedrock/latest/userguide/api-keys.html): create and manage API keys.
443- [Amazon Bedrock model access](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html): enable models in your account.
444- [Converse API reference](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html): the native Converse API docs.