Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
Binary file added lambda-df-slack/Architecture.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
166 changes: 166 additions & 0 deletions lambda-df-slack/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
# AWS Lambda Durable Functions to Slack via Bedrock AgentCore

This pattern demonstrates a Slack chatbot that uses AWS Lambda Durable Functions for stateful, multi-turn conversations with human-in-the-loop interactions. The bot collects travel preferences from users via Slack, generates personalized itineraries using Amazon Bedrock (Claude) through AgentCore, and delivers results back to the user — all with automatic state persistence across invocations.

Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/lambda-df-slack

Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example.

## Requirements

* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources.
* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
* [Terraform](https://developer.hashicorp.com/terraform/downloads) >= 1.5.0 installed
* [Docker](https://docs.docker.com/get-docker/) or [Finch](https://github.com/runfinch/finch) installed (for building the AgentCore agent container)
* Amazon Bedrock access enabled for **Anthropic Claude 3.5 Sonnet v2** in us-east-2
* A Slack workspace where you can create apps

## Slack Bot Setup

Follow these steps to create a Slack bot and obtain the required credentials.

### Create Slack App

1. Go to https://api.slack.com/apps
2. Click **"Create New App"** → **"From scratch"**
3. App Name: `Travel Assistant` (or your choice)
4. Select your workspace → Click **"Create App"**

### Add Bot Token Scopes

1. In the left sidebar, click **"OAuth & Permissions"**
2. Scroll to **"Scopes"** → **"Bot Token Scopes"**
3. Add these scopes:
- `app_mentions:read`
- `channels:history`
- `chat:write`
- `chat:write.public`
- `im:history`
- `im:read`
- `im:write`
- `users:read`

### Install App to Workspace

1. Scroll up to **"OAuth Tokens"** → Click **"Install to Workspace"**
2. Review permissions → Click **"Allow"**
3. Copy the **Bot User OAuth Token** (starts with `xoxb-`)

### Get Signing Secret

1. Go to **"Basic Information"** in the left sidebar
2. Under **"App Credentials"**, copy the **Signing Secret**

Save both values — you'll need them during deployment.

## Deployment Instructions

1. Clone the repository and navigate to the project directory:
```bash
git clone https://github.com/aws-samples/serverless-patterns
cd serverless-patterns/lambda-df-slack
cd terraform
```

2. Initialize and deploy:
```bash
terraform init
terraform apply -auto-approve
```
When prompted, enter:
- **prefix** - this will be the prefix for all resource names
- **slack_bot_token** - **Bot User OAuth Token** (starts with `xoxb-`)
- **slack_signing_secret** - **Signing Secret** copied earlier from **"App Credentials"**

3. Get the API Gateway URL from the output:
```bash
terraform output api_gateway_url
```

4. Configure Slack Event Subscriptions:
- Go to https://api.slack.com/apps → Select your app
- Click **"Event Subscriptions"** → Toggle **Enable Events** to ON
- Set **Request URL** to your API Gateway URL (e.g., `https://abc123.execute-api.us-east-2.amazonaws.com/prod/slack/events`)
- Wait for **"Verified ✓"**
- Under **"Subscribe to bot events"**, add: `app_mention`,`message.channels`,`message.im`
- Click **"Save Changes"**
- Go to **"Install App"** → Click **"Reinstall to Workspace"** → **"Allow"**

## How it works

![Architecture.png]

1. **Slack Handler Lambda** receives webhook events from Slack via API Gateway, verifies the request signature, deduplicates events, and starts a new Durable Function execution for new conversations.

2. **Orchestrator (Durable Function)** manages the multi-turn conversation flow. It uses `wait_for_callback()` to pause execution while waiting for user responses — the Lambda is not running during the wait. When the user replies, the callback resumes the orchestrator exactly where it left off.

3. **DynamoDB Callbacks Table** stores pending callback IDs mapped to execution IDs, enabling the Slack Handler to route incoming user messages back to the correct waiting orchestrator.

4. **AgentCore Agent** receives the collected travel preferences, invokes Amazon Bedrock (Claude) via the Strands framework to generate a personalized itinerary, and sends the result back via a durable execution callback.

5. **Slack Handler** posts the final itinerary back to the user in Slack.

The key innovation is the **wait-for-callback pattern**: the orchestrator suspends (costs nothing while waiting) and automatically resumes when the user responds — enabling multi-turn conversations without managing state manually.

## Testing

### Find Your Bot

1. Open Slack → Go to **"Apps"** in the sidebar
2. Click **"Travel Assistant"**

### Start a Conversation

Send a DM to your bot:
```
Plan a trip for me
```

**Expected response:**
```
Great! I'll help you plan an amazing trip. Let me ask you a few questions...
📍 Where would you like to go? (e.g., Japan, Paris, New York)
```

### Complete the Flow

Answer the bot's questions:
1. **Destination:** `Tokyo`
2. **Dates:** `June 1-10`
3. **Budget:** `$3000`
4. **Interests:** `food`

Wait for a ~2 minutes for Bedrock to generate the itinerary.

### Verify via CLI

```bash
# Check Slack Handler logs
aws logs tail /aws/lambda/<project>-<env>-slack-handler --follow --region us-east-2

# Check Orchestrator logs
aws logs tail /aws/lambda/<project>-<env>-orchestrator --follow --region us-east-2

# Check DynamoDB for conversation state
aws dynamodb scan --table-name <project>-<env>-callbacks --region us-east-2
```

## Cleanup

1. Delete all created resources
```bash
terraform destroy -auto-approve
```

1. During the prompts, enter all details as entered during creation.

1. Confirm all created resources has been deleted
```
terraform show
```

----
Copyright 2026 Amazon.com, Inc. or its affiliates. All Rights Reserved.

SPDX-License-Identifier: MIT-0
3 changes: 3 additions & 0 deletions lambda-df-slack/agentcore-agent/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
__pycache__
*.pyc
.DS_Store
22 changes: 22 additions & 0 deletions lambda-df-slack/agentcore-agent/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
FROM python:3.13-slim

WORKDIR /app

# Create non-root user first
RUN useradd -m -u 1000 bedrock_agentcore

# Install dependencies as root (system-wide)
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Switch to non-root user
USER bedrock_agentcore

# Expose ports for AgentCore
EXPOSE 8080 8000

# Copy application code
COPY --chown=bedrock_agentcore:bedrock_agentcore . .

# Run the agent as a module
CMD ["python", "-m", "agent"]
5 changes: 5 additions & 0 deletions lambda-df-slack/agentcore-agent/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
"""Entry point for AgentCore agent"""
from agent import app

if __name__ == "__main__":
app.run()
143 changes: 143 additions & 0 deletions lambda-df-slack/agentcore-agent/agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
"""
AgentCore Agent for Travel Itinerary Generation.
Accepts prompt + callback info, processes with Bedrock, and sends result via callback.
"""
import os
import json
import logging
import threading
import time

import boto3
from strands import Agent
from strands.models import BedrockModel
from bedrock_agentcore.runtime import BedrockAgentCoreApp

# Configure CloudWatch Logs
logger = logging.getLogger(__name__)
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

# CloudWatch logging is handled by the AgentCore runtime itself
# No need for watchtower - just use standard logging
LAMBDA_REGION = os.environ.get("AWS_REGION", "us-east-2")
logger.info("Agent module loaded")

app = BedrockAgentCoreApp()


def send_callback_success(callback_id: str, result: dict):
"""Send the result back to the durable function via callback."""
logger.info(f"Sending callback success for {callback_id[:20]}...")
lambda_client = boto3.client("lambda", region_name=LAMBDA_REGION)
lambda_client.send_durable_execution_callback_success(
CallbackId=callback_id,
Result=json.dumps(result),
)
logger.info("Callback sent successfully")


def send_callback_failure(callback_id: str, error: str):
"""Send error back to the durable function."""
logger.error(f"Sending callback failure: {error}")
lambda_client = boto3.client("lambda", region_name=LAMBDA_REGION)
lambda_client.send_durable_execution_callback_failure(
CallbackId=callback_id,
Error={"errorMessage": error, "errorType": "AgentError"},
)


def run_agent(prompt: str, model_id: str, callback_id: str, task_id: str, system_prompt: str = None):
"""Invoke Bedrock via Strands Agent and send result back via durable callback."""
try:
logger.info(f"Starting agent with model {model_id}")

model = BedrockModel(
model_id=model_id,
max_tokens=8192, # Increased for detailed itineraries
temperature=0.8,
)

default_system = """You are a knowledgeable travel advisor who creates detailed,
personalized travel itineraries. Provide practical, specific recommendations with
clear day-by-day plans. Be helpful, enthusiastic, and concise."""

agent = Agent(
model=model,
system_prompt=system_prompt or default_system,
)

logger.info("Invoking Bedrock model...")
result = agent(prompt)
answer = str(result)

logger.info(f"LLM completed, generated {len(answer)} characters")
send_callback_success(callback_id, {"itinerary": answer})

except Exception as e:
logger.error(f"Agent failed: {e}", exc_info=True)
send_callback_failure(callback_id, str(e))
finally:
app.complete_async_task(task_id)


@app.entrypoint
def entrypoint(payload):
"""
Main entrypoint invoked by AgentCore Runtime.

Expects payload:
- prompt: travel planning prompt
- callbackId: durable execution callback ID
- model (optional): { modelId: "..." }
- systemPrompt (optional): custom system prompt

Returns confirmation immediately, then processes in background.
"""
prompt = payload.get("prompt", "")
callback_id = payload.get("callbackId")
model_config = payload.get("model", {})
system_prompt = payload.get("systemPrompt")

model_id = model_config.get(
"modelId",
"us.anthropic.claude-sonnet-4-6"
)

if not callback_id:
logger.error("Missing callbackId in payload")
return {"error": "Missing callbackId in payload"}

if not prompt:
logger.error("Missing prompt in payload")
return {"error": "Missing prompt in payload"}

logger.info(f"Received request with callback {callback_id[:20]}...")

# Track the async task so /ping reports HealthyBusy
task_id = app.add_async_task("itinerary_generation", {
"prompt": prompt[:100] + "..." if len(prompt) > 100 else prompt,
"callbackId": callback_id[:20] + "...",
})

# Run the LLM work in background thread
threading.Thread(
target=run_agent,
args=(prompt, model_id, callback_id, task_id, system_prompt),
daemon=True,
).start()

logger.info("Request accepted, processing in background")

# Return confirmation immediately
return {
"status": "accepted",
"message": "Generating itinerary, will callback when complete",
"callbackId": callback_id,
}


if __name__ == "__main__":
app.run()
4 changes: 4 additions & 0 deletions lambda-df-slack/agentcore-agent/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
strands-agents
bedrock-agentcore
boto3
aws-durable-execution-sdk-python
Loading