Crea tu propio chat con Claude en AWS Bedrock usando AWS CDK (guía paso a paso para principiantes)
🎯 Objetivo
Desplegar desde cero una demo serverless de chat con Claude 3.5 (Anthropic) en AWS Bedrock, usando AWS CDK con Python. Ideal si estás empezando con AWS, IaC (Infrastructure as Code) o simplemente quieres experimentar con IA generativa dentro del ecosistema AWS.
🧰 ¿Qué vas a construir?
Un mini proyecto que crea:
- Una Lambda que llama al modelo Claude 3.5 Sonnet en Bedrock.
- Un API Gateway que expone la Lambda vía
/chat
. - Un sitio web estático (S3) con un pequeño chat frontend.
- Todo desplegado automáticamente con AWS CDK (Python).
🚀 1. Requisitos previos
Antes de empezar, asegúrate de tener:
- Una cuenta AWS con acceso al modelo de Bedrock habilitado.
Ve a:Bedrock Console → Model access → Enable anthropic.claude-3-5-sonnet-20240620
- Región recomendada:
us-east-1
- AWS CDK instalado:
npm install -g aws-cdk
- Credenciales configuradas con aws configure.
🏗️ 2. Clona el repositorio
git clone https://github.com/r3xakead0/aws-cdk-bedrock-claude.git
cd aws-cdk-bedrock-claude
Activa un entorno virtual y instala dependencias:
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
🧱 3. Entendiendo la arquitectura
Frontend (S3 static site)
↓
API Gateway → Lambda → AWS Bedrock (Claude)
El flujo es simple:
- El usuario escribe un mensaje.
- La Lambda envía ese texto al modelo de Claude.
- Claude responde, y la API devuelve el texto al navegador.
💡 4. Los componentes clave del CDK
lambda/chat/index.py
Invoca el modelo Claude con la API de Bedrock Runtime:
bedrock_rt = boto3.client("bedrock-runtime")
resp = bedrock_rt.invoke_model(
modelId="anthropic.claude-3-5-sonnet-20240620",
body=json.dumps({
"anthropic_version": "bedrock-2023-05-31",
"messages": [{"role": "user", "content": [{"type": "text", "text": prompt}]}],
"max_tokens": 512
})
)
stacks/bedrock_claude_stack.py
Define la infraestructura: Lambda, API Gateway y bucket S3.
api = apigw.LambdaRestApi(self, "ClaudeChatApi", handler=fn)
CDK genera todo automáticamente y lo despliega.
🚢 5. Desplegar el proyecto
Primero, inicializa el bootstrap (solo una vez por cuenta/región):
cdk bootstrap
Luego despliega:
cdk deploy
Al terminar verás dos salidas (Outputs):
ApiUrl = https://xxxx.execute-api.us-east-1.amazonaws.com/prod/chat
WebsiteUrl = http://claudechatdemo.s3-website-us-east-1.amazonaws.com
💬 6. Prueba el chat
Abre la URL del sitio web y pega el ApiUrl en el campo API URL.
Escribe un mensaje como:
Explícame qué es AWS CDK en palabras simples.
Y verás la respuesta generada por Claude en segundos ✨
Ejemplo:
http://bedrockclaudedemo-claudechatsite2959d623-gpqtnrxt6xwi.s3-website-us-east-1.amazonaws.com/
Respuesta
Yes, I'm familiar with buckets in various contexts. The term "bucket" can have different meanings depending on the context
1. In everyday usage, a bucket is a container used for carrying or storing liquids or other materials
2. In computer science and cloud computing:
- A bucket is a fundamental container for storing data in object storage services like Amazon S3 (Simple Storage Service).
- It's used to organize and control access to data objects
3. In data structures, a bucket is a container that can hold multiple items, often used in hash tables or for sorting algorithms (e.g., bucket sort)
4. In statistics and data analysis, data can be grouped into "buckets" or ranges for easier analysis or visualization
5. In project management, "bucket" might refer to a category or group of related tasks or resources
Given that you're asking about buckets in the context of an AWS expert, I assume you're most likely referring to S3 buckets or similar cloud storage concepts. If you have a morspecific question about buckets in a particular context, please feel free to ask.
🧪 7. Probar desde la terminal
También puedes enviar prompts con curl:
API="https://xxxx.execute-api.us-east-1.amazonaws.com/prod/chat"
curl -s -X POST "$API"
-H 'Content-Type: application/json'
-d '{"prompt":"Resume AWS CDK en 3 viñetas"}' | jq
🧹 8. Limpieza
Para evitar costos:
cdk destroy
Esto eliminará la Lambda, API Gateway y el bucket S3.
🧭 Qué aprendiste
✅ Crear infraestructura serverless con CDK (Python).
✅ Invocar modelos de IA con AWS Bedrock.
✅ Desplegar un sitio web simple en S3.
✅ Conectar todo en una demo lista para mostrar.
✨ Conclusión
Este proyecto muestra lo simple que es unir Infraestructura como Código (CDK) y IA generativa (Bedrock) para crear soluciones reales en minutos.
💙 Código abierto aquí → r3xakead0/aws-cdk-bedrock-claude
Si te sirvió, ¡déjame un ❤️ y comenta qué modelo de Bedrock te gustaría probar después!