linker.py
8.97 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
"""问题 → 语义对象召回。
P0 用的是**纯词法打分**(jieba 切词 + 字段加权),不碰向量、不打网络。
这样做有两个好处:内省完立刻就能问,不用等建索引;单测也不用 mock embedding。
P1 会把这里换成两级混合召回(`sm_models` 选表 → `sm_columns` 拉列 → rerank),
换的时候只要保持 `retrieve()` 的返回结构不变,管线和前端都不用动 ——
所以这个函数的签名是这一层唯一要守住的契约。
"""
from __future__ import annotations
import logging
import re
import jieba
from ..core import db as core_db
from ..core import llm
from . import library, semantic
log = logging.getLogger(__name__)
jieba.setLogLevel(logging.WARNING)
# 业务问句里的高频虚词,参与打分只会制造噪声
_STOP = {"的", "了", "是", "在", "有", "和", "与", "我", "请", "帮", "查", "看", "下",
"一下", "多少", "什么", "哪些", "怎么", "各", "每", "个", "们", "吗", "呢",
"统计", "分析", "数据", "情况", "select", "from", "where", "a", "an", "the", "of"}
def _tok(text: str) -> list[str]:
toks = [w.strip().lower() for w in jieba.lcut(text or "") if w.strip()]
return [w for w in toks if w not in _STOP and not re.fullmatch(r"[\W_]+", w)]
def _score(terms: list[str], text: str, weight: float = 1.0) -> float:
"""命中一个词记一分,长词多记一点 —— 「生态系数」比「门店」更有区分度。"""
if not text:
return 0.0
low = text.lower()
hit = 0.0
for t in terms:
if t and t in low:
hit += weight * (1.0 + 0.3 * min(len(t), 6))
return hit
def retrieve(ds_id: int, question: str, overrides: dict | None = None) -> dict:
"""返回要送进提示词的一切,以及给 trace 展示的命中明细。
结构(P1 换实现时必须保持一致):
{models, relations, metrics, pairs, instructions, flags, hits}
"""
cfg = core_db.get_all_config()
cfg.update({k: str(v) for k, v in (overrides or {}).items()})
top_models = int(cfg.get("SQL_TOP_K_MODEL") or "6")
top_pairs = int(cfg.get("SQL_TOP_K_PAIR") or "3")
budget = int(cfg.get("SQL_CONTEXT_BUDGET") or "8000")
terms = _tok(question)
all_models = semantic.models_with_columns(ds_id, enabled_only=True)
# ---- 先匹配指标 ----
# 指标要在选表之前算:问句里出现「渗透率」时,真正该用的是那个指标的基表,
# 而基表的表名/列名未必含「渗透率」三个字。靠指标把基表顶上来,比纯字面打分准得多。
# 只取「表达式里引用的列都还可用」的指标。引用了全空列的指标必须挡在提示词外面,
# 否则内省做的全空列停用就被绕过去了(实测踩过:交付目标达成率的分母整列是 NULL)。
metrics_all, broken_metrics = semantic.usable_metrics(ds_id)
metric_score: dict[int, float] = {}
for mt in metrics_all:
s = (_score(terms, mt["name"], 3.0) + _score(terms, mt["display_name"], 3.0)
+ _score(terms, "、".join(mt["synonyms"]), 2.5)
+ _score(terms, mt["description"], 1.0))
if s > 0:
metric_score[mt["id"]] = s
base_boost: dict[int, float] = {}
for mt in metrics_all:
s = metric_score.get(mt["id"], 0.0)
if s > 0 and mt["base_model_id"]:
base_boost[mt["base_model_id"]] = base_boost.get(mt["base_model_id"], 0.0) + s * 2.0
# ---- 第一级:选表 ----
scored: list[tuple[float, dict]] = []
for m in all_models:
s = _score(terms, m["name"], 3.0) + _score(terms, m["description"], 2.0)
s += base_boost.get(m["id"], 0.0)
for c in m["columns"]:
s += _score(terms, c["name"], 1.0)
s += _score(terms, c["description"], 1.2)
s += _score(terms, "、".join(c["synonyms"]), 1.5)
# 样例值命中权重最高:问句里出现「问界」而某列的取值里正好有「问界」,
# 这是比列名匹配强得多的信号
s += _score(terms, "、".join(str(v) for v in c["sample_values"]), 2.0)
scored.append((s, m))
scored.sort(key=lambda x: -x[0])
# 刻意**不**只保留命中的表:选错表answer 直接废,而多给几张表只是多花点 token。
# 所以按分数取前 N 张全送进去,真放不下再由下面的预算裁剪按相关度砍列。
# 启用的表本来就是人工挑过的,数量可控,这个取舍在十几张表的规模上明显划算。
hit_models = [m for _, m in scored][:top_models]
chosen_ids = {m["id"] for m in hit_models}
# ---- 关系:只保留两端都在选中集合里的 ----
relations = [r for r in semantic.list_relations(ds_id, enabled_only=True)
if r["from_model_id"] in chosen_ids and r["to_model_id"] in chosen_ids]
# ---- 指标:命中的 + 基表在候选里的 ----
# 基表被选中就把指标带上,是为了让模型看见口径定义(口径是这套业务最容易错的地方)。
# 指标条目很短,十几个也就几百 token,给全比漏掉划算。
metrics = [mt for mt in metrics_all
if metric_score.get(mt["id"], 0) > 0 or mt["base_model_id"] in chosen_ids]
metrics.sort(key=lambda mt: -metric_score.get(mt["id"], 0.0))
# ---- few-shot:只从已采纳的问答对里取 ----
pairs = []
for p in library.verified_pairs(ds_id):
s = _score(terms, p["question"], 1.0)
if s > 0:
pairs.append((s, p))
pairs.sort(key=lambda x: -x[0])
top_pair_rows = [p for _, p in pairs[:top_pairs]]
# ---- 指令:is_default 无条件进,其余按条件文本匹配 ----
instructions = []
for ins in semantic.list_instructions(ds_id, scope="sql"):
if ins["is_default"] or _score(terms, ins["condition_text"], 1.0) > 0:
instructions.append(ins)
# ---- token 预算:超了就砍列,不砍表 ----
# 砍表会直接让答案错;砍掉明显不相关的列只是少点信息,模型还能靠剩下的写对。
dropped_columns = _trim_columns(hit_models, terms, budget)
flags = {
"has_metric": bool(metrics),
"has_calculated_field": any(c["is_calculated"] for m in hit_models for c in m["columns"]),
"has_sample_values": any(c["sample_values"] for m in hit_models for c in m["columns"]),
}
hits = {
"models": [{"id": m["id"], "name": m["name"], "table": m["physical_table"],
"score": round(s, 2), "columns": len(m["columns"])}
for s, m in scored if m["id"] in chosen_ids],
"metrics": [{"id": mt["id"], "name": mt["name"],
"calibre": mt["calibre_note"]} for mt in metrics],
"relations": [{"id": r["id"], "condition": r["condition_sql"]} for r in relations],
"pairs": [{"id": p["id"], "question": p["question"],
"score": round(s, 2)} for s, p in pairs[:top_pairs]],
"instructions": [{"id": i["id"], "content": i["content"],
"is_default": i["is_default"]} for i in instructions],
"dropped_columns": dropped_columns,
"broken_metrics": broken_metrics,
"terms": terms,
}
return {"models": hit_models, "relations": relations, "metrics": metrics,
"pairs": top_pair_rows, "instructions": instructions,
"flags": flags, "hits": hits}
def _trim_columns(models: list[dict], terms: list[str], budget: int) -> int:
"""超预算时按相关度砍列。
两个关键点:
- **从最不相关的表开始砍**。`models` 是按相关度降序排好的,所以倒着走;
正着走会先把最该保留的那张表削秃。
- 主键、时间列、以及命中了问句词的列永远保留 —— 砍掉主键会直接让模型没法写 JOIN。
"""
if llm.count_tokens(semantic.render_schema(models)) <= budget:
return 0
def col_score(c: dict) -> float:
return (_score(terms, c["name"], 1.0) + _score(terms, c["description"], 1.0)
+ _score(terms, "、".join(c.get("synonyms") or []), 1.5)
+ _score(terms, "、".join(str(v) for v in c["sample_values"]), 1.5))
dropped = 0
for m in reversed(models): # 相关度最低的先削
keep_always = {c.strip().lower() for c in (m.get("primary_key") or "").split(",") if c.strip()}
if m.get("time_column"):
keep_always.add(m["time_column"].lower())
order = {id(c): i for i, c in enumerate(m["columns"])}
ranked = sorted(m["columns"], key=lambda c: -col_score(c))
kept: list[dict] = []
for c in ranked:
name = (c["physical_column"] or c["name"]).lower()
if name in keep_always or col_score(c) > 0 or len(kept) < 8:
kept.append(c)
else:
dropped += 1
m["columns"] = sorted(kept, key=lambda c: order.get(id(c), 0))
if llm.count_tokens(semantic.render_schema(models)) <= budget:
break
return dropped