Skip to main content
Article
awsaws-bedrockagent-frameworkserverlesspythonboto3api-integrationaction-groups

Build a Task-Oriented Agent with AWS Bedrock Agents

Create a serverless AI agent that can perform real-world tasks. This guide shows how to connect a large language model to a custom tool (an AWS Lambda function) using an OpenAPI schema, enabling it to act on user requests.

intermediate1 hour5 steps
The play
  1. Define the Action: Lambda & OpenAPI
    First, define what your agent can do. Create an AWS Lambda function in Python that performs a specific task (e.g., checking an order status). Then, write an OpenAPI 3.0 specification that describes how to call this function. The OpenAPI spec is the contract that AWS Bedrock Agents uses to understand the tool's capabilities, inputs, and outputs.
  2. Create the Agent in Bedrock
    Navigate to the Amazon Bedrock console, go to 'Agents', and click 'Create Agent'. Give your agent a name, an optional description, and select a foundation model (e.g., Anthropic's Claude 3 Sonnet). Most importantly, provide clear instructions in the 'Instructions for the Agent' box, like 'You are a customer service assistant. Use your tools to find the status of a customer's order.'
  3. Create and Attach an Action Group
    An Action Group links your agent to its tools. In the agent creation workflow, create a new Action Group. Name it, select the Lambda function you created in Step 1, and provide the S3 URI for the OpenAPI spec you wrote. Bedrock will parse the spec to understand the available actions.
  4. Test and Trace the Agent
    After creating the agent, use the test window in the Bedrock console. Enter a prompt like 'What is the status of order ABC-123?'. The console provides a 'trace' view that shows the agent's entire thought process: how it interprets the prompt, decides to call your tool, constructs the API call, receives the response from Lambda, and formulates a final answer. This is critical for debugging.
  5. Integrate with Boto3
    Once the agent works in the console, integrate it into your application using the AWS SDK. Use the `invoke_agent` function from the `bedrock-agent-runtime` client. You will need your agent's ID and alias ID, which are available on the agent's overview page in the Bedrock console.
Starter code
import boto3
import json
import uuid

# --- Configuration ---
# Find these values in the AWS Bedrock Agents console after creating your agent.
AWS_REGION = "us-east-1"  # Use the region where your agent is deployed
AGENT_ID = "YOUR_AGENT_ID"
AGENT_ALIAS_ID = "YOUR_AGENT_ALIAS_ID"  # Often a 10-char string like 'TSTALIASID'

# --- Boto3 Client ---
bedrock_agent_runtime = boto3.client(
    "bedrock-agent-runtime",
    region_name=AWS_REGION
)

def invoke_bedrock_agent(prompt):
    """Invokes the Bedrock agent and streams the response."""
    session_id = str(uuid.uuid4())
    print(f"Invoking agent with Session ID: {session_id}")
    print(f"\nUser > {prompt}\n")

    try:
        response = bedrock_agent_runtime.invoke_agent(
            agentId=AGENT_ID,
            agentAliasId=AGENT_ALIAS_ID,
            sessionId=session_id,
            inputText=prompt,
        )

        print("Agent > ", end="")
        final_response = ""
        # The response is a stream. Iterate over events to get the full output.
        for event in response.get("completion"):
            chunk = event["chunk"]
            chunk_bytes = chunk["bytes"]
            final_response += chunk_bytes.decode("utf-8")
            print(chunk_bytes.decode("utf-8"), end="")
        
        print("\n\n--- End of response ---")

    except Exception as e:
        print(f"Error invoking agent: {e}")

if __name__ == "__main__":
    if AGENT_ID == "YOUR_AGENT_ID" or AGENT_ALIAS_ID == "YOUR_AGENT_ALIAS_ID":
        print("Please update AGENT_ID and AGENT_ALIAS_ID in the script.")
    else:
        user_prompt = "What is the status for order ID XYZ-987?"
        invoke_bedrock_agent(user_prompt)
Build a Task-Oriented Agent with AWS Bedrock Agents — Action Pack