Datasets:
File size: 4,910 Bytes
d847043 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | """给一个 SQLite 库和一句中文,返回 SQL 和查询结果。
python scripts/ask.py --db shop.sqlite --question "上个月线上渠道取消了多少单?"
python scripts/ask.py --db shop.sqlite # 不给问题就一行一行地问,空行退出
模型默认用 out/merged;只有 LoRA 的话:--model Qwen/Qwen3-4B-Instruct-2507 --adapter out/lora。
库以只读方式打开(mode=ro + query_only),模型写出 DELETE / UPDATE 也改不了数据。
默认 SQL 跑不通就把报错发回去改,最多 2 次;有 GPU 时再一次写 5 条按执行结果投票,没有 GPU 就只写 1 条。
第二轮模型在零售难题集上:直接生成 74%,出错重写 77%,投票加重写 82%(results/infer/summary.md)。
建表语句和「部分字段的取值」都从库里现读,和训练时的 prompt 格式一样(prompt.py)。
把握不够就不给结果,只说明原因(infer.confidence):投票时 5 条里少于 3 条结果一致,或者改完还跑不通。
在两个难题集上,这样会少答约两成的题,给出去的错答案从 41 题降到 17 题。--show-unsure 照样显示,标上「仅供参考」。
"""
import argparse
import sqlite3
import time
import eval as ev
from infer import Generator, answer, confidence
from prompt import build, values_from_db
def open_readonly(path: str) -> sqlite3.Connection:
conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
conn.execute("PRAGMA query_only = ON")
return conn
def schema_of(conn: sqlite3.Connection) -> str:
return "\n\n".join(sql + ";" for (sql,) in conn.execute(
"select sql from sqlite_master where type='table' and name not like 'sqlite_%' and sql is not null"))
def show(conn: sqlite3.Connection, sql: str, limit: int) -> None:
deadline = time.monotonic() + ev.QUERY_TIMEOUT
conn.set_progress_handler(lambda: time.monotonic() > deadline, 10_000)
try:
cur = conn.execute(sql)
rows = cur.fetchmany(limit + 1)
except sqlite3.Error as exc:
print("执行出错:", exc)
return
finally:
conn.set_progress_handler(None, 0)
print(" | ".join(d[0] for d in cur.description))
for r in rows[:limit]:
print(" | ".join("NULL" if v is None else str(v) for v in r))
print(f"(只显示前 {limit} 行)" if len(rows) > limit else f"共 {len(rows)} 行")
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--db", required=True, help="SQLite 库文件")
ap.add_argument("--question", default="")
ap.add_argument("--model", default="out/merged")
ap.add_argument("--adapter", default="")
ap.add_argument("--repair", type=int, default=2)
ap.add_argument("--vote", type=int, default=0, help="写几条投票;默认有 GPU 时 5 条,没有时 1 条(CPU 上写 5 条太慢)")
ap.add_argument("--no-values", action="store_true", help="prompt 里不附「部分字段的取值」")
ap.add_argument("--timeout", type=float, default=30.0, help="单条 SQL 最多跑几秒,大库调大")
ap.add_argument("--rows", type=int, default=20, help="最多显示几行结果")
ap.add_argument("--min-votes", type=int, default=3, help="投票时至少几条结果一致才给答案")
ap.add_argument("--show-unsure", action="store_true", help="没把握时也显示 SQL 和结果,标上「仅供参考」")
args = ap.parse_args()
ev.QUERY_TIMEOUT = args.timeout
conn = open_readonly(args.db)
ddl = schema_of(conn)
values = None if args.no_values else values_from_db(conn)
gen = Generator(args.model, adapter=args.adapter)
if args.vote <= 0:
args.vote = 5 if gen.torch.cuda.is_available() else 1
n_tokens = len(gen.tok.apply_chat_template(build(ddl, "?", values), tokenize=True))
if n_tokens > 3000:
print(f"注意:建表语句加取值有 {n_tokens} token,训练时最长的样本 2678 token,太长的库效果会变差")
questions = [args.question] if args.question else iter(lambda: input("\n问题:").strip(), "")
for q in questions:
out = answer(gen, [build(ddl, q, values)], [conn], repair=args.repair, vote=args.vote)[0]
report(conn, out, args.vote, args.min_votes, args.rows, args.show_unsure)
def report(conn: sqlite3.Connection, out: dict, vote: int, min_votes: int, limit: int, show_unsure: bool) -> None:
level, note = confidence(out, conn, vote, min_votes)
unsure = level in ("low", "failed")
print("\n" + note)
if unsure and not show_unsure:
return
print(("\nSQL(仅供参考):" if unsure else "\nSQL:") + (out["sql"] or "(模型没写出 SQL)"))
if out["repairs"]:
print(f"(第一次写的跑不通,改了 {out['repairs']} 次)")
if out["sql"] and level != "failed":
show(conn, out["sql"], limit)
if __name__ == "__main__":
main()
|