Skip to content
Docs
GitHub

Handle errors and cancel turns

Detect and recover from failed turns, cancel a long-running turn, and react to common error events from the SSE stream.

4 min readEdit on GitHub

Applies toFramework (not available)Self-hostedEverruns Demo

Turns can fail (the LLM rejected the request, a tool errored repeatedly) or be cancelled by the user. The event stream tells you which. This guide covers both paths.

Failures surface as turn.failed events:

async for event in client.events.stream(session.id):
if event.type == "turn.completed":
break
if event.type == "turn.failed":
message = event.data.get("error", "unknown")
code = event.data.get("error_code")
print(f"Turn failed [{code}]: {message}")
break

error is a human-readable string. error_code is a stable, machine-readable string; branch on it, not on the message text. Use it to decide whether to retry, surface to the user, or escalate:

RETRYABLE = {"provider_rate_limited", "provider_unavailable", "dependency_unavailable"}
if event.type == "turn.failed":
code = event.data.get("error_code")
if code in RETRYABLE:
... # wait, then retry with backoff
elif code in {"budget_exhausted", "budget_paused"}:
... # raise or resume the budget
else:
... # surface the message to the user

With the generic error disclosure mode, the displayed error_code collapses to processing_error to hide provider detail.

To cancel a turn that’s already running:

import asyncio
await client.messages.create(session.id, "Analyse every Python package on PyPI")
await asyncio.sleep(2)
await client.sessions.cancel(session.id)

Cancellation emits a turn.cancelled event, appends a user message noting the cancellation, and the worker emits a final agent message confirming the work was stopped. The session itself stays open and accepts new messages.

TERMINAL = {"turn.completed", "turn.failed", "turn.cancelled"}
async for event in client.events.stream(session.id):
if event.type in TERMINAL:
print(f"[{event.type}]")
if event.type == "turn.failed":
print(event.data.get("error"))
break

Failed turns don’t auto-retry from the application’s perspective (durable execution retries individual steps inside a turn, not the whole turn). To retry, send the message again:

async def send_with_retry(client, session_id, content, attempts=2):
for attempt in range(attempts):
await client.messages.create(session_id, content)
async for event in client.events.stream(session_id):
if event.type == "turn.completed":
return True
if event.type == "turn.failed":
if attempt == attempts - 1:
return False
break
return False

Don’t retry indefinitely, a turn that fails twice usually fails for a reason (rate limit, malformed prompt, missing capability). Surface to the user.

error_codeCauseAction
provider_rate_limitedLLM provider throttled the request. reason: "in_flight_budget_exhausted" means the provider’s in-flight spending limit is reached; retry_after is the wait in secondsWait, retry with backoff. When retry_after is at most 600 s, the session retries on its own (auto_retry: true), up to 3 times an hour
provider_usage_limit_reachedProvider subscription or plan limit hit; resets at a later timeWait for the reset time, or switch model
provider_unavailableProvider is down or unreachableRetry later, or switch provider
provider_quota_exhaustedProvider account is out of credits. requested_max_tokens and affordable_tokens are set when the balance covers fewer output tokens than requestedTop up the provider account, or lower max output tokens. The runtime first retries once with fewer max output tokens when the balance covers at least 4,096; otherwise the session checks for credits every minute for up to an hour and continues on its own (credit_wait: true), see turn.credit_shortfall
provider_misconfiguredMissing or invalid provider API keyFix the provider key
provider_attestation_requiredProvider needs an account confirmation (for example OpenRouter age verification)Complete it in the provider settings
model_unavailable / model_not_configuredModel missing, or none set for the agent or sessionPick a configured model
request_too_largeContext overflowed even after compactionTrim the conversation, start a fresh session
invalid_tool_schemaA tool definition was rejected by the providerFix the tool’s schema
budget_exhausted / budget_pausedThe budget has no room left, or is pausedRaise or resume the budget, see Enforce a budget
blocked_by_hookA user_prompt_submit hook rejected the messageChange the message or the hook
processing_errorUnclassified failure, or details hidden by disclosure modeCheck server logs

Cancellation is not a failure: sessions.cancel produces turn.cancelled, which needs no retry.