draft.py 12.4 KB
"""一句话生成函数 / 动作:AI 只起草,确定性引擎把关。

  意图 → [1] 分类 + 推荐对象与属性(1 次 LLM)→ [2] 生成 spec(1 次 LLM)
       → [3] 用 schema.normalize_spec 校验(规则走安全 AST、决策表逐格解析、动作只能调系统效果)
       → 不通过把错误喂回去修一次 → [4] 给出草稿与试跑样例,用户确认后才存为草稿概念

同步生成器 yield 事件,由 deps.sse 桥接成 SSE,前端逐步展示起草过程。
这里**不落库**:起草结果要经人看过、试跑过再保存,AI 永远只产出草稿。
"""
from __future__ import annotations

import json
import logging
from typing import Any, Iterator

from ..capability import registry
from ..core import llm
from ..governance import llmlog
from . import schema, service

log = logging.getLogger(__name__)

CLASSIFY_SYSTEM = """你是本体建模助手。本体只有四种积木:对象、关系、函数、动作。
用户用一句话描述想要的业务逻辑,请判断它该建成什么,并推荐用到的对象与属性。

函数类别:
- aggregate 聚合:可量化的度量(量、额、率、次数),需要从数据里汇总得到
- rule 规则:给定几个输入值,按一个公式或判定条件算出结果(达标判定、差额、得分公式)
- decision 决策表:按多个条件分档 / 查表得出结果(分级、打分档位、多条件组合)
- calendar 周期:统计时间窗口(如某日到次月某日)
- ai AI 分析:需要大模型综合取数与资料做判断、归因、建议(结果仅供参考)
动作 action:要改变业务状态(改对象属性、派任务、发通知、调外部系统),执行前需人工审批。

【现有对象及属性】
{objects}

【现有函数】
{functions}

输出 JSON:
{{"kind":"function|action","category":"aggregate|rule|decision|calendar|ai(动作留空)",
  "name":"简短的中文名称","object_type":"作用于哪个对象(名称,没有就空)",
  "properties":["会用到的对象属性名"],"inputs":["需要的输入量(英文或中文标识符)"],
  "reason":"为什么这样分类,一句话"}}
只输出 JSON。"""

GENERATE_SYSTEM = """你是本体建模助手。按给定的类别,把用户的意图写成可执行的定义(spec)。

{guide}

【现有对象及属性】
{objects}

【现有函数】(可以按名称引用)
{functions}

输出 JSON:{{"name":"名称","description":"一句话定义","synonyms":["别名"],"spec":{{...}},
  "samples":[{{"input":{{...}},"expect":"期望结果(可选)"}}]}}
samples 给 2~3 组试跑用的输入,覆盖不同分支。只输出 JSON。"""

GUIDES = {
    "rule": """类别:规则函数。spec = {"category":"rule","object_type":"对象名或空","rule_kind":"judgement|calculation|calibre",
 "expression":"Python 风格表达式","params":["变量名"],"text":"用业务语言说明规则"}
表达式只能用:算术、比较、and/or/not、x if c else y、obj.属性、白名单函数
(min max abs round floor ceil sum len coalesce safe_div days_between day month year contains startswith)。
变量名用英文或中文标识符,不能有空格;不能写 import、lambda、推导式、赋值。
samples.input 是 {变量名: 值}。""",
    "decision": """类别:决策表。spec = {"category":"decision","object_type":"对象名或空",
 "inputs":[{"name":"输入名","label":"中文","type":"number|string"}],
 "outputs":[{"name":"输出名","label":"中文"}],
 "rows":[{"when":{"输入名":"条件"},"then":{"输出名":值},"note":"这一档的含义"}],
 "hit_policy":"first","default":{"输出名":值},"text":"用业务语言说明"}
条件写法:空或 "-" 表示任意;"> 3"、">= 0 and < 3"、"[0, 3]" 区间、"'A'" 等于、"in ['A','B']"。
行按优先级从上到下排列,first 策略命中第一行即停;务必覆盖所有情况或给 default。
samples.input 是 {输入名: 值}。""",
    "aggregate": """类别:聚合函数(指标)。spec = {"category":"aggregate","object_type":"对象名",
 "unit":"单位","direction":"higher_better|lower_better|neutral","formula_text":"用业务语言写计算方法",
 "calendar":"统计周期函数名或空","dimensions":["可拆分的属性名"]}
取数表达式需要绑定到具体数据表,这一步由人在绑定页完成;这里只写业务定义。samples 留空数组。""",
    "calendar": """类别:周期函数。spec = {"category":"calendar","start_day":1-31,"start_month_offset":整数,
 "end_day":1-31或"last","end_month_offset":整数,"text":"说明"}
例:「上月 26 日至本月 25 日」→ start_day=26,start_month_offset=-1,end_day=25,end_month_offset=0。
samples.input 是 {"ref":"current|last|YYYY-MM"}。""",
    "ai": """类别:AI 分析函数(只读)。spec = {"category":"ai","object_type":"对象名或空",
 "instructions":"分析步骤与要求","functions":["只能从可用只读函数里选"],
 "inputs":[{"name":"输入名","description":"说明"}],
 "output_schema":{"conclusion":"一句话结论","details":["要点"]},"max_steps":4}
可用只读函数:{functions_readonly}
samples 留空数组。""",
    "action": """类别:动作(执行前一律人工审批)。spec = {
 "target_type":"作用的对象名或空",
 "params":[{"name":"英文参数名","label":"中文","type":"string|text|number|boolean|enum","required":true,"enum":[]}],
 "criteria":[{"expression":"前置条件表达式,可用参数名与 obj.属性","message":"不满足时的提示"}],
 "effects":[{"tool":"系统效果名","args":{...}}],
 "approval":{"mode":"manual","approver_roles":["业务角色名"]},"reversible":true}
效果只能从下面的系统效果里选,args 按其参数填写;引用参数写 "$参数名",引用对象写 "$obj_key"、"$obj.属性"、"$obj.label"。
以 "=" 开头的值是表达式,可做计算,如 "=qty * obj.unit_price";内置 "$today"(今天)、"$now_id"(时间戳编号,新单号写 "PO$now_id")。
object.write 改已有对象的属性(会自动开放写回);新建单据(采购单、工单等)用 object.create,values 写全主键和必填属性。
【系统效果】
{tools}
【业务角色】{roles}
samples.input 是 {参数名: 值}。""",
}


def _objects_text() -> str:
    lines = []
    for c in service.list_concepts(kind="object_type", limit=200):
        full = service.get_concept(c["id"])
        props = []
        for p in (full.get("spec") or {}).get("properties") or []:
            flags = [f for f, k in (("主键", "is_key"), ("可写", "is_writable"), ("维度", "is_dimension"))
                     if p.get(k)]
            props.append(p["name"] + (f"({'/'.join(flags)})" if flags else "")
                         + (f"[{'/'.join(p['enum_values'])}]" if p.get("enum_values") else ""))
        lines.append(f"- {c['name']}:{'、'.join(props) or '(无属性)'}")
    return "\n".join(lines) or "(还没有对象)"


def _functions_text() -> str:
    items = [c for c in service.list_concepts(kind="function", limit=300)]
    return "\n".join(f"- {c['name']}({c['kind_label']}):{(c.get('description') or '')[:50]}"
                     for c in items) or "(无)"


def _tools_text() -> str:
    out = []
    for t in registry.TOOLS.values():
        props = "; ".join(f"{k}: {v.get('description', '')}"
                          for k, v in (t.input_schema.get("properties") or {}).items())
        out.append(f"- {t.name}({t.title}):{t.description} 参数 {{{props}}}")
    return "\n".join(out)


def _resolve_names(kind: str, spec: dict) -> dict:
    """AI 按名称引用对象 / 函数,这里换成 id(找不到保留名称,运行时仍可按名称解析)。"""
    fields = (("object_type", "object_type"), ("target_type", "object_type"),
              ("calibre_rule", "function"), ("calendar", "function"))
    for f, k in fields:
        v = spec.get(f)
        if isinstance(v, str) and v:
            found = service.find(v, k)
            if found:
                spec[f] = found["id"]
    return spec


def _validate(kind: str, spec: dict) -> str:
    try:
        schema.normalize_spec(kind, spec)
        return ""
    except schema.SpecError as e:
        return str(e)


def generate(intent: str, hint_kind: str = "", hint_category: str = "") -> Iterator[dict]:
    intent = (intent or "").strip()
    if not intent:
        yield {"type": "error", "error": "请用一句话描述想要的业务逻辑"}
        return
    objects, functions = _objects_text(), _functions_text()
    with llmlog.feature("ontology_draft"):
        # 1) 分类 + 推荐实体
        yield {"type": "stage", "stage": "classify", "message": "判断该建成什么"}
        cls: dict[str, Any] = {}
        if hint_kind:
            cls = {"kind": hint_kind, "category": hint_category, "name": "", "reason": "由你指定"}
        try:
            got = llm.chat_json([{"role": "system", "content": CLASSIFY_SYSTEM.format(
                objects=objects, functions=functions)}, {"role": "user", "content": intent}])
            if isinstance(got, dict):
                cls = {**got, **{k: v for k, v in cls.items() if v}}
        except Exception as e:  # noqa: BLE001
            if not cls:
                yield {"type": "error", "error": f"起草失败:{str(e)[:200]}"}
                return
        kind = "action" if cls.get("kind") == "action" else "function"
        cat = "" if kind == "action" else (cls.get("category") if cls.get("category") in schema.FN_CATEGORIES
                                           else "rule")
        yield {"type": "classify", "kind": kind, "category": cat,
               "label": schema.kind_label(kind, {"category": cat}),
               "name": cls.get("name") or "", "reason": cls.get("reason") or ""}
        yield {"type": "entities", "object_type": cls.get("object_type") or "",
               "properties": cls.get("properties") or [], "inputs": cls.get("inputs") or []}

        # 2) 生成 spec
        yield {"type": "stage", "stage": "generate", "message": "生成计算逻辑"}
        guide = GUIDES["action" if kind == "action" else cat]
        from ..governance import roles
        guide = (guide.replace("{tools}", _tools_text())
                 .replace("{roles}", "、".join(roles.names()) or "(无,可留空)")
                 .replace("{functions_readonly}", "、".join(registry.FUNCTIONS)))
        msgs = [{"role": "system", "content": GENERATE_SYSTEM.format(
                    guide=guide, objects=objects, functions=functions)},
                {"role": "user", "content": f"意图:{intent}\n建议名称:{cls.get('name') or ''}\n"
                                            f"作用对象:{cls.get('object_type') or '无'}\n"
                                            f"会用到的属性:{'、'.join(cls.get('properties') or []) or '无'}"}]
        draft: dict = {}
        err = ""
        for attempt in (1, 2):
            try:
                out = llm.chat_json(msgs)
            except Exception as e:  # noqa: BLE001
                err = f"生成失败:{str(e)[:200]}"
                break
            draft = out if isinstance(out, dict) else {}
            spec = dict(draft.get("spec") or {})
            if kind == "function":
                spec["category"] = cat
            spec = _resolve_names(kind, spec)
            draft["spec"] = spec
            yield {"type": "spec", "attempt": attempt, "spec": spec}
            # 3) 校验
            err = _validate(kind, spec)
            yield {"type": "validate", "attempt": attempt, "ok": not err, "error": err}
            if not err:
                break
            if attempt == 1:
                yield {"type": "stage", "stage": "repair", "message": "校验没过,让 AI 修正一次"}
                msgs += [{"role": "assistant", "content": json.dumps(draft, ensure_ascii=False)},
                         {"role": "user", "content": f"校验失败:{err}\n请修正后输出完整 JSON。"}]
        if not draft:
            yield {"type": "error", "error": err or "起草失败"}
            return
        name = str(draft.get("name") or cls.get("name") or intent[:20]).strip()
        yield {"type": "done", "ok": not err, "error": err,
               "draft": {"kind": kind, "name": name, "description": str(draft.get("description") or ""),
                         "synonyms": [str(x) for x in draft.get("synonyms") or []][:10],
                         "spec": draft["spec"]},
               "samples": [s for s in draft.get("samples") or [] if isinstance(s, dict)][:4]}