Skip to main content

Overview

When working with agents, you can design them to raise exceptions back to you when they encounter specific conditions. This allows you to handle domain-specific error cases gracefully. Agent errors occur when the agent intentionally raises an exception. This could happen if:
  • You told the agent to raise an exception in certain situations
  • The agent believes your task to be impossible or contradictory
  • The tools you provided to the agent are not working as expected
Agent errors are different from operational errors, which are platform-level failures like network issues, API timeouts, or sandbox errors.

Basic Error Handling

There are three approaches to handling agent failures:
  1. Result types: Allow the agent to return a union — either the desired type, or an error type (for example ).
  2. Builtin exceptions: The agent may throw any of the builtin exceptions in your language’s runtime (e.g., ValueError, TypeError).
  3. Custom exceptions: Define your own exception classes and the agent can raise them based on your documented error conditions.

Using Result Types

The simplest approach is to allow the agent to return None/null when it cannot complete the task:

Custom Exceptions

You can define your own exception classes and have the agent raise them when specific error conditions occur. This is useful for domain-specific error handling that goes beyond builtin exceptions. Best practices for custom exceptions:
  • Pass custom exceptions into the function or agent scope so they are available to raise
  • Clearly document when each exception should be raised in your
  • Use descriptive exception names that indicate the error condition
  • Provide clear error messages that help diagnose the issue
  • The agent can see and understand your documentation to know when to raise each exception
The agent can see your ! Be specific about the conditions that should trigger each exception. The more precise your documentation, the more reliably the agent will raise the appropriate exception.

Validation After Invocation

Type annotations help guide agents, and constrain the types the agent is capable of returning, but sometimes you need additional validation logic not expressible in the type system.

Agent-Visible Validation

Validation logic may be realized in the type itself, such as during initialization of custom classes. In these cases, the agent can see validation errors and self-correct when returning back to you.
Here Price cannot be instantiated without satisfying the validation logic, and therefore cannot be returned by the agent until it is satisfied.

Fine-Grained Validation

Off-the-shelf validation libraries such as Pydantic (Python) or Zod (TypeScript) may be used to integrate with existing validation logic or describe more complex validation requirements.
Pydantic provides powerful declarative validation through field constraints and custom validators.Field-level constraints can specify numeric ranges, string lengths, and other basic requirements:
Python
Not only do these fields provide basic validation, but they also provide excellent documentation for the agent.Custom field validators handle complex logic on individual fields using @field_validator:
Python
Cross-field validation uses @model_validator to validate relationships between fields:
Python
The agent sees Pydantic validation errors and adjusts its output to satisfy all constraints:
Python

Graceful Degradation

You may encounter edge cases where a task is genuinely impossible (missing required data, contradictory constraints, etc.). In these cases, you can design your application to degrade gracefully, maintaining basic functionality even when an agent cannot complete the full task.
Frequent fallbacks indicate an opportunity to refine your approach — adjusting prompts, choosing a different model, or providing more context. Use fallback patterns to handle genuine edge cases.

Fallback to Simpler Logic

If a complex agent operation fails, fall back to simpler approaches. This example shows agents generating database migrations, with fallbacks to safer manual approaches. First, define your agent-backed function that attempts the complex task:
Then create a simpler, safer fallback that generates a basic migration:
Attempt the smart migration first, falling back to basic if it fails:

Partial Success Handling

Sometimes an agent-backed operation can partially succeed. Instead of treating this as complete failure, design your workflow to continue with whatever succeeded. This example shows an agent refactoring code across multiple files. Define a workflow where agents process multiple items, tracking successes and failures:
Then act on partial results, applying successful changes while reporting failures:

Multi-Level Fallback Chain

For critical operations, implement progressively simpler agentic tasks as fallbacks. When a task requires data that isn’t available or constraints that can’t be met, agents may raise an error. Simpler fallback tasks with relaxed requirements are more likely to succeed. Define multiple agentic approaches with decreasing strictness:
Attempt each approach, falling back when required data is missing:
When the text only mentions “Send it to John in Seattle”, the validated extraction fails (missing street, state, zip, country), but the minimal extraction can still return “Seattle” as the location.

Custom Exceptions

You can define your own exception classes and have the agent raise them when specific error conditions occur. The agent can raise these exceptions from within its execution environment, and they are automatically bubbled back up to your code.

Defining Custom Exceptions

Custom exceptions are useful for domain-specific error handling. To use them:
  1. Define your custom exception classes
  2. Pass them into the
  3. Document when each exception should be raised so the agent knows when to use them
The agent can see your ! Be specific about when each exception should be raised. The agent uses this documentation to understand when to throw each exception type.
For comprehensive error handling patterns and best practices, see the Error Handling Guide.

Next Steps

Operational Errors

Handle platform-level errors (network, API, sandbox)

Best Practices

Production deployment best practices

Human-in-the-Loop

Add human oversight to your agents

Advanced

Custom system prompts and templating