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
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions lambda-df-slack/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Python caches
__pycache__/
*.pyc
*.pyo

# Vendored dependencies (prevent re-commit)
src/boto3/
src/botocore/
src/urllib3/
src/s3transfer/
src/jmespath/
src/dateutil/
src/bin/
src/*.dist-info/
src/six.py

# Build artifacts
build/
terraform/build/

# Terraform
terraform/lambda_deployment.zip
terraform/*.txt
terraform/.terraform/
terraform/terraform.tfstate
terraform/terraform.tfstate.backup
terraform/*.tfplan
.terraform.lock.hcl

# Generated files
*.zip

# OS files
.DS_Store
Thumbs.db

# IDE
.idea/
.vscode/
*.swp

# Environment
.env
*.env
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.
168 changes: 168 additions & 0 deletions lambda-df-slack/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
# 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) v2.30.0+ installed and configured (v2.30.0+ required for Lambda durable functions)
* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
* [Terraform](https://developer.hashicorp.com/terraform/downloads) >= 1.5.0 installed
* [Finch](https://github.com/runfinch/finch) installed (for building the AgentCore agent container). Docker users can alias `finch` to `docker` or modify `terraform/main.tf` provisioners.
* Amazon Bedrock access enabled for **Anthropic Claude Sonnet 4** (`us.anthropic.claude-sonnet-4-6`) 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
```
> **Note:** The build script (`terraform/build.sh`) automatically installs Python dependencies into a `build/` directory during `terraform apply`. No manual dependency installation is needed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This variant of setup is very opinionated

  1. e.g. I use uv pip, not pip, so it fails -> I can fix it, but I don't think people will probably start doing this.
│ Error: local-exec provisioner error
│
│   with null_resource.lambda_build,
│   on main.tf line 401, in resource "null_resource" "lambda_build":
│  401:   provisioner "local-exec" {
│
│ Error running command 'bash ./build.sh': exit status 127. Output: Building Lambda deployment package...
│ Installing dependencies...
│ ./build.sh: line 22: pip: command not found
  1. finch does not exists
│ Error: local-exec provisioner error
│
│   with null_resource.agentcore_image_build,
│   on main.tf line 782, in resource "null_resource" "agentcore_image_build":
│  782:   provisioner "local-exec" {
│
...
│
│ # Save image digest
│ DIGEST=$(finch images --no-trunc --format '{{.ID}}' ACCOUNT_ID.dkr.ecr.us-east-2.amazonaws.com/dfs-agentcore-agent:latest)echo "$DIGEST" > ./image_digest.txt
│ echo "Image digest saved: $DIGEST"': exit status 1. Output: Login Succeeded
│ time="2026-06-23T11:04:45+02:00" level=fatal msg="instance \"finch\" does not exist, run `finch vm init` to create a new instance"

Which is not true on my machine

❯ which finch
/usr/local/bin/finch

I would recommend splitting the setup in a few separate commands (I can relate the intention to make it easy here), which gives people to a/ see whats happening and, 2/ make it easy to adopt to their local machine.


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](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/<prefix>-slack-handler --follow --region us-east-2

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

# Check DynamoDB for conversation state
aws dynamodb scan --table-name <prefix>-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