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/agent.py ADDED
@@ -0,0 +1,239 @@
1
+ """The agent loop, as an explicit LangGraph state machine.
2
+
3
+ START → think → (tool calls?) → act → think → … → END
4
+
5
+ `think` asks the model what to do next. `act` runs whatever it asked for and
6
+ writes the result back as an observation. The loop is bounded by
7
+ `SQL_AGENT_MAX_STEPS`, because the failure mode of an unbounded agent is not a
8
+ wrong answer, it is a bill.
9
+
10
+ Nothing here is clever. The interesting behaviour comes from `tools.run_sql`
11
+ handing the database's own error text back to the model instead of raising.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import os
18
+ import time
19
+ from pathlib import Path
20
+ from typing import Annotated, Any, TypedDict
21
+
22
+ from langgraph.graph import END, START, StateGraph
23
+
24
+ from sql_agent.llm import LLM
25
+ from sql_agent.tools import SCHEMAS, Tools
26
+ from sql_agent.trace import Trace
27
+
28
+ SYSTEM_TEMPLATE = """You answer questions about a {engine} database by querying it.
29
+
30
+ Work like this:
31
+ 1. Look at what tables exist.
32
+ 2. Read the schema of the tables you intend to use, including the sample rows.
33
+ 3. Write one SELECT that answers the question, and run it.
34
+ 4. Call finish with the answer and the SQL behind it.
35
+
36
+ Rules that matter:
37
+ - Never assume a column exists. Check with describe_table first.
38
+ - If a query errors, read the error, fix the query, and try again. Errors are
39
+ information, not a reason to give up or to invent a result.
40
+ - The sample rows tell you how values are really stored. An INTEGER money
41
+ column is usually minor units — cents — so divide before reporting currency,
42
+ and dates are often plain ISO strings rather than a date type.
43
+ - You may only run one read-only SELECT or WITH statement per call.
44
+ - Never report a number you have not seen in a query result.
45
+ - If the question is ambiguous about what to include, state the choice you made
46
+ in your answer.
47
+
48
+ Answer in the language the question was asked in."""
49
+
50
+ #: The prompt used when nothing engine-specific is known.
51
+ SYSTEM = SYSTEM_TEMPLATE.format(engine="SQL")
52
+
53
+
54
+ def system_prompt(engine: str | None = None) -> str:
55
+ """The system prompt, naming the engine the agent is actually pointed at.
56
+
57
+ An agent told it is querying SQLite will write `strftime`; one told it is
58
+ querying PostgreSQL will write `date_trunc`. That is worth one word.
59
+ """
60
+ return SYSTEM_TEMPLATE.format(engine={
61
+ "sqlite": "SQLite",
62
+ "postgresql": "PostgreSQL",
63
+ }.get(engine or "", "SQL"))
64
+
65
+
66
+ class State(TypedDict):
67
+ messages: list[dict[str, Any]]
68
+ trace: Trace
69
+ done: bool
70
+
71
+
72
+ def _tool_result_message(call_id: str, name: str, result: dict[str, Any]) -> dict[str, Any]:
73
+ return {
74
+ "role": "tool",
75
+ "tool_call_id": call_id,
76
+ "name": name,
77
+ "content": json.dumps(result, ensure_ascii=False, default=str),
78
+ }
79
+
80
+
81
+ def build_graph(llm: LLM, tools: Tools, max_steps: int):
82
+ def think(state: State) -> dict[str, Any]:
83
+ trace = state["trace"]
84
+ reply = llm.chat(state["messages"], SCHEMAS)
85
+ msg = reply.message
86
+ calls = getattr(msg, "tool_calls", None) or []
87
+ summary = (
88
+ "→ " + ", ".join(c.function.name for c in calls) if calls
89
+ else (msg.content or "")[:70]
90
+ )
91
+ trace.add_model(llm.model, reply.latency_ms, reply.usage, summary)
92
+
93
+ # Normalise the assistant turn back into plain dicts, so the message
94
+ # list stays JSON-serialisable and provider-agnostic.
95
+ assistant: dict[str, Any] = {"role": "assistant", "content": msg.content or ""}
96
+ if calls:
97
+ assistant["tool_calls"] = [
98
+ {
99
+ "id": c.id,
100
+ "type": "function",
101
+ "function": {"name": c.function.name, "arguments": c.function.arguments},
102
+ }
103
+ for c in calls
104
+ ]
105
+ return {"messages": state["messages"] + [assistant]}
106
+
107
+ def act(state: State) -> dict[str, Any]:
108
+ trace = state["trace"]
109
+ messages = list(state["messages"])
110
+ calls = messages[-1].get("tool_calls", [])
111
+ done = False
112
+
113
+ for call in calls:
114
+ name = call["function"]["name"]
115
+ raw = call["function"].get("arguments") or "{}"
116
+ try:
117
+ arguments = json.loads(raw) if isinstance(raw, str) else raw
118
+ except json.JSONDecodeError as exc:
119
+ result = {"ok": False, "error": f"arguments were not valid JSON: {exc}"}
120
+ trace.add_tool(name, {"raw": str(raw)[:200]}, result, 0)
121
+ messages.append(_tool_result_message(call["id"], name, result))
122
+ continue
123
+
124
+ # Smaller models sometimes send a JSON array, or a bare string,
125
+ # where the schema asks for an object. That is a malformed call,
126
+ # not a crash: tell the model what shape it owes us and let it
127
+ # try again.
128
+ if not isinstance(arguments, dict):
129
+ result = {
130
+ "ok": False,
131
+ "error": (
132
+ f"arguments must be a JSON object, got "
133
+ f"{type(arguments).__name__}. Expected keys for {name}."
134
+ ),
135
+ }
136
+ trace.add_tool(name, {"raw": str(raw)[:200]}, result, 0)
137
+ messages.append(_tool_result_message(call["id"], name, result))
138
+ continue
139
+
140
+ t0 = time.perf_counter()
141
+ result = tools.call(name, arguments)
142
+ trace.add_tool(name, arguments, result, int((time.perf_counter() - t0) * 1000))
143
+ messages.append(_tool_result_message(call["id"], name, result))
144
+
145
+ if name == "finish" and result.get("ok"):
146
+ trace.answer = result.get("answer")
147
+ # Prefer SQL we actually executed over SQL the model typed into
148
+ # `finish`. Asked how many orders there were, the agent read the
149
+ # count off `list_tables` and then reported a SELECT it had
150
+ # never run — a right answer with fabricated evidence.
151
+ trace.claimed_sql = result.get("sql") or None
152
+ trace.final_sql = _last_successful_sql(trace)
153
+ trace.stopped_reason = "finished"
154
+ done = True
155
+
156
+ return {"messages": messages, "done": done}
157
+
158
+ def route_after_think(state: State) -> str:
159
+ last = state["messages"][-1]
160
+ if last.get("tool_calls"):
161
+ return "act"
162
+ # The model answered in prose without calling finish. Accept it rather
163
+ # than burning another turn, but record that it skipped the tool.
164
+ trace = state["trace"]
165
+ trace.answer = last.get("content") or ""
166
+ trace.final_sql = _last_successful_sql(trace)
167
+ trace.stopped_reason = "answered_without_finish"
168
+ return END
169
+
170
+ def route_after_act(state: State) -> str:
171
+ if state["done"]:
172
+ return END
173
+ if len(state["trace"].steps) >= max_steps:
174
+ trace = state["trace"]
175
+ trace.stopped_reason = "max_steps"
176
+ # Record the SQL that ran, even though the run never answered.
177
+ # This path used to leave `final_sql` empty, so a run that spent
178
+ # its budget reading the schema and then executed a perfectly good
179
+ # query was reported as having produced no SQL at all. The trace is
180
+ # the thing you debug from; it does not get to be wrong about what
181
+ # the database was asked. Whether an unanswered run counts as an
182
+ # answer is the grader's call, not the trace's — and it does not.
183
+ trace.final_sql = _last_successful_sql(trace)
184
+ return END
185
+ return "think"
186
+
187
+ graph = StateGraph(State)
188
+ graph.add_node("think", think)
189
+ graph.add_node("act", act)
190
+ graph.add_edge(START, "think")
191
+ graph.add_conditional_edges("think", route_after_think, {"act": "act", END: END})
192
+ graph.add_conditional_edges("act", route_after_act, {"think": "think", END: END})
193
+ return graph.compile()
194
+
195
+
196
+ def _last_successful_sql(trace: Trace) -> str | None:
197
+ for step in reversed(trace.steps):
198
+ if step.kind == "tool" and step.name == "run_sql" and step.ok:
199
+ return step.arguments.get("query")
200
+ return None
201
+
202
+
203
+ def ask(
204
+ question: str,
205
+ *,
206
+ db_path: Path | str | None = None,
207
+ dsn: str | None = None,
208
+ model: str | None = None,
209
+ max_steps: int | None = None,
210
+ llm: LLM | None = None,
211
+ tools: Tools | None = None,
212
+ ) -> Trace:
213
+ """Answer one question. Returns the trace; the answer is `trace.answer`.
214
+
215
+ `dsn` and `db_path` are the same knob under two names: a connection string
216
+ or a path to a SQLite file. With neither, `SQL_AGENT_DSN` decides.
217
+ """
218
+ max_steps = max_steps or int(os.getenv("SQL_AGENT_MAX_STEPS", "12"))
219
+ timeout_s = float(os.getenv("SQL_AGENT_SQL_TIMEOUT_S", "5"))
220
+ tools = tools or Tools(dsn or db_path, timeout_s=timeout_s)
221
+ llm = llm or LLM(model)
222
+
223
+ trace = Trace(question=question)
224
+ trace.engine = tools.engine
225
+ app = build_graph(llm, tools, max_steps)
226
+ app.invoke(
227
+ {
228
+ "messages": [
229
+ {"role": "system", "content": system_prompt(tools.engine)},
230
+ {"role": "user", "content": question},
231
+ ],
232
+ "trace": trace,
233
+ "done": False,
234
+ },
235
+ {"recursion_limit": max_steps * 2 + 4},
236
+ )
237
+ if trace.stopped_reason is None:
238
+ trace.stopped_reason = "max_steps"
239
+ return trace
sql_agent/cli.py ADDED
@@ -0,0 +1,122 @@
1
+ """Command line entry point."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import os
7
+ import sys
8
+
9
+ from dotenv import load_dotenv
10
+
11
+ from sql_agent import db
12
+ from sql_agent.adapters import ConfigError
13
+
14
+
15
+ def main(argv: list[str] | None = None) -> int:
16
+ load_dotenv()
17
+ parser = argparse.ArgumentParser(
18
+ prog="sql-agent",
19
+ description="Ask a question in plain language; the agent queries the database and shows its work.",
20
+ )
21
+ parser.add_argument("question", nargs="*", help="The question to answer.")
22
+ parser.add_argument(
23
+ "--dsn",
24
+ default=None,
25
+ help="Connection string, e.g. postgresql://user:pw@host/db or "
26
+ "sqlite:///./shop.db. Defaults to $SQL_AGENT_DSN.",
27
+ )
28
+ parser.add_argument(
29
+ "--db",
30
+ dest="db_path",
31
+ default=None,
32
+ help="Path to a SQLite file. Shorthand for --dsn sqlite:///<path>.",
33
+ )
34
+ parser.add_argument(
35
+ "--demo",
36
+ action="store_true",
37
+ help="Use the bundled sample database, building it if it is not there yet.",
38
+ )
39
+ parser.add_argument("--model", default=None, help="Override SQL_AGENT_MODEL.")
40
+ parser.add_argument("--max-steps", type=int, default=None, help="Hard cap on steps.")
41
+ parser.add_argument("--json", action="store_true", help="Print the trace as JSON.")
42
+ parser.add_argument("--save", action="store_true", help="Write the trace to traces/.")
43
+ parser.add_argument("--build-db", action="store_true", help="Rebuild the sample database and exit.")
44
+ args = parser.parse_args(argv)
45
+
46
+ if args.build_db:
47
+ path = db.build(args.db_path or db.DEFAULT_DB_PATH)
48
+ print(f"built {path}")
49
+ return 0
50
+
51
+ question = " ".join(args.question).strip()
52
+ if not question:
53
+ parser.error("give me a question, or use --build-db")
54
+
55
+ try:
56
+ target = _target(args)
57
+ except ConfigError as exc:
58
+ print(f"error: {exc}", file=sys.stderr)
59
+ return 2
60
+
61
+ from sql_agent.agent import ask # imported late so --build-db needs no API key
62
+
63
+ try:
64
+ trace = ask(
65
+ question,
66
+ dsn=target,
67
+ model=args.model,
68
+ max_steps=args.max_steps,
69
+ )
70
+ except (RuntimeError, ConfigError) as exc:
71
+ # Missing configuration is a user error, not a crash. No traceback.
72
+ print(f"error: {exc}", file=sys.stderr)
73
+ return 2
74
+
75
+ if args.json:
76
+ import json
77
+ print(json.dumps(trace.to_dict(), indent=2, ensure_ascii=False))
78
+ else:
79
+ print(trace.render())
80
+ print()
81
+ print(trace.answer or "(no answer)")
82
+ if trace.final_sql:
83
+ print()
84
+ print(trace.final_sql)
85
+
86
+ if args.save:
87
+ print(f"\ntrace → {trace.save()}")
88
+
89
+ return 0 if trace.stopped_reason in ("finished", "answered_without_finish") else 1
90
+
91
+
92
+ def _target(args: argparse.Namespace) -> str | None:
93
+ """Work out which database the user meant, and refuse to guess.
94
+
95
+ `--demo` is the only thing that may create a database, which is the whole
96
+ fix: a mistyped path used to silently build a fictional one and answer
97
+ questions about it.
98
+ """
99
+ given = [name for name, value in
100
+ (("--dsn", args.dsn), ("--db", args.db_path), ("--demo", args.demo))
101
+ if value]
102
+ if len(given) > 1:
103
+ raise ConfigError(f"pick one of {', '.join(given)}, not several")
104
+
105
+ if args.demo:
106
+ return str(db.ensure_demo())
107
+ if args.dsn:
108
+ return args.dsn
109
+ if args.db_path:
110
+ return args.db_path
111
+ if os.getenv("SQL_AGENT_DSN"):
112
+ return None # adapters.resolve reads it
113
+ if (os.getenv("SQL_AGENT_DEMO") or "").strip().lower() in ("1", "true", "yes", "on"):
114
+ return str(db.ensure_demo())
115
+ raise ConfigError(
116
+ "no database configured. Pass --dsn, --db, or --demo for the bundled "
117
+ "sample database; or set SQL_AGENT_DSN."
118
+ )
119
+
120
+
121
+ if __name__ == "__main__":
122
+ sys.exit(main())