-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_errors.py
More file actions
63 lines (51 loc) · 2.78 KB
/
Copy pathapi_errors.py
File metadata and controls
63 lines (51 loc) · 2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
"""Typed, human-readable wrapping of OpenAI API failures.
Both the raw vision call (`client.responses.create` in `image_parser.py`) and
the LangChain chat calls (`ChatOpenAI.invoke` in the two agents) surface the
same `openai.APIError` hierarchy on failure — LangChain does not swallow or
re-wrap it. This module gives every call site a single place to translate
that hierarchy into an actionable message instead of letting a raw SDK
exception (or a generic `except Exception`) reach the CLI unexplained.
"""
from __future__ import annotations
import openai
class ContractAnalysisAPIError(RuntimeError):
"""A call to the OpenAI API failed in a way the caller should act on."""
def describe_openai_error(exc: openai.APIError) -> str:
"""Map a specific `openai.APIError` subtype to an actionable message."""
if isinstance(exc, openai.RateLimitError):
return (
"Límite de rate de OpenAI alcanzado (HTTP 429). Esperá unos "
"segundos y reintentá, o revisá tu cuota en "
"platform.openai.com/usage."
)
if isinstance(exc, openai.APITimeoutError):
return (
f"La llamada a OpenAI superó el timeout configurado ({exc}). "
"La imagen o el prompt pueden ser demasiado grandes, o el "
"servicio está respondiendo lento; podés subir OPENAI_TIMEOUT_SECONDS."
)
if isinstance(exc, openai.BadRequestError):
body = exc.body if isinstance(getattr(exc, "body", None), dict) else {}
code = body.get("code") if isinstance(body, dict) else None
if code == "context_length_exceeded":
return (
"El contrato transcripto excede la ventana de contexto del "
"modelo. Dividí el documento en partes más chicas o usá un "
"modelo con una ventana de contexto mayor."
)
return f"OpenAI rechazó la solicitud (HTTP 400): {exc}"
if isinstance(exc, openai.AuthenticationError):
return "OPENAI_API_KEY inválida, revocada o sin permisos (HTTP 401)."
if isinstance(exc, openai.APIConnectionError):
return f"No se pudo conectar con la API de OpenAI: {exc}"
if isinstance(exc, openai.APIStatusError):
return f"OpenAI devolvió un error HTTP {exc.status_code}: {exc}"
return str(exc)
def reraise_openai_error(exc: openai.APIError) -> None:
"""Re-raise `exc` as a `ContractAnalysisAPIError` with an actionable message.
Always raises; the `-> None` return type only reflects that it never
returns normally. Chaining with `from exc` keeps the original traceback
(and the original exception's `status_code`/`body`) available for
debugging while the message on top is the one a human should read first.
"""
raise ContractAnalysisAPIError(describe_openai_error(exc)) from exc