Error Handling
Catch and recover from agent, tool, and LLM errors
Structured exceptions tell you what failed, whether to retry, and which agent or run was involved โ without parsing raw tracebacks.
from praisonaiagents import Agent, PraisonAIError
agent = Agent(name="assistant", instructions="Be helpful")
try:
print(agent.start("Say hello in one sentence."))
except PraisonAIError as e:
print(f"{e.error_category}: {e.message} (agent={e.agent_id}, run={e.run_id})")The user runs the agent; failures raise typed PraisonAIError with category, message, and run context for recovery.
graph LR
subgraph "praisonaiagents.PraisonAIError โ one base for all"
Base[๐ก PraisonAIError]
Base --> Core[๐ง Core SDK errors<br/>ToolExecutionError<br/>LLMError<br/>ValidationError<br/>NetworkError]
Base --> Wrap[๐ฆ Wrapper errors<br/>RecipeError, CLIExecutionError,<br/>JobQueueFull, ToolTimeoutError, โฆ]
Base --> Mod[๐งฉ Module errors<br/>ConfigValidationError, ConfigVersionError,<br/>InsecureGatewayTransportError, ScheduleTargetError,<br/>CapabilityContractError, GatewayAdapterContractError,<br/>AuthError, AttachmentError, SerializationError,<br/>DatasetError, ToolResolutionError, WorkflowStateError,<br/>CloudSourceError, PortableRunError, SessionEncryptionError]
end
classDef base fill:#8B0000,stroke:#7C90A0,color:#fff
classDef core fill:#189AB4,stroke:#7C90A0,color:#fff
classDef wrap fill:#F59E0B,stroke:#7C90A0,color:#fff
class Base base
class Core core
class Wrap wrap
class Mod coreQuick Start
- Catch any agent error
python from praisonaiagents import Agent, PraisonAIError agent = Agent(name="assistant", instructions="Be helpful") try: result = agent.start("Say hello in one sentence.") print(result) except PraisonAIError as e: print(f"{e.error_category}: {e.message} (agent={e.agent_id}, run={e.run_id})") - Handle tool errors specifically
python from praisonaiagents import Agent, tool, ToolExecutionError @tool def divide(a: float, b: float) -> float: """Divide two numbers.""" return a / b agent = Agent(instructions="Use divide.", tools=[divide]) try: agent.start("Divide 10 by 0.") except ToolExecutionError as e: print(f"Tool {e.tool_name} failed: {e.message}") print(f"Retryable: {e.is_retryable}") - Catch a failed LLM tool-calling loop
python from praisonaiagents import Agent from praisonaiagents.llm import LLMResponseError agent = Agent(name="assistant", instructions="Answer clearly.") try: result = agent.start("Summarise the latest project update.") except LLMResponseError as e: # A mid-loop tool-calling error now raises instead of returning "" print(f"LLM call failed: {e.message}")
How It Works
sequenceDiagram
participant U as ๐ค User
participant A as ๐ง Agent
participant T as ๐ง Tool
U->>A: prompt
A->>T: call tool
T-->>A: raises ToolExecutionError
A-->>U: exception propagates (unless caught)Every structured error carries message, agent_id, run_id, error_category, and is_retryable. Subclasses add domain fields such as tool_name or model_name.
| Class | When raised | Key fields | Default retryable |
|---|---|---|---|
PraisonAIError | Base โ catch-all | error_category, context | False |
ToolExecutionError | Tool fails or loop-guard HALT | tool_name | True |
LLMError | Chat completion fails | model_name | False |
ValidationError | Invalid config or input | field_name | False |
NetworkError | External service unreachable | service_name, status_code | True |
LLMResponseError | LLM tool-calling loop fails mid-iteration | __cause__ (chained) | False |
Module exceptions
These 15 module-level exceptions also inherit from PraisonAIError. Each keeps its original built-in base, so code that wrote except ValueError: or except RuntimeError: to catch them still works unchanged; new code can write a single except PraisonAIError: to catch all of them.
| Class | Module | Original base | Raised when |
|---|---|---|---|
ConfigValidationError | praisonaiagents.gateway.config | ValueError | Gateway config fails validation |
ConfigVersionError | praisonaiagents.gateway.config | ValueError | Gateway config version is unsupported |
InsecureGatewayTransportError | praisonaiagents.gateway.protocols | ValueError | Gateway transport is insecure for the requested binding |
ScheduleTargetError | praisonaiagents.gateway.protocols | ValueError | A schedule target is invalid |
CapabilityContractError | praisonaiagents.bots.base | RuntimeError | A bot violates its declared capability contract |
GatewayAdapterContractError | praisonaiagents.bots.protocols | TypeError | A gateway adapter does not satisfy its protocol |
AuthError | praisonaiagents.auth.subscription.protocols | RuntimeError | Subscription authentication fails |
AttachmentError | praisonaiagents.agent.attachments | ValueError | An agent attachment is invalid or unreadable |
SerializationError | praisonaiagents.agent.serialize | ValueError | Agent serialization or deserialization fails |
DatasetError | praisonaiagents.eval.datasets | ValueError | An eval dataset cannot be loaded or parsed |
ToolResolutionError | praisonaiagents.tools.resolver | ValueError | A tool name cannot be resolved |
WorkflowStateError | praisonaiagents.workflows.state | ValueError | Workflow state is invalid |
CloudSourceError | praisonaiagents.knowledge.cloud | RuntimeError | A cloud knowledge source fails |
PortableRunError | praisonaiagents.runtime.portable | RuntimeError | A portable run fails |
SessionEncryptionError | praisonaiagents.session.encrypted_store | RuntimeError | Encrypted session store cannot encrypt or decrypt |
error_category uses typed kinds such as rate_limit, auth, context_overflow, and billing.
LLMResponseError is raised by LLM.get_response() when the tool-calling loop fails and cannot produce a response โ previously this was swallowed and returned as an empty string. Catch it to distinguish tool-loop failures; a try/except Exception already covers it. See LLMResponseError.
LLM Response Errors
LLMResponseError is raised when the LLM tool-calling loop hits an exception it cannot recover from. It lives in praisonaiagents.llm alongside the other LLM exceptions:
from praisonaiagents.llm import LLMResponseError| Exception | Module | Raised when |
|---|---|---|
LLMResponseError | praisonaiagents.llm | The tool-calling loop in LLM.get_response() fails mid-iteration and surfaces to the caller |
LLMContextLengthExceededException | praisonaiagents.llm | The prompt exceeds the model’s context window |
LLMResponseError carries a message attribute describing the iteration that failed and chains the original exception via raise โฆ from e, so e.__cause__ holds the underlying error.
Wrapper exceptions (praisonai.*)
PraisonAIError now catches every root exception in the praisonai wrapper too, so one except handler covers both tiers.
from praisonaiagents import PraisonAIError
from praisonai.recipe.registry import LocalRegistry
try:
LocalRegistry().pull("missing-recipe")
except PraisonAIError as e:
# Also catches RecipeError, CLIExecutionError, JobQueueFull, ToolTimeoutError, โฆ
print(f"{type(e).__name__}: {e}")Stdlib parents stay in place through multiple inheritance, so existing except ValueError, except RuntimeError, and except TimeoutError handlers keep matching. Keep importing the base from praisonaiagents โ the wrapper adds no new public module.
| Exception | Module | Stdlib parent (still matches) |
|---|---|---|
ToolTimeoutError | praisonai.agents_generator | TimeoutError |
AgentConfigError | praisonai.api.agent_invoke | ValueError |
MergeConflictError | praisonai.auto | โ |
LangfuseAPIError | praisonai.cli.langfuse_client | โ |
CLIExecutionError | praisonai.integrations.base | RuntimeError |
ManagedSandboxRequired | praisonai.integrations.managed_agents | RuntimeError |
JobQueueFull | praisonai.jobs.executor | โ |
RecipeError | praisonai.recipe.exceptions | โ |
RunHistoryError | praisonai.recipe.history | โ |
PolicyError | praisonai.recipe.policy | โ |
RegistryError | praisonai.recipe.registry | โ |
SecurityError | praisonai.recipe.security | โ |
RerunError | praisonai.replay.rerun | RuntimeError |
StrictModeError | praisonai.templates.dependency_checker | โ |
SecurityError | praisonai.templates.tool_override | โ |
Subclasses such as RecipeNotFoundError, RunNotFoundError, and PolicyDeniedError inherit the change automatically.
graph TB
Start[๐ค What do you want to handle?]
Start --> One{Any PraisonAI<br/>failure at all?}
One -->|Yes| Base[except PraisonAIError]
One -->|No| Spec{Specific category?}
Spec -->|Tool call failed| Tool[except ToolExecutionError]
Spec -->|LLM failed| LLM[except LLMError or<br/>LLMResponseError]
Spec -->|CLI integration failed| CLI[except CLIExecutionError]
Spec -->|Recipe / registry / policy| Rec[except RecipeError /<br/>RegistryError / PolicyError]
Spec -->|Job queue saturated| JQ[except JobQueueFull]
classDef base fill:#8B0000,stroke:#7C90A0,color:#fff
classDef path fill:#6366F1,stroke:#7C90A0,color:#fff
classDef pick fill:#189AB4,stroke:#7C90A0,color:#fff
class Start base
class One,Spec path
class Base,Tool,LLM,CLI,Rec,JQ pickObserving a terminal LLM failure
chat() / achat() return None on an unrecoverable LLM failure (a 500, a revoked key, a 429 after all retries). As of PR #5764, agent.last_stop_reason is set to "error" in that same path, so callers that cannot catch the raised exception (web handlers, bots, batch jobs) can still tell “the model answered empty” from “the model never answered”.
from praisonaiagents import Agent
agent = Agent(name="Assistant", instructions="Be helpful")
reply = agent.chat("Draft a reply")
if reply is None and agent.last_stop_reason == "error":
# The LLM call failed terminally. Retry on a healthy endpoint,
# or surface the failure to the user.
print("The model could not answer โ please try again.")The reason is reset to "completed" at the start of every turn, so an "error" from a previous turn cannot leak into the next one.
Tool Failure Behavior
On both chat() and achat(), a tool failure resolves down one of three branches:
- Tool raises an exception โ the framework wraps it as
ToolExecutionErrorand propagates it. - Tool returns
{"error": "..."}โ the error dict is handed back to the LLM as a normal tool result, so the model can self-correct (new behavior since PR #4462, confirmed in #4470 which fixes issue #4446. The generic-exception branch inopenai_client.pybehaves the same way.). - Tool returns a retryable-transient / denial dict โ
ToolExecutionErrorwithis_retryable=True, or a short-circuit denial.
graph TB
subgraph "Tool failure โ sync (chat) and async (achat)"
SReq[๐ค chat / achat request] --> SLLM[๐ค Model calls tool]
SLLM --> STool{๐ง Tool result}
STool -->|raises exception| SRaise[๐ ToolExecutionError propagates]
STool -->|returns error dict| SReturn[๐ Error dict returned to LLM<br/>LLM self-corrects]
STool -->|retryable / denied| SRetry[๐ ToolExecutionError<br/>is_retryable / denial break]
end
classDef req fill:#6366F1,stroke:#7C90A0,color:#fff
classDef proc fill:#189AB4,stroke:#7C90A0,color:#fff
classDef err fill:#8B0000,stroke:#7C90A0,color:#fff
classDef ok fill:#10B981,stroke:#7C90A0,color:#fff
class SReq req
class SLLM,STool proc
class SRaise,SRetry err
class SReturn okIf your tool raises, your agent’s turn ends โ the same way whether you call chat() or achat(). Wrap both in try / except ToolExecutionError:
import asyncio
from praisonaiagents import Agent, tool, ToolExecutionError
@tool
def fetch(url: str) -> str:
"""Fetch a URL."""
raise RuntimeError("429 too many requests")
agent = Agent(instructions="Use fetch.", tools=[fetch])
try:
agent.start("Fetch https://example.com")
except ToolExecutionError as e:
print(f"Tool {e.tool_name} failed: {e.message}")
# Async โ raises the same ToolExecutionError
try:
asyncio.run(agent.achat("Fetch https://example.com"))
except ToolExecutionError as e:
print(f"Tool {e.tool_name} failed: {e.message}")A tool that returns an error dict (instead of raising) no longer aborts the run โ the dict flows back to the model, which retries with corrected arguments:
from praisonaiagents import Agent, tool
@tool
def fetch(url: str) -> dict:
"""Fetch a URL โ returns an error dict on bad input."""
if not url:
return {"error": "Empty URL", "stdout": "", "stderr": ""}
...
agent = Agent(instructions="Use fetch.", tools=[fetch])
# The model calling fetch("") no longer aborts the run.
# The error dict flows back to the model and it retries with a real URL.
agent.start("Fetch example.com and summarise.")Sync and async paths are aligned (PR #6109). A tool that raises ends the turn with ToolExecutionError on both chat() and achat() โ previously achat() handed the error to the model and returned its “the operation failed” reply as a success, so side-effecting tools (email, payments) could fail silently. A tool that returns {"error": "..."} is handed to the LLM as a normal tool result on both. See Async Tool Safety.
Common Patterns
Retry on transient network failures, fail on config bugs:
from praisonaiagents import Agent, NetworkError, ValidationError
agent = Agent(name="assistant")
for attempt in range(3):
try:
print(agent.start("Summarise today's news."))
break
except NetworkError:
if attempt == 2:
raise
except ValidationError:
raise # fix config โ retry won't helpRaised errors stop the run; some callbacks record failures on the output instead. See Non-Fatal Errors.
Reaching the Step Limit
When the tool-calling loop reaches ExecutionConfig.max_steps (or max_iter when max_steps is unset), the agent does not hard-cut. On the final permitted step it injects a graceful wrap-up instruction, so the model returns a real summary of what it accomplished and what remains โ not a placeholder.
Detect truncation with agent.last_stop_reason instead of string-matching:
from praisonaiagents import Agent, ExecutionConfig
agent = Agent(
name="coder",
instructions="You are a coding assistant.",
execution=ExecutionConfig(max_steps=50),
)
result = agent.start("Refactor the auth module across all files")
if agent.last_stop_reason == "max_steps":
result = agent.start("Continue from where you left off.")On a gateway, surface the reason to chat users โ see Turn Completion Notes.
On the CLI: when a truncated run reaches praisonai run / praisonai-code run, the wrapper reports it distinctly from success โ exit code 2 (not 0), status: "truncated" under --output json / --output stream-json with the wrap-up summary preserved in result, plus a one-line stderr warning in interactive mode. See praisonai run โ Exit Codes.
Cap tool-use steps and detect graceful truncation with last_stop_reason
Best Practices
Catch the most specific class you can handle
Use ToolExecutionError when you only care about tool failures; reserve PraisonAIError for top-level logging.
Log structured context
Include e.error_category, e.agent_id, and e.run_id in observability hooks โ they correlate across multi-agent runs.
Don't swallow ValidationError
Validation failures usually mean a programming or config bug. Fix the root cause instead of retrying blindly.
Pair with loop guard for retry loops
Loop-guard HALT raises ToolExecutionError. Combine with Loop Guard when tools may repeat indefinitely.
Treat an LLMResponseError as a real failure, not an empty answer
A failed tool-calling loop now raises LLMResponseError instead of returning "". Catch it explicitly (from praisonaiagents.llm import LLMResponseError) so retries and observability see the actual error rather than a silent empty string.
Use PraisonAIError as the top-level catch for the whole wrapper
Every praisonai.* root exception (RecipeError, CLIExecutionError, JobQueueFull, ToolTimeoutError, and the rest listed under Wrapper exceptions) inherits from praisonaiagents.PraisonAIError. The 15 module exceptions โ gateway config/transport, bots capability/contract, auth, agent attachments/serialize, eval datasets, tools resolver, workflow state, knowledge cloud, runtime portable, and session encryption โ are reachable the same way. One top-level except PraisonAIError works as a safety net โ reserve specific types for branches that handle the failure differently.