-
-
Notifications
You must be signed in to change notification settings - Fork 213
feat(ai-bedrock): add AWS Bedrock adapter with ConverseStream and tool-calling support #220
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
muralidhar-challa
wants to merge
3
commits into
TanStack:main
Choose a base branch
from
muralidhar-challa:feat/ai-bedrock-adapter
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
50d8a8f
feat(ai-bedrock): add AWS Bedrock adapter with AG-UI streaming
muralidhar-challa 45ae9de
fix(ai-bedrock): fix off-by-one in <thinking> tag skip position
muralidhar-challa 7a04feb
feat(ai-bedrock): add pluggable auth with API key bearer token support
muralidhar-challa File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "@tanstack/ai-bedrock": minor | ||
| --- | ||
|
|
||
| Add Amazon Bedrock adapter. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,239 @@ | ||
| --- | ||
| title: AWS Bedrock | ||
| id: bedrock-adapter | ||
| order: 9 | ||
| --- | ||
|
|
||
| The AWS Bedrock adapter provides access to Amazon Bedrock's managed AI models, including Amazon Nova and Anthropic Claude models, via the unified Converse API. | ||
|
|
||
| ## Installation | ||
|
|
||
| ```bash | ||
| npm install @tanstack/ai-bedrock | ||
| ``` | ||
|
|
||
| ## Basic Usage | ||
|
|
||
| ```typescript | ||
| import { chat } from "@tanstack/ai"; | ||
| import { bedrockText } from "@tanstack/ai-bedrock"; | ||
|
|
||
| const stream = chat({ | ||
| adapter: bedrockText("amazon.nova-pro-v1:0"), | ||
| messages: [{ role: "user", content: "Hello!" }], | ||
| }); | ||
| ``` | ||
|
|
||
| ## Basic Usage - Custom Credentials | ||
|
|
||
| ```typescript | ||
| import { chat } from "@tanstack/ai"; | ||
| import { createBedrockChat } from "@tanstack/ai-bedrock"; | ||
|
|
||
| const adapter = createBedrockChat("amazon.nova-pro-v1:0", { | ||
| region: "us-east-1", | ||
| credentials: { | ||
| accessKeyId: process.env.AWS_ACCESS_KEY_ID!, | ||
| secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!, | ||
| }, | ||
| }); | ||
|
|
||
| const stream = chat({ | ||
| adapter, | ||
| messages: [{ role: "user", content: "Hello!" }], | ||
| }); | ||
| ``` | ||
|
|
||
| ## Environment Variables | ||
|
|
||
| The `bedrockText()` factory reads AWS credentials automatically from environment variables: | ||
|
|
||
| ```bash | ||
| AWS_REGION=us-east-1 | ||
| AWS_ACCESS_KEY_ID=AKIA... | ||
| AWS_SECRET_ACCESS_KEY=... | ||
| AWS_SESSION_TOKEN=... # Optional, for temporary credentials | ||
| ``` | ||
|
|
||
| ## Example: Chat Completion | ||
|
|
||
| ```typescript | ||
| import { chat, toServerSentEventsResponse } from "@tanstack/ai"; | ||
| import { bedrockText } from "@tanstack/ai-bedrock"; | ||
|
|
||
| export async function POST(request: Request) { | ||
| const { messages } = await request.json(); | ||
|
|
||
| const stream = chat({ | ||
| adapter: bedrockText("amazon.nova-pro-v1:0"), | ||
| messages, | ||
| }); | ||
|
|
||
| return toServerSentEventsResponse(stream); | ||
| } | ||
| ``` | ||
|
|
||
| ## Example: With Tools | ||
|
|
||
| ```typescript | ||
| import { chat, toolDefinition } from "@tanstack/ai"; | ||
| import { bedrockText } from "@tanstack/ai-bedrock"; | ||
| import { z } from "zod"; | ||
|
|
||
| const getWeatherDef = toolDefinition({ | ||
| name: "get_weather", | ||
| description: "Get current weather for a city", | ||
| inputSchema: z.object({ | ||
| city: z.string(), | ||
| }), | ||
| }); | ||
|
|
||
| const getWeather = getWeatherDef.server(async ({ city }) => { | ||
| return { temperature: 72, conditions: "sunny", city }; | ||
| }); | ||
|
|
||
| const stream = chat({ | ||
| adapter: bedrockText("anthropic.claude-sonnet-4-5-20250929-v1:0"), | ||
| messages: [{ role: "user", content: "What's the weather in Paris?" }], | ||
| tools: [getWeather], | ||
| }); | ||
| ``` | ||
|
|
||
| ## Thinking / Extended Reasoning | ||
|
|
||
| Models that support thinking (Claude Sonnet 4.5, Claude Haiku 4.5, and Nova models) can be configured to show their reasoning process, streamed as `thinking` chunks: | ||
|
|
||
| ```typescript | ||
| import { chat } from "@tanstack/ai"; | ||
| import { bedrockText } from "@tanstack/ai-bedrock"; | ||
|
|
||
| const stream = chat({ | ||
| adapter: bedrockText("anthropic.claude-sonnet-4-5-20250929-v1:0"), | ||
| messages: [{ role: "user", content: "Solve this step by step: 17 * 24" }], | ||
| modelOptions: { | ||
| thinking: { | ||
| type: "enabled", | ||
| budget_tokens: 2000, | ||
| }, | ||
| }, | ||
| }); | ||
|
|
||
| for await (const chunk of stream) { | ||
| if (chunk.type === "thinking") { | ||
| process.stdout.write(`[thinking] ${chunk.delta}`); | ||
| } else if (chunk.type === "content") { | ||
| process.stdout.write(chunk.delta); | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| Nova models use a `reasoningConfig` approach but produce the same `thinking` stream chunks — the adapter normalises both automatically. | ||
|
|
||
| ## Multimodal Content | ||
|
|
||
| Nova Pro, Nova Lite, and Claude models support image and document inputs: | ||
|
|
||
| ```typescript | ||
| import { chat } from "@tanstack/ai"; | ||
| import { bedrockText } from "@tanstack/ai-bedrock"; | ||
| import { readFileSync } from "fs"; | ||
|
|
||
| const imageBytes = readFileSync("./photo.jpg"); | ||
|
|
||
| const stream = chat({ | ||
| adapter: bedrockText("amazon.nova-pro-v1:0"), | ||
| messages: [ | ||
| { | ||
| role: "user", | ||
| content: [ | ||
| { | ||
| type: "image", | ||
| source: { type: "base64", value: imageBytes }, | ||
| metadata: { mediaType: "image/jpeg" }, | ||
| }, | ||
| { type: "text", content: "What do you see in this image?" }, | ||
| ], | ||
| }, | ||
| ], | ||
| }); | ||
| ``` | ||
|
|
||
| ## Model Options | ||
|
|
||
| ```typescript | ||
| const stream = chat({ | ||
| adapter: bedrockText("amazon.nova-pro-v1:0"), | ||
| messages: [{ role: "user", content: "Hello!" }], | ||
| modelOptions: { | ||
| inferenceConfig: { | ||
| maxTokens: 1024, | ||
| temperature: 0.7, | ||
| topP: 0.9, | ||
| }, | ||
| stop_sequences: ["END"], | ||
| top_k: 50, | ||
| }, | ||
| }); | ||
| ``` | ||
|
|
||
| ## Supported Models | ||
|
|
||
| ### Amazon Nova | ||
|
|
||
| | Model | ID | Context | Inputs | | ||
| |-------|----|---------|--------| | ||
| | Nova Pro | `amazon.nova-pro-v1:0` | 300K | text, image, video, document | | ||
| | Nova Lite | `amazon.nova-lite-v1:0` | 300K | text, image, video, document | | ||
| | Nova Micro | `amazon.nova-micro-v1:0` | 128K | text only | | ||
|
|
||
| ### Anthropic Claude (via Bedrock) | ||
|
|
||
| | Model | ID | Context | Inputs | | ||
| |-------|----|---------|--------| | ||
| | Claude Sonnet 4.5 | `anthropic.claude-sonnet-4-5-20250929-v1:0` | 1M | text, image, document | | ||
| | Claude Haiku 4.5 | `anthropic.claude-haiku-4-5-20251001-v1:0` | 200K | text, image, document | | ||
|
|
||
| Both Claude models support extended thinking. | ||
|
|
||
| ## API Reference | ||
|
|
||
| ### `bedrockText(model, config?)` | ||
|
|
||
| Creates a Bedrock text adapter using environment variable credentials. | ||
|
|
||
| **Parameters:** | ||
|
|
||
| - `model` - The Bedrock model ID (e.g., `amazon.nova-pro-v1:0`) | ||
| - `config` (optional) - Partial configuration object: | ||
| - `region` - AWS region (falls back to `AWS_REGION` / `AWS_DEFAULT_REGION`) | ||
| - `credentials.accessKeyId` - AWS access key (falls back to `AWS_ACCESS_KEY_ID`) | ||
| - `credentials.secretAccessKey` - AWS secret key (falls back to `AWS_SECRET_ACCESS_KEY`) | ||
|
|
||
| **Returns:** A `BedrockTextAdapter` instance. | ||
|
|
||
| ### `createBedrockChat(model, config)` | ||
|
|
||
| Creates a Bedrock text adapter with explicit credentials. | ||
|
|
||
| **Parameters:** | ||
|
|
||
| - `model` - The Bedrock model ID | ||
| - `config` - Full configuration object: | ||
| - `region` - AWS region (required) | ||
| - `credentials.accessKeyId` - AWS access key (required) | ||
| - `credentials.secretAccessKey` - AWS secret key (required) | ||
|
|
||
| **Returns:** A `BedrockTextAdapter` instance. | ||
|
|
||
| ## Limitations | ||
|
|
||
| - **Structured output**: Not yet supported via the Converse API (planned). | ||
| - **Nova Micro**: Text-only; does not support image, video, or document inputs. | ||
| - **Thinking for Claude**: Only supported on the first turn of a conversation. | ||
|
|
||
| ## Next Steps | ||
|
|
||
| - [Getting Started](../getting-started/quick-start) - Learn the basics | ||
| - [Tools Guide](../guides/tools) - Learn about tools | ||
| - [Multimodal Content](../guides/multimodal-content) - Using images and documents | ||
| - [Other Adapters](./anthropic) - Explore other providers |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| # Bedrock Live Tests | ||
|
|
||
| These tests verify that the Bedrock adapter correctly handles tool calling and multimodal inputs with various models (Nova, Claude). | ||
|
|
||
| ## Setup | ||
|
|
||
| 1. Create a `.env.local` file in this directory with your AWS credentials: | ||
|
|
||
| ``` | ||
| AWS_ACCESS_KEY_ID=... | ||
| AWS_SECRET_ACCESS_KEY=... | ||
| AWS_REGION=us-east-1 | ||
| ``` | ||
|
|
||
| 2. Install dependencies: | ||
| ```bash | ||
| pnpm install | ||
| ``` | ||
|
|
||
| ## Tests | ||
|
|
||
| ### `tool-test.ts` | ||
| Tests basic tool calling with Claude 3.5 Sonnet. | ||
|
|
||
| ### `tool-test-nova.ts` | ||
| Tests Amazon Nova Pro with multimodal inputs (if applicable) and tool calling. | ||
|
|
||
| ## Running Tests | ||
|
|
||
| ```bash | ||
| # Run Claude tool test | ||
| pnpm test | ||
|
|
||
| # Run Nova tool test | ||
| pnpm test:nova | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| { | ||
| "name": "@tanstack/ai-bedrock-live-tests", | ||
| "version": "0.0.1", | ||
| "private": true, | ||
| "type": "module", | ||
| "scripts": { | ||
| "test": "tsx tool-test.ts", | ||
| "test:nova": "tsx tool-test-nova.ts" | ||
| }, | ||
| "devDependencies": { | ||
| "tsx": "^4.7.1", | ||
| "typescript": "^5.4.2", | ||
| "zod": "^4.2.1" | ||
| } | ||
| } |
86 changes: 86 additions & 0 deletions
86
packages/typescript/ai-bedrock/live-tests/tool-test-haiku.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| // import 'dotenv/config' | ||
| import { bedrockText } from '../src/bedrock-chat' | ||
| import { z } from 'zod' | ||
| import { chat } from '@tanstack/ai' | ||
|
|
||
| function throwMissingEnv(name: string): never { | ||
| throw new Error(`Missing required environment variable: ${name}`) | ||
| } | ||
|
|
||
| async function main() { | ||
| const accessKeyId = process.env.AWS_ACCESS_KEY_ID ?? throwMissingEnv('AWS_ACCESS_KEY_ID') | ||
| const secretAccessKey = process.env.AWS_SECRET_ACCESS_KEY ?? throwMissingEnv('AWS_SECRET_ACCESS_KEY') | ||
|
|
||
| const modelId = 'anthropic.claude-haiku-4-5-20251001-v1:0' | ||
| console.log(`Running tool test for: ${modelId}`) | ||
|
|
||
| const stream = await chat({ | ||
| adapter: bedrockText(modelId, { | ||
| region: process.env.AWS_REGION || 'us-east-1', | ||
| credentials: { | ||
| accessKeyId, | ||
| secretAccessKey, | ||
| }, | ||
| }), | ||
| modelOptions: { | ||
| thinking: { | ||
| type: 'enabled', | ||
| budget_tokens: 1024 | ||
| } | ||
| }, | ||
| messages: [ | ||
| { | ||
| role: 'user', | ||
| content: 'Use the `get_weather` tool to find the weather in New York and explain it.', | ||
| }, | ||
| ], | ||
| tools: [ | ||
| { | ||
| name: 'get_weather', | ||
| description: 'Get the current weather in a location', | ||
| inputSchema: z.object({ | ||
| location: z.string().describe('The city and state, e.g. New York, NY'), | ||
| }), | ||
| execute: async ({ location }) => { | ||
| console.log(`\n[TOOL Weather] Fetching weather for ${location}...`) | ||
| return { | ||
| temperature: 45, | ||
| unit: 'F', | ||
| condition: 'Cloudy', | ||
| } | ||
| }, | ||
| }, | ||
| ], | ||
| stream: true | ||
| }) | ||
|
|
||
| let finalContent = '' | ||
| let hasThinking = false | ||
| let toolCallCount = 0 | ||
|
|
||
| console.log('--- Stream Output ---') | ||
| for await (const chunk of stream) { | ||
| if (chunk.type === 'thinking') { | ||
| hasThinking = true | ||
| } else if (chunk.type === 'content') { | ||
| process.stdout.write(chunk.delta) | ||
| finalContent += chunk.delta | ||
| } else if (chunk.type === 'tool_call') { | ||
| toolCallCount++ | ||
| } | ||
| } | ||
|
|
||
| console.log('--- Results ---') | ||
| console.log('Thinking:', hasThinking) | ||
| console.log('Tool calls:', toolCallCount) | ||
| console.log('Content length:', finalContent.length) | ||
|
|
||
| if (!finalContent || finalContent.trim().length === 0) { | ||
| console.error('Test failed: No final content') | ||
| process.exit(1) | ||
| } | ||
|
|
||
| console.log('Test passed') | ||
| } | ||
|
|
||
| main().catch(console.error) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.