sql-agent-mcp 0.2.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.
sql_agent/evaluate.py ADDED
@@ -0,0 +1,324 @@
1
+ """Run a golden set and report, with no printing.
2
+
3
+ Scoring compares *result sets*, not text. The agent's final SQL and the
4
+ reference SQL both run against the same database; the case passes when they
5
+ return the same rows. Two correct queries almost never look alike, so grading
6
+ the SQL string would mostly measure style.
7
+
8
+ Alongside correctness it reports the things that decide whether an agent is
9
+ deployable: how many steps it took, how often it had to recover, how long it
10
+ took and what it cost.
11
+
12
+ This module is the engine. `evals/run_eval.py` is the command line around it
13
+ and `sql_agent.mcp_server` exposes it as an MCP tool, which is why nothing here
14
+ writes to stdout: an MCP server that prints on stdout corrupts its own
15
+ protocol.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from pathlib import Path
21
+ from typing import Any, Callable
22
+
23
+ import yaml
24
+
25
+ from sql_agent import sqlguard
26
+ from sql_agent.adapters import Adapter, ConfigError, QueryError, resolve
27
+ from sql_agent.tools import Tools
28
+
29
+ #: The grader runs queries itself, uncapped by the agent's 50-row view, but
30
+ #: not without a ceiling: a golden file is a file, and files have mistakes.
31
+ EVAL_MAX_ROWS = 10_000
32
+
33
+ def _default_golden() -> Path:
34
+ """The bundled golden set, in a checkout or installed from a wheel.
35
+
36
+ The file lives at evals/golden.yaml in the repository, and the wheel
37
+ force-includes a copy at sql_agent/data/golden.yaml, so there is one
38
+ source of truth and `evaluate` with no arguments works either way.
39
+ """
40
+ packaged = Path(__file__).with_name("data") / "golden.yaml"
41
+ if packaged.exists():
42
+ return packaged
43
+ return Path(__file__).resolve().parents[1] / "evals" / "golden.yaml"
44
+
45
+
46
+ DEFAULT_GOLDEN = _default_golden()
47
+
48
+ __all__ = [
49
+ "load_cases",
50
+ "matches",
51
+ "normalise",
52
+ "run_suite",
53
+ "DEFAULT_GOLDEN",
54
+ "EVAL_MAX_ROWS",
55
+ ]
56
+
57
+
58
+ # --------------------------------------------------------------------------
59
+ # grading
60
+
61
+
62
+ def normalise(rows: list[dict[str, Any]] | list[tuple]) -> list[tuple]:
63
+ """Compare by value, tolerating column aliases and float noise."""
64
+ out = []
65
+ for row in rows:
66
+ values = row.values() if isinstance(row, dict) else row
67
+ out.append(tuple(
68
+ round(v, 2) if isinstance(v, float) else v for v in values
69
+ ))
70
+ return out
71
+
72
+
73
+ def _contains_in_order(haystack: tuple, needle: tuple) -> bool:
74
+ """Is `needle` a subsequence of `haystack`?
75
+
76
+ The agent is free to select more columns than the reference does. Asking
77
+ for `name, spend` and getting back `id, name, gross, refunds, spend` is a
78
+ cosmetic difference, not a wrong answer.
79
+ """
80
+ it = iter(haystack)
81
+ return all(any(value == h for h in it) for value in needle)
82
+
83
+
84
+ def matches(expected: list[tuple], actual: list[tuple], *, ordered: bool) -> bool:
85
+ """Does the agent's result carry the reference's answer?
86
+
87
+ Two rules that cost a round of false failures to learn:
88
+
89
+ * **Row order is only compared when the question asked for an order.**
90
+ "Revenue per category" has no canonical order, so grading on it measures
91
+ nothing. "Top 5 customers" does, so there it is part of the answer.
92
+ * **Extra columns are allowed.** Only the reference's values have to be
93
+ present, in order, within each row.
94
+ """
95
+ if len(expected) != len(actual):
96
+ return False
97
+ if ordered:
98
+ return all(_contains_in_order(a, e) for e, a in zip(expected, actual))
99
+ remaining = list(actual)
100
+ for row in expected:
101
+ for i, candidate in enumerate(remaining):
102
+ if _contains_in_order(candidate, row):
103
+ remaining.pop(i)
104
+ break
105
+ else:
106
+ return False
107
+ return True
108
+
109
+
110
+ # --------------------------------------------------------------------------
111
+ # cases
112
+
113
+
114
+ def load_cases(path: Path | str | None = None) -> list[dict[str, Any]]:
115
+ """Read a golden file and check its shape before anything runs.
116
+
117
+ A broken golden file should fail here, with the case id in the message,
118
+ rather than halfway through a paid evaluation.
119
+ """
120
+ path = Path(path) if path else DEFAULT_GOLDEN
121
+ if not path.exists():
122
+ raise ConfigError(f"no golden set at {path}")
123
+ try:
124
+ loaded = yaml.safe_load(path.read_text(encoding="utf-8"))
125
+ except yaml.YAMLError as exc:
126
+ raise ConfigError(f"{path} is not valid YAML: {exc}") from exc
127
+
128
+ if not isinstance(loaded, list) or not loaded:
129
+ raise ConfigError(f"{path} should be a non-empty list of cases")
130
+
131
+ seen: set[str] = set()
132
+ for i, case in enumerate(loaded, start=1):
133
+ if not isinstance(case, dict):
134
+ raise ConfigError(f"{path}: case {i} is not a mapping")
135
+ for key in ("id", "question", "reference_sql"):
136
+ if not str(case.get(key) or "").strip():
137
+ raise ConfigError(f"{path}: case {i} has no {key}")
138
+ if case["id"] in seen:
139
+ raise ConfigError(f"{path}: duplicate case id {case['id']!r}")
140
+ seen.add(case["id"])
141
+ return loaded
142
+
143
+
144
+ # --------------------------------------------------------------------------
145
+ # running
146
+
147
+
148
+ def _run_query(adapter: Adapter, query: str) -> tuple[list[tuple] | None, str | None]:
149
+ """Run one query for grading. Returns (rows, error)."""
150
+ refused = sqlguard.check(query, dialect=adapter.dialect)
151
+ if refused:
152
+ # Holds for the reference queries too. A golden file is input, and the
153
+ # grader executes what it finds there, so it gets the same guard the
154
+ # agent does.
155
+ return None, refused
156
+ try:
157
+ return normalise(adapter.select(query, EVAL_MAX_ROWS)), None
158
+ except (QueryError, ConfigError) as exc:
159
+ return None, str(exc)
160
+ except Exception as exc: # pragma: no cover - defensive
161
+ return None, f"{type(exc).__name__}: {exc}"
162
+
163
+
164
+ def run_suite(
165
+ golden_path: Path | str | None = None,
166
+ *,
167
+ target: str | Path | None = None,
168
+ only: str | None = None,
169
+ timeout_s: float = 5.0,
170
+ max_steps: int | None = None,
171
+ model: str | None = None,
172
+ llm: Any = None,
173
+ on_case: Callable[[dict[str, Any]], None] | None = None,
174
+ ) -> dict[str, Any]:
175
+ """Run every case and return the report. Never prints.
176
+
177
+ `on_case` is called with each case's result as it lands, which is how the
178
+ command line shows progress without this module knowing about a terminal.
179
+ """
180
+ from sql_agent.agent import ask
181
+ from sql_agent.llm import LLM
182
+
183
+ cases = load_cases(golden_path)
184
+ if only:
185
+ cases = [c for c in cases if c["id"] == only]
186
+ if not cases:
187
+ raise ConfigError(f"no case with id {only!r}")
188
+
189
+ adapter = resolve(target, timeout_s=timeout_s)
190
+ adapter.check()
191
+ tools = Tools(adapter=adapter, timeout_s=timeout_s)
192
+ # One model client for the whole suite, built before any case runs: a
193
+ # missing API key should stop the run now, not three cases in.
194
+ llm = llm or LLM(model)
195
+
196
+ results: list[dict[str, Any]] = []
197
+ for case in cases:
198
+ expected, ref_error = _run_query(adapter, case["reference_sql"])
199
+ if ref_error is not None:
200
+ result = {
201
+ "id": case["id"],
202
+ "question": case["question"],
203
+ "traps": case.get("traps", []),
204
+ "ambiguous": bool(case.get("ambiguous", False)),
205
+ "passed": False,
206
+ "reason": f"the reference query itself is broken — {ref_error}",
207
+ "bad_reference": True,
208
+ }
209
+ results.append(result)
210
+ if on_case:
211
+ on_case(result)
212
+ continue
213
+
214
+ trace = ask(
215
+ case["question"],
216
+ tools=tools,
217
+ model=model,
218
+ max_steps=max_steps,
219
+ llm=llm,
220
+ )
221
+
222
+ actual, agent_error = None, "the agent produced no SQL that ran"
223
+ if trace.final_sql:
224
+ actual, agent_error = _run_query(adapter, trace.final_sql)
225
+
226
+ ordered = bool(case.get("ordered", False))
227
+ passed = actual is not None and matches(expected, actual, ordered=ordered)
228
+
229
+ # A run that spent its step budget without ever answering does not get
230
+ # credit for the last query it happened to execute. It may well have
231
+ # been the right one — three cases in the first 34-case run got that
232
+ # far — but an agent that never commits to an answer has not answered,
233
+ # and crediting the query would be the same mistake as crediting SQL
234
+ # the model typed into `finish` without running it.
235
+ if trace.stopped_reason == "max_steps" and not trace.answer:
236
+ passed = False
237
+ agent_error = (
238
+ f"stopped on the step budget ({len(trace.steps)} steps) without "
239
+ "answering"
240
+ )
241
+
242
+ result = {
243
+ "id": case["id"],
244
+ "question": case["question"],
245
+ "traps": case.get("traps", []),
246
+ "ambiguous": bool(case.get("ambiguous", False)),
247
+ "passed": passed,
248
+ "reason": None if passed else (agent_error or "result mismatch"),
249
+ "steps": len(trace.steps),
250
+ "tool_path": trace.tool_path,
251
+ "recoveries": trace.recoveries,
252
+ "latency_ms": trace.latency_ms,
253
+ "cost_usd": trace.cost_usd,
254
+ "stopped_reason": trace.stopped_reason,
255
+ "agent_sql": trace.final_sql,
256
+ "claimed_sql": trace.claimed_sql,
257
+ "sql_was_executed": bool(trace.final_sql),
258
+ "expected_rows": len(expected),
259
+ "actual_rows": None if actual is None else len(actual),
260
+ }
261
+ results.append(result)
262
+ if on_case:
263
+ on_case(result)
264
+
265
+ return {
266
+ "summary": _summarise(results, adapter=adapter, golden_path=golden_path),
267
+ "cases": results,
268
+ "failures": [
269
+ {
270
+ "id": r["id"],
271
+ "question": r["question"],
272
+ "reason": r["reason"],
273
+ "traps": r["traps"],
274
+ "ambiguous": r["ambiguous"],
275
+ "agent_sql": r.get("agent_sql"),
276
+ "tool_path": r.get("tool_path"),
277
+ }
278
+ for r in results if not r["passed"]
279
+ ],
280
+ }
281
+
282
+
283
+ def _summarise(
284
+ results: list[dict[str, Any]],
285
+ *,
286
+ adapter: Adapter,
287
+ golden_path: Path | str | None,
288
+ ) -> dict[str, Any]:
289
+ total = len(results)
290
+ passed = sum(1 for r in results if r["passed"])
291
+ graded = [r for r in results if not r.get("bad_reference")]
292
+
293
+ def mean(key: str) -> float:
294
+ values = [r.get(key, 0) or 0 for r in graded]
295
+ return round(sum(values) / len(values), 1) if values else 0.0
296
+
297
+ # Ambiguous cases are reported apart from the headline number. A question
298
+ # with two defensible readings says less about the agent than about the
299
+ # question, and burying it in the accuracy hides both.
300
+ ambiguous = [r for r in results if r["ambiguous"]]
301
+ unambiguous = [r for r in results if not r["ambiguous"]]
302
+
303
+ return {
304
+ "engine": adapter.name,
305
+ "database": adapter.label,
306
+ "golden_path": str(golden_path or DEFAULT_GOLDEN),
307
+ "passed": passed,
308
+ "total": total,
309
+ "accuracy": round(passed / total, 3) if total else 0.0,
310
+ "accuracy_unambiguous": (
311
+ round(sum(1 for r in unambiguous if r["passed"]) / len(unambiguous), 3)
312
+ if unambiguous else 0.0
313
+ ),
314
+ "unambiguous_total": len(unambiguous),
315
+ "ambiguous_total": len(ambiguous),
316
+ "ambiguous_passed": sum(1 for r in ambiguous if r["passed"]),
317
+ "recovery_rate": round(
318
+ sum(1 for r in graded if r.get("recoveries", 0) > 0) / len(graded), 3
319
+ ) if graded else 0.0,
320
+ "avg_steps": mean("steps"),
321
+ "total_cost_usd": round(sum(r.get("cost_usd", 0) or 0 for r in results), 4),
322
+ "total_latency_ms": sum(r.get("latency_ms", 0) or 0 for r in results),
323
+ "broken_references": sum(1 for r in results if r.get("bad_reference")),
324
+ }
sql_agent/llm.py ADDED
@@ -0,0 +1,58 @@
1
+ """Thin wrapper over any OpenAI-compatible chat endpoint.
2
+
3
+ Deliberately not tied to one vendor: `OPENAI_BASE_URL` points at DeepInfra,
4
+ Together, Groq, OpenAI itself or a local server. The agent only needs tool
5
+ calling, which all of them speak the same way.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import time
12
+ from dataclasses import dataclass
13
+ from typing import Any
14
+
15
+ from openai import OpenAI
16
+
17
+ DEFAULT_MODEL = "deepseek-ai/DeepSeek-V3"
18
+
19
+
20
+ @dataclass
21
+ class Reply:
22
+ message: Any # the raw assistant message
23
+ usage: Any # token usage, or None
24
+ latency_ms: int
25
+
26
+
27
+ class LLM:
28
+ def __init__(self, model: str | None = None, *, client: Any = None):
29
+ self.model = model or os.getenv("SQL_AGENT_MODEL", DEFAULT_MODEL)
30
+ if client is not None:
31
+ self.client = client
32
+ return
33
+ api_key = os.getenv("OPENAI_API_KEY")
34
+ if not api_key:
35
+ raise RuntimeError(
36
+ "OPENAI_API_KEY is not set. Copy .env.example to .env and fill it in, "
37
+ "or export the variable."
38
+ )
39
+ self.client = OpenAI(
40
+ api_key=api_key,
41
+ base_url=os.getenv("OPENAI_BASE_URL") or None,
42
+ )
43
+
44
+ def chat(self, messages: list[dict[str, Any]], tools: list[dict[str, Any]]) -> Reply:
45
+ t0 = time.perf_counter()
46
+ resp = self.client.chat.completions.create(
47
+ model=self.model,
48
+ messages=messages,
49
+ tools=tools,
50
+ tool_choice="auto",
51
+ temperature=0,
52
+ )
53
+ latency_ms = int((time.perf_counter() - t0) * 1000)
54
+ return Reply(
55
+ message=resp.choices[0].message,
56
+ usage=getattr(resp, "usage", None),
57
+ latency_ms=latency_ms,
58
+ )