Guardrails y comportamiento seguro de los agentes
Implemente guardrails prácticos de seguridad para agentes de IA —validación de entradas y salidas, filtrado de contenido y acceso limitado a herramientas— para evitar acciones dañinas o imprevistas.
Guardrails y comportamiento seguro de los agentes es una lección gratuita de AI Agents with LangChain & Autonomous Workflows en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de AI Agents with LangChain & Autonomous Workflows, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de AI Agents with LangChain & Autonomous Workflows incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
From Ethics to Engineering
Ethical principles need enforcement in code. Guardrails are the concrete controls that keep an agent within safe, intended boundaries at runtime.
They act on three points: the input, the model's reasoning, and the output or actions.
Input Guardrails
Check user input before it reaches the agent. Catch:
- Prompt-injection attempts
- Requests for disallowed topics
- Personal data that should be redacted
Detecting Prompt Injection
Prompt injection tries to override your instructions (e.g. ignore previous rules). A simple guard flags suspicious phrases before processing.
BAD = ['ignore previous', 'disregard instructions']
if any(p in user_input.lower() for p in BAD):
raise ValueError('Possible prompt injection')Output Guardrails
Validate what the agent produces before showing it. Block unsafe content, leaked secrets, or off-policy answers, replacing them with a safe fallback message.
if contains_sensitive(answer):
answer = 'I cannot share that information.'Structured Output Validation
When an agent must return JSON, validate it against a schema. Reject or repair malformed output so downstream systems never receive bad data.
from pydantic import BaseModel
class Ticket(BaseModel):
priority: str
summary: str
Ticket.model_validate_json(agent_output)Constraining Tool Access
The most dangerous actions come from tools. Give an agent only the tools it needs, and scope each one — read-only where possible, with limits on what it can affect.
Allowlists Over Blocklists
Define what is permitted rather than chasing every bad case. An allowlist of approved domains, tables, or operations is far safer than trying to enumerate everything to forbid.
ALLOWED_DOMAINS = {'docs.company.com'}
if domain not in ALLOWED_DOMAINS:
raise PermissionError('Domain not allowed')Moderation Models
Provider moderation endpoints classify text for harmful categories. Run inputs and outputs through them as an extra safety layer.
result = client.moderations.create(input=text)
if result.results[0].flagged:
block()Limiting Autonomy
Cap how much an agent can do unattended: max iterations, max tool calls, spending limits, and human approval for high-impact actions. Bounded autonomy prevents runaway behavior.
agent = create_agent(llm, tools, max_iterations=8)Fail Safe, Not Open
When a guardrail is uncertain or a check errors, default to the safe choice — refuse or escalate — rather than letting the action through. A blocked safe request is better than an executed harmful one.
Logging and Review
Log every guardrail trigger. Reviewing these reveals attack patterns and false positives, letting you tune rules over time without weakening safety.
Quick Check
Test your guardrails knowledge.
Recap
You learned to engineer safe agent behavior:
- Add input and output guardrails
- Detect prompt injection and validate structured output
- Constrain tool access with allowlists and scoping
- Use moderation, limit autonomy, and fail safe
- Log and review every trigger
Guardrails turn ethical intent into enforced, trustworthy agents.
Aprende AI Agents with LangChain & Autonomous Workflows con un tutor de IA — gratis
Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.
- Cursos
- 12
- Lecciones
- 50
Preguntas frecuentes
¿La lección «Guardrails y comportamiento seguro de los agentes» es gratis?
Sí — el texto completo de «Guardrails y comportamiento seguro de los agentes» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de AI Agents with LangChain & Autonomous Workflows, actualiza a CoddyKit PRO. El curso de AI Agents with LangChain & Autonomous Workflows incluye 4 lecciones en total.
¿Qué aprenderé en «Guardrails y comportamiento seguro de los agentes»?
Implemente guardrails prácticos de seguridad para agentes de IA —validación de entradas y salidas, filtrado de contenido y acceso limitado a herramientas— para evitar acciones dañinas o imprevistas. Practicas AI Agents with LangChain & Autonomous Workflows con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar AI Agents with LangChain & Autonomous Workflows?
No se requiere experiencia previa. AI Agents with LangChain & Autonomous Workflows en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Guardrails y comportamiento seguro de los agentes»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de AI Agents with LangChain & Autonomous Workflows?
Sí. Cada lección de AI Agents with LangChain & Autonomous Workflows incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Consideraciones éticas en los agentes de IA
- Sesgo, equidad y transparencia
- Tendencias emergentes e investigación
- Guardrails y comportamiento seguro de los agentes