Amazon Bedrock
LLMs gestionados, Knowledge Bases, Agents y Guardrails
Amazon Bedrock es el servicio gestionado de LLMs de AWS: accede a modelos de varias proveedoras (Anthropic Claude, Meta Llama, Mistral, Cohere) sin gestionar tu propia infraestructura. En lugar de desplegar modelo_de_llama_70b.tar.gz en SageMaker, haces una llamada API simple: `bedrock.invoke_model(modelId='meta.llama2-70b', body=json.dumps({...}))`. Bedrock maneja automáticamente escalado, load balancing y versionado de modelos — tú solo pagas por tokens consumidos (input + output).
Bedrock expone dos tipos de APIs: (1) Text generation (chat, completions) para generar respuestas; (2) Embeddings para convertir texto a vectores (necesario para Knowledge Bases). Los modelos disponibles varían por región — verifica qué está habilitado en tu región. Claude Instant es barato y rápido (ideal para summarización); Claude 3 Opus es el más poderoso (mejor para razonamiento complejo). Llama 2 y Mistral son open-source hospedados por AWS (sin costo de licencia).
Knowledge Bases es el servicio RAG gestionado de Bedrock: carga documentos (PDF, HTML), Bedrock automáticamente los chunka, genera embeddings y los almacena en una base de datos vectorial (Pinecone, Weaviate, o OpenSearch). Cuando consultas, Bedrock recupera los chunks relevantes y los inyecta al LLM como contexto. No necesitas construir tu propio pipeline RAG — es trivial: load documentos, crear Knowledge Base, consultar.
Bedrock Agents es la automatización: defines herramientas disponibles (ej. 'busca en Knowledge Base', 'llama a una API', 'lee un archivo S3'), y el agente decide automáticamente cuál usar basado en la pregunta del usuario. El agente itera: ve la respuesta de una herramienta, decide si necesita otra, hasta que tiene suficiente información para responder. No necesitas escribir lógica de flujo — el LLM dirige el agente automáticamente.
Guardrails permite definir límites: rechaza respuestas que violen políticas (ej. 'no hagas código de malware', 'no generes contenido adulto'). Se aplican a nivel de entrada (rechaza inputs malos) y salida (rechaza outputs malos). También permite redaction: reemplaza información sensible en las respuestas (ej. números de teléfono, direcciones). Es esencial para producción donde necesitas conformidad o control sobre el contenido generado.
Los errores más comunes con Bedrock son: (1) elegir el modelo incorrecto (Instant para tareas que necesitan Opus), (2) no usar Knowledge Bases y pasar documentos completos al LLM (exceeds token limit), (3) no configurar Guardrails y permitir alucinaciones o contenido dañino, (4) olvidar credenciales IAM para leer de S3 Knowledge Base (acceso denegado), (5) usar versionado de modelo incorrecto (ej. 'latest' es inestable, mejor usar versión específica).
# === INVOKE BEDROCK MODEL ===
import boto3
import json
bedrock = boto3.client('bedrock-runtime', region_name='us-west-2')
# Simple text completion
response = bedrock.invoke_model(
modelId='anthropic.claude-3-sonnet-20240229-v1:0',
contentType='application/json',
accept='application/json',
body=json.dumps({
'anthropic_version': 'bedrock-2023-05-31',
'max_tokens': 1024,
'messages': [
{
'role': 'user',
'content': 'Explain RAG in 3 sentences'
}
]
})
)
result = json.loads(response['body'].read())
print(result['content'][0]['text'])
# === GENERATE EMBEDDINGS ===
response = bedrock.invoke_model(
modelId='amazon.titan-embed-text-v2:0',
contentType='application/json',
body=json.dumps({
'inputText': 'Retrieve augmented generation'
})
)
embedding = json.loads(response['body'].read())['embedding'] # Vector of 1536 dims
# === KNOWLEDGE BASE ===
from boto3.session import Session
# Create knowledge base
kb = boto3.client('bedrock-agent', region_name='us-west-2')
response = kb.create_knowledge_base(
name='ml-docs',
roleArn='arn:aws:iam::123456789:role/BedrockRole',
knowledgeBaseConfiguration={
'type': 'VECTOR',
'vectorKnowledgeBaseConfiguration': {
'embeddingModelArn': 'arn:aws:bedrock:us-west-2:aws:foundation-model/amazon.titan-embed-text-v2:0'
}
},
storageConfiguration={
'type': 'OPENSEARCH',
'opensearchServerlessConfiguration': {
'collectionArn': 'arn:aoss:us-west-2:123456789:collection/default'
}
}
)
kb_id = response['knowledgeBase']['id']
# Ingest documents
kb.start_ingestion_job(
knowledgeBaseId=kb_id,
dataSourceId='ds-123', # S3 bucket with PDFs
)
# === RETRIEVE FROM KNOWLEDGE BASE ===
bedrock_agent = boto3.client('bedrock-agent-runtime')
response = bedrock_agent.retrieve(
knowledgeBaseId=kb_id,
retrievalQuery={
'text': 'How does RAG improve LLMs?'
}
)
for result in response['retrievalResults']:
print(f"Score: {result['score']}")
print(f"Content: {result['content']['text']}")
# === AGENT WITH TOOLS ===
bedrock_mgmt = boto3.client('bedrock-agent', region_name='us-west-2')
agent_response = bedrock_mgmt.create_agent(
agentName='ml-assistant',
agentResourceRoleArn='arn:aws:iam::123456789:role/BedrockRole',
foundationModel='anthropic.claude-3-sonnet-20240229-v1:0',
description='ML documentation assistant'
)
agent_id = agent_response['agent']['agentId']
# Add action group (tools) separately
bedrock_mgmt.create_agent_action_group(
agentId=agent_id,
agentVersion='DRAFT',
actionGroupName='KnowledgeBaseSearch',
actionGroupExecutor={'lambda': 'arn:aws:lambda:us-west-2:123456789:function:kb-search'},
apiSchema={
'payload': json.dumps({
'openapi': '3.0.0',
'paths': {'/search': {'post': {'operationId': 'SearchKnowledgeBase'}}}
})
}
)
# === INVOKE AGENT ===
response = bedrock_agent.invoke_agent(
agentId='agent-123',
agentAliasId='alias-456',
sessionId='session-user-1',
inputText='What is the best way to handle missing data in ML?'
)
# Agent iterates internally until it has answer
# Response is an EventStream — iterate to get the final answer
for event in response['completion']:
if 'chunk' in event:
print(event['chunk']['bytes'].decode('utf-8'))Katas (5)
Debugging lab
Detecta y corrige el error en el código.
- 6.9.5.1
# Tarea: explicar recursión en 10000 tokens response = bedrock.invoke_model( modelId='anthropic.claude-3-sonnet-20240229-v1:0', body=json.dumps({ 'anthropic_version': 'bedrock-2023-05-31', 'max_tokens': 10000, 'messages': [{'role': 'user', 'content': 'Explain recursion in 10000 tokens'}] }) ) # Cost: extremely high for long responses
- 6.9.5.2
# Read 50 PDFs from S3, pass all content to Claude with open('all_docs.txt', 'w') as f: for pdf in s3_files: f.write(pdf_to_text(pdf)) # Concatenate all response = bedrock.invoke_model( body=json.dumps({'messages': [{'role': 'user', 'content': all_docs + query}]}) ) # Error: exceeds context window
- 6.9.5.3
# Model specified as 'latest' response = bedrock.invoke_model( modelId='anthropic.claude-latest', # What is 'latest'? body=json.dumps({...}) ) # In production, different team members get different behavior
- 6.9.5.4
# Agent defined with ambiguous tool tool = { 'toolSpec': { 'name': 'CallAPI', 'description': 'Call an API', # Too vague!
- 6.9.5.5
# LLM generates output with personal information response = bedrock.invoke_model(...) result = json.loads(response['body'].read()) output = result['content'][0]['text'] print(output) # Contains phone numbers, addresses from context # GDPR violation risk
- 6.9.5.6
# Knowledge Base ingestion never finishes ingestion = kb.start_ingestion_job(knowledgeBaseId=kb_id, dataSourceId='ds-123') # Status is PROCESSING for 2 hours, then FAILED # No logs showing what went wrong