0Pricing
AI Agents with LangChain & Autonomous Workflows · Aula

Tratamento de erros e execução segura de ferramentas

Torne as ferramentas dos agentes resilientes e seguras tratando falhas com elegância, validando entradas e restringindo o que elas podem fazer durante a execução autônoma.

Tratamento de erros e execução segura de ferramentas é uma aula grátis de AI Agents with LangChain & Autonomous Workflows no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de AI Agents with LangChain & Autonomous Workflows, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de AI Agents with LangChain & Autonomous Workflows inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Tools Will Fail

Agents call external tools: APIs, databases, shells. These time out, return errors, or behave unexpectedly. An agent that crashes on the first failure is useless in production.

This lesson covers making tool execution safe and resilient.

Returning Errors as Observations

Instead of throwing, a tool should return the error as a message the agent can read. This lets the agent reason about the failure and try another approach.

def search(q):
    try:
        return api.search(q)
    except Exception as e:
        return 'ERROR: search failed: ' + str(e)

Validating Tool Inputs

LLMs sometimes pass nonsense arguments. Validate inputs before acting, so a malformed query never reaches a real system.

def get_user(user_id):
    if not str(user_id).isdigit():
        return 'ERROR: user_id must be numeric'
    return db.fetch(user_id)

Timeouts and Retries

Wrap slow tools with a timeout and retry transient failures a bounded number of times. Without limits, an agent can hang or loop forever.

for attempt in range(3):
    try:
        return call(timeout=5)
    except Timeout:
        continue
return 'ERROR: timed out after 3 attempts'

The Danger of Powerful Tools

A tool that runs shell commands or executes SQL can do real damage if the agent is tricked or confused. Power must be paired with constraints.

Least Privilege

Give each tool only the access it needs. A read tool should not be able to write. A query tool should use a read-only database role.

# read-only DB connection for the query tool
conn = connect(user='reader', readonly=True)

Allowlists over Blocklists

Trying to block every dangerous action is a losing game. Instead, permit only an explicit set of safe operations and reject everything else by default.

ALLOWED = {'read_file', 'list_dir', 'search'}
if action not in ALLOWED:
    return 'ERROR: action not permitted'

Human-in-the-Loop Approval

For high-impact actions like sending money or deleting data, pause and require human confirmation before executing. The agent proposes; a person approves.

if action.is_destructive:
    return await request_human_approval(action)

Preventing Infinite Loops

Agents can get stuck retrying the same failing tool. Cap the number of steps and detect repeated identical actions, stopping with a clear message instead of burning tokens forever.

agent = initialize_agent(tools, llm, max_iterations=8)

Logging for Auditing

Record every tool call with its inputs, outputs, and outcome. This audit trail is essential for debugging agent behavior and for catching unsafe actions after the fact.

A Safe Tool Workflow

Putting it together:

  • Return errors as observations, not crashes
  • Validate inputs and bound timeouts/retries
  • Apply least privilege and allowlists
  • Require approval for destructive actions
  • Cap iterations and log every call

Quick Check

Test your understanding of safe tool execution.

Recap

You learned to make agent tools resilient and safe.

  • Surface errors as observations the agent can handle
  • Validate inputs and bound timeouts, retries, and iterations
  • Apply least privilege and allowlists
  • Require approval for destructive actions and log everything

Perguntas Frequentes

A aula “Tratamento de erros e execução segura de ferramentas” é grátis?

Sim — o texto completo de “Tratamento de erros e execução segura de ferramentas” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de AI Agents with LangChain & Autonomous Workflows, atualize para CoddyKit PRO. O curso de AI Agents with LangChain & Autonomous Workflows inclui 4 aulas no total.

O que vou aprender em “Tratamento de erros e execução segura de ferramentas”?

Torne as ferramentas dos agentes resilientes e seguras tratando falhas com elegância, validando entradas e restringindo o que elas podem fazer durante a execução autônoma. Você pratica AI Agents with LangChain & Autonomous Workflows com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar AI Agents with LangChain & Autonomous Workflows?

Nenhuma experiência prévia é necessária. AI Agents with LangChain & Autonomous Workflows no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Tratamento de erros e execução segura de ferramentas”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de AI Agents with LangChain & Autonomous Workflows?

Sim. Cada aula de AI Agents with LangChain & Autonomous Workflows inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Definindo e usando ferramentas
  2. Tipos de agentes e tomada de decisões
  3. Aproveitando conjuntos de ferramentas prontos
  4. Tratamento de erros e execução segura de ferramentas
← Voltar para AI Agents with LangChain & Autonomous Workflows