Amazon Bedrock Agents

Generative & Agentic AI · Agentic AI · Advanced · 24 min

Build a managed AWS agent from instructions, a foundation model, Lambda action groups and knowledge bases, call it with InvokeAgent, and read its trace.

A hotel clerk with a job description, a phone with speed-dial buttons to the back office, and a binder of hotel policies. Every call the clerk makes is written into a logbook you can read afterwards.

The idea in everyday words

Imagine hiring a new front-desk clerk. You give them a job description (instructions). They bring their own brain (the foundation model). You give them a phone with buttons for the kitchen and housekeeping (action groups) and a binder of hotel rules (a knowledge base). You never script every guest conversation: the clerk decides which button to press. Amazon Bedrock Agents is AWS hiring, housing and supervising that clerk for you.

What a Bedrock agent is made of

In the AI Agents lesson you wrote the think, act, observe loop yourself. With Bedrock Agents you configure the pieces and AWS runs the loop.

Piece What it is Hotel clerk version
Instructions Plain-language job description ("You help customers with orders. Never promise refunds.") The job description
Foundation model (FM) The LLM that reasons and plans, e.g. a Claude or Amazon Nova model on Bedrock The clerk's brain
Action groups Things the agent can do. Each one points at a Lambda function (or hands control back to your app) Speed-dial buttons
Knowledge bases Documents the agent can search (a Bedrock Knowledge Base over S3 files) The policy binder
Guardrail (optional) A Bedrock Guardrail that filters harmful input and output The manager listening in

Two more words you will see everywhere:

  • Session = one conversation. You choose a sessionId; the agent remembers earlier turns of the same session.
  • Trace = the agent's logbook: its reasoning, which tool it called with which inputs, and what came back.

Key idea: the model decides what to call; your Lambda decides how it is done. The model never touches your database directly.

Action groups: how the agent calls your code

You describe each action so the model knows when to use it. There are two ways:

  1. Function details: a list of functions with a name, a description and typed parameters. Simple, great for most cases.
  2. OpenAPI schema: an API spec with paths (/orders/{orderId}), methods and request bodies. Good when you already have a REST API.

Then you pick an executor: a Lambda function (AWS calls it for you) or return of control (AWS hands the call back to your application, covered below).

When the agent decides to act, Lambda receives an event and must reply in a fixed shape. For function details the important parts look like this (simplified, see the AWS docs for every field):

{
  "messageVersion": "1.0",
  "agent": { "name": "support-agent", "id": "...", "alias": "...", "version": "..." },
  "sessionId": "s-42",
  "actionGroup": "OrderTools",
  "function": "get_order_status",
  "parameters": [{ "name": "order_id", "type": "string", "value": "A1" }],
  "sessionAttributes": { "customerId": "C7" },
  "promptSessionAttributes": {}
}

Here is a handler you can run. It uses a fake event, so no AWS account is needed:

ORDERS = {"A1": "delivered", "B2": "in transit"}

def lambda_handler(event, context=None):
    params = {p["name"]: p["value"] for p in event.get("parameters", [])}
    status = ORDERS.get(params.get("order_id"), "not found")
    return {
        "messageVersion": "1.0",
        "response": {
            "actionGroup": event["actionGroup"],   # echo back what was called
            "function": event["function"],
            "functionResponse": {
                "responseBody": {"TEXT": {"body": "Order is " + status}}
            },
        },
        "sessionAttributes": event.get("sessionAttributes", {}),
    }

fake_event = {"actionGroup": "OrderTools", "function": "get_order_status",
              "parameters": [{"name": "order_id", "type": "string", "value": "A1"}],
              "sessionAttributes": {"customerId": "C7"}}
print(lambda_handler(fake_event))

The body text is what the model reads as the observation. You can also set responseState to "FAILURE" or "REPROMPT" to tell the agent the call did not work. For OpenAPI action groups the reply instead echoes apiPath and httpMethod, adds httpStatusCode, and puts the body under responseBody["application/json"].

Permissions: the Lambda needs a resource-based policy that lets bedrock.amazonaws.com invoke it, and the agent has its own IAM service role.

The orchestration loop and the trace

Each call to the agent runs through up to three stages:

  1. Pre-processing (optional): check the input is valid and on-topic.
  2. Orchestration: the loop. The FM reads the instructions, the conversation and the tool descriptions, writes a short rationale, then picks one action: call an action group, search a knowledge base, or give the final answer. The result (the observation) goes back into the prompt and the loop repeats.
  3. Post-processing (optional): polish the final answer.

That is the default orchestration: a built-in ReAct-style loop where you can override the prompt template for each stage. If that is not enough, Bedrock Agents also offers custom orchestration: you write a Lambda function (the orchestrator) that decides each step itself, for example "always look up the order before searching the policy". Check the Bedrock docs for the current options.

You call the agent from your app with the InvokeAgent API on the bedrock-agent-runtime client. The answer comes back as a stream of events: text chunks, trace events (when tracing is on) and return-of-control events.

import boto3, uuid
rt = boto3.client("bedrock-agent-runtime")

resp = rt.invoke_agent(
    agentId="AGENT_ID", agentAliasId="ALIAS_ID",
    sessionId=str(uuid.uuid4()),          # same id = same conversation
    inputText="Where is order A1 and can I return it?",
    enableTrace=True,
    sessionState={"sessionAttributes": {"customerId": "C7"}},
)
answer = ""
for event in resp["completion"]:
    if "chunk" in event:
        answer += event["chunk"]["bytes"].decode()
    elif "trace" in event:
        print(event["trace"])              # rationale, tool inputs, KB hits
print(answer)

Read the trace when something goes wrong. It shows the rationale, the exact parameters the model chose and the observation it got back. Most bugs are a vague tool description or instructions that contradict each other, and the trace makes that visible.

Session attributes, return of control and memory

Session attributes are key-value pairs that live for the whole session, for example customerId. You send them in sessionState, and they are passed to your Lambda in every event. Use them for facts your code needs (who is the user?) without trusting the model to repeat them correctly.

Prompt session attributes last for one turn and are added to the prompt, for example today's date, so the model can reason with them.

Return of control means: instead of calling Lambda, the agent stops and returns the chosen action and parameters to your application. Your app runs it and sends the result back in the next InvokeAgent call (in sessionState, with the matching invocation id). Use it when:

  • the action must run with the end user's own credentials or inside your app,
  • a human must approve first (a refund, an email to a customer),
  • the work takes longer than you want a Lambda to wait.

Memory: within a session the agent keeps the conversation. Bedrock Agents can also be configured to keep summaries across sessions for a user (you pass a memory id). Check the docs for which models support it.

Built-in actions: you can let the agent ask the user a clarifying question (user input) or run Python in a sandbox (code interpreter) without writing a Lambda.

Versions, aliases, guardrails and shipping

Editing an agent changes its working draft (DRAFT). After a change you prepare the agent so the draft can be tested (the console has a test window that talks to the draft).

To ship:

  1. Create a version: a frozen, read-only snapshot (v1, v2, ...).
  2. Point an alias (prod, staging) at a version. Your app always calls the alias.
  3. To roll back, point prod at the previous version. No app redeploy.
ba = boto3.client("bedrock-agent")      # build time (control plane)
agent = ba.create_agent(agentName="support-agent",
                        foundationModel="MODEL_ID_FROM_CONSOLE",
                        instruction="You help customers track orders...",
                        agentResourceRoleArn=ROLE_ARN)
# then: create_agent_action_group(...), associate_agent_knowledge_base(...),
#       prepare_agent(...), create_agent_alias(...)  -> see the boto3 docs

Guardrails: attach a Bedrock Guardrail (id + version) to block denied topics, filter harmful content, catch prompt attacks and mask PII on both the user input and the agent's answer.

Production checklist: tight tool descriptions, least-privilege IAM for each Lambda, guardrail attached, trace logged, an evaluation set run before each new version, and an alias per environment.

Other clouds: Azure AI Foundry Agent Service and Google Vertex AI Agent Builder are the managed equivalents; LangGraph or Strands Agents if you want to own the loop yourself.

Go deeper (engineer level)

Every orchestration step is a model call. A question that needs two tools and a KB search is roughly four FM calls plus pre- and post-processing if enabled. Latency and token cost grow with the number of steps, so the trace's step count is your first performance metric. Turn off stages you do not need.

Failure modes you will meet in production:

Failure Mechanism Defence
Tool-call loops The observation does not answer the question, so the model calls the same tool again A clear FAILURE body ("order not found, do not retry"), a cap on iterations, alarms on step count
Hallucinated arguments The model fills order_id with "my last order" Tight parameter descriptions with a format (A123), validation in Lambda, REPROMPT on bad input. Values arrive as strings: parse and check types yourself
Indirect prompt injection A KB document or a tool result says "ignore your instructions" and the model obeys Treat observations as data, keep authorisation in code, attach a guardrail, never give a tool more power than the user has
Confused deputy Your Lambda's resource policy lets bedrock.amazonaws.com invoke it from ANY agent Add AWS:SourceArn (your agent's ARN) and AWS:SourceAccount conditions
Non-idempotent retries A timeout makes the action run twice: two refunds Idempotency keys (sessionId + action + order), and return of control for money

Mutating the event is a subtle Lambda bug: warm containers reuse module-level objects, so a dict you change in place can leak into the next invocation if you ever cache it. Copy, then change.

Testing: freeze the agent as a version, replay an evaluation set of questions through the alias, and assert on the trace (which function, which parameters), not only on the final text.

Step by step

  1. Invoke:

    Your app calls InvokeAgent on alias prod with sessionId s-42, inputText 'Where is order A1 and can I return it?' and sessionAttributes {customerId: 'C7'}.

  2. Pre-process:

    The agent checks the input: it is a normal customer question, so it continues.

  3. Reason 1:

    Rationale in the trace: 'I need the order status first.' The FM picks action group OrderTools, function get_order_status, order_id = 'A1'.

  4. Act 1:

    Bedrock calls the Lambda with that event. Lambda returns responseBody.TEXT.body = 'Order A1 was delivered on 2 Nov.'

  5. Reason 2:

    Rationale: 'Now I need the return rule.' The FM queries the knowledge base with 'return window'. Top chunk: 'Returns are accepted within 30 days of delivery.'

  6. Answer:

    No more tools needed. The FM writes: 'Order A1 was delivered on 2 Nov, so you can return it until 2 Dec.' The guardrail checks it, the answer streams back as chunks, the trace shows all 2 tool steps.

Code example

# A tiny, mocked Bedrock agent: instructions + model + action group + knowledge base.
ORDERS = {"A1": "delivered on 2 Nov", "B2": "in transit"}
KB = ["Returns are accepted within 30 days of delivery.",
      "Refunds go back to the original payment method."]

def order_lambda(event):
    params = {p["name"]: p["value"] for p in event["parameters"]}
    status = ORDERS.get(params["order_id"], "not found")
    body = "Order " + params["order_id"] + " is " + status
    return {"messageVersion": "1.0",
            "response": {"actionGroup": event["actionGroup"], "function": event["function"],
                         "functionResponse": {"responseBody": {"TEXT": {"body": body}}}},
            "sessionAttributes": event.get("sessionAttributes", {})}

def kb_search(query):
    words = set(query.lower().split())
    return max(KB, key=lambda doc: len(words & set(doc.lower().split())))

def fake_model_plan(question):
    # A real foundation model makes this plan from the instructions and tool descriptions.
    q = question.lower()
    plan = []
    if "order" in q:
        plan.append(("action", "get_order_status", "A1"))
    if "return" in q:
        plan.append(("kb", "returns accepted within days", None))
    return plan

def invoke_agent(question, session_attributes):
    trace, facts = [], []
    for kind, name, arg in fake_model_plan(question):
        if kind == "action":
            event = {"actionGroup": "OrderTools", "function": name,
                     "parameters": [{"name": "order_id", "type": "string", "value": arg}],
                     "sessionAttributes": session_attributes}
            reply = order_lambda(event)
            body = reply["response"]["functionResponse"]["responseBody"]["TEXT"]["body"]
            trace.append("ACTION " + name + "(" + arg + ") -> " + body)
            facts.append(body + ".")
        else:
            hit = kb_search(name)
            trace.append("KB '" + name + "' -> " + hit)
            facts.append(hit)
    return trace, " ".join(facts)

trace, answer = invoke_agent("Where is order A1 and can I return it?", {"customerId": "C7"})
for line in trace:
    print("TRACE", line)
print("ANSWER", answer)

Interview tips

  • Walk through what happens inside one InvokeAgent call: pre-processing, the orchestration loop (rationale, action, observation), post-processing, and where the guardrail checks.

  • Explain action groups: function details vs OpenAPI schema, Lambda vs return of control, and the response shape Lambda must send back.

  • How do you pass the logged-in user's id safely? Session attributes from your backend, checked again in Lambda, never taken from the user's message.

  • How do you release a prompt change safely? Prepare the draft, test, create a version, move the staging alias, run the eval set, then move prod. Roll back by repointing the alias.

  • When would you not use Bedrock Agents? When you need custom control flow, a specific framework, or non-Bedrock models: then AgentCore or your own code.

Challenge: Action-group Lambda router

Write handle_action(event), the Lambda for a Bedrock agent action group defined with function details.

The event has actionGroup, function, parameters (a list of {"name", "type", "value"}) and maybe sessionAttributes (treat missing as {}). Use this data:

ORDERS = {"A1": "delivered", "B2": "in transit", "C3": "processing"}

Route on function:

  • "get_order_status" with order_id found → body "Order A1 is delivered." and add "lastOrderId": "A1" to the session attributes.
  • "get_order_status" with an unknown id → body "Order Z9 was not found." (session attributes unchanged).
  • "get_order_status" with no order_id parameter → body "Please provide an order id." and responseState "REPROMPT".
  • "get_return_window" → body "Returns are accepted within 30 days of delivery."
  • anything else → body "Unknown function: <name>" and responseState "FAILURE".

Return this shape (put responseState inside functionResponse only when it is set):

{"messageVersion": "1.0",
 "response": {"actionGroup": "...", "function": "...",
              "functionResponse": {"responseBody": {"TEXT": {"body": "..."}}}},
 "sessionAttributes": {...}}

Do not change the input event: copy sessionAttributes before adding to it. One test checks that the event you were given is exactly the same after your call.

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Agentic AI

Previous: Model Context Protocol (MCP) · Next: Amazon Bedrock AgentCore: Running Agents in Production