File size: 6,040 Bytes
57fa15f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a7e08a9
 
 
 
 
 
 
57fa15f
 
 
 
 
 
 
a7e08a9
57fa15f
 
 
1997812
 
 
 
 
 
 
 
 
 
57fa15f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
"""Say what actually went wrong when a model provider refuses a call.

Stages retry a failed call a few times and, when every attempt fails, report
that they produced nothing. The message they raise names the most likely cause
in their own terms - "the planner returned no plan, review the blueprint" - and
that is wrong often enough to be harmful. Three runs of the same bag failed with
that sentence while the real causes were, in order: a schema keyword the
provider rejected, a second schema keyword, and an exhausted credit limit. Each
time the designer was told to go and look at a blueprint that was fine.

For someone using the product rather than building it, this is the difference
between "top up the account" and an afternoon rewriting a correct document.

So the exception that actually ended the attempts is carried out of the stage
and translated here. Anything unrecognised keeps its own text rather than being
smoothed into a guess.
"""

from __future__ import annotations

import re

# Matched against the exception's text, in order. First hit wins.
_PATTERNS: list[tuple[str, str]] = [
    (
        r"more credits|insufficient credits|can only afford|key limit exceeded"
        r"|402|403",
        "انتهى رصيد OpenRouter أو بلغ المفتاح حدّه (Key limit exceeded). افتح "
        "https://openrouter.ai/settings/keys وارفع حدّ المفتاح أو اشحن الحساب.",
    ),
    (
        r"invalid api key|no auth credentials|user not found|401",
        "مفتاح OpenRouter غير صالح أو غير مُصرَّح به. راجع OPENROUTER_API_KEY.",
    ),
    (
        r"rate limit|429|too many requests",
        "تجاوزت الحد المسموح من الطلبات على OpenRouter. أعد المحاولة بعد قليل.",
    ),
    (
        # Named by the notebook as the first thing to suspect: model ids on
        # OpenRouter change, and the failure lands on the first call of a stage
        # rather than at startup.
        r"\b404\b|no endpoints found|not a valid model|model not found",
        "الموديل المطلوب غير متاح على OpenRouter بهذا الاسم. غالبًا تغيّر "
        "معرّفه — راجع سلاسل البدائل في app/agents/arabic_bag/llms.py.",
    ),
    (
        r"output_config\.format\.schema|is not supported|minItems|maxItems",
        "رفض المزوّد شكل مخطط المخرجات. هذه مشكلة في النظام لا في مدخلاتك — "
        "أبلغ الفريق بنص الخطأ.",
    ),
    (
        r"context length|maximum context|too long|token limit",
        "المحتوى المطلوب أطول مما يقبله الموديل في نداء واحد. قلّل عدد المحاور "
        "في اليوم الواحد أو قسّم الحقيبة.",
    ),
    (
        r"timeout|timed out",
        "انتهت مهلة الاتصال بالمزوّد. أعد المحاولة.",
    ),
]


def explain(error: BaseException | str | None) -> str:
    """A sentence naming the cause, for a person who did not write this code.

    Returns "" when there is nothing to explain, so a caller can fall back to
    its own wording.
    """
    if error is None:
        return ""
    text = error if isinstance(error, str) else f"{type(error).__name__}: {error}"
    if not text.strip():
        return ""

    lowered = text.lower()
    for pattern, message in _PATTERNS:
        if re.search(pattern, lowered):
            return message

    # Unrecognised: the raw text beats a confident guess about the wrong thing.
    return f"فشل الاتصال بالموديل: {text[:300]}"


#: The three status codes are bounded so each matches a code and not any
#: number that contains one. They were written `401`, and the escape did
#: not survive whatever wrote the line: the pattern carried three literal
#: backspace characters instead, so «401 Unauthorized» was retried four times
#: with fifteen-second sleeps - the exact waste the note below describes -
#: while the word forms beside it kept working and hid the hole.
#:
#: Refusals that will refuse the next call too. A spent key does not recover
#: between one subsection and the next, so retrying is time spent waiting for
#: the same answer - a thirty-subsection book grinds through four attempts and
#: fifteen-second sleeps each, half an hour of it, and delivers empty prose.
_TERMINAL = (
    r"more credits|insufficient credits|can only afford|key limit exceeded"
    r"|invalid api key|no auth credentials|user not found"
    r"|(?<!\d)401(?!\d)|(?<!\d)402(?!\d)|(?<!\d)403(?!\d)"
)


class ProviderExhausted(RuntimeError):
    """A refusal that will refuse every further call in this run.

    Raised by a stage the moment it sees one, so the run stops with the cause
    in its message instead of grinding through every remaining item: a bag
    written after its key ran dry made 230 refused calls in a row, shipped
    eighteen empty محاور out of twenty, and was recorded as a success.
    """


def is_terminal(error: BaseException | str | None) -> bool:
    """Whether retrying this refusal can possibly help.

    A rate limit can clear in seconds and a timeout is worth another try. An
    exhausted key, a spent balance and a rejected credential cannot change
    while the run is in flight, and treating them as transient is how a book
    finished with thirty empty subsections and no error anywhere.
    """
    if error is None:
        return False
    text = error if isinstance(error, str) else f"{type(error).__name__}: {error}"
    return bool(re.search(_TERMINAL, text.lower()))


class ProviderRefused(RuntimeError):
    """A refusal there is no point retrying. Carries the explained cause."""


def with_cause(fallback: str, error: BaseException | str | None) -> str:
    """``fallback``, followed by the real cause when one is known."""
    explained = explain(error)
    return f"{fallback} — {explained}" if explained else fallback