Commit 6c748314 by 黄南光

大幅修改优化本体系统

1 parent 743bd6df
Showing 59 changed files with 2637 additions and 20 deletions
...@@ -159,7 +159,7 @@ RUNTIME_META: dict[str, dict] = { ...@@ -159,7 +159,7 @@ RUNTIME_META: dict[str, dict] = {
"EMBED_MODEL": {"group": "模型", "label": "向量模型", "type": "text", "help": "text-embedding-v4,维度 1024"}, "EMBED_MODEL": {"group": "模型", "label": "向量模型", "type": "text", "help": "text-embedding-v4,维度 1024"},
"EMBED_DIM": {"group": "模型", "label": "向量维度", "type": "int", "min": 64, "max": 4096}, "EMBED_DIM": {"group": "模型", "label": "向量维度", "type": "int", "min": 64, "max": 4096},
"RERANK_MODEL": {"group": "模型", "label": "重排模型", "type": "text", "help": "留空则不重排"}, "RERANK_MODEL": {"group": "模型", "label": "重排模型", "type": "text", "help": "留空则不重排"},
"LLM_BASE_URL": {"group": "模型", "label": "OpenAI 兼容地址", "type": "text", "help": "留空 = 用 DashScope SDK"}, "LLM_BASE_URL": {"group": "模型", "label": "OpenAI 兼容地址", "type": "text", "help": "留空 = 用 DashScope SDK。deepseek-v4.1-flash、qwen3.7-plus 等 SDK 不支持的模型要填 https://dashscope.aliyuncs.com/compatible-mode/v1"},
"LLM_THINKING": {"group": "模型", "label": "让模型先思考再回答", "type": "text", "LLM_THINKING": {"group": "模型", "label": "让模型先思考再回答", "type": "text",
"help": "只对带思考能力的模型有用。auto = 提问和起草时思考(更准),有校验兜底的小步骤不思考;on = 总是;off = 从不(快几倍,但会答错、会凑数)"}, "help": "只对带思考能力的模型有用。auto = 提问和起草时思考(更准),有校验兜底的小步骤不思考;on = 总是;off = 从不(快几倍,但会答错、会凑数)"},
"LLM_THINKING_BUDGET": {"group": "模型", "label": "建模时最多思考多少", "type": "int", "min": 0, "max": 32768, "LLM_THINKING_BUDGET": {"group": "模型", "label": "建模时最多思考多少", "type": "int", "min": 0, "max": 32768,
......
...@@ -151,7 +151,10 @@ def chat(messages: list[dict], temperature: float = 0.2, max_retries: int = 3, ...@@ -151,7 +151,10 @@ def chat(messages: list[dict], temperature: float = 0.2, max_retries: int = 3,
handle = sink.begin(label + (f"(第 {attempt + 1} 次)" if attempt else ""), _feature(), model, handle = sink.begin(label + (f"(第 {attempt + 1} 次)" if attempt else ""), _feature(), model,
_prompt_text(messages)) _prompt_text(messages))
with _sem: with _sem:
if traced and not base_url: if traced and base_url:
out, reasoning, usage = _chat_openai_traced(base_url, model, messages, temperature,
traced[0], handle)
elif traced:
out, reasoning, usage = _chat_dashscope_traced(model, messages, temperature, traced[0], handle) out, reasoning, usage = _chat_dashscope_traced(model, messages, temperature, traced[0], handle)
else: else:
out = (_chat_openai(base_url, model, messages, temperature) if base_url out = (_chat_openai(base_url, model, messages, temperature) if base_url
...@@ -306,22 +309,27 @@ def _stream_dashscope(model: str, messages: list[dict], temperature: float) -> I ...@@ -306,22 +309,27 @@ def _stream_dashscope(model: str, messages: list[dict], temperature: float) -> I
yield piece yield piece
def _chat_openai(base_url: str, model: str, messages: list[dict], temperature: float) -> str: # ---------------- OpenAI 兼容接口 ----------------
url = base_url.rstrip("/") + "/chat/completions" # 有些模型(如 deepseek-v4.1-flash、qwen3.7-plus)在 DashScope 上只能走兼容接口,SDK 会报 url error。
resp = requests.post(url, headers={"Authorization": f"Bearer {_key()}"}, # 这条路统一用流式:思考再长也不会撞整体超时(超时只算两个数据块之间的空档),思考过程也能边想边报给追踪。
json={"model": model, "messages": messages, "temperature": temperature}, def _is_dashscope(base_url: str) -> bool:
timeout=180) return "dashscope" in base_url.lower()
resp.raise_for_status()
return resp.json()["choices"][0]["message"]["content"]
def _stream_openai(base_url: str, model: str, messages: list[dict], temperature: float) -> Iterator[str]: def _openai_deltas(base_url: str, model: str, messages: list[dict],
temperature: float) -> Iterator[tuple[str, str, dict]]:
"""逐块吐出 (思考增量, 输出增量, usage);usage 只在最后一块里有,没有就是空 dict。
enable_thinking / thinking_budget 与 stream_options 是 DashScope 的扩展参数,别家服务可能不认,只对它发。"""
body: dict[str, Any] = {"model": model, "messages": messages, "temperature": temperature, "stream": True}
if _is_dashscope(base_url):
body["stream_options"] = {"include_usage": True}
body.update(_thinking())
url = base_url.rstrip("/") + "/chat/completions" url = base_url.rstrip("/") + "/chat/completions"
with requests.post(url, headers={"Authorization": f"Bearer {_key()}"}, with requests.post(url, headers={"Authorization": f"Bearer {_key()}"}, json=body,
json={"model": model, "messages": messages, timeout=(15, 180), stream=True) as resp:
"temperature": temperature, "stream": True}, if resp.status_code != 200:
timeout=180, stream=True) as resp: raise RuntimeError(f"HTTP {resp.status_code} {(resp.text or '')[:200]}")
resp.raise_for_status()
for raw in resp.iter_lines(decode_unicode=False): for raw in resp.iter_lines(decode_unicode=False):
if not raw: if not raw:
continue continue
...@@ -332,12 +340,45 @@ def _stream_openai(base_url: str, model: str, messages: list[dict], temperature: ...@@ -332,12 +340,45 @@ def _stream_openai(base_url: str, model: str, messages: list[dict], temperature:
if payload == "[DONE]": if payload == "[DONE]":
break break
try: try:
delta = json.loads(payload)["choices"][0].get("delta", {}) chunk = json.loads(payload)
except Exception: except Exception: # noqa: BLE001
continue continue
piece = delta.get("content") u = chunk.get("usage") or {}
if piece: usage = {"input_tokens": u.get("prompt_tokens"), "output_tokens": u.get("completion_tokens"),
yield piece "output_tokens_details": {"reasoning_tokens": (u.get("completion_tokens_details") or {})
.get("reasoning_tokens")}} if u else {}
choices = chunk.get("choices") or []
delta = (choices[0].get("delta") or {}) if choices else {}
think, piece = delta.get("reasoning_content") or "", delta.get("content") or ""
if think or piece or usage:
yield think, piece, usage
def _chat_openai(base_url: str, model: str, messages: list[dict], temperature: float) -> str:
return "".join(piece for _, piece, _ in _openai_deltas(base_url, model, messages, temperature))
def _chat_openai_traced(base_url: str, model: str, messages: list[dict], temperature: float,
sink: Any, handle: Any) -> tuple[str, str, dict]:
"""同 _chat_dashscope_traced:边收边报给 sink(它可以借机抛 Cancelled 打断)。返回 (输出, 思考, usage)。"""
think: list[str] = []
out: list[str] = []
usage: dict = {}
last = time.time()
for t, piece, u in _openai_deltas(base_url, model, messages, temperature):
think.append(t)
out.append(piece)
usage = u or usage
if time.time() - last > 1.5:
last = time.time()
sink.update(handle, "".join(think), "".join(out))
return "".join(out), "".join(think), usage
def _stream_openai(base_url: str, model: str, messages: list[dict], temperature: float) -> Iterator[str]:
for _, piece, _ in _openai_deltas(base_url, model, messages, temperature):
if piece:
yield piece
def chat_json(messages: list[dict], temperature: float = 0.1) -> Any: def chat_json(messages: list[dict], temperature: float = 0.1) -> Any:
......
"""函数的测试用例:编辑时一键全跑,发布前自动跑(没过就不让发布)。
用例 = {name, inputs, expect};expect 的键是输出里的路径(result、result.level、value、output.紧急程度……),
值是期望值。数字按 1e-6 的误差比较,其余按字符串比较("1" 和 1 算相等)。
AI 分析函数的结论不确定,不跑用例(编辑器里也不给加);聚合函数要连业务库,照常跑。
"""
from __future__ import annotations
from typing import Any
from fastapi import HTTPException
from . import service
SKIP = ("ai",)
def _get(v: Any, path: str) -> Any:
from ..capability.actions import lookup
return lookup(path, v if isinstance(v, dict) else {"result": v})
def _same(got: Any, want: Any) -> bool:
try:
if isinstance(want, bool) or isinstance(got, bool):
return str(got).lower() in ("true", "1", "是") if str(want).lower() in ("true", "1", "是") \
else str(got).lower() in ("false", "0", "否", "none", "")
return abs(float(got) - float(want)) < 1e-6
except (TypeError, ValueError):
return str(got if got is not None else "") == str(want if want is not None else "")
def run(fn: dict, tests: list[dict] | None = None) -> list[dict]:
"""跑一个函数的用例(默认用它自己 spec 里的),返回每条的结果。"""
from ..capability import builtins
cat = (fn.get("spec") or {}).get("category")
out = []
for t in (tests if tests is not None else (fn.get("spec") or {}).get("tests")) or []:
item = {"name": t.get("name") or "", "ok": False, "got": {}, "error": ""}
if cat in SKIP:
item.update(ok=True, error="AI 分析的结论不固定,不跑用例")
out.append(item)
continue
try:
with service.draft_runtime():
res = builtins.eval_function(fn, t.get("inputs") or {}, draft=True)
bad = []
for path, want in (t.get("expect") or {}).items():
got = _get(res, path)
item["got"][path] = got
if not _same(got, want):
bad.append(f"{path} 期望 {want!r},实际 {got!r}")
item["ok"] = not bad
item["error"] = ";".join(bad)
except HTTPException as e:
item["error"] = str(e.detail)
except Exception as e: # noqa: BLE001
item["error"] = str(e)[:300]
out.append(item)
return out
def _gate(diff: dict, concept_ids: list[str] | None = None) -> tuple[bool, str]:
"""发布闸门:这次要发布的函数里,有用例没过的就拦下。"""
ids = {x["id"] for k in ("added", "changed") for x in diff.get(k) or [] if x.get("kind") == "function"}
failed = []
for cid in ids:
try:
fn = service.get_concept(cid)
except HTTPException:
continue
for r in run(fn):
if not r["ok"]:
failed.append(f"「{fn['name']}」的{r['name']}:{r['error'][:80]}")
if failed:
return False, "函数的测试用例没过 —— " + ";".join(failed[:4]) + ("……" if len(failed) > 4 else "")
return True, ""
service.register_publish_gate(_gate)
"""函数的类型化签名:六类函数(聚合 / 规则 / 周期 / 决策表 / 模型推理 / AI 分析)各自的实现方式不同,
但对外都是同一个样子 —— 一组带类型的输入、一份带类型的输出:
inputs = [{name, label, type, required, default, options, object_type, description}]
outputs = 输出结构(types 的 schema 写法:{type, label, fields: [...]} / {type: array, items})
流程卡按它生成「调用函数」的表单、知道结果里有哪些字段可以往后引用;试跑和测试用例按它准备输入;
调用一律给扁平的 inputs(不再分规则的 vars、决策表的 inputs、周期的 ref……)。
"""
from __future__ import annotations
from typing import Any
# 输入 / 输出的类型(和流程卡参数、动作参数同一套叫法)
TYPES = {"string": "文字", "number": "数字", "integer": "整数", "boolean": "是否", "date": "日期",
"choice": "单选", "object": "对象", "list": "多行数据", "period": "统计周期", "any": "任意"}
def field(name: str, label: str = "", type_: str = "any", **kw: Any) -> dict:
return {"name": name, "label": label or name, "type": type_ or "any", **kw}
def obj(fields: list[dict], label: str = "") -> dict:
return {"type": "object", "label": label, "fields": fields}
def arr(items: dict, label: str = "") -> dict:
return {"type": "array", "label": label, "items": items}
def norm_inputs(raw: Any, default_type: str = "any") -> list[dict]:
"""规整输入定义。老写法:字符串列表(规则的 params)、{name, label}(决策表 / 模型)。"""
out, seen = [], set()
for x in raw or []:
if isinstance(x, str):
x = {"name": x}
if not isinstance(x, dict):
continue
n = str(x.get("name") or "").strip()
if not n or n in seen:
continue
seen.add(n)
t = str(x.get("type") or default_type)
item = {"name": n, "label": str(x.get("label") or n), "type": t if t in TYPES else default_type,
"required": bool(x.get("required", True)), "description": str(x.get("description") or "")[:200]}
if x.get("default") not in (None, ""):
item["default"] = x["default"]
if t == "choice":
item["options"] = [str(o) for o in x.get("options") or []]
if t == "object":
item["object_type"] = str(x.get("object_type") or "")
if x.get("dimension"):
item["dimension"] = str(x["dimension"]) # 聚合函数:这个输入绑定到哪个维度的筛选
out.append(item)
return out
def _typed(fields: list[dict]) -> list[dict]:
return [field(f["name"], f.get("label") or f["name"], f.get("type") or "any") for f in fields]
def _metric_rows(fn: dict) -> dict:
from . import service as ksvc
dims = (ksvc.rt_binding(fn, "metric_expr") or {}).get("ref", {}).get("dimensions") or {}
names = list(dims) or list((fn.get("spec") or {}).get("dimensions") or [])
unit = (fn.get("spec") or {}).get("unit") or ""
return arr(obj([field(d, d, "string") for d in names] + [field("value", "数值" + (f"({unit})" if unit else ""), "number")]),
"每一行")
def signature(fn: dict) -> dict:
"""{category, inputs, outputs}。fn 是函数元素(运行时或工作副本都行)。"""
spec = fn.get("spec") or {}
cat = spec.get("category") or "rule"
if cat == "rule":
inputs = norm_inputs(spec.get("inputs") or spec.get("params"))
kind = spec.get("rule_kind") or "judgement"
rtype = spec.get("output_type") or {"judgement": "boolean", "calculation": "number"}.get(kind, "any")
outs = [field("result", "判断结果" if kind == "judgement" else "结果", rtype)]
if kind == "judgement":
outs.append(field("message", "不通过时的提示", "string"))
return {"category": cat, "inputs": inputs, "outputs": obj(outs)}
if cat == "decision":
inputs = norm_inputs(spec.get("inputs"), "number")
row = obj(_typed(spec.get("outputs") or []), "命中的输出")
many = spec.get("hit_policy") == "collect"
return {"category": cat, "inputs": inputs,
"outputs": obj([{**(arr(row) if many else row), "name": "result", "label": "输出"},
field("matched", "命中的行号", "list"), field("hit", "是否命中", "boolean")])}
if cat == "calendar":
return {"category": cat,
"inputs": [field("ref", "哪一期", "string", required=False, default="current",
description="current 本期 / last 上期 / prev:N / next / 2026-08 / 某一天")],
"outputs": obj([field("period", "期号", "string"), field("start", "开始日期", "date"),
field("end", "结束日期", "date")])}
if cat == "aggregate":
params = norm_inputs(spec.get("inputs"), "string")
inputs = [field("time", "统计时间", "period", required=False),
field("object_key", "只取某一个对象", "string", required=False),
field("dimensions", "按什么拆分", "list", required=False)] + params
outs = [field("value", "数值", "number"), {**_metric_rows(fn), "name": "rows", "label": "拆分后的每一行"},
field("period", "统计时间", "string")]
if spec.get("compare"):
outs += [field("previous", "对比期数值", "number"), field("change", "变化量", "number"),
field("change_rate", "变化率", "number")]
return {"category": cat, "inputs": inputs, "outputs": obj(outs)}
if cat == "ml":
return {"category": cat, "inputs": norm_inputs(spec.get("inputs"), "number"),
"outputs": obj([{**obj(_typed(spec.get("outputs") or [])), "name": "result", "label": "预测结果"}])}
if cat == "ai":
schema = spec.get("output_fields") or []
outs = _typed(schema) if schema else [field("conclusion", "结论", "string"), field("points", "要点", "list")]
return {"category": cat, "inputs": norm_inputs(spec.get("inputs"), "string"),
"outputs": obj([{**obj(outs), "name": "output", "label": "AI 结论(参考)"},
field("confidence", "把握程度(0~1)", "number"),
field("ai_judged", "由 AI 判断", "boolean")])}
return {"category": cat, "inputs": [], "outputs": obj([])}
def flat_inputs(fn: dict, args: dict) -> dict:
"""调用方给的参数 → 扁平 inputs。兼容老写法:{vars: {...}}(规则)、{inputs: {...}}(决策表 / 模型 / AI)。"""
args = dict(args or {})
for k in ("vars", "inputs"):
if isinstance(args.get(k), dict) and len(args) == 1:
return dict(args[k])
return args
def coerce(fn: dict, inputs: dict) -> dict:
"""按签名补默认值、转类型;必填没给报错。"""
from fastapi import HTTPException
out = dict(inputs or {})
for i in signature(fn)["inputs"]:
v = out.get(i["name"])
if v in (None, "") and i.get("default") not in (None, ""):
v = out[i["name"]] = i["default"]
if v in (None, ""):
if i.get("required") and fn.get("spec", {}).get("category") in ("decision", "ml"):
raise HTTPException(422, f"缺少输入「{i['label']}」")
continue
if i["type"] in ("number", "integer") and isinstance(v, str):
try:
out[i["name"]] = int(v) if i["type"] == "integer" else float(v)
except ValueError as e:
raise HTTPException(422, f"输入「{i['label']}」应为数字") from e
elif i["type"] == "boolean" and isinstance(v, str):
out[i["name"]] = v.strip().lower() in ("true", "1", "是", "yes")
return out
"""条件:编辑器里的「条件组」与引擎执行的规则表达式之间的转换。
条件组 = {mode: all|any, items: [条件 | 条件组]}
条件 = {left: "$变量.字段", op, right: 常量或 "$变量.字段"}
或者高级写法 {expr: "规则表达式"}
条件组编进 `when`(规则表达式,引擎求值),原样留在 `cond` 里给编辑器还原 —— 两份由 spec.normalize 保持一致。
"""
from __future__ import annotations
import re
from typing import Any
OPS = {"eq": "等于", "ne": "不等于", "gt": "大于", "ge": "大于等于", "lt": "小于", "le": "小于等于",
"contains": "包含", "not_contains": "不包含", "startswith": "开头是", "in": "属于", "not_in": "不属于",
"empty": "为空", "not_empty": "不为空", "len_gt": "条数大于", "len_eq": "条数等于",
"is_true": "为是", "is_false": "为否"}
_CMP = {"eq": "==", "ne": "!=", "gt": ">", "ge": ">=", "lt": "<", "le": "<="}
_IDENT = re.compile(r"^[A-Za-z_一-鿿][\w一-鿿]*$")
_STEP = re.compile(r"\.|(\[\d+\])")
class CondError(ValueError):
pass
def path_expr(ref: str) -> str:
"""数据引用($gap.value、$q.items[0].数量、$item.缺口 数量)→ 表达式里的写法;
不是合法标识符的字段用下标取。"""
raw = str(ref or "").strip().lstrip("$")
parts = [p for p in _STEP.split(raw) if p]
if not parts:
return "None"
head = parts[0]
out = head if _IDENT.match(head) else f"item[{head!r}]"
for p in parts[1:]:
if p.startswith("["):
out += p
else:
out += f".{p}" if _IDENT.match(p) else f"[{p!r}]"
return out
def literal(v: Any) -> str:
if isinstance(v, bool):
return "True" if v else "False"
if isinstance(v, (int, float)):
return repr(v)
if v is None:
return "None"
if isinstance(v, list):
return "[" + ", ".join(literal(x) for x in v) + "]"
s = str(v)
if s.startswith("$"):
return path_expr(s)
if s.startswith("="):
return f"({s[1:]})"
low = s.strip().lower()
if low in ("true", "是"):
return "True"
if low in ("false", "否"):
return "False"
t = s.strip()
try:
num = float(t)
except ValueError:
return repr(s)
# 「007」「1e3」这类按原样当文本(多半是编号);只有写法规整的数字才当数字比
return t if t in (repr(num), str(int(num)) if num == int(num) else "") else repr(s)
def _item_expr(it: dict) -> str:
left = str(it.get("left") or "").strip()
if not left:
return ""
op, lhs, right = str(it.get("op") or "eq"), path_expr(left), it.get("right")
if op == "empty":
return f"({lhs} == None or {lhs} == '' or {lhs} == [])"
if op == "not_empty":
return f"({lhs} != None and {lhs} != '' and {lhs} != [])"
if op == "is_true":
return f"({lhs} == True)"
if op == "is_false":
return f"({lhs} != True)"
if right in (None, "") and op not in ("in", "not_in"):
return "" # 没填值的条件当作没写
if op in ("contains", "not_contains"):
e = f"contains({lhs}, {literal(right)})"
return e if op == "contains" else f"(not {e})"
if op == "startswith":
return f"startswith({lhs}, {literal(right)})"
if op in ("in", "not_in"):
if isinstance(right, str) and right.startswith("$"):
vals = path_expr(right)
else:
items = right if isinstance(right, list) else [x.strip() for x in str(right or "").replace(",", ",").split(",")
if x.strip()]
if not items:
return ""
vals = "[" + ", ".join(literal(x) for x in items) + "]"
return f"({lhs} {'not in' if op == 'not_in' else 'in'} {vals})"
if op in ("len_gt", "len_eq"):
return f"(count({lhs}) {'>' if op == 'len_gt' else '=='} {literal(right)})"
if op in _CMP:
return f"({lhs} {_CMP[op]} {literal(right)})"
raise CondError(f"不认识的比较方式:{op}")
def to_expr(cond: Any) -> str:
"""条件组 → 规则表达式。空条件返回空串(= 不筛选 / 恒成立,由调用方决定含义)。"""
if not cond:
return ""
if isinstance(cond, str):
return cond.strip()
if not isinstance(cond, dict):
return ""
if cond.get("expr"):
return str(cond["expr"]).strip()
parts = []
for it in cond.get("items") or []:
if not isinstance(it, dict):
continue
p = f"({to_expr(it)})" if "items" in it or "expr" in it else _item_expr(it)
if p and p != "()":
parts.append(p)
if not parts:
return ""
return parts[0] if len(parts) == 1 else (" or " if cond.get("mode") == "any" else " and ").join(parts)
def normalize(v: Any, depth: int = 0) -> dict | None:
"""规整一个条件组(老数据里可能是字符串表达式)。"""
if not v:
return None
if isinstance(v, str):
return {"expr": v}
if not isinstance(v, dict):
return None
if v.get("expr"):
return {"expr": str(v["expr"])}
items: list[dict] = []
for i in v.get("items") or []:
if not isinstance(i, dict):
continue
if "items" in i or "expr" in i:
if depth < 2:
sub = normalize(i, depth + 1)
if sub:
items.append(sub)
continue
items.append({"left": str(i.get("left") or ""), "op": str(i.get("op") or "eq"), "right": i.get("right")})
return {"mode": "any" if v.get("mode") == "any" else "all", "items": items} if items else None
def refs(cond: Any) -> list[str]:
"""条件组里引用到的数据($开头的左右值)。"""
out: list[str] = []
if not isinstance(cond, dict):
return out
for it in cond.get("items") or []:
if "items" in it:
out += refs(it)
continue
for side in (it.get("left"), it.get("right")):
if isinstance(side, str) and side.startswith("$"):
out.append(side[1:])
return out
def describe(cond: Any, label=lambda r: r) -> str:
"""给人看的一句话(卡片摘要、大纲)。label 把 $引用 换成名字。"""
if not cond:
return ""
if cond.get("expr"):
return str(cond["expr"])
parts = []
for it in cond.get("items") or []:
if "items" in it:
d = describe(it, label)
if d:
parts.append(f"({d})")
continue
if not it.get("left"):
continue
left = label(it["left"])
op = OPS.get(it.get("op") or "eq", it.get("op"))
if it.get("op") in ("empty", "not_empty", "is_true", "is_false"):
parts.append(f"{left}{op}")
continue
r = it.get("right")
rv = label(r) if isinstance(r, str) and r.startswith("$") else ("是" if r is True else "否" if r is False else str(r))
parts.append(f"{left} {op} {rv}")
return (" 或 " if cond.get("mode") == "any" else " 且 ").join(parts)
"""SQL 调试台的会话。
一个会话 = 一串连续追问(同一个 thread_id 的取数记录)。每一轮在 `SqlRun.trace_json` 里存一份
回放快照(计划、SQL、结果前 200 行、结论……),重新打开会话直接还原,不用重跑。
「改 SQL 重跑」会记一条新的取数记录并标明它替换了哪一轮,会话里只显示最新的那一版。
"""
from __future__ import annotations
import datetime as dt
import json
import logging
import uuid
from typing import Any, Iterator
from fastapi import HTTPException
from sqlalchemy import select, update
from sqlalchemy.orm import Session
from ..core import identity
from ..core.db import get_engine
from . import executor
from .models import SqlRun, SqlThread
log = logging.getLogger(__name__)
SNAPSHOT_ROWS = 200
def _dict(t: SqlThread) -> dict:
return {"id": t.id, "ds_id": t.ds_id, "title": t.title or "新会话", "created_by": t.created_by,
"created_at": t.created_at.isoformat() if t.created_at else None,
"updated_at": t.updated_at.isoformat() if t.updated_at else None}
def _own(s: Session, thread_id: str) -> SqlThread:
t = s.get(SqlThread, thread_id)
if t is None or t.created_by != identity.current().id:
raise HTTPException(404, "会话不存在")
return t
def list_threads(ds_id: int) -> list[dict]:
with Session(get_engine()) as s:
rows = s.scalars(select(SqlThread).where(
SqlThread.ds_id == ds_id, SqlThread.created_by == identity.current().id)
.order_by(SqlThread.updated_at.desc()).limit(200)).all()
return [_dict(t) for t in rows]
def create(ds_id: int, title: str = "") -> dict:
with Session(get_engine()) as s:
t = SqlThread(id=uuid.uuid4().hex[:16], ds_id=ds_id, title=title[:200],
created_by=identity.current().id)
s.add(t)
s.commit()
return _dict(t)
def rename(thread_id: str, title: str) -> dict:
with Session(get_engine()) as s:
t = _own(s, thread_id)
t.title = title.strip()[:200]
s.commit()
return _dict(t)
def delete(thread_id: str) -> None:
"""删会话不删取数记录(那是审计),只是把它们从会话里摘掉。"""
with Session(get_engine()) as s:
t = _own(s, thread_id)
s.execute(update(SqlRun).where(SqlRun.thread_id == thread_id).values(thread_id=""))
s.delete(t)
s.commit()
def touch(thread_id: str, question: str = "") -> None:
"""有新一轮:更新时间;还没有标题就用第一句问题当标题。"""
if not thread_id:
return
with Session(get_engine()) as s:
t = s.get(SqlThread, thread_id)
if t is None:
return
if question and not (t.title or "").strip():
t.title = question.strip()[:60]
t.updated_at = dt.datetime.now()
s.commit()
def check(thread_id: str) -> None:
if thread_id:
with Session(get_engine()) as s:
_own(s, thread_id)
def get(thread_id: str) -> dict:
with Session(get_engine()) as s:
t = _own(s, thread_id)
runs = s.scalars(select(SqlRun).where(SqlRun.thread_id == thread_id).order_by(SqlRun.id)).all()
snaps = [(r, _load(r.trace_json)) for r in runs]
replaced = {int(sn.get("replaces") or 0) for _, sn in snaps}
turns = []
for r, sn in snaps:
if r.id in replaced or not sn.get("v"):
continue
turns.append({"run_id": r.id, "question": r.question or "", "status": r.status,
"rating": r.rating, "sql": r.sql_final or r.sql_text or "",
"duration_ms": r.duration_ms, "error": r.error or "",
"created_at": r.created_at.isoformat() if r.created_at else None, **sn})
return {**_dict(t), "turns": turns}
def _load(raw: str) -> dict:
try:
v = json.loads(raw or "{}")
except Exception: # noqa: BLE001
return {}
return v if isinstance(v, dict) else {}
def save_snapshot(run_id: int, snap: dict) -> None:
with Session(get_engine()) as s:
s.execute(update(SqlRun).where(SqlRun.id == run_id).values(
trace_json=json.dumps(snap, ensure_ascii=False, default=str)[:3_000_000]))
s.commit()
def patch_snapshot(run_id: int, **fields: Any) -> None:
with Session(get_engine()) as s:
r = s.get(SqlRun, run_id)
if r is None:
return
snap = _load(r.trace_json)
if not snap.get("v"):
return
snap.update(fields)
r.trace_json = json.dumps(snap, ensure_ascii=False, default=str)[:3_000_000]
s.commit()
def snapshot(**fields: Any) -> dict:
rows = fields.pop("rows", None) or []
return {"v": 1, "rows": rows[:SNAPSHOT_ROWS], **fields}
def record(gen: Iterator[dict], ds_id: int, question: str, thread_id: str) -> Iterator[dict]:
"""把管线事件原样往外推,同时攒一份回放快照,结束时存到这一轮的取数记录上。
管线只有跑到执行那一步才记取数记录;澄清、直接回答、半路失败这些结局在这里补记,
会话里每一轮都要留得住。"""
snap: dict = {"outcome": "", "plan": {}, "calibre": "", "clarify": "", "answer": "", "summary": "",
"columns": [], "rows": [], "truncated": False, "issues": [], "retrieve": None, "error": ""}
sql = ""
run_id = 0
for ev in gen:
t = ev.get("type")
if t == "retrieve":
snap["retrieve"] = ev
elif t == "plan":
snap["plan"], snap["calibre"] = ev.get("plan") or {}, ev.get("calibre") or ""
snap["clarify"] = ev.get("clarify") or ""
elif t == "answer":
snap["answer"] = ev.get("text") or ""
elif t == "sql_draft":
sql = ev.get("sql") or sql
elif t == "validate":
snap["issues"] = ev.get("issues") or []
if ev.get("ok"):
sql = ev.get("sql") or sql
elif t == "execute":
sql = ev.get("sql") or sql
snap["truncated"] = bool(ev.get("truncated"))
elif t == "rows":
snap["columns"], snap["rows"] = ev.get("columns") or [], ev.get("rows") or []
elif t == "summary":
snap["summary"] = ev.get("text") or ""
elif t == "error":
snap["error"] = ev.get("error") or ""
sql = ev.get("sql") or sql
elif t == "done":
snap["outcome"] = ev.get("outcome") or ""
snap["clarify"] = ev.get("clarify") or snap["clarify"]
snap["answer"] = ev.get("answer") or snap["answer"]
run_id = int(ev.get("run_id") or 0)
try:
full = snapshot(**snap)
if run_id:
save_snapshot(run_id, full)
else:
status = {"clarify": "clarify", "metadata": "answer", "not_data": "answer"}.get(
snap["outcome"], "failed")
run_id = executor.log_run(ds_id, question, sql, sql, status, thread_id=thread_id,
plan=snap["plan"], error=snap["error"], trace=full)
ev = {**ev, "run_id": run_id}
touch(thread_id, question)
except Exception: # noqa: BLE001 会话留痕失败不能影响这一轮的回答
log.exception("保存会话快照失败")
yield ev
"""为模型对比建独立的元数据库:从 9101 复制 系统设置 + 数据源 + 语义模型(表/列/关系)+ 角色,不带任何本体 / 草案 / 建模记录。
用法:prep_clones.py <tag> [<tag> ...] 库名 ai_ontology_cmp_<tag>,数据目录 scratchpad/data_<tag>
"""
import os, sys, subprocess
ROOT = r"D:\code\onto_query"
SCR = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, ROOT); os.chdir(ROOT)
sys.stdout.reconfigure(encoding="utf-8")
from sqlalchemy import create_engine, text
from app.core.config import get_settings
st = get_settings()
SRC = "ai_ontology_9101"
COPY = ["otlg_config", "otlg_datasource", "otlg_sm_model", "otlg_sm_column", "otlg_sm_relation", "otlg_biz_role", "otlg_workspace"]
root = create_engine(st.url_for(st.db_name), future=True)
for tag in sys.argv[1:]:
db = f"ai_ontology_cmp_{tag}"
data = os.path.join(SCR, "_data", tag)
with root.begin() as c:
c.execute(text(f"DROP DATABASE IF EXISTS `{db}`"))
c.execute(text(f"CREATE DATABASE `{db}` DEFAULT CHARACTER SET utf8mb4"))
env = {**os.environ, "DB_NAME": db, "DATA_DIR": data}
subprocess.run([sys.executable, "-c",
"from app.core import db; db.init_db(); from app.governance import users; users.seed(); print('init ok')"],
cwd=ROOT, env=env, check=True)
with root.begin() as c:
for t in COPY:
c.execute(text(f"DELETE FROM `{db}`.`{t}`"))
c.execute(text(f"INSERT INTO `{db}`.`{t}` SELECT * FROM `{SRC}`.`{t}`"))
n = {t: c.execute(text(f"SELECT COUNT(*) FROM `{db}`.`{t}`")).scalar() for t in COPY}
print(tag, db, n)
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
"""在一个克隆库里用指定模型跑一遍 AI 建模流水线(读 docs/demo3_wms 的手册 + 已接入的 WMS 数据源),记录耗时与产出。
用法:run_cmp.py <tag> <model> [round]
所有模型统一走 DashScope OpenAI 兼容接口(流式,带 enable_thinking / thinking_budget),保证条件一致。
"""
import os, sys, json, time, traceback, datetime as dt
ROOT = r"D:\code\onto_query"
SCR = os.path.dirname(os.path.abspath(__file__))
tag, model = sys.argv[1], sys.argv[2]
rnd = sys.argv[3] if len(sys.argv) > 3 else "1"
THINK = sys.argv[4] if len(sys.argv) > 4 else "auto"
os.environ["DB_NAME"] = f"ai_ontology_cmp_{tag}"
os.environ["DATA_DIR"] = os.path.join(SCR, "_data", tag)
os.chdir(ROOT); sys.path.insert(0, ROOT)
sys.stdout.reconfigure(encoding="utf-8")
OUT = os.path.join(SCR, "results"); os.makedirs(OUT, exist_ok=True)
LOG = open(os.path.join(OUT, f"{tag}_r{rnd}.log"), "w", encoding="utf-8", buffering=1)
def say(*a):
LOG.write(dt.datetime.now().strftime("%H:%M:%S ") + " ".join(str(x) for x in a) + "\n")
import requests
from app.core import db, llm
from app.core.config import get_settings
import app.main # noqa: F401 注册系统工具、审核处理器、发布闸门(真实服务启动时会做)
key = get_settings().dashscope_api_key
URL = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"
def compat_stream(model_, messages, temperature, sink=None, handle=None):
body = {"model": model_, "messages": messages, "temperature": temperature, "stream": True,
"stream_options": {"include_usage": True}, **llm._thinking()}
think, out, usage, last = [], [], {}, time.time()
with requests.post(URL, headers={"Authorization": f"Bearer {key}"}, json=body, stream=True, timeout=(15, 180)) as r:
if r.status_code != 200:
raise RuntimeError(f"HTTP {r.status_code} {r.text[:200]}")
for raw in r.iter_lines(decode_unicode=False):
if not raw:
continue
line = raw.decode("utf-8", errors="replace").strip()
if not line.startswith("data:"):
continue
p = line[5:].strip()
if p == "[DONE]":
break
try:
j = json.loads(p)
except Exception:
continue
if j.get("usage"):
u = j["usage"]
usage = {"input_tokens": u.get("prompt_tokens"), "output_tokens": u.get("completion_tokens"),
"output_tokens_details": {"reasoning_tokens": (u.get("completion_tokens_details") or {}).get("reasoning_tokens")}}
ch = (j.get("choices") or [])
if not ch:
continue
d = ch[0].get("delta") or {}
think.append(d.get("reasoning_content") or "")
out.append(d.get("content") or "")
if sink is not None and time.time() - last > 1.5:
last = time.time()
sink.update(handle, "".join(think), "".join(out))
return "".join(out), "".join(think), usage
def traced(model_, messages, temperature, sink, handle):
return compat_stream(model_, messages, temperature, sink, handle)
def plain(model_, messages, temperature):
return compat_stream(model_, messages, temperature)[0]
llm._chat_dashscope_traced = traced
llm._chat_dashscope = plain
db.set_config({"QWEN_MODEL": model, "LLM_CACHE": "0", "LLM_BASE_URL": "", "LLM_THINKING": THINK,
"LLM_THINKING_BUDGET": "4096"})
from app.kernel import modeling # noqa: E402
doc = os.path.join(ROOT, "docs", "demo3_wms", "配件库存补货业务手册.md")
raw = open(doc, "rb").read()
res: dict = {"tag": tag, "model": model, "round": rnd}
t0 = time.time()
try:
run = modeling.create(f"对比-{tag}", files=[("配件库存补货业务手册.md", raw)], ds_ids=[1])
rid = run["id"]
res["run_id"] = rid
say("created", rid, "stages", [s["key"] + ":" + s["status"] for s in run["stages"]])
last = ""
for ev in modeling.execute(rid):
m = f"{ev.get('stage')} {ev.get('progress')} {ev.get('message', '')}"
if m != last:
say(m); last = m
res["wall_s"] = round(time.time() - t0, 1)
g = modeling.get(rid)
res["status"] = g["status"]; res["error"] = g["error"]
res["stages"] = [{"key": s["key"], "status": s["status"], "started_at": s["started_at"], "ended_at": s["ended_at"],
"counts": s["counts"], "log": [x["msg"] for x in s["log"]]} for s in g["stages"]]
res["elapsed_ms"] = g["elapsed_ms"]
res["call_stats"] = g["call_stats"]
res["calls"] = modeling.calls(rid)
items = {k: [{"id": it["id"], "name": (it["payload"] or {}).get("name"), "status": it["status"],
"confidence": it.get("confidence"), "payload": it["payload"]} for it in v]
for k, v in g["items"].items()}
res["items"] = items
res["sops"] = g["sops"]
# 采纳全部草案并上线,看有多少能真正落地
ids = [it["id"] for v in g["items"].values() for it in v]
sids = [s["id"] for s in g["sops"]]
t1 = time.time()
try:
ad = modeling.adopt(rid, ids, sids)
res["adopt"] = {"accepted": len(ad["accepted"]), "failed": ad["failed"], "published": ad["published"],
"held": ad["held"], "warnings": len(ad.get("warnings") or []), "sops": ad["sops"],
"adopt_s": round(time.time() - t1, 1)}
except BaseException as e: # noqa: BLE001
res["adopt"] = {"error": str(e)[:500]}
except BaseException as e: # noqa: BLE001
res["fatal"] = traceback.format_exc()[-1500:]
res["wall_s"] = round(time.time() - t0, 1)
say("FATAL", str(e)[:300])
json.dump(res, open(os.path.join(OUT, f"{tag}_r{rnd}.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1, default=str)
say("DONE wall", res.get("wall_s"))
import json, sys, os, glob, re, datetime as dt, statistics as stt
sys.stdout.reconfigure(encoding="utf-8")
S = os.path.dirname(os.path.abspath(__file__))
names = {"b0": "v4-flash-0731(现用)", "f1": "v4.1-flash(默认思考)", "f1n": "v4.1-flash(关思考)", "p0": "v4-pro", "q7": "qwen3.7-plus", "b0n": "v4-flash-0731(关思考)", "p0n": "v4-pro(关思考)", "q7n": "qwen3.7-plus(关思考)"}
GROUP = {"f1n2": "f1n", "f1n3": "f1n"}
def secs(a, b):
if not a or not b: return 0
return (dt.datetime.fromisoformat(b) - dt.datetime.fromisoformat(a)).total_seconds()
def cover(r):
it = r["items"]
fn = json.dumps(it["function"], ensure_ascii=False)
act = json.dumps(it["action"], ensure_ascii=False)
sop = json.dumps([[s["title"], s.get("outline")] for s in r["sops"]], ensure_ascii=False)
allt = fn + act + sop
exprs = []
for x in it["function"]:
sp = (x["payload"].get("spec") or {})
exprs.append(str(sp.get("expression") or ""))
for b in x["payload"].get("bindings") or []:
if b.get("target_kind") == "metric_expr":
exprs.append(str(b["ref"].get("expression") or ""))
exprs.append(json.dumps(sp.get("rows") or [], ensure_ascii=False))
ex = " ".join(exprs)
names_ = " ".join(str(x["payload"].get("name")) for k in ("function", "action") for x in it[k]) + " " + " ".join(s["title"] for s in r["sops"])
chk = {
"建议量=期望-(库存+在途)": bool(re.search(r"(expected|target|期望|reorder)", ex) and re.search(r"(transit|在途)", ex) and re.search(r"(on_hand|inventory|库存|stock)", ex)),
"封顶min(建议,当日可订)": bool(re.search(r"min\(", ex) and re.search(r"(daily|avail|remaining|可订|limit)", ex)) or ("可订" in names_ and "封顶" in names_),
"只认广州仓/华南仓": ("广州仓" in allt and "华南仓" in allt) or bool(re.search(r"(gz|guangzhou).*(hn|south|huanan)|(wh_gz|wh_south)", ex)),
"厂家缺货→不订并提醒": "缺货" in names_,
"一天只订一次": bool(re.search(r"(一次|once|order_count|ordered_today|每日只能)", allt)),
"订单类型SO": "'SO'" in allt or "SO" in names_ or "SO 类型" in allt,
"16:00截单/当日作废": bool(re.search(r"(16|截单)", ex + names_ + sop)) and bool(re.search(r"(作废|void|cutoff|截|expire)", allt)),
"5分钟×3次提醒": bool(re.search(r"(remind|提醒|催办)", allt)) and bool(re.search(r"(< ?3|<= ?3|3 ?次|最多 ?3)", allt)),
"先建单(待确认)再提交": "待确认" in allt and "提交" in allt,
"记录未订原因": bool(re.search(r"(未订|原因|reason)", allt)),
"计划员改量/划掉/整单不订": ("划掉" in allt or "删除" in allt) and ("整单" in allt) and bool(re.search(r"(修改|调整|改)", allt)),
"指标:低于期望库存": "低于期望" in names_ or "低于" in names_,
"指标:库存为0": bool(re.search(r"(库存为 ?0|为0的|零库存)", names_)),
"指标:长期缺货": "长期缺货" in names_,
"指标:出库量": "出库" in names_,
}
return chk
rows = []
for p in sorted(glob.glob(os.path.join(S, "results", "*_r*.json"))):
r = json.load(open(p, encoding="utf-8"))
if r.get("fatal") or r.get("status") != "done":
print("SKIP", p, r.get("fatal", "")[:200]); continue
st = {s["key"]: s for s in r["stages"]}
calls = r["calls"]
it = r["items"]
objs = it["object_type"]
bound = sum(1 for x in objs if any(b["target_kind"] == "table" for b in x["payload"].get("bindings") or []))
links = it["link_type"]
lbound = sum(1 for x in links if x["payload"].get("bindings"))
fn = it["function"]
rule_ok = sum(1 for x in fn if (x["payload"].get("spec") or {}).get("category") in ("rule",) and (x["payload"]["spec"].get("expression")))
dec_ok = sum(1 for x in fn if (x["payload"].get("spec") or {}).get("category") == "decision" and x["payload"]["spec"].get("rows"))
met_ok = sum(1 for x in fn if (x["payload"].get("spec") or {}).get("category") == "aggregate" and any(b.get("target_kind") == "metric_expr" for b in x["payload"].get("bindings") or []))
met_all = sum(1 for x in fn if (x["payload"].get("spec") or {}).get("category") == "aggregate")
act = it["action"]
act_ok = sum(1 for x in act if not (x["payload"].get("spec") or {}).get("_stub"))
sops = r["sops"]
sop_steps = [s["step_count"] for s in sops]
ad = r.get("adopt") or {}
sop_pub = sum(1 for v in (ad.get("sops") or {}).values() if not v)
cov = cover(r)
rr = dict(tag=GROUP.get(r["tag"], r["tag"]), raw=r["tag"], rnd=r["round"], wall=r["wall_s"],
convert=secs(st["convert"]["started_at"], st["convert"]["ended_at"]),
deepen=secs(st["deepen"]["started_at"], st["deepen"]["ended_at"]),
sop=secs(st["sop"]["started_at"], st["sop"]["ended_at"]),
calls=len(calls), fail=sum(c["status"] != "done" for c in calls),
ptok=sum(c["prompt_tokens"] for c in calls), otok=sum(c["output_tokens"] for c in calls), rtok=sum(c["reasoning_tokens"] for c in calls),
obj=len(objs), obj_bound=bound, link=len(links), link_bound=lbound, fn=len(fn), rule_ok=rule_ok, dec_ok=dec_ok, met_ok=met_ok, met_all=met_all,
act=len(act), act_ok=act_ok, sops=len(sops), sop_steps=sop_steps,
published=ad.get("published"), held=len(ad.get("held") or {}), sop_pub=sop_pub,
cov=sum(cov.values()), covd=cov)
rows.append(rr)
print(f"{'tag':4s} r wall conv deep sop calls fail ptok otok rtok | obj/bnd link/bnd fn(rule ok,dec ok,met ok/all) act ok/all sops steps | 上线 held sopPub | 覆盖/15")
for x in rows:
print(f"{x['raw']:4s} {x['rnd']} {x['wall']:6.0f} {x['convert']:4.0f} {x['deepen']:4.0f} {x['sop']:4.0f} {x['calls']:4d} {x['fail']:3d} {x['ptok']:7d} {x['otok']:6d} {x['rtok']:7d} | "
f"{x['obj']}/{x['obj_bound']} {x['link']}/{x['link_bound']} {x['fn']}({x['rule_ok']},{x['dec_ok']},{x['met_ok']}/{x['met_all']}) {x['act_ok']}/{x['act']} {x['sops']} {x['sop_steps']} | {x['published']} {x['held']} {x['sop_pub']} | {x['cov']}")
print()
by = {}
for x in rows: by.setdefault(x["tag"], []).append(x)
print("均值(轮数 n)")
for t, xs in by.items():
m = lambda k: stt.mean(x[k] for x in xs)
print(f"{names[t]:20s} n={len(xs)} wall={m('wall')/60:.1f}min [{min(x['wall'] for x in xs)/60:.1f}~{max(x['wall'] for x in xs)/60:.1f}] "
f"calls={m('calls'):.0f} reason_tok={m('rtok')/1000:.0f}k out_tok={m('otok')/1000:.0f}k in_tok={m('ptok')/1000:.0f}k "
f"fn={m('fn'):.0f} act_ok={m('act_ok'):.1f}/{m('act'):.0f} met_ok={m('met_ok'):.1f}/{m('met_all'):.1f} rule_ok={m('rule_ok'):.1f} 覆盖={m('cov'):.1f}/15 held={m('held'):.1f} "
f"sop步数={[x['sop_steps'] for x in xs]}")
print()
print("覆盖明细(各轮命中数)")
keys = list(rows[0]["covd"].keys())
for k in keys:
print(f" {k:24s}", {t: sum(x['covd'][k] for x in xs) for t, xs in by.items()}, "/ n=", {t: len(xs) for t, xs in by.items()})
# AI 建模模型选型对比(配件库存补货手册)
2026-10-16。输入是 `docs/demo3_wms/配件库存补货业务手册.md`,加上已内省的 WMS 数据源(8 张 `otlg_dm3_*` 表)。
跑的是完整的 5 环节流水线(对上数据表 → 读文档 → 规则变成可算的 → 起草流程卡 → 汇总草案),跑完再「全部采纳并上线」检查能不能落地。
## 先说结论
| | 默认配置(起草类环节思考,预算 4096) | 关闭思考 |
|---|---|---|
| **推荐:qwen3.7-plus** | 平均 **12.1 分钟**(11.3~13.1,最稳);草案最「干净」,动作补全率最高 | 3.8 分钟,但草案明显变薄,不建议 |
| deepseek-v4-flash-0731(现用) | 平均 14.2 分钟(9.4~20.2,波动大);召回最全,动作补全率最低 | 2.2 分钟(只跑 1 次) |
| deepseek-v4.1-flash | 平均 17.5 分钟(比现用还慢);指标绑定最好 | **1.7 分钟**(3 次),骨架可用,指标和动作要人补 |
| deepseek-v4-pro | 平均 19.0 分钟,最慢,3 次里 2 次流程卡是空的 | 4.8 分钟 |
- **想要「质量稳 + 速度可接受」→ qwen3.7-plus。**
- 想要「最全、宁多勿漏」,并接受人工删减 → 留着 deepseek-v4-flash-0731。
- **想要「几分钟出一个骨架,人再补」→ deepseek-v4.1-flash 关思考(1.7 分钟)。** 它的指标几乎都没绑上数据(平均 0.3/4.7),动作补全 2.7/8。
- **不推荐 deepseek-v4-pro**:最慢,召回最低,起草流程卡时 2/3 次出空流程卡,且思考预算用完后推理过程会漏进答案正文。
- 你要对比的 **deepseek-v4.1-pro 在 DashScope 上不存在**(`model_not_found`),我用最接近的 `deepseek-v4-pro` 代替。
> 样本量很小(每个配置 3 次、同一份文档),模型之间的质量差别和同一个模型两次之间的波动差不多大。
> 比较稳的结论是耗时、失败形态和配置兼容性;「谁的规则写得更对」只能说倾向,不能说定论。
## 耗时(分钟,默认配置,3 次)
| 模型 | 3 次墙钟 | 平均 | 读文档 | 规则深化 | 流程卡 | 思考 token(平均) | 输出 token | AI 调用数 |
|---|---|---|---|---|---|---|---|---|
| qwen3.7-plus | 11.9 / 13.1 / 11.3 | **12.1** | 3.0 | 5.3 | 3.8 | 72k | 25k | 25 |
| deepseek-v4-flash-0731 | 13.1 / 9.4 / 20.2 | 14.2 | 3.9 | 6.4 | 3.9 | 124k | 60k | 39 |
| deepseek-v4.1-flash | 19.0 / 18.7 / 14.8 | 17.5 | 7.1 | 4.5 | 5.8 | **173k** | 49k | 42 |
| deepseek-v4-pro | 19.9 / 15.6 / 21.4 | 19.0 | 3.7 | 8.7 | 6.6 | 70k | 33k | 33 |
关思考:v4.1-flash 1.5 / 1.8 / 1.8;v4-flash-0731 2.2;qwen3.7-plus 3.8;v4-pro 4.8(后三个各 1 次)。
两点值得注意:
- deepseek-v4.1-flash **不遵守 `thinking_budget`**:读文档 3 次调用思考了 44k~54k token(别的模型被卡在 12k 左右),所以比现用模型还慢。
- 全部 18 次默认配置/关思考的运行,AI 调用失败数都是 0。
## 质量(默认配置,3 次平均;括号内为各次)
| 指标 | qwen3.7-plus | v4-flash-0731 | v4.1-flash | v4-pro |
|---|---|---|---|---|
| 对象 / 关系(手册对应 8 张表 / 7 条关联) | 8 / 7,每次都对 | 8~9 / 7~8 | 8~9 / 7~8 | 8 / 7,每次都对 |
| 多出来、没绑表的重复对象 | 0 次 | 1/3 次 | 2/3 次 | 0 次 |
| 函数条数 | 11 | 18 | 16 | 12 |
| 指标:对上数据并试算通过 / 总数 | 2.7 / 3.0 | 3.0 / 5.3 | **4.0 / 4.0** | 1.3 / 2.0 |
| 动作:补全参数和效果 / 总数 | **5.3 / 7** | 2.3 / 8 | 5.3 / 10 | 4.3 / 9 |
| 流程卡不是空的 | 2/3(0 / 8 / 13 步) | 3/3(13 / 19 / 5 张) | 3/3(11 / 4 张 / 13 步) | **1/3**(10 / 0 / 0 步) |
| 手册 §五「日常盯一盯」的 4 个监控指标(每次命中几个) | 0 | **2.7 / 4** | 1.3 / 4 | 0 |
| 全部采纳后被体检挡在草稿的元素数 | 0 | 0~2 | 0~8 | 0 |
我读了产出的内容,印象是:
- qwen3.7-plus:规则表达式最规矩(`max(0, expected_qty - (on_hand + in_transit))`、`warehouse_name in ['广州仓','华南仓']`),很少有凑数的条目;缺点是偏保守,手册里的监控指标一条没提。
- v4-flash-0731:什么都提,所以召回最全,也有噪声(例如「是否需补货」写成 `on_hand + in_transit >= expected_qty`,和名字的意思相反;出库量指标里把 `move_type` 写成 `'out'`,而库里存的是 `'出库'`,算出来会是 0)。
- v4.1-flash:指标写得最好、全部绑上;流程卡能直接发布的最多,但流程里很多步骤是「人工任务」而不是自动执行;有些规则是空话(例如「期望库存口径:`expected_inventory == planner_expected_inventory`」)。
- v4-pro:有一次「可订数量限制」写成了 `min(建议量, 广州仓库存 + 华南仓库存)`,把厂家仓库存当成了当日可订数,是语义错误。
## 配置兼容性(切换模型前要知道)
1. `deepseek-v4.1-flash`、`qwen3.7-plus` 用 DashScope 原生 SDK 调用会报 `url error`,**只能走 OpenAI 兼容接口**(`https://dashscope.aliyuncs.com/compatible-mode/v1`)。
2. 现在代码里 `LLM_BASE_URL` 有值时走的 `_chat_openai` 是**非流式、不带 `enable_thinking` / `thinking_budget`、180 秒超时、不记思考过程**。
也就是说,直接把 `QWEN_MODEL` 改成这两个模型并填上 `LLM_BASE_URL`,跑出来的耗时会和本报告不一样(思考不受限,建模页也看不到思考过程)。
本报告的跑批脚本统一用「兼容接口 + 流式 + 同样的思考参数」,所以几个模型的条件一致。要上线这两个模型,`app/core/llm.py` 需要补这一段。
3. `thinking_budget` 的表现:v4-flash-0731 和 v4-pro、qwen3.7-plus 都会被卡住;v4.1-flash 不会。
## 顺带发现的两个流水线问题(与模型无关,所有模型都会遇到)
- **流程卡会被「错误条数更少」的空稿替换**。`app/sop/draft.py` 起草后若校验有错,会让模型改一次,然后只在「新稿的错误条数 < 旧稿」时才采用新稿。
第一稿解析失败成空稿(只有 1 条错误「没有任何步骤」)时,一个 21 步但有 10 条小错误的第二稿会被丢掉,留下 0 步的流程卡。v4-pro、qwen3.7-plus 的空流程卡就是这么来的。
- **流程卡里「写数据」步骤常引用不存在的属性**(「补货单」没有属性「订单号」「订单类型」…)。几乎所有模型的流程卡都因此在采纳时发布不了,原因是起草流程卡时给模型的目录里没有各对象的属性清单。
## 怎么复现
脚本在本目录:
```bash
python prep_clones.py b0 f1 p0 q7 # 从 9101 复制数据源和语义模型,建独立元数据库 ai_ontology_cmp_<tag>
python run_cmp.py b0 deepseek-v4-flash-0731 1 auto # tag 模型 轮次 思考模式(auto|off)
python score.py # 汇总(读取 out/*.json)
```
`run_cmp.py` 里的 `import app.main` 不能省:它会注册系统工具和发布闸门,漏掉的话动作补全和流程卡会全部变成空的(我第一轮就踩了,数据已作废重跑)。
原始结果在 `results/`,每个文件含草案全文、每次 AI 调用的耗时和 token。
## 实验条件
- 每个模型一个从 9101 克隆的元数据库,只带系统设置、数据源和表结构,没有任何本体或建模记录;你 9101 里的数据没动。
- `LLM_CACHE=0`,`LLM_THINKING=auto`(或 off),`LLM_THINKING_BUDGET=4096`,其余不变。
- 同一轮里几个模型是同时跑的(各自的接口,互不排队),所以耗时里含一些服务端波动。
- 另外一次用你 9101 当前模型(走 SDK)实际跑的结果:12 分 14 秒,对象 8 / 关系 7 / 函数 19 / 动作 9 / 流程卡 1,和本报告里 v4-flash-0731 的范围吻合。
"""OpenAI 兼容接口(LLM_BASE_URL 有值时):带思考参数、流式、接入调用追踪、能被终止。
不连网:requests.post 换成按行吐 SSE 的假响应。
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).parent))
from app.core import llm
from app.governance import llmlog
from test_platform import env # noqa: F401
DS = "https://dashscope.aliyuncs.com/compatible-mode/v1"
def sse(*chunks: dict) -> list[bytes]:
return [b"data: " + json.dumps(c, ensure_ascii=False).encode() for c in chunks] + [b"", b"data: [DONE]"]
def delta(think: str = "", text: str = "") -> dict:
return {"choices": [{"delta": {"reasoning_content": think, "content": text}}]}
USAGE = {"choices": [], "usage": {"prompt_tokens": 30, "completion_tokens": 20,
"completion_tokens_details": {"reasoning_tokens": 12}}}
class FakeResp:
def __init__(self, lines: list[bytes], status: int = 200, text: str = ""):
self.lines, self.status_code, self.text = lines, status, text
def __enter__(self):
return self
def __exit__(self, *a):
return False
def iter_lines(self, decode_unicode=False):
yield from self.lines
@pytest.fixture()
def post(monkeypatch):
"""记下每次请求体;每次返回 post.next 里排好的响应。"""
sent: list[dict] = []
queue: list[FakeResp] = []
def fake(url, headers=None, json=None, timeout=None, stream=False): # noqa: A002
sent.append({"url": url, "body": json, "stream": stream, "timeout": timeout})
return queue.pop(0)
monkeypatch.setattr(llm.requests, "post", fake)
monkeypatch.setattr(llm.time, "sleep", lambda s: None)
fake.sent, fake.queue = sent, queue
return fake
@pytest.fixture()
def cfg(monkeypatch):
vals = {"QWEN_MODEL": "qwen3.7-plus", "LLM_BASE_URL": DS, "LLM_THINKING": "auto", "LLM_THINKING_BUDGET": "4096",
"LLM_CACHE": "0"}
monkeypatch.setattr(llm.db, "get_config", lambda k, d=None: vals.get(k, d if d is not None else ""))
return vals
class Sink:
def __init__(self, cancel_at: int = 0):
self.updates, self.ended, self.began, self.cancel_at = [], [], [], cancel_at
def begin(self, label, feature, model, prompt):
self.began.append((label, feature, model))
return len(self.began)
def update(self, h, reasoning, output):
self.updates.append((reasoning, output))
if self.cancel_at and len(self.updates) >= self.cancel_at:
raise llm.Cancelled()
def end(self, h, **kw):
self.ended.append(kw)
MSGS = [{"role": "user", "content": "你好"}]
def test_非追踪_累加输出_思考不进正文(post, cfg):
post.queue.append(FakeResp(sse(delta("先想", ""), delta("再想", ""), delta("", "好"), delta("", "的"), USAGE)))
assert llm.chat(MSGS, use_cache=False) == "好的"
sent = post.sent[0]
assert sent["url"] == DS + "/chat/completions" and sent["stream"] is True
assert sent["timeout"] == (15, 180) # 只限两块之间的空档,思考再长不会撞整体超时
@pytest.mark.parametrize("feature,mode,want", [
("modeling_deepen", "auto", {"thinking_budget": 4096}), # 起草类:思考,但限预算
("ask", "auto", {}), # 提问:思考不限
("modeling_metric_unknown", "auto", {"enable_thinking": False}), # 不在白名单:不思考
("ask", "off", {"enable_thinking": False}),
])
def test_带上思考参数(post, cfg, feature, mode, want):
cfg["LLM_THINKING"] = mode
post.queue.append(FakeResp(sse(delta("", "x"))))
with llmlog.feature(feature):
llm.chat(MSGS, use_cache=False)
body = post.sent[0]["body"]
assert body["stream_options"] == {"include_usage": True}
for k in ("enable_thinking", "thinking_budget"):
assert body.get(k) == want.get(k)
assert ("enable_thinking" in body) == ("enable_thinking" in want)
assert ("thinking_budget" in body) == ("thinking_budget" in want)
def test_别家服务不发扩展参数(post, cfg):
cfg["LLM_BASE_URL"] = "http://localhost:8000/v1"
cfg["LLM_THINKING"] = "off"
post.queue.append(FakeResp(sse(delta("", "x"))))
llm.chat(MSGS, use_cache=False)
body = post.sent[0]["body"]
assert not {"enable_thinking", "thinking_budget", "stream_options"} & set(body)
assert body["stream"] is True
def test_追踪_思考过程_用量_耗时(post, cfg, monkeypatch):
t = iter([0.0, 0.0, 2.0, 4.0, 6.0, 6.0, 6.0, 6.0]) # 让「约每 1.5 秒报一次」每块都触发
monkeypatch.setattr(llm.time, "time", lambda: next(t, 9.0))
post.queue.append(FakeResp(sse(delta("想一", ""), delta("想二", ""), delta("", "答"), USAGE)))
sink = Sink()
with llm.tracing(sink, "读文档"), llmlog.feature("modeling_deepen"):
assert llm.chat(MSGS, use_cache=False) == "答"
assert sink.began and sink.began[0][0] == "读文档" and sink.began[0][2] == "qwen3.7-plus"
assert sink.updates and sink.updates[-1][0].startswith("想一")
end = sink.ended[0]
assert end["output"] == "答" and end["reasoning"] == "想一想二"
assert end["usage"] == {"input_tokens": 30, "output_tokens": 20, "output_tokens_details": {"reasoning_tokens": 12}}
def test_追踪_建模记录里拆出思考token(env, post, cfg):
"""和 modeling._Calls 对接:usage 里 output_tokens 含思考,记录里要拆成输出 + 思考。"""
from app.core.dbx import session
from app.kernel import modeling
from app.kernel.models import ModelCall
doc = ("# 工单\n\n" + "内容。" * 50).encode("utf-8")
run = modeling.create("工单", files=[("工单.md", doc)], ds_ids=[], stages=["convert", "draft"])
post.queue.append(FakeResp(sse(delta("想", "答"), USAGE)))
with llm.tracing(modeling._Calls(run["id"], "convert"), "读文档"):
assert llm.chat(MSGS, use_cache=False) == "答"
with session() as s:
row = s.query(ModelCall).filter(ModelCall.run_id == run["id"]).one()
assert row.status == "done" and row.reasoning == "想" and row.output == "答"
assert (row.prompt_tokens, row.output_tokens, row.reasoning_tokens) == (30, 8, 12)
def test_追踪_终止不重试(post, cfg, monkeypatch):
post.queue.append(FakeResp(sse(delta("想", ""))))
post.queue.append(FakeResp(sse(delta("不该被请求", ""))))
sink = Sink(cancel_at=1)
seq = iter(range(0, 1000, 5)) # 每次取时间都过了 5 秒:第一块就触发 update
monkeypatch.setattr(llm.time, "time", lambda: next(seq))
with llm.tracing(sink, "x"):
with pytest.raises(llm.Cancelled):
llm.chat(MSGS, use_cache=False)
assert len(post.sent) == 1 # 终止了就别再请求
assert sink.ended and sink.ended[0]["error"] == "已终止"
def test_HTTP出错_重试后报错并带上返回内容(post, cfg):
for _ in range(3):
post.queue.append(FakeResp([], status=400, text='{"error":"url error"}'))
with pytest.raises(RuntimeError, match="url error"):
llm.chat(MSGS, use_cache=False)
assert len(post.sent) == 3
def test_流式提问_也带思考参数(post, cfg):
cfg["LLM_THINKING"] = "off"
post.queue.append(FakeResp(sse(delta("想", ""), delta("", "你"), delta("", "好"))))
assert "".join(llm._stream_openai(DS, "m", MSGS, 0.3)) == "你好" # 思考不当作回答吐出去
assert post.sent[0]["body"]["enable_thinking"] is False
"""v10 新增的几块纯逻辑:公式编译成 SQL、一次请求内的缓存、模型思考开关。"""
from __future__ import annotations
import pytest
from app.core import reqcache
from app.kernel import rules
def _sql(expr: str) -> str:
return rules.to_sql(expr, lambda n: f"t.`{n}`", lambda o, a: f"{o}.`{a}`")
def test_公式编译成SQL_算术与比较():
s = _sql("on_hand - reserved + in_transit")
assert "t.`on_hand`" in s and "t.`reserved`" in s and "t.`in_transit`" in s
assert "<" in _sql("available < order_point")
def test_公式编译成SQL_逻辑与条件():
s = _sql("overstock and region_share > 0.5")
assert " AND " in s.upper()
s = _sql("0 if kind == '常规' else 30")
assert "CASE" in s.upper() and "'常规'" in s
def test_公式编译成SQL_取关联对象的属性():
assert "配件.`dealer_price`" in _sql("on_hand * 配件.dealer_price")
def test_公式编译成SQL_字符串里的引号被转义():
assert "''" in _sql("name == \"a'b\"")
def test_公式编译成SQL_不认识的写法报错():
with pytest.raises(rules.RuleError):
_sql("__import__('os')")
with pytest.raises(rules.RuleError):
rules.to_sql("x + 1", lambda n: (_ for _ in ()).throw(rules.RuleError(f"没有 {n}")), lambda o, a: "")
def test_请求内缓存_同参数只算一次_返回的是副本():
calls = []
@reqcache.per_request
def load(k):
calls.append(k)
return {"k": k, "items": [1]}
load("a"); load("a")
assert calls == ["a", "a"], "请求之外不缓存"
tok = reqcache.begin()
try:
calls.clear()
r1 = load("a")
r1["items"].append(2) # 调用方改了拿到的结果
r2 = load("a")
assert calls == ["a"] and r2["items"] == [1]
reqcache.clear() # 有写操作时会被清空
load("a")
assert calls == ["a", "a"]
finally:
reqcache.end(tok)
def test_请求内缓存_参数不能当键时直接算():
@reqcache.per_request
def total(xs):
return sum(xs)
tok = reqcache.begin()
try:
assert total([1, 2]) == 3 and total([1, 2]) == 3
finally:
reqcache.end(tok)
def test_模型思考开关(monkeypatch):
from app.core import db, llm
from app.governance import llmlog
mode = {"v": "auto"}
monkeypatch.setattr(db, "get_config", lambda k, d=None: mode["v"] if k == "LLM_THINKING" else "")
with llmlog.feature("modeling_metric"):
assert llm._thinking() == {"enable_thinking": False} # 有校验兜底的小步骤:不思考
with llmlog.feature("ask"):
assert llm._thinking() == {} # 回答问题:思考
mode["v"] = "off"
with llmlog.feature("ask"):
assert llm._thinking() == {"enable_thinking": False}
mode["v"] = "on"
assert llm._thinking() == {}
import { describe, expect, it } from "vitest";
import type { FlowOutput, SopSpec } from "@/lib/onto";
import { addStep, autoLayout, connect, edgesOf, newStep, portsOf, refLabel, removeStep, ROOT, visibleOutputs } from "@/features/sop/canvas/model";
const spec = (): SopSpec => ({
params: [{ name: "wo", label: "工单", type: "object", object_type: "维修工单", calendar: "", required: true }],
start: "q", evidence: [],
steps: [
{ id: "q", type: "query", title: "查工单", next: "gate", output: "q" },
{ id: "gate", type: "decision", title: "有缺件吗", branches: [{ label: "有", cond: null, next: "each" }], default: "none" },
{ id: "each", type: "foreach", title: "每个缺件", items: "$q.缺件", next: "fin", output: "each",
body: { start: "w", steps: [{ id: "w", type: "write", title: "下单", next: "e", output: "w" }, { id: "e", type: "end", title: "完" }] } },
{ id: "fin", type: "end", title: "完成" }, { id: "none", type: "end", title: "没有" },
],
});
const outputs: FlowOutput[] = [
{ id: "param:wo", var: "wo", title: "工单", kind: "param", scope: "", schema: { type: "object", fields: [{ name: "key", label: "主键", type: "string" }] } },
{ id: "q", var: "q", title: "查工单", kind: "query", scope: "", schema: { type: "object", fields: [
{ name: "缺件", label: "缺件", type: "array", items: { type: "object", fields: [{ name: "qty_short", label: "缺件数量", type: "number" }] } }] } },
{ id: "each", var: "each", title: "每个缺件", kind: "foreach", scope: "", schema: { type: "object", fields: [] } },
{ id: "each:item", var: "item", title: "这一条", kind: "item", scope: "each", schema: { type: "object", fields: [{ name: "qty_short", label: "缺件数量", type: "number" }] } },
{ id: "w", var: "w", title: "下单", kind: "write", scope: "each", schema: { type: "object", fields: [] } },
];
describe("流程画布模型", () => {
it("条件节点每种情况一个出口,加上否则;动作 / 写数据多一个被驳回", () => {
const s = spec();
expect(portsOf(s.steps[1]).map((p) => p.id)).toEqual(["b0", "default"]);
expect(portsOf(s.steps[2].body.steps[0]).map((p) => p.id)).toEqual(["next", "reject"]);
});
it("连线、断开、删节点会把指向它的线一起去掉", () => {
let s = connect(spec(), ROOT, "gate", "default", "fin");
expect(s.steps[1].default).toBe("fin");
s = removeStep(s, "fin");
expect(s.steps.find((x) => x.id === "each")!.next).toBe("");
expect(s.steps[1].default).toBe("");
expect(edgesOf(s, ROOT).some((e) => e.target === "fin")).toBe(false);
});
it("循环体是独立的容器,开始节点连到循环体第一步", () => {
const s = spec();
expect(edgesOf(s, "each")).toEqual([
{ source: "__start", port: "next", target: "w", label: "" }, { source: "w", port: "next", target: "e", label: "", tone: undefined }]);
const n = newStep(s, "notify");
const s2 = connect(addStep(s, "each", n), "each", "__start", "next", n.id);
expect(s2.steps[2].body.start).toBe(n.id);
});
it("自动排版:从上往下分层,分支并排", () => {
const s = autoLayout(spec());
const y = (id: string) => s.steps.find((x) => x.id === id)!.ui!.y;
expect(y("q")).toBeLessThan(y("gate"));
expect(y("each")).toBe(y("none"));
expect(s.steps.find((x) => x.id === "each")!.body.steps.every((b: any) => b.ui)).toBe(true);
});
it("只看得到上游的数据;循环体里还看得到当前这一条", () => {
const s = spec();
expect(visibleOutputs(s, "gate", outputs).map((o) => o.var)).toEqual(["wo", "q"]);
expect(visibleOutputs(s, "e", outputs).map((o) => o.var)).toEqual(["wo", "q", "item", "w"]);
expect(refLabel("$q.缺件[0].qty_short", outputs)).toBe("查工单 · 缺件 · 第 1 条 · 缺件数量");
});
});
/**
* 这次草案的关系图:对象是节点、关系是连线(标出名字和基数);已有的对象灰色显示。
* 点节点 / 连线在右侧看那条草案的详情。
*/
import {
Background, Controls, Handle, MarkerType, Position, ReactFlow, type Edge, type Node, type NodeProps,
} from "@xyflow/react";
import "@xyflow/react/dist/style.css";
import Graph from "graphology";
import circular from "graphology-layout/circular";
import forceAtlas2 from "graphology-layout-forceatlas2";
import noverlap from "graphology-layout-noverlap";
import { useMemo } from "react";
import { Empty } from "@/components/ui";
import { KIND_COLOR, type ModelDraftItem } from "@/lib/onto";
import { cn } from "@/lib/utils";
import type { DraftCtx } from "./DraftDetail";
import { DRAFT_STATE, draftState, itemKind } from "./util";
type NData = { name: string; item?: ModelDraftItem; props: number; fns: number; acts: number; selected: boolean };
function ObjNode({ data }: NodeProps<Node<NData>>) {
const st = data.item ? draftState(data.item) : null;
return (
<div className={cn("min-w-[120px] max-w-[200px] rounded-xl border-2 bg-surface px-2.5 py-1.5 shadow-sm",
!data.item && "border-dashed opacity-70", data.selected && "ring-2 ring-brand/50")}
style={{ borderColor: data.item ? KIND_COLOR.object_type : "#94a3b8" }}>
<Handle type="target" position={Position.Left} className="!opacity-0" />
<p className="break-words text-label font-semibold">{data.name}</p>
<p className="text-caption text-muted">
{data.item ? `${data.props} 个属性` : "已有对象"}{data.fns ? ` · 函数 ${data.fns}` : ""}{data.acts ? ` · 动作 ${data.acts}` : ""}
</p>
{st && st !== "pending" && <p className={cn("text-caption", st === "live" ? "text-ok" : "text-muted")}>{DRAFT_STATE[st].label}</p>}
<Handle type="source" position={Position.Right} className="!opacity-0" />
</div>
);
}
const nodeTypes = { obj: ObjNode };
export function DraftGraph({ ctx, selected, onSelect }: { ctx: DraftCtx; selected: string; onSelect: (itemId: string) => void }) {
const { nodes, edges } = useMemo(() => {
const objs = ctx.items.filter((x) => itemKind(x) === "object_type" && x.status !== "rejected");
const alias: Record<string, string> = {};
objs.forEach((o) => [o.payload.name, ...(o.payload.synonyms || [])].forEach((n: string) => { alias[n] = o.payload.name; }));
const norm = (ref: string) => alias[ctx.objName[ref] || ref] || ctx.objName[ref] || ref;
const links = ctx.items.filter((x) => itemKind(x) === "link_type" && x.status !== "rejected");
const names = new Set(objs.map((o) => o.payload.name));
links.forEach((l) => [l.payload.spec?.from_type, l.payload.spec?.to_type].forEach((r) => { if (r) names.add(norm(r)); }));
const count = (kind: string, field: string, n: string) =>
ctx.items.filter((x) => itemKind(x) === kind && x.status !== "rejected" && norm(x.payload?.spec?.[field] || "") === n).length;
// 力导向排一下:连得多的聚在一起,再去掉重叠
const g = new Graph({ multi: true });
names.forEach((n) => g.addNode(n, { size: 12 }));
links.forEach((l) => {
const a = norm(l.payload.spec?.from_type || ""), b = norm(l.payload.spec?.to_type || "");
if (g.hasNode(a) && g.hasNode(b) && a !== b) g.addEdge(a, b);
});
circular.assign(g, { scale: 400 });
if (g.order > 2) {
forceAtlas2.assign(g, { iterations: 300, settings: { ...forceAtlas2.inferSettings(g), gravity: 1, scalingRatio: 10 } });
noverlap.assign(g, { maxIterations: 200, settings: { margin: 40, ratio: 1.2 } });
}
// 力导向的坐标尺度不固定:缩放到一个和节点数相称的框里,免得 fitView 缩得太小、卡片看不清
const pts = [...names].map((n) => g.getNodeAttributes(n) as { x: number; y: number });
const xs = pts.map((p) => p.x), ys = pts.map((p) => p.y);
const [x0, x1, y0, y1] = [Math.min(...xs), Math.max(...xs), Math.min(...ys), Math.max(...ys)];
const side = Math.sqrt(names.size);
const W = 190 * side, H = 130 * side;
const fit = (v: number, lo: number, hi: number, span: number) => (hi > lo ? ((v - lo) / (hi - lo)) * span : span / 2);
const byName: Record<string, ModelDraftItem> = Object.fromEntries(objs.map((o) => [o.payload.name, o]));
const nodes: Node<NData>[] = [...names].map((n) => {
const a = g.getNodeAttributes(n) as { x: number; y: number };
const item = byName[n];
return { id: n, type: "obj", position: { x: fit(a.x, x0, x1, W), y: fit(a.y, y0, y1, H) },
data: { name: n, item, props: (item?.payload?.spec?.properties || []).length,
fns: count("function", "object_type", n), acts: count("action", "target_type", n),
selected: !!item && item.id === selected } };
});
const edges: Edge[] = links.map((l) => {
const s = l.payload.spec || {};
return { id: l.id, source: norm(s.from_type || ""), target: norm(s.to_type || ""),
label: `${l.payload.name}(${s.cardinality || "?"})`,
markerEnd: { type: MarkerType.ArrowClosed },
style: { stroke: l.id === selected ? "#6366f1" : KIND_COLOR.link_type, strokeWidth: l.id === selected ? 2.5 : 1.5 },
labelStyle: { fontSize: 11 }, labelBgStyle: { fillOpacity: 0.85 } };
}).filter((e) => names.has(e.source) && names.has(e.target));
return { nodes, edges };
}, [ctx, selected]);
if (!nodes.length) return <Empty title="这次草案里没有对象" />;
return (
<div className="h-full min-h-[360px]">
<ReactFlow nodes={nodes} edges={edges} nodeTypes={nodeTypes} fitView minZoom={0.2} nodesConnectable={false}
onNodeClick={(_, n) => { const it = (n.data as NData).item; if (it) onSelect(it.id); }}
onEdgeClick={(_, e) => onSelect(e.id)} proOptions={{ hideAttribution: true }}>
<Background gap={20} />
<Controls showInteractive={false} />
</ReactFlow>
</div>
);
}
/**
* AI 建模:先是一页「建模卡片」(每次建模一张,看得到状态、产出、用时),点进去才是这次建模的完整工作区
* (流水线日志 + 草案工作台);新建单独一页。
*/
import { ArrowLeft, Database, FileText, Plus } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { Badge, Empty, Spinner } from "@/components/ui";
import { go, useHashParams } from "@/lib/nav";
import { onto, type Me, type ModelRunRec } from "@/lib/onto";
import { cn } from "@/lib/utils";
import { loadFailed } from "@/store/useAppStore";
import { NewRun } from "./NewRun";
import { RunWorkspace } from "./RunWorkspace";
import { fmtDur, RUN_STATUS } from "./util";
export function ModelingPage({ me }: { me: Me | null }) {
const params = useHashParams();
const runId = params.get("run") || "";
const isNew = !!params.get("new");
const canEdit = !!me?.permissions.includes("build");
const [runs, setRuns] = useState<ModelRunRec[] | null>(null);
const load = useCallback(() => {
void onto.modelingRuns().then(setRuns).catch((e) => { setRuns([]); loadFailed(e); });
}, []);
useEffect(load, [load]);
// 有在跑的就定时刷新卡片(状态、耗时)
const anyRunning = !!runs?.some((r) => r.status === "running");
useEffect(() => {
if (!anyRunning || runId || isNew) return undefined;
const h = window.setInterval(load, 4000);
return () => window.clearInterval(h);
}, [anyRunning, runId, isNew, load]);
if (isNew || runId) {
return (
<div className="flex h-full min-h-0 flex-col gap-2">
<button className="btn btn-ghost btn-sm self-start" onClick={() => go("modeling")}>
<ArrowLeft className="h-4 w-4" />全部建模
</button>
<section className="flex min-h-0 min-w-0 flex-1 flex-col">
{isNew ? <NewRun canEdit={canEdit} onCreated={load} />
: <RunWorkspace key={runId} id={runId} canEdit={canEdit} onChanged={load} />}
</section>
</div>
);
}
return (
<div className="h-full overflow-auto pr-1">
<div className="mb-3 flex items-center gap-2">
<p className="text-label text-muted">每次建模是一张卡片,点进去看流水线日志和草案,逐条采纳上线。</p>
{canEdit && (
<button className="btn btn-primary btn-sm ml-auto" onClick={() => go("modeling", { new: 1 })}>
<Plus className="h-4 w-4" />新建建模
</button>
)}
</div>
{!runs ? <div className="p-8"><Spinner /></div> : !runs.length ? (
<Empty title="还没有建模记录" desc={canEdit ? "点右上角「新建建模」,选文档和 / 或数据库开始。" : undefined} />
) : (
<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
{runs.map((r) => <RunCard key={r.id} r={r} />)}
</div>
)}
</div>
);
}
function RunCard({ r }: { r: ModelRunRec }) {
const st = RUN_STATUS[r.status] || RUN_STATUS.draft;
const c = r.counts || {};
const docs = r.inputs.files.length + r.inputs.doc_ids.length;
const nums: [string, number][] = [["对象", c.object_type ?? 0], ["关系", c.link_type ?? 0], ["函数", c.function ?? 0],
["动作", c.action ?? 0], ["流程卡", c.sop ?? 0]];
return (
<button onClick={() => go("modeling", { run: r.id })}
className="card flex flex-col gap-2 p-4 text-left transition-shadow hover:shadow-md">
<div className="flex items-start gap-2">
<span className="min-w-0 flex-1 break-words text-body font-semibold">{r.title}</span>
<Badge variant={st.variant}>{st.label}</Badge>
</div>
<p className="flex items-center gap-1.5 text-caption text-muted">
{docs ? <FileText className="h-3.5 w-3.5" /> : <Database className="h-3.5 w-3.5" />}
{docs ? `${docs} 份文档` : "只用数据库"}
{(r.options?.ds_ids || []).length ? ` · ${(r.options.ds_ids || []).length} 个数据库` : ""}
</p>
{r.status === "done" ? (
<div className="grid grid-cols-5 gap-1 rounded-lg bg-ink/[0.03] px-2 py-2 text-center">
{nums.map(([k, n]) => (
<span key={k}><span className="block text-section font-semibold tabular-nums">{n}</span>
<span className="text-caption text-muted">{k}</span></span>
))}
</div>
) : r.error ? <p className="line-clamp-2 text-caption text-bad">{r.error}</p> : null}
<p className={cn("mt-auto text-caption text-muted")}>
{r.created_at.replace("T", " ").slice(0, 16)}{r.elapsed_ms ? ` · 用时 ${fmtDur(r.elapsed_ms)}` : ""}
</p>
</button>
);
}
/**
* 运行中的流水线:每个节点显示状态、耗时、产出和当前一句进度;点节点打开详情(日志、AI 调用、重跑)。
*/
import {
ArrowRight, CheckCircle2, Circle, CircleSlash, Database, GitBranch, Layers, ListChecks, Loader2, PauseCircle, Sparkles, XCircle,
} from "lucide-react";
import { useEffect, useState } from "react";
import type { ModelCallStat, ModelRunFull, ModelStage } from "@/lib/onto";
import { cn } from "@/lib/utils";
import { fmtDur, STAGE_STATUS, stageMs } from "./util";
export const STAGE_ICON: Record<string, React.ReactNode> = {
data: <Database className="h-4 w-4" />, convert: <Sparkles className="h-4 w-4" />,
deepen: <Layers className="h-4 w-4" />, sop: <ListChecks className="h-4 w-4" />, draft: <GitBranch className="h-4 w-4" />,
};
export function StatusIcon({ status }: { status: string }) {
if (status === "done") return <CheckCircle2 className="h-3.5 w-3.5 text-ok" />;
if (status === "running") return <Loader2 className="h-3.5 w-3.5 animate-spin text-brand" />;
if (status === "failed") return <XCircle className="h-3.5 w-3.5 text-bad" />;
if (status === "stopped") return <PauseCircle className="h-3.5 w-3.5 text-warn" />;
if (status === "cancelled") return <CircleSlash className="h-3.5 w-3.5 text-muted" />;
return <Circle className="h-3.5 w-3.5 text-muted/50" />;
}
const TONE: Record<string, string> = {
done: "border-ok/40 bg-ok/[0.04]", running: "border-brand bg-brand/5 ring-2 ring-brand/20",
failed: "border-bad/50 bg-bad/5", stopped: "border-warn/50 bg-warn/5", cancelled: "border-line bg-ink/[0.02]",
skipped: "border-dashed border-line opacity-55", pending: "border-line bg-surface",
};
/** 节点上的一句产出 */
function outputText(s: ModelStage): string {
const c = s.counts || {};
switch (s.key) {
case "data": return s.status === "done" ? `${c.tables ?? 0} 张表 · ${c.joins ?? 0} 条关联` : "";
case "convert": return s.status === "done" ? `${c.proposed ?? 0} 条草案` : "";
case "deepen": return s.status === "done" ? `公式 ${c.deepened ?? 0} · 取数 ${c.metrics_bound ?? 0} · 动作 ${c.actions_completed ?? 0}` : "";
case "sop": return s.status === "done" ? `${c.sops ?? 0} 张流程卡` : "";
case "draft": return s.status === "done"
? `${(c.object_type ?? 0) + (c.link_type ?? 0) + (c.function ?? 0) + (c.action ?? 0)} 条 + ${c.sop ?? 0} 张流程卡` : "";
default: return "";
}
}
export function PipelineBar({ run, selected, onSelect }: {
run: ModelRunFull; selected: string; onSelect: (key: string) => void;
}) {
const [now, setNow] = useState(Date.now());
const live = run.status === "running";
useEffect(() => {
if (!live) return undefined;
const h = window.setInterval(() => setNow(Date.now()), 1000);
return () => window.clearInterval(h);
}, [live]);
const stats: Record<string, ModelCallStat> = run.call_stats || {};
return (
<div className="flex items-stretch gap-1 overflow-x-auto pb-1">
{run.stages.map((s, i) => {
const ms = stageMs(s, now);
const last = s.log.length ? s.log[s.log.length - 1].msg : "";
const st = stats[s.key];
return (
<div key={s.key} className="flex items-stretch gap-1">
{i > 0 && <ArrowRight className="mt-7 h-4 w-4 shrink-0 text-muted/60" />}
<button onClick={() => onSelect(s.key)} disabled={s.status === "skipped"}
className={cn("flex w-44 shrink-0 flex-col rounded-xl border p-2.5 text-left transition-shadow hover:shadow-sm",
TONE[s.status] || TONE.pending, selected === s.key && "outline outline-2 outline-offset-1 outline-brand")}>
<span className="flex items-center gap-1.5 text-label font-semibold">
<span className="text-brand">{STAGE_ICON[s.key]}</span>{s.label}
<span className="ml-auto"><StatusIcon status={s.status} /></span>
</span>
<span className="mt-1 flex flex-wrap items-center gap-x-1.5 text-caption text-muted">
<span className="whitespace-nowrap">{STAGE_STATUS[s.status] || s.status}</span>
{ms !== null && <span className="whitespace-nowrap tabular-nums">· {fmtDur(ms)}</span>}
{st?.calls ? <span className="whitespace-nowrap">· AI {st.calls} 次</span> : null}
</span>
{s.status === "running" && last
? <span className="mt-1 line-clamp-2 text-caption text-brand">{last}</span>
: outputText(s) ? <span className="mt-1 text-caption text-ink/80">{outputText(s)}</span> : null}
</button>
</div>
);
})}
</div>
);
}
/**
* 一次 AI 建模的工作区:顶栏(状态、耗时、暂停 / 继续 / 终止 / 重跑)→ 流水线 → 草案工作台。
* 运行中每 2 秒刷新一次;点流水线节点在右侧抽屉里看这一步的日志和 AI 调用。
*/
import { CircleSlash, Download, PauseCircle, Play, RotateCcw, Trash2 } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { Badge, Card, Spinner } from "@/components/ui";
import { confirmDialog } from "@/lib/dialog";
import { go } from "@/lib/nav";
import { errText, onto, type ModelRunFull } from "@/lib/onto";
import { toast } from "@/store/useAppStore";
import { DraftWorkbench } from "./DraftWorkbench";
import { PipelineBar } from "./PipelineBar";
import { StageDrawer } from "./StageDrawer";
import { fmtDur, RUN_STATUS } from "./util";
export function RunWorkspace({ id, canEdit, onChanged }: { id: string; canEdit: boolean; onChanged: () => void }) {
const [run, setRun] = useState<ModelRunFull | null>(null);
const [stage, setStage] = useState("");
const load = useCallback(async () => {
try {
const r = await onto.modelingRun(id);
setRun(r);
return r;
} catch (e) { toast("error", "加载失败", errText(e)); return null; }
}, [id]);
const live = run?.status === "running";
useEffect(() => { void load(); }, [load]);
useEffect(() => {
if (!live) return undefined;
const h = window.setInterval(() => { void load(); }, 2000);
return () => window.clearInterval(h);
}, [live, load]);
// 跑完的那一下刷新左栏(状态、计数)
const [wasLive, setWasLive] = useState(false);
useEffect(() => {
if (live) setWasLive(true);
else if (wasLive) { setWasLive(false); onChanged(); }
}, [live, wasLive, onChanged]);
if (!run) return <Spinner />;
const st = RUN_STATUS[run.status] || RUN_STATUS.draft;
const act = async (fn: () => Promise<unknown>, ok: string) => {
try { await fn(); toast("ok", ok); await load(); onChanged(); } catch (e) { toast("error", errText(e)); }
};
const retry = async (from: string) => {
const label = run.stages.find((s) => s.key === from)?.label || from;
if (!(await confirmDialog(`从「${label}」重跑?`, { desc: "这一步和之后各步上次的产出会先清掉(还没决定的草案、没采纳的流程卡);已经采纳上线的不受影响。" }))) return;
await act(() => onto.startModelingRun(run.id, from), "已重新开始");
};
const inputs = [...run.inputs.files, ...run.inputs.doc_ids.map((d) => `知识库文档 #${d}`)];
const dbs = (run.options?.ds_ids || []).length;
return (
<div className="flex min-h-0 flex-1 flex-col gap-3 overflow-auto pr-1">
<div className="flex flex-wrap items-center gap-2">
<h2 className="min-w-0 break-words text-section font-semibold">{run.title}</h2>
<Badge variant={st.variant}>{st.label}</Badge>
{run.control && <Badge variant="warn">正在{run.control === "stop" ? "暂停" : "终止"}…</Badge>}
<span className="text-label text-muted">
{run.started_at ? `开始于 ${run.started_at.replace("T", " ").slice(5, 16)} · ` : ""}共用时 {fmtDur(run.elapsed_ms)}
{" · "}{inputs.length ? `${inputs.length} 份文档` : "无文档"}{dbs ? ` · ${dbs} 个数据库` : ""}
</span>
<div className="ml-auto flex flex-wrap gap-1.5">
{canEdit && live && <>
<button className="btn btn-sm" disabled={!!run.control} onClick={() => void act(() => onto.stopModelingRun(run.id), "正在暂停")}>
<PauseCircle className="h-3.5 w-3.5" />暂停</button>
<button className="btn btn-sm" disabled={run.control === "cancel"} onClick={async () => {
if (await confirmDialog("终止这次建模?", { desc: "正在进行的 AI 调用会被打断。已经产出的草案保留,之后可以从任意一步重跑。", danger: true }))
await act(() => onto.cancelModelingRun(run.id), "正在终止");
}}><CircleSlash className="h-3.5 w-3.5" />终止</button>
</>}
{canEdit && !live && ["stopped", "failed", "draft"].includes(run.status) && (
<button className="btn btn-primary btn-sm" onClick={() => void act(() => onto.startModelingRun(run.id), "继续运行")}>
<Play className="h-3.5 w-3.5" />{run.status === "draft" ? "开始" : "继续"}</button>
)}
{canEdit && !live && run.status !== "draft" && (
<button className="btn btn-sm" onClick={() => void retry(run.stages.find((s) => s.status !== "skipped")?.key || "convert")}>
<RotateCcw className="h-3.5 w-3.5" />全部重跑</button>
)}
<a className="btn btn-sm" href={onto.modelingExportUrl(run.id)} download={`${run.title}-草案.md`}><Download className="h-3.5 w-3.5" />导出</a>
{canEdit && !live && (
<button className="btn btn-sm" title="删除这条建模记录" onClick={async () => {
if (!(await confirmDialog("删除这条建模记录?", { desc: "还没决定的草案一起删掉;已经采纳上线的元素不受影响。", danger: true }))) return;
try { await onto.deleteModelingRun(run.id); onChanged(); go("modeling"); } catch (e) { toast("error", errText(e)); }
}}><Trash2 className="h-3.5 w-3.5" /></button>
)}
</div>
</div>
<Card className="p-3">
<PipelineBar run={run} selected={stage} onSelect={(k) => setStage(stage === k ? "" : k)} />
{run.error && (
<p className="mt-2 rounded-lg border border-bad/30 bg-bad/5 px-3 py-2 text-label text-bad">
{run.error}{run.status === "stopped" || run.status === "failed" ? "。点上面的节点看详情,或「继续」接着跑。" : ""}
</p>
)}
{!stage && <p className="mt-1.5 text-caption text-muted">点任意一步,看它的处理日志、AI 思考过程和耗时,也可以从那一步重跑。</p>}
</Card>
<DraftWorkbench run={run} canEdit={canEdit} onChanged={() => { void load(); onChanged(); }} />
{stage && (
<StageDrawer run={run} stageKey={stage} canEdit={canEdit} onClose={() => setStage("")}
onRetry={(k) => void retry(k)}
onStop={() => void act(() => onto.stopModelingRun(run.id), "正在暂停")}
onCancel={() => void act(() => onto.cancelModelingRun(run.id), "正在终止")} />
)}
</div>
);
}
/**
* 流程卡草稿就地看:做什么用、谁负责、要填哪些参数、每一步做什么(分支 / 循环缩进显示)、还有什么问题。
* 以前点一下就跳到流程卡页,回来还得重新找这次建模。
*/
import { AlertTriangle, Check, ExternalLink, X } from "lucide-react";
import { Badge, Spinner, Term } from "@/components/ui";
import { go, here } from "@/lib/nav";
import type { ModelSopDraft } from "@/lib/onto";
export function sopState(s: ModelSopDraft): { label: string; variant: "ok" | "warn" | "neutral" } {
if (s.status === "archived") return { label: "不采纳", variant: "neutral" };
if (s.current_version > 0) return { label: "已上线", variant: "ok" };
return { label: "待定", variant: "warn" };
}
export function SopDraftView({ s, canEdit, busy, onAdopt, onDiscard }: {
s: ModelSopDraft; canEdit: boolean; busy: boolean; onAdopt: () => void; onDiscard: () => void;
}) {
const st = sopState(s);
const v = s.validation || { errors: [], warnings: [] };
const params = s.params || [];
return (
<div className="space-y-4 p-4">
<div>
<div className="flex flex-wrap items-center gap-2">
<Badge variant="info"><Term>流程卡</Term></Badge>
<h3 className="min-w-0 break-words text-section font-semibold">{s.title}</h3>
<Badge variant={st.variant}>{st.label}</Badge>
</div>
{s.description && <p className="mt-2 break-words text-body">{s.description}</p>}
<p className="mt-1 text-caption text-muted">负责角色:{s.owner_role || "没指定"} · {s.step_count} 步</p>
</div>
{s.issue && <p className="rounded-lg border border-bad/30 bg-bad/5 px-3 py-2 text-label text-bad">没能上线:{s.issue}</p>}
{(v.errors.length > 0 || (v.draft_refs || []).length > 0 || v.warnings.length > 0) && (
<div className="space-y-1 rounded-lg border border-line p-3 text-label">
{v.errors.map((e, i) => <p key={`e${i}`} className="flex gap-1.5 text-bad"><AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />{e}</p>)}
{(v.draft_refs || []).length > 0 && (
<p className="text-warn">用到了还没上线的元素:{(v.draft_refs || []).map((x: any) => `「${x.name}」`).join("、")}。
采纳时把这些草案一起勾上(或先采纳它们),流程卡才能上线。</p>
)}
{v.warnings.map((w, i) => <p key={`w${i}`} className="text-muted">提示:{w}</p>)}
</div>
)}
{canEdit && (
<div className="flex flex-wrap gap-1.5">
{st.label === "待定" && <>
<button className="btn btn-primary btn-sm" disabled={busy || v.errors.length > 0} onClick={onAdopt}
title={v.errors.length ? "先在编辑器里把错误改掉" : ""}>
{busy ? <Spinner className="h-3.5 w-3.5" /> : <Check className="h-3.5 w-3.5" />}采纳并上线</button>
<button className="btn btn-sm" disabled={busy} onClick={onDiscard}><X className="h-3.5 w-3.5" />不要</button>
</>}
<button className="btn btn-sm" onClick={() => go("sop", { id: s.id, back: here() })}><ExternalLink className="h-3.5 w-3.5" />在流程卡编辑器中打开</button>
</div>
)}
<section>
<h4 className="mb-1.5 text-label font-semibold"><Term>参数</Term>(运行时要填,{params.length} 个)</h4>
{params.length ? (
<div className="overflow-x-auto rounded-lg border border-line">
<table className="tbl text-label">
<thead><tr><th>名称</th><th>类型</th><th>必填</th><th>默认</th></tr></thead>
<tbody>{params.map((p) => (
<tr key={p.name}><td className="break-words">{p.label || p.name}{p.description ? <span className="text-muted">:{p.description}</span> : null}</td>
<td className="text-muted">{p.type}{p.object_type ? ` · ${p.object_type}` : ""}</td><td>{p.required ? "是" : ""}</td>
<td className="text-muted">{p.default !== undefined && p.default !== "" ? String(p.default) : ""}</td></tr>
))}</tbody>
</table>
</div>
) : <p className="text-label text-muted">不需要参数</p>}
</section>
<section>
<h4 className="mb-1.5 text-label font-semibold">步骤</h4>
{s.outline.length ? (
<ol className="space-y-1 text-label">
{s.outline.map((x, i) => (
<li key={i} style={{ paddingLeft: x.depth * 18 }} className={x.kind === "case" ? "text-caption font-medium text-brand" : ""}>
{x.title}{x.kind_label && <span className="ml-1.5 rounded bg-ink/[0.05] px-1.5 text-caption text-muted">{x.kind_label}</span>}
</li>
))}
</ol>
) : <p className="text-label text-muted">没有步骤</p>}
</section>
</div>
);
}
/**
* 流水线节点详情:这一步什么时候开始、跑了多久、处理日志、每一次 AI 调用(耗时、token、思考过程、输出、提示词),
* 以及「从这一步重跑」「暂停」「终止」。运行中的调用思考过程实时滚动。
*/
import { Brain, ChevronDown, ChevronRight, CircleSlash, PauseCircle, RotateCcw, X } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import { Tabs } from "@/components/kit";
import { Badge, Spinner } from "@/components/ui";
import { onto, type ModelCallDetail, type ModelCallRec, type ModelRunFull } from "@/lib/onto";
import { cn } from "@/lib/utils";
import { StatusIcon } from "./PipelineBar";
import { clock, fmtDur, STAGE_STATUS, stageMs } from "./util";
export function StageDrawer({ run, stageKey, canEdit, onClose, onRetry, onStop, onCancel }: {
run: ModelRunFull; stageKey: string; canEdit: boolean; onClose: () => void;
onRetry: (key: string) => void; onStop: () => void; onCancel: () => void;
}) {
const s = run.stages.find((x) => x.key === stageKey)!;
const [tab, setTab] = useState<"log" | "calls">("log");
const [calls, setCalls] = useState<ModelCallRec[] | null>(null);
const [open, setOpen] = useState<number | null>(null);
const running = s.status === "running";
const load = useCallback(() => {
void onto.modelingCalls(run.id, stageKey).then(setCalls).catch(() => setCalls([]));
}, [run.id, stageKey]);
useEffect(load, [load]);
useEffect(() => {
if (!running) return undefined;
const h = window.setInterval(load, 2000);
return () => window.clearInterval(h);
}, [running, load]);
useEffect(() => {
const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [onClose]);
const st = run.call_stats?.[stageKey];
const ms = stageMs(s);
const runLive = run.status === "running";
return (
<div className="fixed inset-y-0 right-0 z-40 flex w-[min(720px,100vw)] flex-col border-l border-line bg-surface shadow-2xl animate-fade-up">
<div className="flex items-start gap-2 border-b border-line px-4 py-3">
<div className="min-w-0 flex-1">
<p className="flex items-center gap-2 text-title font-semibold"><StatusIcon status={s.status} />{s.label}
<Badge>{STAGE_STATUS[s.status] || s.status}</Badge></p>
<p className="mt-0.5 text-caption text-muted">{s.desc}</p>
</div>
<button className="btn btn-ghost btn-sm" onClick={onClose} aria-label="关闭"><X className="h-4 w-4" /></button>
</div>
<div className="grid grid-cols-2 gap-x-6 gap-y-1.5 border-b border-line px-4 py-3 text-label sm:grid-cols-4">
<Info k="开始" v={s.started_at ? s.started_at.replace("T", " ").slice(5, 19) : "-"} />
<Info k="结束" v={s.ended_at ? s.ended_at.replace("T", " ").slice(5, 19) : running ? "进行中" : "-"} />
<Info k="耗时" v={fmtDur(ms)} />
<Info k="AI 调用" v={st ? `${st.calls} 次 · 共 ${fmtDur(st.ms)}` : "0 次"} />
{st && <Info k="读入 token" v={st.prompt_tokens.toLocaleString()} />}
{st && <Info k="思考 token" v={st.reasoning_tokens.toLocaleString()} />}
{st && <Info k="输出 token" v={st.output_tokens.toLocaleString()} />}
</div>
{canEdit && (
<div className="flex flex-wrap items-center gap-1.5 border-b border-line px-4 py-2">
{runLive ? (<>
<button className="btn btn-sm" disabled={!!run.control} onClick={onStop}><PauseCircle className="h-3.5 w-3.5" />暂停</button>
<button className="btn btn-sm" disabled={run.control === "cancel"} onClick={onCancel}><CircleSlash className="h-3.5 w-3.5" />终止</button>
{run.control && <span className="text-caption text-warn">正在{run.control === "stop" ? "暂停" : "终止"}…</span>}
</>) : s.status !== "skipped" && (
<button className="btn btn-sm" onClick={() => onRetry(s.key)}><RotateCcw className="h-3.5 w-3.5" />从这一步重跑</button>
)}
{!runLive && s.status !== "skipped" && (
<span className="text-caption text-muted">重跑会先清掉这一步和之后各步上次的产出(已采纳的不受影响)</span>
)}
</div>
)}
<Tabs className="px-2" value={tab} onChange={setTab}
options={[{ key: "log", label: "处理日志", count: s.log.length }, { key: "calls", label: "AI 调用", count: calls?.length ?? null }]} />
<div className="min-h-0 flex-1 overflow-auto">
{tab === "log" ? (
<div className="space-y-0.5 p-3 text-label">
{s.log.map((l, i) => (
<p key={i} className="flex gap-3 rounded px-1.5 py-0.5 hover:bg-ink/[0.03]">
<span className="w-16 shrink-0 tabular-nums text-muted">{clock(l.t)}</span>
<span className="min-w-0 flex-1 break-words">{l.msg}</span>
</p>
))}
{!s.log.length && <p className="p-3 text-muted">{s.status === "skipped" ? "这一步跳过了" : "还没有日志"}</p>}
</div>
) : !calls ? <div className="p-6"><Spinner /></div> : (
<div className="divide-y divide-line">
{calls.map((c) => (
<CallRow key={c.id} runId={run.id} c={c} open={open === c.id} onToggle={() => setOpen(open === c.id ? null : c.id)} />
))}
{!calls.length && <p className="p-4 text-label text-muted">
{s.key === "data" || s.key === "draft" ? "这一步不调用 AI。" : s.status === "pending" ? "还没开始。" : "这一步没有 AI 调用记录。"}</p>}
</div>
)}
</div>
</div>
);
}
function Info({ k, v }: { k: string; v: React.ReactNode }) {
return <p className="flex gap-2"><span className="shrink-0 text-muted">{k}</span><span className="tabular-nums">{v}</span></p>;
}
const CALL_TONE: Record<string, string> = { running: "text-brand", done: "text-ok", failed: "text-bad", cancelled: "text-muted" };
const CALL_LABEL: Record<string, string> = { running: "进行中", done: "完成", failed: "失败", cancelled: "已终止" };
function CallRow({ runId, c, open, onToggle }: { runId: string; c: ModelCallRec; open: boolean; onToggle: () => void }) {
const [d, setD] = useState<ModelCallDetail | null>(null);
const [showPrompt, setShowPrompt] = useState(false);
const thinkRef = useRef<HTMLPreElement>(null);
const live = c.status === "running";
useEffect(() => {
if (!open) return undefined;
let alive = true;
const get = () => void onto.modelingCall(runId, c.id).then((x) => { if (alive) setD(x); }).catch(() => undefined);
get();
if (!live) return () => { alive = false; };
const h = window.setInterval(get, 1500);
return () => { alive = false; window.clearInterval(h); };
}, [open, live, runId, c.id]);
// 运行中的思考过程跟着滚到底
useEffect(() => {
if (live && thinkRef.current) thinkRef.current.scrollTop = thinkRef.current.scrollHeight;
}, [d?.reasoning, live]);
return (
<div>
<button className="flex w-full items-start gap-2 px-3 py-2 text-left hover:bg-ink/[0.02]" onClick={onToggle}>
{open ? <ChevronDown className="mt-0.5 h-4 w-4 shrink-0 text-muted" /> : <ChevronRight className="mt-0.5 h-4 w-4 shrink-0 text-muted" />}
<span className="min-w-0 flex-1">
<span className="block break-words text-label font-medium">{c.label || c.feature}</span>
<span className="mt-0.5 flex flex-wrap gap-x-3 text-caption text-muted">
<span className="tabular-nums">{clock(c.started_at)}</span>
<span className={CALL_TONE[c.status]}>{CALL_LABEL[c.status] || c.status}</span>
<span className="tabular-nums">{c.cached ? "命中缓存" : fmtDur(c.duration_ms)}</span>
<span className="tabular-nums">读入 {c.prompt_tokens} · 思考 {c.reasoning_tokens} · 输出 {c.output_tokens}</span>
</span>
{c.error && c.status !== "cancelled" && <span className="mt-0.5 block break-words text-caption text-bad">{c.error}</span>}
</span>
{live && <Brain className="h-4 w-4 shrink-0 animate-pulse text-brand" />}
</button>
{open && (
<div className="space-y-2 px-4 pb-3 pl-9">
{!d ? <Spinner /> : (<>
<Block title={live ? "思考过程(实时)" : "思考过程"} empty={c.cached ? "命中缓存,没有重新思考" : "这次调用没有思考(或模型没返回思考过程)"}>
{d.reasoning && <pre ref={thinkRef} className="max-h-72 overflow-auto whitespace-pre-wrap break-words text-caption leading-relaxed text-ink/80">{d.reasoning}</pre>}
</Block>
<Block title="输出" empty={live ? "还在想,没开始输出" : "没有输出"}>
{d.output && <pre className="max-h-72 overflow-auto whitespace-pre-wrap break-words font-mono text-caption">{d.output}</pre>}
</Block>
<button className="text-caption text-brand" onClick={() => setShowPrompt(!showPrompt)}>{showPrompt ? "收起" : "看发给模型的完整内容"}</button>
{showPrompt && <pre className={cn("max-h-80 overflow-auto whitespace-pre-wrap break-words rounded-lg bg-ink/[0.03] p-2 text-caption text-muted")}>{d.prompt}</pre>}
</>)}
</div>
)}
</div>
);
}
function Block({ title, children, empty }: { title: string; children: React.ReactNode; empty: string }) {
return (
<div className="rounded-lg border border-line">
<p className="border-b border-line bg-ink/[0.02] px-2.5 py-1 text-caption font-medium text-muted">{title}</p>
<div className="p-2.5">{children || <p className="text-caption text-muted">{empty}</p>}</div>
</div>
);
}
/**
* AI 建模页的小工具:状态文字与配色、耗时格式、草案条目的名称 / 类型 / 可信度 / 状态。
*/
import type { BadgeVariant } from "@/components/ui";
import type { ModelDraftItem, ModelStage } from "@/lib/onto";
export const RUN_STATUS: Record<string, { label: string; variant: BadgeVariant; dot: string }> = {
draft: { label: "未开始", variant: "neutral", dot: "bg-muted/50" },
running: { label: "运行中", variant: "info", dot: "bg-brand animate-pulse" },
stopped: { label: "已暂停", variant: "warn", dot: "bg-warn" },
cancelled: { label: "已终止", variant: "neutral", dot: "bg-muted" },
done: { label: "已完成", variant: "ok", dot: "bg-ok" },
failed: { label: "失败", variant: "danger", dot: "bg-bad" },
};
export const STAGE_STATUS: Record<string, string> = {
pending: "等待", running: "进行中", done: "完成", skipped: "跳过", failed: "出错", stopped: "已暂停", cancelled: "已终止",
};
/** 毫秒 → 「3 分 12 秒」 */
export function fmtDur(ms?: number | null): string {
if (ms === null || ms === undefined || ms < 0) return "-";
const s = Math.round(ms / 1000);
if (s < 60) return `${s} 秒`;
const m = Math.floor(s / 60);
if (m < 60) return `${m} 分 ${s % 60} 秒`;
return `${Math.floor(m / 60)} 小时 ${m % 60} 分`;
}
/** 环节耗时:跑完的取起止,正在跑的算到现在 */
export function stageMs(s: ModelStage, now = Date.now()): number | null {
if (!s.started_at) return null;
const end = s.ended_at ? new Date(s.ended_at).getTime() : now;
return Math.max(0, end - new Date(s.started_at).getTime());
}
export function clock(t?: string | null): string {
return t ? t.replace("T", " ").slice(11, 19) : "";
}
export type DraftKind = "object_type" | "link_type" | "function" | "action";
export const itemName = (it: ModelDraftItem): string => it.payload?.name || it.title;
export const itemKind = (it: ModelDraftItem): string => it.payload?.kind || "other";
/** 类型徽标用:函数细分到类别 */
export function itemTypeKey(it: ModelDraftItem): string {
const p = it.payload || {};
return p.kind === "function" ? (p.spec?.category || "rule") : p.kind || "object_type";
}
export function confLevel(c: number): { label: string; cls: string } {
if (c >= 0.8) return { label: "高", cls: "text-ok" };
if (c >= 0.6) return { label: "中", cls: "text-muted" };
return { label: "低", cls: "text-warn" };
}
/** 这条草案还缺什么才能直接用(没绑表、没公式、动作没补全);空串 = 能直接用 */
export function weakReason(it: ModelDraftItem): string {
const p = it.payload || {};
const spec = p.spec || {};
const binds: any[] = p.bindings || [];
if (p.kind === "action" && spec._stub) return "动作只有说明,参数和效果还没补全";
if (p.kind === "function" && spec.category === "aggregate" && !binds.some((b) => b.target_kind === "metric_expr"))
return "指标还没对上数据(没有取数表达式)";
if (p.kind === "function" && spec.category === "rule" && !spec.expression) return "规则还没写成公式";
if (p.kind === "function" && spec.category === "decision" && !(spec.rows || []).length) return "决策表还是空的";
return "";
}
/** 草案的落地状态:待定 / 已上线 / 已采纳没上线 / 不采纳 */
export type DraftState = "pending" | "live" | "held" | "rejected";
export function draftState(it: ModelDraftItem): DraftState {
if (it.status === "pending") return "pending";
if (it.status === "rejected") return "rejected";
const c = it.concept;
if (c && c.status === "published" && !c.dirty) return "live";
return "held";
}
export const DRAFT_STATE: Record<DraftState, { label: string; variant: BadgeVariant }> = {
pending: { label: "待定", variant: "warn" },
live: { label: "已上线", variant: "ok" },
held: { label: "没上线", variant: "danger" },
rejected: { label: "不采纳", variant: "neutral" },
};
/** 绑定情况 */
export function bindLabel(it: ModelDraftItem): string {
const kinds = (it.payload?.bindings || []).map((b: any) => b.target_kind);
if (kinds.includes("metric_expr")) return "取数已校验";
if (kinds.includes("table")) return "已绑表";
if (kinds.includes("join")) return "已对上关联列";
return "";
}
export const CARD_TEXT: Record<string, string> = {
"1:1": "一个对应一个", "1:n": "一个对应多个", "n:1": "多个对应一个", "n:n": "多个对应多个",
};
/** 动作效果翻成一句业务话 */
export function effectText(e: any): string {
const a = e?.args || {};
const v = (x: any) => (typeof x === "string" ? x.replace(/^\$/, "参数 ").replace(/^=/, "按公式 ") : JSON.stringify(x));
switch (e?.tool) {
case "object.write": return `把「${a.object_type || "对象"}」的「${a.property}」改成 ${v(a.value)}`;
case "object.create": return `新建一条「${a.object_type}」:${Object.entries(a.values || {}).map(([k, x]) => `${k} = ${v(x)}`).join(",")}`;
case "notify.send": return `发通知给 ${a.to || a.role || "相关人"}:${a.title || a.text || a.body || ""}`;
case "task.create": return `派一项待办给 ${a.role || a.assignee || "相关人"}:${a.title || ""}${a.description ? `(${v(a.description)})` : ""}`;
default: return `${e?.tool || "?"} ${JSON.stringify(a)}`;
}
}
/**
* 条件组编辑器:若干条「左边 比较 右边」,用「全部满足 / 任一满足」连起来,可以再嵌一层子条件组
* (如:等级是 A 且(金额 > 5000 或 是大客户))。比较方式随左边的类型变化(数字有大于小于,列表有条数,是否只有为是 / 为否)。
*
* 两种左边:
* - 数据:左边是上游的一份数据(条件节点、循环的筛选);
* - 属性:左边是某类对象的一个属性(查数据的条件,fields 给出可选属性)。
* 也可以切到「高级」直接写表达式。
*/
import { Code2, Plus, Trash2 } from "lucide-react";
import type { CondGroup, CondItem, DataSchema, FlowCond } from "@/lib/onto";
import { Select } from "@/components/kit";
import { cn } from "@/lib/utils";
import { ExprInput, RefPicker, useScope, ValueInput } from "./data";
import { isGroup, OP_LABEL, refType, UNARY } from "./model";
const OPS_BY_TYPE: Record<string, string[]> = {
number: ["eq", "ne", "gt", "ge", "lt", "le", "in", "empty", "not_empty"],
integer: ["eq", "ne", "gt", "ge", "lt", "le", "in", "empty", "not_empty"],
date: ["eq", "ne", "gt", "ge", "lt", "le", "empty", "not_empty"],
boolean: ["is_true", "is_false", "empty"],
array: ["len_gt", "len_eq", "empty", "not_empty", "contains"],
string: ["eq", "ne", "contains", "not_contains", "startswith", "in", "not_in", "empty", "not_empty"],
};
const QUERY_OPS = ["eq", "ne", "gt", "ge", "lt", "le", "contains", "not_contains", "startswith", "in", "not_in", "empty", "not_empty"];
const opsFor = (t: string, query: boolean) => (query ? QUERY_OPS : OPS_BY_TYPE[t] || [...OPS_BY_TYPE.string, "gt", "ge", "lt", "le"]);
function ItemRow({ it, onChange, onRemove, fields, disabled }: {
it: CondItem; onChange: (x: CondItem) => void; onRemove: () => void; fields?: DataSchema[]; disabled?: boolean;
}) {
const sc = useScope();
const query = !!fields;
const field = query ? fields!.find((f) => f.name === it.left) : undefined;
const t = query ? (field?.type || "string") : refType(it.left, [...(sc.extra || []), ...sc.outputs]);
const ops = opsFor(t, query);
return (
<div className="space-y-1 rounded-md border border-line/70 bg-surface p-1.5">
<div className="flex items-center gap-1.5">
<div className="min-w-0 flex-1">
{query ? (
<Select className="input h-8 w-full" disabled={disabled} value={it.left} onChange={(e) => onChange({ ...it, left: e.target.value })}>
<option value="">选属性</option>
{fields!.map((f) => <option key={f.name} value={f.name}>{f.label || f.name}</option>)}
</Select>
) : <RefPicker value={it.left} disabled={disabled} onChange={(v) => onChange({ ...it, left: v })} placeholder="选数据" />}
</div>
<Select className="input h-8 w-[6.5rem] shrink-0" disabled={disabled} value={it.op} onChange={(e) => onChange({ ...it, op: e.target.value })}>
{(ops.includes(it.op) ? ops : [it.op, ...ops]).map((o) => <option key={o} value={o}>{OP_LABEL[o] || o}</option>)}
</Select>
{!disabled && <button className="btn btn-ghost btn-sm shrink-0 px-1.5" title="删掉这条" onClick={onRemove}><Trash2 className="h-3.5 w-3.5" /></button>}
</div>
{!UNARY.includes(it.op) && (
<ValueInput value={it.right} disabled={disabled} onChange={(v) => onChange({ ...it, right: v })}
type={["len_gt", "len_eq"].includes(it.op) ? "number" : t === "array" ? "string" : t}
options={field?.options} placeholder={it.op === "in" || it.op === "not_in" ? "多个用逗号隔开" : "比较的值"} />
)}
</div>
);
}
function Group({ g, onChange, fields, disabled, depth }: {
g: CondGroup; onChange: (g: CondGroup | null) => void; fields?: DataSchema[]; disabled?: boolean; depth: number;
}) {
const set = (i: number, x: CondItem | CondGroup | null) => {
const items = x === null ? g.items.filter((_, j) => j !== i) : g.items.map((y, j) => (j === i ? x : y));
onChange(items.length ? { ...g, items } : null);
};
return (
<div className={cn("space-y-1.5", depth > 0 && "rounded-lg border border-dashed border-line bg-ink/[0.015] p-2")}>
{g.items.length > 1 && (
<div className="flex items-center gap-1.5 text-caption text-muted">
<Select className="input h-7 w-auto py-0 text-caption" disabled={disabled} value={g.mode}
onChange={(e) => onChange({ ...g, mode: e.target.value as "all" | "any" })}>
<option value="all">下面全部满足</option><option value="any">下面任一满足</option>
</Select>
</div>
)}
{g.items.map((it, i) => (isGroup(it)
? <Group key={i} g={it} depth={depth + 1} fields={fields} disabled={disabled} onChange={(x) => set(i, x)} />
: <ItemRow key={i} it={it} fields={fields} disabled={disabled} onChange={(x) => set(i, x)} onRemove={() => set(i, null)} />))}
{!disabled && (
<div className="flex gap-1.5">
<button className="btn btn-sm" onClick={() => onChange({ ...g, items: [...g.items, { left: "", op: "eq", right: "" }] })}>
<Plus className="h-3.5 w-3.5" />加一条
</button>
{depth === 0 && (
<button className="btn btn-ghost btn-sm" title="一组「或者」:如 金额 > 5000 或 是大客户"
onClick={() => onChange({ ...g, items: [...g.items, { mode: g.mode === "all" ? "any" : "all", items: [{ left: "", op: "eq", right: "" }] }] })}>
<Plus className="h-3.5 w-3.5" />加一组
</button>
)}
</div>
)}
</div>
);
}
export function ConditionEditor({ value, onChange, fields, disabled, emptyHint = "没有条件" }: {
value: FlowCond | undefined; onChange: (v: FlowCond) => void; fields?: DataSchema[]; disabled?: boolean; emptyHint?: string;
}) {
if (value && "expr" in value) {
return (
<div className="space-y-1.5">
<ExprInput value={value.expr} disabled={disabled} onChange={(v) => onChange({ expr: v })} />
{!disabled && <button className="btn btn-ghost btn-sm" onClick={() => onChange(null)}>改回逐条选择</button>}
</div>
);
}
const g: CondGroup = value || { mode: "all", items: [] };
return (
<div className="space-y-1.5">
{g.items.length === 0 && <p className="text-caption text-muted">{emptyHint}</p>}
<Group g={g} depth={0} fields={fields} disabled={disabled} onChange={(x) => onChange(x)} />
{!disabled && !fields && (
<button className="btn btn-ghost btn-sm text-muted" title="直接写表达式(高级)" onClick={() => onChange({ expr: "" })}>
<Code2 className="h-3.5 w-3.5" />写表达式
</button>
)}
</div>
);
}
/**
* 表关系图:每张表一个卡片,列出主键和参与关联的字段;关联画成「字段 → 字段」的连线。
* 从一个字段拖到另一张表的字段就新建一条关联;点连线可以删除。
*/
import {
Background, ConnectionMode, Controls, Handle, MarkerType, Position, ReactFlow, applyNodeChanges,
type Connection, type Edge, type Node, type NodeChange, type NodeProps,
} from "@xyflow/react";
import "@xyflow/react/dist/style.css";
import Graph from "graphology";
import circular from "graphology-layout/circular";
import forceAtlas2 from "graphology-layout-forceatlas2";
import noverlap from "graphology-layout-noverlap";
import { KeyRound, Trash2 } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { api } from "@/lib/api";
import { cn } from "@/lib/utils";
import { toast } from "@/store/useAppStore";
import { Modal } from "@/components/ui";
import type { SmModel, SmRelation } from "@/lib/types";
type TData = { model: SmModel; fields: { name: string; type: string; pk: boolean; linked: boolean }[]; onOpen: (id: number) => void };
const ROW = 22;
function TableNode({ data }: NodeProps<Node<TData>>) {
const m = data.model;
return (
<div className="w-[230px] overflow-hidden rounded-lg border border-line bg-surface shadow-sm">
<button className="block w-full border-b border-line bg-brand/[0.06] px-2.5 py-1.5 text-left"
title={m.description || m.physical_table} onDoubleClick={() => data.onOpen(m.id)}>
<span className="block truncate font-mono text-label font-semibold">{m.physical_table}</span>
{m.description && <span className="block truncate text-caption text-muted">{m.description}</span>}
</button>
{data.fields.map((f) => (
<div key={f.name} className={cn("relative flex items-center gap-1.5 px-2.5 font-mono text-caption",
f.linked && "bg-ok/[0.06]")} style={{ height: ROW }}>
<Handle id={`${f.name}|l`} type="source" position={Position.Left}
className="!h-2 !w-2 !border-0 !bg-brand/50" />
{f.pk ? <KeyRound className="h-3 w-3 shrink-0 text-warn" /> : <span className="w-3 shrink-0" />}
<span className={cn("min-w-0 flex-1 truncate", f.linked && "font-semibold")}>{f.name}</span>
<span className="max-w-[70px] shrink-0 truncate text-muted">{f.type}</span>
<Handle id={`${f.name}|r`} type="source" position={Position.Right}
className="!h-2 !w-2 !border-0 !bg-brand/50" />
</div>
))}
</div>
);
}
const nodeTypes = { table: TableNode };
const posKey = (dsId: number) => `relgraph.pos.${dsId}`;
function loadPos(dsId: number): Record<string, { x: number; y: number }> {
try { return JSON.parse(localStorage.getItem(posKey(dsId)) || "{}"); } catch { return {}; }
}
export function RelationGraph({ dsId, models, relations, onChanged, onOpenTable, onClose }: {
dsId: number; models: SmModel[]; relations: SmRelation[];
onChanged: () => void; onOpenTable: (modelId: number) => void; onClose: () => void;
}) {
const [showAll, setShowAll] = useState(false);
const [picked, setPicked] = useState<SmRelation | null>(null);
const layout = useMemo(() => {
const saved = loadPos(dsId);
const g = new Graph({ multi: true });
models.forEach((m) => g.addNode(String(m.id), { size: 10 }));
relations.forEach((r) => {
const a = String(r.from_model_id), b = String(r.to_model_id);
if (g.hasNode(a) && g.hasNode(b) && a !== b) g.addEdge(a, b);
});
circular.assign(g, { scale: 500 });
if (g.order > 2) {
forceAtlas2.assign(g, { iterations: 300, settings: { ...forceAtlas2.inferSettings(g), gravity: 2, scalingRatio: 8 } });
noverlap.assign(g, { maxIterations: 300, settings: { margin: 60, ratio: 1.2 } });
}
const pts = models.map((m) => g.getNodeAttributes(String(m.id)) as { x: number; y: number });
const xs = pts.map((p) => p.x), ys = pts.map((p) => p.y);
const [x0, x1, y0, y1] = [Math.min(...xs), Math.max(...xs), Math.min(...ys), Math.max(...ys)];
const side = Math.ceil(Math.sqrt(models.length));
// 卡片约 230 宽、100~200 高:按这个尺度铺开,fitView 后字还看得清
const W = 270 * side, H = 190 * side;
const fit = (v: number, lo: number, hi: number, span: number) => (hi > lo ? ((v - lo) / (hi - lo)) * span : span / 2);
return Object.fromEntries(models.map((m, i) => [String(m.id),
saved[String(m.id)] ?? { x: fit(pts[i].x, x0, x1, W), y: fit(pts[i].y, y0, y1, H) }]));
}, [dsId, models, relations]);
const buildNodes = useCallback((): Node<TData>[] => {
const linked = new Map<number, Set<string>>();
relations.forEach((r) => {
if (!linked.has(r.from_model_id)) linked.set(r.from_model_id, new Set());
if (!linked.has(r.to_model_id)) linked.set(r.to_model_id, new Set());
linked.get(r.from_model_id)!.add(r.from_column);
linked.get(r.to_model_id)!.add(r.to_column);
});
return models.map((m) => {
const pk = new Set((m.primary_key || "").split(",").map((x) => x.trim()).filter(Boolean));
const lk = linked.get(m.id) ?? new Set<string>();
let cols = m.columns.filter((c) => showAll || pk.has(c.name) || lk.has(c.name));
if (!cols.length) cols = m.columns.slice(0, 3);
return {
id: String(m.id), type: "table", position: layout[String(m.id)],
data: { model: m, onOpen: onOpenTable,
fields: cols.map((c) => ({ name: c.name, type: c.data_type.replace(/\(.*\)/, ""), pk: pk.has(c.name), linked: lk.has(c.name) })) },
};
});
}, [models, relations, showAll, layout, onOpenTable]);
const [nodes, setNodes] = useState<Node<TData>[]>(buildNodes);
useEffect(() => {
// 换了显示字段 / 关联变化:保留拖过的位置
setNodes((cur) => {
const at = Object.fromEntries(cur.map((n) => [n.id, n.position]));
return buildNodes().map((n) => ({ ...n, position: at[n.id] ?? n.position }));
});
}, [buildNodes]);
const onNodesChange = (changes: NodeChange<Node<TData>>[]) => setNodes((ns) => {
const next = applyNodeChanges(changes, ns);
if (changes.some((c) => c.type === "position" && !c.dragging)) {
try { localStorage.setItem(posKey(dsId), JSON.stringify(Object.fromEntries(next.map((n) => [n.id, n.position])))); }
catch { /* 记不住位置不影响使用 */ }
}
return next;
});
const edges: Edge[] = useMemo(() => relations.map((r) => {
const a = layout[String(r.from_model_id)], b = layout[String(r.to_model_id)];
const leftToRight = !a || !b || a.x <= b.x;
return {
id: String(r.id), source: String(r.from_model_id), target: String(r.to_model_id),
sourceHandle: `${r.from_column}|${leftToRight ? "r" : "l"}`, targetHandle: `${r.to_column}|${leftToRight ? "l" : "r"}`,
type: "default", label: r.cardinality || "N:1",
labelStyle: { fontSize: 10 }, labelBgPadding: [4, 2] as [number, number],
style: { strokeWidth: picked?.id === r.id ? 2.5 : 1.5, stroke: picked?.id === r.id ? "#6366f1" : "#64748b" },
markerEnd: { type: MarkerType.ArrowClosed, width: 14, height: 14 },
};
}), [relations, layout, picked]);
const connect = async (c: Connection) => {
if (!c.source || !c.target || c.source === c.target) return;
const [fromCol] = (c.sourceHandle || "").split("|");
const [toCol] = (c.targetHandle || "").split("|");
if (!fromCol || !toCol) return;
try {
await api.upsertSqlRelation(dsId, { from_model_id: Number(c.source), from_column: fromCol,
to_model_id: Number(c.target), to_column: toCol,
join_type: "inner", cardinality: "N:1" });
toast("ok", "已新增关联", `${fromCol} → ${toCol}`);
onChanged();
} catch (e) { toast("error", "新增失败", e instanceof Error ? e.message : String(e)); }
};
const remove = async (r: SmRelation) => {
try { await api.deleteSqlRelation(r.id); setPicked(null); onChanged(); }
catch (e) { toast("error", "删除失败", e instanceof Error ? e.message : String(e)); }
};
const nameOf = (id: number) => models.find((m) => m.id === id)?.physical_table ?? `#${id}`;
return (
<Modal open onClose={onClose} width="max-w-[min(1400px,96vw)]" title="表关系图" bodyClass="p-0">
<div className="flex items-center gap-3 border-b border-line px-4 py-2 text-label">
<label className="flex items-center gap-1.5">
<input type="checkbox" checked={showAll} onChange={(e) => setShowAll(e.target.checked)} />显示全部字段
</label>
<span className="text-muted">{models.length} 张表 · {relations.length} 条关联 · 从字段拖到另一张表的字段可新建关联</span>
<span className="flex-1" />
{picked && (
<span className="flex items-center gap-2">
<code className="text-label">{nameOf(picked.from_model_id)}.{picked.from_column} → {nameOf(picked.to_model_id)}.{picked.to_column}</code>
<button className="btn btn-sm text-bad" onClick={() => void remove(picked)}><Trash2 className="h-3.5 w-3.5" />删除这条</button>
</span>
)}
</div>
<div className="h-[72vh]">
<ReactFlow nodes={nodes} edges={edges} nodeTypes={nodeTypes} onNodesChange={onNodesChange}
connectionMode={ConnectionMode.Loose} onConnect={(c) => void connect(c)}
onEdgeClick={(_, e) => setPicked(relations.find((r) => String(r.id) === e.id) ?? null)}
onPaneClick={() => setPicked(null)}
fitView fitViewOptions={{ padding: 0.08 }} minZoom={0.15} proOptions={{ hideAttribution: true }}>
<Background gap={20} />
<Controls showInteractive={false} />
</ReactFlow>
</div>
</Modal>
);
}
import {
AlertTriangle, CheckCircle2, Code2, Crosshair, ListChecks, PlayCircle,
RotateCw, Sparkles, XCircle,
} from "lucide-react";
import { cn, formatDuration } from "@/lib/utils";
import { Badge } from "@/components/ui";
import type { SqlTraceEvent } from "@/lib/types";
const META: Record<string, { label: string; icon: React.ReactNode; tone: string }> = {
retrieve: { label: "召回上下文", icon: <Crosshair className="h-3.5 w-3.5" />, tone: "bg-sky-500" },
plan: { label: "查询计划", icon: <ListChecks className="h-3.5 w-3.5" />, tone: "bg-indigo-500" },
sql_draft: { label: "生成 SQL", icon: <Code2 className="h-3.5 w-3.5" />, tone: "bg-amber-500" },
validate: { label: "安全校验", icon: <CheckCircle2 className="h-3.5 w-3.5" />, tone: "bg-teal-500" },
repair: { label: "自愈重试", icon: <RotateCw className="h-3.5 w-3.5" />, tone: "bg-purple-500" },
execute: { label: "执行", icon: <PlayCircle className="h-3.5 w-3.5" />, tone: "bg-emerald-600" },
error: { label: "出错", icon: <XCircle className="h-3.5 w-3.5" />, tone: "bg-rose-600" },
};
/** 后端 error 事件里的 stage 值 → 中文步骤名 */
const STAGE_TEXT: Record<string, string> = {
start: "启动", retrieve: "召回上下文", plan: "查询计划",
sql_draft: "生成 SQL", validate: "安全校验", execute: "执行",
};
/**
* 生成轨迹。和「深挖检索」页的时间线是同一套语言 —— 每一步都要看得见:
* 召回了哪些表和指标(带分数)、用的什么口径、校验拦下了什么、重试了几轮。
* 黑盒地丢一段 SQL 出来,业务同事没法判断对不对,也就没法纠错。
*/
export function SqlTrace({ trace, running }: { trace: SqlTraceEvent[]; running: boolean }) {
const steps = trace.filter((e) => META[e.type] && e.type !== "rows");
if (steps.length === 0 && !running) return null;
return (
<ol className="space-y-1.5">
{steps.map((ev, i) => (
<li key={i} className="flex gap-2.5">
<span className={cn("mt-0.5 grid h-5 w-5 shrink-0 place-items-center rounded-full text-white",
META[ev.type].tone)}>
{META[ev.type].icon}
</span>
<div className="min-w-0 flex-1 pb-1">
<p className="flex flex-wrap items-center gap-1.5 text-label font-medium">
{META[ev.type].label}
<StepBadges ev={ev} />
</p>
<StepBody ev={ev} />
</div>
</li>
))}
{running && (
<li className="flex items-center gap-2.5 text-label text-muted">
<Sparkles className="h-3.5 w-3.5 animate-pulse" /> 处理中…
</li>
)}
</ol>
);
}
function StepBadges({ ev }: { ev: SqlTraceEvent }) {
switch (ev.type) {
case "retrieve":
return (
<>
<Badge>{ev.models.length} 张表</Badge>
{ev.metrics.length > 0 && <Badge tone="bg-brand2/10 text-brand2">{ev.metrics.length} 个指标</Badge>}
{(ev.hints?.length ?? 0) > 0 && <Badge tone="bg-warn/10 text-warn">{ev.hints.length} 条取数规则</Badge>}
{ev.pairs.length > 0 && <Badge tone="bg-ok/10 text-ok">复用 {ev.pairs.length} 条沉淀</Badge>}
<Badge tone="bg-ink/5 text-muted">{ev.schema_tokens} token</Badge>
</>
);
case "sql_draft":
return ev.attempt > 1 ? <Badge tone="bg-warn/10 text-warn">第 {ev.attempt} 次</Badge> : null;
case "validate":
return ev.ok
? <Badge tone="bg-ok/10 text-ok">通过</Badge>
: <Badge tone="bg-bad/10 text-bad">未通过</Badge>;
case "execute":
return (
<>
<Badge tone="bg-ok/10 text-ok">{ev.row_count} 行</Badge>
<Badge tone="bg-ink/5 text-muted">{formatDuration(ev.duration_ms)}</Badge>
{ev.truncated && <Badge tone="bg-warn/10 text-warn">已截断</Badge>}
</>
);
default:
return null;
}
}
function StepBody({ ev }: { ev: SqlTraceEvent }) {
switch (ev.type) {
case "retrieve":
return (
<div className="mt-1 space-y-1">
<div className="flex flex-wrap gap-1">
{ev.models.map((m) => (
<span key={m.id} className="chip px-1.5 py-0 text-caption" title={`相关度 ${m.score}`}>
{m.table}
<span className="text-muted">{m.columns} 列</span>
</span>
))}
</div>
{ev.metrics.length > 0 && (
// 口径说明动辄两三行,十几个指标铺开能把整张卡片顶到屏幕外。
// 这里每个只留一行,完整内容挂在 title 上,要细看去「取数规则」页。
<div className="space-y-0.5">
{ev.metrics.map((m) => (
<p key={m.id} className="truncate text-label text-muted"
title={m.calibre || m.name}>
指标 <span className="text-ink">{m.name}</span>
{m.calibre && <> · 口径:{m.calibre}</>}
</p>
))}
</div>
)}
{(ev.hints?.length ?? 0) > 0 && (
<div className="space-y-0.5">
{ev.hints.map((h) => (
<p key={h.id} className="truncate text-label text-muted" title={h.text}>
规则{h.ds_id ? "(本数据源)" : ""} <span className="text-ink">{h.text}</span>
</p>
))}
</div>
)}
{ev.pairs.length > 0 && (
<p className="text-label text-muted">
命中沉淀:{ev.pairs.map((p) => p.question).join(" / ")}
</p>
)}
{ev.dropped_columns > 0 && (
<p className="text-label text-warn">
上下文超预算,按相关度剪掉了 {ev.dropped_columns} 个列
</p>
)}
</div>
);
case "plan":
return (
<div className="mt-1 space-y-1 text-label text-muted">
{ev.plan?.summary && <p className="text-ink">{ev.plan.summary}</p>}
{ev.plan?.grain && <p>粒度:{ev.plan.grain}</p>}
{!!ev.plan?.measures?.length && <p>度量:{ev.plan.measures.join("、")}</p>}
{!!ev.plan?.dimensions?.length && <p>分组:{ev.plan.dimensions.join("、")}</p>}
{!!ev.plan?.filters?.length && <p>过滤:{ev.plan.filters.join(";")}</p>}
{ev.plan?.time_range && <p>时间范围:{ev.plan.time_range}</p>}
{ev.calibre && ev.calibre !== "无特殊口径" && (
// 口径是这套业务最容易出错的地方,单独高亮
<p className="rounded-md border border-brand/30 bg-brand/5 px-2 py-1 text-brand">
口径:{ev.calibre}
</p>
)}
{ev.clarify && <p className="text-warn">需要澄清:{ev.clarify}</p>}
</div>
);
case "validate":
if (ev.issues.length === 0) {
return (
<p className="mt-0.5 text-label text-muted">
只读检查、表与关联白名单都通过{ev.limited && ";已自动补上 LIMIT"}
</p>
);
}
return (
<ul className="mt-1 space-y-0.5">
{ev.issues.map((it, i) => (
<li key={i} className={cn("flex gap-1.5 text-label",
it.level === "error" ? "text-bad" : "text-warn")}>
<AlertTriangle className="mt-0.5 h-3 w-3 shrink-0" />
<span>
{it.msg}
{it.fix && <span className="text-muted"> — {it.fix}</span>}
</span>
</li>
))}
</ul>
);
case "repair":
return <p className="mt-0.5 text-label text-muted">因为:{ev.reason}</p>;
case "error":
// 只说清在哪一步挂的。完整报错在右边的醒目框里,这里重复一遍纯属噪声。
return (
<p className="mt-0.5 text-label text-muted">
在「{STAGE_TEXT[ev.stage] ?? ev.stage}」阶段失败
{ev.attempts ? `,已重试 ${ev.attempts - 1} 轮` : ""}
</p>
);
default:
return null;
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!