Skip to content

LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows

UN-4248 [FIX] Show LLM provider errors as a readable line with a model-not-found hint (#2325)

Deepak Ke344a5251778
diff --git a/unstract/sdk1/src/unstract/sdk1/exceptions.py b/unstract/sdk1/src/unstract/sdk1/exceptions.py
index 40889af87..d272d5a3e 100644
--- a/unstract/sdk1/src/unstract/sdk1/exceptions.py
+++ b/unstract/sdk1/src/unstract/sdk1/exceptions.py
@@ -1,3 +1,5 @@
+import ast
+import json
import logging
import re
@@ -131,6 +133,149 @@ def strip_litellm_prefix(error_message: str) -> str:
return cleaned.strip()
+# Prefixes litellm stacks ahead of the provider body, in order. Its subclasses
+# re-prefix the parent's message ("litellm.ContextWindowExceededError:
+# litellm.BadRequestError: ...") and some mappings repeat the class bare
+# ("AuthenticationError: MistralException - ...").
+_LITELLM_CLASS_PREFIX = re.compile(r"^(?:litellm\.)?(?:\w+Error|Timeout):\s*")
+# The provider tag is a word ending in Exception or Error, optionally followed
+# by a few words naming the failure (Azure, Bedrock), then a spaced dash.
+_PROVIDER_TAG_SEPARATOR = " - "
+_PROVIDER_TAG_SUFFIXES = ("Exception", "Error")
+# Calls routed through the OpenAI SDK carry its str(): "Error code: 404 - {...}".
+_OPENAI_SDK_PREFIX = re.compile(r"^Error code:\s*\d+\s+-\s+")
+_LITELLM_HANDLE_HINT = "Handle with `litellm."
+# The streaming path formats the raw httpx body with str(bytes): b'{...}'.
+_BYTES_REPR = re.compile(r"^b(['\"]).*\1$", re.DOTALL)
+# Bodies past this size are shown as-is rather than parsed.
+_MAX_PARSED_BODY_CHARS = 64_000
+
+
+def _strip_repeated(pattern: re.Pattern[str], text: str) -> str:
+ while True:
+ stripped = pattern.sub("", text, count=1)
+ if stripped == text:
+ return text
+ text = stripped
+
+
+def _strip_provider_tag(body: str) -> str:
+ head, separator, rest = body.partition(_PROVIDER_TAG_SEPARATOR)
+ if not separator:
+ return body
+ words = head.split(" ")
+ if not words[0].endswith(_PROVIDER_TAG_SUFFIXES):
+ return body
+ if not all(word.replace("_", "").isalnum() for word in words):
+ return body
+ return rest
+
+
+def _strip_handle_hint(body: str) -> str:
+ """Drop litellm's trailing "Handle with `litellm.<Class>`." advice."""
+ index = body.rfind(_LITELLM_HANDLE_HINT)
+ if index == -1 or not body.rstrip(" .").endswith("`"):
+ return body
+ return body[:index].rstrip(" .")
+
+
+def _unwrap_bytes_repr(body: str) -> str:
+ if not _BYTES_REPR.match(body):
+ return body
+ raw = ast.literal_eval(body)
+ if isinstance(raw, bytes):
+ return raw.decode("utf-8", errors="replace")
+ return body
+
+
+def _parse_body(body: str) -> object:
+ """Parse a provider body given as JSON or as a Python dict repr."""
+ if len(body) > _MAX_PARSED_BODY_CHARS or not body.startswith("{"):
+ return None
+ try:
+ return json.loads(body)
+ except ValueError:
+ pass
+ try:
+ return ast.literal_eval(body)
+ except (ValueError, SyntaxError):
+ return None
+
+
+def _extract_provider_message(body: str) -> tuple[str, str | None]:
+ """Pull the human message and request id out of a provider's error body.
+
+ Falls back to the body as-is when it cannot be parsed or has no known
+ message field.
+ """
+ payload = _parse_body(body)
+ if not isinstance(payload, dict):
+ return body, None
+
+ error = payload.get("error")
+ error_dict = error if isinstance(error, dict) else {}
+ message = (
+ error_dict.get("message")
+ or (error if isinstance(error, str) else None)
+ or payload.get("message")
+ or payload.get("detail")
+ )
+ request_id = payload.get("request_id") or error_dict.get("request_id")
+ if not isinstance(request_id, str):
+ request_id = None
+ if not isinstance(message, str) or not message:
+ return body, request_id
+ return message, request_id
+
+
+def format_provider_error(e: Exception) -> str:
+ """Render a litellm provider error as one readable line.
+
+ Keeps the error class and HTTP status that litellm's string form either
+ hides or buries, and points at the adapter's model when the provider
+ reports it as not found — Anthropic's 404 for a retired model says only
+ ``model: <id>``. Never raises: it runs inside error handlers, so anything
+ unparseable falls back to the litellm text.
+ """
+ cleaned = strip_litellm_prefix(str(e))
+ if not isinstance(e, openai.APIError):
+ return cleaned
+ try:
+ return _render_provider_error(e, cleaned)
+ except Exception:
+ logger.warning("Could not format provider error", exc_info=True)
+ return cleaned
+
+
+def _render_provider_error(e: openai.APIError, cleaned: str) -> str:
+ body = _strip_repeated(_LITELLM_CLASS_PREFIX, cleaned)
+ body = _strip_provider_tag(body)
+ body = _OPENAI_SDK_PREFIX.sub("", body, count=1)
+ body = _strip_handle_hint(body)
+ message, request_id = _extract_provider_message(_unwrap_bytes_repr(body))
+
+ label = type(e).__name__
+ # litellm assigns a status to failures that never got a response (a
+ # refused connection is an InternalServerError with 500); it records the
+ # response headers only when one actually came back.
+ status_code = getattr(e, "status_code", None)
+ if status_code and getattr(e, "litellm_response_headers", None) is not None:
+ label += f" (HTTP {status_code})"
+ text = f"{label}: {message}"
+ if request_id:
+ text += f" (request_id: {request_id})"
+
+ model = getattr(e, "model", None)
+ if isinstance(e, openai.NotFoundError) and model:
+ text = text.rstrip(". ")
+ text += (
+ f". Model '{model}' was not found by the provider; it may have "
+ "been retired, or the model name or endpoint may be incorrect. "
+ "Update the model configured in this adapter."
+ )
+ return text
+
+
def parse_litellm_err(e: Exception, provider_name: str | None = None) -> SdkError:
"""Parse litellm errors - both LLM and embedding provider's.
@@ -155,7 +300,7 @@ def parse_litellm_err(e: Exception, provider_name: str | None = None) -> SdkErro
or getattr(e, "code", None)
)
- cleaned_message = strip_litellm_prefix(str(e))
+ cleaned_message = format_provider_error(e)
err = SdkError(cleaned_message, actual_err=e, status_code=status_code)
if not provider_name:
diff --git a/unstract/sdk1/src/unstract/sdk1/llm.py b/unstract/sdk1/src/unstract/sdk1/llm.py
index 894a9b7d9..241601d16 100644
--- a/unstract/sdk1/src/unstract/sdk1/llm.py
+++ b/unstract/sdk1/src/unstract/sdk1/llm.py
@@ -15,7 +15,7 @@ from unstract.sdk1.adapters.constants import Common
from unstract.sdk1.adapters.llm1 import adapters
from unstract.sdk1.constants import Common as SdkCommon
from unstract.sdk1.constants import ToolEnv
-from unstract.sdk1.exceptions import LLMError, SdkError, strip_litellm_prefix
+from unstract.sdk1.exceptions import LLMError, SdkError, format_provider_error
from unstract.sdk1.platform import PlatformHelper
from unstract.sdk1.tool.base import BaseTool
from unstract.sdk1.utils.common import (
@@ -715,7 +715,7 @@ class LLM:
error_msg = (
f"Error from LLM adapter '{self._get_adapter_info()}': "
- f"{strip_litellm_prefix(str(e))}"
+ f"{format_provider_error(e)}"
)
raise LLMError(
@@ -808,7 +808,7 @@ class LLM:
error_msg = (
f"Error from LLM adapter '{self._get_adapter_info()}': "
- f"{strip_litellm_prefix(str(e))}"
+ f"{format_provider_error(e)}"
)
raise LLMError(
@@ -890,7 +890,7 @@ class LLM:
error_msg = (
f"Error from LLM adapter '{self._get_adapter_info()}': "
- f"{strip_litellm_prefix(str(e))}"
+ f"{format_provider_error(e)}"
)
raise LLMError(
@@ -970,7 +970,7 @@ class LLM:
error_msg = (
f"Error from LLM adapter '{self._get_adapter_info()}': "
- f"{strip_litellm_prefix(str(e))}"
+ f"{format_provider_error(e)}"
)
raise LLMError(
diff --git a/unstract/sdk1/tests/test_provider_error_message.py b/unstract/sdk1/tests/test_provider_error_message.py
new file mode 100644
index 000000000..0c246f63b
--- /dev/null
+++ b/unstract/sdk1/tests/test_provider_error_message.py
@@ -0,0 +1,418 @@
+"""Provider errors reach the user as one readable line.
+
+The exceptions here are real litellm exceptions, raised by litellm itself
+against a local HTTP server that answers with the provider's actual error
+body. That pins the contract to litellm's string format — streaming wraps
+the body in a bytes repr, Mistral repeats the class name — rather than to a
+hand-built approximation of it.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+import threading
+from functools import lru_cache
+from http.server import BaseHTTPRequestHandler, HTTPServer
+from importlib import import_module
+from types import ModuleType
+from typing import TYPE_CHECKING
+from unittest.mock import patch
+
+import litellm
+import pytest
+from unstract.sdk1.exceptions import (
+ LLMError,
+ SdkError,
+ format_provider_error,
+ parse_litellm_err,
+)
+
+if TYPE_CHECKING:
+ from collections.abc import Iterator
+
+ANTHROPIC_ADAPTER_ID = "anthropic|90ebd4cd-2f19-4cef-a884-9eeb6ac0f203"
+RETIRED_MODEL = "claude-sonnet-4-20250514"
+ANTHROPIC_RETIRED_BODY = {
+ "type": "error",
+ "error": {"type": "not_found_error", "message": f"model: {RETIRED_MODEL}"},
+ "request_id": "req_011CfbL1yvFpPPSQB81HnWmr",
+}
+OPENAI_NOT_FOUND_BODY = {
+ "error": {
+ "message": "The model `gpt-9` does not exist or you do not have access to it.",
+ "type": "invalid_request_error",
+ "param": None,
+ "code": "model_not_found",
+ }
+}
+ANTHROPIC_TOO_LONG = "prompt is too long: 210000 tokens > 200000 maximum"
+OPENAI_TOO_LONG = (
+ "This model's maximum context length is 128000 tokens. "
+ "However, your messages resulted in 210000 tokens."
+)
+_REAL_COMPLETION = litellm.completion
+
+
+class _ProviderStub:
+ """Local HTTP server answering every POST with one canned error."""
+
+ def __init__(self) -> None:
+ self.status = 500
+ self.body: object = {}
+ stub = self
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_POST(self) -> None: # noqa: N802
+ self.rfile.read(int(self.headers.get("content-length", 0)))
+ raw = (
+ stub.body
+ if isinstance(stub.body, bytes)
+ else json.dumps(stub.body).encode()
+ )
+ self.send_response(stub.status)
+ self.send_header("content-type", "application/json")
+ self.send_header("content-length", str(len(raw)))
+ self.end_headers()
+ self.wfile.write(raw)
+
+ def log_message(self, *args: object) -> None:
+ pass
+
+ self._server = HTTPServer(("127.0.0.1", 0), Handler)
+ self.url = f"http://127.0.0.1:{self._server.server_port}"
+ threading.Thread(target=self._server.serve_forever, daemon=True).start()
+
+ def respond(self, status: int, body: object) -> None:
+ self.status = status
+ self.body = body
+
+ def close(self) -> None:
+ self._server.shutdown()
+ self._server.server_close()
+
+
+def provider() -> Iterator[_ProviderStub]:
+ stub = _ProviderStub()
+ yield stub
+ stub.close()
+
+
+def _raise_from_litellm(provider: _ProviderStub, model: str, stream: bool) -> Exception:
+ try:
+ response = _REAL_COMPLETION(
+ model=model,
+ api_base=provider.url,
+ api_key="test-key",
+ messages=[{"role": "user", "content": "hi"}],
+ stream=stream,
+ num_retries=0,
+ )
+ if stream:
+ for _ in response:
+ pass
+ except Exception as e: # noqa: BLE001 - the exception is the subject
+ return e
+ pytest.fail("litellm did not raise")
+
+
[email protected]("stream", [False, True], ids=["non-streaming", "streaming"])
+def test_retired_anthropic_model_reads_as_model_not_found(
+ provider: _ProviderStub, stream: bool
+) -> None:
+ provider.respond(404, ANTHROPIC_RETIRED_BODY)
+ err = _raise_from_litellm(provider, f"anthropic/{RETIRED_MODEL}", stream)
+
+ message = format_provider_error(err)
+
+ assert message.startswith(f"NotFoundError (HTTP 404): model: {RETIRED_MODEL}")
+ assert "(request_id: req_011CfbL1yvFpPPSQB81HnWmr)" in message
+ assert f"Model '{RETIRED_MODEL}' was not found by the provider" in message
+ assert "retired" in message
+ for noise in ("b'", '{"type"', "AnthropicException", "litellm."):
+ assert noise not in message
+
+
+def test_plain_text_provider_message_is_kept(provider: _ProviderStub) -> None:
+ provider.respond(404, OPENAI_NOT_FOUND_BODY)
+ err = _raise_from_litellm(provider, "openai/gpt-9", stream=False)
+
+ message = format_provider_error(err)
+
+ assert message.startswith(
+ "NotFoundError (HTTP 404): The model `gpt-9` does not exist"
+ )
+ assert "Model 'gpt-9' was not found by the provider" in message
+ assert "OpenAIException" not in message
+
+
+def test_repeated_class_name_is_dropped_and_no_model_hint_on_auth(
+ provider: _ProviderStub,
+) -> None:
+ provider.respond(401, {"message": "Unauthorized", "request_id": "abc"})
+ err = _raise_from_litellm(provider, "mistral/mistral-large", stream=False)
+
+ assert format_provider_error(err) == (
+ "AuthenticationError (HTTP 401): Unauthorized (request_id: abc)"
+ )
+
+
+def test_non_json_body_is_shown_as_is(provider: _ProviderStub) -> None:
+ provider.respond(400, b"upstream exploded")
+ err = _raise_from_litellm(provider, "anthropic/claude-x", stream=True)
+
+ assert format_provider_error(err) == ("BadRequestError (HTTP 400): upstream exploded")
+
+
+def test_litellm_retry_suffix_is_still_stripped() -> None:
+ err = litellm.RateLimitError(
+ message="AnthropicException - slow down LiteLLM Retried: 3 times",
+ llm_provider="anthropic",
+ model="claude-x",
+ )
+
+ assert format_provider_error(err) == "RateLimitError: slow down"
+
+
+def test_non_provider_errors_keep_their_text() -> None:
+ assert format_provider_error(ValueError("bad metadata")) == "bad metadata"
+
+
[email protected]("stream", [False, True], ids=["non-streaming", "streaming"])
+def test_anthropic_error_tag_variant_is_parsed(
+ provider: _ProviderStub, stream: bool
+) -> None:
+ """Auth, overload and context-window errors use "AnthropicError - "."""
+ provider.respond(
+ 401,
+ {
+ "type": "error",
+ "error": {"type": "authentication_error", "message": "Invalid API Key"},
+ },
+ )
+ err = _raise_from_litellm(provider, "anthropic/claude-x", stream)
+
+ assert format_provider_error(err) == (
+ "AuthenticationError (HTTP 401): Invalid API Key"
+ )
+
+
+ ("model", "body", "too_long"),
+ [
+ (
+ "anthropic/claude-x",
+ {
+ "type": "error",
+ "error": {
+ "type": "invalid_request_error",
+ "message": ANTHROPIC_TOO_LONG,
+ },
+ },
+ ANTHROPIC_TOO_LONG,
+ ),
+ (
+ # Three levels: "litellm.ContextWindowExceededError: litellm.
+ # BadRequestError: ContextWindowExceededError: OpenAIException - "
+ "openai/gpt-4o",
+ {
+ "error": {
+ "type": "invalid_request_error",
+ "code": "context_length_exceeded",
+ "message": OPENAI_TOO_LONG,
+ }
+ },
+ OPENAI_TOO_LONG,
+ ),
+ ],
+ ids=["anthropic", "openai"],
+)
+def test_stacked_litellm_prefixes_are_stripped(
+ provider: _ProviderStub, model: str, body: dict[str, object], too_long: str
+) -> None:
+ provider.respond(400, body)
+ err = _raise_from_litellm(provider, model, stream=True)
+
+ assert isinstance(err, litellm.ContextWindowExceededError)
+ assert format_provider_error(err) == (
+ f"ContextWindowExceededError (HTTP 400): {too_long}"
+ )
+
+
+def test_litellm_handle_with_hint_is_dropped(provider: _ProviderStub) -> None:
+ provider.respond(
+ 500,
+ {
+ "type": "error",
+ "error": {"type": "api_error", "message": "Internal server error"},
+ "request_id": "req_1",
+ },
+ )
+ err = _raise_from_litellm(provider, "anthropic/claude-x", stream=False)
+
+ assert format_provider_error(err) == (
+ "InternalServerError (HTTP 500): Internal server error (request_id: req_1)"
+ )
+
+
+def test_azure_provider_tag_with_class_name_is_stripped(
+ provider: _ProviderStub,
+) -> None:
+ provider.respond(404, OPENAI_NOT_FOUND_BODY)
+ with pytest.raises(litellm.NotFoundError) as exc_info:
+ _REAL_COMPLETION(
+ model="azure/gpt-9",
+ api_base=provider.url,
+ api_key="test-key",
+ api_version="2024-02-01",
+ messages=[{"role": "user", "content": "hi"}],
+ num_retries=0,
+ )
+ message = format_provider_error(exc_info.value)
+
+ assert message.startswith(
+ "NotFoundError (HTTP 404): The model `gpt-9` does not exist"
+ )
+ assert "AzureException" not in message
+
+
[email protected]("model", ["openai/gpt-x", "anthropic/claude-x"])
+def test_refused_connection_does_not_claim_an_http_status(model: str) -> None:
+ """A refused connection reaches us as InternalServerError with 500."""
+ with pytest.raises(litellm.InternalServerError) as exc_info:
+ _REAL_COMPLETION(
+ model=model,
+ api_base="http://127.0.0.1:1",
+ api_key="test-key",
+ messages=[{"role": "user", "content": "hi"}],
+ num_retries=0,
+ )
+ message = format_provider_error(exc_info.value)
+
+ assert "HTTP" not in message
+
+
+def test_connection_errors_do_not_claim_an_http_status() -> None:
+ err = litellm.APIConnectionError(
+ message="Service account info was not in the expected format",
+ llm_provider="vertex_ai",
+ model="gemini-x",
+ )
+
+ message = format_provider_error(err)
+
+ assert message.startswith("APIConnectionError: ")
+ assert "HTTP" not in message
+
+
+def test_multi_word_provider_tag_is_stripped(
+ provider: _ProviderStub, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ for key, value in {
+ "AWS_ACCESS_KEY_ID": "test",
+ "AWS_SECRET_ACCESS_KEY": "test",
+ "AWS_REGION_NAME": "us-east-1",
+ }.items():
+ monkeypatch.setenv(key, value)
+ invalid = "The security token included in the request is invalid."
+ provider.respond(403, {"message": invalid})
+ err = _raise_from_litellm(
+ provider, "bedrock/anthropic.claude-3-sonnet-20240229-v1:0", stream=False
+ )
+
+ message = format_provider_error(err)
+
+ assert message.endswith(f"(HTTP 403): {invalid}")
+ assert "BedrockException" not in message
+
+
+def test_model_hint_does_not_double_the_period(provider: _ProviderStub) -> None:
+ provider.respond(
+ 404,
+ {
+ "error": {
+ "code": "DeploymentNotFound",
+ "message": "The API deployment for this resource does not exist.",
+ }
+ },
+ )
+ with pytest.raises(litellm.NotFoundError) as exc_info:
+ _REAL_COMPLETION(
+ model="azure/dep",
+ api_base=provider.url,
+ api_key="test-key",
+ api_version="2024-02-01",
+ messages=[{"role": "user", "content": "hi"}],
+ num_retries=0,
+ )
+ message = format_provider_error(exc_info.value)
+
+ assert "does not exist. Model 'dep' was not found" in message
+ assert ".." not in message
+
+
+def test_unparseable_body_never_raises() -> None:
+ # Deep enough for json.loads to raise RecursionError, short enough to be
+ # parsed at all.
+ deeply_nested = '{"a":' * 10000 + "1" + "}" * 10000
+ err = litellm.BadRequestError(
+ message=f"AnthropicException - {deeply_nested}",
+ llm_provider="anthropic",
+ model="claude-x",
+ )
+
+ assert format_provider_error(err).startswith("AnthropicException - {")
+
+
+def test_embedding_errors_use_the_same_format(provider: _ProviderStub) -> None:
+ """Embeddings go through the OpenAI SDK, whose body is a dict repr."""
+ provider.respond(404, OPENAI_NOT_FOUND_BODY)
+ with pytest.raises(litellm.NotFoundError) as exc_info:
+ litellm.embedding(
+ model="openai/gpt-9",
+ api_base=provider.url,
+ api_key="test-key",
+ input=["hi"],
+ )
+ wrapped = parse_litellm_err(exc_info.value, "my-embedding (OpenAI)")
+
+ assert isinstance(wrapped, SdkError)
+ assert wrapped.status_code == 404
+ assert wrapped.message.startswith("Error from my-embedding (OpenAI).")
+ assert "NotFoundError (HTTP 404): The model `gpt-9` does not exist" in wrapped.message
+ assert "Error code" not in wrapped.message
+ assert "{'error'" not in wrapped.message
+
+
+@lru_cache(maxsize=1)
+def _load_llm_module() -> object:
+ sys.modules.setdefault("magic", ModuleType("magic"))
+ return import_module("unstract.sdk1.llm")
+
+
+def test_llm_complete_surfaces_the_readable_error(provider: _ProviderStub) -> None:
+ """End to end through ``LLM.complete`` — the path API deployments hit."""
+ provider.respond(404, ANTHROPIC_RETIRED_BODY)
+ llm = _load_llm_module().LLM(
+ adapter_id=ANTHROPIC_ADAPTER_ID,
+ adapter_metadata={"model": RETIRED_MODEL, "api_key": "test-key"},
+ )
+
+ def to_stub(**kwargs: object) -> object:
+ return _REAL_COMPLETION(**{**kwargs, "api_base": provider.url})
+
+ with (
+ patch.object(litellm, "completion", side_effect=to_stub),
+ pytest.raises(LLMError) as exc_info,
+ ):
+ llm.complete("hi")
+
+ err = exc_info.value
+ assert err.status_code == 404
+ assert err.message.startswith(
+ "Error from LLM adapter 'anthropic': "
+ f"NotFoundError (HTTP 404): model: {RETIRED_MODEL}"
+ )
+ assert "Update the model configured in this adapter." in err.message
+ assert "b'" not in err.message