OpenAI's Agents SDK Now Hides Tool Exceptions From the Model. Decide What It Sees
Book: Hexagonal Architecture in Python
Companion code: hexagonal-python-examples - every listing from the book, free on GitHub
My project: Hermes IDE | GitHub - an IDE for developers who ship with Claude Code and other AI coding tools
Me: xgabriel.com | GitHub
Until this fall, a tool that raised in the OpenAI Agents SDK for Python sent this to the model by default:
An error occurred while running the tool. Please try again. Error:
{str(error)}.
That f-string is in the 0.22.3 source. Whatever your database driver put in its exception, the model got to read.
PR #5112, merged on September 20 as commit 40956e0, replaced it with a fixed sentence. The PR says the old handling could expose sensitive exception text to the model and to handled-error traces. It doesn't describe a real leak, and neither does this post. It closes one hole and leaves you a decision.
A model that only hears "an error occurred" can't tell a mistyped order ID from a dead database.
What changed, release by release
The change is listed in the 0.23.0 GitHub release, but that version isn't on PyPI. The file index goes from 0.22.3 straight to 0.23.1. The 0.23.1 notes say the runtime source differs from 0.23.0 only in its version string. If you install from PyPI, 0.23.1 is the first version with the fix.
These are the stable versions and their PyPI dates:
| Version | Date (2026) | What the model gets by default |
|---|---|---|
| 0.22.3 | Sep 17 | fixed text, plus str(error) |
| 0.23.1 | Oct 2 | An error occurred while running the tool. Please try again. |
| 0.24.0 | Oct 15 | same as 0.23.1 |
| 0.25.0 | Nov 18 | An error occurred while running the tool. |
| 0.26.0 | Nov 24 | same as 0.25.0 |
The 0.25.0 row is a second fix. Issue #5573, opened on November 7, includes a repro on 0.24.0 with a scripted model standing in for a live one: a write succeeded, the reply was lost, the default text said to try again, the script did, and two orders were committed.
PR #5632 removed the advice with a one-line reason: "A tool can raise after a write succeeds, and the SDK cannot determine whether repeating the call is safe."
The SDK can't tell what your exception contains or whether the call took effect. Your order code can tell you the first, and sometimes the second.
Why str(exception) was a bad message to send
SQLAlchemy is a good example because its error strings are so helpful to humans. When a statement fails, StatementError builds its text from the message, then [SQL: ...], then [parameters: ...]. You can read that in _sql_message() in 2.1.9. The SQLAlchemy error docs show one with the full INSERT statement and every bound value. If a tool looked up a customer by email, that email is one of those values.
create_engine(hide_parameters=True) keeps parameters out of INFO logging and out of the string form of StatementError. Turn it on, but it covers only part of the string. The SQL is still there, with your table and column names. So is the driver's own message, because DBAPIError embeds str(orig) before the parameters are considered.
On PostgreSQL, a duplicate key comes with a detail line like DETAIL: Key (email)=(a****@example.com) already exists. libpq's default verbosity includes detail fields, and psycopg builds its message from libpq's. With psycopg, the value SQLAlchemy hid can come back through the driver.
asyncpg depends on your SQLAlchemy version: 2.0.58 copies the driver's full string, while the 2.1 docs say the DETAIL line may be missing. Hiding the parameters closes one exit. The driver's own message is another.
The fixed sentence leaves the model blind
The generic message keeps exception text away from the model, but it's nothing a model can act on. The request for something better arrived within days of the PyPI release. Issue #5324, opened on October 6, calls the new string "a sensible secure default", then points out that tools added later fall back to it, "so the model can no longer self-correct bad arguments."
Take a tool called cancel_order. These three failures now look identical to the model:
- The order ID doesn't exist. Asking the customer for it again fixes this.
- The order already shipped, so the model should offer a return.
- The connection dropped mid-write. Nobody knows if it was applied, and the model has to stop.
The obvious repair is the SDK's per-tool failure_error_function, which receives the exception and returns the text for the model. It fixes the model's view but has a catch in the trace. In 0.26.0's error handler, the span gets the raw error text when sensitive tracing is allowed and the resolved handler is anything other than the default one.
Sensitive tracing is on by default, and traces go to the OpenAI backend by default. Writing your own careful formatter can put str(error) back into the exported span.
The run-wide hook added in 0.24.0 is better behaved. RunConfig.tool_error_formatter can handle kind="tool_exception", and its PR says original exceptions "remain redacted in handled-error traces even when sensitive tracing is enabled." It covers only function tools that use the default handler, so Agent.as_tool(), local MCP tools, timeouts and cancellation keep their own policies. It is still one callback for the whole run, and knowing that a shipped order can't be cancelled belongs next to the order code.
The other option is inside the tool, before the SDK sees any exception.
An adapter that names the failures
In ports and adapters terms, the tool is a driving adapter. It takes a call from the outside, talks to your core through a port, and translates the result. An HTTP endpoint already does this when it turns "not found" into a 404. A tool needs the same translation, with a model as the reader.
The port and the failures it names:
# orders/port.py
from typing import Protocol
class OrderError(Exception):
"""A refusal the domain knows by name.
Contract: if one of these is raised, nothing changed.
"""
class OrderNotFound(OrderError):
pass
class AlreadyShipped(OrderError):
pass
class Orders(Protocol):
async def cancel(self, order_id: str) -> None:
...
The adapter has no SDK import and no SQLAlchemy import. It starts with the sentences:
# orders/agent_adapter.py
import logging
import traceback
from uuid import uuid4
from orders.port import (
AlreadyShipped,
OrderError,
OrderNotFound,
Orders,
)
log = logging.getLogger("orders.agent")
MESSAGES: dict[type[OrderError], str] = {
OrderNotFound: (
"No order has that ID. Nothing was changed. "
"Ask the customer to check the ID."
),
AlreadyShipped: (
"That order has shipped and cannot be cancelled. "
"Nothing was changed. Offer a return instead."
),
}
These are constants, with nothing interpolated from the exception. If a colleague later writes raise OrderNotFound(f"no row for {email}"), the model still gets the fixed sentence.
explain looks them up by exact type, so a new subclass of OrderError gets the generic reply until someone writes a sentence for it:
# orders/agent_adapter.py, continued
def explain(exc: Exception, tool: str) -> str:
known = MESSAGES.get(type(exc))
if known is not None:
return known
ref = uuid4().hex[:8]
orig = getattr(exc, "orig", None)
frames = traceback.format_tb(exc.__traceback__)
log.error(
"tool=%s ref=%s type=%s sqlstate=%s\n%s",
tool,
ref,
type(exc).__name__,
getattr(orig, "sqlstate", None),
"".join(frames),
)
return (
"The order system failed and the outcome is unknown. "
"Do not call this tool again for this request. "
f"Give the customer reference {ref}."
)
The reply says the outcome is unknown because, for a write, "failed" would be a guess. For a read-only tool, you can write a softer version that allows one retry.
The log line skips the exception text too. log.exception would write the full message, parameters included, into your logs. traceback.format_tb formats only the stack frames and their source lines. You also get the type and, when the driver error has one, the SQLSTATE. orig is the one place the adapter knows what a SQLAlchemy error looks like. It only feeds the log, and an exception without it logs None there.
You need this line, because the SDK won't write it for you: tool data logging is off by default, and in that mode a handled failure is one debug message without the details.
The function your tool calls does the catching:
# orders/agent_adapter.py, continued
async def cancel_order_reply(orders: Orders, order_id: str) -> str:
try:
await orders.cancel(order_id)
except Exception as exc:
return explain(exc, tool="cancel_order")
return "The order is cancelled."
In the core, raise OrderNotFound for an order that belongs to another customer too. A separate "not yours" message would confirm that the ID exists. That check needs to know who is asking, and the customer must come from your session, never from a tool argument. Build orders per request, already scoped to the signed-in customer, and pass that to build_agent below.
Failures go through the desk, and a prepared card leaves toward the model.
Wire it to the SDK, keep the default handler
The SDK part stays thin:
# orders/agent.py
from agents import Agent, function_tool
from orders.agent_adapter import cancel_order_reply
from orders.port import Orders
def build_agent(orders: Orders) -> Agent:
@function_tool
async def cancel_order(order_id: str) -> str:
"""Cancel one order by its ID."""
return await cancel_order_reply(orders, order_id)
return Agent(
name="Support",
instructions="Help customers with their orders.",
tools=[cancel_order],
)
There's no failure_error_function here on purpose. Ordinary exceptions from the order code are caught inside the function, so the SDK gets no exception text from them to send, trace or log. The default handler remains as the backstop for what happens outside your body, such as malformed arguments, and it keeps its redacted span.
If you want the model to fix bad arguments on its own, add the run-wide formatter and have it return an approved hint. The function span still records the tool's input and output while sensitive tracing is on, so arguments reach the trace whatever you do with errors. Set trace_include_sensitive_data=False if those are private.
Also, except Exception leaves asyncio.CancelledError alone, since it derives from BaseException. Leave it uncaught, because swallowing it breaks cancellation. That has a cost: if one escapes the tool body, the SDK can hand the model its default sentence instead of your "outcome is unknown" one, and your adapter logs nothing. It's one more reason to put an idempotency key under the write.
Test it with a fake that raises
The tests run on plain pytest, without a model or a database. Run them from the project root with python -m pytest.
The fake raises whatever you hand it:
# tests/test_agent_adapter.py
import asyncio
import logging
import pytest
from sqlalchemy.exc import IntegrityError, StatementError
from orders.agent_adapter import MESSAGES, cancel_order_reply
from orders.port import OrderError
SECRET = "a****@example.com"
class RaisingOrders:
def __init__(self, exc: Exception) -> None:
self.exc = exc
async def cancel(self, order_id: str) -> None:
raise self.exc
def reply(exc: Exception) -> str:
orders = RaisingOrders(exc)
return asyncio.run(cancel_order_reply(orders, "A-1"))
The dangerous exceptions are real SQLAlchemy objects. The first carries the email in its bound parameters. The second hides the parameters and carries it in the driver's message, which is the hide_parameters=True gap from earlier, kept as a regression test:
# tests/test_agent_adapter.py, continued
def with_parameters() -> Exception:
return StatementError(
"connection lost",
"UPDATE orders SET state='x' WHERE email=:email",
{"email": SECRET},
None,
)
def with_driver_detail() -> Exception:
driver = Exception(
"duplicate key value\n"
f"DETAIL:Key (email)=({SECRET}) already exists."
)
return IntegrityError(
"INSERT INTO cancellations (email) VALUES (:email)",
{"email": SECRET},
driver,
hide_parameters=True,
)
The leak test runs both through the adapter and reads the reply and the log:
# tests/test_agent_adapter.py, continued
@pytest.mark.parametrize("make", [with_parameters, with_driver_detail])
def test_unknown_failure_leaks_nothing(make, caplog):
exc = make()
assert SECRET in str(exc) # the fake is dangerous
with caplog.at_level(logging.ERROR):
text = reply(exc)
assert SECRET not in text
assert "cancellations" not in text
assert "outcome is unknown" in text
assert SECRET not in caplog.text
assert type(exc).__name__ in caplog.text
Don't delete the first assertion. It proves the fake carries the secret before the rest check that the reply and caplog don't. Without it, a change in how SQLAlchemy formats errors could leave you with a test that passes because there was nothing to leak.
The remaining tests pin the mapping:
# tests/test_agent_adapter.py, continued
@pytest.mark.parametrize("kind", list(MESSAGES))
def test_named_failures_ignore_exception_text(kind):
assert reply(kind(SECRET)) == MESSAGES[kind]
def test_unmapped_domain_error_fails_closed():
class BrandNew(OrderError):
pass
assert "outcome is unknown" in reply(BrandNew(SECRET))
def test_each_named_failure_reads_differently():
texts = list(MESSAGES.values())
assert len(set(texts)) == len(texts)
These tests cover what your adapter says. Whether a given model then asks for the ID or obeys "do not call this tool again" is a separate eval, and for a write like this you want that idempotency key underneath anyway.
Start with your most dangerous write tool. List the ways it can refuse, give each one a name and a sentence, and send everything else to the log with a reference.
If this was useful
The trick here is an old one: the code that knows about orders shouldn't know who is calling, and whoever is calling shouldn't see the
Comments
No comments yet. Start the discussion.