draft.py 14.6 KB
"""AI 起草 SOP:从文档(和本体里的流程概念)生成一份可执行的 SOP 草稿。

大模型只能用「能力目录」里已有的东西:只读函数、已登记的技能与动作、本体里的角色/指标/规则。
生成后立刻按 spec.validate 校验,有错误就把错误喂回去让它改一轮 —— 仍有错也保存为草稿,
人在编辑器里补齐,发布前还要过试运行与审核两道关。
"""
from __future__ import annotations

import json
import logging
from typing import Any

from fastapi import HTTPException

from ..capability import defs, registry
from ..core import llm
from ..governance import llmlog
from ..kernel import service as ksvc
from . import service
from . import spec as sop_spec

log = logging.getLogger(__name__)
FIX_ROUNDS = 2          # 校验有错时最多让 AI 按错误改几轮

DRAFT_SYSTEM = """你是流程设计专家,要把业务文档里描述的流程写成一份**可执行的流程卡**(JSON)。

结构:
{
 "title": "流程名", "description": "一句话说明", "owner_role": "负责执行这个流程的角色(文档写了就填)",
 "params": [{"name":"英文变量名","label":"中文名","type":"string|number|date|object|period|list","object_type":"对象类型名(type=object时)",
             "columns":[{"name":"英文","label":"中文","type":"string|number"}](type=list 明细行时),"required":true}],
 "start": "第一步id",
 "steps": [ 步骤... ],
 "evidence": ["出处片段编号"]
}
每一步都有 id(英文)、type、title(中文)、description、next(下一步 id)、output(结果变量名,默认就是 id)。步骤类型:
- query 查数据:{"object_type":"对象名","mode":"one|list","where":{"mode":"all","items":[{"left":"属性名","op":"eq","right":"$工单号"}]},
    "include":[{"link":"关系名或对方对象名","as":"放在哪个字段","mode":"list|one","where":{...},"aggs":[{"fn":"count|sum","field":"属性","as":"名字"}]}],
    "limit":50}。mode=one 时结果就是那个对象($变量.属性、$变量.found);list 时是 {items:[...], total}。
    op 可用:eq ne gt ge lt le contains in empty not_empty。一次就能把主对象和关联对象(明细、关联单据)都查回来。
- function 调用函数:{"function":"metric.query","args":{"metric":"指标名","dimensions":[...]}} 取指标;
    {"function":"function.eval","args":{"name":"规则 / 决策表 / 对象集名","args":{"输入名":"$变量.字段"}}} 调本体函数。
- compute 计算:{"assign":[{"name":"英文","label":"中文","type":"number|string|boolean|list","expr":"表达式"}]}
    表达式可用:sum_by(列表,'字段') count(列表) where(列表,'字段','>',值) pluck(列表,'字段') first(列表) 及 + - * / 比较、and/or。
- decision 条件:{"branches":[{"label":"情况名","when":"表达式,如 count(q.items) > 0 and calc.total < 5000","next":"..."}],"default":"..."}
- foreach 循环:{"items":"$前一步.items","when":"只处理满足条件的行(表达式,item.列名)","limit":50,
    "body":{"start":"循环体第一步","steps":[循环体里的步骤,最后一步 type=end]}},循环体里用 $item.列名 引用当前行。
- write 写数据(同一事务,要审批):{"ops":[
      {"op":"create","object_type":"对象名","as":"po","values":{"属性":"$变量.字段","单号":"=('PO' + now_id)"}},
      {"op":"create_rows","object_type":"明细对象名","rows":"$明细数据","values":{"所属单号":"$ops.po.key","数量":"$row.数量"}},
      {"op":"update","object_type":"对象名","key":"$item.key","values":{"状态":"处理中"}}],
    "approval":{"mode":"manual|auto|conditional","approver_roles":["角色"],"auto_when":"表达式"}}
    $ops.<as>.key 引用同一次写入里前面新建出来的主键;$row.列 是按行新建时的这一行;$now_id 是不重复编号。
- action 执行动作:{"action":"动作名","params":{...},"object_key":"$obj.key","on_reject":"驳回时去哪"}
- skill AI 分析:{"instruction":"让 AI 判断什么","inputs":{"数据名":"$变量"},"outputs":[{"name":"level","label":"等级","type":"string","options":["高","中","低"]}]}
- human_task 人工任务:{"role":"角色","instructions":"要做什么,可嵌 $变量.字段","form":[{"name":"英文","label":"中文","type":"text|number|boolean|choice|date","options":[],"required":true}],"sla_hours":24}
- notify 通知:{"role":"角色","subject":"标题","body":"内容"}
- end 结束:{"outcome":"结果说明","outputs":[{"name":"英文","label":"中文","value":"$变量.字段"}]}
引用变量用 "$变量名.字段"、"$变量.items[0].字段";when / expr 表达式里直接写变量名(不加 $)。
规则:
1. 只能使用下面列出的对象、关系、函数、动作;写数据只能写列出的对象和属性,不要编造。没有合适的就用 human_task 让人去做。
2. 流程必须能从第一步走到 end,不能有环(要重复用 foreach);每个 decision 必须有 default。
3. 查数据优先用 query(一次带出关联对象),取统计数用 metric.query;判断写成 decision;新建 / 修改业务数据用 write。
4. 一张流程卡只管一件事,步骤控制在 20 步以内;description 一句话写清即可,不要复述原文。
5. 「计算」步骤算出来的字段挂在这一步的输出下:后面的条件和公式里写 步骤输出.字段(如 calc.total),文字里写 $calc.total。
6. 同一行两列比较(某个量低于另一个量)不要用 where(列表,'字段','<','另一列名')——第 4 个参数是值;
   用对象上已有的计算属性筛(查数据的 where 里写它),没有合适的就在查数据的条件里写清楚。
7. 给了【文档里这个流程的步骤】时,每一条都要有对应的步骤(排序、汇总、逐条处理、通知这类也算),
   并在顶层 "covers" 里写 {"条目编号":"步骤 id"};要人判断的用 human_task。
8. 只输出 JSON。
"""

DRAFT_USER = """要生成的流程:{topic}

【可用函数】
{functions}

【可用技能】
{skills}

【可用动作】(需要审批)
{actions}

【本体】
角色:{roles}
指标:{metrics}
规则 / 决策表 / 对象集:{rules};{decisions};{object_sets}
对象类型(属性):
{object_types}
关系:
{links}

【文档依据】
{evidence}
{steps}"""


def _catalog(extra: dict | None = None) -> dict:
    """extra:业务建模时这次草案里的元素(还没采纳成概念,但流程卡要按它们的名字引用)。"""
    # 带上参数名:不写清楚模型就会自己起名字(data.ask 写成 prompt),运行时才报错
    fns = "\n".join(f"- {f.name}:{f.description} 参数 {list((f.input_schema or {}).get('properties') or {})}"
                    for f in registry.FUNCTIONS.values())
    sk = "\n".join(f"- {s['name']}:{s['description']}" for s in defs.list_defs("skill")) or "(无)"
    ac = "\n".join(
        f"- {a['name']}:{a['description']} 参数:{[p['name'] for p in a['spec'].get('params') or []]}"
        + (f" 作用对象:{a['spec'].get('target_type')}" if a['spec'].get('target_type') else "")
        for a in defs.list_defs("action")) or "(无)"

    def names(kind: str, category: str = "") -> str:
        return "、".join(c["name"] for c in ksvc.list_concepts(kind=kind, limit=300)
                        if not category or c.get("category") == category) or "(无)"
    from ..governance import roles

    def objects_text() -> str:
        lines = []
        for c in ksvc.list_full("object_type", limit=200):
            props = [f"{p['name']}{'(可改)' if p.get('is_writable') else ''}" for p in (c.get("spec") or {}).get("properties") or []]
            lines.append(f"- {c['name']}:{'、'.join(props[:30])}")
        return "\n".join(lines) or "(无)"

    def links_text() -> str:
        return "\n".join(f"- {c['name']}:{(c.get('spec') or {}).get('from_type')} → {(c.get('spec') or {}).get('to_type')}"
                         f"({(c.get('spec') or {}).get('cardinality')})"
                         for c in ksvc.list_full("link_type", limit=300)) or "(无)"
    out = {"functions": fns, "skills": sk, "actions": ac,
           "roles": "、".join(roles.names()) or "(无)",
           "metrics": names("function", "aggregate"), "rules": names("function", "rule"),
           "decisions": names("function", "decision"),
           "object_sets": names("function", "object_set"), "object_types": objects_text(), "links": links_text()}
    for k, v in (extra or {}).items():
        if v:
            base = "" if out.get(k) in ("(无)", "", None) else out[k]
            out[k] = (base + ("\n" if k in ("actions", "object_types", "links") else "、") + v).lstrip("、\n")
    return out


def _coverage(raw: Any, spec: dict, must: list[dict]) -> tuple[dict[str, str], list[dict]]:
    """文档步骤条目 → 流程卡步骤:AI 写在 covers 里,对不上实际步骤的不算。返回 (covers, 没覆盖的条目)。"""
    if not must:
        return {}, []
    ids: set[str] = set()

    def collect(steps: list[dict]) -> None:
        for st in steps:
            ids.add(st["id"])
            if st.get("type") == "foreach":            # 只有循环的 body 是步骤;通知的 body 是正文
                collect((st.get("body") or {}).get("steps") or [])
    collect(spec.get("steps") or [])
    cov = raw.get("covers") if isinstance(raw, dict) and isinstance(raw.get("covers"), dict) else {}
    covers = {str(k): str(v) for k, v in cov.items() if str(v) in ids}
    return covers, [r for r in must if r["id"] not in covers]


def generate(topic: str, process_concept_id: str = "", chunks: list[dict] | None = None,
             extra_catalog: dict | None = None, draft_names: dict[str, set[str]] | None = None,
             owner_role: str = "", must_cover: list[dict] | None = None) -> dict:
    """chunks 给了就直接拿它当依据(业务建模的 SOP 编排阶段),否则去知识库检索。
    draft_names:AI 建模这次草案里的元素名(按种类)—— 还没采纳,校验时算「待发布」,不当成错误让 AI 去改。
    must_cover:文档里这个流程的步骤条目 [{id, text}]:每一条都要有对应步骤,缺了的和校验错误一起让 AI 补。
    返回的流程卡带 coverage:{covers, total, covered, missing}。"""
    from ..capability.builtins import knowledge_search
    topic = (topic or "").strip()
    concept = None
    if process_concept_id:
        concept = ksvc.get_concept(process_concept_id)
        topic = topic or concept["name"]
        topic += f"({concept.get('description', '')})" if concept.get("description") else ""
    if not topic:
        raise HTTPException(422, "请说明要生成哪个流程")
    if chunks is None:
        try:
            found = knowledge_search({"query": f"{topic} 的流程、步骤、角色、判定条件"}, None)
            chunks = found.get("chunks") or []
        except Exception as e:  # noqa: BLE001
            log.warning("起草 SOP 时检索失败:%s", e)
            chunks = []
    evidence = "\n\n".join(f"[{c['id']}]【{c.get('heading') or '正文'}】{c['text'][:900]}"
                           for c in chunks[:8]) or "(没有检索到文档依据,请基于常识给出最小可用流程)"
    must = [r for r in must_cover or [] if r.get("id")]
    steps_text = ("\n【文档里这个流程的步骤】(每一条都要有对应步骤,写进 covers):\n"
                  + "\n".join(f"{r['id']}:{r['text']}" for r in must) + "\n") if must else ""
    messages = [{"role": "system", "content": DRAFT_SYSTEM},
                {"role": "user", "content": DRAFT_USER.format(topic=topic, evidence=evidence, steps=steps_text,
                                                              **_catalog(extra_catalog))}]

    def check(raw_: Any) -> tuple[dict, list[str], list[dict]]:
        spec_ = sop_spec.normalize(raw_ if isinstance(raw_, dict) else {})
        sop_spec.qualify_refs(spec_)                 # 计算步骤的字段写成了裸名字:意思确定,直接补上前缀
        errs = sop_spec.validate(spec_, draft_names=draft_names)["errors"]
        return spec_, errs, _coverage(raw_, spec_, must)[1]

    with llmlog.feature("sop_draft"):
        try:
            raw = llm.chat_json(messages, temperature=0.2)
        except Exception as e:  # noqa: BLE001
            raise HTTPException(502, f"大模型起草失败:{str(e)[:200]}") from e
        spec, errors, missing = check(raw)
        cur = raw
        for _ in range(FIX_ROUNDS):
            if not errors and not missing:
                break
            ask = []
            if errors:
                ask.append("校验发现以下错误:\n- " + "\n- ".join(errors[:12]))
            if missing:
                ask.append("文档里这些步骤还没有对应的流程步骤(补上,并写进 covers):\n- "
                           + "\n- ".join(f"{r['id']}:{r['text']}" for r in missing))
            messages += [{"role": "assistant", "content": json.dumps(cur, ensure_ascii=False)},
                         {"role": "user", "content": "\n\n".join(ask) + "\n请修正后重新输出完整 JSON。"}]
            try:
                with llmlog.feature("sop_draft_fix"):         # 只是照着错误改,不用再长考
                    cur = llm.chat_json(messages, temperature=0.1)
            except Exception:  # noqa: BLE001
                break
            spec2, errors2, missing2 = check(cur)
            # 改过的稿子问题不多于原稿、又不是空的就用它(原稿常常就是空的,「更少」这条会把空卡留下来)
            if spec2.get("steps") and (not spec.get("steps") or len(errors2) + len(missing2) <= len(errors) + len(missing)):
                raw, spec, errors, missing = cur, spec2, errors2, missing2
    ev_ids = {str(x) for x in (raw.get("evidence") if isinstance(raw, dict) else None) or []}
    spec["evidence"] = [{"chunk_id": c["id"], "doc_id": c.get("doc_id"), "heading": c.get("heading", ""),
                         "snippet": c["text"][:300]} for c in chunks if not ev_ids or c["id"] in ev_ids][:8]
    title = (raw.get("title") if isinstance(raw, dict) else "") or topic[:60]
    role = owner_role or (str(raw.get("owner_role") or "").strip() if isinstance(raw, dict) else "")
    d = service.create(title, (raw.get("description") if isinstance(raw, dict) else "") or "",
                       spec, process_concept_id=process_concept_id, owner_role=role[:64], ai_generated=True)
    covers, missing = _coverage(raw, spec, must)
    d["coverage"] = {"covers": covers, "total": len(must), "covered": len(must) - len(missing),
                     "missing": [r["id"] for r in missing]}
    return d