Bedrock Knowledge Bases Basics
Create a Knowledge Base over an S3 data source via SDK.
Busca en todas las páginas de la documentación
Create a Knowledge Base over an S3 data source via SDK.
This page walks the full lifecycle in order: create the Knowledge Base, attach an S3 Data Source, run ingestion, then query it two ways. Each example builds on IDs returned by the last, so read them top to bottom the first time.
pip install boto3 (boto3 1.43.x, Python 3.10+). TypeScript: npm install @aws-sdk/client-bedrock-agent @aws-sdk/client-bedrock-agent-runtime (Node.js 18+).bedrock-agent control-plane permissions (CreateKnowledgeBase, CreateDataSource, StartIngestionJob, GetIngestionJob) to build, and bedrock-agent-runtime permissions (Retrieve, RetrieveAndGenerate) to query.us-east-1.Point it at an embedding model and a vector store.
# --- Python (boto3) ---
import boto3
agent = boto3.client("bedrock-agent", region_name="us-east-1")
kb = agent.create_knowledge_base(
name="support-docs-kb",
roleArn="arn:aws:iam::123456789012:role/BedrockKBServiceRole",
knowledgeBaseConfiguration={
"type": "VECTOR",
"vectorKnowledgeBaseConfiguration": {
"embeddingModelArn": "arn:aws:bedrock:us-east-1::foundation-model/amazon.titan-embed-text-v2:0",
},
},
storageConfiguration={
"type": "OPENSEARCH_SERVERLESS",
"opensearchServerlessConfiguration": {
"collectionArn": "arn:aws:aoss:us-east-1:123456789012:collection/abc123",
"vectorIndexName": "support-docs-index",
"fieldMapping": {"vectorField": "embedding", "textField": "text", "metadataField": "metadata"},
},
},
)
kb_id = kb["knowledgeBase"]["knowledgeBaseId"]
print("Knowledge Base:", kb_id)// --- TypeScript (AWS SDK v3) ---
import { BedrockAgentClient, CreateKnowledgeBaseCommand } from "@aws-sdk/client-bedrock-agent";
const agent = new BedrockAgentClient({ region: "us-east-1" });
const kb = await agent.send(new CreateKnowledgeBaseCommand({
name: "support-docs-kb",
roleArn: "arn:aws:iam::123456789012:role/BedrockKBServiceRole",
knowledgeBaseConfiguration: {
type: "VECTOR",
vectorKnowledgeBaseConfiguration: {
embeddingModelArn: "arn:aws:bedrock:us-east-1::foundation-model/amazon.titan-embed-text-v2:0",
},
},
storageConfiguration: {
type: "OPENSEARCH_SERVERLESS",
opensearchServerlessConfiguration: {
collectionArn: "arn:aws:aoss:us-east-1:123456789012:collection/abc123",
vectorIndexName: "support-docs-index",
fieldMapping: { vectorField: "embedding", textField: "text", metadataField: "metadata" },
},
},
}));
const kbId = kb.knowledgeBase?.knowledgeBaseId;
console.log("Knowledge Base:", kbId);knowledgeBaseConfiguration picks the embedding model; storageConfiguration picks and configures the vector store.roleArn service role must have read access to the eventual Data Source and permission to invoke the embedding model.Tell the Knowledge Base where its documents live.
# --- Python (boto3) ---
ds = agent.create_data_source(
knowledgeBaseId=kb_id,
name="support-docs-s3",
dataSourceConfiguration={
"type": "S3",
"s3Configuration": {"bucketArn": "arn:aws:s3:::my-support-docs"},
},
)
data_source_id = ds["dataSource"]["dataSourceId"]
print("Data Source:", data_source_id)// --- TypeScript (AWS SDK v3) ---
import { CreateDataSourceCommand } from "@aws-sdk/client-bedrock-agent";
const ds = await agent.send(new CreateDataSourceCommand({
knowledgeBaseId: kbId,
name: "support-docs-s3",
dataSourceConfiguration: {
type: "S3",
s3Configuration: { bucketArn: "arn:aws:s3:::my-support-docs" },
},
}));
const dataSourceId = ds.dataSource?.dataSourceId;
console.log("Data Source:", dataSourceId);bucketArn (not a bucket name string) is what the API expects.Trigger the read-chunk-embed-store pipeline, then wait for it to finish.
# --- Python (boto3) ---
import time
job = agent.start_ingestion_job(knowledgeBaseId=kb_id, dataSourceId=data_source_id)
job_id = job["ingestionJob"]["ingestionJobId"]
while True:
status = agent.get_ingestion_job(
knowledgeBaseId=kb_id, dataSourceId=data_source_id, ingestionJobId=job_id,
)["ingestionJob"]
print("status:", status["status"])
if status["status"] in ("COMPLETE", "FAILED"):
break
time.sleep(5)// --- TypeScript (AWS SDK v3) ---
import { StartIngestionJobCommand, GetIngestionJobCommand } from "@aws-sdk/client-bedrock-agent";
const job = await agent.send(new StartIngestionJobCommand({ knowledgeBaseId: kbId, dataSourceId }));
const jobId = job.ingestionJob?.ingestionJobId;
let status = "STARTING";
while (status !== "COMPLETE" && status !== "FAILED") {
const check = await agent.send(new GetIngestionJobCommand({
knowledgeBaseId: kbId, dataSourceId, ingestionJobId: jobId,
}));
status = check.ingestionJob!.status!;
console.log("status:", status);
if (status !== "COMPLETE" && status !== "FAILED") await new Promise(r => setTimeout(r, 5000));
}StartIngestionJob returns immediately with a job id; the actual work runs asynchronously.GetIngestionJob until status is COMPLETE (or FAILED) - a Knowledge Base is not reliably queryable before that.Query the Knowledge Base and get ranked source passages back, no generation involved.
# --- Python (boto3) ---
agent_rt = boto3.client("bedrock-agent-runtime", region_name="us-east-1")
resp = agent_rt.retrieve(
knowledgeBaseId=kb_id,
retrievalQuery={"text": "How long does a refund take?"},
retrievalConfiguration={"vectorSearchConfiguration": {"numberOfResults": 3}},
)
for r in resp["retrievalResults"]:
print(round(r["score"], 3), "-", r["content"]["text"][:100])// --- TypeScript (AWS SDK v3) ---
import { BedrockAgentRuntimeClient, RetrieveCommand } from "@aws-sdk/client-bedrock-agent-runtime";
const agentRt = new BedrockAgentRuntimeClient({ region: "us-east-1" });
const resp = await agentRt.send(new RetrieveCommand({
knowledgeBaseId: kbId,
retrievalQuery: { text: "How long does a refund take?" },
retrievalConfiguration: { vectorSearchConfiguration: { numberOfResults: 3 } },
}));
for (const r of resp.retrievalResults ?? []) {
console.log(r.score?.toFixed(3), "-", r.content?.text?.slice(0, 100));
}Retrieve is a bedrock-agent-runtime call - the data-plane client, separate from the control-plane client used above.score, the passage content.text, and a location pointing back to the source document.numberOfResults caps how many passages come back; start small and raise it based on evals.Combine retrieval and generation into a single managed call.
# --- Python (boto3) ---
resp = agent_rt.retrieve_and_generate(
input={"text": "How long does a refund take?"},
retrieveAndGenerateConfiguration={
"type": "KNOWLEDGE_BASE",
"knowledgeBaseConfiguration": {
"knowledgeBaseId": kb_id,
"modelArn": "arn:aws:bedrock:us-east-1::foundation-model/amazon.nova-lite-v1:0",
},
},
)
print(resp["output"]["text"])// --- TypeScript (AWS SDK v3) ---
import { RetrieveAndGenerateCommand } from "@aws-sdk/client-bedrock-agent-runtime";
const resp = await agentRt.send(new RetrieveAndGenerateCommand({
input: { text: "How long does a refund take?" },
retrieveAndGenerateConfiguration: {
type: "KNOWLEDGE_BASE",
knowledgeBaseConfiguration: {
knowledgeBaseId: kbId,
modelArn: "arn:aws:bedrock:us-east-1::foundation-model/amazon.nova-lite-v1:0",
},
},
}));
console.log(resp.output?.text);output.text is the final answer.citations, each linking part of the answer back to a retrieved passage - do not discard them.modelArn is the generation model, independent of the embedding model chosen at Knowledge Base creation.Related: RetrieveAndGenerate vs Retrieve-Then-Prompt - when each pattern wins.
Discover IDs instead of hardcoding them.
# --- Python (boto3) ---
for kb_summary in agent.list_knowledge_bases()["knowledgeBaseSummaries"]:
print(kb_summary["knowledgeBaseId"], "-", kb_summary["name"], "-", kb_summary["status"])
for ds_summary in agent.list_data_sources(knowledgeBaseId=kb_id)["dataSourceSummaries"]:
print(ds_summary["dataSourceId"], "-", ds_summary["name"])// --- TypeScript (AWS SDK v3) ---
import { ListKnowledgeBasesCommand, ListDataSourcesCommand } from "@aws-sdk/client-bedrock-agent";
const kbs = await agent.send(new ListKnowledgeBasesCommand({}));
for (const s of kbs.knowledgeBaseSummaries ?? []) console.log(s.knowledgeBaseId, "-", s.name, "-", s.status);
const dss = await agent.send(new ListDataSourcesCommand({ knowledgeBaseId: kbId }));
for (const s of dss.dataSourceSummaries ?? []) console.log(s.dataSourceId, "-", s.name);status on a Knowledge Base summary reports whether it is ACTIVE, still creating, or failed.Related: Managed RAG on Bedrock: What the Knowledge Base Owns - the mental model behind these calls.
Stack versions: This page was written for boto3 1.43.x (Python 3.10+) and the AWS SDK for JavaScript v3 (Node.js 18+). Bedrock Knowledge Bases' Agentic Retriever is a fast-evolving 2026 capability - verify exact parameters against current docs.
Revisado por Chris St. John·Última actualización: 24 jul 2026