Guide · Amazon Bedrock Flows
Bedrock Flows with Knowledge Bases — KnowledgeBaseNode, StorageNode, retrieval chains for MCP servers
Bedrock Flows has native nodes for both Knowledge Base retrieval (KnowledgeBase node type) and S3 object storage (Storage node type), which together let you build retrieval-augmented generation pipelines entirely in the flow graph without custom Lambda code. The KnowledgeBaseNode queries a Bedrock Knowledge Base and returns either raw retrieved chunks or a generated response (depending on configuration), while the StorageNode reads and writes S3 objects — useful for caching intermediate results across flow invocations, persisting conversation state, or passing large payloads between flows. This guide covers both node types in detail, including the exact output shapes from KnowledgeBaseNode (which differ between retrieval-only and retrieve-and-generate modes), the gotcha that StorageNode S3 URI must include an object key (not just a bucket prefix), and how to wire multiple Knowledge Bases through a ConditionNode to route queries to the right data source based on content.
TL;DR
KnowledgeBaseNode has two modes: retrieval-only (output: outputText as a concatenated string) and retrieve-and-generate (output: outputText as a generated response). Use retrieval-only when you want to inject chunks into your own PromptNode — it gives you finer control over the generation prompt. StorageNode requires a full S3 URI including object key (s3://bucket/path/key.json), not just the bucket. The execution role needs s3:GetObject and s3:PutObject on the specific key, not s3:* on the bucket. The body output from StorageNode is always a String — parse it in a LambdaFunctionNode if you need a typed object.
KnowledgeBaseNode: two retrieval modes
KnowledgeBaseNode has two operating modes controlled by whether you include a modelArn in the configuration. Without modelArn, the node retrieves chunks and returns them as a concatenated text string. With modelArn, the node runs a full retrieve-and-generate pass internally and returns the generated answer.
Retrieval-only mode (recommended for RAG chains)
const kbRetrievalNode = {
name: 'DocumentRetrieval',
type: 'KnowledgeBase',
configuration: {
knowledgeBase: {
knowledgeBaseId: 'ABCDEF1234', // from CreateKnowledgeBaseCommand
// No modelArn = retrieval only
},
},
inputs: [
{
name: 'retrievalQuery', // the search query
type: 'String',
expression: '$.data',
},
],
outputs: [
{ name: 'outputText', type: 'String' }, // concatenated chunks
],
};
In retrieval-only mode, outputText is a single String containing the retrieved chunks concatenated with newlines. The node does not expose individual chunks with scores or metadata — if you need per-chunk scoring or citation metadata, use the Bedrock Runtime RetrieveCommand in a LambdaFunctionNode instead.
The number of chunks retrieved defaults to the Knowledge Base's default configuration. You cannot override numberOfResults in the KnowledgeBaseNode definition — it uses whatever is set on the Knowledge Base resource. Configure the retrieval count in the Knowledge Base's storage configuration before creating the flow.
Retrieve-and-generate mode
const kbRagNode = {
name: 'DocumentRAG',
type: 'KnowledgeBase',
configuration: {
knowledgeBase: {
knowledgeBaseId: 'ABCDEF1234',
// modelArn = retrieve-and-generate internally
modelArn: 'arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-3-haiku-20240307-v1:0',
},
},
inputs: [
{
name: 'retrievalQuery',
type: 'String',
expression: '$.data',
},
],
outputs: [
{ name: 'outputText', type: 'String' }, // generated answer, not raw chunks
],
};
In retrieve-and-generate mode, the KnowledgeBaseNode runs RetrieveAndGenerateCommand internally. The output is the model's generated response grounded in the retrieved documents. Use this mode when you want the simplest possible RAG result without prompt engineering — the model uses Bedrock's default RAG system prompt. Use retrieval-only + PromptNode when you need control over the system prompt, temperature, or response format.
Wiring a RAG chain: retrieval-only + PromptNode
The recommended RAG pattern in Bedrock Flows retrieves chunks in a KnowledgeBaseNode and passes them as context into a PromptNode. This gives you full control over the generation model, prompt template, temperature, and output format:
// Full flow definition for a retrieval-augmented QA pipeline
const ragFlowDefinition = {
nodes: [
{
name: 'FlowInputNode',
type: 'Input',
outputs: [{ name: 'document', type: 'String' }],
},
{
name: 'KBRetrieval',
type: 'KnowledgeBase',
configuration: {
knowledgeBase: {
knowledgeBaseId: process.env.KB_ID,
},
},
inputs: [
{ name: 'retrievalQuery', type: 'String', expression: '$.data' },
],
outputs: [
{ name: 'outputText', type: 'String' },
],
},
{
name: 'QAGeneration',
type: 'Prompt',
configuration: {
prompt: {
sourceConfiguration: {
inline: {
modelId: 'anthropic.claude-3-sonnet-20240229-v1:0',
templateType: 'TEXT',
templateConfiguration: {
text: {
text: `You are a helpful assistant. Use ONLY the following context to answer the question.
If the context does not contain enough information to answer, say "I don't have enough information."
Context:
{{context}}
Question: {{question}}
Answer:`,
inputVariables: [
{ name: 'context' },
{ name: 'question' },
],
},
},
inferenceConfiguration: {
text: {
maxTokens: 512,
temperature: 0.1,
},
},
},
},
},
},
inputs: [
{ name: 'context', type: 'String', expression: '$.data' }, // from KBRetrieval
{ name: 'question', type: 'String', expression: '$.data' }, // from FlowInput
],
outputs: [
{ name: 'modelCompletion', type: 'String' },
],
},
{
name: 'FlowOutputNode',
type: 'Output',
inputs: [
{ name: 'document', type: 'String', expression: '$.data' },
],
},
],
connections: [
// Input → KB (use the question as the retrieval query)
{
name: 'InputToKB',
source: 'FlowInputNode',
target: 'KBRetrieval',
type: 'Data',
configuration: { data: { sourceOutput: 'document', targetInput: 'retrievalQuery' } },
},
// KB chunks → Prompt context variable
{
name: 'KBToPromptContext',
source: 'KBRetrieval',
target: 'QAGeneration',
type: 'Data',
configuration: { data: { sourceOutput: 'outputText', targetInput: 'context' } },
},
// Input question → Prompt question variable
{
name: 'InputToPromptQuestion',
source: 'FlowInputNode',
target: 'QAGeneration',
type: 'Data',
configuration: { data: { sourceOutput: 'document', targetInput: 'question' } },
},
// Prompt answer → Output
{
name: 'PromptToOutput',
source: 'QAGeneration',
target: 'FlowOutputNode',
type: 'Data',
configuration: { data: { sourceOutput: 'modelCompletion', targetInput: 'document' } },
},
],
};
The flow receives the user's question, retrieves relevant document chunks from the KB, then passes both the retrieved context and the original question into the PromptNode as separate variables. From an MCP server, the tool call is a single InvokeFlowCommand with the question as inputs[0].content.document.
Multi-KB routing with ConditionNode
When your MCP server needs to route queries to different Knowledge Bases based on domain (e.g., technical docs vs. HR policies vs. product catalog), combine a ConditionNode with multiple KnowledgeBaseNodes. Each condition branch routes to the appropriate KB:
// Multi-KB flow: route queries to domain-specific knowledge bases
const multiKbNodes = [
{
name: 'FlowInputNode',
type: 'Input',
outputs: [{ name: 'document', type: 'Object' }],
},
// A LambdaFunctionNode extracts the domain tag from the input object
{
name: 'DomainExtractor',
type: 'LambdaFunction',
configuration: {
lambdaFunction: {
lambdaArn: 'arn:aws:lambda:us-east-1:123456789012:function:extract-domain',
},
},
inputs: [
{ name: 'payload', type: 'Object', expression: '$.data' },
],
outputs: [
{ name: 'functionResponse', type: 'String' }, // 'technical' | 'hr' | 'product'
],
},
// ConditionNode routes on domain string
{
name: 'DomainRouter',
type: 'Condition',
configuration: {
condition: {
conditions: [
{ name: 'isTechnical', expression: "$.data == 'technical'" },
{ name: 'isHR', expression: "$.data == 'hr'" },
{ name: 'default' },
],
},
},
inputs: [
{ name: 'domain', type: 'String', expression: '$.data' },
],
},
// Three separate KnowledgeBaseNodes
{
name: 'TechnicalKB',
type: 'KnowledgeBase',
configuration: {
knowledgeBase: { knowledgeBaseId: process.env.TECHNICAL_KB_ID },
},
inputs: [{ name: 'retrievalQuery', type: 'String', expression: '$.data.query' }],
outputs: [{ name: 'outputText', type: 'String' }],
},
{
name: 'HumanResourcesKB',
type: 'KnowledgeBase',
configuration: {
knowledgeBase: { knowledgeBaseId: process.env.HR_KB_ID },
},
inputs: [{ name: 'retrievalQuery', type: 'String', expression: '$.data.query' }],
outputs: [{ name: 'outputText', type: 'String' }],
},
{
name: 'ProductCatalogKB',
type: 'KnowledgeBase',
configuration: {
knowledgeBase: { knowledgeBaseId: process.env.PRODUCT_KB_ID },
},
inputs: [{ name: 'retrievalQuery', type: 'String', expression: '$.data.query' }],
outputs: [{ name: 'outputText', type: 'String' }],
},
// Shared PromptNode — all three branches converge here
{
name: 'GenerationPrompt',
type: 'Prompt',
// ... prompt configuration ...
inputs: [
{ name: 'context', type: 'String', expression: '$.data' },
{ name: 'question', type: 'String', expression: '$.data.query' },
],
outputs: [{ name: 'modelCompletion', type: 'String' }],
},
{
name: 'FlowOutputNode',
type: 'Output',
inputs: [{ name: 'document', type: 'String', expression: '$.data' }],
},
];
The critical connection detail: use type: 'Conditional' for the ConditionNode → KnowledgeBaseNode connections, and type: 'Data' for all KB → PromptNode connections. The flow graph diverges at the ConditionNode and re-converges at the shared PromptNode.
The input to the multi-KB flow is an Object: { query: "user's question", domain: "technical" }. Notice the KnowledgeBaseNode inputs use expression: '$.data.query' to extract the query subfield — but they receive the input from the ConditionNode which passes its entire incoming value through. The incoming value to the ConditionNode is the domain string from DomainExtractor, not the original Object. This is a common design error: the original Object needs to flow in parallel to the KBs, not through the ConditionNode. The ConditionNode should receive the domain tag, while the KBs receive the query directly from FlowInputNode via separate Data connections.
StorageNode: S3 read and write
StorageNode reads from or writes to an S3 object. It is useful for caching expensive intermediate results (such as retrieved chunks or model outputs) so that subsequent flow invocations skip the retrieval step for identical queries, or for passing large payloads between flows that exceed the InvokeFlow input size limit.
Write (put) mode
const storageWriteNode = {
name: 'CacheWrite',
type: 'Storage',
configuration: {
storage: {
serviceConfiguration: {
s3: {
bucketName: 'my-flow-cache-bucket',
objectKey: 'cache/{{cacheKey}}.json', // key with dynamic segment
},
},
},
},
inputs: [
{
name: 'objectBody', // the content to write
type: 'String',
expression: '$.data',
},
{
name: 'writeAction', // must be 'put' for write
type: 'String',
expression: "'put'", // literal string — use single quotes in expression
},
],
outputs: [
// No meaningful output from write — flow continues after the write completes
],
};
Read (get) mode
const storageReadNode = {
name: 'CacheRead',
type: 'Storage',
configuration: {
storage: {
serviceConfiguration: {
s3: {
bucketName: 'my-flow-cache-bucket',
objectKey: 'cache/cached-retrieval.json',
},
},
},
},
inputs: [
{
name: 'readAction',
type: 'String',
expression: "'get'",
},
],
outputs: [
{ name: 'body', type: 'String' }, // S3 object contents as String
],
};
Important constraints for StorageNode:
- The
objectKeymust be a full object key, not a prefix.'cache/'will fail — it must be'cache/results.json'or similar. Dynamic keys are not supported in the node configuration — use a LambdaFunctionNode before StorageNode if you need to compute the key at runtime. - The
bodyoutput is always a String. If you stored a JSON object, you receive it back as the JSON string. Use a LambdaFunctionNode downstream toJSON.parseit if you need an Object-typed value for downstream nodes. - The execution role needs
s3:GetObjectands3:PutObjecton the specific bucket and key path. Use an IAM condition likes3:prefix: ['cache/']to scope it tightly rather than granting on the whole bucket. - StorageNode does not handle missing keys gracefully. A
geton a non-existent key causes aninternalServerExceptionin the response stream. Implement cache existence checks in a LambdaFunctionNode before the StorageNode read if cache misses are expected. - Object size limit: StorageNode is intended for small-to-medium payloads (a few KB to low MB). For large payloads, store a pointer (S3 presigned URL or object key) in the flow and retrieve the actual content in a LambdaFunctionNode.
Caching KB retrieval results with StorageNode
A common optimization for flows that answer the same questions repeatedly is to cache retrieval results in S3. The pattern uses a ConditionNode to decide whether to read from cache or query the KB, and a StorageNode write to populate the cache on a miss:
// Conceptual flow: check S3 cache → if hit, return cached → if miss, retrieve + cache
//
// Flow inputs: { query: string, cacheKey: string }
//
// Nodes:
// 1. FlowInputNode (Object input)
// 2. CacheCheckLambda — tries HeadObject on S3; returns { hit: bool, cacheKey }
// 3. CacheRouter (ConditionNode) — routes on $.data.hit
// Branch 'cacheHit' → CacheReadNode → GenerationPrompt
// Branch 'cacheMiss' → KBRetrieval → CacheWriteLambda → GenerationPrompt
// 4. GenerationPrompt — shared by both branches (receives context String)
// 5. FlowOutputNode
// CacheCheckLambda handler example:
export async function handler(event: BedrockFlowLambdaEvent) {
const payload = event.inputs.find(i => i.name === 'payload')?.value as {
query: string;
cacheKey: string;
};
const { S3Client, HeadObjectCommand } = await import('@aws-sdk/client-s3');
const s3 = new S3Client({ region: process.env.AWS_REGION });
try {
await s3.send(new HeadObjectCommand({
Bucket: process.env.CACHE_BUCKET!,
Key: `cache/${payload.cacheKey}.json`,
}));
return { hit: true, cacheKey: payload.cacheKey, query: payload.query };
} catch {
return { hit: false, cacheKey: payload.cacheKey, query: payload.query };
}
}
This pattern reduces KB query costs and latency for high-traffic flows. The cache hit rate depends on how well you normalize the cache key — use a hash of the semantic query rather than the raw string to improve hit rates across paraphrased questions.
IAM permissions for KB and storage nodes
The flow execution role requires specific permissions for each node type. Here is the minimal policy for a flow with one KnowledgeBaseNode (retrieval-only) and one StorageNode (read + write):
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "BedrockKBRetrieval",
"Effect": "Allow",
"Action": "bedrock:Retrieve",
"Resource": "arn:aws:bedrock:us-east-1:123456789012:knowledge-base/ABCDEF1234"
},
{
"Sid": "BedrockModelInvoke",
"Effect": "Allow",
"Action": ["bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream"],
"Resource": "arn:aws:bedrock:us-east-1::foundation-model/*"
},
{
"Sid": "S3CacheAccess",
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject"],
"Resource": "arn:aws:s3:::my-flow-cache-bucket/cache/*"
},
{
"Sid": "S3CacheList",
"Effect": "Allow",
"Action": "s3:ListBucket",
"Resource": "arn:aws:s3:::my-flow-cache-bucket",
"Condition": {
"StringLike": { "s3:prefix": "cache/*" }
}
}
]
}
For retrieve-and-generate mode on the KnowledgeBaseNode (when modelArn is set), add bedrock:RetrieveAndGenerate to the KB statement — the node calls that API internally, not bedrock:Retrieve.
Common failure modes with KB and storage nodes
| Error | Cause | Fix |
|---|---|---|
KnowledgeBaseNode returns empty outputText |
No documents in the KB matched the query above the relevance threshold, or the KB is not in ACTIVE status | Verify KB is in ACTIVE status (GetKnowledgeBaseCommand); lower the relevance threshold in KB configuration; test the KB separately with RetrieveCommand |
AccessDeniedException on KnowledgeBaseNode |
Execution role missing bedrock:Retrieve or bedrock:RetrieveAndGenerate |
Add the missing permission to the execution role; ensure the KB ARN in the policy matches exactly |
StorageNode read fails with internalServerException |
S3 object key does not exist (cache miss handled as error) | Use a LambdaFunctionNode before the StorageNode to check existence with HeadObjectCommand; route via ConditionNode on cache hit/miss |
PromptNode receives null context from KBRetrieval |
Expression mismatch — PromptNode context input expression doesn't match KBRetrieval's output name | Verify the connection sourceOutput: 'outputText' and PromptNode input name 'context' both match; double-check the expression $.data is on the PromptNode input |
Flow PrepareFlow fails with KnowledgeBase not found |
knowledgeBaseId doesn't exist in the same region as the flow |
Knowledge Bases and flows must be in the same region; verify with ListKnowledgeBasesCommand |
| StorageNode writes empty objects | objectBody input receives null (expression error) instead of actual content |
Trace the flow with flowTraceEvent logging enabled to see what value reaches the StorageNode input; fix the upstream expression |