Bedrock agents

From frank-luongt/faos-skills-marketplace · View interactive version

Bedrock agents is an AI agent skill from the GitHub repository frank-luongt/faos-skills-marketplace. Amazon Bedrock Agents patterns for building autonomous AI agents with Claude on AWS. Use when designing agent action groups, knowledge bases, guardrails, multi-agent orchestration, or deploying production agents on Bedrock.

How to use this skill

Skill file

<!-- AUTO-GENERATED by export-skills.py — DO NOT EDIT -->


name: bedrock-agents

description: Amazon Bedrock Agents patterns for building autonomous AI agents with Claude on AWS. Use when designing agent action groups, knowledge bases, guardrails, multi-agent orchestration, or deploying production agents on Bedrock.


Platform Note: This skill was designed for multi-agent execution. In Codex, treat sub-agent instructions as sequential steps to complete thoroughly within a single agent context.

Amazon Bedrock Agents

Build production-grade autonomous AI agents on Amazon Bedrock with Claude as the foundation model.

When to Use

Core Architecture

User Query
  --> Bedrock Agent (Claude)
    --> ReAct Loop:
      1. Reason about intent
      2. Select action group or knowledge base
      3. Execute (Lambda / KB retrieval)
      4. Observe result
      5. Repeat or respond

Patterns

1. Action Group with Lambda

Action groups define tools the agent can invoke via OpenAPI schemas backed by Lambda functions.

# Lambda handler for Bedrock Agent action group
import json

def lambda_handler(event, context):
    action_group = event.get("actionGroup")
    api_path = event.get("apiPath")
    http_method = event.get("httpMethod")
    parameters = event.get("parameters", [])
    request_body = event.get("requestBody", {})

    # Route to handler based on API path
    if api_path == "/customers/{customerId}":
        customer_id = next(p["value"] for p in parameters if p["name"] == "customerId")
        result = get_customer(customer_id)
    elif api_path == "/orders":
        result = create_order(request_body)
    else:
        result = {"error": f"Unknown path: {api_path}"}

    return {
        "messageVersion": "1.0",
        "response": {
            "actionGroup": action_group,
            "apiPath": api_path,
            "httpMethod": http_method,
            "httpStatusCode": 200,
            "responseBody": {
                "application/json": {"body": json.dumps(result)}
            }
        }
    }

OpenAPI Schema for Action Group:

openapi: 3.0.0
info:
  title: Customer Service API
  version: 1.0.0
paths:
  /customers/{customerId}:
    get:
      summary: Get customer details
      operationId: getCustomer
      parameters:
        - name: customerId
          in: path
          required: true
          schema:
            type: string
          description: The unique customer identifier
      responses:
        "200":
          description: Customer details
          content:
            application/json:
              schema:
                type: object
                properties:
                  name:
                    type: string
                  email:
                    type: string
                  accountStatus:
                    type: string

2. Knowledge Base (RAG)

import boto3

bedrock_agent = boto3.client("bedrock-agent-runtime")

# Retrieve from knowledge base
response = bedrock_agent.retrieve(
    knowledgeBaseId="KB_ID",
    retrievalQuery={"text": "What is the refund policy?"},
    retrievalConfiguration={
        "vectorSearchConfiguration": {
            "numberOfResults": 5,
            "overrideSearchType": "HYBRID"  # SEMANTIC or HYBRID
        }
    }
)

# Retrieve and generate (RAG in one call)
response = bedrock_agent.retrieve_and_generate(
    input={"text": "What is the refund policy?"},
    retrieveAndGenerateConfiguration={
        "type": "KNOWLEDGE_BASE",
        "knowledgeBaseConfiguration": {
            "knowledgeBaseId": "KB_ID",
            "modelArn": "arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-3-5-sonnet-20241022-v2:0",
            "retrievalConfiguration": {
                "vectorSearchConfiguration": {
                    "numberOfResults": 5
                }
            }
        }
    }
)

Supported Data Sources:

Supported Vector Stores:

3. Multi-Agent Collaboration (Supervisor Pattern)

import boto3

bedrock_agent = boto3.client("bedrock-agent-runtime")

# Invoke supervisor agent that orchestrates sub-agents
response = bedrock_agent.invoke_agent(
    agentId="SUPERVISOR_AGENT_ID",
    agentAliasId="ALIAS_ID",
    sessionId="session-123",
    inputText="Process the insurance claim for policy #12345",
    enableTrace=True  # For debugging agent reasoning
)

# Stream response
for event in response["completion"]:
    if "chunk" in event:
        print(event["chunk"]["bytes"].decode())
    if "trace" in event:
        # Inspect agent reasoning steps
        trace = event["trace"]["trace"]
        if "orchestrationTrace" in trace:
            print(f"Agent thinking: {trace['orchestrationTrace']}")

4. Guardrails

# Apply guardrails to agent responses
guardrail_config = {
    "guardrailIdentifier": "GUARDRAIL_ID",
    "guardrailVersion": "1",
    "trace": "enabled"
}

# Guardrail capabilities:
# - Content filters (hate, violence, sexual, misconduct)
# - Denied topics (custom topic blocks)
# - Word filters (profanity, custom words)
# - PII filters (detect/redact SSN, email, phone, etc.)
# - Contextual grounding (check response is grounded in source docs)
# - Automated reasoning (formal verification of claims)

5. Return of Control (Human-in-the-Loop)

# Agent returns control to application for confirmation
response = bedrock_agent.invoke_agent(
    agentId="AGENT_ID",
    agentAliasId="ALIAS_ID",
    sessionId="session-123",
    inputText="Transfer $10,000 to account ending in 4567"
)

for event in response["completion"]:
    if "returnControl" in event:
        # Agent wants confirmation before executing
        invocation = event["returnControl"]["invocationInputs"][0]
        action = invocation["apiInvocationInput"]
        print(f"Agent wants to call: {action['apiPath']}")
        print(f"With parameters: {action['parameters']}")
        # Show to user for approval, then continue session

Anti-Patterns

Enterprise Security Checklist

References

<!-- Source: .faos/custom/skills/cloud/aws/bedrock-agents/SKILL.md -->

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.