modeling_check.py
13.5 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
"""AI 建模 ⑨ 对账:文档条目(「列条目」那一步拆出来的)逐条对上这次的草案。
- 覆盖是确定性的:每个元素、流程卡步骤、监控都标了它落实了哪几条(req_ids / covers),没有元素认领的条目就是漏了;
- 一致性交给 AI 逐条核对:条目说的数字、阈值、角色、状态值,和元素的定义对不对得上。
有出入的要写清「文档要求 / 草案现在 / 差在哪」和「怎么修」,下一步「按对账修改」照着改;
- 草案里还不能用的元素(没公式、没补全、测试没过)会告诉对账,这种不能算已落实;
- 平台本来就有的(审批留痕、问数…)和不归本系统管的(业务数据的日常维护)标成「不用建模」,见 platform_caps。
「谁关心什么」的条目改写成业务人员会问的一句话,采纳上线后拿去问数里试问。
"""
from __future__ import annotations
import re
from typing import Any, Iterator
from ..core import llm
from ..governance import llmlog
from . import modeling, platform_caps
STATUSES = ("covered", "partial", "missing", "builtin", "na")
CHECK_PROMPT = """逐条核对:文档里的每一条要求,草案有没有落实、落实得对不对。
{caps}
【文档条目】(编号|类别|章节|内容|已标注落实它的草案元素)
{reqs}
【草案】(每个元素的定义;「还不能用」的写了原因)
{draft}
每条标 status:
- covered:有元素落实,而且意思一致(数字、阈值、角色、状态值、步骤都对得上)。
术语的意思就是业务表里某一列(对象属性的中文名对得上)时,算 covered,不用再建计算;
- partial:有对应元素但有出入。写清 doc_says(文档要求,照原意)、draft_has(草案现在是什么,具体到值)、
gap(差在哪,一句话,具体到字段 / 值 / 角色)。元素「还不能用」的也算 partial,gap 写它差什么;
- missing:草案里没有对应的元素或步骤;
- builtin:平台本来就有、或者不归本系统管,reason 写依据(对照上面两张清单)。尤其是:
数据什么时候更新、由谁录入 / 维护 / 盘点(「每天早上盘点更新」「由某角色维护」)是业务系统的事 → builtin,
除非文档要求在本系统里提供一个修改它的操作;审批要留痕、要能查询 → builtin;
- na:背景、目标这类不用落实的。
partial / missing 再给 fix:{{"type":"modify|add|sop|watch|none","target":"modify 时要改的元素名 / sop 时流程卡名 / watch 时监控名",
"kind":"add 时新元素的种类:action|function|object_type","name":"add 时新元素的名字(文档叫法)",
"object":"add 时新元素作用于哪类对象(指标统计的对象 / 动作改的对象,照抄草案里的对象名)",
"instruction":"一句话说清怎么改,具体到值(如:审批角色改成 X;补一个判断 Y 的步骤)"}};改不了的(要人拍板)type 写 none。
「谁关心什么」的条目:能用已建的元素回答就是 covered,question 写成业务人员会问的一句话(问数里能直接问)。
by 写落实它的草案元素名(照抄草案里的名字,不带「对象」「函数」这类前缀)。
doc_says / draft_has / gap 用自己的话写成一句中文,不要照抄草案里的符号和引号。
只输出 JSON:{{"items":[{{"id":"R01","status":"...","by":[],"doc_says":"","draft_has":"","gap":"","reason":"",
"fix":{{}},"question":""}}]}}"""
def _spec_line(kind: str, p: dict) -> str:
sp = p.get("spec") or {}
if kind == "object_type":
# 每个属性都列上(表里的列也算落实:术语对应现成的列,就不用再算一遍)
props = [f"{x['name']}({x.get('display_name') or ''})" + (f"={x['expression']}" if x.get("expression") else "")
+ ("[本系统保存]" if x.get("storage") == "ontology" else "")
+ (f"[{'/'.join(x['enum_values'])}]" if x.get("enum_values") else "")
for x in sp.get("properties") or []]
return ("属性:" + "、".join(props))[:900] if props else ""
if kind == "link_type":
return f"{sp.get('from_type')} → {sp.get('to_type')}({sp.get('cardinality')})"
if kind == "function":
cat = sp.get("category")
if cat == "aggregate":
mb = next((b for b in p.get("bindings") or [] if b.get("target_kind") == "metric_expr"), None)
return f"指标,口径:{sp.get('formula_text') or ''}" + (f";取数:{mb['ref'].get('expression')}" if mb else "")
if cat == "decision":
# 写成人话,不放 Python 的字典写法:AI 会把它原样抄进回答里,引号一乱 JSON 就坏了
def kv(d: Any, sep: str) -> str:
return ",".join(f"{k}{sep}{_plain(v)}" for k, v in (d or {}).items()) if isinstance(d, dict) else _plain(d)
rows = ";".join(f"当 {kv(r.get('when'), ' ') or '任意'} 时 {kv(r.get('then'), '=')}" for r in sp.get("rows") or [])
return f"决策表:{rows}"[:700]
return f"规则:{sp.get('expression') or '(没写成公式)'}"
if kind == "action":
if sp.get("_stub"):
return "动作(只有说明,参数和效果没补全)"
appr = sp.get("approval") or {}
who = (f"按决策表「{appr['decision']['function']}」" if (appr.get("decision") or {}).get("function")
else "、".join(r for s in appr.get("stages") or [] for r in s.get("approver_roles") or [])
or "、".join(appr.get("approver_roles") or []) or ("不用审批" if appr.get("mode") == "auto" else "有审批权限的人"))
eff = ";".join(f"{e.get('label') or e.get('tool')}" for e in sp.get("effects") or [])
return (f"动作,作用于 {sp.get('target_type') or '-'};参数 {[x.get('name') for x in sp.get('params') or []]};"
f"前置条件 {[c.get('expression') for c in sp.get('criteria') or []]};效果 {eff};审批:{who}")[:600]
return ""
def _plain(v: Any) -> str:
if isinstance(v, (list, tuple)):
return "/".join(_plain(x) for x in v)
if isinstance(v, bool):
return "是" if v else "否"
return str(v).replace('"', "").replace("'", "")
def jdump_short(v: Any) -> str:
from ..core.dbx import jdump
return jdump(v)[:200]
def _draft_text(g: dict) -> str:
lines = []
for kind, label in (("object_type", "对象"), ("link_type", "关系"), ("function", "函数"), ("action", "动作")):
for it in g["items"].get(kind) or []:
if it["status"] == "rejected":
continue
p = it["payload"] or {}
rd = it.get("readiness") or {}
miss = [c["text"] for c in rd.get("checks") or [] if c.get("must") and not c.get("ok")]
lines.append(f"- {label}「{p.get('name')}」:{(p.get('description') or '')[:60]} {_spec_line(kind, p)}"
+ (f"(还不能用:{';'.join(miss)[:120]})" if miss else ""))
for s in g["sops"]:
if s.get("status") == "archived":
continue
steps = "→".join(f"{o['title']}" for o in s.get("outline") or [] if o["kind"] != "end")[:600]
errs = (s.get("validation") or {}).get("errors") or []
lines.append(f"- 流程卡「{s['title']}」:{steps}" + (f"(还有 {len(errs)} 处错误)" if errs else ""))
from . import modeling_schedule
for w in g["watches"]:
if w.get("status") != "discarded":
lines.append(f"- 监控「{w['title']}」:{modeling_schedule.describe(w)}" + (f"(有问题:{w['issue']})" if w.get("issue") else ""))
return "\n".join(lines) or "(空)"
def _claims(g: dict) -> dict[str, list[str]]:
"""条目编号 → 标注了落实它的元素名(元素、对象的派生量、流程卡步骤、监控)。"""
out: dict[str, list[str]] = {}
def add(rid: str, name: str) -> None:
if name not in out.setdefault(str(rid), []):
out[str(rid)].append(name)
for v in g["items"].values():
for it in v:
p = it.get("payload") or {}
for rid in p.get("req_ids") or []:
add(rid, p.get("name") or "")
for d in p.get("derived") or []:
for rid in d.get("req_ids") or []:
add(rid, p.get("name") or "")
for s in g["sops"]:
for rid in ((s.get("coverage") or {}).get("covers") or {}):
add(rid, s["title"])
for w in g["watches"]:
for rid in w.get("req_ids") or []:
add(rid, w["title"])
return out
BATCH = 16 # 一次核对几条:条目多时分批同时核对,回答短、不容易写坏,也更快
def verify(run_id: str, ids: list[str] | None = None) -> list[dict]:
"""核对条目(ids 给了就只核对这几条)。返回核对结果,不落盘。"""
import contextvars
from concurrent.futures import ThreadPoolExecutor
g = modeling.get(run_id)
reqs = [r for r in g.get("reqs") or [] if not ids or r["id"] in ids]
if not reqs:
return []
claims = _claims(g)
draft = llm.truncate_to_tokens(_draft_text(g), 9000)
caps = platform_caps.text()
def one(batch: list[dict]) -> dict[str, dict]:
req_text = "\n".join(f"{r['id']}|{r['kind_label']}|{r['section']}|{r['text']}|"
f"{'、'.join(claims.get(r['id']) or []) or '(无)'}" for r in batch)
msg = CHECK_PROMPT.format(caps=caps, reqs=req_text, draft=draft)
for attempt in (1, 2): # 回答写坏了(JSON 解析不出来)就再问一次
with llmlog.feature("modeling_check"), llm.trace_label(
f"对账:{batch[0]['id']}~{batch[-1]['id']}" + ("(重问)" if attempt > 1 else "")):
res = llm.chat_json([{"role": "user", "content": msg}], temperature=0)
got_ = {str(x.get("id")): x for x in (res.get("items") or []) if isinstance(x, dict)} \
if isinstance(res, dict) else {}
if got_:
return got_
return {}
batches = [reqs[i:i + BATCH] for i in range(0, len(reqs), BATCH)]
got: dict[str, dict] = {}
with ThreadPoolExecutor(max_workers=min(4, len(batches))) as pool:
for part in pool.map(lambda b: contextvars.copy_context().run(one, b), batches):
got.update(part)
out = []
for r in reqs:
x = got.get(r["id"]) or {}
st = str(x.get("status") or "")
if st not in STATUSES:
st = "missing" if not claims.get(r["id"]) else "partial"
if r["kind"] == "background" and st in ("missing", "partial"):
st = "na"
fix = x.get("fix") if isinstance(x.get("fix"), dict) else {}
# AI 照着草案清单抄回来的是「对象「供应商」」这种带种类的写法:只留名字,页面上才能点过去
by = [re.sub(r"^[^「]*「(.+)」$", r"", str(b).strip()) for b in x.get("by") or claims.get(r["id"]) or []
if str(b).strip()][:6]
out.append({**r, "status": st, "by": by,
"doc_says": str(x.get("doc_says") or "")[:300], "draft_has": str(x.get("draft_has") or "")[:300],
"gap": str(x.get("gap") or "")[:300], "reason": str(x.get("reason") or "")[:200],
"fix": {k: str(fix.get(k) or "")[:300] for k in ("type", "target", "kind", "name", "object", "instruction")}
if st in ("partial", "missing") else {},
"question": str(x.get("question") or "")[:120] if r["kind"] == "concern" else ""})
return out
def summarize(items: list[dict]) -> dict:
return {k: sum(1 for x in items if x["status"] == k and not x.get("ignored")) for k in STATUSES}
def save(run_id: str, items: list[dict]) -> dict:
questions = [x["question"] for x in items if x.get("question")][:12]
chk = {"items": items, "summary": summarize(items), "questions": questions}
modeling._patch_inputs(run_id, lambda inp: inp.update(check=chk))
return chk
def stage(run_id: str, st: Any, ctx: dict) -> Iterator[dict]:
from . import modeling_grade, modeling_reqs
note = st.note("check")
if not ctx.get("reqs"):
try:
ctx["reqs"] = modeling_reqs.extract(ctx.get("chunks") or [])
modeling._patch_inputs(run_id, lambda inp: inp.update(reqs=ctx["reqs"]))
except Exception as e: # noqa: BLE001
st.set("check", "done", f"对账没做成:文档没拆成条目({str(e)[:100]})")
yield {"stage": "check", "progress": 94, "message": "对账:没做成"}
return
modeling_grade.grade_all(run_id) # 先体检:哪些元素还不能用,对账要知道
try:
items = verify(run_id)
except Exception as e: # noqa: BLE001
st.set("check", "done", f"对账没做成:{str(e)[:120]}")
yield {"stage": "check", "progress": 94, "message": "对账:没做成"}
return
chk = save(run_id, items)
sm = chk["summary"]
for x in items:
if x["status"] in ("partial", "missing"):
note(f"{'漏了' if x['status'] == 'missing' else '有出入'}:{x['id']} {x['text']}" + (f"({x['gap']})" if x.get("gap") else ""))
st.set("check", "done", f"文档 {len(items)} 条:落实 {sm['covered']}、有出入 {sm['partial']}、漏了 {sm['missing']}、"
f"平台已有或不归本系统 {sm['builtin']}", **sm)
yield {"stage": "check", "progress": 94, "message": f"对账:要处理 {sm['partial'] + sm['missing']} 条"}