Gateway Error Handling

Unicode-safe error handling for Gateway bot replies with root-cause extraction

Gateway error handling automatically sanitises exception text to prevent encoding crashes while preserving meaningful error information for users.

python
from praisonaiagents import Agent

agent = Agent(
    name="Assistant",
    instructions="Help the user",
    model="gpt-4o-mini",
)
# Gateway bots receive clean ASCII-safe errors โ€” not raw stack traces
agent.start("What's the weather?")

The user sends a message that triggers an internal error; the gateway sanitises the exception to ASCII-safe text in the reply while logging full detail.

Diagram

Error Handling Flow

โš ๏ธ Exception

๐Ÿ” Extract Root Cause

๐Ÿ”ง Sanitize to ASCII

๐Ÿ’ฌ User Reply

๐Ÿ“ Full Unicode Log

Quick Start

  1. Simple Usage

    Error handling is automatic โ€” no configuration needed. When agents throw exceptions containing Unicode characters, the gateway safely converts them for bot replies.

    python
    from praisonaiagents import Agent
    
    agent = Agent(
        name="Assistant",
        instructions="Help the user",
        model="gpt-4o-mini"
    )
    # When the agent hits an API error (quota, rate limit, auth, timeout),
    # the gateway sends the user a clean message โ€” not a stack trace.
    agent.start("What's the weather?")
  2. Test Error Handling

    Verify your version includes Unicode-safe error handling:

    bash
    python -c "from praisonai_bot.gateway.unicode_utils import safe_error_message; print('OK')"

    If this runs without error, your install includes the ASCII-safe error sanitizer (originally PraisonAI PR #1754; extended in PR #3430 to strip box-drawing frame characters).


How It Works

Diagram
AgentGatewayBotUserAgentGatewayBotUserSend messageForward to agentProcess requestException with Unicode (โš ๏ธ quota exceeded)Extract root causeSanitize to ASCII-safe text“API quota exceeded. Check billing.”Clean error message

The gateway processes exceptions in three stages:

  1. Root-cause extraction โ€” identifies the underlying API error
  2. Unicode sanitization โ€” converts symbols to ASCII-safe equivalents
  3. Safe reply โ€” sends clean message to user via bot

Related Helpers

The unicode_utils module exports two sibling helpers alongside safe_error_message.

HelperPurpose
safe_log_message(exc)Preserves Unicode for UTF-8-capable log handlers, replacing lone surrogates (U+D800โ€“U+DFFF) with U+FFFD. Use it for logs instead of user-facing replies.
extract_root_cause_from_error(text)Pulls the underlying API error out of chained exceptions before sanitising โ€” this powers the Recognized Error Types table below.

Configuration Options

Error handling is automatic with no required configuration. The feature is included in PraisonAI versions containing PR #1754.

Gateway Error Handling Reference

Source implementation details in PraisonAI PR #1754


Structured Connection Errors

The hello handshake returns machine-readable ConnectErrorCode values (auth_required, auth_unauthorized, protocol_unsupported, pairing_required, agent_not_found) with optional next_action hints โ€” instead of free-text-only connection failures.

Codes fall into two client-side classes: transient (rate_limited โ€” back off and retry) and terminal (auth_required, auth_unauthorized, pairing_required, protocol_unsupported, agent_not_found, origin_not_allowed, configuration_error โ€” reconnect loop stops until an operator intervenes). See Gateway Client โ†’ Terminal vs Transient Connect Errors for how GatewayClient handles each class and the on_reconnect_paused callback.

See Gateway Handshake Protocol for the full error matrix and capability negotiation.


Structured turn-failure error (wire)

The Unicode sanitiser protects chat-reply text; the typed outcome.error on the final response frame protects programmatic clients (operator UIs, OpenAI-compat consumers, custom bots).

The end-user text comes from a fixed per-code table (_TURN_ERROR_MESSAGES), never str(e). See Gateway Turn Error Codes for the full code vocabulary.


Reconnect After Disconnect

Pending inbox messages and in-flight executions are preserved when a WebSocket disconnects. On reconnect with the same session_id, the client receives a status frame:

json
{
  "type": "status",
  "message": "Resuming processing (2 pending messages)..."
}

Queued messages are processed in FIFO order. See Gateway Session Continuity for drain behaviour and persisted session shape.


Common Patterns

Recognized Error Types

The gateway automatically recognizes and formats these error patterns:

Pattern matched in exceptionUser-facing reply
`Error code:
  • <msg> (OpenAI format) | Error

: <msg> | | HTTP

: <msg> | Error

: <msg> | | Contains quota (exceeded / insufficient) | API quota exceeded. Check billing. | | Contains rate limit (exceeded) | Rate limit exceeded. Try again later. | | Contains authentication (failed) | Authentication failed. Check API key. | | Contains timeout | Request timeout. Try again.` | | (anything else) | Original error text, sanitized to ASCII |

Symbol Replacements

Unicode symbols are replaced with ASCII equivalents:

UnicodeASCIIDescription
โš !Warning sign
โœ“OKCheck mark
โœ—XBallot X
โ†’->Right arrow
โ†<-Left arrow
โ€ข*Bullet
ยฎ(R)Registered sign
ยฉ(C)Copyright sign
โ€ฆ...Horizontal ellipsis
" ""Smart double quotes
' ''Smart single quotes
โ€“-En dash
โ€”--Em dash
โ”€ โ” โ”‚ โ”ƒ โ• โ•‘ โ•” โ•— โ•š โ• โ”Œ โ” โ”” โ”˜spaceBox-drawing frame characters (e.g. Playwright’s playwright install banner) โ€” replaced with spaces so the actionable hint stays readable on Windows cp1252 consoles

Accented letters (รก, รฉ, รฑ, etc.) are converted to their base forms (a, e, n).

Before vs After

Before PR #1754 (broken on Windows):

User sees: 'charmap' codec can't encode character 'โš ' in position 27: character maps to <undefined>

After PR #1754 (safe on all platforms):

User sees: API quota exceeded. Check billing.

Before PR #3430 (cluttered ? placeholders around the frame on Windows cp1252):

User sees: ? Please run: playwright install ?

After PR #3430 (frame collapses to spaces, hint stays readable):

User sees: Please run: playwright install

Best Practices

Monitor Gateway Logs

Full Unicode exception details are preserved in gateway logs for debugging while users see clean ASCII-safe messages.

bash
praisonai gateway logs
Handle API Quota Limits

Set up billing alerts and monitor usage to prevent quota exceeded errors:

bash
# Users see: "API quota exceeded. Check billing."
# Solution: Add credits at platform.openai.com
Test Cross-Platform Compatibility

The Unicode-safe error handling works on Windows, macOS, and Linux:

python
# Test with Unicode in agent instructions or error messages
agent = Agent(
    name="Test",
    instructions="Handle errors with Unicode: โš ๏ธ warnings, โœ… success",
    model="gpt-4o-mini"
)
Upgrade Legacy Environments

No workaround needed on supported versions. Previously recommended environment variables (PYTHONUTF8=1) are no longer required for the bot reply path.


Related