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
stackdoctor/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""StackDoctor: integration validation and root cause analysis for containerized applications."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import version
|
|
4
|
+
|
|
5
|
+
# The distribution (what is installed, and its name on PyPI) is not called
|
|
6
|
+
# like the import package: "stackdoctor" on PyPI is an unrelated project.
|
|
7
|
+
# Look metadata up by this name only; version("stackdoctor") would fail, or
|
|
8
|
+
# return that other project's version if it happens to be installed too.
|
|
9
|
+
DISTRIBUTION = "stackdoctor-cli"
|
|
10
|
+
|
|
11
|
+
# Single source of truth for the version is `pyproject.toml`; read it from the
|
|
12
|
+
# installed package metadata rather than duplicating it here.
|
|
13
|
+
__version__ = version(DISTRIBUTION)
|
|
14
|
+
|
|
15
|
+
__all__ = ["DISTRIBUTION", "__version__"]
|
stackdoctor/__main__.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Fitting tool results into a provider's request-size limit without losing citations.
|
|
2
|
+
|
|
3
|
+
Some providers accept only small requests (Groq's free tier allows 8K tokens
|
|
4
|
+
per minute, and every request carries the whole conversation). When new tool
|
|
5
|
+
results would push a request over the provider's limit, the loop compacts
|
|
6
|
+
them here before sending.
|
|
7
|
+
|
|
8
|
+
Compaction only shortens long **string values**. Every key, every list item
|
|
9
|
+
and every evidence ID stays, so every path the model could cite still
|
|
10
|
+
exists, and citations resolve against the full evidence the loop keeps
|
|
11
|
+
locally: excerpts in the diagnosis are never shortened.
|
|
12
|
+
|
|
13
|
+
Token counts are estimated from the JSON text: providers tokenize
|
|
14
|
+
differently, so the estimate is deliberately conservative.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
from collections.abc import Sequence
|
|
19
|
+
|
|
20
|
+
from pydantic import JsonValue
|
|
21
|
+
|
|
22
|
+
# Characters per token, on the safe side for JSON-heavy text.
|
|
23
|
+
CHARS_PER_TOKEN = 3.0
|
|
24
|
+
# Longest string kept, tried in order until the results fit.
|
|
25
|
+
STRING_LIMITS = (2000, 800, 300, 120, 48)
|
|
26
|
+
# Values under these keys are identifiers the model cites: never shortened.
|
|
27
|
+
PROTECTED_KEYS = frozenset({"id", "item"})
|
|
28
|
+
|
|
29
|
+
NOTE = (
|
|
30
|
+
"Long text values in this result were shortened to fit the model's request limit. "
|
|
31
|
+
"Every key, list item and evidence ID is kept, so citations still resolve."
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def estimate_tokens(value: object) -> int:
|
|
36
|
+
"""A conservative token estimate for ``value`` as sent (JSON, or the text itself)."""
|
|
37
|
+
text = value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)
|
|
38
|
+
return int(len(text) / CHARS_PER_TOKEN) + 1
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def shorten(value: JsonValue, limit: int, *, key: str | None = None) -> JsonValue:
|
|
42
|
+
"""``value`` with every string longer than ``limit`` cut, except identifiers."""
|
|
43
|
+
if isinstance(value, str):
|
|
44
|
+
if key in PROTECTED_KEYS or len(value) <= limit:
|
|
45
|
+
return value
|
|
46
|
+
return f"{value[:limit]}…[truncated {len(value) - limit} chars]"
|
|
47
|
+
if isinstance(value, dict):
|
|
48
|
+
return {name: shorten(item, limit, key=name) for name, item in value.items()}
|
|
49
|
+
if isinstance(value, list):
|
|
50
|
+
return [shorten(item, limit) for item in value]
|
|
51
|
+
return value
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def fit(results: Sequence[JsonValue], budget_tokens: int) -> list[JsonValue] | None:
|
|
55
|
+
"""The results, shortened just enough to fit ``budget_tokens`` together.
|
|
56
|
+
|
|
57
|
+
Returns them unchanged when they already fit, and None when even the
|
|
58
|
+
shortest strings do not fit.
|
|
59
|
+
"""
|
|
60
|
+
if estimate_tokens(list(results)) <= budget_tokens:
|
|
61
|
+
return list(results)
|
|
62
|
+
for limit in STRING_LIMITS:
|
|
63
|
+
shortened = [shorten(result, limit) for result in results]
|
|
64
|
+
if estimate_tokens(shortened) <= budget_tokens:
|
|
65
|
+
return shortened
|
|
66
|
+
return None
|
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
"""The agent's result: a diagnosis whose claims cite collected evidence.
|
|
2
|
+
|
|
3
|
+
The model proposes a root cause and findings through the `submit_diagnosis`
|
|
4
|
+
tool, citing evidence as ``{item, path}``: an evidence item ID from a tool
|
|
5
|
+
result and a path inside its data. The engine, not the model, resolves each
|
|
6
|
+
citation against the evidence the tools actually returned in this run and
|
|
7
|
+
records the value found there as the excerpt, so a diagnosis cannot quote
|
|
8
|
+
data that was never collected.
|
|
9
|
+
|
|
10
|
+
Claims whose citations do not all resolve are kept, but moved to
|
|
11
|
+
``unsupported`` with the reason, so a reader can see what the model said
|
|
12
|
+
without mistaking it for a supported finding.
|
|
13
|
+
|
|
14
|
+
A resolvable citation shows that the cited data exists and says what the
|
|
15
|
+
excerpt says. It does not prove the diagnosis: claims here are *supported by*
|
|
16
|
+
evidence, not proven.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
from collections.abc import Mapping, Sequence
|
|
21
|
+
from typing import Literal, Self
|
|
22
|
+
|
|
23
|
+
from pydantic import (
|
|
24
|
+
BaseModel,
|
|
25
|
+
ConfigDict,
|
|
26
|
+
Field,
|
|
27
|
+
JsonValue,
|
|
28
|
+
ValidationError,
|
|
29
|
+
field_validator,
|
|
30
|
+
model_validator,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
from stackdoctor.evidence import EvidenceError, format_path, format_value, resolve_path
|
|
34
|
+
from stackdoctor.models import EvidenceItem, EvidenceRef
|
|
35
|
+
|
|
36
|
+
# Version of the `Diagnosis` JSON shape (docs/schema/). Bump it when a field is
|
|
37
|
+
# removed or changes meaning; adding an optional field does not.
|
|
38
|
+
DIAGNOSIS_SCHEMA_VERSION = 1
|
|
39
|
+
|
|
40
|
+
SUBMIT_TOOL = "submit_diagnosis"
|
|
41
|
+
|
|
42
|
+
# Bounds on what the model may submit, so one answer cannot flood the report.
|
|
43
|
+
MAX_TEXT_CHARS = 2_000
|
|
44
|
+
MAX_FINDINGS = 20
|
|
45
|
+
MAX_CITATIONS = 10
|
|
46
|
+
MAX_PATH_SEGMENTS = 12
|
|
47
|
+
# A citation must point at a specific value: a scalar, a list, or an object of
|
|
48
|
+
# scalars (such as one port mapping). Objects that hold further objects (a
|
|
49
|
+
# whole service) and values that render longer than this are rejected with a
|
|
50
|
+
# request to be more specific.
|
|
51
|
+
MAX_EXCERPT_CHARS = 500
|
|
52
|
+
|
|
53
|
+
Status = Literal["diagnosed", "no_problem_found", "unsupported", "incomplete"]
|
|
54
|
+
StopReason = Literal[
|
|
55
|
+
"submitted", # the model submitted an answer that was accepted
|
|
56
|
+
"tool_call_limit", # the tool-call limit was reached and no answer followed
|
|
57
|
+
"timeout", # the wall-clock limit was reached
|
|
58
|
+
"token_budget", # the token budget was used up
|
|
59
|
+
"cost_cap", # the cost cap was reached
|
|
60
|
+
"invalid_output", # the model's answer stayed malformed after one repair
|
|
61
|
+
"provider_error", # the provider failed, after retries where they apply
|
|
62
|
+
"turn_limit", # the model kept talking without calling tools or answering
|
|
63
|
+
"server_error", # StackDoctor's MCP server could not be started or reached
|
|
64
|
+
]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class _Model(BaseModel):
|
|
68
|
+
model_config = ConfigDict(frozen=True, extra="forbid")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class RootCause(_Model):
|
|
72
|
+
"""The most likely root cause, with the evidence that supports it."""
|
|
73
|
+
|
|
74
|
+
summary: str
|
|
75
|
+
evidence: tuple[EvidenceRef, ...] = Field(min_length=1)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class AIFinding(_Model):
|
|
79
|
+
"""One problem the model identified, with the evidence that supports it."""
|
|
80
|
+
|
|
81
|
+
title: str
|
|
82
|
+
explanation: str
|
|
83
|
+
service: str | None = None
|
|
84
|
+
evidence: tuple[EvidenceRef, ...] = Field(min_length=1)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class UnsupportedClaim(_Model):
|
|
88
|
+
"""A claim the model made whose citations did not all resolve."""
|
|
89
|
+
|
|
90
|
+
kind: Literal["root_cause", "finding"]
|
|
91
|
+
title: str
|
|
92
|
+
explanation: str
|
|
93
|
+
problems: tuple[str, ...] = Field(min_length=1)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class Attempt(_Model):
|
|
97
|
+
"""One model's part of a run. A run tries the next model only after a provider failure."""
|
|
98
|
+
|
|
99
|
+
provider: str
|
|
100
|
+
model: str
|
|
101
|
+
settings: dict[str, str] = Field(default_factory=dict)
|
|
102
|
+
model_calls: int = 0
|
|
103
|
+
retries: int = 0
|
|
104
|
+
input_tokens: int = 0
|
|
105
|
+
output_tokens: int = 0
|
|
106
|
+
thinking_tokens: int = 0
|
|
107
|
+
# None when the model's price is not known.
|
|
108
|
+
estimated_cost_usd: float | None = None
|
|
109
|
+
stop_reason: StopReason
|
|
110
|
+
stop_detail: str | None = None
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class RunStats(_Model):
|
|
114
|
+
"""How the run went: model, limits used, and why it stopped.
|
|
115
|
+
|
|
116
|
+
``provider`` and ``model`` name the model that produced the answer (or
|
|
117
|
+
the last one tried). The counters are totals over the whole run;
|
|
118
|
+
``attempts`` lists every model tried, in order, with its own share and
|
|
119
|
+
why it stopped.
|
|
120
|
+
"""
|
|
121
|
+
|
|
122
|
+
provider: str
|
|
123
|
+
model: str
|
|
124
|
+
settings: dict[str, str] = Field(default_factory=dict)
|
|
125
|
+
live: bool = False
|
|
126
|
+
tool_calls: int = 0
|
|
127
|
+
model_calls: int = 0
|
|
128
|
+
retries: int = 0
|
|
129
|
+
repairs: int = 0
|
|
130
|
+
duration_seconds: float = 0.0
|
|
131
|
+
input_tokens: int = 0
|
|
132
|
+
output_tokens: int = 0
|
|
133
|
+
thinking_tokens: int = 0
|
|
134
|
+
# None when the model's price is not known.
|
|
135
|
+
estimated_cost_usd: float | None = None
|
|
136
|
+
stop_reason: StopReason
|
|
137
|
+
# A short, redacted explanation when the run stopped early.
|
|
138
|
+
stop_detail: str | None = None
|
|
139
|
+
attempts: tuple[Attempt, ...] = ()
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class Diagnosis(_Model):
|
|
143
|
+
"""The result of `stackdoctor diagnose`.
|
|
144
|
+
|
|
145
|
+
``status``:
|
|
146
|
+
|
|
147
|
+
- ``diagnosed``: a root cause supported by at least one resolvable citation;
|
|
148
|
+
- ``no_problem_found``: the model reported no problem;
|
|
149
|
+
- ``unsupported``: the model answered, but no root cause is supported by
|
|
150
|
+
evidence;
|
|
151
|
+
- ``incomplete``: the run stopped (a limit, invalid output, a provider
|
|
152
|
+
error) before an answer was accepted.
|
|
153
|
+
|
|
154
|
+
``evidence`` holds every item the claims cite, so a diagnosis can be
|
|
155
|
+
checked on its own (`check_diagnosis`).
|
|
156
|
+
"""
|
|
157
|
+
|
|
158
|
+
schema_version: int = DIAGNOSIS_SCHEMA_VERSION
|
|
159
|
+
project: str | None = None
|
|
160
|
+
status: Status
|
|
161
|
+
root_cause: RootCause | None = None
|
|
162
|
+
findings: tuple[AIFinding, ...] = ()
|
|
163
|
+
unsupported: tuple[UnsupportedClaim, ...] = ()
|
|
164
|
+
suggested_fix: str | None = None
|
|
165
|
+
evidence: tuple[EvidenceItem, ...] = ()
|
|
166
|
+
run: RunStats
|
|
167
|
+
|
|
168
|
+
@model_validator(mode="after")
|
|
169
|
+
def _check(self) -> Self:
|
|
170
|
+
if (self.status == "diagnosed") != (self.root_cause is not None):
|
|
171
|
+
raise ValueError("a root cause is present exactly when the status is diagnosed")
|
|
172
|
+
ids = [item.id for item in self.evidence]
|
|
173
|
+
if len(ids) != len(set(ids)):
|
|
174
|
+
raise ValueError("evidence item IDs must be unique")
|
|
175
|
+
missing = sorted({ref.item for ref in _refs(self)} - set(ids))
|
|
176
|
+
if missing:
|
|
177
|
+
raise ValueError(f"claims cite evidence items not in the diagnosis: {missing}")
|
|
178
|
+
return self
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def check_diagnosis(diagnosis: Diagnosis) -> None:
|
|
182
|
+
"""Resolve every citation in ``diagnosis`` against its own evidence items.
|
|
183
|
+
|
|
184
|
+
Raises:
|
|
185
|
+
EvidenceError: if a citation does not resolve or does not match its
|
|
186
|
+
excerpt.
|
|
187
|
+
"""
|
|
188
|
+
items = {item.id: item for item in diagnosis.evidence}
|
|
189
|
+
for ref in _refs(diagnosis):
|
|
190
|
+
value = resolve_path(items[ref.item].data, ref.path)
|
|
191
|
+
if format_value(value) != ref.excerpt:
|
|
192
|
+
raise EvidenceError(f"evidence {ref.item}:{format_path(ref.path)} does not match")
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def diagnosis_json_schema() -> str:
|
|
196
|
+
"""The JSON Schema of `Diagnosis`, as committed in docs/schema/."""
|
|
197
|
+
schema = Diagnosis.model_json_schema(mode="serialization")
|
|
198
|
+
return json.dumps(schema, indent=2, sort_keys=True) + "\n"
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _refs(diagnosis: Diagnosis) -> list[EvidenceRef]:
|
|
202
|
+
refs = list(diagnosis.root_cause.evidence) if diagnosis.root_cause else []
|
|
203
|
+
return refs + [ref for finding in diagnosis.findings for ref in finding.evidence]
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
# --- The model's submission ----------------------------------------------------
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
class _Submitted(BaseModel):
|
|
210
|
+
# Lenient about extra keys (models add them) but strict about the shape of
|
|
211
|
+
# what is used.
|
|
212
|
+
model_config = ConfigDict(extra="ignore")
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
class SubmittedCitation(_Submitted):
|
|
216
|
+
item: str = Field(min_length=1, max_length=200)
|
|
217
|
+
path: list[str | int] = Field(min_length=1, max_length=MAX_PATH_SEGMENTS)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
class SubmittedRootCause(_Submitted):
|
|
221
|
+
summary: str = Field(min_length=1, max_length=MAX_TEXT_CHARS)
|
|
222
|
+
evidence: list[SubmittedCitation] = Field(min_length=1, max_length=MAX_CITATIONS)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
class SubmittedFinding(_Submitted):
|
|
226
|
+
title: str = Field(min_length=1, max_length=200)
|
|
227
|
+
explanation: str = Field(min_length=1, max_length=MAX_TEXT_CHARS)
|
|
228
|
+
service: str | None = Field(default=None, max_length=200)
|
|
229
|
+
evidence: list[SubmittedCitation] = Field(min_length=1, max_length=MAX_CITATIONS)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
class Submission(_Submitted):
|
|
233
|
+
"""The arguments of a `submit_diagnosis` call, as the model sent them."""
|
|
234
|
+
|
|
235
|
+
status: Literal["problem_found", "no_problem_found"]
|
|
236
|
+
root_cause: SubmittedRootCause | None = None
|
|
237
|
+
findings: list[SubmittedFinding] = Field(default_factory=list, max_length=MAX_FINDINGS)
|
|
238
|
+
suggested_fix: str | None = Field(default=None, max_length=MAX_TEXT_CHARS)
|
|
239
|
+
|
|
240
|
+
@field_validator("suggested_fix")
|
|
241
|
+
@classmethod
|
|
242
|
+
def _blank_is_none(cls, value: str | None) -> str | None:
|
|
243
|
+
return value if value and value.strip() else None
|
|
244
|
+
|
|
245
|
+
@model_validator(mode="after")
|
|
246
|
+
def _consistent(self) -> Self:
|
|
247
|
+
if self.status == "problem_found" and self.root_cause is None:
|
|
248
|
+
raise ValueError(
|
|
249
|
+
"status problem_found needs a root_cause. Add one, or submit status "
|
|
250
|
+
"no_problem_found with no findings"
|
|
251
|
+
)
|
|
252
|
+
if self.status == "no_problem_found" and (self.root_cause or self.findings):
|
|
253
|
+
raise ValueError(
|
|
254
|
+
"status no_problem_found must not have a root_cause or findings. If you "
|
|
255
|
+
"found a problem, submit status problem_found with a root_cause; if not, "
|
|
256
|
+
'submit "findings": [] and no root_cause'
|
|
257
|
+
)
|
|
258
|
+
return self
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
_CITATION_SCHEMA: dict[str, JsonValue] = {
|
|
262
|
+
"type": "object",
|
|
263
|
+
"description": (
|
|
264
|
+
"Where the evidence is: an evidence item ID from a tool result (the "
|
|
265
|
+
'configuration is item "config") and the path to a specific value inside '
|
|
266
|
+
"that item's data, one key or list index per element."
|
|
267
|
+
),
|
|
268
|
+
"properties": {
|
|
269
|
+
"item": {"type": "string", "description": 'Evidence item ID, for example "config".'},
|
|
270
|
+
"path": {
|
|
271
|
+
"type": "array",
|
|
272
|
+
"items": {"type": "string"},
|
|
273
|
+
"description": (
|
|
274
|
+
'For example ["services", "api", "environment", "DATABASE_URL"]. '
|
|
275
|
+
'List indexes are written as numbers in strings, for example "0".'
|
|
276
|
+
),
|
|
277
|
+
},
|
|
278
|
+
},
|
|
279
|
+
"required": ["item", "path"],
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
SUBMIT_PARAMETERS: dict[str, JsonValue] = {
|
|
283
|
+
"type": "object",
|
|
284
|
+
"properties": {
|
|
285
|
+
"status": {"type": "string", "enum": ["problem_found", "no_problem_found"]},
|
|
286
|
+
"root_cause": {
|
|
287
|
+
"type": "object",
|
|
288
|
+
"description": (
|
|
289
|
+
"The most likely root cause. Required when status is problem_found; "
|
|
290
|
+
"left out when status is no_problem_found."
|
|
291
|
+
),
|
|
292
|
+
"properties": {
|
|
293
|
+
"summary": {"type": "string"},
|
|
294
|
+
"evidence": {"type": "array", "items": _CITATION_SCHEMA},
|
|
295
|
+
},
|
|
296
|
+
"required": ["summary", "evidence"],
|
|
297
|
+
},
|
|
298
|
+
"findings": {
|
|
299
|
+
"type": "array",
|
|
300
|
+
"description": (
|
|
301
|
+
"Every problem found, including the root cause's symptoms. Problems "
|
|
302
|
+
"only, never checks that passed: empty when status is no_problem_found."
|
|
303
|
+
),
|
|
304
|
+
"items": {
|
|
305
|
+
"type": "object",
|
|
306
|
+
"properties": {
|
|
307
|
+
"title": {"type": "string"},
|
|
308
|
+
"explanation": {"type": "string"},
|
|
309
|
+
"service": {"type": "string"},
|
|
310
|
+
"evidence": {"type": "array", "items": _CITATION_SCHEMA},
|
|
311
|
+
},
|
|
312
|
+
"required": ["title", "explanation", "evidence"],
|
|
313
|
+
},
|
|
314
|
+
},
|
|
315
|
+
"suggested_fix": {
|
|
316
|
+
"type": "string",
|
|
317
|
+
"description": (
|
|
318
|
+
"What a person could change to fix it. It is never applied. Left out "
|
|
319
|
+
"when status is no_problem_found."
|
|
320
|
+
),
|
|
321
|
+
},
|
|
322
|
+
},
|
|
323
|
+
"required": ["status", "findings"],
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
SUBMIT_DESCRIPTION = (
|
|
327
|
+
"Submit the final diagnosis. Call this exactly once, at the end. Every root "
|
|
328
|
+
"cause and finding must cite evidence returned by the tools in this conversation."
|
|
329
|
+
)
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def parse_submission(arguments: Mapping[str, JsonValue]) -> Submission | list[str]:
|
|
333
|
+
"""Parse the model's `submit_diagnosis` arguments, or say what is wrong with them."""
|
|
334
|
+
try:
|
|
335
|
+
return Submission.model_validate(dict(arguments))
|
|
336
|
+
except ValidationError as error:
|
|
337
|
+
# Locations and messages only: input values are never echoed.
|
|
338
|
+
return [
|
|
339
|
+
f"{'.'.join(str(part) for part in detail['loc']) or 'arguments'}: {detail['msg']}"
|
|
340
|
+
for detail in error.errors(include_input=False, include_url=False)
|
|
341
|
+
][:10]
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def resolve_citation(
|
|
345
|
+
citation: SubmittedCitation, items: Mapping[str, EvidenceItem]
|
|
346
|
+
) -> EvidenceRef | str:
|
|
347
|
+
"""Resolve one citation against the collected items, or say why it does not resolve.
|
|
348
|
+
|
|
349
|
+
Path segments may arrive as strings even for list indexes ("0"); each one
|
|
350
|
+
is interpreted by the type of the value it indexes, so the result is
|
|
351
|
+
unambiguous.
|
|
352
|
+
"""
|
|
353
|
+
shown = f"{citation.item}:{'.'.join(str(part) for part in citation.path)}"
|
|
354
|
+
item = items.get(citation.item)
|
|
355
|
+
if item is None:
|
|
356
|
+
return f"evidence item {citation.item!r} was not returned by any tool in this run"
|
|
357
|
+
node: JsonValue = item.data
|
|
358
|
+
path: list[str | int] = []
|
|
359
|
+
for segment in citation.path:
|
|
360
|
+
if isinstance(node, dict) and str(segment) in node:
|
|
361
|
+
key: str | int = str(segment)
|
|
362
|
+
node = node[str(segment)]
|
|
363
|
+
elif isinstance(node, list) and (index := _as_index(segment, len(node))) is not None:
|
|
364
|
+
key = index
|
|
365
|
+
node = node[index]
|
|
366
|
+
else:
|
|
367
|
+
return f"evidence {shown} does not resolve"
|
|
368
|
+
path.append(key)
|
|
369
|
+
excerpt = format_value(node)
|
|
370
|
+
nested = isinstance(node, dict) and any(isinstance(v, dict | list) for v in node.values())
|
|
371
|
+
if nested or len(excerpt) > MAX_EXCERPT_CHARS:
|
|
372
|
+
return f"evidence {shown} is too broad; cite a more specific value"
|
|
373
|
+
return EvidenceRef(item=item.id, path=tuple(path), excerpt=excerpt)
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def resolve_citations(
|
|
377
|
+
citations: Sequence[SubmittedCitation], items: Mapping[str, EvidenceItem]
|
|
378
|
+
) -> tuple[list[EvidenceRef], list[str]]:
|
|
379
|
+
"""Resolve every citation; return the resolved references and the problems."""
|
|
380
|
+
refs: list[EvidenceRef] = []
|
|
381
|
+
problems: list[str] = []
|
|
382
|
+
for citation in citations:
|
|
383
|
+
resolved = resolve_citation(citation, items)
|
|
384
|
+
if isinstance(resolved, str):
|
|
385
|
+
problems.append(resolved)
|
|
386
|
+
elif resolved not in refs:
|
|
387
|
+
refs.append(resolved)
|
|
388
|
+
return refs, problems
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def _as_index(segment: str | int, length: int) -> int | None:
|
|
392
|
+
if isinstance(segment, int):
|
|
393
|
+
index = segment
|
|
394
|
+
elif segment.isdigit():
|
|
395
|
+
index = int(segment)
|
|
396
|
+
else:
|
|
397
|
+
return None
|
|
398
|
+
return index if 0 <= index < length else None
|