<!-- 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.
tags: [aws, bedrock, agents, claude]
---

# Amazon Bedrock Agents

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

## When to Use

- Designing AI agents that call enterprise APIs via Lambda action groups
- Building RAG pipelines with Bedrock Knowledge Bases
- Implementing multi-agent orchestration (supervisor/worker patterns)
- Adding guardrails for PII redaction, content filtering, and grounding checks
- Deploying agents with VPC endpoints, IAM, and CloudTrail for regulated industries

## 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.

```python
# 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:**
```yaml
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)

```python
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:**
- Amazon S3 (PDF, TXT, HTML, Markdown, CSV, DOCX, XLSX)
- Web crawlers
- Confluence
- SharePoint
- Salesforce
- Custom (via Lambda connector)

**Supported Vector Stores:**
- Amazon OpenSearch Serverless (default, fully managed)
- Amazon Aurora PostgreSQL (pgvector)
- Pinecone
- Redis Enterprise Cloud
- MongoDB Atlas

### 3. Multi-Agent Collaboration (Supervisor Pattern)

```python
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

```python
# 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)

```python
# 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

- Calling Bedrock models directly when you need tool orchestration -- use Agents instead
- Storing secrets in action group OpenAPI schemas -- use Lambda environment variables + Secrets Manager
- Creating one massive action group -- split by domain (CRM, ERP, ITSM)
- Skipping guardrails in regulated industries -- always enable PII filtering and grounding checks
- Using synchronous invocation for long-running tasks -- use async with session state

## Enterprise Security Checklist

- [ ] VPC endpoints configured (no public internet for model calls)
- [ ] IAM roles follow least-privilege principle
- [ ] CloudTrail logging enabled for all Bedrock API calls
- [ ] Guardrails configured for PII redaction
- [ ] Knowledge base data encrypted with KMS CMK
- [ ] Agent session data retention policy defined

## References

- [Amazon Bedrock Agents Documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/agents.html)
- [Bedrock Agent Samples (GitHub)](https://github.com/awslabs/amazon-bedrock-agent-samples)
- [AWS MCP Servers](https://github.com/awslabs/mcp)
- [Bedrock Guardrails](https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails.html)

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