Skip to content

Agent Zero AI framework

Show friendly Telegram errors

Anmol Malik92b728c3d770
diff --git a/plugins/_telegram_integration/extensions/python/_functions/agent/Agent/handle_exception/end/_85_telegram_error.py b/plugins/_telegram_integration/extensions/python/_functions/agent/Agent/handle_exception/end/_85_telegram_error.py
new file mode 100644
index 000000000..443df0d74
--- /dev/null
+++ b/plugins/_telegram_integration/extensions/python/_functions/agent/Agent/handle_exception/end/_85_telegram_error.py
@@ -0,0 +1,42 @@
+from helpers.errors import HandledException
+from helpers.extension import Extension
+from helpers.print_style import PrintStyle
+from plugins._telegram_integration.helpers.constants import (
+ CTX_TG_BOT,
+ CTX_TG_ERROR_SENT,
+ CTX_TG_REPLY_TO,
+ CTX_TG_TYPING_STOP,
+)
+
+
+class TelegramFriendlyError(Extension):
+ async def execute(self, data: dict = {}, **kwargs):
+ if not self.agent or self.agent.number != 0:
+ return
+
+ context = self.agent.context
+ if not context.data.get(CTX_TG_BOT):
+ return
+
+ exception = data.get("exception")
+ if not exception or isinstance(exception, HandledException):
+ return
+
+ if context.data.get(CTX_TG_ERROR_SENT):
+ return
+
+ context.data[CTX_TG_ERROR_SENT] = True
+
+ from plugins._telegram_integration.helpers import draft_stream, error_ui
+ from plugins._telegram_integration.helpers.handler import send_telegram_reply
+
+ text = error_ui.friendly_error_message(exception)
+ error = await send_telegram_reply(context, text)
+ if error:
+ PrintStyle.debug(f"Telegram error reply failed: {error}")
+
+ typing_stop = context.data.pop(CTX_TG_TYPING_STOP, None)
+ if typing_stop:
+ typing_stop.set()
+ draft_stream.clear(context)
+ context.data.pop(CTX_TG_REPLY_TO, None)
diff --git a/plugins/_telegram_integration/helpers/constants.py b/plugins/_telegram_integration/helpers/constants.py
index abab54ed2..1ef80c81a 100644
--- a/plugins/_telegram_integration/helpers/constants.py
+++ b/plugins/_telegram_integration/helpers/constants.py
@@ -22,3 +22,4 @@ CTX_TG_PROGRESS_LINES = "_telegram_progress_lines"
CTX_TG_RESPONSE_MESSAGE_ID = "_telegram_response_message_id"
CTX_TG_RESPONSE_TEXT = "_telegram_response_text"
CTX_TG_RESPONSE_LAST_UPDATE = "_telegram_response_last_update"
+CTX_TG_ERROR_SENT = "_telegram_error_sent"
diff --git a/plugins/_telegram_integration/helpers/draft_stream.py b/plugins/_telegram_integration/helpers/draft_stream.py
index a64cb47a6..22390fdff 100644
--- a/plugins/_telegram_integration/helpers/draft_stream.py
+++ b/plugins/_telegram_integration/helpers/draft_stream.py
@@ -18,6 +18,7 @@ from plugins._telegram_integration.helpers.constants import (
CTX_TG_RESPONSE_TEXT,
CTX_TG_STREAM_ENABLED,
CTX_TG_TOOLS_ENABLED,
+ CTX_TG_ERROR_SENT,
)
MAX_STREAM_CHARS: int = 3900
@@ -42,6 +43,7 @@ TOOL_EMOJIS: dict[str, str] = {
async def start(context: AgentContext) -> None:
+ context.data.pop(CTX_TG_ERROR_SENT, None)
# Do not pre-create a placeholder Telegram message. Wait until we have
# real assistant text so the stream starts with meaningful content.
if not _stream_enabled(context):
diff --git a/plugins/_telegram_integration/helpers/error_ui.py b/plugins/_telegram_integration/helpers/error_ui.py
new file mode 100644
index 000000000..b9db82ebb
--- /dev/null
+++ b/plugins/_telegram_integration/helpers/error_ui.py
@@ -0,0 +1,100 @@
+from __future__ import annotations
+
+import re
+
+
+MAX_DETAIL_CHARS = 500
+
+
+def friendly_error_message(exception: BaseException) -> str:
+ summary = _error_summary(exception)
+ category = _classify_error(exception, summary)
+
+ if category == "auth":
+ return (
+ "**Agent Zero hit a provider setup issue.**\n\n"
+ "The model provider rejected the request because an API key or credential is missing, invalid, or unauthorized.\n\n"
+ f"Details: `{summary}`\n\n"
+ "Please check the model/API key settings, then send the message again."
+ )
+
+ if category == "rate_limit":
+ return (
+ "**Agent Zero was rate limited by the model provider.**\n\n"
+ "The provider is asking us to slow down before trying again.\n\n"
+ f"Details: `{summary}`"
+ )
+
+ if category == "timeout":
+ return (
+ "**Agent Zero did not get a response in time.**\n\n"
+ "The provider or tool call timed out before the agent could finish this request.\n\n"
+ f"Details: `{summary}`"
+ )
+
+ if category == "provider":
+ return (
+ "**Agent Zero could not complete the model request.**\n\n"
+ "The model provider returned an error before the agent could finish.\n\n"
+ f"Details: `{summary}`"
+ )
+
+ return (
+ "**Agent Zero ran into an error while working on this.**\n\n"
+ f"Details: `{summary}`"
+ )
+
+
+def _classify_error(exception: BaseException, summary: str) -> str:
+ text = f"{type(exception).__name__} {summary}".lower()
+
+ if any(
+ marker in text
+ for marker in (
+ "api key",
+ "api_key",
+ "apikey",
+ "auth",
+ "credential",
+ "unauthorized",
+ "forbidden",
+ "invalid key",
+ "missing key",
+ "permission denied",
+ "401",
+ "403",
+ )
+ ):
+ return "auth"
+
+ if any(marker in text for marker in ("rate limit", "ratelimit", "too many requests", "429")):
+ return "rate_limit"
+
+ if any(marker in text for marker in ("timeout", "timed out", "deadline", "read timed out")):
+ return "timeout"
+
+ if any(
+ marker in text
+ for marker in (
+ "litellm",
+ "openai",
+ "anthropic",
+ "model",
+ "provider",
+ "badrequest",
+ "service unavailable",
+ "overloaded",
+ "503",
+ )
+ ):
+ return "provider"
+
+ return "generic"
+
+
+def _error_summary(exception: BaseException) -> str:
+ text = str(exception).strip() or type(exception).__name__
+ text = re.sub(r"\s+", " ", text)
+ if len(text) > MAX_DETAIL_CHARS:
+ text = f"{text[: MAX_DETAIL_CHARS - 3].rstrip()}..."
+ return text
diff --git a/tests/test_telegram_error_ui.py b/tests/test_telegram_error_ui.py
new file mode 100644
index 000000000..3b73fdf5b
--- /dev/null
+++ b/tests/test_telegram_error_ui.py
@@ -0,0 +1,96 @@
+import asyncio
+
+from plugins._telegram_integration.extensions.python._functions.agent.Agent.handle_exception.end import (
+ _85_telegram_error,
+)
+from plugins._telegram_integration.helpers import error_ui
+from plugins._telegram_integration.helpers.constants import (
+ CTX_TG_BOT,
+ CTX_TG_ERROR_SENT,
+ CTX_TG_REPLY_TO,
+ CTX_TG_TYPING_STOP,
+)
+
+
+class FakeContext:
+ def __init__(self):
+ self.data = {
+ CTX_TG_BOT: "main",
+ CTX_TG_REPLY_TO: 456,
+ }
+
+
+class FakeAgent:
+ number = 0
+
+ def __init__(self):
+ self.context = FakeContext()
+
+
+def test_friendly_error_message_for_missing_api_key():
+ message = error_ui.friendly_error_message(
+ RuntimeError("OPENAI_API_KEY is missing or invalid")
+ )
+
+ assert "provider setup issue" in message
+ assert "API key" in message
+ assert "OPENAI_API_KEY is missing or invalid" in message
+
+
+def test_friendly_error_message_for_rate_limit():
+ message = error_ui.friendly_error_message(
+ RuntimeError("Rate limit exceeded: too many requests")
+ )
+
+ assert "rate limited" in message
+ assert "too many requests" in message
+
+
+def test_telegram_exception_hook_sends_once_and_cleans_stream_state(monkeypatch):
+ sends = []
+ cleared = []
+ typing_stopped = []
+
+ async def fake_send(context, text, attachments=None, keyboard=None):
+ sends.append(
+ {
+ "text": text,
+ "reply_to": context.data.get(CTX_TG_REPLY_TO),
+ "attachments": attachments,
+ "keyboard": keyboard,
+ }
+ )
+ return None
+
+ def fake_clear(context):
+ cleared.append(True)
+
+ class FakeStop:
+ def set(self):
+ typing_stopped.append(True)
+
+ agent = FakeAgent()
+ agent.context.data[CTX_TG_TYPING_STOP] = FakeStop()
+
+ monkeypatch.setattr(
+ "plugins._telegram_integration.helpers.handler.send_telegram_reply",
+ fake_send,
+ )
+ monkeypatch.setattr(
+ "plugins._telegram_integration.helpers.draft_stream.clear",
+ fake_clear,
+ )
+
+ extension = _85_telegram_error.TelegramFriendlyError(agent=agent)
+ data = {"exception": RuntimeError("provider returned 503 service unavailable")}
+
+ asyncio.run(extension.execute(data=data))
+ asyncio.run(extension.execute(data=data))
+
+ assert len(sends) == 1
+ assert "could not complete the model request" in sends[0]["text"]
+ assert sends[0]["reply_to"] == 456
+ assert cleared == [True]
+ assert typing_stopped == [True]
+ assert agent.context.data[CTX_TG_ERROR_SENT] is True
+ assert CTX_TG_REPLY_TO not in agent.context.data