Sign inSign up

anvesh35/bedrock-chatbot

By anvesh35

โ€ขUpdated 12 months ago

bedrock-chatbot

Image
0

257

anvesh35/bedrock-chatbot repository overview

โ ๐Ÿค– Amazon Bedrock Chatbot with Memory

Level: Intermediate | Duration: 60 minutes | Cost: ~$3.00

Build an intelligent chatbot with conversation memory using Amazon Bedrock, LangChain, and Streamlit. Deploy it on AWS ECS with complete infrastructure as code.

โ ๐ŸŽฏ What You'll Build

  • Intelligent Chatbot with conversation memory and context awareness
  • Streamlit Web Interface for interactive chat experience
  • AWS ECS Deployment with Application Load Balancer
  • Conversation Memory using LangChain's ConversationSummaryBufferMemory
  • Production-Ready Infrastructure with CDK

โ ๐Ÿ—๏ธ Architecture Overview

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   User Browser  โ”‚โ”€โ”€โ”€โ–บโ”‚  Application    โ”‚โ”€โ”€โ”€โ–บโ”‚   ECS Fargate   โ”‚
โ”‚                 โ”‚    โ”‚  Load Balancer  โ”‚    โ”‚   Container     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                                        โ”‚
                                                        โ–ผ
                                               โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                                               โ”‚  Amazon Bedrock โ”‚
                                               โ”‚  (Claude/Nova)  โ”‚
                                               โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

โ ๐Ÿ“‹ Table of Contents

โ โœ… Prerequisites

โ Required Tools
# AWS CLI v2
aws --version

# AWS CDK
npm install -g aws-cdk
cdk --version

# Python 3.11+
python --version

# Docker
docker --version
โ AWS Account Setup
  • โœ… AWS Account with appropriate permissions
  • โœ… AWS CLI configured with credentials
  • โœ… Amazon Bedrock model access enabled (Claude or Nova models)
  • โœ… ECR repository permissions
  • โœ… ECS and VPC permissions
โ Enable Bedrock Models
  1. Navigate to Amazon Bedrock Console
  2. Go to "Model access" โ†’ "Enable specific models"
  3. Enable: anthropic.claude-3-sonnet-20240229-v1:0 or amazon.nova-pro-v1:0
  4. Wait for approval (usually immediate)

โ ๐Ÿ“ Project Structure

05-chatbot/
โ”œโ”€โ”€ source/                     # Application source code
โ”‚   โ”œโ”€โ”€ chatbot_backend.py      # Backend logic with LangChain
โ”‚   โ””โ”€โ”€ chatbot_frontend.py     # Streamlit UI
โ”œโ”€โ”€ chatbot/                    # CDK infrastructure
โ”‚   โ”œโ”€โ”€ app.py                  # CDK app entry point
โ”‚   โ””โ”€โ”€ chatbot/
โ”‚       โ”œโ”€โ”€ chatbot_ecr_stack.py    # ECR repository
โ”‚       โ””โ”€โ”€ chatbot_ecs_stack.py    # ECS service & ALB
โ”œโ”€โ”€ Dockerfile                  # Container configuration
โ”œโ”€โ”€ docker-compose.yml          # Local development
โ”œโ”€โ”€ requirements.txt            # Python dependencies
โ””โ”€โ”€ README.md                   # This guide

โ ๐Ÿ”ง Implementation Details

โ Backend Architecture (chatbot_backend.py)
โ 1. Bedrock Client Initialization
# Singleton pattern for efficient resource usage
_bedrock_llm = None

def get_bedrock_client():
    global _bedrock_llm
    if _bedrock_llm is None:
        _bedrock_llm = ChatBedrockConverse(
            region_name='us-east-1',
            model='amazon.nova-pro-v1:0',
            temperature=0.1,      # Low randomness for consistent responses
            max_tokens=1000       # Reasonable response length
        )
    return _bedrock_llm
โ 2. Conversation Memory Management
def create_chat_memory():
    return ConversationSummaryBufferMemory(
        llm=get_bedrock_client(), 
        max_token_limit=2000      # Prevents context overflow
    )

Memory Flow:

  1. Initial State: Empty memory buffer
  2. User Input: Added to conversation history
  3. AI Response: Generated with full context
  4. Memory Update: Conversation stored with automatic summarization
  5. Context Management: Old conversations summarized when token limit reached
โ 3. Response Generation
def get_ai_response(user_input, chat_memory):
    conversation_chain = ConversationChain(
        llm=get_bedrock_client(), 
        memory=chat_memory, 
        verbose=True              # Debug logging
    )
    return conversation_chain.invoke(user_input)['response']
โ Frontend Architecture (chatbot_frontend.py)
โ 1. Session State Management
# Initialize persistent memory across page reloads
if 'chat_memory' not in st.session_state: 
    st.session_state.chat_memory = backend.create_chat_memory()

# Initialize chat history for UI display
if 'chat_history' not in st.session_state:
    st.session_state.chat_history = []
โ 2. Chat Flow Process

Step-by-Step User Interaction:

  1. User Input Capture

    user_input = st.chat_input("Ask me anything...")
    
  2. Display User Message

    with st.chat_message("user"): 
        st.markdown(user_input)
    
  3. Store in Session History

    st.session_state.chat_history.append({
        "role": "user", 
        "text": user_input
    })
    
  4. Generate AI Response

    ai_response = backend.get_ai_response(
        user_input, 
        st.session_state.chat_memory
    )
    
  5. Display AI Response

    with st.chat_message("assistant"): 
        st.markdown(ai_response)
    
  6. Update Session History

    st.session_state.chat_history.append({
        "role": "assistant", 
        "text": ai_response
    })
    
โ Infrastructure Architecture
โ ECR Stack (chatbot_ecr_stack.py)
  • Purpose: Container registry for Docker images
  • Components: ECR Repository with lifecycle policies
โ ECS Stack (chatbot_ecs_stack.py)
  • VPC: Multi-AZ setup with public/private subnets
  • ECS Cluster: Fargate-based container orchestration
  • Task Definition: Container specs with Bedrock permissions
  • Application Load Balancer: Internet-facing with health checks
  • Security Groups: Controlled network access

โ ๐Ÿš€ Step-by-Step Guide

โ Phase 1: Local Development Setup
โ 1. Clone and Setup Environment
# Clone repository
git clone https://github.com/anveshmuppeda/amazon-bedrock.git
cd amazon-bedrock/05-chatbot

# Create virtual environment
python -m venv chatbot-env
source chatbot-env/bin/activate  # Windows: chatbot-env\Scripts\activate

# Install dependencies
pip install -r requirements.txt
โ 2. Configure AWS Credentials
# Configure AWS CLI
aws configure
# Enter: Access Key, Secret Key, Region (us-east-1), Output format (json)

# Verify configuration
aws sts get-caller-identity
โ 3. Test Bedrock Access
# List available models
aws bedrock list-foundation-models --region us-east-1

# Test model access
aws bedrock invoke-model \
    --model-id "amazon.nova-pro-v1:0" \
    --body '{"messages":[{"role":"user","content":[{"text":"Hello"}]}],"inferenceConfig":{"maxTokens":100}}' \
    --cli-binary-format raw-in-base64-out \
    --region us-east-1 \
    output.json
โ Phase 2: Local Testing
# Start the application
docker-compose up --build

# Access application
open http://localhost:8501
โ 2. Run Locally (Development)
# Navigate to source directory
cd source

# Set environment variables
export AWS_DEFAULT_REGION=us-east-1
export BEDROCK_MODEL_ID=amazon.nova-pro-v1:0

# Run Streamlit
streamlit run chatbot_frontend.py
โ 3. Test Conversation Memory

Test Scenario:

  1. First Message: "My name is John and I like pizza"
  2. Second Message: "What's my name?"
  3. Expected Response: AI should remember "John"
  4. Third Message: "What do I like to eat?"
  5. Expected Response: AI should remember "pizza"
โ Phase 3: AWS Deployment
โ 1. Bootstrap CDK (First Time Only)
cd chatbot
cdk bootstrap aws://$(aws sts get-caller-identity --query Account --output text)/us-east-1
โ 2. Deploy ECR Repository
# Deploy ECR stack
cdk deploy ChatbotEcrStack

# Note the ECR repository URI from output
โ 3. Build and Push Docker Image
# Get ECR login token
aws ecr get-login-password --region us-east-1 | \
docker login --username AWS --password-stdin \
$(aws sts get-caller-identity --query Account --output text).dkr.ecr.us-east-1.amazonaws.com

# Build for Linux/AMD64 (required for ECS)
docker build --platform linux/amd64 -t chatbot-ecr-repository:latest .

# Tag for ECR
docker tag chatbot-ecr-repository:latest \
$(aws sts get-caller-identity --query Account --output text).dkr.ecr.us-east-1.amazonaws.com/chatbot-ecr-repository:latest

# Push to ECR
docker push \
$(aws sts get-caller-identity --query Account --output text).dkr.ecr.us-east-1.amazonaws.com/chatbot-ecr-repository:latest
โ 4. Deploy ECS Infrastructure
# Deploy ECS stack
cdk deploy ChatbotEcsStack

# Note the LoadBalancer DNS from output
โ 5. Access Deployed Application
# Get ALB DNS name
aws elbv2 describe-load-balancers \
    --names chatbot-alb \
    --query 'LoadBalancers[0].DNSName' \
    --output text

# Access application
open http://[ALB-DNS-NAME]

โ ๐Ÿงช Testing

โ Functional Tests
โ 1. Memory Persistence Test
User: "Remember that I work as a software engineer at AWS"
AI: "I'll remember that you work as a software engineer at AWS."

User: "What's my job?"
AI: "You work as a software engineer at AWS."
โ 2. Context Awareness Test
User: "I have a meeting at 3 PM about the new project"
AI: "Got it, you have a meeting at 3 PM about the new project."

User: "What time is my meeting?"
AI: "Your meeting is at 3 PM."

User: "What's it about?"
AI: "It's about the new project."
โ 3. Long Conversation Test
  • Send 10+ messages to test memory summarization
  • Verify older context is summarized but key information retained
โ Performance Tests
โ 1. Response Time
# Test API response time
curl -w "@curl-format.txt" -s -o /dev/null http://[ALB-DNS]/
โ 2. Concurrent Users
# Simulate multiple users
for i in {1..5}; do
    curl -X POST http://[ALB-DNS]/ &
done
โ Health Checks
โ 1. Container Health
# Check container status
docker ps

# Check health endpoint
curl http://localhost:8501/_stcore/health
โ 2. ECS Service Health
# Check ECS service status
aws ecs describe-services \
    --cluster chatbot-ecs-cluster \
    --services chatbot-ecs-service

โ ๐Ÿ”ง Troubleshooting

โ Common Issues
โ 1. Bedrock Access Denied
Error: AccessDeniedException
Solution: Enable model access in Bedrock console
โ 2. Memory Issues
Error: Token limit exceeded
Solution: Reduce max_token_limit in ConversationSummaryBufferMemory
โ 3. Container Won't Start
# Check logs
docker logs [container-id]

# Common issues:
# - Missing AWS credentials
# - Wrong model ID
# - Network connectivity
โ 4. ECS Task Failures
# Check ECS logs
aws logs get-log-events \
    --log-group-name "/chatbot/logs" \
    --log-stream-name [stream-name]
โ Debug Commands
# Test Bedrock connectivity
aws bedrock list-foundation-models --region us-east-1

# Check ECR repository
aws ecr describe-repositories --repository-names chatbot-ecr-repository

# Verify ECS service
aws ecs list-services --cluster chatbot-ecs-cluster

# Check ALB health
aws elbv2 describe-target-health --target-group-arn [target-group-arn]

โ ๐Ÿ’ฐ Cost Optimization

โ Estimated Costs (Monthly)
ComponentCostUsage
ECS Fargate~$151 task, 0.5 vCPU, 1GB RAM
Application Load Balancer~$18Standard ALB
Bedrock API Calls~$51000 requests/month
CloudWatch Logs~$1Standard logging
Total~$39/monthLight usage
โ Cost Reduction Tips
  1. Auto Scaling: Configure ECS auto-scaling based on CPU/memory
  2. Spot Instances: Use Fargate Spot for non-production
  3. Log Retention: Set shorter CloudWatch log retention
  4. Resource Right-Sizing: Monitor and adjust CPU/memory allocation
โ Cleanup Resources
# Destroy ECS stack
cdk destroy ChatbotEcsStack

# Destroy ECR stack (after confirming no images needed)
cdk destroy ChatbotEcrStack

# Verify cleanup
aws ecs list-clusters
aws ecr describe-repositories

โ ๐ŸŽฏ Key Learning Outcomes

After completing this guide, you'll understand:

  • โœ… Conversation Memory: How LangChain manages chat context
  • โœ… Bedrock Integration: Direct API calls vs LangChain abstraction
  • โœ… Streamlit State Management: Session persistence across interactions
  • โœ… Container Orchestration: ECS Fargate deployment patterns
  • โœ… Load Balancing: ALB configuration for web applications
  • โœ… Infrastructure as Code: CDK best practices for AI applications

โ ๐Ÿ“š Additional Resources


Ready to build your intelligent chatbot? Start with local developmentโ  and work your way up to production deployment! ๐Ÿš€

Tag summary

Content type

Image

Digest

sha256:0eaa467f8โ€ฆ

Size

245.7 MB

Last updated

12 months ago

docker pull anvesh35/bedrock-chatbot