agent-doctor-cli 0.5.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.
- agent_doctor/__init__.py +42 -0
- agent_doctor/_util.py +166 -0
- agent_doctor/analyzers/__init__.py +34 -0
- agent_doctor/analyzers/base.py +208 -0
- agent_doctor/analyzers/bloat.py +44 -0
- agent_doctor/analyzers/compare.py +96 -0
- agent_doctor/analyzers/cost.py +97 -0
- agent_doctor/analyzers/latency.py +89 -0
- agent_doctor/analyzers/loops.py +168 -0
- agent_doctor/analyzers/redundancy.py +123 -0
- agent_doctor/analyzers/report.py +181 -0
- agent_doctor/cli.py +770 -0
- agent_doctor/config.py +41 -0
- agent_doctor/core.py +212 -0
- agent_doctor/evals/__init__.py +52 -0
- agent_doctor/evals/cases.py +67 -0
- agent_doctor/evals/results.py +46 -0
- agent_doctor/evals/runner.py +332 -0
- agent_doctor/evals/scorers.py +196 -0
- agent_doctor/evals/stats.py +48 -0
- agent_doctor/evals/suite.py +72 -0
- agent_doctor/ingest/__init__.py +75 -0
- agent_doctor/ingest/common.py +165 -0
- agent_doctor/ingest/langfuse.py +96 -0
- agent_doctor/ingest/langsmith.py +111 -0
- agent_doctor/ingest/otel.py +123 -0
- agent_doctor/ingest/redact.py +102 -0
- agent_doctor/mcp_server.py +344 -0
- agent_doctor/pricing/__init__.py +14 -0
- agent_doctor/pricing/cost.py +110 -0
- agent_doctor/pricing/pricing.yaml +50 -0
- agent_doctor/pricing/table.py +121 -0
- agent_doctor/recommender/__init__.py +30 -0
- agent_doctor/recommender/knowledge.py +106 -0
- agent_doctor/recommender/llm.py +81 -0
- agent_doctor/recommender/playbooks/anthropic-prompt-caching.md +43 -0
- agent_doctor/recommender/playbooks/cache-tool-results.md +45 -0
- agent_doctor/recommender/playbooks/circuit-breaker.md +48 -0
- agent_doctor/recommender/playbooks/dedupe-model-queries.md +37 -0
- agent_doctor/recommender/playbooks/llm-rate-limit-backoff.md +35 -0
- agent_doctor/recommender/playbooks/openai-prompt-caching.md +36 -0
- agent_doctor/recommender/playbooks/parallel-tool-calls.md +43 -0
- agent_doctor/recommender/playbooks/remove-unused-tool-calls.md +32 -0
- agent_doctor/recommender/playbooks/retry-with-backoff.md +49 -0
- agent_doctor/recommender/playbooks/route-to-small-model.md +37 -0
- agent_doctor/recommender/playbooks/speed-up-slow-tools.md +41 -0
- agent_doctor/recommender/playbooks/stable-prompt-prefix.md +35 -0
- agent_doctor/recommender/playbooks/stop-no-progress-loops.md +34 -0
- agent_doctor/recommender/playbooks/surface-tool-failures.md +33 -0
- agent_doctor/recommender/playbooks/trim-context.md +32 -0
- agent_doctor/recommender/recommend.py +181 -0
- agent_doctor/replay/__init__.py +26 -0
- agent_doctor/replay/engine.py +300 -0
- agent_doctor/schema.py +277 -0
- agent_doctor/sdk/__init__.py +17 -0
- agent_doctor/sdk/decorators.py +259 -0
- agent_doctor/sdk/instrument.py +419 -0
- agent_doctor/sdk/recorder.py +272 -0
- agent_doctor/store/__init__.py +14 -0
- agent_doctor/store/sqlite.py +312 -0
- agent_doctor/testing.py +75 -0
- agent_doctor_cli-0.5.0.dist-info/METADATA +378 -0
- agent_doctor_cli-0.5.0.dist-info/RECORD +66 -0
- agent_doctor_cli-0.5.0.dist-info/WHEEL +4 -0
- agent_doctor_cli-0.5.0.dist-info/entry_points.txt +2 -0
- agent_doctor_cli-0.5.0.dist-info/licenses/LICENSE +21 -0
agent_doctor/__init__.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Agent Doctor: find out why your AI agent is expensive, slow or unreliable."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.5.0"
|
|
4
|
+
|
|
5
|
+
from agent_doctor.schema import ( # noqa: E402
|
|
6
|
+
Finding,
|
|
7
|
+
FindingType,
|
|
8
|
+
Run,
|
|
9
|
+
Severity,
|
|
10
|
+
Span,
|
|
11
|
+
SpanKind,
|
|
12
|
+
SpanStatus,
|
|
13
|
+
compute_args_hash,
|
|
14
|
+
)
|
|
15
|
+
from agent_doctor.sdk import ( # noqa: E402
|
|
16
|
+
RunRecorder,
|
|
17
|
+
current_run,
|
|
18
|
+
instrument,
|
|
19
|
+
record_run,
|
|
20
|
+
span,
|
|
21
|
+
trace_run,
|
|
22
|
+
trace_tool,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"Finding",
|
|
27
|
+
"FindingType",
|
|
28
|
+
"Run",
|
|
29
|
+
"RunRecorder",
|
|
30
|
+
"Severity",
|
|
31
|
+
"Span",
|
|
32
|
+
"SpanKind",
|
|
33
|
+
"SpanStatus",
|
|
34
|
+
"__version__",
|
|
35
|
+
"compute_args_hash",
|
|
36
|
+
"current_run",
|
|
37
|
+
"instrument",
|
|
38
|
+
"record_run",
|
|
39
|
+
"span",
|
|
40
|
+
"trace_run",
|
|
41
|
+
"trace_tool",
|
|
42
|
+
]
|
agent_doctor/_util.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""Small helpers shared across modules."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import dataclasses
|
|
6
|
+
import math
|
|
7
|
+
import time
|
|
8
|
+
import uuid
|
|
9
|
+
import warnings
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
from datetime import date, datetime
|
|
12
|
+
from enum import Enum
|
|
13
|
+
from typing import Any, Protocol
|
|
14
|
+
|
|
15
|
+
MAX_STR = 20_000
|
|
16
|
+
_warned: set[str] = set()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Clock(Protocol):
|
|
20
|
+
def time_ms(self) -> int: ... # wall clock, Unix epoch milliseconds
|
|
21
|
+
def perf(self) -> float: ... # monotonic seconds, for durations
|
|
22
|
+
def sleep(self, seconds: float) -> None: ...
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class SystemClock:
|
|
26
|
+
def time_ms(self) -> int:
|
|
27
|
+
return time.time_ns() // 1_000_000
|
|
28
|
+
|
|
29
|
+
def perf(self) -> float:
|
|
30
|
+
return time.perf_counter()
|
|
31
|
+
|
|
32
|
+
def sleep(self, seconds: float) -> None:
|
|
33
|
+
time.sleep(seconds)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
_clock: Clock = SystemClock()
|
|
37
|
+
_id_factory: Callable[[str], str] | None = None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def get_clock() -> Clock:
|
|
41
|
+
return _clock
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def set_clock(clock: Clock) -> Clock:
|
|
45
|
+
"""Replace the clock used for all span timings; returns the previous one."""
|
|
46
|
+
global _clock
|
|
47
|
+
prev, _clock = _clock, clock
|
|
48
|
+
return prev
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def set_id_factory(factory: Callable[[str], str] | None) -> Callable[[str], str] | None:
|
|
52
|
+
global _id_factory
|
|
53
|
+
prev, _id_factory = _id_factory, factory
|
|
54
|
+
return prev
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def now_ms() -> int:
|
|
58
|
+
return _clock.time_ms()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def new_id(prefix: str) -> str:
|
|
62
|
+
if _id_factory is not None:
|
|
63
|
+
return _id_factory(prefix)
|
|
64
|
+
return f"{prefix}_{uuid.uuid4().hex[:12]}"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def warn_once(key: str, message: str) -> None:
|
|
68
|
+
"""Warn about a recording problem once per process; never raise."""
|
|
69
|
+
if key not in _warned:
|
|
70
|
+
_warned.add(key)
|
|
71
|
+
warnings.warn(f"agent-doctor: {message}", RuntimeWarning, stacklevel=3)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def to_jsonable(obj: Any, max_str: int = MAX_STR, _depth: int = 0) -> Any:
|
|
75
|
+
"""Convert any value into something json.dumps accepts, truncating long strings."""
|
|
76
|
+
if _depth > 20:
|
|
77
|
+
return repr(obj)[:200]
|
|
78
|
+
d = _depth + 1
|
|
79
|
+
if obj is None or isinstance(obj, bool | int):
|
|
80
|
+
return obj
|
|
81
|
+
if isinstance(obj, float):
|
|
82
|
+
return obj if math.isfinite(obj) else str(obj)
|
|
83
|
+
if isinstance(obj, str):
|
|
84
|
+
if len(obj) <= max_str:
|
|
85
|
+
return obj
|
|
86
|
+
return obj[:max_str] + f"...[truncated {len(obj) - max_str} chars]"
|
|
87
|
+
if isinstance(obj, bytes | bytearray):
|
|
88
|
+
return f"<{len(obj)} bytes>"
|
|
89
|
+
if isinstance(obj, Enum):
|
|
90
|
+
return to_jsonable(obj.value, max_str, d)
|
|
91
|
+
if isinstance(obj, datetime | date):
|
|
92
|
+
return obj.isoformat()
|
|
93
|
+
if isinstance(obj, dict):
|
|
94
|
+
return {str(k): to_jsonable(v, max_str, d) for k, v in obj.items()}
|
|
95
|
+
if isinstance(obj, list | tuple | set | frozenset):
|
|
96
|
+
return [to_jsonable(v, max_str, d) for v in obj]
|
|
97
|
+
if hasattr(obj, "model_dump"):
|
|
98
|
+
try:
|
|
99
|
+
return to_jsonable(obj.model_dump(mode="json"), max_str, d)
|
|
100
|
+
except Exception:
|
|
101
|
+
pass
|
|
102
|
+
if dataclasses.is_dataclass(obj) and not isinstance(obj, type):
|
|
103
|
+
try:
|
|
104
|
+
return to_jsonable(dataclasses.asdict(obj), max_str, d)
|
|
105
|
+
except Exception:
|
|
106
|
+
pass
|
|
107
|
+
return repr(obj)[:max_str]
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def pick(obj: Any, path: str, default: Any = None) -> Any:
|
|
111
|
+
"""Read a dotted path from dicts, objects and lists: pick(resp, "choices.0.message.content")."""
|
|
112
|
+
cur = obj
|
|
113
|
+
for part in path.split("."):
|
|
114
|
+
if cur is None:
|
|
115
|
+
return default
|
|
116
|
+
if isinstance(cur, list | tuple):
|
|
117
|
+
try:
|
|
118
|
+
cur = cur[int(part)]
|
|
119
|
+
except (ValueError, IndexError):
|
|
120
|
+
return default
|
|
121
|
+
continue
|
|
122
|
+
if isinstance(cur, dict):
|
|
123
|
+
if part in cur:
|
|
124
|
+
cur = cur[part]
|
|
125
|
+
continue
|
|
126
|
+
# HF output types are dict subclasses that also expose attributes
|
|
127
|
+
nxt = getattr(cur, part, None)
|
|
128
|
+
if nxt is None and isinstance(cur, dict):
|
|
129
|
+
return default
|
|
130
|
+
cur = nxt
|
|
131
|
+
return default if cur is None else cur
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def import_path(path: Any) -> Any:
|
|
135
|
+
"""Import a .py file. A file inside a package (folders with __init__.py) is imported by
|
|
136
|
+
its dotted name, so its relative imports work; the folder above the package goes on
|
|
137
|
+
sys.path, as pytest does."""
|
|
138
|
+
import importlib
|
|
139
|
+
import importlib.util
|
|
140
|
+
import sys
|
|
141
|
+
from pathlib import Path
|
|
142
|
+
|
|
143
|
+
path = Path(path).resolve()
|
|
144
|
+
if not path.is_file():
|
|
145
|
+
raise FileNotFoundError(f"no such file: {path}")
|
|
146
|
+
parts = [path.stem]
|
|
147
|
+
root = path.parent
|
|
148
|
+
while (root / "__init__.py").is_file():
|
|
149
|
+
parts.insert(0, root.name)
|
|
150
|
+
root = root.parent
|
|
151
|
+
if len(parts) > 1:
|
|
152
|
+
if str(root) not in sys.path:
|
|
153
|
+
sys.path.insert(0, str(root))
|
|
154
|
+
return importlib.import_module(".".join(parts))
|
|
155
|
+
name = f"_agent_doctor_user_{path.stem}"
|
|
156
|
+
spec = importlib.util.spec_from_file_location(name, path)
|
|
157
|
+
if spec is None or spec.loader is None:
|
|
158
|
+
raise ImportError(f"cannot import {path}")
|
|
159
|
+
module = importlib.util.module_from_spec(spec)
|
|
160
|
+
sys.modules[name] = module
|
|
161
|
+
sys.path.insert(0, str(path.parent))
|
|
162
|
+
try:
|
|
163
|
+
spec.loader.exec_module(module)
|
|
164
|
+
finally:
|
|
165
|
+
sys.path.remove(str(path.parent))
|
|
166
|
+
return module
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Analyzers: deterministic detectors for wasted cost, time and reliability problems.
|
|
2
|
+
|
|
3
|
+
>>> from agent_doctor.analyzers import analyze_run
|
|
4
|
+
>>> report = analyze_run(run)
|
|
5
|
+
>>> for f in report.findings: print(f.severity, f.title)
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from agent_doctor.analyzers.base import DEFAULT_THRESHOLDS, Context, Thresholds
|
|
9
|
+
from agent_doctor.analyzers.report import (
|
|
10
|
+
DETECTORS,
|
|
11
|
+
SEVERITY_RANK,
|
|
12
|
+
AnalysisReport,
|
|
13
|
+
ProblemStats,
|
|
14
|
+
RunDigest,
|
|
15
|
+
ScanReport,
|
|
16
|
+
analyze_run,
|
|
17
|
+
problem_name,
|
|
18
|
+
scan_reports,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"DEFAULT_THRESHOLDS",
|
|
23
|
+
"DETECTORS",
|
|
24
|
+
"SEVERITY_RANK",
|
|
25
|
+
"AnalysisReport",
|
|
26
|
+
"Context",
|
|
27
|
+
"ProblemStats",
|
|
28
|
+
"RunDigest",
|
|
29
|
+
"ScanReport",
|
|
30
|
+
"Thresholds",
|
|
31
|
+
"analyze_run",
|
|
32
|
+
"problem_name",
|
|
33
|
+
"scan_reports",
|
|
34
|
+
]
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""Shared pieces for the detectors: thresholds, the analysis context and text helpers.
|
|
2
|
+
|
|
3
|
+
Detectors are plain functions ``(ctx) -> list[Finding]``. They only read the run (what
|
|
4
|
+
a real agent records); they never call an LLM, so analysis is free and repeatable.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import re
|
|
11
|
+
from collections.abc import Callable, Iterator
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from functools import cached_property
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from agent_doctor.pricing import CostReport, ModelPrice, PriceTable, estimate_cost
|
|
17
|
+
from agent_doctor.schema import Finding, Run, Span, SpanKind
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class Thresholds:
|
|
22
|
+
"""Every tunable number in one place. Defaults favour precision over recall."""
|
|
23
|
+
|
|
24
|
+
retry_min_attempts: int = 3 # a failed call retried twice or more
|
|
25
|
+
no_backoff_gap_ms: int = 250 # retries closer together than this have no backoff
|
|
26
|
+
loop_min_repeats: int = 3 # same tool, same result, this many times
|
|
27
|
+
near_duplicate_min_similarity: float = 0.3 # word overlap of reworded arguments
|
|
28
|
+
slow_step_share: float = 0.5 # one step taking this share of the run...
|
|
29
|
+
slow_step_min_ms: int = 1000 # ...and at least this long
|
|
30
|
+
parallel_min_saving_ms: int = 300 # only suggest parallelism that saves this much
|
|
31
|
+
bloat_min_calls: int = 3
|
|
32
|
+
bloat_growth_ratio: float = 2.0 # last prompt this many times the first
|
|
33
|
+
bloat_min_growth_tokens: int = 1000
|
|
34
|
+
tiny_output_tokens: int = 5 # a "one-word" answer
|
|
35
|
+
expensive_input_price: float = 1.0 # USD per 1M input tokens
|
|
36
|
+
cache_min_shared_chars: int = 4000 # ~1,000 tokens: what providers typically cache
|
|
37
|
+
cache_varying_head_chars: int = 200 # a dynamic header shorter than this breaks caching
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
DEFAULT_THRESHOLDS = Thresholds()
|
|
41
|
+
|
|
42
|
+
STOPWORDS = {
|
|
43
|
+
"a", "an", "the", "is", "are", "was", "what", "which", "who", "how", "for", "of", "to",
|
|
44
|
+
"in", "on", "and", "or", "my", "your", "me", "i", "do", "does", "can", "about", "with",
|
|
45
|
+
}
|
|
46
|
+
_COMMON_VALUES = {"true", "false", "none", "null", "ok", "yes", "no", "n/a"}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def canonical(value: Any) -> str:
|
|
50
|
+
return json.dumps(value, sort_keys=True, separators=(",", ":"), default=str)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def leaves(value: Any, key: str | None = None) -> Iterator[tuple[str | None, Any]]:
|
|
54
|
+
"""Every scalar inside nested dicts and lists, with the key it sits under."""
|
|
55
|
+
if isinstance(value, dict):
|
|
56
|
+
for k, v in value.items():
|
|
57
|
+
yield from leaves(v, str(k))
|
|
58
|
+
elif isinstance(value, list | tuple):
|
|
59
|
+
for v in value:
|
|
60
|
+
yield from leaves(v, key)
|
|
61
|
+
elif value is not None:
|
|
62
|
+
yield key, value
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def words(text: str) -> set[str]:
|
|
66
|
+
return {w for w in re.findall(r"[a-z0-9]+", text.lower()) if w not in STOPWORDS}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def jaccard(a: set, b: set) -> float:
|
|
70
|
+
return len(a & b) / len(a | b) if (a or b) else 1.0
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def strip_echo(output: Any, args: dict[str, Any] | None) -> Any:
|
|
74
|
+
"""Drop top-level output fields that just repeat an argument (e.g. "query")."""
|
|
75
|
+
if not isinstance(output, dict) or not args:
|
|
76
|
+
return output
|
|
77
|
+
echoed = {canonical(v) for v in args.values()}
|
|
78
|
+
return {k: v for k, v in output.items() if canonical(v) not in echoed}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def prompt_text(span: Span) -> str:
|
|
82
|
+
parts: list[str] = []
|
|
83
|
+
for m in span.input_messages or []:
|
|
84
|
+
content = m.get("content") if isinstance(m, dict) else m
|
|
85
|
+
if isinstance(content, list):
|
|
86
|
+
parts += [str(p.get("text", p)) if isinstance(p, dict) else str(p) for p in content]
|
|
87
|
+
elif content is not None:
|
|
88
|
+
parts.append(str(content))
|
|
89
|
+
return "\n".join(parts)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def first_message(span: Span) -> str:
|
|
93
|
+
msgs = span.input_messages or []
|
|
94
|
+
if not msgs:
|
|
95
|
+
return ""
|
|
96
|
+
content = msgs[0].get("content") if isinstance(msgs[0], dict) else msgs[0]
|
|
97
|
+
return content if isinstance(content, str) else canonical(content)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def common_prefix_len(a: str, b: str) -> int:
|
|
101
|
+
n = min(len(a), len(b))
|
|
102
|
+
i = 0
|
|
103
|
+
while i < n and a[i] == b[i]:
|
|
104
|
+
i += 1
|
|
105
|
+
return i
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def common_suffix_len(a: str, b: str) -> int:
|
|
109
|
+
n = min(len(a), len(b))
|
|
110
|
+
i = 0
|
|
111
|
+
while i < n and a[-1 - i] == b[-1 - i]:
|
|
112
|
+
i += 1
|
|
113
|
+
return i
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def value_appears(key: str | None, value: Any, haystack: str, haystack_lower: str) -> bool:
|
|
117
|
+
"""Does this output value show up in later prompt text?"""
|
|
118
|
+
if isinstance(value, bool):
|
|
119
|
+
return False
|
|
120
|
+
if isinstance(value, int | float):
|
|
121
|
+
text = str(value)
|
|
122
|
+
if abs(value) >= 100:
|
|
123
|
+
return re.search(rf"(?<![\w.]){re.escape(text)}(?![\w])", haystack) is not None
|
|
124
|
+
if not key:
|
|
125
|
+
return False
|
|
126
|
+
# small numbers only count next to their key: in_stock=3, "in_stock": 3
|
|
127
|
+
return re.search(rf"{re.escape(key)}\W{{0,4}}{re.escape(text)}(?![\w.])", haystack) is not None
|
|
128
|
+
text = str(value).strip()
|
|
129
|
+
if len(text) < 4 or text.lower() in _COMMON_VALUES:
|
|
130
|
+
return False
|
|
131
|
+
return text.lower() in haystack_lower
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def has_checkable_values(output: Any) -> bool:
|
|
135
|
+
for key, v in leaves(output):
|
|
136
|
+
if isinstance(v, bool):
|
|
137
|
+
continue
|
|
138
|
+
if isinstance(v, int | float) and (abs(v) >= 100 or key):
|
|
139
|
+
return True
|
|
140
|
+
if isinstance(v, str) and len(v.strip()) >= 4 and v.strip().lower() not in _COMMON_VALUES:
|
|
141
|
+
return True
|
|
142
|
+
return False
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class Context:
|
|
146
|
+
"""One run plus everything detectors share: prices, costs, step numbers, loop spans."""
|
|
147
|
+
|
|
148
|
+
def __init__(self, run: Run, prices: PriceTable, thresholds: Thresholds = DEFAULT_THRESHOLDS):
|
|
149
|
+
self.run = run
|
|
150
|
+
self.prices = prices
|
|
151
|
+
self.t = thresholds
|
|
152
|
+
|
|
153
|
+
@cached_property
|
|
154
|
+
def spans(self) -> list[Span]:
|
|
155
|
+
return self.run.ordered_spans
|
|
156
|
+
|
|
157
|
+
@cached_property
|
|
158
|
+
def llm(self) -> list[Span]:
|
|
159
|
+
return [s for s in self.spans if s.kind is SpanKind.LLM]
|
|
160
|
+
|
|
161
|
+
@cached_property
|
|
162
|
+
def ok_llm(self) -> list[Span]:
|
|
163
|
+
return [s for s in self.llm if not s.is_error]
|
|
164
|
+
|
|
165
|
+
@cached_property
|
|
166
|
+
def tools(self) -> list[Span]:
|
|
167
|
+
return [s for s in self.spans if s.kind is SpanKind.TOOL]
|
|
168
|
+
|
|
169
|
+
@cached_property
|
|
170
|
+
def cost(self) -> CostReport:
|
|
171
|
+
return estimate_cost(self.run, self.prices)
|
|
172
|
+
|
|
173
|
+
@cached_property
|
|
174
|
+
def span_cost(self) -> dict[str, float | None]:
|
|
175
|
+
return {s.span_id: s.cost_usd for s in self.cost.spans}
|
|
176
|
+
|
|
177
|
+
@cached_property
|
|
178
|
+
def step(self) -> dict[str, int]:
|
|
179
|
+
return {s.span_id: i for i, s in enumerate(self.spans, start=1)}
|
|
180
|
+
|
|
181
|
+
def price(self, span: Span) -> ModelPrice | None:
|
|
182
|
+
return self.prices.find(span.model or span.name, span.provider)
|
|
183
|
+
|
|
184
|
+
def steps(self, spans: list[Span]) -> str:
|
|
185
|
+
return ", ".join(f"#{self.step[s.span_id]}" for s in spans)
|
|
186
|
+
|
|
187
|
+
@cached_property
|
|
188
|
+
def loop_groups(self) -> list[list[Span]]:
|
|
189
|
+
"""Groups of >= N successful calls to one tool that all returned the same result."""
|
|
190
|
+
groups: dict[tuple[str, str], list[Span]] = {}
|
|
191
|
+
for s in self.tools:
|
|
192
|
+
if s.is_error or s.tool_output is None:
|
|
193
|
+
continue
|
|
194
|
+
key = (s.name, canonical(strip_echo(s.tool_output, s.tool_args)))
|
|
195
|
+
groups.setdefault(key, []).append(s)
|
|
196
|
+
return [g for g in groups.values() if len(g) >= self.t.loop_min_repeats]
|
|
197
|
+
|
|
198
|
+
@cached_property
|
|
199
|
+
def loop_span_ids(self) -> set[str]:
|
|
200
|
+
return {s.span_id for g in self.loop_groups for s in g}
|
|
201
|
+
|
|
202
|
+
def finding(self, **fields: Any) -> Finding:
|
|
203
|
+
spans = fields.pop("evidence")
|
|
204
|
+
fields["evidence_span_ids"] = [s.span_id for s in sorted(spans, key=lambda x: x.start_ms)]
|
|
205
|
+
return Finding(run_id=self.run.run_id, **fields)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
Detector = Callable[[Context], list[Finding]]
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Context bloat: prompts that keep growing because history and raw tool output pile up."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from agent_doctor.analyzers.base import Context
|
|
6
|
+
from agent_doctor.schema import Finding, FindingType, Severity
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def context_bloat(ctx: Context) -> list[Finding]:
|
|
10
|
+
calls = ctx.ok_llm
|
|
11
|
+
if len(calls) < ctx.t.bloat_min_calls:
|
|
12
|
+
return []
|
|
13
|
+
tokens = [s.input_tokens for s in calls]
|
|
14
|
+
first, last = tokens[0], tokens[-1]
|
|
15
|
+
if first <= 0 or last < ctx.t.bloat_growth_ratio * first:
|
|
16
|
+
return []
|
|
17
|
+
if last - first < ctx.t.bloat_min_growth_tokens:
|
|
18
|
+
return []
|
|
19
|
+
if any(b < 0.9 * a for a, b in zip(tokens, tokens[1:], strict=False)):
|
|
20
|
+
return [] # not a steady pile-up
|
|
21
|
+
|
|
22
|
+
extra = [t - first for t in tokens[1:]]
|
|
23
|
+
cost = 0.0
|
|
24
|
+
priced = True
|
|
25
|
+
for s, n in zip(calls[1:], extra, strict=False):
|
|
26
|
+
price = ctx.price(s)
|
|
27
|
+
if price is None:
|
|
28
|
+
priced = False
|
|
29
|
+
continue
|
|
30
|
+
cost += n * price.rates(s.input_tokens)[0] / 1_000_000
|
|
31
|
+
ratio = last / first
|
|
32
|
+
return [ctx.finding(
|
|
33
|
+
type=FindingType.CONTEXT_BLOAT,
|
|
34
|
+
severity=Severity.HIGH if ratio >= 3 else Severity.MEDIUM,
|
|
35
|
+
title=f"Prompt grew {ratio:.1f}x over {len(calls)} LLM calls ({first:,} to {last:,} tokens)",
|
|
36
|
+
detail=("Input tokens per call: " + " -> ".join(f"{t:,}" for t in tokens)
|
|
37
|
+
+ f". About {sum(extra):,} tokens were re-sent history or raw tool output."),
|
|
38
|
+
suggestion=("Send the model only what the next step needs: summarize or trim tool results, "
|
|
39
|
+
"drop old turns, and keep large raw data out of the prompt."),
|
|
40
|
+
evidence=calls,
|
|
41
|
+
wasted_tokens=sum(extra),
|
|
42
|
+
wasted_cost_usd=cost if priced and cost else None,
|
|
43
|
+
data={"tokens": tokens, "ratio": round(ratio, 2), "kind": "context_bloat"},
|
|
44
|
+
)]
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""Side-by-side comparison of two runs: what changed in cost, time, calls and problems."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import Counter
|
|
6
|
+
|
|
7
|
+
from pydantic import BaseModel, Field
|
|
8
|
+
|
|
9
|
+
from agent_doctor.analyzers.base import DEFAULT_THRESHOLDS, Thresholds
|
|
10
|
+
from agent_doctor.analyzers.report import AnalysisReport, analyze_run, problem_name
|
|
11
|
+
from agent_doctor.pricing import PriceTable, estimate_cost
|
|
12
|
+
from agent_doctor.schema import Run
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class RunTotals(BaseModel):
|
|
16
|
+
run_id: str
|
|
17
|
+
agent_name: str
|
|
18
|
+
status: str
|
|
19
|
+
duration_ms: int
|
|
20
|
+
llm_calls: int
|
|
21
|
+
tool_calls: int
|
|
22
|
+
errors: int
|
|
23
|
+
input_tokens: int
|
|
24
|
+
output_tokens: int
|
|
25
|
+
cached_tokens: int
|
|
26
|
+
cost_usd: float
|
|
27
|
+
cost_complete: bool
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class CountDiff(BaseModel):
|
|
31
|
+
name: str
|
|
32
|
+
a: int
|
|
33
|
+
b: int
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class ModelDiff(BaseModel):
|
|
37
|
+
model: str
|
|
38
|
+
a_calls: int
|
|
39
|
+
b_calls: int
|
|
40
|
+
a_cost_usd: float | None
|
|
41
|
+
b_cost_usd: float | None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class RunComparison(BaseModel):
|
|
45
|
+
a: RunTotals
|
|
46
|
+
b: RunTotals
|
|
47
|
+
delta: dict[str, float] = Field(description="b minus a, for every numeric total.")
|
|
48
|
+
tool_calls: list[CountDiff] = Field(description="Tools called a different number of times.")
|
|
49
|
+
models: list[ModelDiff] = Field(description="Models whose calls or cost differ.")
|
|
50
|
+
problems_only_in_a: list[str]
|
|
51
|
+
problems_only_in_b: list[str]
|
|
52
|
+
problems_in_both: list[str]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _totals(run: Run, report: AnalysisReport) -> RunTotals:
|
|
56
|
+
return RunTotals(
|
|
57
|
+
run_id=run.run_id, agent_name=run.agent_name, status=run.status.value,
|
|
58
|
+
duration_ms=run.duration_ms, llm_calls=report.llm_calls, tool_calls=report.tool_calls,
|
|
59
|
+
errors=run.error_count, input_tokens=run.total_input_tokens, output_tokens=run.total_output_tokens,
|
|
60
|
+
cached_tokens=run.total_cached_tokens, cost_usd=report.total_cost_usd,
|
|
61
|
+
cost_complete=report.fully_priced,
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def compare_runs(
|
|
66
|
+
a: Run, b: Run, prices: PriceTable | None = None, thresholds: Thresholds = DEFAULT_THRESHOLDS
|
|
67
|
+
) -> RunComparison:
|
|
68
|
+
prices = prices if prices is not None else PriceTable.load()
|
|
69
|
+
rep_a, rep_b = analyze_run(a, prices, thresholds), analyze_run(b, prices, thresholds)
|
|
70
|
+
ta, tb = _totals(a, rep_a), _totals(b, rep_b)
|
|
71
|
+
numeric = [k for k, v in ta.model_dump().items()
|
|
72
|
+
if isinstance(v, int | float) and not isinstance(v, bool)]
|
|
73
|
+
delta = {k: getattr(tb, k) - getattr(ta, k) for k in numeric}
|
|
74
|
+
|
|
75
|
+
tools_a = Counter(s.name for s in a.tool_spans)
|
|
76
|
+
tools_b = Counter(s.name for s in b.tool_spans)
|
|
77
|
+
tool_diffs = [CountDiff(name=t, a=tools_a[t], b=tools_b[t])
|
|
78
|
+
for t in sorted(tools_a.keys() | tools_b.keys()) if tools_a[t] != tools_b[t]]
|
|
79
|
+
|
|
80
|
+
by_a = {m.model: m for m in estimate_cost(a, prices).by_model}
|
|
81
|
+
by_b = {m.model: m for m in estimate_cost(b, prices).by_model}
|
|
82
|
+
model_diffs = []
|
|
83
|
+
for name in sorted(by_a.keys() | by_b.keys()):
|
|
84
|
+
ma, mb = by_a.get(name), by_b.get(name)
|
|
85
|
+
diff = ModelDiff(model=name, a_calls=ma.calls if ma else 0, b_calls=mb.calls if mb else 0,
|
|
86
|
+
a_cost_usd=ma.cost_usd if ma else 0.0, b_cost_usd=mb.cost_usd if mb else 0.0)
|
|
87
|
+
if diff.a_calls != diff.b_calls or diff.a_cost_usd != diff.b_cost_usd:
|
|
88
|
+
model_diffs.append(diff)
|
|
89
|
+
|
|
90
|
+
pa = {problem_name(f) for f in rep_a.findings}
|
|
91
|
+
pb = {problem_name(f) for f in rep_b.findings}
|
|
92
|
+
return RunComparison(
|
|
93
|
+
a=ta, b=tb, delta=delta, tool_calls=tool_diffs, models=model_diffs,
|
|
94
|
+
problems_only_in_a=sorted(pa - pb), problems_only_in_b=sorted(pb - pa),
|
|
95
|
+
problems_in_both=sorted(pa & pb),
|
|
96
|
+
)
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Cost waste: big models on trivial steps, and prompts that miss the provider's cache."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from agent_doctor.analyzers.base import (
|
|
6
|
+
Context,
|
|
7
|
+
common_prefix_len,
|
|
8
|
+
common_suffix_len,
|
|
9
|
+
first_message,
|
|
10
|
+
prompt_text,
|
|
11
|
+
)
|
|
12
|
+
from agent_doctor.schema import Finding, FindingType, Severity
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def expensive_model_for_simple_step(ctx: Context) -> list[Finding]:
|
|
16
|
+
findings = []
|
|
17
|
+
for s in ctx.ok_llm:
|
|
18
|
+
if s.output_tokens > ctx.t.tiny_output_tokens or s.attributes.get("tool_calls"):
|
|
19
|
+
continue
|
|
20
|
+
price = ctx.price(s)
|
|
21
|
+
if price is None or price.rates(s.input_tokens)[0] < ctx.t.expensive_input_price:
|
|
22
|
+
continue
|
|
23
|
+
cost = ctx.span_cost.get(s.span_id)
|
|
24
|
+
findings.append(ctx.finding(
|
|
25
|
+
type=FindingType.COST,
|
|
26
|
+
severity=Severity.MEDIUM,
|
|
27
|
+
title=f"{s.model} used for a {s.output_tokens}-token answer",
|
|
28
|
+
detail=(f"Step {ctx.steps([s])} sends {s.input_tokens:,} tokens to {s.model} "
|
|
29
|
+
f"(${price.rates(s.input_tokens)[0]}/1M input) to get a {s.output_tokens}-token "
|
|
30
|
+
"reply, which looks like a classification or yes/no decision."
|
|
31
|
+
+ (f" It cost ${cost:.6f}." if cost else "")),
|
|
32
|
+
suggestion=("Route simple decisions (classification, yes/no, picking a tool) to a small, "
|
|
33
|
+
"cheap model and keep the large model for the final answer."),
|
|
34
|
+
evidence=[s],
|
|
35
|
+
data={"model": s.model, "output_tokens": s.output_tokens, "cost_usd": cost,
|
|
36
|
+
"kind": "expensive_model_for_simple_step"},
|
|
37
|
+
))
|
|
38
|
+
return findings
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def prompt_cache_misses(ctx: Context) -> list[Finding]:
|
|
42
|
+
"""Consecutive calls share a long block of prompt, but nothing was served from cache."""
|
|
43
|
+
calls = [s for s in ctx.ok_llm if s.input_messages]
|
|
44
|
+
flagged: dict[str, object] = {}
|
|
45
|
+
reasons: set[str] = set()
|
|
46
|
+
stable_tokens: dict[str, int] = {}
|
|
47
|
+
for a, b in zip(calls, calls[1:], strict=False):
|
|
48
|
+
if b.cached_tokens > 0:
|
|
49
|
+
continue
|
|
50
|
+
full_a, full_b = prompt_text(a), prompt_text(b)
|
|
51
|
+
prefix = common_prefix_len(full_a, full_b)
|
|
52
|
+
sys_a, sys_b = first_message(a), first_message(b)
|
|
53
|
+
head = common_prefix_len(sys_a, sys_b)
|
|
54
|
+
tail = common_suffix_len(sys_a, sys_b)
|
|
55
|
+
if prefix >= ctx.t.cache_min_shared_chars:
|
|
56
|
+
reasons.add("shared_prefix_not_cached")
|
|
57
|
+
stable = prefix
|
|
58
|
+
elif head < ctx.t.cache_varying_head_chars and tail >= ctx.t.cache_min_shared_chars:
|
|
59
|
+
reasons.add("dynamic_prompt_head")
|
|
60
|
+
stable = tail
|
|
61
|
+
else:
|
|
62
|
+
continue
|
|
63
|
+
flagged[a.span_id] = a
|
|
64
|
+
flagged[b.span_id] = b
|
|
65
|
+
stable_tokens[b.span_id] = stable // 4
|
|
66
|
+
if not flagged:
|
|
67
|
+
return []
|
|
68
|
+
|
|
69
|
+
saving, priced = 0.0, True
|
|
70
|
+
for sid, n in stable_tokens.items():
|
|
71
|
+
span = ctx.run.get_span(sid)
|
|
72
|
+
price = ctx.price(span)
|
|
73
|
+
if price is None:
|
|
74
|
+
priced = False
|
|
75
|
+
continue
|
|
76
|
+
inp, cached, _ = price.rates(span.input_tokens)
|
|
77
|
+
saving += n * (inp - cached) / 1_000_000
|
|
78
|
+
spans = sorted(flagged.values(), key=lambda s: s.start_ms) # type: ignore[attr-defined]
|
|
79
|
+
dynamic = "dynamic_prompt_head" in reasons
|
|
80
|
+
return [ctx.finding(
|
|
81
|
+
type=FindingType.COST,
|
|
82
|
+
severity=Severity.MEDIUM,
|
|
83
|
+
title=("Prompt caching is broken by text that changes at the start of the prompt"
|
|
84
|
+
if dynamic else "A long shared prompt prefix is never served from cache"),
|
|
85
|
+
detail=(f"Steps {ctx.steps(spans)} share about {max(stable_tokens.values()):,} tokens of "
|
|
86
|
+
"identical prompt, but 0 tokens were cached."
|
|
87
|
+
+ (" The first message differs only in its opening characters (a timestamp or ID?),"
|
|
88
|
+
" which stops prefix caching." if dynamic else "")),
|
|
89
|
+
suggestion=("Put stable content (system prompt, policies, tool definitions) first and move "
|
|
90
|
+
"anything that changes per call (time, user, IDs) to the end of the prompt."
|
|
91
|
+
if dynamic else
|
|
92
|
+
"Enable prompt caching with your provider and keep the shared prefix identical."),
|
|
93
|
+
evidence=spans,
|
|
94
|
+
wasted_tokens=sum(stable_tokens.values()),
|
|
95
|
+
wasted_cost_usd=saving if priced and saving else None,
|
|
96
|
+
data={"reasons": sorted(reasons), "kind": "prompt_cache_miss"},
|
|
97
|
+
)]
|