Datasets:
Download scripts/prompt.py from YukiKaze1337/cn-sqlite-sft: direct link, hf CLI and curl.
- Browser
- Download file 2.84 kB
-
https://huggingface.co/datasets/YukiKaze1337/cn-sqlite-sft/resolve/main/scripts/prompt.py
- Command line
-
hf download hf://datasets/YukiKaze1337/cn-sqlite-sft/scripts/prompt.py
-
curl -L -o prompt.py https://huggingface.co/datasets/YukiKaze1337/cn-sqlite-sft/resolve/main/scripts/prompt.py
2.84 kB
| """训练和推理共用的一套 prompt,两边必须一模一样,不然分数都是假的。 | |
| 可以附上「部分字段的取值」:状态、等级、渠道这种分类字段,把库里实际有的值列出来, | |
| 模型照着抄,不用猜是写 '已完成' 还是 'completed'。推理时用 values_from_db() 从真实库里取; | |
| 不给也能用(训练时有两成样本不带),只是分类值要靠猜。 | |
| """ | |
| import re | |
| import sqlite3 | |
| SYSTEM = ( | |
| "你是 SQLite 查询专家。用户会给你建表语句和一句中文问题," | |
| "你要写出一条能回答它的 SQLite 查询。只输出 SQL,不要解释。" | |
| ) | |
| USER = """建表语句: | |
| {ddl} | |
| 问题:{question}""" | |
| USER_WITH_VALUES = """建表语句: | |
| {ddl} | |
| 部分字段的取值: | |
| {values} | |
| 问题:{question}""" | |
| DATE_LIKE = re.compile(r"^\d{4}-\d{2}(-\d{2})?") | |
| def build(ddl: str, question: str, values: dict[str, list[str]] | None = None) -> list[dict]: | |
| """values 形如 {"orders.status": ["已取消", "已完成"]},按给的顺序列出。""" | |
| if values: | |
| lines = "\n".join(f"- {col}:{'、'.join(vs)}" for col, vs in values.items()) | |
| user = USER_WITH_VALUES.format(ddl=ddl.strip(), values=lines, question=question.strip()) | |
| else: | |
| user = USER.format(ddl=ddl.strip(), question=question.strip()) | |
| return [ | |
| {"role": "system", "content": SYSTEM}, | |
| {"role": "user", "content": user}, | |
| ] | |
| def values_from_db(conns, max_distinct: int = 12) -> dict[str, list[str]]: | |
| """从库里找分类字段:文本列、不同值不超过 max_distinct 个、值有重复(不是名字、编号)、不是日期。 | |
| conns 可以是同一个库的几份数据,取并集。返回 {"表.列": [排好序的值]},表和列按建表顺序。""" | |
| if isinstance(conns, sqlite3.Connection): | |
| conns = [conns] | |
| out = {} | |
| tables = [t for (t,) in conns[0].execute( | |
| "select name from sqlite_master where type='table' and name not like 'sqlite_%' order by rowid")] | |
| for t in tables: | |
| for col in conns[0].execute(f'pragma table_info("{t}")').fetchall(): | |
| name, decl = col[1], (col[2] or "").upper() | |
| if decl and "TEXT" not in decl and "CHAR" not in decl: | |
| continue | |
| vals, rows = set(), 0 | |
| for c in conns: | |
| vals.update(v for (v,) in c.execute( | |
| f'select distinct "{name}" from "{t}" where "{name}" is not null limit {max_distinct + 1}')) | |
| rows += c.execute(f'select count("{name}") from "{t}"').fetchone()[0] | |
| if (not vals or len(vals) > max_distinct or len(vals) * 2 > rows | |
| or not all(isinstance(v, str) and not DATE_LIKE.match(v) for v in vals)): | |
| continue | |
| out[f"{t}.{name}"] = sorted(vals) | |
| return out | |