Hands-On: Query a Knowledge Base

Ask a question and get a grounded, cited answer in a single API call.

1 min read

Once your Knowledge Base has synced, one call to retrieve_and_generate does search, prompt building, and generation together. Note that this lives on a different client, bedrock-agent-runtime.

Try it

kb_query.py
import boto3

client = boto3.client("bedrock-agent-runtime", region_name="us-east-1")

KB_ID = "ABCDEFGHIJ"  # from the Knowledge Base console page
MODEL_ARN = "arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-opus-5-5"

response = client.retrieve_and_generate(
    input={"text": "How many vacation days do new employees get?"},
    retrieveAndGenerateConfiguration={
        "type": "KNOWLEDGE_BASE",
        "knowledgeBaseConfiguration": {
            "knowledgeBaseId": KB_ID,
            "modelArn": MODEL_ARN,
        },
    },
)

print("Answer:", response["output"]["text"])
for citation in response["citations"]:
    for ref in citation["retrievedReferences"]:
        print("Source:", ref["location"]["s3Location"]["uri"])
Tip

Want to write the prompt yourself or use a model that isn't wired into the Knowledge Base? Use retrieve instead. It returns only the matching chunks, and you pass them to converse with your own instructions.

Note

If your model needs an inference profile, use the inference profile's ARN for modelArn.

Key takeaways

  • retrieve_and_generate does search, prompt, and answer in one call.
  • Citations tell users exactly which document an answer came from.
  • Use retrieve plus converse when you want full control of the prompt.

Check your understanding

Pick an answer to see the explanation.

  1. 1. Which client do you use for Knowledge Base queries?