propose.py
17.2 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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
"""AI 提议本体:从文档、从数据源。所有提议都进审核队列,人采纳后才落成概念。
- 文档:按段落分批喂给 LLM,让它按元模型(schema.KINDS)找对象类型、指标、规则、日历、角色、流程……
每条提议都带出处 chunk,采纳后成为概念的证据。
- 数据源:内省出来的表 / 指标 / 关联是确定性的,直接翻译成对象类型 + 绑定、指标 + 绑定、关系类型。
- 与已有概念同名:说法一致就只补证据;规则/日历的定义不一致则提「知识冲突」让人裁决。
"""
from __future__ import annotations
import logging
from typing import Iterator
from ..core import llm
from ..governance import llmlog, review
from . import schema, service
log = logging.getLogger(__name__)
BATCH_TOKENS = 3200
PROPOSE_SYSTEM = """你是一名本体(Ontology)建模专家。你的任务是从业务文档里识别出可以建模的业务概念,
按下面的元模型输出。只输出文档里**明确出现或明确定义**的概念,不要臆造,不要输出通用词(系统、数据、功能、信息)。
概念类别(kind)与 spec 字段:
- object_type 对象类型:业务里可被指认、有属性的实体类别。spec: {"properties":[{"name":属性名,"data_type":"string|number|date|enum|boolean","is_key":bool,"enum_values":[...]}]}
- link_type 关系类型:两个对象类型之间的关系。spec: {"from_type":对象类型名,"to_type":对象类型名,"cardinality":"1:1|1:n|n:1|n:n"}
- metric 指标:可量化的度量。spec: {"unit":单位,"direction":"higher_better|lower_better|neutral","calibre_rule":口径规则名,"calendar":统计周期名,"formula_text":文字版计算公式}
- rule 规则:口径/判定/计算规则。spec: {"rule_kind":"judgement|calibre|calculation","params":[英文变量名],"expression":"用这些变量写的 Python 风格表达式,如 actual >= target;写不出就留空","text":规则原文要点}
- calendar 统计周期:spec: {"start_day":1-31,"start_month_offset":整数,"end_day":1-31或"last","end_month_offset":整数,"applies_when":适用条件,"text":原文要点}
例:「上月 26 日至本月 25 日」→ start_day=26,start_month_offset=-1,end_day=25,end_month_offset=0
- role 角色:岗位、职责主体。spec: {"responsibilities":职责}
- process 流程:业务流程。spec: {"roles":[参与角色名]}
- term 术语:业务术语/缩写,指向另一个概念。spec: {"refers_to":被指向的概念名}
类别判定要点(最容易错的地方):
- 凡是统计周期 / 时间窗口(自然月、财务月、执行期、对照期、T-1 等),一律 calendar,不要用 term。
- 凡是可以算出一个数的度量(量、率、额、系数、差额、单价),一律 metric —— 即使文中给了计算公式;
公式写进 spec.formula_text,计算规则另提一条 rule。
- rule 只用于判定条件、计算方法、口径约定、例外处理(如「X 为 0 时用 Y 替代」「不参与赔付」)。
- 业务流程(核算、同步、导入、跟踪、评估这类有先后步骤的事)一律 process,不要用 term。
- 可被指认、有属性、会有多个实例的东西(组织、对象、单据、批次、人员)一律 object_type。
- term 只用于缩写、统称、别称(如「四界」指四个子品牌),并在 spec.refers_to 写它指向谁。
输出严格 JSON:
{"concepts":[{"kind":..., "name":规范名称, "synonyms":[文中出现的其他叫法], "description":一句话定义,
"spec":{...}, "evidence":[出处片段编号,如 "d1:c3"], "confidence":0~1}]}
"""
PROPOSE_USER = """已存在的概念(不要重复提议,除非你发现了新的别名或定义):
{existing}
文档片段:
{text}
"""
def _existing_names(limit: int = 300) -> str:
items = service.list_concepts(limit=limit)
if not items:
return "(暂无)"
return "、".join(f"{c['name']}({c['kind_label']})" for c in items)
def _batches(chunks: list[dict]) -> list[list[dict]]:
out: list[list[dict]] = []
cur: list[dict] = []
size = 0
for c in chunks:
t = llm.count_tokens(c.get("text", ""))
if cur and size + t > BATCH_TOKENS:
out.append(cur)
cur, size = [], 0
cur.append(c)
size += t
if cur:
out.append(cur)
return out
def _merge(bucket: dict, item: dict, chunk_map: dict[str, dict]) -> None:
kind = item.get("kind")
name = str(item.get("name") or "").strip()
if kind not in schema.KINDS or not name or len(name) > 60:
return
key = (kind, name)
ev = []
for cid in item.get("evidence") or []:
ch = chunk_map.get(str(cid))
if ch:
ev.append({"chunk_id": ch["id"], "doc_id": ch.get("doc_id", 0),
"heading": ch.get("heading", ""), "snippet": ch.get("text", "")[:400]})
cur = bucket.get(key)
if cur is None:
bucket[key] = {"kind": kind, "name": name, "synonyms": list(item.get("synonyms") or []),
"description": str(item.get("description") or ""),
"spec": item.get("spec") if isinstance(item.get("spec"), dict) else {},
"evidence": ev, "confidence": float(item.get("confidence") or 0.6)}
return
for s in item.get("synonyms") or []:
if s not in cur["synonyms"]:
cur["synonyms"].append(s)
if len(str(item.get("description") or "")) > len(cur["description"]):
cur["description"] = str(item["description"])
if isinstance(item.get("spec"), dict):
for k, v in item["spec"].items():
if v not in (None, "", [], {}) and not cur["spec"].get(k):
cur["spec"][k] = v
have = {e["chunk_id"] for e in cur["evidence"]}
cur["evidence"] += [e for e in ev if e["chunk_id"] not in have]
cur["confidence"] = max(cur["confidence"], float(item.get("confidence") or 0))
def _definition(kind: str, spec: dict) -> str:
if kind == "rule":
return str(spec.get("expression") or "").replace(" ", "")
if kind == "calendar":
return f"{spec.get('start_day')}/{spec.get('start_month_offset')}-{spec.get('end_day')}/{spec.get('end_month_offset')}"
return ""
def submit_proposals(proposals: list[dict], source: str) -> dict:
"""把一批提议送进审核队列(或补证据 / 提冲突)。返回计数。"""
created = conflicts = enriched = 0
for p in proposals:
try:
spec = schema.normalize_spec(p["kind"], p.get("spec") or {})
except schema.SpecError:
spec = {}
p["spec"] = spec
existing = service.find(p["name"], p["kind"])
if existing:
old_def = _definition(p["kind"], existing.get("spec") or {})
new_def = _definition(p["kind"], spec)
if old_def and new_def and old_def != new_def:
review.propose("conflict", f"「{p['name']}」的定义存在冲突", {
"concept_id": existing["id"], "kind": p["kind"],
"current": {"spec": existing.get("spec"), "description": existing.get("description")},
"proposed": {"spec": spec, "description": p.get("description")},
"evidence": p.get("evidence") or []},
source=source, confidence=p.get("confidence", 0.5), target_ref=existing["id"])
conflicts += 1
else:
if p.get("evidence"):
service.add_evidence(existing["id"], p["evidence"])
new_syn = [s for s in p.get("synonyms") or []
if s not in (existing.get("synonyms") or []) and s != existing["name"]]
if new_syn:
review.propose("concept_update", f"为「{existing['name']}」补充别名", {
"concept_id": existing["id"],
"synonyms": list(existing.get("synonyms") or []) + new_syn},
source=source, confidence=p.get("confidence", 0.5),
target_ref=existing["id"])
enriched += 1
continue
title = f"{schema.KINDS[p['kind']]['label']}「{p['name']}」"
review.propose("concept_create", title, p, source=source,
confidence=p.get("confidence", 0.6), target_ref=f"{p['kind']}:{p['name']}")
created += 1
return {"proposed": created, "conflicts": conflicts, "enriched": enriched}
def from_documents(chunks: list[dict]) -> Iterator[dict]:
"""后台任务:分批让 LLM 提议概念。yield 进度事件,最后一条带统计。"""
chunks = [c for c in chunks if (c.get("text") or "").strip()]
if not chunks:
yield {"stage": "error", "error": "没有可用的文档片段,请先上传并抽取文档"}
return
batches = _batches(chunks)
chunk_map = {c["id"]: c for c in chunks}
bucket: dict = {}
yield {"stage": "propose", "message": f"共 {len(chunks)} 个片段,分 {len(batches)} 批", "progress": 2}
existing = _existing_names()
with llmlog.feature("ontology_propose"):
for i, batch in enumerate(batches, 1):
text = "\n\n".join(f"[{c['id']}]【{c.get('heading') or '正文'}】\n{c['text']}" for c in batch)
try:
res = llm.chat_json([{"role": "system", "content": PROPOSE_SYSTEM},
{"role": "user", "content": PROPOSE_USER.format(
existing=existing, text=text)}])
except Exception as e: # noqa: BLE001
yield {"stage": "propose", "message": f"第 {i} 批失败:{str(e)[:200]}",
"progress": int(i / len(batches) * 90)}
continue
items = res.get("concepts") if isinstance(res, dict) else res
for it in items or []:
if isinstance(it, dict):
_merge(bucket, it, chunk_map)
yield {"stage": "propose", "message": f"第 {i}/{len(batches)} 批,累计 {len(bucket)} 个候选",
"progress": int(i / len(batches) * 90)}
stats = submit_proposals(list(bucket.values()), "extract")
yield {"stage": "done", "progress": 100,
"message": f"提议 {stats['proposed']} 个新概念,{stats['conflicts']} 个冲突,"
f"{stats['enriched']} 个已有概念补充了出处", "result": stats}
def from_datasource(ds_id: int) -> dict:
"""把内省好的语义模型翻译成本体提议:表→对象类型、指标→指标、关联→关系类型。"""
from ..text2sql import semantic
models = semantic.models_with_columns(ds_id, enabled_only=True)
proposals: list[dict] = []
by_id = {m["id"]: m for m in models}
for m in models:
cols = m.get("columns") or []
phys = {c["name"]: (c.get("physical_column") or c["name"]) for c in cols}
key = m.get("primary_key") or next((c["name"] for c in cols if c["name"].lower() == "id"), "")
if not key:
continue
label_col = next((c["name"] for c in cols if any(
t in c["name"].lower() for t in ("name", "title", "label"))), "")
props = []
for c in cols[:40]:
dt_ = "number" if c.get("is_measure") or any(
t in (c.get("data_type") or "").lower() for t in ("int", "dec", "double", "float")) \
else "date" if "date" in (c.get("data_type") or "").lower() or "time" in (c.get("data_type") or "").lower() \
else "string"
props.append({"name": c["name"], "display_name": (c.get("description") or "")[:40],
"data_type": dt_, "is_key": c["name"] == key,
"description": c.get("description") or ""})
name = (m.get("description") or "").split(",")[0].split("。")[0][:30] or m["name"]
proposals.append({
"kind": "object_type", "name": name, "synonyms": [m["name"]] if name != m["name"] else [],
"description": m.get("description") or "",
"spec": {"properties": props, "label_property": label_col},
"bindings": [{"ds_id": ds_id, "target_kind": "table",
"ref": {"table": m["physical_table"] or m["name"],
"key_column": phys.get(key, key),
"label_column": phys.get(label_col, label_col),
"columns": {p["name"]: phys.get(p["name"], p["name"])
for p in props}}}],
"confidence": 0.8})
for mt in semantic.list_metrics(ds_id, enabled_only=True):
base = by_id.get(mt.get("base_model_id"))
if not base or not mt.get("expression"):
continue
proposals.append({
"kind": "metric", "name": mt.get("display_name") or mt["name"],
"synonyms": list(mt.get("synonyms") or []) + ([mt["name"]] if mt.get("display_name") else []),
"description": mt.get("description") or "",
"spec": {"formula_text": mt.get("calibre_note") or ""},
"bindings": [{"ds_id": ds_id, "target_kind": "metric_expr",
"ref": {"base_table": base["physical_table"] or base["name"],
"expression": mt["expression"],
"time_column": mt.get("time_column") or base.get("time_column") or "",
"filters": [f for f in (mt.get("filters") or [])
if isinstance(f, str)],
"dimensions": {d: d for d in (mt.get("allowed_dimensions") or [])}}}],
"confidence": 0.85})
return submit_proposals(proposals, "introspect")
# ---------------- 审核处理器 ----------------
def _resolve_refs(kind: str, spec: dict) -> dict:
"""spec 里按名称引用的概念,能找到的换成 id(找不到保留名称,运行时仍可按名称解析)。"""
ref_fields = {"metric": [("calibre_rule", "rule"), ("calendar", "calendar"), ("object_type", "object_type")],
"link_type": [("from_type", "object_type"), ("to_type", "object_type")],
"dimension": [("object_type", "object_type")],
"term": [("refers_to", None)]}
for field, k in ref_fields.get(kind, []):
v = spec.get(field)
if v and not str(v).startswith(("obj_", "rul_", "cal_", "met_")):
found = service.find(str(v), k)
if found:
spec[field] = found["id"]
return spec
def _accept_create(payload: dict, item: dict) -> dict:
kind = payload["kind"]
# 提议之后,别的提议可能已经被采纳、并把这个名字当成了别名(如「二级品牌」带别名「品牌」)。
# 这时合并进已有概念(补别名与出处),而不是让采纳失败。
existing = service.find(payload["name"], kind)
if existing:
syn = list(dict.fromkeys([*(existing.get("synonyms") or []), payload["name"],
*(payload.get("synonyms") or [])]))
syn = [s for s in syn if s != existing["name"]]
service.update_concept(existing["id"], synonyms=syn)
if payload.get("evidence"):
service.add_evidence(existing["id"], payload["evidence"])
return {"concept_id": existing["id"], "name": existing["name"], "merged": True}
spec = _resolve_refs(kind, dict(payload.get("spec") or {}))
c = service.create_concept(kind, payload["name"], display_name=payload.get("display_name", ""),
description=payload.get("description", ""),
synonyms=payload.get("synonyms"), spec=spec,
origin=item.get("source") or "ai",
evidence=payload.get("evidence"),
bindings=payload.get("bindings"))
return {"concept_id": c["id"], "name": c["name"]}
def _accept_update(payload: dict, item: dict) -> dict:
cid = payload["concept_id"]
fields = {k: payload[k] for k in ("name", "display_name", "description", "synonyms", "spec")
if k in payload}
c = service.update_concept(cid, **fields)
return {"concept_id": cid, "name": c["name"]}
def _accept_conflict(payload: dict, item: dict) -> dict:
"""冲突采纳 = 用提议的定义覆盖;驳回 = 保留现有定义。payload.choice 可显式选 current。"""
cid = payload["concept_id"]
if payload.get("choice") == "current":
return {"concept_id": cid, "kept": "current"}
prop = payload.get("proposed") or {}
c = service.update_concept(cid, spec=prop.get("spec"),
description=prop.get("description") or None)
if payload.get("evidence"):
service.add_evidence(cid, payload["evidence"])
return {"concept_id": cid, "kept": "proposed", "name": c["name"]}
def _accept_binding(payload: dict, item: dict) -> dict:
b = service.set_binding(payload["concept_id"], int(payload.get("ds_id") or 0),
payload["target_kind"], payload.get("ref") or {})
return {"binding_id": b["id"]}
review.register_handler("concept_create", _accept_create)
review.register_handler("concept_update", _accept_update)
review.register_handler("conflict", _accept_conflict)
review.register_handler("binding", _accept_binding)