modeling_edit.py 18.6 KB
"""AI 建模:采纳之前就地改草案。

AI 已经起草了大部分内容,差的往往只是一个审批人、一个阈值、一行决策表 —— 以前只能先采纳上线、再去各个编辑器里改。
现在两种改法,改完都当场复验(规整、测试用例、在真实数据上试算),结果写回草案,体检清单跟着更新:
- 表单直接改:前端把改好的定义整块交回来(save_*);
- 一句话让 AI 改:「审批人改成 X」「再加一个判断 Y 的分支」—— AI 只改提到的地方,
  先返回改前 / 改后给人看,人点「用这个」才保存(ai_edit_* 不落盘)。
「按对账修改」也走这里的 AI 改法(apply=True 直接保存)。
"""
from __future__ import annotations

import copy
from fastapi import HTTPException

from ..core import llm
from ..core.dbx import jdump
from ..governance import llmlog, review
from . import modeling, modeling_grade, modeling_world, schema

EDITABLE = ("name", "description", "synonyms", "spec", "bindings")


def _item(run_id: str, item_id: str) -> dict:
    it = review.get(item_id)
    if it is None or it["source"] != modeling._source(run_id) or it["kind"] != "concept_create":
        raise HTTPException(404, "草案不属于这次建模")
    if it["status"] != "pending":
        raise HTTPException(409, "这条草案已经处理过了(采纳或不要),请到对应的编辑器里改")
    return it


def check_payload(run_id: str, p: dict, new_props: list[dict] | None = None) -> tuple[dict, list[str]]:
    """规整 + 复验一份草案定义,返回 (规整后的定义, 问题清单)。不落盘。
    new_props:这次改动要顺带加的本体自有属性(还没落到对象上),校验时当它们已经有了。"""
    from . import fntests
    p = copy.deepcopy(p)
    kind = p.get("kind")
    problems: list[str] = []
    spec = dict(p.get("spec") or {})
    if not str(p.get("name") or "").strip():
        problems.append("名称不能为空")
    if not (kind == "action" and spec.get("_stub")):
        try:
            spec = schema.normalize_spec(kind, spec)
        except schema.SpecError as e:
            problems.append(str(e))
    p["spec"] = spec
    p.pop("test_failures", None)
    if kind == "function":
        cat = spec.get("category")
        if cat == "rule":
            problems += modeling._rule_problems(spec)
        if cat in ("rule", "decision") and spec.get("tests") and not problems:
            fails = [f"{x['name']}:{x['error']}" for x in fntests.run({"name": p["name"], "kind": "function", "spec": spec})
                     if not x["ok"]]
            if fails:
                p["test_failures"] = fails[:5]
        for b in p.get("bindings") or []:
            if b.get("target_kind") == "metric_expr":
                try:
                    b["ref"] = schema.normalize_binding("metric_expr", b.get("ref") or {})
                except schema.SpecError as e:
                    problems.append(f"取数定义:{e}")
    if kind == "action" and not spec.get("_stub"):
        objs = copy.deepcopy(modeling._run_objects(run_id))
        for x in new_props or []:
            rec = modeling._resolve_obj(str(x.get("object_type") or ""), objs)
            if rec is not None and not any(q["name"] == x.get("name") for q in rec["properties"]):
                rec["properties"].append({"name": str(x["name"]), "storage": "ontology", "is_writable": True})
        err = modeling._check_action_refs(spec, objs) or modeling._check_enum_writes(spec, objs)
        if err:
            problems.append(err)
    if kind == "object_type":
        from . import rules
        for x in spec.get("properties") or []:
            if x.get("expression"):
                try:
                    rules.parse(x["expression"])
                except rules.RuleError as e:
                    problems.append(f"计算属性「{x.get('display_name') or x['name']}」:{e}")
    return p, problems


def _trial(run_id: str, item_id: str, p: dict) -> dict:
    """把改后的定义放进草案世界里试算(别的草案照旧)。"""
    items = [x if x["id"] != item_id else {**x, "payload": p} for x in modeling._pending(run_id)]
    with modeling_world.world(items):
        return modeling_grade.trial_item({"id": item_id, "payload": p})


def _finish(run_id: str, item_id: str, p: dict, problems: list[str], how: str) -> dict:
    for k in ("trial", "prop_trials"):
        p.pop(k, None)
    p.update(_trial(run_id, item_id, p))
    p["problems"] = problems
    p["edited"] = how
    p["readiness"] = modeling_grade.readiness(p)
    review.update_payload(item_id, p, confidence=1.0 if p["readiness"]["ready"] else 0.5)
    return {"id": item_id, "payload": p, "readiness": p["readiness"], "problems": problems}


def save_item(run_id: str, item_id: str, patch: dict) -> dict:
    it = _item(run_id, item_id)
    newp = [x for x in patch.get("new_properties") or [] if isinstance(x, dict) and x.get("name")]
    if newp:                                   # 「告诉 AI 怎么改」时 AI 顺带声明的本体自有属性,确认采用时一起加上
        modeling._own_properties(newp, modeling._run_objects(run_id))
    p = {**(it["payload"] or {}), **{k: patch[k] for k in EDITABLE if k in patch}}
    if p.get("kind") == "action" and isinstance(p.get("spec"), dict) and p["spec"].get("effects"):
        p["spec"].pop("_stub", None)              # 人把参数和效果补上了:不再是只有说明的骨架
    p, problems = check_payload(run_id, p)
    return _finish(run_id, item_id, p, problems, "human")


# ---------------- 一句话让 AI 改 ----------------
AI_EDIT_PROMPT = """按要求修改下面这条草案,输出改后的完整定义。

【要求】{instruction}

【现在的定义】({kind_label})
{current}

【原文出处】
{evidence}

【写法】
{guide}

【对象及属性】
{objects}

【可以引用的函数】
{functions}

【业务角色和职责】{roles}

只改要求里提到的地方,其余保持原样(名字、别名、没提到的字段都照抄)。
动作要存的信息在对象里没有对应属性时,在顶层 new_properties 里声明本体自有属性
[{{"object_type":"对象名","name":"英文","display_name":"中文","data_type":"text"}}]。
只输出 JSON:{{"name":"","description":"","synonyms":[],"spec":{{}},"metric":{{取数定义,只有指标需要,没改就照抄}},
"new_properties":[],"summary":"一句话说明改了什么"}}"""

_OBJECT_GUIDE = """对象 spec = {"properties":[{"name":"英文","display_name":"中文","data_type":"string|number|boolean|date|enum|text",
 "enum_values":[],"is_dimension":bool,"is_writable":bool,"expression":"计算属性的公式(表里的列留空)","synonyms":[],"value_hints":[]}],
 "label_property":"","title_template":""}。计算属性的公式只能用这个对象的属性名、「关系名.属性」、count_of / sum_of 汇总指向它的记录。
表里的列(没有公式的)不要改名、不要删。"""


def _guide(p: dict) -> str:
    from . import draft
    kind = p.get("kind")
    if kind == "object_type":
        return _OBJECT_GUIDE
    if kind == "link_type":
        return 'spec = {"from_type":"对象名","to_type":"对象名","cardinality":"1:1|1:n|n:1|n:n","inverse_name":"反向说法"}'
    if kind == "action":
        return draft.GUIDES["action"].replace("{tools}", draft._tools_text()).replace("{roles}", "见下方业务角色")
    cat = (p.get("spec") or {}).get("category") or "rule"
    g = draft.GUIDES.get(cat, "")
    if cat == "aggregate":
        g += '\n指标的取数定义写在 metric:{"base_object":"对象名","expression":"SUM(属性)","filters":[],"dimensions":{}} ' \
             '或 {"base_table":"表名","expression":"...","filters":[],"dimensions":{},"time_column":"","object_key_column":""}'
    return g


def ai_edit_item(run_id: str, item_id: str, instruction: str, *, apply: bool = False) -> dict:
    """让 AI 按一句话改这条草案。apply=False 只返回改前 / 改后和复验结果;apply=True 直接保存(按对账修改用)。"""
    from ..governance import roles
    instruction = (instruction or "").strip()
    if not instruction:
        raise HTTPException(422, "请说明要怎么改")
    it = _item(run_id, item_id)
    p = it["payload"] or {}
    objs = modeling._run_objects(run_id)
    mb = next((b for b in p.get("bindings") or [] if b.get("target_kind") == "metric_expr"), None)
    current = {"name": p.get("name"), "description": p.get("description"), "synonyms": p.get("synonyms") or [],
               "spec": p.get("spec") or {}, **({"metric": mb["ref"]} if mb else {})}
    msg = AI_EDIT_PROMPT.format(
        instruction=instruction, kind_label=schema.kind_label(p.get("kind") or "", p.get("spec")),
        current=jdump(current)[:6000],
        evidence="\n".join(f"- {e.get('heading') or ''}:{e.get('snippet') or ''}" for e in (p.get("evidence") or [])[:4]) or "(无)",
        guide=_guide(p), objects=modeling._objects_text(objs, modeling._run_links(run_id)),
        functions=modeling._draft_functions_text(run_id),
        roles=";".join(f"{r['name']}:{r['description']}" if r.get("description") else r["name"] for r in roles.list_roles()) or "(无)")
    msgs = [{"role": "user", "content": msg}]
    after, problems, res, newp = {}, [], {}, []
    for attempt in (1, 2):                 # 改出来的定义过不了校验:把问题交回去再改一次
        with llmlog.feature("modeling_edit"), llm.trace_label(f"按要求改:{p.get('name')}" + ("(按校验错误再改)" if attempt > 1 else "")):
            res = llm.chat_json(msgs, temperature=0.1)
        if not isinstance(res, dict) or not isinstance(res.get("spec"), dict):
            raise HTTPException(502, "AI 没给出改后的定义,换个说法再试一次")
        after = {**p, "name": str(res.get("name") or p.get("name")),
                 "description": str(res.get("description") or p.get("description") or ""),
                 "synonyms": [str(x) for x in res.get("synonyms") or p.get("synonyms") or []], "spec": res["spec"]}
        if isinstance(res.get("metric"), dict) and res["metric"].get("expression"):
            ds = int((mb or {}).get("ds_id") or next((r["binding"]["ds_id"] for r in objs.values() if r.get("binding")), 0))
            after["bindings"] = [*[b for b in p.get("bindings") or [] if b.get("target_kind") != "metric_expr"],
                                 {"ds_id": ds, "target_kind": "metric_expr", "ref": res["metric"]}]
        if p.get("kind") == "action" and after["spec"].get("params") is not None:
            after["spec"].pop("_stub", None)
        newp = [x for x in res.get("new_properties") or [] if isinstance(x, dict) and x.get("name")]
        after, problems = check_payload(run_id, after, newp)
        if not problems:
            break
        msgs += [{"role": "assistant", "content": jdump(res)},
                 {"role": "user", "content": "校验没过:" + ";".join(problems[:4]) + "\n请修正后输出完整 JSON(公式用 Python 写法:and/or、x if c else y、字符串加引号)。"}]
    summary = str(res.get("summary") or "")[:200]
    if apply:
        _, before_problems = check_payload(run_id, p)
        if len(problems) > len(before_problems):
            # 按对账自动改:改坏了就不保存,留着原样让人看
            return {"id": item_id, "applied": False, "problems": problems, "before": current,
                    "summary": f"AI 改出来的有问题({problems[0][:80]}),没有保存"}
        if newp:
            modeling._own_properties(newp, modeling._run_objects(run_id))
        out = _finish(run_id, item_id, after, problems, "ai")
        return {**out, "applied": True, "summary": summary, "before": current}
    trial = _trial(run_id, item_id, after)
    preview = {**after, **trial}
    return {"before": current, "after": {k: preview.get(k) for k in ("name", "description", "synonyms", "spec", "bindings",
                                                                     "trial", "prop_trials", "test_failures")},
            "problems": problems, "readiness": modeling_grade.readiness({**preview, "problems": problems}),
            "summary": summary, "new_properties": newp}


# ---------------- 定时与监控 ----------------
def _watch(run_id: str, wid: str) -> dict:
    for d in modeling._inputs(run_id).get("watch_drafts") or []:
        if d["id"] == wid:
            if d.get("status") != "pending":
                raise HTTPException(409, "这条定时任务已经处理过了,请到「定时与监控」里改")
            return d
    raise HTTPException(404, "定时任务草稿不属于这次建模")


def save_watch(run_id: str, wid: str, body: dict) -> dict:
    from . import modeling_schedule
    _watch(run_id, wid)
    c = modeling_schedule._context(run_id, {})
    body = modeling_schedule._body({**body, "condition": str(body.get("condition") or "")})
    probs = modeling_schedule._problems(body, c)
    with modeling_world.world(modeling._pending(run_id)):
        trial = modeling_world.watch_trial(body) if not probs else {}

    def keep(inp: dict) -> None:
        for d in inp.get("watch_drafts") or []:
            if d["id"] == wid:
                d.update(body=body, title=str(body.get("title") or d["title"])[:120], issue=";".join(probs),
                         weak=bool(probs), trial=trial, edited="human")
    modeling._patch_inputs(run_id, keep)
    return _watch(run_id, wid)


WATCH_EDIT_PROMPT = """按要求修改下面这条监控 / 定时任务草稿,输出改后的完整定义(格式不变)。

【要求】{instruction}

【现在的定义】
{current}

【对象及属性】
{objects}

【指标】{metrics}
【流程卡】{sops}
【动作】{actions}
【业务角色】{roles}

只改要求里提到的地方。文字匹配用 contains(字段,'关键字')。只输出 JSON:{{"watch":{{...}},"summary":"一句话说明改了什么"}}"""


def ai_edit_watch(run_id: str, wid: str, instruction: str, *, apply: bool = False) -> dict:
    from . import modeling_schedule
    d = _watch(run_id, wid)
    c = modeling_schedule._context(run_id, {})
    msg = WATCH_EDIT_PROMPT.format(instruction=instruction, current=jdump(d["body"]), objects=c["objects_text"],
                                   metrics="、".join(c["metrics"]) or "(无)", sops="、".join(c["sops"]) or "(无)",
                                   actions="、".join(c["actions"]) or "(无)", roles="、".join(c["roles"]) or "(无)")
    with llmlog.feature("modeling_edit"), llm.trace_label(f"按要求改监控:{d['title']}"):
        res = llm.chat_json([{"role": "user", "content": msg}], temperature=0.1)
    w = res.get("watch") if isinstance(res, dict) else None
    if not isinstance(w, dict):
        raise HTTPException(502, "AI 没给出改后的定义,换个说法再试一次")
    body = modeling_schedule._body(w)
    modeling_schedule._lift_fields(run_id, body, c, lambda m: None)
    probs = modeling_schedule._problems(body, c)
    if apply:
        out = save_watch(run_id, wid, body)
        return {"watch": out, "summary": str(res.get("summary") or "")}
    with modeling_world.world(modeling._pending(run_id)):
        trial = modeling_world.watch_trial(body) if not probs else {}
    return {"before": d["body"], "after": body, "problems": probs, "trial": trial, "summary": str(res.get("summary") or "")}


# ---------------- 流程卡 ----------------
SOP_EDIT_PROMPT = """按要求修改下面这张流程卡,输出改后的完整 JSON(结构同原来)。

【要求】{instruction}

【现在的流程卡】
{current}

【还有这些问题】
{problems}

【可用的对象、函数、动作】
{catalog}

只改要求里提到的和上面列出的问题,其余步骤保持原样。只输出 JSON:{{"spec":{{...}},"summary":"一句话说明改了什么"}}"""


def ai_edit_sop(run_id: str, sid: str, instruction: str = "", *, extra_steps: list[dict] | None = None) -> dict:
    """让 AI 按一句话(或按校验错误、按对账缺的步骤)改流程卡草稿,改好且问题不比原来多才保存。"""
    from ..sop import draft as sop_draft
    from ..sop import service as sop_service
    from ..sop import spec as sop_spec
    if sid not in (modeling._inputs(run_id).get("sop_ids") or []):
        raise HTTPException(404, "流程卡不属于这次建模")
    d = sop_service.get(sid)
    if d["current_version"]:
        raise HTTPException(409, "这张流程卡已经上线了,请在流程卡编辑器里改")
    names = modeling._draft_names(run_id)
    before = sop_spec.validate(d["spec"], def_id=sid, draft_names=names)
    probs = list(before["errors"]) + [f"文档的这一步还没有:{r['text']}" for r in extra_steps or []]
    if not instruction and not probs:
        return {"changed": False, "summary": "没有要改的", "validation": before}
    cat = sop_draft._catalog(modeling._draft_catalog(run_id))
    catalog = "\n".join(f"【{k}】{v}" for k, v in cat.items())
    msg = SOP_EDIT_PROMPT.format(instruction=instruction or "把下面的问题改掉", current=jdump(d["spec"])[:9000],
                                 problems="\n".join(f"- {x}" for x in probs) or "(无)", catalog=llm.truncate_to_tokens(catalog, 5000))
    with llmlog.feature("modeling_edit"), llm.trace_label(f"按要求改流程卡:{d['title']}"):
        res = llm.chat_json([{"role": "system", "content": sop_draft.DRAFT_SYSTEM}, {"role": "user", "content": msg}],
                            temperature=0.1)
    raw = res.get("spec") if isinstance(res, dict) else None
    if not isinstance(raw, dict) or not raw.get("steps"):
        raise HTTPException(502, "AI 没给出改后的流程卡,换个说法再试一次")
    spec = sop_spec.normalize(raw)
    sop_spec.qualify_refs(spec)
    after = sop_spec.validate(spec, def_id=sid, draft_names=names)
    if len(after["errors"]) > len(before["errors"]) and not instruction:
        return {"changed": False, "summary": "AI 改出来的问题比原来还多,保留原稿", "validation": before}
    sop_service.update(sid, title=d["title"], description=d.get("description") or "", spec=spec,
                       process_concept_id=d.get("process_concept_id") or "", owner_role=d.get("owner_role") or "")
    summary = str((res or {}).get("summary") or "")[:200]
    entry = {"instruction": instruction or "按问题改", "summary": summary,
             "before_errors": len(before["errors"]), "after_errors": len(after["errors"])}

    def keep(inp: dict) -> None:
        h = inp.setdefault("sop_hints", {}).setdefault(sid, {})
        h["fix_log"] = [*(h.get("fix_log") or []), entry][-10:]
    modeling._patch_inputs(run_id, keep)
    trial = modeling._sop_trial(run_id, sid)
    return {"changed": True, "summary": summary, "validation": after, "dry_run": trial}