Skip to content

Errors and retries

Actionable tool error messages: what the model sees by default

See what the OpenAI Agents SDK, Pydantic AI and the AI SDK hand the model when a fetch tool fails, and write an error sentence the model can act on.

By Amaan Mcdonald, AgentFetch team · Published

This article was drafted with AI assistance from the sources listed below and edited and published by the AgentFetch team. Disclosure: the AgentFetch API, which this article mentions, is this site's own product.

A fetch error the model can act on
  • What failed: Name the tool, the URL and the kind of failure: not found, timeout, rate limit.
  • Retry or not: Say whether calling again with the same URL can help.
  • Next step: Give one action: ask the user, use another URL from the conversation, or stop.
  • Nothing leaked: Keep stack traces, keys and internal hostnames out of the text.

The fetch tool failed. The model will read something about it and decide what to do next. The question is what that something is, and in most frameworks you did not write it.

This post looks at one tool, fetch_page(url), in three frameworks, and at the text each one gives the model when the tool fails. Checked against the current docs and source in November 2026; these SDKs change often, so recheck before you rely on a detail.

What does the OpenAI Agents SDK show the model?

The default: when a function tool raises, the SDK runs its default failure function, and in the current source that returns one fixed sentence: "An error occurred while running the tool." The source comment says it does this without exposing the exception to the model.

It stops working when the model needs to tell a 404 from a timeout. Both look the same, so the model has to guess: it may retry a URL that will never exist, or answer from memory as if the page had been read.

The fix is your own failure_error_function, which receives the run context and the exception and returns the string the model sees. Pass None instead and the error is re-raised for your code to handle.

from typing import Any

import httpx
from agents import RunContextWrapper, function_tool


class FetchFailed(Exception):
    """An error whose message is written for the model."""


def fetch_error_text(ctx: RunContextWrapper[Any], error: Exception) -> str:
    if isinstance(error, FetchFailed):
        return str(error)
    return "fetch_page failed for an internal reason. Do not retry. Tell the user the page could not be read."


@function_tool(failure_error_function=fetch_error_text, timeout=30)
async def fetch_page(url: str) -> str:
    """Fetch one public web page and return its text."""
    async with httpx.AsyncClient(follow_redirects=True) as client:
        r = await client.get(url)
    if r.status_code == 404:
        raise FetchFailed(
            f"Page not found (HTTP 404) at {url}. Do not retry this URL. "
            "Use a URL from the conversation or ask the user for the right one."
        )
    if r.status_code >= 400:
        raise FetchFailed(f"HTTP {r.status_code} at {url}. Do not retry this URL in this run.")
    return r.text[:20000]

Timeouts have their own path. With the default timeout_behavior of "error_as_result", the model gets a timeout message instead of an exception; with the default text in the source, this tool would report Tool 'fetch_page' timed out after 30 seconds. The docs note that timeouts work only for async @function_tool handlers. Set "raise_exception" and a ToolTimeoutError fails the run instead.

What does Pydantic AI show the model?

The default: an ordinary exception from a tool does not reach the model at all. The retries docs say that anything else a tool raises, beyond the retry triggers, propagates out of the run. The run ends with an exception instead of an answer.

It stops working the moment a fetch fails for an everyday reason, like a moved page. Pydantic AI gives you two exceptions for that, and the difference is the outcome they record:

  • ModelRetry records outcome='retried': the call was wrong, here is why, try again. The default retry budget is 1 per tool, and once a tool's budget is used up the run raises UnexpectedModelBehavior.
  • ToolFailed records outcome='failed': the call was fine, the result is a failure, adapt. It does not use the retry budget, so bound it with UsageLimits; its request_limit defaults to 50.
import httpx
from pydantic_ai import Agent, ModelRetry, ToolFailed

agent = Agent("openai:gpt-6.1-sol", tool_timeout=30)


@agent.tool_plain
async def fetch_page(url: str) -> str:
    """Fetch one public web page and return its text."""
    if not url.startswith(("https://", "http://")):
        raise ModelRetry("Pass a full URL that starts with https://.")
    async with httpx.AsyncClient(follow_redirects=True) as client:
        r = await client.get(url)
    if r.status_code == 404:
        raise ToolFailed(
            f"Page not found (HTTP 404) at {url}. Do not retry this URL. "
            "Use a URL from the conversation or ask the user for the right one."
        )
    if r.status_code >= 400:
        raise ToolFailed(f"HTTP {r.status_code} at {url}. Do not retry this URL in this run.")
    return r.text[:20000]

A bad argument is a ModelRetry, because a corrected call can work. A 404 is a ToolFailed, because the same URL will fail again. If the model API has a native error or failed-status field for tool results, Pydantic AI uses it; otherwise the message is framed as {"error": ...}. A tool timeout counts as a retry, and the model sees "Timed out after {timeout} seconds."

What does the AI SDK show the model?

The default: when your tool's execute throws, the SDK adds the error as a tool-error content part, and the tools docs say this is there to enable automated roundtrips to the model in multi-step runs. Whatever you throw is what the next step works with.

It stops working when the thrown error is a library's raw failure, a network stack message or a parser complaint, written for a developer rather than for the model. Throw your own error with the sentence you want read:

import { tool } from "ai";
import { z } from "zod";

export const fetchPage = tool({
  description: "Fetch one public web page and return its text.",
  inputSchema: z.object({ url: z.string().url() }),
  execute: async ({ url }) => {
    const res = await fetch(url, { signal: AbortSignal.timeout(30_000) });
    if (res.status === 404) {
      throw new Error(
        `Page not found (HTTP 404) at ${url}. Do not retry this URL. ` +
          "Use a URL from the conversation or ask the user for the right one.",
      );
    }
    if (!res.ok) {
      throw new Error(`HTTP ${res.status} at ${url}. Do not retry this URL in this run.`);
    }
    return (await res.text()).slice(0, 20_000);
  },
});

In generateText, the failures stay readable for your code too: filter each step's content for parts whose type is tool-error.

What should the sentence say?

The default to copy: three parts, in this order. What failed (tool, URL, kind of failure), whether the same call can work again, and one next step. "Page not found (HTTP 404) at https://example.com/docs/v2. Do not retry this URL. Use a URL from the conversation or ask the user for the right one."

It stops working when the next step depends on your app. A research agent may be allowed to try another URL; a support bot should say it could not read the page. Write the next step for your agent, not a generic one. The error-handling guide covers what the orchestrator does around this sentence, and the post on answers after a failed fetch covers what happens when the model gets no clear failure at all.

If your tool calls an API, map its error codes to these sentences once. The AgentFetch API, for example, returns a per-URL status with an error tag such as CRAWL_NOT_FOUND or CRAWL_LIVECRAWL_TIMEOUT, and when nothing was charged its MCP errors end with "No credits were charged." The tags are listed in the API reference.

Where this breaks

  • A good sentence does not stop a model from retrying. Keep a hard limit in code: the retry budget in Pydantic AI, UsageLimits, or a step limit in your loop.
  • The OpenAI default is generic on purpose. When you replace it, keep stack traces, API keys and internal hostnames out of the text; return only what you wrote for the model.
  • An error page is still page content. If the body of an error page goes into the message, treat it as untrusted text like any other fetched page.

Frequently asked questions

What does the OpenAI Agents SDK tell the model when a function tool raises?

In the current source, the default failure function returns the fixed text "An error occurred while running the tool." It does not pass the exception to the model. You can supply your own failure_error_function, or pass None to have the error re-raised to your code.

What happens in Pydantic AI when a tool raises an ordinary exception?

It propagates out of the run instead of reaching the model. Raise ModelRetry to ask the model to correct its call, or ToolFailed to report a failed result the model should adapt to.

Does ToolFailed in Pydantic AI use up the tool's retry budget?

No. ToolFailed does not consume the per-tool retry budget, so the docs suggest bounding repeated failures with UsageLimits, for example request_limit.

What makes a tool error message actionable for an LLM?

It says what failed, whether a retry with the same input can help, and which single next step to take, in one or two plain sentences without stack traces or secrets.

Sources

  1. OpenAI Agents SDK: Tools (Documentation)
  2. openai-agents-python: src/agents/tool.py (Documentation)
  3. Pydantic AI: Retries (Documentation)
  4. Pydantic AI: Advanced tool features (Documentation)
  5. AI SDK Core: Tool calling (Documentation)