grounding.py
10.3 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
196
197
198
199
"""把本体「喂」给提问:大模型看见的是业务语言(对象、属性、关系),不只是物理表名。
以前提问链路里本体只进了两处:命中的函数名,以及问句里恰好点到的概念(每个 80 字描述)。
对象类型有哪些属性、属性的中文名、对象之间怎么关联 —— 这些建模时花最多力气的东西,
在「提问」里从来没用上;自由 SQL 那一路更是完全绕开本体,只看另一套 sm_* 表结构说明。
这里提供四样东西,都只读已发布版本:
- digest():本体结构摘要(对象 + 关键属性 + 关系),进主 Agent 与问数路由的提示词;
- sql_overlay(ds_id):给自由 SQL 的伪 DDL 加注「这张表是哪个对象、这一列是哪个属性」,
并把本体里的关系(join 绑定)并进允许的关联路径;
- ask_scope(ds_id):模型写的 SQL 能碰哪些表、列、关联 —— 只有本空间已发布绑定覆盖到的;
- scope_sql(ds_id, sql):按当前用户的数据范围改写 SQL。以前只有指标路和对象查询做了范围过滤,
自由 SQL 路直接查全表 —— 限定了「只看华南仓」的人,换个问法就能看到全部。
"""
from __future__ import annotations
import logging
from . import service as ksvc
log = logging.getLogger(__name__)
def _tables_by_type(ds_id: int | None = None) -> dict[str, dict]:
"""对象类型 id → {concept, table, ref}(只取绑定了表的)。"""
out = {}
for ot in ksvc.rt_by_kind("object_type"):
b = ksvc.rt_binding(ot, "table", ds_id)
if b and (b.get("ref") or {}).get("table"):
out[ot["id"]] = {"concept": ot, "table": b["ref"]["table"], "ref": b["ref"], "ds_id": b["ds_id"]}
return out
def _type_of(ref: str) -> dict | None:
return ksvc.rt_find(ref, "object_type") if ref else None
def digest(limit_chars: int = 1800) -> str:
"""本体结构摘要:对象(主键 + 最多 8 个属性,带中文名 / 单位 / 可选值)与关系(A —关系→ B)。"""
lines: list[str] = []
for ot in ksvc.rt_by_kind("object_type"):
spec = ot.get("spec") or {}
props = []
# 主键、计算出来的状态和量(「超时」「缺口」这类问得最多)、有别名 / 常见取值的排在前面
ranked = sorted(spec.get("properties") or [], key=lambda p: (
0 if p.get("is_key") else 1 if p.get("expression") else 2 if (p.get("synonyms") or p.get("value_hints")) else 3))
for p in ranked[:10]:
label = p["name"] + (f"({p['display_name']})" if p.get("display_name") else "")
tags = [t for t, on in (("主键", p.get("is_key")), ("维度", p.get("is_dimension")),
("时间", p.get("is_time")), ("算出来的", p.get("expression"))) if on]
if p.get("enum_values"):
tags.append("取值 " + "/".join(p["enum_values"][:5]))
if p.get("synonyms"):
tags.append("这一类记录叫 " + "/".join(p["synonyms"][:3]))
if p.get("value_hints"):
tags.append("例如 " + "/".join(p["value_hints"][:3]))
props.append(label + (f"[{','.join(tags)}]" if tags else ""))
desc = (ot.get("description") or "")[:30]
lines.append(f"- 对象「{ot['name']}」{(':' + desc) if desc else ''} 属性:{'、'.join(props) or '(未定义)'}")
for lt in ksvc.rt_by_kind("link_type"):
spec = lt.get("spec") or {}
a, b = _type_of(spec.get("from_type") or ""), _type_of(spec.get("to_type") or "")
if not a or not b:
continue
lines.append(f"- 关系「{lt['name']}」:{a['name']} → {b['name']}({spec.get('cardinality') or 'n:1'})"
+ (f",反过来叫「{spec['inverse_name']}」" if spec.get("inverse_name") else ""))
text = "\n".join(lines)
if len(text) > limit_chars:
text = text[:limit_chars].rsplit("\n", 1)[0] + "\n- ……(其余略,可用 list_ontology_types / lookup_concept 查)"
return text or "(还没有已发布的对象)"
def sql_overlay(ds_id: int) -> dict:
"""{tables: {表名小写: {concept, cols: {列名小写: 属性说明}}}, joins: [{from, to, name}]}。"""
tables: dict[str, dict] = {}
by_type = _tables_by_type(ds_id)
for tid, t in by_type.items():
ot, ref = t["concept"], t["ref"]
props = {p["name"]: p for p in (ot.get("spec") or {}).get("properties") or []}
cols = {}
for prop, col in (ref.get("columns") or {}).items():
p = props.get(prop) or {}
label = prop + (f"({p['display_name']})" if p.get("display_name") else "")
cols[str(col).lower()] = f"本体属性:{ot['name']}.{label}"
if ref.get("key_column"):
cols.setdefault(str(ref["key_column"]).lower(), f"本体属性:{ot['name']} 的主键")
tables[t["table"].lower()] = {"concept": ot["name"], "cols": cols}
joins = []
for lt in ksvc.rt_by_kind("link_type"):
spec = lt.get("spec") or {}
b = ksvc.rt_binding(lt, "join", ds_id)
a_ot, b_ot = _type_of(spec.get("from_type") or ""), _type_of(spec.get("to_type") or "")
if not b or not a_ot or not b_ot or a_ot["id"] not in by_type or b_ot["id"] not in by_type:
continue
ref = b.get("ref") or {}
if not ref.get("from_column") or not ref.get("to_column"):
continue
joins.append({"from": f"{by_type[a_ot['id']]['table']}.{ref['from_column']}".lower(),
"to": f"{by_type[b_ot['id']]['table']}.{ref['to_column']}".lower(),
"name": f"{a_ot['name']} —{lt['name']}→ {b_ot['name']}"})
return {"tables": tables, "joins": joins}
def ask_scope(ds_id: int) -> tuple[set[str], dict[str, set[str]], set[str]]:
"""(允许的物理表, {表: 列集合}, 允许的 JOIN 键),全部小写:模型写的(或人手改的)SQL 的可查范围。
范围由本空间**已发布**的绑定推导:对象绑定的表、指标的基表;关联只认关系的 join 绑定
(外加共同维度闭包)。数据源可以跨空间共享,所以不能再用「表结构」页的启用开关表达
「对提问开放」—— 那样在一个空间里启用一张表,就把它暴露给了所有空间。
"""
from ..text2sql import semantic
_, cat_cols = semantic.catalog_context(ds_id, usable_columns_only=True)
overlay = sql_overlay(ds_id)
tables = set(overlay["tables"])
for m in ksvc.rt_by_kind("function", "aggregate"):
b = ksvc.rt_binding(m, "metric_expr", ds_id)
base = ((b or {}).get("ref") or {}).get("base_table")
if base:
tables.add(str(base).lower())
tables -= semantic.system_tables()
columns = {t: cat_cols[t] for t in tables if t in cat_cols}
joins = semantic.conformed_joins([(j["from"], j["to"]) for j in overlay["joins"]])
return tables, columns, joins
def scope_sql(ds_id: int, sql: str, dialect: str = "mysql") -> str:
"""按当前用户的数据范围改写 SQL:受限对象的表替换成「带范围条件的子查询」,别名不变。
没有范围限制时原样返回;改写失败时拒绝执行(宁可不给数,也不越权给数)。"""
from ..core import identity
from .objects import _scope_where
scope = identity.current().scope or {}
if not scope:
return sql
restricted: dict[str, list[str]] = {}
for tid, t in _tables_by_type(ds_id).items():
if tid not in scope:
continue
conds = [c.replace("t.`", "`", 1) for c in _scope_where(t["concept"], t["ref"])]
if conds:
restricted[t["table"].lower()] = conds
if not restricted:
return sql
import sqlglot
from sqlglot import exp
try:
tree = sqlglot.parse_one(sql, dialect=dialect)
except Exception as e: # noqa: BLE001
raise ValueError(f"无法按数据范围改写这条 SQL:{e}") from e
ctes = {c.alias_or_name.lower() for c in tree.find_all(exp.CTE)}
for tbl in list(tree.find_all(exp.Table)):
name = tbl.name.lower()
if name in ctes or name not in restricted:
continue
alias = tbl.alias_or_name
base = exp.Table(this=tbl.this.copy(), db=tbl.args["db"].copy() if tbl.args.get("db") else None)
# 范围条件是按 MySQL 引号拼的(sqlutil.ident / lit),按 mysql 读进来,输出时再转成目标方言
cond = sqlglot.condition(" AND ".join("(" + c + ")" for c in restricted[name]), dialect="mysql")
sub = exp.select("*").from_(base).where(cond)
tbl.replace(exp.Subquery(this=sub, alias=exp.TableAlias(this=exp.to_identifier(alias))))
return tree.sql(dialect=dialect)
def used_concepts(results: list[dict]) -> list[dict]:
"""从一轮提问里各工具的结果中,摘出**实际执行过**的本体元素(而不是问句里匹配到的)。"""
seen: dict[str, dict] = {}
def add(name: str, kind: str, how: str) -> None:
if not name:
return
c = ksvc.rt_find(name)
if c is None and kind == "口径": # 自由 SQL 路的「取数口径」只是一段说明,不是本体里的元素
return
key = (c or {}).get("id") or f"{kind}:{name}"
if key not in seen:
seen[key] = {"id": (c or {}).get("id", ""), "name": (c or {}).get("name") or name,
"kind_label": (c or {}).get("kind_label") or kind, "how": how}
for r in results or []:
if not isinstance(r, dict):
continue
m = r.get("metric")
if isinstance(m, dict) and m.get("name"):
add(m["name"], "指标", "取数")
calibre = r.get("calibre")
if isinstance(calibre, dict) and calibre.get("name"):
add(calibre["name"], "口径", "口径")
for k, how in (("rule", "规则求值"), ("table", "决策表"), ("function", "函数")):
v = r.get(k)
if isinstance(v, str):
add(v, how, how)
elif isinstance(v, dict) and v.get("name"):
add(v["name"], how, how)
c = r.get("concept")
if isinstance(c, dict) and c.get("name"):
add(c["name"], c.get("kind_label") or "概念", "查定义")
if r.get("type_name"):
add(r["type_name"], "对象", "查对象")
return list(seen.values())