modeling_fix.py
16.4 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
"""AI 建模 ⑩ 按对账修改:对账发现的出入和遗漏,交给 AI 改进草案,改完再核对一次。
对账每一条有出入 / 漏了的,都带着「怎么修」(fix):
- modify:改某条草案(审批人不对、阈值不对、少一种情况)—— 走「一句话让 AI 改」,改完当场复验;
- add:缺一个元素(文档写了「解除…」,草案只有「标记…」)—— 先建成草案,再按种类补全(动作补参数和效果、规则写公式、指标写取数);
- sop:流程卡缺步骤 —— 按缺的条目让 AI 改流程卡(文档里的流程整张没起草的,就起草一张);
- watch:监控的条件、对象、通知人不对 —— 让 AI 改那条监控。
只动草案,不上线,所以流水线里自动跑一轮是安全的;页面上也能对单条或全部再跑。
每条改动记一条日志(改了什么、为什么),页面上能看到「AI 按对账改过」。
"""
from __future__ import annotations
import contextvars
import threading
from concurrent.futures import ThreadPoolExecutor
from typing import Any, Callable, Iterator
from fastapi import HTTPException
from ..core import llm
from ..core.dbx import iso, now
from . import modeling
MAX_FIXES = 10 # 一轮最多改几个目标(同一目标的几条合在一次改里)
def _todo(run_id: str, ids: list[str] | None) -> list[dict]:
"""要改的条目:漏了的排前面;同一个目标的几条合在一次改里,所以按「改几个目标」限量,不按条数。"""
chk = modeling._inputs(run_id).get("check") or {}
cand = [x for x in chk.get("items") or [] if x.get("status") in ("partial", "missing") and not x.get("ignored")
and (ids is None or x["id"] in ids) and (x.get("fix") or {}).get("type") not in ("", "none", None)]
cand.sort(key=lambda x: 0 if x["status"] == "missing" else 1)
out, targets = [], set()
for x in cand:
f = x.get("fix") or {}
t = (f.get("type"), f.get("target") or f.get("name") or x.get("process") or x["id"])
if t in targets or len(targets) < MAX_FIXES:
targets.add(t)
out.append(x)
return out
def _ask(x: dict) -> str:
fix = x.get("fix") or {}
bits = [fix.get("instruction") or x.get("gap") or x["text"]]
if x.get("doc_says") or x.get("quote"):
bits.append(f"文档原文:{x.get('doc_says') or x.get('quote')}")
if x.get("draft_has"):
bits.append(f"草案现在:{x['draft_has']}")
return ";".join(bits)
def run_fixes(run_id: str, ids: list[str] | None, note: Callable[[str], None]) -> dict:
from . import modeling_check, modeling_edit, modeling_grade, propose
todo = _todo(run_id, ids)
if not todo:
note("对账没有需要 AI 修改的条目")
return {"tried": 0, "ok": 0}
g = modeling.get(run_id)
items = {(it["payload"] or {}).get("name"): it for v in g["items"].values() for it in v if it["status"] == "pending"
and it["kind"] == "concept_create"}
sops = {s["title"]: s for s in g["sops"] if not s["current_version"] and s.get("status") != "archived"}
watches = {w["title"]: w for w in g["watches"] if w.get("status") == "pending"}
reqs = g.get("reqs") or []
logs: list[dict] = []
note(f"对账里 {len(todo)} 条要改:" + "、".join(f"{x['id']}" for x in todo))
def log(x: dict, kind: str, target: str, ok: bool, summary: str) -> None:
logs.append({"req_id": x["id"], "type": kind, "target": target, "ok": ok, "summary": summary[:300],
"instruction": _ask(x)[:300], "at": iso(now())})
note(f"{x['id']} {'改好了' if ok else '没改成'}:{target}({summary[:120]})")
def find(name: str, pool: dict) -> Any:
if not name:
return None
hit = modeling._match_fn(name, pool)
return hit
# 1. 改已有的草案:目标各不相同,可以同时改
edits = []
for x in todo:
fix = x.get("fix") or {}
t = fix.get("type")
# 要改的目标:先按 AI 写的名字找,找不到就看对账时它认的那几个元素(名字常常差几个字)
names = [fix.get("target") or "", *(x.get("by") or [])]
it = next((find(n, items) for n in names if find(n, items) is not None), None)
w = next((find(n, watches) for n in names if find(n, watches) is not None), None)
sp = next((find(n, sops) for n in names if find(n, sops) is not None), None)
if t == "modify" and it is not None:
edits.append((x, it))
elif t in ("modify", "watch") and w is not None:
x["fix"].update(type="watch", target=w["title"])
elif t in ("modify", "sop") and sp is not None:
x["fix"].update(type="sop", target=sp["title"])
elif t == "modify":
log(x, "modify", fix.get("target") or "", False, "没找到要改的草案,请人看一下")
by_target: dict[str, list[dict]] = {}
for x, it in edits:
by_target.setdefault(it["id"], []).append(x)
def edit_one(item_id: str) -> tuple[str, Any, str]:
xs = by_target[item_id]
try:
res = modeling_edit.ai_edit_item(run_id, item_id, ";".join(_ask(x) for x in xs), apply=True)
return item_id, res, ""
except HTTPException as e:
return item_id, None, str(e.detail)
except Exception as e: # noqa: BLE001
return item_id, None, str(e)[:200]
if by_target:
with ThreadPoolExecutor(max_workers=min(4, len(by_target))) as pool:
futs = [pool.submit(contextvars.copy_context().run, edit_one, iid) for iid in by_target]
for f in futs:
iid, res, err = f.result()
name = next((n for n, it in items.items() if it["id"] == iid), iid)
ok = bool(res) and res.get("applied", True)
for x in by_target[iid]:
log(x, "modify", name, ok, (res or {}).get("summary") or err or "")
if ok:
_mark_fixed(run_id, iid, [x["id"] for x in by_target[iid]], (res or {}).get("summary") or "")
# 2. 补漏掉的元素
for x in todo:
fix = x.get("fix") or {}
if fix.get("type") != "add":
continue
kind = fix.get("kind") or {"action": "action", "metric": "function", "rule": "function", "approval": "function",
"term": "function", "schedule": "watch"}.get(x["kind"], "")
name = (fix.get("name") or "").strip()
if kind == "watch" or x["kind"] == "schedule":
from . import modeling_schedule
made = modeling_schedule.add_one(run_id, x, note)
log(x, "watch", made or name or x["text"][:20], bool(made), "按这条要求配了一条监控" if made else "没配成")
continue
if kind not in ("action", "function") or not name:
log(x, "add", name or x["text"][:20], False, "这类缺口要人来补(新对象要先接入数据表)")
continue
if name in items:
log(x, "add", name, False, "草案里已经有同名的元素,改成按要求修改它")
continue
cat = {"metric": "aggregate", "approval": "decision"}.get(x["kind"], "rule")
obj = (fix.get("object") or "").strip()
spec = {"_stub": True, "text": _ask(x) + (f"(作用于「{obj}」)" if obj else "")} if kind == "action" else {"category": cat, "text": _ask(x), **({"object_type": obj} if obj else {})}
stats = propose.submit_proposals([{"kind": kind, "name": name, "synonyms": [], "description": fix.get("instruction") or x["text"],
"spec": spec, "req_ids": [x["id"]], "confidence": 0.6,
"evidence": [{"chunk_id": "", "doc_id": 0, "heading": x.get("section") or "",
"snippet": x.get("quote") or x["text"]}]}], modeling._source(run_id))
new = next((it for it in modeling._pending(run_id) if (it["payload"] or {}).get("name") == name), None)
if not stats.get("proposed") or new is None:
log(x, "add", name, False, "没建成草案(可能和已有元素重名)")
continue
if kind == "action":
done, _, _ = modeling._complete_actions(run_id, note, reqs, only={new["id"]})
elif cat == "aggregate":
done, _ = modeling._bind_metrics(run_id, note, only={new["id"]})
else:
done, _, _, _ = modeling._rules(run_id, note, only={new["id"]})
log(x, "add", name, bool(done), "建好了并补全" if done else "建了草案,但没补全,要人看一下")
if done:
_mark_fixed(run_id, new["id"], [x["id"]], "按对账新增")
# 3. 流程卡缺步骤 / 整张没起草
by_sop: dict[str, list[dict]] = {}
new_proc: dict[str, list[dict]] = {}
for x in todo:
fix = x.get("fix") or {}
if fix.get("type") != "sop":
continue
s = find(fix.get("target") or x.get("process") or "", sops)
if s is not None:
by_sop.setdefault(s["id"], []).append(x)
else:
new_proc.setdefault(x.get("process") or fix.get("target") or "未命名流程", []).append(x)
for sid, xs in by_sop.items():
title = next(t for t, s in sops.items() if s["id"] == sid)
steps = [r for r in reqs if r["id"] in {x["id"] for x in xs} and r["kind"] == "step"]
try:
res = modeling_edit.ai_edit_sop(run_id, sid, ";".join(_ask(x) for x in xs), extra_steps=steps)
for x in xs:
log(x, "sop", title, bool(res.get("changed")), res.get("summary") or "")
if res.get("changed"):
_cover(run_id, sid, [x["id"] for x in xs if x["kind"] == "step"])
except HTTPException as e:
for x in xs:
log(x, "sop", title, False, str(e.detail))
if new_proc:
inp = modeling._inputs(run_id)
chunks = modeling._doc_chunks(inp.get("doc_ids") or []) + (inp.get("chunks") or [])
for proc, xs in new_proc.items():
from . import modeling_reqs
must = modeling_reqs.steps_of(reqs, proc) or [r for r in reqs if r["id"] in {x["id"] for x in xs}]
made = modeling._sops(chunks, note, run_id, reqs, only=[{"title": proc, "section": xs[0].get("section") or "",
"owner_role": xs[0].get("role") or "", "schedule": "",
"chunks": [], "must": must}])
for x in xs:
log(x, "sop", proc, bool(made), "按文档起草了这张流程卡" if made else "没起草成")
# 4. 监控
for x in todo:
fix = x.get("fix") or {}
if fix.get("type") != "watch":
continue
w = find(fix.get("target") or "", watches)
if w is None:
log(x, "watch", fix.get("target") or "", False, "没找到这条监控;新的监控请重跑「定时与监控」")
continue
try:
res = modeling_edit.ai_edit_watch(run_id, w["id"], _ask(x), apply=True)
log(x, "watch", w["title"], True, res.get("summary") or "")
_watch_req(run_id, w["id"], x["id"])
except HTTPException as e:
log(x, "watch", w["title"], False, str(e.detail))
modeling._patch_inputs(run_id, lambda inp: inp.update(fixes=[*(inp.get("fixes") or []), *logs]))
modeling_grade.grade_all(run_id)
# 改过的条目再核对一次
again = list(dict.fromkeys(l["req_id"] for l in logs if l["ok"]))
if again:
try:
fresh = {x["id"]: x for x in modeling_check.verify(run_id, again)}
except Exception as e: # noqa: BLE001
fresh = {}
note(f"复核没做成:{str(e)[:100]}")
chk = modeling._inputs(run_id).get("check") or {}
merged = []
for x in chk.get("items") or []:
y = fresh.get(x["id"])
if y:
y = {**y, "fixed": next((l for l in reversed(logs) if l["req_id"] == x["id"]), None),
"before": {k: x.get(k) for k in ("status", "gap", "draft_has")}}
merged.append(y or x)
modeling_check.save(run_id, merged)
better = sum(1 for i in again if (fresh.get(i) or {}).get("status") in ("covered", "builtin"))
note(f"复核 {len(again)} 条:{better} 条已落实")
return {"tried": len(todo), "ok": sum(1 for l in logs if l["ok"])}
def _mark_fixed(run_id: str, item_id: str, req_ids: list[str], summary: str) -> None:
from ..governance import review
it = review.get(item_id)
if it is None or it["status"] != "pending":
return
p = dict(it["payload"] or {})
p["req_ids"] = list(dict.fromkeys([*(p.get("req_ids") or []), *req_ids]))
p["fix_log"] = [*(p.get("fix_log") or []), {"req_ids": req_ids, "summary": summary, "at": iso(now())}][-10:]
review.update_payload(item_id, p)
def _cover(run_id: str, sid: str, req_ids: list[str]) -> None:
"""流程卡按缺的步骤改过之后,把这几条记到它的覆盖里(复核再确认)。"""
def keep(inp: dict) -> None:
h = inp.setdefault("sop_hints", {}).setdefault(sid, {})
cov = h.setdefault("coverage", {"covers": {}, "total": 0, "covered": 0, "missing": []})
for r in req_ids:
cov.setdefault("covers", {})[r] = cov.get("covers", {}).get(r) or "(AI 按对账补的步骤)"
cov["missing"] = [r for r in cov.get("missing") or [] if r not in req_ids]
cov["covered"] = max(0, cov.get("total", 0) - len(cov["missing"]))
modeling._patch_inputs(run_id, keep)
def _watch_req(run_id: str, wid: str, req_id: str) -> None:
def keep(inp: dict) -> None:
for d in inp.get("watch_drafts") or []:
if d["id"] == wid:
d["req_ids"] = list(dict.fromkeys([*(d.get("req_ids") or []), req_id]))
modeling._patch_inputs(run_id, keep)
def stage(run_id: str, st: Any, ctx: dict) -> Iterator[dict]:
res = run_fixes(run_id, None, st.note("fix"))
st.set("fix", "done", f"对账要改的 {res['tried']} 条里,AI 改好了 {res['ok']} 条(只改草案,没有上线)" if res["tried"]
else "对账没有需要 AI 修改的条目", tried=res["tried"], fixed=res["ok"])
yield {"stage": "fix", "progress": 97, "message": f"按对账修改:{res['ok']} 条"}
def start(run_id: str, ids: list[str] | None) -> dict:
"""页面上点「让 AI 补上」:只跑这一步(后台),跑的时候运行记录是「运行中」,页面照常轮询看进度。"""
from ..core import envs, identity
r = modeling._load(run_id)
if r.status == "running":
raise HTTPException(409, "这次建模正在运行,等它跑完再改")
if not _todo(run_id, ids):
raise HTTPException(422, "选中的条目没有可以让 AI 修改的(要人拍板的、平台已有的不用改)")
k = modeling._k(run_id)
with modeling._lock:
if k in modeling._live:
raise HTTPException(409, "这次建模正在运行")
modeling._live.add(k)
st = modeling._Stages(run_id)
st.set("fix", "running", "手动:" + ("全部要处理的条目" if ids is None else "、".join(ids)))
modeling._finish(run_id, "running")
env, actor = envs.current(), identity.current()
model = (modeling.db.get_config("MODELING_MODEL") or "").strip()
def main() -> None:
t1, t2 = envs.set_current(env), identity.set_current(actor)
try:
with llm.use_model(model), llm.tracing(modeling._Calls(run_id, "fix"), "按对账修改"):
res = run_fixes(run_id, ids, st.note("fix"))
st.set("fix", "done", f"手动修改:{res['ok']}/{res['tried']} 条改好了")
modeling._finish(run_id, "done")
except BaseException as e: # noqa: BLE001
modeling.log.exception("按对账修改失败")
st.set("fix", "done", f"出错:{str(e)[:200]}")
modeling._finish(run_id, "done", "")
finally:
identity.reset(t2)
envs.reset(t1)
modeling._live.discard(k)
threading.Thread(target=main, name=f"modeling-fix-{run_id}", daemon=True).start()
return modeling._dict(modeling._load(run_id))
def ignore(run_id: str, req_id: str, ignored: bool) -> dict:
from . import modeling_check
chk = modeling._inputs(run_id).get("check") or {}
items = [{**x, "ignored": ignored} if x["id"] == req_id else x for x in chk.get("items") or []]
return modeling_check.save(run_id, items)