math-scout 0.2.0a2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of math-scout might be problematic. Click here for more details.

@@ -0,0 +1,152 @@
1
+ This block is identical for every reviewer in the pipeline. It describes what you are
2
+ given, how to grade what you find, and what each output field must contain. Your own
3
+ lane — what you are responsible for finding, and what you must leave alone — is in the
4
+ `# REVIEWER PROMPT` block that follows.
5
+
6
+ ## What you are given
7
+
8
+ Four blocks, in this order:
9
+
10
+ 1. `# GLOBAL CONTEXT` — the paper's title, abstract, preamble, and the bodies of up to
11
+ fifteen `theorem` and `definition` environments, extracted mechanically from the
12
+ source. It is shared by every reviewer and is background only.
13
+ 2. `# REVIEW PROTOCOL` — this block.
14
+ 3. `# REVIEWER PROMPT` — your lane.
15
+ 4. `# DETECTED ISSUES` — one line per finding already filed by an earlier pass in this
16
+ run, as `[Reviewer - SEVERITY] location: title`. It is truncated to the fifteen
17
+ highest-severity entries, so it is a sample of what is already known, not a complete
18
+ record. Early in a run it will say "No previously detected issues"; that is normal and
19
+ says nothing about the paper.
20
+
21
+ Then the text you are to review, headed either `# SECTION UNDER REVIEW` (one `\section`
22
+ of the paper, with its title) or `# FULL PAPER UNDER REVIEW` (the entire source). Your
23
+ `# REVIEWER PROMPT` block tells you which one you get.
24
+
25
+ ## What you can and cannot see
26
+
27
+ **The `## Theorem N` and `## Definition N` headings in `GLOBAL CONTEXT` are extraction
28
+ indices, not the paper's numbering.** `## Theorem 3` is the third environment the
29
+ extractor happened to reach; the paper may call it Proposition 1.4. Never cite one of
30
+ these numbers. When you need to point at a result from the global context, quote enough
31
+ of its statement to identify it, or use the label the paper itself gives it in the text
32
+ you are reviewing.
33
+
34
+ `GLOBAL CONTEXT` is also incomplete by construction: it stops at fifteen environments,
35
+ and it captures only `theorem` and `definition` environments, so lemmas, propositions,
36
+ corollaries and remarks are absent from it entirely. Their absence is not evidence that
37
+ the paper lacks them.
38
+
39
+ **If you are reviewing a single section:** you are seeing a slice of a longer document.
40
+ Everything defined in earlier sections, and everything proved in later ones, is invisible
41
+ to you. Therefore:
42
+
43
+ - An object, symbol, constant or convention that is used without definition here is
44
+ presumed to have been defined elsewhere. Do not flag it as undefined. Flag it only if
45
+ *this* section is where it should have been introduced — because this section
46
+ announces the definition, or because the surrounding text implies it was just given.
47
+ - A `\ref`, `\cite`, `\eqref` or a cross-reference by name that points outside this
48
+ section is presumed to resolve. You cannot see the target, so you cannot report it
49
+ broken.
50
+ - A "forward reference to a result that does not exist" is not something you are in a
51
+ position to observe. Do not report one.
52
+
53
+ All of the above is covered by a reviewer that reads the whole document, and that pass
54
+ runs after every section has been read — so it is not your job, and it will not yet
55
+ appear in `DETECTED ISSUES`. Filing a guess at one of these from inside a single section
56
+ adds a false positive that a later pass has to pay to remove.
57
+
58
+ ## Severity
59
+
60
+ One scale, shared by every reviewer, on a single axis: **what does this finding do to the
61
+ paper's claims?** Not how much work the fix is, and not how annoyed the reader will be.
62
+
63
+ - `critical` — as written, a main theorem, or a result a main theorem depends on, is not
64
+ established. The paper's headline claim does not currently stand.
65
+ - `major` — a real defect that needs new argument, an added hypothesis, or a restated
66
+ result. The claim may well survive, but the paper as written does not support it.
67
+ - `moderate` — a localized defect with a clear local fix that leaves every claim intact.
68
+ - `minor` — a small slip, easily patched, with no bearing on any claim.
69
+
70
+ `critical` is for findings that bear on whether the mathematics holds. A finding about how
71
+ the paper reads, or about how its symbols are spelled, is at most `major` however severe it
72
+ is in its own terms. The one exception is a *statement* — a theorem, definition, or
73
+ hypothesis — that is itself ambiguous or self-contradictory, so that there is no single
74
+ claim to evaluate: that may be `critical`, because nothing can be verified until it is
75
+ resolved. A passage being hard to read is never that.
76
+
77
+ **Findings that are not about correctness** — exposition, notation, presentation — cannot
78
+ be graded on the claims, because by construction they leave the claims alone. Grade them
79
+ instead on how much of the paper a reader cannot use as written:
80
+
81
+ - `major` — an expert cannot follow, or cannot unambiguously interpret, a main result or
82
+ its proof without doing work the paper should have done.
83
+ - `moderate` — one passage costs a re-read or a guess that a sentence would have saved.
84
+ - `minor` — noticeable, easily fixed, and it costs the reader nothing real.
85
+
86
+ Grade each finding on its own. Do not inflate a finding because it is the only one you
87
+ have, and do not deflate one because you have already filed something worse.
88
+
89
+ ## Confidence
90
+
91
+ A number in `[0, 1]` that a later pass acts on, so it must mean something. It is
92
+ calibrated on evidence, not on how important the issue would be if true.
93
+
94
+ - `0.9`–`1.0` — the quoted text alone demonstrates it. Someone reading only your `quote`
95
+ and `analysis` would agree.
96
+ - `0.7`–`0.9` — strong evidence; the residual doubt is about a convention, or about text
97
+ you cannot see.
98
+ - `0.5`–`0.7` — a plausible concern the authors should be asked to address. You are not
99
+ asserting the defect, you are asserting that it has not been ruled out.
100
+ - below `0.5` — a lead, not a claim. The final referee will check it against the full
101
+ paper. File one only if a positive answer would matter; say in `analysis` exactly what
102
+ would settle it.
103
+
104
+ Do not report a suspicion at high confidence because the consequence would be serious.
105
+ Severity carries that; confidence does not.
106
+
107
+ ## Output fields
108
+
109
+ Populate the structured output schema. Every field is required and every field is read.
110
+
111
+ - `title` — one line, specific enough to be recognised in a list. "Lemma 3.2 applied
112
+ without checking properness", not "Issue with Lemma 3.2".
113
+ - `severity` — from the scale above.
114
+ - `type` — a kebab-case slug from the taxonomy in your `# REVIEWER PROMPT` block, so that
115
+ related findings can be grouped. Use `other` if nothing fits; do not invent new slugs.
116
+ - `location` — where the author should look, in the paper's own terms: `Theorem 3.2`,
117
+ `Proof of Lemma 4.2, third paragraph`, `eq. (4.7)`, `Section 5, first display`. Never a
118
+ `GLOBAL CONTEXT` index, never a character offset.
119
+ - `quote` — verbatim LaTeX copied character for character out of the text under review,
120
+ one to three lines, enough that a search for it finds the spot. Do not paraphrase,
121
+ normalise whitespace, or reconstruct it from memory. **If you cannot quote the text the
122
+ finding is about, the finding is not concrete enough to file — drop it.**
123
+ - `analysis` — what is wrong and why it matters, in a few sentences. Address the author.
124
+ Name the step that fails, not the general area. If your objection depends on an
125
+ assumption about something you cannot see, say so here.
126
+ - `suggested_fix` — what would resolve it: the hypothesis to add, the case to treat, the
127
+ sentence to insert, the verification to supply. "Clarify this" is not a fix. If you do
128
+ not know the fix, say what the authors must establish instead.
129
+ - `confidence` — from the scale above.
130
+
131
+ ## Discipline
132
+
133
+ - **An empty `issues` array is a correct and common answer.** You are not being measured
134
+ on volume, and a run that reports nothing on a sound section is working as intended.
135
+ Padding a report with weak findings makes the real ones harder to see and is the single
136
+ most damaging thing you can do here.
137
+ - Prefer few well-evidenced findings to many thin ones. Two solid findings beat eight
138
+ hedged ones.
139
+ - Do not invent counterexamples. If you suspect one exists, describe the candidate,
140
+ say it is a candidate, and set confidence accordingly.
141
+ - Do not paraphrase the paper into a weaker claim and then object to the paraphrase.
142
+ - **Stay in your lane.** Every other kind of defect belongs to another reviewer in this
143
+ pipeline, and filing it here produces a duplicate rather than coverage. Cross into
144
+ another lane only when a defect there is inseparable from one in yours, and say so.
145
+ - Do not re-file a concern already in `DETECTED ISSUES`. But if you find the *same*
146
+ defect recurring in new text, one short finding naming it as a pattern and pointing at
147
+ the new occurrence is worth more than silence — a systematic problem reads differently
148
+ from a one-off.
149
+ - You have no access to the literature and no way to check a citation's contents. Never
150
+ assert that a result is already known, and never name a paper, author or year that does
151
+ not appear in the source in front of you. Doubts of that kind are questions for the
152
+ authors, phrased as questions.
@@ -0,0 +1,61 @@
1
+ """Native LLM provider adapters."""
2
+
3
+ from .anthropic import AnthropicProvider
4
+ from .base import (
5
+ EFFORT_LEVELS,
6
+ FATAL_PROVIDER_ERRORS,
7
+ TRANSIENT_PROVIDER_ERRORS,
8
+ ConfigurationError,
9
+ GenerationRequest,
10
+ GenerationResult,
11
+ GenerationUsage,
12
+ ModelRef,
13
+ Pricing,
14
+ PromptBlock,
15
+ Provider,
16
+ ProviderAuthenticationError,
17
+ ProviderConnectionError,
18
+ ProviderEmptyOutputError,
19
+ ProviderError,
20
+ ProviderModelError,
21
+ ProviderPermissionError,
22
+ ProviderRateLimitError,
23
+ ProviderRefusalError,
24
+ ProviderRequestError,
25
+ ProviderServerError,
26
+ ProviderTimeoutError,
27
+ next_lower_effort,
28
+ )
29
+ from .openai import OpenAIProvider
30
+ from .registry import PROVIDER_TYPES, ProviderRegistry, provider_type
31
+
32
+ __all__ = [
33
+ "EFFORT_LEVELS",
34
+ "FATAL_PROVIDER_ERRORS",
35
+ "PROVIDER_TYPES",
36
+ "TRANSIENT_PROVIDER_ERRORS",
37
+ "AnthropicProvider",
38
+ "ConfigurationError",
39
+ "GenerationRequest",
40
+ "GenerationResult",
41
+ "GenerationUsage",
42
+ "ModelRef",
43
+ "OpenAIProvider",
44
+ "Pricing",
45
+ "PromptBlock",
46
+ "Provider",
47
+ "ProviderAuthenticationError",
48
+ "ProviderConnectionError",
49
+ "ProviderEmptyOutputError",
50
+ "ProviderError",
51
+ "ProviderModelError",
52
+ "ProviderPermissionError",
53
+ "ProviderRateLimitError",
54
+ "ProviderRefusalError",
55
+ "ProviderRegistry",
56
+ "ProviderRequestError",
57
+ "ProviderServerError",
58
+ "ProviderTimeoutError",
59
+ "next_lower_effort",
60
+ "provider_type",
61
+ ]
@@ -0,0 +1,233 @@
1
+ """Native Anthropic Messages API adapter."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from typing import Any
7
+
8
+ import anthropic
9
+
10
+ from .base import (
11
+ EFFORT_LEVELS,
12
+ ConfigurationError,
13
+ GenerationRequest,
14
+ GenerationResult,
15
+ GenerationUsage,
16
+ Pricing,
17
+ Provider,
18
+ ProviderAuthenticationError,
19
+ ProviderConnectionError,
20
+ ProviderEmptyOutputError,
21
+ ProviderError,
22
+ ProviderModelError,
23
+ ProviderPermissionError,
24
+ ProviderRateLimitError,
25
+ ProviderRefusalError,
26
+ ProviderRequestError,
27
+ ProviderServerError,
28
+ ProviderTimeoutError,
29
+ )
30
+
31
+ _ALL_EFFORTS = frozenset(EFFORT_LEVELS)
32
+
33
+
34
+ class AnthropicProvider(Provider):
35
+ name = "anthropic"
36
+ display_name = "Anthropic"
37
+ credentials_help = (
38
+ "No usable Anthropic credentials. Either export ANTHROPIC_API_KEY, or sign in "
39
+ "with `ant auth login` and the SDK will pick up the stored profile."
40
+ )
41
+ models_url = "https://platform.claude.com/docs/en/about-claude/models/overview"
42
+
43
+ # efforts, highest effort accepted with thinking explicitly disabled, max output
44
+ _CAPABILITIES: dict[str, tuple[frozenset[str], str | None, int]] = {
45
+ "claude-opus-5": (_ALL_EFFORTS, "high", 128_000),
46
+ "claude-opus-4-8": (_ALL_EFFORTS, None, 64_000),
47
+ "claude-opus-4-7": (_ALL_EFFORTS, None, 64_000),
48
+ "claude-opus-4-6": (_ALL_EFFORTS - {"xhigh"}, None, 64_000),
49
+ "claude-sonnet-5": (_ALL_EFFORTS, None, 128_000),
50
+ "claude-sonnet-4-6": (_ALL_EFFORTS - {"xhigh"}, None, 64_000),
51
+ "claude-haiku-4-5": (frozenset(), None, 64_000),
52
+ }
53
+
54
+ _PRICING = {
55
+ "claude-opus-5": Pricing(input=5.0, output=25.0, cache_read=0.5),
56
+ "claude-opus-4-8": Pricing(input=5.0, output=25.0, cache_read=0.5),
57
+ "claude-opus-4-7": Pricing(input=5.0, output=25.0, cache_read=0.5),
58
+ "claude-opus-4-6": Pricing(input=5.0, output=25.0, cache_read=0.5),
59
+ "claude-sonnet-5": Pricing(input=3.0, output=15.0, cache_read=0.3),
60
+ "claude-sonnet-4-6": Pricing(input=3.0, output=15.0, cache_read=0.3),
61
+ }
62
+
63
+ def __init__(self, client: anthropic.Anthropic | None = None):
64
+ self._client_instance: anthropic.Anthropic | None = client
65
+
66
+ @property
67
+ def client(self) -> anthropic.Anthropic:
68
+ if self._client_instance is None:
69
+ try:
70
+ self._client_instance = anthropic.Anthropic()
71
+ except TypeError as exc:
72
+ # The Anthropic SDK uses a bare TypeError when neither an environment
73
+ # key nor an `ant auth login` profile can be resolved.
74
+ raise ProviderAuthenticationError(str(exc)) from exc
75
+ except Exception as exc: # credential resolution can fail during construction
76
+ raise self._normalize(exc) from exc
77
+ return self._client_instance
78
+
79
+ @classmethod
80
+ def validate_request(
81
+ cls, model: str, *, reasoning: bool, effort: str, output_limit: int
82
+ ) -> None:
83
+ support = cls._CAPABILITIES.get(model)
84
+ if support is None:
85
+ return
86
+ efforts, disabled_max, max_output = support
87
+ if not efforts:
88
+ raise ConfigurationError(
89
+ f"{model} cannot be used here: it rejects the effort and thinking "
90
+ "settings this pipeline sends on every call. Choose another model for it."
91
+ )
92
+ if effort not in efforts:
93
+ allowed = ", ".join(level for level in EFFORT_LEVELS if level in efforts)
94
+ raise ConfigurationError(
95
+ f"{model} does not support --effort {effort}. It accepts: {allowed}."
96
+ )
97
+ if (
98
+ not reasoning
99
+ and disabled_max is not None
100
+ and EFFORT_LEVELS.index(effort) > EFFORT_LEVELS.index(disabled_max)
101
+ ):
102
+ raise ConfigurationError(
103
+ f"A reviewer runs without thinking on {model}, which rejects "
104
+ f"--effort above {disabled_max}. Use --effort {disabled_max} or lower, "
105
+ "or give it a different model."
106
+ )
107
+ if output_limit > max_output:
108
+ raise ConfigurationError(
109
+ f"{model} accepts at most {max_output:,} output tokens; got {output_limit:,}."
110
+ )
111
+
112
+ def _normalize(self, exc: Exception) -> Exception:
113
+ if isinstance(exc, ProviderError):
114
+ return exc
115
+ if isinstance(exc, anthropic.AuthenticationError):
116
+ return ProviderAuthenticationError(str(exc))
117
+ if isinstance(exc, anthropic.PermissionDeniedError):
118
+ return ProviderPermissionError(str(exc))
119
+ if isinstance(exc, anthropic.NotFoundError):
120
+ return ProviderModelError(str(exc))
121
+ if isinstance(exc, anthropic.RateLimitError):
122
+ return ProviderRateLimitError(str(exc))
123
+ if isinstance(exc, anthropic.APITimeoutError):
124
+ return ProviderTimeoutError(str(exc))
125
+ if isinstance(exc, anthropic.APIConnectionError):
126
+ return ProviderConnectionError(str(exc))
127
+ if isinstance(exc, anthropic.APIStatusError):
128
+ if exc.status_code >= 500:
129
+ return ProviderServerError(str(exc), status_code=exc.status_code)
130
+ return ProviderRequestError(str(exc))
131
+ return exc
132
+
133
+ def _invoke(self, fn: Callable[[], Any]) -> Any:
134
+ try:
135
+ return fn()
136
+ except Exception as exc:
137
+ normalized = self._normalize(exc)
138
+ if normalized is exc:
139
+ raise
140
+ raise normalized from exc
141
+
142
+ @staticmethod
143
+ def _system(request: GenerationRequest) -> list[dict[str, Any]]:
144
+ return [
145
+ {
146
+ "type": "text",
147
+ "text": block.text,
148
+ **({"cache_control": {"type": "ephemeral"}} if block.cacheable else {}),
149
+ }
150
+ for block in request.blocks
151
+ if block.role == "system"
152
+ ]
153
+
154
+ @staticmethod
155
+ def _messages(request: GenerationRequest) -> list[dict[str, Any]]:
156
+ content = [
157
+ {"type": "text", "text": block.text} for block in request.blocks if block.role == "user"
158
+ ]
159
+ return [{"role": "user", "content": content}]
160
+
161
+ def _generation_kwargs(self, request: GenerationRequest) -> dict[str, Any]:
162
+ kwargs: dict[str, Any] = {
163
+ "model": request.model.model,
164
+ "max_tokens": request.output_limit,
165
+ "system": self._system(request),
166
+ "messages": self._messages(request),
167
+ "thinking": {"type": "adaptive" if request.reasoning else "disabled"},
168
+ "output_config": {"effort": request.effort},
169
+ }
170
+ if request.output_schema is not None:
171
+ kwargs["output_format"] = request.output_schema
172
+ return kwargs
173
+
174
+ def preflight(self, model: str) -> None:
175
+ self._invoke(
176
+ lambda: self.client.messages.count_tokens(
177
+ model=model,
178
+ messages=[{"role": "user", "content": "ping"}],
179
+ )
180
+ )
181
+
182
+ def generate(self, request: GenerationRequest) -> GenerationResult:
183
+ def call():
184
+ with self.client.messages.stream(**self._generation_kwargs(request)) as stream:
185
+ return stream.get_final_message()
186
+
187
+ response = self._invoke(call)
188
+ stop_reason = getattr(response, "stop_reason", None)
189
+ if stop_reason == "refusal":
190
+ raise ProviderRefusalError("Anthropic refused the request.")
191
+ truncated = stop_reason == "max_tokens"
192
+ parsed = getattr(response, "parsed_output", None)
193
+ texts = [
194
+ block.text
195
+ for block in getattr(response, "content", [])
196
+ if getattr(block, "type", None) == "text"
197
+ ]
198
+ text = "".join(texts) or None
199
+ if not truncated and request.output_schema is not None and parsed is None:
200
+ raise ProviderEmptyOutputError("Anthropic returned no parsed structured output.")
201
+ if not truncated and request.output_schema is None and text is None:
202
+ raise ProviderEmptyOutputError("Anthropic returned no text output.")
203
+ usage = getattr(response, "usage", None)
204
+ normalized_usage = None
205
+ if usage is not None:
206
+ normalized_usage = GenerationUsage(
207
+ input_tokens=getattr(usage, "input_tokens", None),
208
+ output_tokens=getattr(usage, "output_tokens", None),
209
+ cached_input_tokens=getattr(usage, "cache_read_input_tokens", None),
210
+ cache_write_input_tokens=getattr(usage, "cache_creation_input_tokens", None),
211
+ )
212
+ return GenerationResult(
213
+ parsed=parsed,
214
+ text=text,
215
+ completed=not truncated,
216
+ truncated=truncated,
217
+ usage=normalized_usage,
218
+ )
219
+
220
+ def count_tokens(self, request: GenerationRequest) -> int:
221
+ kwargs: dict[str, Any] = {
222
+ "model": request.model.model,
223
+ "system": self._system(request),
224
+ "messages": self._messages(request),
225
+ }
226
+ if request.output_schema is not None:
227
+ kwargs["output_format"] = request.output_schema
228
+ response = self._invoke(lambda: self.client.messages.count_tokens(**kwargs))
229
+ return response.input_tokens
230
+
231
+ @classmethod
232
+ def pricing(cls, model: str) -> Pricing | None:
233
+ return cls._PRICING.get(model)
@@ -0,0 +1,200 @@
1
+ """Provider-neutral request, result, capability, and error contracts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC, abstractmethod
6
+ from dataclasses import dataclass
7
+ from typing import Literal
8
+
9
+ from pydantic import BaseModel
10
+
11
+ EFFORT_LEVELS = ("low", "medium", "high", "xhigh", "max")
12
+
13
+
14
+ class ConfigurationError(Exception):
15
+ """A problem with the input, environment, or invocation."""
16
+
17
+
18
+ @dataclass(frozen=True, order=True)
19
+ class ModelRef:
20
+ """A model identifier together with the native API provider that serves it."""
21
+
22
+ provider: str
23
+ model: str
24
+
25
+ @classmethod
26
+ def parse(cls, value: str | ModelRef) -> ModelRef:
27
+ if isinstance(value, cls):
28
+ return value
29
+ provider, separator, model = value.partition(":")
30
+ if not separator:
31
+ raise ConfigurationError(
32
+ f"Invalid model {value!r}; expected PROVIDER:MODEL. "
33
+ "Use --preset opus-sonnet or --preset sol-luna for a common model pair."
34
+ )
35
+ provider = provider.strip().lower()
36
+ model = model.strip()
37
+ if not provider or not model:
38
+ raise ConfigurationError(f"Invalid model {value!r}; expected PROVIDER:MODEL.")
39
+ return cls(provider=provider, model=model)
40
+
41
+ @property
42
+ def qualified(self) -> str:
43
+ return f"{self.provider}:{self.model}"
44
+
45
+ def __str__(self) -> str:
46
+ return self.qualified
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class PromptBlock:
51
+ """One ordered text block in a generation request."""
52
+
53
+ role: Literal["system", "user"]
54
+ text: str
55
+ cacheable: bool = False
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class GenerationRequest:
60
+ """Everything a provider needs to perform one text generation."""
61
+
62
+ model: ModelRef
63
+ blocks: tuple[PromptBlock, ...]
64
+ reasoning: bool
65
+ effort: str
66
+ output_limit: int
67
+ output_schema: type[BaseModel] | None = None
68
+ prompt_cache_key: str | None = None
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class GenerationUsage:
73
+ input_tokens: int | None = None
74
+ output_tokens: int | None = None
75
+ cached_input_tokens: int | None = None
76
+ cache_write_input_tokens: int | None = None
77
+
78
+
79
+ @dataclass(frozen=True)
80
+ class GenerationResult:
81
+ """A normalized completed or truncated provider response."""
82
+
83
+ parsed: BaseModel | None = None
84
+ text: str | None = None
85
+ completed: bool = True
86
+ truncated: bool = False
87
+ usage: GenerationUsage | None = None
88
+
89
+
90
+ @dataclass(frozen=True)
91
+ class Pricing:
92
+ """USD per million tokens. Missing metadata never prevents a request."""
93
+
94
+ input: float
95
+ output: float
96
+ cache_read: float | None = None
97
+ cache_write: float | None = None
98
+
99
+
100
+ class ProviderError(Exception):
101
+ """Base class for errors normalized across native provider SDKs."""
102
+
103
+
104
+ class ProviderAuthenticationError(ProviderError):
105
+ pass
106
+
107
+
108
+ class ProviderPermissionError(ProviderError):
109
+ pass
110
+
111
+
112
+ class ProviderModelError(ProviderError):
113
+ pass
114
+
115
+
116
+ class ProviderRateLimitError(ProviderError):
117
+ pass
118
+
119
+
120
+ class ProviderConnectionError(ProviderError):
121
+ pass
122
+
123
+
124
+ class ProviderTimeoutError(ProviderError):
125
+ pass
126
+
127
+
128
+ class ProviderRefusalError(ProviderError):
129
+ pass
130
+
131
+
132
+ class ProviderServerError(ProviderError):
133
+ def __init__(self, message: str, status_code: int | None = None):
134
+ super().__init__(message)
135
+ self.status_code = status_code
136
+
137
+
138
+ class ProviderRequestError(ProviderError):
139
+ pass
140
+
141
+
142
+ class ProviderEmptyOutputError(ProviderError):
143
+ pass
144
+
145
+
146
+ FATAL_PROVIDER_ERRORS = (
147
+ ProviderAuthenticationError,
148
+ ProviderPermissionError,
149
+ ProviderModelError,
150
+ )
151
+
152
+ TRANSIENT_PROVIDER_ERRORS = (
153
+ ProviderRateLimitError,
154
+ ProviderConnectionError,
155
+ ProviderTimeoutError,
156
+ ProviderServerError,
157
+ )
158
+
159
+
160
+ def next_lower_effort(effort: str) -> str | None:
161
+ """Return the next application effort level down, if there is one."""
162
+ index = EFFORT_LEVELS.index(effort)
163
+ return EFFORT_LEVELS[index - 1] if index > 0 else None
164
+
165
+
166
+ class Provider(ABC):
167
+ """Native-provider adapter used by the provider-neutral orchestration."""
168
+
169
+ name: str
170
+ display_name: str
171
+ credentials_help: str
172
+ models_url: str
173
+
174
+ @classmethod
175
+ @abstractmethod
176
+ def validate_request(
177
+ cls, model: str, *, reasoning: bool, effort: str, output_limit: int
178
+ ) -> None:
179
+ """Reject a known-incompatible request before any paid generation."""
180
+
181
+ @abstractmethod
182
+ def preflight(self, model: str) -> None:
183
+ """Verify credentials and model access without generating output."""
184
+
185
+ @abstractmethod
186
+ def generate(self, request: GenerationRequest) -> GenerationResult:
187
+ """Stream one structured or text response and return its final result."""
188
+
189
+ @abstractmethod
190
+ def count_tokens(self, request: GenerationRequest) -> int:
191
+ """Return the provider's exact input-token count for *request*."""
192
+
193
+ def retry_effort(self, request: GenerationRequest) -> str | None:
194
+ """Map a truncation retry to a genuinely different provider request."""
195
+ return next_lower_effort(request.effort)
196
+
197
+ @classmethod
198
+ @abstractmethod
199
+ def pricing(cls, model: str) -> Pricing | None:
200
+ """Return trustworthy current pricing metadata when it is known."""