stackdoctor-cli 1.0.1__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.
- stackdoctor/__init__.py +15 -0
- stackdoctor/__main__.py +6 -0
- stackdoctor/agent/__init__.py +5 -0
- stackdoctor/agent/compaction.py +66 -0
- stackdoctor/agent/diagnosis.py +398 -0
- stackdoctor/agent/loop.py +801 -0
- stackdoctor/agent/prompts.py +85 -0
- stackdoctor/agent/providers/__init__.py +295 -0
- stackdoctor/agent/providers/base.py +210 -0
- stackdoctor/agent/providers/claude.py +285 -0
- stackdoctor/agent/providers/gemini.py +312 -0
- stackdoctor/agent/providers/openai_compat.py +537 -0
- stackdoctor/agent/providers/prices.py +90 -0
- stackdoctor/benchmark/__init__.py +11 -0
- stackdoctor/benchmark/__main__.py +198 -0
- stackdoctor/benchmark/holmes.py +386 -0
- stackdoctor/benchmark/report.py +362 -0
- stackdoctor/benchmark/runner.py +710 -0
- stackdoctor/benchmark/scenarios.py +153 -0
- stackdoctor/benchmark/scoring.py +184 -0
- stackdoctor/cli.py +882 -0
- stackdoctor/dependencies.py +221 -0
- stackdoctor/discovery.py +361 -0
- stackdoctor/evidence.py +134 -0
- stackdoctor/github.py +168 -0
- stackdoctor/live.py +808 -0
- stackdoctor/mcp_server.py +233 -0
- stackdoctor/models.py +275 -0
- stackdoctor/pglog.py +55 -0
- stackdoctor/postgres.py +294 -0
- stackdoctor/probes.py +172 -0
- stackdoctor/py.typed +0 -0
- stackdoctor/redaction.py +215 -0
- stackdoctor/rules.py +303 -0
- stackdoctor/validation.py +61 -0
- stackdoctor_cli-1.0.1.dist-info/METADATA +177 -0
- stackdoctor_cli-1.0.1.dist-info/RECORD +40 -0
- stackdoctor_cli-1.0.1.dist-info/WHEEL +4 -0
- stackdoctor_cli-1.0.1.dist-info/entry_points.txt +3 -0
- stackdoctor_cli-1.0.1.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,537 @@
|
|
|
1
|
+
"""OpenAI-compatible chat APIs, through the official openai SDK (Chat Completions).
|
|
2
|
+
|
|
3
|
+
One adapter covers every server that speaks the OpenAI Chat Completions API
|
|
4
|
+
with function calling: the ``groq`` and ``ollama`` presets, and any other
|
|
5
|
+
endpoint through ``--provider openai-compatible --base-url ...`` (OpenAI
|
|
6
|
+
itself, OpenRouter, vLLM, ...).
|
|
7
|
+
|
|
8
|
+
Only this module imports the SDK, and only `create_provider` imports this
|
|
9
|
+
module, for those providers.
|
|
10
|
+
|
|
11
|
+
Choices worth knowing:
|
|
12
|
+
|
|
13
|
+
- **API key.** Read only from the preset's variable
|
|
14
|
+
(``STACKDOCTOR_GROQ_API_KEY``; never ``GROQ_API_KEY``) or the one named
|
|
15
|
+
with ``--api-key-env``, and passed to the client explicitly.
|
|
16
|
+
Ollama needs none; a placeholder is sent, which Ollama ignores.
|
|
17
|
+
- **Base URL.** Always passed explicitly, so ``OPENAI_BASE_URL`` cannot
|
|
18
|
+
redirect the data. It must use https, except for a server on this machine
|
|
19
|
+
(loopback), and must not contain credentials or a query string. Reports
|
|
20
|
+
show only its scheme, host and port.
|
|
21
|
+
- **No OpenAI account headers.** The SDK reads ``OPENAI_ORG_ID`` and
|
|
22
|
+
``OPENAI_PROJECT_ID`` from the environment and sends them as headers to
|
|
23
|
+
any base URL. They are removed: a third-party server never needs them.
|
|
24
|
+
- **Retries.** The SDK's own retries are disabled (``max_retries=0``); the
|
|
25
|
+
agent loop retries itself, so the count stays bounded and visible.
|
|
26
|
+
- **Reasoning.** Groq's reasoning models take ``--thinking-level`` as
|
|
27
|
+
``reasoning_effort``. Reasoning tokens are reported inside
|
|
28
|
+
``completion_tokens`` and are split out as thinking tokens. On Groq, the
|
|
29
|
+
model's reasoning (the response's ``reasoning`` field) is sent back after
|
|
30
|
+
each tool call, until the model answers without one. gpt-oss needs it:
|
|
31
|
+
OpenAI's harmony guide says the chain of thought must be passed back after
|
|
32
|
+
a tool call, and without it gpt-oss-120b at low effort often names its
|
|
33
|
+
next tool call after a format token (``json``, ``commentary``), which Groq
|
|
34
|
+
rejects. The reasoning comes from the same provider and saw only redacted
|
|
35
|
+
data. Other servers get no reasoning back: the field is not standard.
|
|
36
|
+
- **Tool calls.** Arguments arrive as a JSON string. A string that is not a
|
|
37
|
+
JSON object becomes a `ToolCall` with ``error`` set, as for every
|
|
38
|
+
provider. A tool call the server itself rejects (Groq: a 400 with
|
|
39
|
+
``failed_generation``) is reported as ``malformed_output``.
|
|
40
|
+
- **Forced calls.** ``tool_choice`` names the tool, except on Ollama, which
|
|
41
|
+
does not support ``tool_choice``.
|
|
42
|
+
- **Optional arguments may be null.** Groq checks every tool call against
|
|
43
|
+
the tool's schema on its side, and models often send ``null`` for an
|
|
44
|
+
optional argument they leave empty (gpt-oss: ``"root_cause": null`` with
|
|
45
|
+
no problem found), which Groq rejected in M6. Every optional property is
|
|
46
|
+
sent as nullable (``["string", "null"]``); StackDoctor reads ``null`` as
|
|
47
|
+
absent. Gemini and Anthropic get the schema unchanged.
|
|
48
|
+
- **Output cap.** None by default, so the server estimates each reply's size
|
|
49
|
+
itself. ``--max-output-tokens`` sends one, as ``max_completion_tokens``
|
|
50
|
+
(``max_tokens`` on Ollama, which supports only that).
|
|
51
|
+
- **Request too large.** Groq rejects a request whose expected output is
|
|
52
|
+
above the model's output tokens per minute with a 429 "Request too
|
|
53
|
+
large". Waiting does not help, so it is ``too_large``, not a rate limit:
|
|
54
|
+
it is not retried, and the next model in the chain is tried. Groq's
|
|
55
|
+
messages name the account's organization (``org_...``); that ID is
|
|
56
|
+
removed from every error message.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
import contextlib
|
|
60
|
+
import ipaddress
|
|
61
|
+
import json
|
|
62
|
+
import re
|
|
63
|
+
import urllib.request
|
|
64
|
+
from collections.abc import Mapping, Sequence
|
|
65
|
+
from dataclasses import dataclass, field
|
|
66
|
+
from typing import Any
|
|
67
|
+
from urllib.parse import urlsplit
|
|
68
|
+
|
|
69
|
+
import openai
|
|
70
|
+
from openai import AsyncOpenAI
|
|
71
|
+
|
|
72
|
+
from stackdoctor.agent.providers import THINKING_LEVELS, ProviderSpec, find_key, key_names
|
|
73
|
+
from stackdoctor.agent.providers.base import (
|
|
74
|
+
ErrorKind,
|
|
75
|
+
Price,
|
|
76
|
+
ProviderError,
|
|
77
|
+
ProviderUnavailableError,
|
|
78
|
+
ToolCall,
|
|
79
|
+
ToolResult,
|
|
80
|
+
ToolSpec,
|
|
81
|
+
Turn,
|
|
82
|
+
Usage,
|
|
83
|
+
)
|
|
84
|
+
from stackdoctor.agent.providers.prices import price_for
|
|
85
|
+
|
|
86
|
+
# Seconds allowed for one model call. The loop's wall-clock limit bounds the run.
|
|
87
|
+
REQUEST_TIMEOUT_SECONDS = 120.0
|
|
88
|
+
# Seconds allowed for checking that a local server (Ollama) is running.
|
|
89
|
+
PROBE_TIMEOUT_SECONDS = 3.0
|
|
90
|
+
# Ollama ignores the key, but the client requires one.
|
|
91
|
+
PLACEHOLDER_KEY = "unused"
|
|
92
|
+
# OpenAI account headers, removed from every request: a third-party server
|
|
93
|
+
# never needs them.
|
|
94
|
+
ACCOUNT_HEADERS: dict[str, openai.Omit] = {
|
|
95
|
+
"OpenAI-Organization": openai.omit,
|
|
96
|
+
"OpenAI-Project": openai.omit,
|
|
97
|
+
}
|
|
98
|
+
# Longest provider error message kept, in characters.
|
|
99
|
+
MAX_ERROR_MESSAGE = 300
|
|
100
|
+
|
|
101
|
+
_LOOPBACK_NAMES = {"localhost"}
|
|
102
|
+
# An account's organization ID in an error message, such as Groq's
|
|
103
|
+
# "in organization `org_...`".
|
|
104
|
+
_ORGANIZATION = re.compile(r"\s*\bin organization `?org_\w+`?|\s*\borg_\w+")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class BaseUrlError(ValueError):
|
|
108
|
+
"""The base URL is not allowed (see `check_base_url`)."""
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def check_base_url(url: str) -> str:
|
|
112
|
+
"""Check a base URL and return the form shown in reports: scheme://host[:port].
|
|
113
|
+
|
|
114
|
+
Raises:
|
|
115
|
+
BaseUrlError: if the URL is not http(s), has no host, contains
|
|
116
|
+
credentials, a query or a fragment, or uses plain http for a
|
|
117
|
+
host that is not this machine.
|
|
118
|
+
"""
|
|
119
|
+
parts = urlsplit(url)
|
|
120
|
+
if parts.scheme not in ("https", "http") or not parts.hostname:
|
|
121
|
+
raise BaseUrlError("The base URL must be an http:// or https:// URL with a host.")
|
|
122
|
+
if parts.username is not None or parts.password is not None:
|
|
123
|
+
raise BaseUrlError(
|
|
124
|
+
"The base URL must not contain credentials. Put the key in an environment "
|
|
125
|
+
"variable and name it with --api-key-env."
|
|
126
|
+
)
|
|
127
|
+
if parts.query or parts.fragment:
|
|
128
|
+
raise BaseUrlError(
|
|
129
|
+
"The base URL must not contain a query or a fragment. Put a key in an "
|
|
130
|
+
"environment variable and name it with --api-key-env."
|
|
131
|
+
)
|
|
132
|
+
if parts.scheme == "http" and not _is_loopback(parts.hostname):
|
|
133
|
+
raise BaseUrlError(
|
|
134
|
+
"Plain http is only allowed for a server on this machine (localhost). "
|
|
135
|
+
"Use https for any other host."
|
|
136
|
+
)
|
|
137
|
+
port = f":{parts.port}" if parts.port is not None else ""
|
|
138
|
+
return f"{parts.scheme}://{parts.hostname}{port}"
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _is_loopback(host: str) -> bool:
|
|
142
|
+
if host.lower() in _LOOPBACK_NAMES:
|
|
143
|
+
return True
|
|
144
|
+
try:
|
|
145
|
+
return ipaddress.ip_address(host).is_loopback
|
|
146
|
+
except ValueError:
|
|
147
|
+
return False
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def create_openai_compatible(
|
|
151
|
+
spec: ProviderSpec,
|
|
152
|
+
*,
|
|
153
|
+
model: str,
|
|
154
|
+
thinking_level: str,
|
|
155
|
+
price: Price | None,
|
|
156
|
+
base_url: str | None,
|
|
157
|
+
api_key_variable: str | None,
|
|
158
|
+
max_request_tokens: int | None = None,
|
|
159
|
+
max_output_tokens: int | None = None,
|
|
160
|
+
client: Any = None,
|
|
161
|
+
) -> "OpenAICompatibleProvider":
|
|
162
|
+
"""Create the provider for a preset (``groq``, ``ollama``) or ``openai-compatible``.
|
|
163
|
+
|
|
164
|
+
Raises:
|
|
165
|
+
ProviderUnavailableError: if the base URL is missing or not allowed,
|
|
166
|
+
the key is not set, or a local server is not running or lacks
|
|
167
|
+
the model.
|
|
168
|
+
"""
|
|
169
|
+
url = base_url or spec.base_url
|
|
170
|
+
if url is None:
|
|
171
|
+
raise ProviderUnavailableError(f"The {spec.title} provider needs --base-url.")
|
|
172
|
+
url = url.rstrip("/")
|
|
173
|
+
try:
|
|
174
|
+
shown = check_base_url(url)
|
|
175
|
+
except BaseUrlError as error:
|
|
176
|
+
raise ProviderUnavailableError(str(error)) from None
|
|
177
|
+
|
|
178
|
+
variables = (api_key_variable,) if api_key_variable else spec.key_variables
|
|
179
|
+
api_key = PLACEHOLDER_KEY
|
|
180
|
+
if variables:
|
|
181
|
+
api_key = find_key(variables) or ""
|
|
182
|
+
if not api_key:
|
|
183
|
+
raise ProviderUnavailableError(
|
|
184
|
+
f"Set {key_names(variables)} to use the {spec.title} provider."
|
|
185
|
+
+ (" Create a key at https://console.groq.com/keys" if spec.name == "groq" else "")
|
|
186
|
+
)
|
|
187
|
+
if spec.local and client is None:
|
|
188
|
+
_check_local_server(spec, url, model)
|
|
189
|
+
return OpenAICompatibleProvider(
|
|
190
|
+
spec=spec,
|
|
191
|
+
model=model,
|
|
192
|
+
base_url=url,
|
|
193
|
+
shown_url=shown,
|
|
194
|
+
thinking_level=thinking_level,
|
|
195
|
+
price=price,
|
|
196
|
+
client=client if client is not None else _client(api_key, url),
|
|
197
|
+
max_request_tokens=max_request_tokens or spec.max_request_tokens,
|
|
198
|
+
max_output_tokens=max_output_tokens,
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _client(api_key: str, base_url: str) -> AsyncOpenAI:
|
|
203
|
+
return AsyncOpenAI(
|
|
204
|
+
api_key=api_key,
|
|
205
|
+
base_url=base_url,
|
|
206
|
+
# Empty here, and the headers removed from every request (see
|
|
207
|
+
# ACCOUNT_HEADERS): otherwise read from OPENAI_ORG_ID and
|
|
208
|
+
# OPENAI_PROJECT_ID and sent to whatever server this is.
|
|
209
|
+
organization="",
|
|
210
|
+
project="",
|
|
211
|
+
max_retries=0,
|
|
212
|
+
timeout=REQUEST_TIMEOUT_SECONDS,
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _check_local_server(spec: ProviderSpec, base_url: str, model: str) -> None:
|
|
217
|
+
"""Fail early, with a clear message, if the local server is down or lacks the model."""
|
|
218
|
+
try:
|
|
219
|
+
# The URL was checked by check_base_url. urllib's errors are OSErrors.
|
|
220
|
+
with urllib.request.urlopen(
|
|
221
|
+
f"{base_url}/models", timeout=PROBE_TIMEOUT_SECONDS
|
|
222
|
+
) as response:
|
|
223
|
+
listed = json.load(response)
|
|
224
|
+
except (OSError, ValueError):
|
|
225
|
+
raise ProviderUnavailableError(
|
|
226
|
+
f"The {spec.title} server is not reachable at {check_base_url(base_url)}. "
|
|
227
|
+
"Start it (for Ollama: 'ollama serve') or give its address with --base-url."
|
|
228
|
+
) from None
|
|
229
|
+
data = listed.get("data") if isinstance(listed, dict) else None
|
|
230
|
+
names = [str(item.get("id")) for item in data or () if isinstance(item, dict)]
|
|
231
|
+
if names and model not in names:
|
|
232
|
+
raise ProviderUnavailableError(
|
|
233
|
+
f"The {spec.title} server has no model {model!r}. "
|
|
234
|
+
f"Available: {', '.join(names[:20])}. For Ollama: 'ollama pull {model}'."
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
class OpenAICompatibleProvider:
|
|
239
|
+
"""`LLMProvider` for any OpenAI-compatible Chat Completions API."""
|
|
240
|
+
|
|
241
|
+
def __init__(
|
|
242
|
+
self,
|
|
243
|
+
*,
|
|
244
|
+
spec: ProviderSpec,
|
|
245
|
+
model: str,
|
|
246
|
+
base_url: str,
|
|
247
|
+
shown_url: str,
|
|
248
|
+
thinking_level: str,
|
|
249
|
+
price: Price | None,
|
|
250
|
+
client: Any,
|
|
251
|
+
max_request_tokens: int | None = None,
|
|
252
|
+
max_output_tokens: int | None = None,
|
|
253
|
+
) -> None:
|
|
254
|
+
if thinking_level not in THINKING_LEVELS:
|
|
255
|
+
raise ValueError(f"thinking_level must be one of {', '.join(THINKING_LEVELS)}")
|
|
256
|
+
if max_output_tokens is not None and max_output_tokens < 1:
|
|
257
|
+
raise ValueError("max_output_tokens must be at least 1")
|
|
258
|
+
self._spec = spec
|
|
259
|
+
self._model = model
|
|
260
|
+
self._base_url = base_url
|
|
261
|
+
self._shown_url = shown_url
|
|
262
|
+
self._thinking_level = thinking_level
|
|
263
|
+
self._price = price
|
|
264
|
+
self._client = client
|
|
265
|
+
self._max_request_tokens = max_request_tokens
|
|
266
|
+
self._max_output_tokens = max_output_tokens
|
|
267
|
+
|
|
268
|
+
@property
|
|
269
|
+
def name(self) -> str:
|
|
270
|
+
return self._spec.name
|
|
271
|
+
|
|
272
|
+
@property
|
|
273
|
+
def model(self) -> str:
|
|
274
|
+
return self._model
|
|
275
|
+
|
|
276
|
+
@property
|
|
277
|
+
def can_force_tool(self) -> bool:
|
|
278
|
+
return self._spec.can_force_tool
|
|
279
|
+
|
|
280
|
+
@property
|
|
281
|
+
def max_request_tokens(self) -> int | None:
|
|
282
|
+
return self._max_request_tokens
|
|
283
|
+
|
|
284
|
+
@property
|
|
285
|
+
def settings(self) -> Mapping[str, str]:
|
|
286
|
+
settings: dict[str, str] = {}
|
|
287
|
+
if self._spec.sends_reasoning_effort:
|
|
288
|
+
settings["reasoning_effort"] = self._thinking_level
|
|
289
|
+
if self._spec.base_url is None or self._base_url != self._spec.base_url:
|
|
290
|
+
settings["base_url"] = self._shown_url
|
|
291
|
+
if self._max_output_tokens is not None:
|
|
292
|
+
settings["max_output_tokens"] = str(self._max_output_tokens)
|
|
293
|
+
return settings
|
|
294
|
+
|
|
295
|
+
def price(self) -> Price | None:
|
|
296
|
+
if self._price is not None:
|
|
297
|
+
return self._price
|
|
298
|
+
if self._spec.local:
|
|
299
|
+
return Price(0.0, 0.0)
|
|
300
|
+
return price_for(self._spec.name, self._model)
|
|
301
|
+
|
|
302
|
+
def start(self, system: str, tools: Sequence[ToolSpec]) -> "OpenAICompatibleSession":
|
|
303
|
+
return OpenAICompatibleSession(
|
|
304
|
+
client=self._client,
|
|
305
|
+
model=self._model,
|
|
306
|
+
title=self._spec.title,
|
|
307
|
+
tools=[
|
|
308
|
+
{
|
|
309
|
+
"type": "function",
|
|
310
|
+
"function": {
|
|
311
|
+
"name": tool.name,
|
|
312
|
+
"description": tool.description,
|
|
313
|
+
"parameters": nullable_optional(dict(tool.parameters)),
|
|
314
|
+
},
|
|
315
|
+
}
|
|
316
|
+
for tool in tools
|
|
317
|
+
],
|
|
318
|
+
reasoning_effort=self._thinking_level if self._spec.sends_reasoning_effort else None,
|
|
319
|
+
can_force_tool=self._spec.can_force_tool,
|
|
320
|
+
returns_reasoning=self._spec.returns_reasoning,
|
|
321
|
+
output_cap=(
|
|
322
|
+
{self._spec.output_cap_field: self._max_output_tokens}
|
|
323
|
+
if self._max_output_tokens is not None
|
|
324
|
+
else {}
|
|
325
|
+
),
|
|
326
|
+
history=({"role": "system", "content": system},),
|
|
327
|
+
)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
@dataclass
|
|
331
|
+
class OpenAICompatibleSession:
|
|
332
|
+
"""One conversation. ``history`` holds Chat Completions messages."""
|
|
333
|
+
|
|
334
|
+
client: Any
|
|
335
|
+
model: str
|
|
336
|
+
title: str
|
|
337
|
+
tools: list[dict[str, Any]]
|
|
338
|
+
reasoning_effort: str | None
|
|
339
|
+
can_force_tool: bool
|
|
340
|
+
returns_reasoning: bool = False
|
|
341
|
+
# The output cap's request field and value; empty for none.
|
|
342
|
+
output_cap: dict[str, int] = field(default_factory=dict)
|
|
343
|
+
history: tuple[dict[str, Any], ...] = field(default=())
|
|
344
|
+
|
|
345
|
+
def request(self, messages: Sequence[dict[str, Any]], force_tool: str | None) -> dict[str, Any]:
|
|
346
|
+
"""The arguments of one ``chat.completions.create`` call."""
|
|
347
|
+
request: dict[str, Any] = {
|
|
348
|
+
"model": self.model,
|
|
349
|
+
"messages": list(messages),
|
|
350
|
+
"tools": self.tools,
|
|
351
|
+
"extra_headers": ACCOUNT_HEADERS,
|
|
352
|
+
}
|
|
353
|
+
if force_tool is not None and self.can_force_tool:
|
|
354
|
+
request["tool_choice"] = {"type": "function", "function": {"name": force_tool}}
|
|
355
|
+
if self.reasoning_effort is not None:
|
|
356
|
+
request["reasoning_effort"] = self.reasoning_effort
|
|
357
|
+
request.update(self.output_cap)
|
|
358
|
+
return request
|
|
359
|
+
|
|
360
|
+
async def send(
|
|
361
|
+
self, message: str | Sequence[ToolResult], *, force_tool: str | None = None
|
|
362
|
+
) -> Turn:
|
|
363
|
+
messages = (*self.history, *_user_messages(message))
|
|
364
|
+
try:
|
|
365
|
+
response = await self.client.chat.completions.create(
|
|
366
|
+
**self.request(messages, force_tool)
|
|
367
|
+
)
|
|
368
|
+
except openai.APIStatusError as error:
|
|
369
|
+
raise _provider_error(self.title, error) from None
|
|
370
|
+
except openai.APIConnectionError as error:
|
|
371
|
+
# Timeouts and connection failures: worth retrying.
|
|
372
|
+
raise ProviderError(
|
|
373
|
+
f"{self.title} request failed: {type(error).__name__}", retryable=True
|
|
374
|
+
) from None
|
|
375
|
+
|
|
376
|
+
choice = response.choices[0] if response.choices else None
|
|
377
|
+
reply = choice.message if choice is not None else None
|
|
378
|
+
calls = _tool_calls(reply)
|
|
379
|
+
# Only after success, so a failed call can be sent again unchanged.
|
|
380
|
+
if reply is None:
|
|
381
|
+
self.history = messages
|
|
382
|
+
elif calls:
|
|
383
|
+
self.history = (*messages, _assistant_message(reply, self.returns_reasoning))
|
|
384
|
+
else:
|
|
385
|
+
# An answer without a tool call ends the model's chain of
|
|
386
|
+
# thought: earlier reasoning is not sent again.
|
|
387
|
+
self.history = (*map(_without_reasoning, messages), _assistant_message(reply, False))
|
|
388
|
+
return Turn(
|
|
389
|
+
text=(reply.content or "") if reply is not None else "",
|
|
390
|
+
tool_calls=calls,
|
|
391
|
+
usage=_usage(response.usage),
|
|
392
|
+
finish_reason=choice.finish_reason if choice is not None else None,
|
|
393
|
+
)
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def nullable_optional(schema: Any) -> Any:
|
|
397
|
+
"""A copy of a JSON schema whose optional object properties also accept null.
|
|
398
|
+
|
|
399
|
+
Only properties with a single ``type`` that are not in ``required`` change,
|
|
400
|
+
at every depth (inside ``properties`` and ``items``).
|
|
401
|
+
"""
|
|
402
|
+
if isinstance(schema, list):
|
|
403
|
+
return [nullable_optional(item) for item in schema]
|
|
404
|
+
if not isinstance(schema, dict):
|
|
405
|
+
return schema
|
|
406
|
+
result = {key: nullable_optional(value) for key, value in schema.items()}
|
|
407
|
+
properties = result.get("properties")
|
|
408
|
+
if isinstance(properties, dict):
|
|
409
|
+
required = set(schema.get("required") or ())
|
|
410
|
+
result["properties"] = {
|
|
411
|
+
name: _with_null(value) if name not in required else value
|
|
412
|
+
for name, value in properties.items()
|
|
413
|
+
}
|
|
414
|
+
return result
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def _with_null(schema: Any) -> Any:
|
|
418
|
+
if isinstance(schema, dict) and isinstance(schema.get("type"), str):
|
|
419
|
+
return {**schema, "type": [schema["type"], "null"]}
|
|
420
|
+
return schema
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def _user_messages(message: str | Sequence[ToolResult]) -> list[dict[str, Any]]:
|
|
424
|
+
if isinstance(message, str):
|
|
425
|
+
return [{"role": "user", "content": message}]
|
|
426
|
+
return [
|
|
427
|
+
{
|
|
428
|
+
"role": "tool",
|
|
429
|
+
"tool_call_id": result.call.id or "",
|
|
430
|
+
"content": json.dumps(result.content, ensure_ascii=False),
|
|
431
|
+
}
|
|
432
|
+
for result in message
|
|
433
|
+
]
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def _assistant_message(reply: Any, with_reasoning: bool) -> dict[str, Any]:
|
|
437
|
+
"""The model's turn for the history: its text, tool calls, and reasoning if kept."""
|
|
438
|
+
message: dict[str, Any] = {"role": "assistant", "content": reply.content or ""}
|
|
439
|
+
extra = getattr(reply, "model_extra", None) or {}
|
|
440
|
+
reasoning = extra.get("reasoning") if with_reasoning else None
|
|
441
|
+
if isinstance(reasoning, str) and reasoning:
|
|
442
|
+
message["reasoning"] = reasoning
|
|
443
|
+
calls = [
|
|
444
|
+
{
|
|
445
|
+
"id": call.id,
|
|
446
|
+
"type": "function",
|
|
447
|
+
"function": {"name": call.function.name, "arguments": call.function.arguments},
|
|
448
|
+
}
|
|
449
|
+
for call in reply.tool_calls or ()
|
|
450
|
+
if getattr(call, "type", None) == "function"
|
|
451
|
+
]
|
|
452
|
+
if calls:
|
|
453
|
+
message["tool_calls"] = calls
|
|
454
|
+
return message
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def _without_reasoning(message: dict[str, Any]) -> dict[str, Any]:
|
|
458
|
+
return {key: value for key, value in message.items() if key != "reasoning"}
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def _tool_calls(reply: Any) -> tuple[ToolCall, ...]:
|
|
462
|
+
if reply is None:
|
|
463
|
+
return ()
|
|
464
|
+
calls = []
|
|
465
|
+
for call in reply.tool_calls or ():
|
|
466
|
+
if getattr(call, "type", None) != "function":
|
|
467
|
+
# A custom (free-text) tool call: StackDoctor offers none.
|
|
468
|
+
name = str(getattr(getattr(call, "custom", None), "name", "") or "")
|
|
469
|
+
calls.append(ToolCall(name, {}, id=call.id, error="the call is not a function call"))
|
|
470
|
+
continue
|
|
471
|
+
arguments, error = _arguments(call.function.arguments)
|
|
472
|
+
calls.append(ToolCall(call.function.name, arguments, id=call.id, error=error))
|
|
473
|
+
return tuple(calls)
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def _arguments(raw: str | None) -> tuple[dict[str, Any], str | None]:
|
|
477
|
+
if not raw:
|
|
478
|
+
return {}, None
|
|
479
|
+
try:
|
|
480
|
+
value = json.loads(raw)
|
|
481
|
+
except ValueError:
|
|
482
|
+
return {}, "the arguments are not valid JSON"
|
|
483
|
+
if not isinstance(value, dict):
|
|
484
|
+
return {}, "the arguments are not a JSON object"
|
|
485
|
+
return value, None
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def _usage(usage: Any) -> Usage:
|
|
489
|
+
if usage is None:
|
|
490
|
+
return Usage()
|
|
491
|
+
details = usage.completion_tokens_details
|
|
492
|
+
reasoning = (details.reasoning_tokens or 0) if details is not None else 0
|
|
493
|
+
completion = usage.completion_tokens or 0
|
|
494
|
+
# completion_tokens already includes the reasoning tokens.
|
|
495
|
+
return Usage(
|
|
496
|
+
input_tokens=usage.prompt_tokens or 0,
|
|
497
|
+
output_tokens=max(completion - reasoning, 0),
|
|
498
|
+
thinking_tokens=reasoning,
|
|
499
|
+
)
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def _provider_error(title: str, error: openai.APIStatusError) -> ProviderError:
|
|
503
|
+
status = error.status_code
|
|
504
|
+
body = error.body if isinstance(error.body, dict) else {}
|
|
505
|
+
detail = body.get("error", body)
|
|
506
|
+
detail = detail if isinstance(detail, dict) else {}
|
|
507
|
+
text = _without_organization(str(detail.get("message") or error.message or "no message"))
|
|
508
|
+
kind: ErrorKind
|
|
509
|
+
if status == 400 and ("failed_generation" in detail or detail.get("code") == "tool_use_failed"):
|
|
510
|
+
# The model produced a tool call the server could not parse. The
|
|
511
|
+
# failed generation itself is not repeated in the message.
|
|
512
|
+
kind = "malformed_output"
|
|
513
|
+
elif status == 413 or (status == 429 and "request too large" in text.lower()):
|
|
514
|
+
# Groq sends a request whose expected output is above the model's
|
|
515
|
+
# output tokens per minute as a 429: waiting would not help.
|
|
516
|
+
kind = "too_large"
|
|
517
|
+
elif status == 429 and "per day" in text.lower():
|
|
518
|
+
kind = "exhausted"
|
|
519
|
+
elif status in (408, 409, 429, 498) or status >= 500:
|
|
520
|
+
kind = "transient"
|
|
521
|
+
else:
|
|
522
|
+
kind = "fatal"
|
|
523
|
+
message = f"{title} API error {status}: {text[:MAX_ERROR_MESSAGE]}"
|
|
524
|
+
return ProviderError(message, kind=kind, status=status, retry_after=_retry_after(error))
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def _without_organization(text: str) -> str:
|
|
528
|
+
"""The message without the account's organization ID (Groq names it)."""
|
|
529
|
+
return _ORGANIZATION.sub("", text)
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def _retry_after(error: openai.APIStatusError) -> float | None:
|
|
533
|
+
value = error.response.headers.get("retry-after")
|
|
534
|
+
if value:
|
|
535
|
+
with contextlib.suppress(ValueError):
|
|
536
|
+
return float(value)
|
|
537
|
+
return None
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Published model prices, each with its source and the day it was checked.
|
|
2
|
+
|
|
3
|
+
Prices are USD per million tokens on the provider's standard (paid) tier.
|
|
4
|
+
Thinking tokens are billed at the output price by every provider here. A
|
|
5
|
+
free tier costs nothing, but StackDoctor always estimates the paid price so
|
|
6
|
+
the cost cap means the same thing on every tier.
|
|
7
|
+
|
|
8
|
+
Each model lists one or more `PriceEntry` items, in the order they take
|
|
9
|
+
effect, so a published price change can be recorded ahead of time.
|
|
10
|
+
|
|
11
|
+
Prices change: re-check the sources when updating this table, and update
|
|
12
|
+
``checked`` with them.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from datetime import UTC, date, datetime
|
|
17
|
+
|
|
18
|
+
from stackdoctor.agent.providers.base import Price
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class PriceEntry:
|
|
23
|
+
"""A price that applies from ``since`` (UTC), as published at ``source``."""
|
|
24
|
+
|
|
25
|
+
since: date
|
|
26
|
+
price: Price
|
|
27
|
+
source: str
|
|
28
|
+
checked: date
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
GEMINI_PRICING_URL = "https://aistudio.google.com/docs/pricing"
|
|
32
|
+
_GEMINI_CHECKED = date(2026, 11, 28)
|
|
33
|
+
ANTHROPIC_PRICING_URL = "https://platform.claude.com/docs/en/about-claude/pricing"
|
|
34
|
+
_ANTHROPIC_CHECKED = date(2026, 11, 28)
|
|
35
|
+
|
|
36
|
+
# (provider, model) -> price entries, oldest first.
|
|
37
|
+
PRICES: dict[tuple[str, str], tuple[PriceEntry, ...]] = {
|
|
38
|
+
("gemini", "gemini-3.8-flash"): (
|
|
39
|
+
PriceEntry(date.min, Price(0.75, 3.75), GEMINI_PRICING_URL, _GEMINI_CHECKED),
|
|
40
|
+
PriceEntry(date(2027, 1, 1), Price(1.50, 7.50), GEMINI_PRICING_URL, _GEMINI_CHECKED),
|
|
41
|
+
),
|
|
42
|
+
("gemini", "gemini-3.5-flash-lite"): (
|
|
43
|
+
PriceEntry(date.min, Price(0.30, 2.50), GEMINI_PRICING_URL, _GEMINI_CHECKED),
|
|
44
|
+
),
|
|
45
|
+
# Base input and output prices. Claude Haiku 5.5 costs more for a prompt
|
|
46
|
+
# over 100,000 tokens ($0.50 / $2.50); StackDoctor's requests stay far
|
|
47
|
+
# below that.
|
|
48
|
+
("anthropic", "claude-haiku-5-5"): (
|
|
49
|
+
PriceEntry(date.min, Price(0.10, 0.50), ANTHROPIC_PRICING_URL, _ANTHROPIC_CHECKED),
|
|
50
|
+
),
|
|
51
|
+
("anthropic", "claude-sonnet-5-5"): (
|
|
52
|
+
PriceEntry(date.min, Price(2.00, 10.00), ANTHROPIC_PRICING_URL, _ANTHROPIC_CHECKED),
|
|
53
|
+
),
|
|
54
|
+
("anthropic", "claude-opus-5-5"): (
|
|
55
|
+
PriceEntry(date.min, Price(4.00, 20.00), ANTHROPIC_PRICING_URL, _ANTHROPIC_CHECKED),
|
|
56
|
+
),
|
|
57
|
+
# Groq lists each price on the model's own page.
|
|
58
|
+
("groq", "openai/gpt-oss-120b"): (
|
|
59
|
+
PriceEntry(
|
|
60
|
+
date.min,
|
|
61
|
+
Price(0.15, 0.60),
|
|
62
|
+
"https://console.groq.com/docs/model/openai/gpt-oss-120b",
|
|
63
|
+
date(2026, 11, 28),
|
|
64
|
+
),
|
|
65
|
+
),
|
|
66
|
+
("groq", "qwen/qwen3.8-27b"): (
|
|
67
|
+
PriceEntry(
|
|
68
|
+
date.min,
|
|
69
|
+
Price(0.80, 4.00),
|
|
70
|
+
"https://console.groq.com/docs/model/qwen/qwen3.8-27b",
|
|
71
|
+
date(2026, 11, 28),
|
|
72
|
+
),
|
|
73
|
+
),
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def price_entry(provider: str, model: str, today: date | None = None) -> PriceEntry | None:
|
|
78
|
+
"""The entry that applies to ``model`` on ``today`` (UTC), or None if unknown."""
|
|
79
|
+
day = today or datetime.now(UTC).date()
|
|
80
|
+
current = None
|
|
81
|
+
for entry in PRICES.get((provider, model), ()):
|
|
82
|
+
if entry.since <= day:
|
|
83
|
+
current = entry
|
|
84
|
+
return current
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def price_for(provider: str, model: str, today: date | None = None) -> Price | None:
|
|
88
|
+
"""The published price of ``model`` on ``today`` (UTC), or None if unknown."""
|
|
89
|
+
entry = price_entry(provider, model, today)
|
|
90
|
+
return entry.price if entry is not None else None
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""StackDoctor's benchmark (M6): scenarios with answer keys, scoring, and a runner.
|
|
2
|
+
|
|
3
|
+
Not part of the ``stackdoctor`` command. Run it from a clone:
|
|
4
|
+
|
|
5
|
+
uv run python -m stackdoctor.benchmark --help
|
|
6
|
+
|
|
7
|
+
The scenarios are Compose fixtures under ``tests/fixtures/compose``, each with
|
|
8
|
+
an ``answer.json``. Scoring is deterministic: an answer is compared with the
|
|
9
|
+
answer key's services and config paths, never judged by another model. See
|
|
10
|
+
docs/benchmark.md.
|
|
11
|
+
"""
|