Subchapter 36.31
references/managed-knowledge-bases-retrieval.mdMarkdown9 KBView on GitHub
The AWS MCP server is recommended for executing these commands but is not required.
Retrieveuses standard AWS CLI syntax; is streaming and therefore (boto3), shown inline below.
references/bedrock-kb-migration/Scripts
Fetch Bedrock AgentAssets
Kb Shim PyAgenticRetrieveStreamOn a managed knowledge base, query with Retrieve (single-shot chunks) or AgenticRetrieveStream (agentic, streaming). RetrieveAndGenerate (a fully-synthesized answer with citations) is the Customer-managed path — see customer-managed KB retrieval. If you specifically need RetrieveAndGenerate behavior on a managed KB, verify support against the docs rather than assuming it is or isn’t available.
| API | Endpoint | When | Transport |
|---|---|---|---|
Retrieve | bedrock-agent-runtime | Single-shot chunks for your own prompt/ranking | CLI or SDK |
AgenticRetrieveStream | bedrock-agent-runtime | Agent plans → retrieves → evaluates → iterates across multiple KBs (check the quota); optional synthesized answer | SDK only (streaming; not the AWS CLI) |
RetrieveAndGenerate | bedrock-agent-runtime | Customer-managed path (synthesized answer); verify MKB support against the docs | CLI or SDK |
aws bedrock-agent-runtime retrieve --knowledge-base-id <kb-id> --retrieval-query '{"text":"<query>"}'Metadata filtering, numberOfResults, and overrideSearchType work as for other KBs — the filter operator syntax is identical to the customer-managed retrieval reference; pass it under retrievalConfiguration.vectorSearchConfiguration.filter. Metadata attributes must have been present on the ingested documents to be filterable.
The AWS CLI cannot consume the response stream, so use boto3. Requires boto3/botocore >= 1.43.64 (which includes agentic_retrieve_stream; absent below that floor) — verify your installed version.
import boto3
def agentic_retrieve(kb_ids, question, region="us-east-1", generate=True):
"""Run AgenticRetrieveStream against one or more MANAGED knowledge bases and
print the streamed answer. `kb_ids` is a list of managed KB IDs (check the service quota for the max retrievers per request)."""
if not isinstance(question, str) or not question.strip():
raise ValueError("Provide a non-empty question.")
if not kb_ids or not all(isinstance(k,
messages uses Converse-style content blocks ([{"text": ...}]).retrievers accepts multiple managed KBs (check the service quota for the max); each is {"configuration": {"knowledgeBase": {"knowledgeBaseId": ...}}}, with optional retrievalOverrides and a description.generateResponse=False returns retrieval results without a synthesized answer.result event carries the retrieved references/citations.AgenticRetrieveStream targets managed knowledge bases.policyConfiguration; check the AgenticRetrieveStream docs for which guardrail action modes (e.g. BLOCK, MASK) are supported on this path — not all modes may be available.bedrock:InvokeModel on those model ARNs.nextToken continues a multi-part response.Retrieve, RetrieveAndGenerate, AgenticRetrieveStream, GetDocumentContent, or s3:GetObject on a corpus document returns document text, and two things follow: the text lands in this conversation and its logs, and the call runs under your role rather than an end user’s, so the document-level ACLs and userContext filters the application enforces do not apply. Before any such read, ask the customer for an explicit yes to that read and give both reasons. A specific request (“show me the full text of the top document”), a query string, a Region or a general “go ahead” is not that yes; ask once and wait. Configuration reads (get-* / list-*, object listings with sizes) return no document text and need no yes. Rule: safety-and-iam (opens in a new tab) → “Content-returning reads”.userContext where the connector supports it.policyConfiguration for the synthesized response; verify which action modes (e.g. BLOCK, MASK) the API supports rather than assuming, and don’t rely on a mode you haven’t confirmed.bedrock:InvokeModel to the specific planner/reranking/embedding model ARNs used — not foundation-model/*.Retrieve / AgenticRetrieveStream are CloudTrail data events (not logged by default); enable data-event logging for AWS::Bedrock::KnowledgeBase to attribute who queried what. Always encrypt CloudWatch Logs log groups that receive Bedrock data events / retrieval traces with a customer-managed KMS key — retrieval results can expose any ingested data, not only PII.Retrieve / AgenticRetrieveStream, and apply client-side rate limiting (per-user caps) to avoid abuse and service-quota exhaustion.