codeveto 0.1.0__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.
- codeveto/__init__.py +3 -0
- codeveto/__main__.py +8 -0
- codeveto/ai/__init__.py +19 -0
- codeveto/ai/harness.py +303 -0
- codeveto/ai/packets.py +855 -0
- codeveto/ai/policy.py +222 -0
- codeveto/ai/prompt.py +101 -0
- codeveto/ai/providers/__init__.py +178 -0
- codeveto/ai/providers/claude.py +247 -0
- codeveto/ai/providers/openai_compat.py +246 -0
- codeveto/ai/runner.py +293 -0
- codeveto/ai/verify.py +324 -0
- codeveto/anchor.py +211 -0
- codeveto/cli.py +247 -0
- codeveto/cli_explain.py +49 -0
- codeveto/cli_hook.py +31 -0
- codeveto/cli_init.py +254 -0
- codeveto/cli_mcp.py +29 -0
- codeveto/cli_packets.py +35 -0
- codeveto/cli_publish.py +29 -0
- codeveto/cli_review.py +362 -0
- codeveto/cli_rules.py +78 -0
- codeveto/cli_verify.py +47 -0
- codeveto/config.py +1229 -0
- codeveto/data/README.md +16 -0
- codeveto/data/ai-wire.schema.json +53 -0
- codeveto/data/prompts/system.md +57 -0
- codeveto/data/report-v1.schema.json +268 -0
- codeveto/data/templates/forgejo-codeveto.yml +104 -0
- codeveto/data/templates/github-codeveto.yml +18 -0
- codeveto/embedded.py +311 -0
- codeveto/engine.py +1570 -0
- codeveto/git.py +1549 -0
- codeveto/globs.py +348 -0
- codeveto/integrations/__init__.py +1 -0
- codeveto/integrations/hooks.py +327 -0
- codeveto/integrations/mcp.py +770 -0
- codeveto/integrations/mcp_ai.py +77 -0
- codeveto/integrations/prepush.py +222 -0
- codeveto/jsonsafe.py +60 -0
- codeveto/languages.py +539 -0
- codeveto/lexers.py +2560 -0
- codeveto/model.py +372 -0
- codeveto/publish/__init__.py +28 -0
- codeveto/publish/action.py +330 -0
- codeveto/publish/common.py +84 -0
- codeveto/publish/diff.py +208 -0
- codeveto/publish/event.py +241 -0
- codeveto/publish/forgejo.py +184 -0
- codeveto/publish/github.py +380 -0
- codeveto/publish/http.py +263 -0
- codeveto/publish/pull.py +218 -0
- codeveto/publish/untrusted.py +110 -0
- codeveto/py.typed +0 -0
- codeveto/redact.py +113 -0
- codeveto/render/__init__.py +64 -0
- codeveto/render/agent.py +43 -0
- codeveto/render/github.py +101 -0
- codeveto/render/json.py +23 -0
- codeveto/render/markdown.py +208 -0
- codeveto/render/safe.py +249 -0
- codeveto/render/sarif.py +217 -0
- codeveto/render/text.py +210 -0
- codeveto/report.py +252 -0
- codeveto/rules/__init__.py +84 -0
- codeveto/rules/agent.py +2972 -0
- codeveto/rules/base.py +1026 -0
- codeveto/rules/ci.py +1708 -0
- codeveto/rules/config.py +493 -0
- codeveto/rules/deps.py +1693 -0
- codeveto/rules/docker.py +479 -0
- codeveto/rules/examples/__init__.py +148 -0
- codeveto/rules/examples/agent.py +839 -0
- codeveto/rules/examples/ci.py +1046 -0
- codeveto/rules/examples/config.py +191 -0
- codeveto/rules/examples/deps.py +369 -0
- codeveto/rules/examples/docker.py +157 -0
- codeveto/rules/examples/go.py +241 -0
- codeveto/rules/examples/hygiene.py +466 -0
- codeveto/rules/examples/js.py +462 -0
- codeveto/rules/examples/python.py +595 -0
- codeveto/rules/examples/rust.py +268 -0
- codeveto/rules/examples/secrets.py +561 -0
- codeveto/rules/examples/security.py +608 -0
- codeveto/rules/examples/shell.py +174 -0
- codeveto/rules/examples/sql.py +194 -0
- codeveto/rules/examples/tests.py +497 -0
- codeveto/rules/go.py +328 -0
- codeveto/rules/hygiene.py +1094 -0
- codeveto/rules/js.py +768 -0
- codeveto/rules/python.py +1642 -0
- codeveto/rules/rust.py +209 -0
- codeveto/rules/secrets.py +1335 -0
- codeveto/rules/security.py +3680 -0
- codeveto/rules/shell.py +867 -0
- codeveto/rules/sql.py +629 -0
- codeveto/rules/tests.py +1404 -0
- codeveto/schema.py +384 -0
- codeveto/statements.py +607 -0
- codeveto/worktree.py +1176 -0
- codeveto/yamlish.py +1179 -0
- codeveto-0.1.0.dist-info/METADATA +253 -0
- codeveto-0.1.0.dist-info/RECORD +106 -0
- codeveto-0.1.0.dist-info/WHEEL +4 -0
- codeveto-0.1.0.dist-info/entry_points.txt +2 -0
- codeveto-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""The ``claude`` provider: the Anthropic Python SDK (``codeveto[claude]``, SPEC 9.4).
|
|
2
|
+
|
|
3
|
+
The base URL is ``[ai] base_url`` / ``--ai-base-url``, else
|
|
4
|
+
``ANTHROPIC_BASE_URL``, else ``https://api.anthropic.com``, checked like the
|
|
5
|
+
OpenAI-compatible one (https, or http only for ``localhost`` and literal
|
|
6
|
+
loopback IPs; no user info) and passed to the client explicitly;
|
|
7
|
+
``ai.endpoint`` records its host, port and path. Calls follow the SDK's
|
|
8
|
+
documented surface:
|
|
9
|
+
|
|
10
|
+
- capability step: ``client.beta.models.retrieve(model,
|
|
11
|
+
betas=["server-side-fallback-2026-07-01"])``. ``capabilities.structured_outputs``
|
|
12
|
+
must be supported (else the pass fails up front); ``effort`` is sent only
|
|
13
|
+
when the model supports that level; ``fallbacks`` only when the model lists
|
|
14
|
+
``allowed_fallback_models`` (the beta header makes the API publish them).
|
|
15
|
+
- each packet: ``client.with_options(timeout=T, max_retries=2).beta.messages.stream(
|
|
16
|
+
model=..., max_tokens=N, system=[{"type": "text", "text": SYSTEM,
|
|
17
|
+
"cache_control": {"type": "ephemeral"}}], messages=[{"role": "user",
|
|
18
|
+
"content": PACKET}], output_config={"effort": E, "format": {"type":
|
|
19
|
+
"json_schema", "schema": WIRE}}, betas=["server-side-fallback-2026-07-01"],
|
|
20
|
+
fallbacks="default")`` and ``stream.get_final_message()``. ``T`` is 180 s
|
|
21
|
+
or the time left before the pass deadline, whichever is less. No
|
|
22
|
+
``thinking`` and no sampling parameters are sent.
|
|
23
|
+
|
|
24
|
+
Only ``stop_reason == "end_turn"`` is accepted; ``max_tokens`` is
|
|
25
|
+
``truncated``, ``refusal`` is ``refused`` (with ``stop_details.category``),
|
|
26
|
+
anything else ``unexpected_stop``. JSON is read from ``text`` blocks only, and
|
|
27
|
+
only those after the last ``fallback`` block (a streamed answer keeps the
|
|
28
|
+
declined model's partial text before the switch). Authentication, permission,
|
|
29
|
+
not-found, bad-request and billing errors abort the pass; rate limits, other
|
|
30
|
+
HTTP errors, connection errors and timeouts fail the packet after the SDK's
|
|
31
|
+
retries. ``served_model`` is the response's ``model`` (the fallback model when
|
|
32
|
+
one answered).
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
from __future__ import annotations
|
|
36
|
+
|
|
37
|
+
import os
|
|
38
|
+
import re
|
|
39
|
+
from collections.abc import Mapping
|
|
40
|
+
from types import ModuleType
|
|
41
|
+
from typing import Any
|
|
42
|
+
|
|
43
|
+
from codeveto.ai import prompt
|
|
44
|
+
from codeveto.ai.providers import (
|
|
45
|
+
Outcome,
|
|
46
|
+
ProviderUnavailable,
|
|
47
|
+
Request,
|
|
48
|
+
check_base_url,
|
|
49
|
+
usage_of,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
__all__ = [
|
|
53
|
+
"DEFAULT_BASE_URL",
|
|
54
|
+
"DEFAULT_MODEL",
|
|
55
|
+
"FALLBACK_BETA",
|
|
56
|
+
"MAX_RETRIES",
|
|
57
|
+
"REQUEST_TIMEOUT_S",
|
|
58
|
+
"ClaudeProvider",
|
|
59
|
+
]
|
|
60
|
+
|
|
61
|
+
DEFAULT_MODEL = "claude-opus-5-5"
|
|
62
|
+
DEFAULT_BASE_URL = "https://api.anthropic.com"
|
|
63
|
+
FALLBACK_BETA = "server-side-fallback-2026-07-01"
|
|
64
|
+
REQUEST_TIMEOUT_S = 180.0
|
|
65
|
+
MAX_RETRIES = 2
|
|
66
|
+
INSTALL_HINT = "install codeveto[claude]"
|
|
67
|
+
_TOKEN = re.compile(r"[a-z][a-z0-9_]{0,40}")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _import_sdk() -> ModuleType:
|
|
71
|
+
try:
|
|
72
|
+
import anthropic # optional extra, imported only when used
|
|
73
|
+
except ImportError:
|
|
74
|
+
raise ProviderUnavailable(
|
|
75
|
+
f"the claude provider needs the Anthropic SDK, which is not installed: {INSTALL_HINT}"
|
|
76
|
+
) from None
|
|
77
|
+
return anthropic
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _get(obj: object, name: str) -> Any:
|
|
81
|
+
if obj is None:
|
|
82
|
+
return None
|
|
83
|
+
if isinstance(obj, dict):
|
|
84
|
+
return obj.get(name)
|
|
85
|
+
return getattr(obj, name, None)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _status(exc: BaseException) -> str:
|
|
89
|
+
code = getattr(exc, "status_code", None)
|
|
90
|
+
return f"HTTP {code}" if isinstance(code, int) else type(exc).__name__
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _token(value: object) -> str | None:
|
|
94
|
+
return value if isinstance(value, str) and _TOKEN.fullmatch(value) else None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _answer(content: object) -> str:
|
|
98
|
+
parts: list[str] = []
|
|
99
|
+
for block in content or (): # type: ignore[attr-defined]
|
|
100
|
+
kind = _get(block, "type")
|
|
101
|
+
if kind == "fallback":
|
|
102
|
+
parts = [] # a declined model's partial text comes before the switch
|
|
103
|
+
elif kind == "text":
|
|
104
|
+
text = _get(block, "text")
|
|
105
|
+
if isinstance(text, str):
|
|
106
|
+
parts.append(text)
|
|
107
|
+
return "".join(parts)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class ClaudeProvider:
|
|
111
|
+
"""Anthropic Messages API adapter (see the module docstring)."""
|
|
112
|
+
|
|
113
|
+
name = "claude"
|
|
114
|
+
|
|
115
|
+
def __init__(self, settings: object, *, environ: Mapping[str, str] | None = None) -> None:
|
|
116
|
+
env = os.environ if environ is None else environ
|
|
117
|
+
self.base_url: str = (
|
|
118
|
+
getattr(settings, "base_url", None) or env.get("ANTHROPIC_BASE_URL") or DEFAULT_BASE_URL
|
|
119
|
+
)
|
|
120
|
+
self.model: str | None = getattr(settings, "model", None) or DEFAULT_MODEL
|
|
121
|
+
self.requested_effort: str | None = getattr(settings, "effort", None)
|
|
122
|
+
self.effort: str | None = None
|
|
123
|
+
self.endpoint: str | None = None
|
|
124
|
+
self.fallbacks = False
|
|
125
|
+
self._sdk: ModuleType | None = None
|
|
126
|
+
self._client: Any = None
|
|
127
|
+
|
|
128
|
+
def prepare(self) -> None:
|
|
129
|
+
endpoint = check_base_url(self.base_url)
|
|
130
|
+
sdk = _import_sdk()
|
|
131
|
+
try:
|
|
132
|
+
client = sdk.Anthropic(
|
|
133
|
+
base_url=endpoint.url, max_retries=MAX_RETRIES, timeout=REQUEST_TIMEOUT_S
|
|
134
|
+
)
|
|
135
|
+
except sdk.AnthropicError:
|
|
136
|
+
raise ProviderUnavailable(
|
|
137
|
+
"no Anthropic credentials were found (set ANTHROPIC_API_KEY or sign in "
|
|
138
|
+
"with `ant auth login`)"
|
|
139
|
+
) from None
|
|
140
|
+
self.endpoint = endpoint.shown
|
|
141
|
+
try:
|
|
142
|
+
info = client.with_options(
|
|
143
|
+
timeout=REQUEST_TIMEOUT_S, max_retries=MAX_RETRIES
|
|
144
|
+
).beta.models.retrieve(self.model, betas=[FALLBACK_BETA])
|
|
145
|
+
except (sdk.AuthenticationError, sdk.PermissionDeniedError) as exc:
|
|
146
|
+
raise ProviderUnavailable(
|
|
147
|
+
f"the Anthropic API refused the credentials ({_status(exc)})"
|
|
148
|
+
) from None
|
|
149
|
+
except sdk.NotFoundError:
|
|
150
|
+
raise ProviderUnavailable(
|
|
151
|
+
"the Anthropic API does not know the model (HTTP 404); check --ai-model"
|
|
152
|
+
) from None
|
|
153
|
+
except sdk.AnthropicError as exc:
|
|
154
|
+
raise ProviderUnavailable(
|
|
155
|
+
f"the model capability check failed ({_status(exc)})"
|
|
156
|
+
) from None
|
|
157
|
+
capabilities = _get(info, "capabilities")
|
|
158
|
+
structured = _get(_get(capabilities, "structured_outputs"), "supported")
|
|
159
|
+
if capabilities is not None and structured is not True:
|
|
160
|
+
raise ProviderUnavailable(
|
|
161
|
+
"the model does not support structured outputs, which the AI pass needs; "
|
|
162
|
+
"choose another model with --ai-model"
|
|
163
|
+
)
|
|
164
|
+
effort = _get(capabilities, "effort")
|
|
165
|
+
level = self.requested_effort
|
|
166
|
+
if capabilities is None or (
|
|
167
|
+
level and _get(effort, "supported") is True and _get(_get(effort, level), "supported")
|
|
168
|
+
):
|
|
169
|
+
self.effort = level
|
|
170
|
+
self.fallbacks = bool(_get(info, "allowed_fallback_models"))
|
|
171
|
+
self._sdk, self._client = sdk, client
|
|
172
|
+
|
|
173
|
+
def review(self, request: Request) -> Outcome:
|
|
174
|
+
sdk, client = self._sdk, self._client
|
|
175
|
+
if sdk is None or client is None:
|
|
176
|
+
return Outcome("abort", reason="the claude provider was not prepared")
|
|
177
|
+
output_config: dict[str, object] = {
|
|
178
|
+
"format": {"type": "json_schema", "schema": prompt.wire_schema()}
|
|
179
|
+
}
|
|
180
|
+
if self.effort:
|
|
181
|
+
output_config["effort"] = self.effort
|
|
182
|
+
kwargs: dict[str, object] = {
|
|
183
|
+
"model": self.model,
|
|
184
|
+
"max_tokens": request.max_tokens,
|
|
185
|
+
"system": [
|
|
186
|
+
{
|
|
187
|
+
"type": "text",
|
|
188
|
+
"text": prompt.system_prompt(),
|
|
189
|
+
"cache_control": {"type": "ephemeral"},
|
|
190
|
+
}
|
|
191
|
+
],
|
|
192
|
+
"messages": [{"role": "user", "content": request.message}],
|
|
193
|
+
"output_config": output_config,
|
|
194
|
+
}
|
|
195
|
+
if self.fallbacks:
|
|
196
|
+
kwargs["betas"] = [FALLBACK_BETA]
|
|
197
|
+
kwargs["fallbacks"] = "default"
|
|
198
|
+
try:
|
|
199
|
+
scoped = client.with_options(timeout=request.timeout, max_retries=MAX_RETRIES)
|
|
200
|
+
with scoped.beta.messages.stream(**kwargs) as stream:
|
|
201
|
+
message = stream.get_final_message()
|
|
202
|
+
except (sdk.AuthenticationError, sdk.PermissionDeniedError) as exc:
|
|
203
|
+
return Outcome(
|
|
204
|
+
"abort", reason=f"the Anthropic API refused the credentials ({_status(exc)})"
|
|
205
|
+
)
|
|
206
|
+
except sdk.NotFoundError:
|
|
207
|
+
return Outcome("abort", reason="the Anthropic API does not know the model (HTTP 404)")
|
|
208
|
+
except sdk.BadRequestError:
|
|
209
|
+
return Outcome("abort", reason="the Anthropic API rejected the request (HTTP 400)")
|
|
210
|
+
except sdk.RateLimitError:
|
|
211
|
+
return Outcome("error", reason="rate limited (HTTP 429)")
|
|
212
|
+
except sdk.APIStatusError as exc:
|
|
213
|
+
if getattr(exc, "status_code", None) == 402:
|
|
214
|
+
return Outcome(
|
|
215
|
+
"abort", reason="the Anthropic API reported a billing problem (HTTP 402)"
|
|
216
|
+
)
|
|
217
|
+
return Outcome("error", reason=f"the Anthropic API failed ({_status(exc)})")
|
|
218
|
+
except sdk.APITimeoutError:
|
|
219
|
+
return Outcome("error", reason="the request timed out")
|
|
220
|
+
except sdk.APIConnectionError:
|
|
221
|
+
return Outcome("error", reason="the connection to the Anthropic API failed")
|
|
222
|
+
except sdk.AnthropicError as exc:
|
|
223
|
+
return Outcome("error", reason=f"the Anthropic SDK failed ({type(exc).__name__})")
|
|
224
|
+
return _outcome(message)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _outcome(message: object) -> Outcome:
|
|
228
|
+
raw = _get(message, "usage")
|
|
229
|
+
usage = usage_of(
|
|
230
|
+
input_tokens=_get(raw, "input_tokens"),
|
|
231
|
+
output_tokens=_get(raw, "output_tokens"),
|
|
232
|
+
cache_creation_input_tokens=_get(raw, "cache_creation_input_tokens"),
|
|
233
|
+
cache_read_input_tokens=_get(raw, "cache_read_input_tokens"),
|
|
234
|
+
)
|
|
235
|
+
served = _get(message, "model")
|
|
236
|
+
served = served if isinstance(served, str) else None
|
|
237
|
+
stop = _get(message, "stop_reason")
|
|
238
|
+
if stop == "end_turn":
|
|
239
|
+
return Outcome("ok", _answer(_get(message, "content")), served, usage)
|
|
240
|
+
if stop == "max_tokens":
|
|
241
|
+
return Outcome("truncated", None, served, usage, "max_tokens")
|
|
242
|
+
if stop == "refusal":
|
|
243
|
+
category = _token(_get(_get(message, "stop_details"), "category"))
|
|
244
|
+
reason = f"refusal ({category})" if category else "refusal"
|
|
245
|
+
return Outcome("refused", None, served, usage, reason)
|
|
246
|
+
label = _token(stop) or "unknown"
|
|
247
|
+
return Outcome("unexpected_stop", None, served, usage, f"stop_reason {label}")
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"""The ``openai`` provider: any OpenAI-compatible endpoint via the ``openai`` SDK (SPEC 9.4).
|
|
2
|
+
|
|
3
|
+
- Endpoint: ``--ai-base-url`` / user config ``[ai] base_url``, else
|
|
4
|
+
``CODEVETO_AI_BASE_URL``, else ``https://api.openai.com/v1``; the SDK gets it
|
|
5
|
+
explicitly, so ``OPENAI_BASE_URL`` is never consulted. ``http://`` is
|
|
6
|
+
refused except for ``localhost`` and literal loopback IPs, and a URL with
|
|
7
|
+
user info, spaces or control characters is refused
|
|
8
|
+
(:func:`codeveto.ai.providers.check_base_url`).
|
|
9
|
+
- Key: ``CODEVETO_AI_API_KEY``; for ``api.openai.com`` only, ``OPENAI_API_KEY``
|
|
10
|
+
when that is unset. Any other host needs ``CODEVETO_AI_API_KEY`` (a loopback
|
|
11
|
+
host may go without one, an empty key is sent).
|
|
12
|
+
- ``--ai-model`` (or user config ``[ai] model``) is required.
|
|
13
|
+
- ``client.with_options(timeout=T).chat.completions.create(model=...,
|
|
14
|
+
messages=[system, user], max_completion_tokens=N | max_tokens=N,
|
|
15
|
+
response_format=...)`` with ``max_completion_tokens`` on api.openai.com and
|
|
16
|
+
the widely supported ``max_tokens`` elsewhere. ``--ai-response-format``:
|
|
17
|
+
``json_schema`` (default, ``strict: true``), ``json_object``, or ``prompt``
|
|
18
|
+
(no response format); the last two embed the wire schema in the system
|
|
19
|
+
prompt. A 400 that mentions ``response_format`` aborts the pass with an
|
|
20
|
+
issue naming the flag; it is never downgraded silently.
|
|
21
|
+
- A response fails its packet when it has ``tool_calls``, a non-null
|
|
22
|
+
``refusal`` (``refused``), ``finish_reason`` ``length`` (``truncated``),
|
|
23
|
+
``content_filter`` (``refused``) or anything else but ``stop``
|
|
24
|
+
(``unexpected_stop``). ``ai.endpoint`` records host, port and path.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import json
|
|
30
|
+
from collections.abc import Mapping
|
|
31
|
+
from types import ModuleType
|
|
32
|
+
from typing import Any
|
|
33
|
+
from urllib.parse import urlsplit
|
|
34
|
+
|
|
35
|
+
from codeveto.ai import prompt
|
|
36
|
+
from codeveto.ai.providers import (
|
|
37
|
+
Outcome,
|
|
38
|
+
ProviderUnavailable,
|
|
39
|
+
Request,
|
|
40
|
+
check_base_url,
|
|
41
|
+
loopback,
|
|
42
|
+
usage_of,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
__all__ = ["DEFAULT_BASE_URL", "MAX_RETRIES", "REQUEST_TIMEOUT_S", "OpenAIProvider", "loopback"]
|
|
46
|
+
|
|
47
|
+
DEFAULT_BASE_URL = "https://api.openai.com/v1"
|
|
48
|
+
OPENAI_HOST = "api.openai.com"
|
|
49
|
+
REQUEST_TIMEOUT_S = 180.0
|
|
50
|
+
MAX_RETRIES = 2
|
|
51
|
+
INSTALL_HINT = "install codeveto[openai]"
|
|
52
|
+
RESPONSE_FORMATS = ("json_schema", "json_object", "prompt")
|
|
53
|
+
_SCHEMA_NAME = "codeveto_review"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _import_sdk() -> ModuleType:
|
|
57
|
+
try:
|
|
58
|
+
import openai # optional extra, imported only when used
|
|
59
|
+
except ImportError:
|
|
60
|
+
raise ProviderUnavailable(
|
|
61
|
+
f"the openai provider needs the OpenAI SDK, which is not installed: {INSTALL_HINT}"
|
|
62
|
+
) from None
|
|
63
|
+
return openai
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _get(obj: object, name: str) -> Any:
|
|
67
|
+
if obj is None:
|
|
68
|
+
return None
|
|
69
|
+
if isinstance(obj, dict):
|
|
70
|
+
return obj.get(name)
|
|
71
|
+
return getattr(obj, name, None)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _status(exc: BaseException) -> str:
|
|
75
|
+
code = getattr(exc, "status_code", None)
|
|
76
|
+
return f"HTTP {code}" if isinstance(code, int) else type(exc).__name__
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _mentions_response_format(exc: BaseException) -> bool:
|
|
80
|
+
body = getattr(exc, "body", None)
|
|
81
|
+
try:
|
|
82
|
+
text = f"{getattr(exc, 'message', '')} {json.dumps(body, default=str)}"
|
|
83
|
+
except (TypeError, ValueError):
|
|
84
|
+
text = str(getattr(exc, "message", ""))
|
|
85
|
+
return "response_format" in text
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class OpenAIProvider:
|
|
89
|
+
"""OpenAI-compatible Chat Completions adapter (see the module docstring)."""
|
|
90
|
+
|
|
91
|
+
name = "openai"
|
|
92
|
+
effort: str | None = None
|
|
93
|
+
|
|
94
|
+
def __init__(
|
|
95
|
+
self, settings: object, *, response_format: str, environ: Mapping[str, str]
|
|
96
|
+
) -> None:
|
|
97
|
+
self.model: str | None = getattr(settings, "model", None)
|
|
98
|
+
self.response_format = response_format
|
|
99
|
+
self.base_url: str = (
|
|
100
|
+
getattr(settings, "base_url", None)
|
|
101
|
+
or environ.get("CODEVETO_AI_BASE_URL")
|
|
102
|
+
or DEFAULT_BASE_URL
|
|
103
|
+
)
|
|
104
|
+
self.endpoint: str | None = None
|
|
105
|
+
self._environ = environ
|
|
106
|
+
self._sdk: ModuleType | None = None
|
|
107
|
+
self._client: Any = None
|
|
108
|
+
|
|
109
|
+
def _key(self, host: str) -> str:
|
|
110
|
+
env = self._environ
|
|
111
|
+
key = env.get("CODEVETO_AI_API_KEY")
|
|
112
|
+
if host == OPENAI_HOST:
|
|
113
|
+
key = key or env.get("OPENAI_API_KEY")
|
|
114
|
+
if not key:
|
|
115
|
+
raise ProviderUnavailable(
|
|
116
|
+
"no API key for api.openai.com: set CODEVETO_AI_API_KEY or OPENAI_API_KEY"
|
|
117
|
+
)
|
|
118
|
+
return key
|
|
119
|
+
if key is None:
|
|
120
|
+
if loopback(host):
|
|
121
|
+
return ""
|
|
122
|
+
raise ProviderUnavailable(
|
|
123
|
+
f"set CODEVETO_AI_API_KEY for the AI endpoint {host} "
|
|
124
|
+
"(OPENAI_API_KEY is only sent to api.openai.com)"
|
|
125
|
+
)
|
|
126
|
+
return key
|
|
127
|
+
|
|
128
|
+
def prepare(self) -> None:
|
|
129
|
+
if self.response_format not in RESPONSE_FORMATS:
|
|
130
|
+
raise ProviderUnavailable(f"unknown --ai-response-format {self.response_format!r}")
|
|
131
|
+
if not self.model:
|
|
132
|
+
raise ProviderUnavailable(
|
|
133
|
+
"the openai provider needs a model: pass --ai-model or set [ai] model "
|
|
134
|
+
"in user config"
|
|
135
|
+
)
|
|
136
|
+
endpoint = check_base_url(self.base_url)
|
|
137
|
+
self.endpoint = endpoint.shown
|
|
138
|
+
key = self._key(endpoint.host)
|
|
139
|
+
sdk = _import_sdk()
|
|
140
|
+
try:
|
|
141
|
+
self._client = sdk.OpenAI(
|
|
142
|
+
api_key=key,
|
|
143
|
+
base_url=self.base_url,
|
|
144
|
+
max_retries=MAX_RETRIES,
|
|
145
|
+
timeout=REQUEST_TIMEOUT_S,
|
|
146
|
+
)
|
|
147
|
+
except sdk.OpenAIError:
|
|
148
|
+
raise ProviderUnavailable("the OpenAI client could not be created") from None
|
|
149
|
+
self._sdk = sdk
|
|
150
|
+
|
|
151
|
+
def _kwargs(self, request: Request) -> dict[str, object]:
|
|
152
|
+
embed = self.response_format != "json_schema"
|
|
153
|
+
kwargs: dict[str, object] = {
|
|
154
|
+
"model": self.model,
|
|
155
|
+
"messages": [
|
|
156
|
+
{"role": "system", "content": prompt.system_prompt(embed_schema=embed)},
|
|
157
|
+
{"role": "user", "content": request.message},
|
|
158
|
+
],
|
|
159
|
+
}
|
|
160
|
+
if urlsplit(self.base_url).hostname == OPENAI_HOST:
|
|
161
|
+
kwargs["max_completion_tokens"] = request.max_tokens
|
|
162
|
+
else:
|
|
163
|
+
kwargs["max_tokens"] = request.max_tokens
|
|
164
|
+
if self.response_format == "json_schema":
|
|
165
|
+
kwargs["response_format"] = {
|
|
166
|
+
"type": "json_schema",
|
|
167
|
+
"json_schema": {
|
|
168
|
+
"name": _SCHEMA_NAME,
|
|
169
|
+
"schema": prompt.wire_schema(),
|
|
170
|
+
"strict": True,
|
|
171
|
+
},
|
|
172
|
+
}
|
|
173
|
+
elif self.response_format == "json_object":
|
|
174
|
+
kwargs["response_format"] = {"type": "json_object"}
|
|
175
|
+
return kwargs
|
|
176
|
+
|
|
177
|
+
def review(self, request: Request) -> Outcome:
|
|
178
|
+
sdk, client = self._sdk, self._client
|
|
179
|
+
if sdk is None or client is None:
|
|
180
|
+
return Outcome("abort", reason="the openai provider was not prepared")
|
|
181
|
+
try:
|
|
182
|
+
completion = client.with_options(timeout=request.timeout).chat.completions.create(
|
|
183
|
+
**self._kwargs(request)
|
|
184
|
+
)
|
|
185
|
+
except sdk.BadRequestError as exc:
|
|
186
|
+
if _mentions_response_format(exc):
|
|
187
|
+
return Outcome(
|
|
188
|
+
"abort",
|
|
189
|
+
reason=(
|
|
190
|
+
f"the endpoint rejected response_format {self.response_format} "
|
|
191
|
+
"(HTTP 400); choose another with --ai-response-format "
|
|
192
|
+
"(json_schema, json_object or prompt)"
|
|
193
|
+
),
|
|
194
|
+
)
|
|
195
|
+
return Outcome("abort", reason="the endpoint rejected the request (HTTP 400)")
|
|
196
|
+
except (sdk.AuthenticationError, sdk.PermissionDeniedError) as exc:
|
|
197
|
+
return Outcome("abort", reason=f"the endpoint refused the API key ({_status(exc)})")
|
|
198
|
+
except sdk.NotFoundError:
|
|
199
|
+
return Outcome("abort", reason="the endpoint does not know the model (HTTP 404)")
|
|
200
|
+
except sdk.RateLimitError:
|
|
201
|
+
return Outcome("error", reason="rate limited (HTTP 429)")
|
|
202
|
+
except sdk.APIStatusError as exc:
|
|
203
|
+
if getattr(exc, "status_code", None) == 402:
|
|
204
|
+
return Outcome("abort", reason="the endpoint reported a billing problem (HTTP 402)")
|
|
205
|
+
return Outcome("error", reason=f"the endpoint failed ({_status(exc)})")
|
|
206
|
+
except sdk.APITimeoutError:
|
|
207
|
+
return Outcome("error", reason="the request timed out")
|
|
208
|
+
except sdk.APIConnectionError:
|
|
209
|
+
return Outcome("error", reason="the connection to the endpoint failed")
|
|
210
|
+
except sdk.OpenAIError as exc:
|
|
211
|
+
return Outcome("error", reason=f"the OpenAI SDK failed ({type(exc).__name__})")
|
|
212
|
+
return _outcome(completion)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _outcome(completion: object) -> Outcome:
|
|
216
|
+
raw = _get(completion, "usage")
|
|
217
|
+
prompt_tokens = _get(raw, "prompt_tokens")
|
|
218
|
+
cached = _get(_get(raw, "prompt_tokens_details"), "cached_tokens")
|
|
219
|
+
prompt_count = prompt_tokens if isinstance(prompt_tokens, int) else 0
|
|
220
|
+
cached_count = cached if isinstance(cached, int) and 0 <= cached <= prompt_count else 0
|
|
221
|
+
usage = usage_of(
|
|
222
|
+
input_tokens=prompt_count - cached_count,
|
|
223
|
+
output_tokens=_get(raw, "completion_tokens"),
|
|
224
|
+
cache_read_input_tokens=cached_count,
|
|
225
|
+
)
|
|
226
|
+
served = _get(completion, "model")
|
|
227
|
+
served = served if isinstance(served, str) else None
|
|
228
|
+
choices = _get(completion, "choices") or []
|
|
229
|
+
if not choices:
|
|
230
|
+
return Outcome("unexpected_stop", None, served, usage, "no choices in the response")
|
|
231
|
+
choice = choices[0]
|
|
232
|
+
message = _get(choice, "message")
|
|
233
|
+
if _get(message, "tool_calls"):
|
|
234
|
+
return Outcome("error", None, served, usage, "the response contains tool_calls")
|
|
235
|
+
if _get(message, "refusal") is not None:
|
|
236
|
+
return Outcome("refused", None, served, usage, "refusal")
|
|
237
|
+
finish = _get(choice, "finish_reason")
|
|
238
|
+
if finish == "stop":
|
|
239
|
+
content = _get(message, "content")
|
|
240
|
+
return Outcome("ok", content if isinstance(content, str) else "", served, usage)
|
|
241
|
+
if finish == "length":
|
|
242
|
+
return Outcome("truncated", None, served, usage, "finish_reason length")
|
|
243
|
+
if finish == "content_filter":
|
|
244
|
+
return Outcome("refused", None, served, usage, "finish_reason content_filter")
|
|
245
|
+
label = finish if finish in ("tool_calls", "function_call") else "other"
|
|
246
|
+
return Outcome("unexpected_stop", None, served, usage, f"finish_reason {label}")
|