dagnose 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.
dagnose/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Dagnose: open source AI on-call engineer for Apache Airflow."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ try:
6
+ __version__ = version("dagnose") # single source: [project].version in pyproject.toml
7
+ except PackageNotFoundError: # running from a source tree that was never installed
8
+ __version__ = "0.0.0+unknown"
@@ -0,0 +1,38 @@
1
+ """Diagnosis agent: LLM loop with read-only tools, structured JSON output."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ from dagnose.agent.diagnose import DiagnosisError, diagnose
8
+ from dagnose.agent.provider import LLMProvider, ProviderConfigError, ProviderError
9
+ from dagnose.agent.tools import ToolBox
10
+
11
+ if TYPE_CHECKING:
12
+ from dagnose.config import Settings
13
+
14
+ __all__ = [
15
+ "DiagnosisError",
16
+ "LLMProvider",
17
+ "ProviderConfigError",
18
+ "ProviderError",
19
+ "ToolBox",
20
+ "diagnose",
21
+ "make_provider",
22
+ ]
23
+
24
+
25
+ def make_provider(settings: Settings) -> LLMProvider:
26
+ """Claude on the configured platform: the Claude API, Bedrock, Vertex AI or Foundry.
27
+ The model may also carry the platform, e.g. "bedrock/claude-opus-5-5"."""
28
+ from dagnose.agent.anthropic_provider import AnthropicProvider
29
+ from dagnose.agent.clients import build_client
30
+
31
+ choice = build_client(settings)
32
+ return AnthropicProvider(
33
+ choice.model,
34
+ client=choice.client,
35
+ effort=settings.llm_effort,
36
+ fallbacks=choice.fallbacks,
37
+ name=choice.provider,
38
+ )
@@ -0,0 +1,203 @@
1
+ """Claude via the official Anthropic SDK.
2
+
3
+ - Final answer as structured output (output_config.format, JSON schema) so it always
4
+ parses; tools are strict so their inputs always match their schemas.
5
+ - The conversation is append-only and the assistant content is sent back exactly as
6
+ returned, which keeps thinking blocks valid across turns.
7
+ - Server-side refusal fallback is on by default (fallbacks="default").
8
+ - Prompt caching when tools are on (multi-turn); a one-turn call is not cached.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from collections.abc import Sequence
14
+ from typing import Any
15
+
16
+ import anthropic
17
+
18
+ from dagnose.agent.provider import (
19
+ ProviderConfigError,
20
+ ProviderError,
21
+ StopReason,
22
+ ToolCall,
23
+ ToolResult,
24
+ ToolSpec,
25
+ Turn,
26
+ )
27
+ from dagnose.models import Usage
28
+
29
+ FALLBACK_BETA = "server-side-fallback-2026-07-01"
30
+
31
+ _STOP: dict[str, StopReason] = {
32
+ "end_turn": "done",
33
+ "tool_use": "tool_use",
34
+ "max_tokens": "max_tokens",
35
+ "refusal": "refusal",
36
+ "pause_turn": "continue",
37
+ "stop_sequence": "done",
38
+ }
39
+
40
+
41
+ class AnthropicProvider:
42
+ def __init__(
43
+ self,
44
+ model: str = "claude-opus-5-5",
45
+ *,
46
+ api_key: str | None = None,
47
+ effort: str = "high",
48
+ fallbacks: bool = True,
49
+ max_tokens: int = 16000,
50
+ client: Any = None, # Anthropic or the Bedrock (Mantle), Vertex or Foundry client
51
+ name: str = "anthropic",
52
+ ) -> None:
53
+ self.name = name
54
+ self.model = model
55
+ self.effort = effort
56
+ self.fallbacks = fallbacks
57
+ self.max_tokens = max_tokens
58
+ # No api_key: the SDK resolves ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN or an
59
+ # `ant auth login` profile itself.
60
+ self.client = client or anthropic.Anthropic(api_key=api_key)
61
+
62
+ def start(
63
+ self,
64
+ *,
65
+ system: str,
66
+ prompt: str,
67
+ tools: Sequence[ToolSpec],
68
+ output_schema: dict[str, Any],
69
+ ) -> AnthropicSession:
70
+ return AnthropicSession(self, system, prompt, tools, output_schema)
71
+
72
+ def verify(self) -> int:
73
+ """Check the key and model without generating anything (token counting is free).
74
+ Returns the counted tokens; raises ProviderConfigError / ProviderError."""
75
+ try:
76
+ resp = self.client.messages.count_tokens(
77
+ model=self.model, messages=[{"role": "user", "content": "ping"}]
78
+ )
79
+ except (anthropic.AuthenticationError, anthropic.PermissionDeniedError) as exc:
80
+ raise ProviderConfigError(f"Anthropic rejected the credentials: {exc}") from exc
81
+ except (anthropic.NotFoundError, anthropic.BadRequestError) as exc:
82
+ raise ProviderConfigError(f"Anthropic rejected the model: {exc}") from exc
83
+ except (anthropic.RateLimitError, anthropic.APIConnectionError) as exc:
84
+ raise ProviderError(f"Anthropic unavailable: {exc}") from exc
85
+ except anthropic.APIStatusError as exc:
86
+ raise ProviderError(f"Anthropic error {exc.status_code}: {exc}") from exc
87
+ except TypeError as exc:
88
+ if "authentication method" not in str(exc):
89
+ raise
90
+ raise ProviderConfigError(
91
+ "no Anthropic credentials: set DAGNOSE_LLM_API_KEY or "
92
+ "ANTHROPIC_API_KEY, or run `ant auth login`"
93
+ ) from exc
94
+ return int(resp.input_tokens)
95
+
96
+
97
+ class AnthropicSession:
98
+ def __init__(
99
+ self,
100
+ provider: AnthropicProvider,
101
+ system: str,
102
+ prompt: str,
103
+ tools: Sequence[ToolSpec],
104
+ output_schema: dict[str, Any],
105
+ ) -> None:
106
+ self.p = provider
107
+ self.system = system
108
+ self.tools = [
109
+ {
110
+ "name": t.name,
111
+ "description": t.description,
112
+ "input_schema": t.input_schema,
113
+ "strict": True,
114
+ }
115
+ for t in tools
116
+ ]
117
+ self.output_schema = output_schema
118
+ self.messages: list[dict[str, Any]] = [{"role": "user", "content": prompt}]
119
+ self._started = False
120
+
121
+ def send(self, tool_results: Sequence[ToolResult] = (), note: str | None = None) -> Turn:
122
+ if self._started:
123
+ content: list[dict[str, Any]] = [
124
+ {
125
+ "type": "tool_result",
126
+ "tool_use_id": r.call_id,
127
+ "content": r.content,
128
+ "is_error": r.is_error,
129
+ }
130
+ for r in tool_results
131
+ ]
132
+ if note:
133
+ content.append({"type": "text", "text": note})
134
+ if content:
135
+ self.messages.append({"role": "user", "content": content})
136
+ self._started = True
137
+
138
+ kwargs: dict[str, Any] = {
139
+ "model": self.p.model,
140
+ "max_tokens": self.p.max_tokens,
141
+ "system": self.system,
142
+ "messages": self.messages,
143
+ "output_config": {
144
+ "effort": self.p.effort,
145
+ "format": {"type": "json_schema", "schema": self.output_schema},
146
+ },
147
+ }
148
+ if self.tools:
149
+ kwargs["tools"] = self.tools
150
+ # Cache only when the conversation can have several turns. A one-turn
151
+ # diagnosis would pay the cache-write premium and never read it back.
152
+ kwargs["cache_control"] = {"type": "ephemeral"}
153
+ try:
154
+ if self.p.fallbacks:
155
+ response: Any = self.p.client.beta.messages.create(
156
+ **kwargs, betas=[FALLBACK_BETA], fallbacks="default"
157
+ )
158
+ else:
159
+ response = self.p.client.messages.create(**kwargs)
160
+ except (anthropic.AuthenticationError, anthropic.PermissionDeniedError) as exc:
161
+ raise ProviderConfigError(f"Anthropic rejected the credentials: {exc}") from exc
162
+ except (anthropic.NotFoundError, anthropic.BadRequestError) as exc:
163
+ raise ProviderConfigError(f"Anthropic rejected the request: {exc}") from exc
164
+ except (anthropic.RateLimitError, anthropic.APIConnectionError) as exc:
165
+ raise ProviderError(f"Anthropic unavailable: {exc}") from exc
166
+ except anthropic.APIStatusError as exc:
167
+ raise ProviderError(f"Anthropic error {exc.status_code}: {exc}") from exc
168
+ except anthropic.AnthropicError as exc:
169
+ raise ProviderConfigError(str(exc)) from exc
170
+ except TypeError as exc:
171
+ # The SDK raises a plain TypeError, before any network call, when no API
172
+ # key, auth token or profile can be found.
173
+ if "authentication method" not in str(exc):
174
+ raise
175
+ raise ProviderConfigError(
176
+ "no Anthropic credentials: set DAGNOSE_LLM_API_KEY or "
177
+ "ANTHROPIC_API_KEY, or run `ant auth login`"
178
+ ) from exc
179
+
180
+ # Append exactly what came back (thinking blocks included): append-only history.
181
+ self.messages.append({"role": "assistant", "content": response.content})
182
+
183
+ text = "".join(b.text for b in response.content if getattr(b, "type", "") == "text")
184
+ calls = [
185
+ ToolCall(id=b.id, name=b.name, input=dict(b.input))
186
+ for b in response.content
187
+ if getattr(b, "type", "") == "tool_use"
188
+ ]
189
+ u = response.usage
190
+ details = getattr(response, "stop_details", None)
191
+ return Turn(
192
+ stop=_STOP.get(str(response.stop_reason), "done"),
193
+ text=text,
194
+ tool_calls=calls,
195
+ usage=Usage(
196
+ input_tokens=u.input_tokens or 0,
197
+ output_tokens=u.output_tokens or 0,
198
+ cache_read_input_tokens=getattr(u, "cache_read_input_tokens", 0) or 0,
199
+ cache_creation_input_tokens=getattr(u, "cache_creation_input_tokens", 0) or 0,
200
+ ),
201
+ served_model=getattr(response, "model", None),
202
+ refusal_category=getattr(details, "category", None) if details else None,
203
+ )
@@ -0,0 +1,82 @@
1
+ """Build the Claude client for the configured platform.
2
+
3
+ The same AnthropicProvider (and so the same diagnosis loop) runs on every platform; only
4
+ the SDK client differs. On Bedrock, Vertex AI and Foundry the prompt stays inside the
5
+ customer's own cloud account. Server-side refusal fallback exists only on the Claude
6
+ API, so it is switched off elsewhere (a refusal then becomes "not diagnosed").
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+ from typing import Any
13
+
14
+ from dagnose.agent.provider import ProviderConfigError
15
+
16
+ PROVIDERS = ("anthropic", "bedrock", "vertex", "foundry")
17
+
18
+
19
+ @dataclass
20
+ class ClientChoice:
21
+ provider: str
22
+ model: str # as the platform names it, e.g. "anthropic.claude-opus-5-5" on Bedrock
23
+ client: Any
24
+ fallbacks: bool
25
+
26
+
27
+ def build_client(settings: Any) -> ClientChoice:
28
+ prefix, _, model = settings.llm_model.rpartition("/")
29
+ provider = prefix or settings.llm_provider
30
+ if provider not in PROVIDERS:
31
+ raise ProviderConfigError(
32
+ f"LLM provider {provider!r} is not supported (supported: {', '.join(PROVIDERS)})"
33
+ )
34
+ key = settings.llm_api_key.get_secret_value() if settings.llm_api_key else None
35
+ client: Any
36
+ try:
37
+ import anthropic
38
+
39
+ if provider == "anthropic":
40
+ # No key: the SDK finds ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN or a profile.
41
+ return ClientChoice(
42
+ provider, model, anthropic.Anthropic(api_key=key), settings.llm_fallbacks
43
+ )
44
+ if provider == "bedrock":
45
+ region = settings.llm_region or settings.aws_region
46
+ client = anthropic.AnthropicBedrockMantle(aws_region=region)
47
+ bedrock_model = model if model.startswith("anthropic.") else f"anthropic.{model}"
48
+ return ClientChoice(provider, bedrock_model, client, False)
49
+ if provider == "vertex":
50
+ if not settings.llm_project:
51
+ raise ProviderConfigError("DAGNOSE_LLM_PROVIDER=vertex needs DAGNOSE_LLM_PROJECT")
52
+ client = anthropic.AnthropicVertex(
53
+ project_id=settings.llm_project, region=settings.llm_region or "global"
54
+ )
55
+ return ClientChoice(provider, model, client, False)
56
+ # foundry
57
+ if not settings.llm_foundry_resource:
58
+ raise ProviderConfigError(
59
+ "DAGNOSE_LLM_PROVIDER=foundry needs DAGNOSE_LLM_FOUNDRY_RESOURCE"
60
+ )
61
+ if key:
62
+ client = anthropic.AnthropicFoundry(resource=settings.llm_foundry_resource, api_key=key)
63
+ else:
64
+ try:
65
+ from azure.identity import DefaultAzureCredential, get_bearer_token_provider
66
+ except ImportError as exc:
67
+ raise ProviderConfigError(
68
+ "Foundry without an API key uses Entra ID: pip install 'dagnose[azure]'"
69
+ ) from exc
70
+ token_provider = get_bearer_token_provider(
71
+ DefaultAzureCredential(), settings.llm_azure_scope
72
+ )
73
+ client = anthropic.AnthropicFoundry(
74
+ resource=settings.llm_foundry_resource, azure_ad_token_provider=token_provider
75
+ )
76
+ return ClientChoice(provider, model, client, False)
77
+ except ProviderConfigError:
78
+ raise
79
+ except Exception as exc: # missing cloud SDK, unreadable cloud credentials, ...
80
+ raise ProviderConfigError(
81
+ f"could not set up {provider}: {type(exc).__name__}: {exc}"
82
+ ) from exc
@@ -0,0 +1,192 @@
1
+ """The diagnosis loop: prompt -> (tool calls)* -> structured answer -> evidence check.
2
+
3
+ Only a RedactedContext can be diagnosed (enforced by the type), and tool results are
4
+ redacted by the ToolBox, so nothing unredacted reaches the provider.
5
+
6
+ Evidence check: every quote the model cites is looked up in the context (or in the
7
+ tool results it saw). Evidence that is not found is kept but marked unverified, and
8
+ confidence is capped, so a plausible-sounding guess cannot pass as a proven diagnosis.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import re
15
+ import time
16
+ from datetime import datetime, timezone
17
+
18
+ from pydantic import ValidationError
19
+
20
+ from dagnose.agent.prompt import (
21
+ DIAGNOSIS_SCHEMA,
22
+ SYSTEM_PROMPT,
23
+ history_row,
24
+ render_context,
25
+ )
26
+ from dagnose.agent.provider import LLMProvider, ToolResult
27
+ from dagnose.agent.tools import ToolBox
28
+ from dagnose.models import (
29
+ Diagnosis,
30
+ DiagnosisRun,
31
+ RedactedContext,
32
+ ToolCallRecord,
33
+ Usage,
34
+ )
35
+
36
+ LAST_TURN_NOTE = (
37
+ "No more tool calls are available. Give your final diagnosis now, based on what you have."
38
+ )
39
+ NO_EVIDENCE_CAP = 0.3 # nothing the model cited could be found
40
+ WEAK_EVIDENCE_CAP = 0.6 # less than half could be found
41
+
42
+
43
+ class DiagnosisError(RuntimeError):
44
+ """The model did not produce a usable diagnosis (refusal, bad output, no answer)."""
45
+
46
+
47
+ def diagnose(
48
+ ctx: RedactedContext,
49
+ provider: LLMProvider,
50
+ toolbox: ToolBox,
51
+ *,
52
+ max_turns: int = 6,
53
+ ) -> DiagnosisRun:
54
+ started = time.monotonic()
55
+ session = provider.start(
56
+ system=SYSTEM_PROMPT,
57
+ prompt=render_context(ctx),
58
+ tools=toolbox.specs,
59
+ output_schema=DIAGNOSIS_SCHEMA,
60
+ )
61
+ usage = Usage()
62
+ calls: list[ToolCallRecord] = []
63
+ tool_outputs: list[str] = []
64
+ results: list[ToolResult] = []
65
+ served_model: str | None = None
66
+
67
+ for turn_no in range(1, max_turns + 1):
68
+ last = turn_no == max_turns
69
+ turn = session.send(results, note=LAST_TURN_NOTE if last and results else None)
70
+ usage = usage + turn.usage
71
+ served_model = turn.served_model or served_model
72
+
73
+ if turn.stop == "continue":
74
+ results = []
75
+ continue
76
+ if turn.stop == "refusal":
77
+ raise DiagnosisError(f"the model declined (category: {turn.refusal_category})")
78
+ if turn.stop == "max_tokens":
79
+ raise DiagnosisError("the answer was cut off (max_tokens)")
80
+ if turn.stop == "tool_use" and turn.tool_calls:
81
+ if last:
82
+ raise DiagnosisError(f"no final answer after {max_turns} turns")
83
+ results = [toolbox.run(call) for call in turn.tool_calls]
84
+ for call, result in zip(turn.tool_calls, results, strict=True):
85
+ calls.append(
86
+ ToolCallRecord(name=call.name, input=call.input, is_error=result.is_error)
87
+ )
88
+ if not result.is_error:
89
+ tool_outputs.append(result.content)
90
+ continue
91
+
92
+ diagnosis = parse_diagnosis(turn.text)
93
+ model_confidence = diagnosis.confidence
94
+ verified, total = verify_evidence(diagnosis, ctx, tool_outputs)
95
+ capped = cap_confidence(diagnosis, verified, total)
96
+ return DiagnosisRun(
97
+ job=ctx.job,
98
+ diagnosis=diagnosis,
99
+ provider=provider.name,
100
+ model=provider.model,
101
+ served_model=served_model,
102
+ turns=turn_no,
103
+ tool_calls=calls,
104
+ usage=usage,
105
+ duration_s=round(time.monotonic() - started, 3),
106
+ evidence_verified=verified,
107
+ evidence_total=total,
108
+ confidence_capped=capped,
109
+ model_confidence=model_confidence,
110
+ created_at=datetime.now(timezone.utc),
111
+ )
112
+ raise DiagnosisError(f"no final answer after {max_turns} turns")
113
+
114
+
115
+ def parse_diagnosis(text: str) -> Diagnosis:
116
+ try:
117
+ data = json.loads(text)
118
+ except json.JSONDecodeError as exc:
119
+ raise DiagnosisError(f"the answer is not JSON: {exc}") from exc
120
+ if isinstance(data, dict) and isinstance(data.get("confidence"), (int, float)):
121
+ data["confidence"] = min(max(float(data["confidence"]), 0.0), 1.0)
122
+ try:
123
+ return Diagnosis.model_validate(data)
124
+ except ValidationError as exc:
125
+ raise DiagnosisError(f"the answer does not match the schema: {exc}") from exc
126
+
127
+
128
+ # ---- evidence -----------------------------------------------------------------------
129
+
130
+ _WS = re.compile(r"\s+")
131
+
132
+
133
+ def _norm(text: str) -> str:
134
+ return _WS.sub(" ", text).strip().lower()
135
+
136
+
137
+ def _found(quote: str, haystack: str) -> bool:
138
+ q = _norm(quote)
139
+ return bool(q) and q in _norm(haystack)
140
+
141
+
142
+ def verify_evidence(
143
+ diagnosis: Diagnosis, ctx: RedactedContext, tool_outputs: list[str]
144
+ ) -> tuple[int, int]:
145
+ """Mark each evidence item verified if its quote is where it says. Returns counts."""
146
+ log_by_n = {line.n: line.message for line in ctx.log_tail}
147
+ source_lines = (ctx.dag_source or "").splitlines()
148
+ exceptions = "\n".join(
149
+ f"{e.type}: {e.message}\n"
150
+ + "\n".join(f"{f.filename}:{f.lineno} in {f.name}" for f in e.frames)
151
+ for e in ctx.exceptions
152
+ )
153
+ params = json.dumps({"task_params": ctx.task_params, "run_conf": ctx.run_conf}, default=str)
154
+ history = "\n".join(history_row(r) for r in ctx.run_history)
155
+ commits = "\n".join(f"{c.sha} {c.subject}\n{c.diff}" for c in ctx.recent_commits)
156
+ tools = "\n".join(tool_outputs)
157
+
158
+ for ev in diagnosis.evidence:
159
+ if ev.source == "log":
160
+ ev.verified = ev.line in log_by_n and _found(ev.quote, log_by_n[ev.line])
161
+ elif ev.source == "dag_source":
162
+ ev.verified = (
163
+ ev.line is not None
164
+ and 1 <= ev.line <= len(source_lines)
165
+ and _found(ev.quote, source_lines[ev.line - 1])
166
+ )
167
+ elif ev.source == "exception":
168
+ ev.verified = _found(ev.quote, exceptions)
169
+ elif ev.source == "task_params":
170
+ ev.verified = _found(ev.quote, params)
171
+ elif ev.source == "run_history":
172
+ ev.verified = _found(ev.quote, history)
173
+ elif ev.source == "commit":
174
+ ev.verified = _found(ev.quote, commits)
175
+ elif ev.source == "tool_result":
176
+ ev.verified = _found(ev.quote, tools)
177
+ verified = sum(ev.verified for ev in diagnosis.evidence)
178
+ return verified, len(diagnosis.evidence)
179
+
180
+
181
+ def cap_confidence(diagnosis: Diagnosis, verified: int, total: int) -> bool:
182
+ """Lower confidence when the evidence does not check out. Returns True if capped."""
183
+ if verified == 0:
184
+ cap = NO_EVIDENCE_CAP
185
+ elif verified * 2 < total:
186
+ cap = WEAK_EVIDENCE_CAP
187
+ else:
188
+ return False
189
+ if diagnosis.confidence > cap:
190
+ diagnosis.confidence = cap
191
+ return True
192
+ return False