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,285 @@
|
|
|
1
|
+
"""Claude, through Anthropic's official anthropic SDK (the Messages API).
|
|
2
|
+
|
|
3
|
+
Only this module imports the SDK, and only `create_provider("anthropic")`
|
|
4
|
+
imports this module. (It is not called ``anthropic.py`` so that it never
|
|
5
|
+
shadows the SDK.)
|
|
6
|
+
|
|
7
|
+
Choices worth knowing:
|
|
8
|
+
|
|
9
|
+
- **API key and endpoint.** The key is read only from ``ANTHROPIC_API_KEY``
|
|
10
|
+
and passed to the client together with an explicit base URL, so neither
|
|
11
|
+
``ANTHROPIC_BASE_URL`` nor another credential the SDK could find on its
|
|
12
|
+
own (an auth token, a stored profile) changes where the data goes or
|
|
13
|
+
which account pays.
|
|
14
|
+
- **History.** The model's content blocks are sent back exactly as returned,
|
|
15
|
+
thinking blocks included: the API requires that.
|
|
16
|
+
- **Retries.** The SDK's own retries are disabled (``max_retries=0``); the
|
|
17
|
+
agent loop retries 429, 529 (overloaded) and 5xx itself.
|
|
18
|
+
- **Thinking.** Adaptive thinking, with ``--thinking-level`` as the effort.
|
|
19
|
+
``output_tokens`` includes the thinking tokens; the response's breakdown
|
|
20
|
+
splits them out.
|
|
21
|
+
- **No forced tool calls.** Current Claude models reject a forced
|
|
22
|
+
``tool_choice`` (or do not combine it with thinking), so the loop's
|
|
23
|
+
instruction to call ``submit_diagnosis`` is the only steer, and the loop
|
|
24
|
+
checks what the model did.
|
|
25
|
+
- **Refusals.** A ``refusal`` stop ends the run with that reason. It is not
|
|
26
|
+
retried with another model.
|
|
27
|
+
- **No server-side fallbacks.** The API can switch to another model on a
|
|
28
|
+
refusal; StackDoctor does not enable that, because the run report must
|
|
29
|
+
name the model that produced the answer.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
import contextlib
|
|
33
|
+
import json
|
|
34
|
+
from collections.abc import Mapping, Sequence
|
|
35
|
+
from dataclasses import dataclass, field
|
|
36
|
+
from typing import Any
|
|
37
|
+
|
|
38
|
+
import anthropic
|
|
39
|
+
from anthropic import AsyncAnthropic
|
|
40
|
+
|
|
41
|
+
from stackdoctor.agent.providers import ANTHROPIC, THINKING_LEVELS, find_key, key_names
|
|
42
|
+
from stackdoctor.agent.providers.base import (
|
|
43
|
+
ErrorKind,
|
|
44
|
+
Price,
|
|
45
|
+
ProviderError,
|
|
46
|
+
ProviderUnavailableError,
|
|
47
|
+
ToolCall,
|
|
48
|
+
ToolResult,
|
|
49
|
+
ToolSpec,
|
|
50
|
+
Turn,
|
|
51
|
+
Usage,
|
|
52
|
+
)
|
|
53
|
+
from stackdoctor.agent.providers.prices import price_for
|
|
54
|
+
|
|
55
|
+
BASE_URL = "https://api.anthropic.com"
|
|
56
|
+
# Seconds allowed for one model call. The loop's wall-clock limit bounds the run.
|
|
57
|
+
REQUEST_TIMEOUT_SECONDS = 120.0
|
|
58
|
+
# Room for thinking plus a full submission. Non-streaming requests stay well
|
|
59
|
+
# within the SDK's timeout at this size.
|
|
60
|
+
MAX_OUTPUT_TOKENS = 16_000
|
|
61
|
+
# Longest provider error message kept, in characters.
|
|
62
|
+
MAX_ERROR_MESSAGE = 300
|
|
63
|
+
|
|
64
|
+
# Out of credit or over a spend limit: waiting will not help within the run.
|
|
65
|
+
_EXHAUSTED_ERRORS: tuple[type[anthropic.APIStatusError], ...] = (
|
|
66
|
+
anthropic.EnforcedSpendLimitReachedError,
|
|
67
|
+
anthropic.ContractSpendLimitReachedError,
|
|
68
|
+
anthropic.PaymentRequiredError,
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class ClaudeProvider:
|
|
73
|
+
"""`LLMProvider` for Claude models."""
|
|
74
|
+
|
|
75
|
+
name = ANTHROPIC.name
|
|
76
|
+
can_force_tool = False
|
|
77
|
+
max_request_tokens = None
|
|
78
|
+
|
|
79
|
+
def __init__(
|
|
80
|
+
self,
|
|
81
|
+
*,
|
|
82
|
+
model: str,
|
|
83
|
+
thinking_level: str,
|
|
84
|
+
price: Price | None = None,
|
|
85
|
+
client: Any = None,
|
|
86
|
+
request_timeout: float = REQUEST_TIMEOUT_SECONDS,
|
|
87
|
+
max_output_tokens: int | None = None,
|
|
88
|
+
) -> None:
|
|
89
|
+
"""Create the provider.
|
|
90
|
+
|
|
91
|
+
Raises:
|
|
92
|
+
ProviderUnavailableError: if no client is given and the API key
|
|
93
|
+
is not set.
|
|
94
|
+
ValueError: if the thinking level is not supported.
|
|
95
|
+
"""
|
|
96
|
+
if thinking_level not in THINKING_LEVELS:
|
|
97
|
+
raise ValueError(f"thinking_level must be one of {', '.join(THINKING_LEVELS)}")
|
|
98
|
+
if max_output_tokens is not None and max_output_tokens < 1:
|
|
99
|
+
raise ValueError("max_output_tokens must be at least 1")
|
|
100
|
+
self._model = model
|
|
101
|
+
self._thinking_level = thinking_level
|
|
102
|
+
self._price = price
|
|
103
|
+
self._max_output_tokens = max_output_tokens
|
|
104
|
+
self._client = client if client is not None else _default_client(request_timeout)
|
|
105
|
+
|
|
106
|
+
@property
|
|
107
|
+
def model(self) -> str:
|
|
108
|
+
return self._model
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
def settings(self) -> Mapping[str, str]:
|
|
112
|
+
settings = {"effort": self._thinking_level}
|
|
113
|
+
if self._max_output_tokens is not None:
|
|
114
|
+
settings["max_output_tokens"] = str(self._max_output_tokens)
|
|
115
|
+
return settings
|
|
116
|
+
|
|
117
|
+
def price(self) -> Price | None:
|
|
118
|
+
return self._price or price_for(self.name, self._model)
|
|
119
|
+
|
|
120
|
+
def start(self, system: str, tools: Sequence[ToolSpec]) -> "ClaudeSession":
|
|
121
|
+
return ClaudeSession(
|
|
122
|
+
client=self._client,
|
|
123
|
+
model=self._model,
|
|
124
|
+
system=system,
|
|
125
|
+
tools=[
|
|
126
|
+
{
|
|
127
|
+
"name": tool.name,
|
|
128
|
+
"description": tool.description,
|
|
129
|
+
"input_schema": dict(tool.parameters),
|
|
130
|
+
}
|
|
131
|
+
for tool in tools
|
|
132
|
+
],
|
|
133
|
+
effort=self._thinking_level,
|
|
134
|
+
# The Messages API requires max_tokens: a lower cap replaces the
|
|
135
|
+
# default, never a higher one. Thinking counts toward it.
|
|
136
|
+
max_tokens=min(self._max_output_tokens or MAX_OUTPUT_TOKENS, MAX_OUTPUT_TOKENS),
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@dataclass
|
|
141
|
+
class ClaudeSession:
|
|
142
|
+
"""One conversation. ``history`` holds Messages API messages."""
|
|
143
|
+
|
|
144
|
+
client: Any
|
|
145
|
+
model: str
|
|
146
|
+
system: str
|
|
147
|
+
tools: list[dict[str, Any]]
|
|
148
|
+
effort: str
|
|
149
|
+
max_tokens: int = MAX_OUTPUT_TOKENS
|
|
150
|
+
history: tuple[dict[str, Any], ...] = field(default=())
|
|
151
|
+
|
|
152
|
+
def request(self, messages: Sequence[dict[str, Any]]) -> dict[str, Any]:
|
|
153
|
+
"""The arguments of one ``messages.create`` call (``tool_choice`` stays auto)."""
|
|
154
|
+
return {
|
|
155
|
+
"model": self.model,
|
|
156
|
+
"max_tokens": self.max_tokens,
|
|
157
|
+
"system": self.system,
|
|
158
|
+
"messages": list(messages),
|
|
159
|
+
"tools": self.tools,
|
|
160
|
+
"thinking": {"type": "adaptive"},
|
|
161
|
+
"output_config": {"effort": self.effort},
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async def send(
|
|
165
|
+
self, message: str | Sequence[ToolResult], *, force_tool: str | None = None
|
|
166
|
+
) -> Turn:
|
|
167
|
+
# force_tool cannot be enforced (see the module docstring); the
|
|
168
|
+
# loop's message already names the tool.
|
|
169
|
+
messages = (*self.history, _user_message(message))
|
|
170
|
+
try:
|
|
171
|
+
response = await self.client.messages.create(**self.request(messages))
|
|
172
|
+
except anthropic.APIStatusError as error:
|
|
173
|
+
raise _provider_error(error) from None
|
|
174
|
+
except anthropic.APIConnectionError as error:
|
|
175
|
+
# Timeouts and connection failures: worth retrying.
|
|
176
|
+
raise ProviderError(
|
|
177
|
+
f"Claude request failed: {type(error).__name__}", retryable=True
|
|
178
|
+
) from None
|
|
179
|
+
|
|
180
|
+
if response.stop_reason == "refusal":
|
|
181
|
+
details = getattr(response, "stop_details", None)
|
|
182
|
+
category = getattr(details, "category", None)
|
|
183
|
+
raise ProviderError(
|
|
184
|
+
"Claude declined the request (stop reason: refusal"
|
|
185
|
+
+ (f", category: {category}" if category else "")
|
|
186
|
+
+ ").",
|
|
187
|
+
kind="fatal",
|
|
188
|
+
)
|
|
189
|
+
# Only after success, so a failed call can be sent again unchanged.
|
|
190
|
+
# The content blocks are kept as returned (thinking blocks included).
|
|
191
|
+
self.history = (*messages, {"role": "assistant", "content": response.content})
|
|
192
|
+
return Turn(
|
|
193
|
+
text="".join(block.text for block in response.content if block.type == "text"),
|
|
194
|
+
tool_calls=tuple(
|
|
195
|
+
_tool_call(block) for block in response.content if block.type == "tool_use"
|
|
196
|
+
),
|
|
197
|
+
usage=_usage(response.usage),
|
|
198
|
+
finish_reason=response.stop_reason,
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _default_client(request_timeout: float) -> AsyncAnthropic:
|
|
203
|
+
api_key = find_key(ANTHROPIC.key_variables)
|
|
204
|
+
if not api_key:
|
|
205
|
+
raise ProviderUnavailableError(
|
|
206
|
+
f"Set {key_names(ANTHROPIC.key_variables)} to use the Anthropic provider. "
|
|
207
|
+
"Create a key at https://platform.claude.com/settings/keys"
|
|
208
|
+
)
|
|
209
|
+
return AsyncAnthropic(
|
|
210
|
+
api_key=api_key,
|
|
211
|
+
base_url=BASE_URL,
|
|
212
|
+
max_retries=0,
|
|
213
|
+
timeout=request_timeout,
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _user_message(message: str | Sequence[ToolResult]) -> dict[str, Any]:
|
|
218
|
+
if isinstance(message, str):
|
|
219
|
+
return {"role": "user", "content": message}
|
|
220
|
+
return {
|
|
221
|
+
"role": "user",
|
|
222
|
+
"content": [
|
|
223
|
+
{
|
|
224
|
+
"type": "tool_result",
|
|
225
|
+
"tool_use_id": result.call.id or "",
|
|
226
|
+
"content": json.dumps(result.content, ensure_ascii=False),
|
|
227
|
+
}
|
|
228
|
+
for result in message
|
|
229
|
+
],
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _tool_call(block: Any) -> ToolCall:
|
|
234
|
+
arguments = block.input
|
|
235
|
+
if not isinstance(arguments, dict):
|
|
236
|
+
return ToolCall(block.name, {}, id=block.id, error="the arguments are not a JSON object")
|
|
237
|
+
return ToolCall(block.name, arguments, id=block.id)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _usage(usage: Any) -> Usage:
|
|
241
|
+
if usage is None:
|
|
242
|
+
return Usage()
|
|
243
|
+
details = getattr(usage, "output_tokens_details", None)
|
|
244
|
+
thinking = (details.thinking_tokens or 0) if details is not None else 0
|
|
245
|
+
output = usage.output_tokens or 0
|
|
246
|
+
# Cache reads and writes are input too (StackDoctor sets no cache breakpoints).
|
|
247
|
+
prompt = (
|
|
248
|
+
(usage.input_tokens or 0)
|
|
249
|
+
+ (usage.cache_read_input_tokens or 0)
|
|
250
|
+
+ (usage.cache_creation_input_tokens or 0)
|
|
251
|
+
)
|
|
252
|
+
# output_tokens includes the thinking tokens.
|
|
253
|
+
return Usage(
|
|
254
|
+
input_tokens=prompt,
|
|
255
|
+
output_tokens=max(output - thinking, 0),
|
|
256
|
+
thinking_tokens=min(thinking, output),
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _provider_error(error: anthropic.APIStatusError) -> ProviderError:
|
|
261
|
+
status = error.status_code
|
|
262
|
+
body = error.body if isinstance(error.body, dict) else {}
|
|
263
|
+
detail = body.get("error", body)
|
|
264
|
+
detail = detail if isinstance(detail, dict) else {}
|
|
265
|
+
text = str(detail.get("message") or error.message or "no message")
|
|
266
|
+
kind: ErrorKind
|
|
267
|
+
if isinstance(error, _EXHAUSTED_ERRORS):
|
|
268
|
+
kind = "exhausted"
|
|
269
|
+
elif status == 413:
|
|
270
|
+
kind = "too_large"
|
|
271
|
+
elif status in (408, 409, 429) or status >= 500:
|
|
272
|
+
# 529 is "overloaded".
|
|
273
|
+
kind = "transient"
|
|
274
|
+
else:
|
|
275
|
+
kind = "fatal"
|
|
276
|
+
message = f"Anthropic API error {status}: {text[:MAX_ERROR_MESSAGE]}"
|
|
277
|
+
return ProviderError(message, kind=kind, status=status, retry_after=_retry_after(error))
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _retry_after(error: anthropic.APIStatusError) -> float | None:
|
|
281
|
+
value = error.response.headers.get("retry-after")
|
|
282
|
+
if value:
|
|
283
|
+
with contextlib.suppress(ValueError):
|
|
284
|
+
return float(value)
|
|
285
|
+
return None
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
"""Gemini, through Google's official google-genai SDK (the generate_content API).
|
|
2
|
+
|
|
3
|
+
Only this module imports the SDK, and only `create_provider("gemini")`
|
|
4
|
+
imports this module.
|
|
5
|
+
|
|
6
|
+
Choices worth knowing:
|
|
7
|
+
|
|
8
|
+
- **API key.** Read only from ``STACKDOCTOR_GEMINI_API_KEY`` (never
|
|
9
|
+
``GEMINI_API_KEY``) and passed to the client explicitly, so the SDK's own
|
|
10
|
+
``GEMINI_API_KEY``/``GOOGLE_API_KEY`` lookup is never used. It is not
|
|
11
|
+
stored on the provider, logged or put in any output. The client is pinned
|
|
12
|
+
to the Gemini Developer API (``enterprise=False``), so an environment
|
|
13
|
+
variable cannot switch it to another backend.
|
|
14
|
+
- **History.** The model's turns are appended to the history exactly as
|
|
15
|
+
returned. Gemini 3 attaches thought signatures to function calls and rejects
|
|
16
|
+
a request whose history lost them.
|
|
17
|
+
- **Retries.** The SDK's own retries are disabled (``attempts=1``); the agent
|
|
18
|
+
loop retries 429 and 5xx itself, so the retry count stays bounded and
|
|
19
|
+
visible.
|
|
20
|
+
- **Thinking.** A low thinking level by default. Thinking tokens are reported
|
|
21
|
+
separately and billed as output.
|
|
22
|
+
- **Function calling.** Automatic function calling is disabled: the loop runs
|
|
23
|
+
every tool call itself. A forced call uses mode ``ANY`` with one allowed name.
|
|
24
|
+
- **Network errors** (timeouts, connection failures) are retryable, like 429
|
|
25
|
+
and 5xx responses.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
import contextlib
|
|
29
|
+
import re
|
|
30
|
+
from collections.abc import Mapping, Sequence
|
|
31
|
+
from dataclasses import dataclass
|
|
32
|
+
from typing import Any
|
|
33
|
+
|
|
34
|
+
from google import genai
|
|
35
|
+
from google.genai import errors, types
|
|
36
|
+
|
|
37
|
+
from stackdoctor.agent.providers import (
|
|
38
|
+
DEFAULT_THINKING_LEVEL,
|
|
39
|
+
GEMINI_DEFAULT_MODEL,
|
|
40
|
+
GEMINI_KEY_VARIABLES,
|
|
41
|
+
THINKING_LEVELS,
|
|
42
|
+
find_key,
|
|
43
|
+
key_names,
|
|
44
|
+
)
|
|
45
|
+
from stackdoctor.agent.providers.base import (
|
|
46
|
+
Price,
|
|
47
|
+
ProviderError,
|
|
48
|
+
ProviderUnavailableError,
|
|
49
|
+
ToolCall,
|
|
50
|
+
ToolResult,
|
|
51
|
+
ToolSpec,
|
|
52
|
+
Turn,
|
|
53
|
+
Usage,
|
|
54
|
+
)
|
|
55
|
+
from stackdoctor.agent.providers.prices import price_for
|
|
56
|
+
|
|
57
|
+
# Seconds allowed for one model call. The loop's wall-clock limit bounds the run.
|
|
58
|
+
REQUEST_TIMEOUT_SECONDS = 60.0
|
|
59
|
+
|
|
60
|
+
_RETRY_DELAY = re.compile(r"^(\d+(?:\.\d+)?)s$")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class GeminiProvider:
|
|
64
|
+
"""`LLMProvider` for Gemini models."""
|
|
65
|
+
|
|
66
|
+
name = "gemini"
|
|
67
|
+
can_force_tool = True
|
|
68
|
+
max_request_tokens = None
|
|
69
|
+
|
|
70
|
+
def __init__(
|
|
71
|
+
self,
|
|
72
|
+
*,
|
|
73
|
+
model: str = GEMINI_DEFAULT_MODEL,
|
|
74
|
+
thinking_level: str = DEFAULT_THINKING_LEVEL,
|
|
75
|
+
client: Any = None,
|
|
76
|
+
price: Price | None = None,
|
|
77
|
+
request_timeout: float = REQUEST_TIMEOUT_SECONDS,
|
|
78
|
+
max_output_tokens: int | None = None,
|
|
79
|
+
) -> None:
|
|
80
|
+
"""Create the provider.
|
|
81
|
+
|
|
82
|
+
Args:
|
|
83
|
+
model: Gemini model ID.
|
|
84
|
+
thinking_level: "low", "medium" or "high".
|
|
85
|
+
client: A `genai.Client` (or a stand-in, in tests). By default one
|
|
86
|
+
is created with the key from ``STACKDOCTOR_GEMINI_API_KEY``.
|
|
87
|
+
price: Overrides the published price, for models not in
|
|
88
|
+
`stackdoctor.agent.providers.prices.PRICES`.
|
|
89
|
+
request_timeout: Seconds allowed for one model call.
|
|
90
|
+
max_output_tokens: Sent as ``max_output_tokens``; None sends no cap.
|
|
91
|
+
|
|
92
|
+
Raises:
|
|
93
|
+
ProviderUnavailableError: if no client is given and the API key is
|
|
94
|
+
not set.
|
|
95
|
+
ValueError: if the thinking level is not supported.
|
|
96
|
+
"""
|
|
97
|
+
if thinking_level not in THINKING_LEVELS:
|
|
98
|
+
raise ValueError(f"thinking_level must be one of {', '.join(THINKING_LEVELS)}")
|
|
99
|
+
if max_output_tokens is not None and max_output_tokens < 1:
|
|
100
|
+
raise ValueError("max_output_tokens must be at least 1")
|
|
101
|
+
self._model = model
|
|
102
|
+
self._thinking_level = thinking_level
|
|
103
|
+
self._price = price
|
|
104
|
+
self._max_output_tokens = max_output_tokens
|
|
105
|
+
self._client = client if client is not None else _default_client(request_timeout)
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def model(self) -> str:
|
|
109
|
+
return self._model
|
|
110
|
+
|
|
111
|
+
@property
|
|
112
|
+
def settings(self) -> Mapping[str, str]:
|
|
113
|
+
settings = {"thinking_level": self._thinking_level}
|
|
114
|
+
if self._max_output_tokens is not None:
|
|
115
|
+
settings["max_output_tokens"] = str(self._max_output_tokens)
|
|
116
|
+
return settings
|
|
117
|
+
|
|
118
|
+
def price(self) -> Price | None:
|
|
119
|
+
return self._price or price_for(self.name, self._model)
|
|
120
|
+
|
|
121
|
+
def start(self, system: str, tools: Sequence[ToolSpec]) -> "GeminiSession":
|
|
122
|
+
declarations = [
|
|
123
|
+
types.FunctionDeclaration(
|
|
124
|
+
name=tool.name,
|
|
125
|
+
description=tool.description,
|
|
126
|
+
# Gemini rejects an object schema without properties; a tool
|
|
127
|
+
# without arguments has no schema at all.
|
|
128
|
+
parameters_json_schema=dict(tool.parameters)
|
|
129
|
+
if tool.parameters.get("properties")
|
|
130
|
+
else None,
|
|
131
|
+
)
|
|
132
|
+
for tool in tools
|
|
133
|
+
]
|
|
134
|
+
return GeminiSession(
|
|
135
|
+
client=self._client,
|
|
136
|
+
model=self._model,
|
|
137
|
+
system=system,
|
|
138
|
+
tools=types.Tool(function_declarations=declarations),
|
|
139
|
+
thinking_level=types.ThinkingLevel(self._thinking_level.upper()),
|
|
140
|
+
max_output_tokens=self._max_output_tokens,
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
@dataclass
|
|
145
|
+
class GeminiSession:
|
|
146
|
+
"""One conversation. ``history`` is the SDK's own `Content` list."""
|
|
147
|
+
|
|
148
|
+
client: Any
|
|
149
|
+
model: str
|
|
150
|
+
system: str
|
|
151
|
+
tools: types.Tool
|
|
152
|
+
thinking_level: types.ThinkingLevel
|
|
153
|
+
max_output_tokens: int | None = None
|
|
154
|
+
history: tuple[types.Content, ...] = ()
|
|
155
|
+
|
|
156
|
+
def config(self, force_tool: str | None) -> types.GenerateContentConfig:
|
|
157
|
+
"""The request configuration; with ``force_tool``, that tool must be called."""
|
|
158
|
+
tool_config = None
|
|
159
|
+
if force_tool is not None:
|
|
160
|
+
tool_config = types.ToolConfig(
|
|
161
|
+
function_calling_config=types.FunctionCallingConfig(
|
|
162
|
+
mode=types.FunctionCallingConfigMode.ANY,
|
|
163
|
+
allowed_function_names=[force_tool],
|
|
164
|
+
)
|
|
165
|
+
)
|
|
166
|
+
return types.GenerateContentConfig(
|
|
167
|
+
system_instruction=self.system,
|
|
168
|
+
tools=[self.tools],
|
|
169
|
+
tool_config=tool_config,
|
|
170
|
+
automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True),
|
|
171
|
+
thinking_config=types.ThinkingConfig(thinking_level=self.thinking_level),
|
|
172
|
+
max_output_tokens=self.max_output_tokens,
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
async def send(
|
|
176
|
+
self, message: str | Sequence[ToolResult], *, force_tool: str | None = None
|
|
177
|
+
) -> Turn:
|
|
178
|
+
contents = (*self.history, _user_content(message))
|
|
179
|
+
try:
|
|
180
|
+
response = await self.client.aio.models.generate_content(
|
|
181
|
+
model=self.model, contents=list(contents), config=self.config(force_tool)
|
|
182
|
+
)
|
|
183
|
+
except errors.APIError as error:
|
|
184
|
+
raise _provider_error(error) from None
|
|
185
|
+
except Exception as error:
|
|
186
|
+
if not _is_network_error(error):
|
|
187
|
+
raise
|
|
188
|
+
# Timeouts and connection failures: worth retrying.
|
|
189
|
+
raise ProviderError(
|
|
190
|
+
f"Gemini request failed: {type(error).__name__}", retryable=True
|
|
191
|
+
) from None
|
|
192
|
+
|
|
193
|
+
candidate = response.candidates[0] if response.candidates else None
|
|
194
|
+
content = candidate.content if candidate is not None else None
|
|
195
|
+
# Only after success, so a failed call can be retried unchanged. The
|
|
196
|
+
# model's content is kept as returned (thought signatures included).
|
|
197
|
+
self.history = (*contents, content) if content is not None else contents
|
|
198
|
+
return Turn(
|
|
199
|
+
text=_text(content),
|
|
200
|
+
tool_calls=_tool_calls(content),
|
|
201
|
+
usage=_usage(response.usage_metadata),
|
|
202
|
+
finish_reason=_finish_reason(candidate),
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _default_client(request_timeout: float) -> genai.Client:
|
|
207
|
+
api_key = find_key(GEMINI_KEY_VARIABLES)
|
|
208
|
+
if not api_key:
|
|
209
|
+
raise ProviderUnavailableError(
|
|
210
|
+
f"Set {key_names(GEMINI_KEY_VARIABLES)} to use the Gemini provider. Create a key at "
|
|
211
|
+
"https://aistudio.google.com/apikey"
|
|
212
|
+
)
|
|
213
|
+
return genai.Client(
|
|
214
|
+
api_key=api_key,
|
|
215
|
+
enterprise=False,
|
|
216
|
+
http_options=types.HttpOptions(
|
|
217
|
+
timeout=int(request_timeout * 1000), # milliseconds
|
|
218
|
+
retry_options=types.HttpRetryOptions(attempts=1),
|
|
219
|
+
),
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _user_content(message: str | Sequence[ToolResult]) -> types.Content:
|
|
224
|
+
if isinstance(message, str):
|
|
225
|
+
return types.Content(role="user", parts=[types.Part(text=message)])
|
|
226
|
+
return types.Content(
|
|
227
|
+
role="user",
|
|
228
|
+
parts=[
|
|
229
|
+
types.Part(
|
|
230
|
+
function_response=types.FunctionResponse(
|
|
231
|
+
id=result.call.id, name=result.call.name, response=dict(result.content)
|
|
232
|
+
)
|
|
233
|
+
)
|
|
234
|
+
for result in message
|
|
235
|
+
],
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _text(content: types.Content | None) -> str:
|
|
240
|
+
parts = content.parts if content is not None and content.parts else []
|
|
241
|
+
return "".join(part.text for part in parts if part.text and not part.thought)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _tool_calls(content: types.Content | None) -> tuple[ToolCall, ...]:
|
|
245
|
+
parts = content.parts if content is not None and content.parts else []
|
|
246
|
+
return tuple(
|
|
247
|
+
ToolCall(
|
|
248
|
+
name=part.function_call.name or "",
|
|
249
|
+
arguments=dict(part.function_call.args or {}),
|
|
250
|
+
id=part.function_call.id,
|
|
251
|
+
)
|
|
252
|
+
for part in parts
|
|
253
|
+
if part.function_call is not None
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _usage(metadata: types.GenerateContentResponseUsageMetadata | None) -> Usage:
|
|
258
|
+
if metadata is None:
|
|
259
|
+
return Usage()
|
|
260
|
+
return Usage(
|
|
261
|
+
input_tokens=(metadata.prompt_token_count or 0)
|
|
262
|
+
+ (metadata.tool_use_prompt_token_count or 0),
|
|
263
|
+
output_tokens=metadata.candidates_token_count or 0,
|
|
264
|
+
thinking_tokens=metadata.thoughts_token_count or 0,
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _finish_reason(candidate: types.Candidate | None) -> str | None:
|
|
269
|
+
if candidate is None or candidate.finish_reason is None:
|
|
270
|
+
return None
|
|
271
|
+
return str(candidate.finish_reason.value)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
# The SDK's HTTP stack has changed between releases (httpx, httpx2, aiohttp), so
|
|
275
|
+
# its network errors are recognized by class name rather than imported.
|
|
276
|
+
_NETWORK_ERROR_BASES = {"TransportError", "ClientError", "ServerTimeoutError"}
|
|
277
|
+
_NETWORK_ERROR_MODULES = ("httpx", "httpx2", "aiohttp")
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _is_network_error(error: Exception) -> bool:
|
|
281
|
+
if isinstance(error, TimeoutError | ConnectionError):
|
|
282
|
+
return True
|
|
283
|
+
return any(
|
|
284
|
+
cls.__name__ in _NETWORK_ERROR_BASES
|
|
285
|
+
and cls.__module__.split(".")[0] in _NETWORK_ERROR_MODULES
|
|
286
|
+
for cls in type(error).__mro__
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _provider_error(error: errors.APIError) -> ProviderError:
|
|
291
|
+
code = error.code
|
|
292
|
+
retryable = code == 429 or code >= 500
|
|
293
|
+
status = f" {error.status}" if error.status else ""
|
|
294
|
+
message = f"Gemini API error {code}{status}: {error.message or 'no message'}"
|
|
295
|
+
return ProviderError(message, retryable=retryable, status=code, retry_after=_retry_after(error))
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _retry_after(error: errors.APIError) -> float | None:
|
|
299
|
+
"""Seconds to wait, from a Retry-After header or a RetryInfo error detail."""
|
|
300
|
+
headers = getattr(error.response, "headers", None)
|
|
301
|
+
if headers is not None and headers.get("retry-after"):
|
|
302
|
+
with contextlib.suppress(ValueError):
|
|
303
|
+
return float(headers["retry-after"])
|
|
304
|
+
details = (
|
|
305
|
+
error.details.get("error", {}).get("details", []) if isinstance(error.details, dict) else []
|
|
306
|
+
)
|
|
307
|
+
for detail in details if isinstance(details, list) else []:
|
|
308
|
+
if isinstance(detail, dict) and str(detail.get("@type", "")).endswith("RetryInfo"):
|
|
309
|
+
match = _RETRY_DELAY.match(str(detail.get("retryDelay", "")))
|
|
310
|
+
if match:
|
|
311
|
+
return float(match[1])
|
|
312
|
+
return None
|