Coverage for mt_tools/ai_gaps.py: 95.50%
87 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 17:31 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 17:31 +0000
1"""What MT AI could not answer (SB-1308): not_found and ambiguous tool calls.
3Read from `ai_tool_calls` (SB-1197), which keeps each MT AI tool call with the
4arguments the model sent. A call's outcome is read the way mt-mcp's
5ToolCallObserver labels it: the tool's error kind when it reported one, else its
6own `status`. So a search_teams `not_found` that was really an outage
7(`error.kind = unavailable`) is an outage here too, not a gap.
9Calls are grouped by tool and query — the same name typed with different case or
10spacing is one gap — with counts and when it was last asked. The output feeds
11team aliases (a not_found name that is a real team), eval cases (ai-quality.md)
12and what tool to build next (mt2/mcp.md § Observability).
14Arguments can name minors: this is admin only, and argument values are never
15logged.
16"""
18import json
19from datetime import UTC, datetime, timedelta
20from typing import Any, Protocol
22import structlog
23from pydantic import BaseModel
25from mt_ai.tools.schemas import ToolError
27logger = structlog.get_logger()
29GAP_OUTCOMES = ("not_found", "ambiguous")
31DEFAULT_DAYS = 30
32MAX_DAYS = 365
33# A guard on how many gap calls one report reads; a report that hits it says so.
34MAX_ROWS = 5000
37class ToolCallSource(Protocol):
38 def gap_tool_calls( 38 ↛ exitline 38 didn't return from function 'gap_tool_calls' because
39 self, since: str, outcomes: tuple[str, ...], tool: str | None = None, max_rows: int = MAX_ROWS
40 ) -> list[dict[str, Any]]: ...
42 def count_tool_calls(self, since: str, tool: str | None = None) -> int: ... 42 ↛ exitline 42 didn't return from function 'count_tool_calls' because
45class AIGap(BaseModel):
46 tool: str
47 query: str # as most recently typed
48 age_groups: list[str] = []
49 count: int
50 not_found: int = 0
51 ambiguous: int = 0
52 first_seen: str | None = None
53 last_seen: str | None = None
56class AIGapsResult(BaseModel):
57 """`gaps` is [] when nothing went unanswered, and null only when the read failed.
59 `total_calls` is the denominator: every tool call in the window, any outcome.
60 """
62 gaps: list[AIGap] | None = None
63 count: int = 0
64 gap_calls: int = 0
65 total_calls: int | None = None
66 days: int = DEFAULT_DAYS
67 since: str | None = None
68 tool: str | None = None
69 truncated: bool = False
70 error: ToolError | None = None
73def call_outcome(row: dict[str, Any]) -> str | None:
74 """The error kind the tool reported, else its status (as ToolCallObserver labels it)."""
75 if row.get("error_kind"):
76 return str(row["error_kind"])
77 status = row.get("status")
78 if status is None and isinstance(row.get("result"), dict):
79 status = row["result"].get("status")
80 return str(status) if status else None
83def query_of(args: Any) -> str:
84 """The text that was looked up: `query` when the tool takes one, else every argument but the age group."""
85 if not isinstance(args, dict):
86 return ""
87 query = args.get("query")
88 if isinstance(query, str):
89 return " ".join(query.split())
90 rest = {k: v for k, v in args.items() if k != "age_group"}
91 return ", ".join(f"{k}={json.dumps(v, default=str)}" for k, v in sorted(rest.items()))
94def _key(query: str) -> str:
95 return query.casefold()
98def group_gaps(rows: list[dict[str, Any]]) -> list[AIGap]:
99 """not_found / ambiguous calls → one row per (tool, query), most asked first.
101 Other outcomes are skipped, so a caller may pass every call it has.
102 """
103 groups: dict[tuple[str, str], dict[str, Any]] = {}
104 for row in rows:
105 outcome = call_outcome(row)
106 if outcome not in GAP_OUTCOMES:
107 continue
108 tool = str(row.get("tool_name") or "unknown")
109 args = row.get("args") if isinstance(row.get("args"), dict) else {}
110 query = query_of(args)
111 seen = str(row["created_at"]) if row.get("created_at") is not None else None
112 group = groups.setdefault(
113 (tool, _key(query)),
114 {
115 "tool": tool,
116 "query": query,
117 "age_groups": [],
118 "count": 0,
119 "not_found": 0,
120 "ambiguous": 0,
121 "first_seen": seen,
122 "last_seen": seen,
123 },
124 )
125 group["count"] += 1
126 group[outcome] += 1
127 age_group = args.get("age_group")
128 if isinstance(age_group, str) and age_group.strip() and age_group.strip() not in group["age_groups"]:
129 group["age_groups"].append(age_group.strip())
130 if seen is not None: 130 ↛ 104line 130 didn't jump to line 104 because the condition on line 130 was always true
131 if group["first_seen"] is None or seen < group["first_seen"]: 131 ↛ 132line 131 didn't jump to line 132 because the condition on line 131 was never true
132 group["first_seen"] = seen
133 if group["last_seen"] is None or seen >= group["last_seen"]:
134 group["last_seen"] = seen
135 group["query"] = query # show the latest spelling
136 gaps = [AIGap(**g) for g in groups.values()]
137 gaps.sort(key=lambda g: g.last_seen or "", reverse=True)
138 gaps.sort(key=lambda g: g.count, reverse=True) # stable: ties stay newest first
139 return gaps
142def list_ai_gaps(
143 source: ToolCallSource, days: int = DEFAULT_DAYS, tool: str | None = None, now: datetime | None = None
144) -> AIGapsResult:
145 days = max(1, min(days, MAX_DAYS))
146 since = ((now or datetime.now(UTC)) - timedelta(days=days)).isoformat()
147 try:
148 rows = source.gap_tool_calls(since, GAP_OUTCOMES, tool=tool, max_rows=MAX_ROWS)
149 total = source.count_tool_calls(since, tool=tool)
150 except Exception:
151 logger.exception("list_ai_gaps failed", days=days)
152 return AIGapsResult(
153 days=days,
154 since=since,
155 tool=tool,
156 error=ToolError(kind="unavailable", message="The AI gap report is unavailable right now."),
157 )
158 gaps = group_gaps(rows)
159 return AIGapsResult(
160 gaps=gaps,
161 count=len(gaps),
162 gap_calls=sum(g.count for g in gaps),
163 total_calls=total,
164 days=days,
165 since=since,
166 tool=tool,
167 truncated=len(rows) >= MAX_ROWS,
168 )