Commit 743bd6df by 黄南光

大幅修改优化本体系统

1 parent 068a6186
Showing 144 changed files with 2286 additions and 540 deletions
......@@ -24,6 +24,14 @@
"port": 9100
},
{
"name": "onto-9101",
"runtimeExecutable": "./.venv/Scripts/python.exe",
"runtimeArgs": [
"scripts/serve_9101.py"
],
"port": 9101
},
{
"name": "onto-8100-api",
"runtimeExecutable": "./.venv/Scripts/python.exe",
"runtimeArgs": [
......
......@@ -15,3 +15,6 @@ default.rules
/data_*/
*.log
/results*.json
data_9101/
web/e2e/shots/
......@@ -210,7 +210,8 @@ ANSWER_SYSTEM = """你是企业本体系统的主 Agent,现在根据各子 Age
4. `#### 建议下一步`:**只有【本轮实际生成的卡片】里列出的**动作 / 流程才可以说「已在答案下方生成卡片」——
动作卡请用户核对参数后点「提交审批」,流程卡请用户核对后点「确认并发起」。
【本轮实际生成的卡片】写着「无」时,绝不能说已经生成、已经提交、已经发起了任何东西;
可以用「建议……」的口吻说下一步怎么办。不要让用户「去业务系统里操作」。
可以用「建议……」的口吻说下一步怎么办,但**不要提「卡片」两个字**,也不要说「本轮未生成卡片」这类话。
没有明确的下一步时,整个「建议下一步」小节省略。不要让用户「去业务系统里操作」。
引用规则:
- 数字只能来自【执行结果】,**绝不编造**;引用取数结果时在句末加 [^run:编号],编号只能是「数据编号 run:数字」里的数字。
......@@ -219,6 +220,8 @@ ANSWER_SYSTEM = """你是企业本体系统的主 Agent,现在根据各子 Age
- 执行失败或没查到的,如实说明缺什么,不要硬答;没查到的事实不下结论。
- 读者是业务人员:不要写工具名、步骤编号(k1、d2)、「数据编号 run:…」和技术报错原文,换成业务语言;
数据来源只用句末角标表示,表头写业务名称。
- 不要写字段的英文名(如 on_hand、status),用它的业务名称;整数不带 .0,金额带千分位;
只说查到的事实,不要推测业务原因,也不要写「符合……特征」这类没有依据的判断。
- 组织记忆里的口径与偏好要遵循。
"""
......@@ -253,6 +256,7 @@ FAST_ANSWER_SYSTEM = """你是企业本体系统的助手。系统已经按确
- 数字、名称只能来自【查询结果】,**绝不编造**;引用取数结果在句末加 [^run:编号],引用文档原文加 [^片段编号]。
- 没查到就如实说没查到、缺什么,不要硬答。
- 不要写工具名、SQL、技术报错原文;不要说已经发起、提交、创建了任何东西。
- 不要写字段的英文名(如 on_hand),用它的业务名称;整数不带 .0,金额带千分位。
"""
FAST_ANSWER_USER = """【问题】
......
......@@ -40,7 +40,7 @@ async def upload_document(file: UploadFile = File(...)):
415, f"暂不支持 {suffix or '无扩展名'} 格式。支持:{'、'.join(sorted(SUPPORTED))}")
h = hashlib.sha256(raw).hexdigest()[:16]
existing = db.find_document_by_hash(h)
existing = db.find_document_by_hash(h, identity.current().workspace)
if existing:
return {**existing, "duplicate": True,
"message": f"该文件已存在(ID {existing['id']}:{existing['filename']})"}
......
......@@ -51,7 +51,7 @@ def _sync_after_publish(rev) -> None:
from .kernel import pipeline
def gen():
created = pipeline.ensure_all()["created"]
created = pipeline.ensure_all("hourly")["created"] # 关系索引每小时自己刷新,用户不用管
if created:
yield {"stage": "pipeline", "progress": 1, "message": f"新建 {len(created)} 条数据管道"}
yield from pipeline.run_all_events()
......
......@@ -155,7 +155,7 @@ async def prepare_action(ref: str, body: ProposeIn, _: identity.Actor = Depends(
# 预览可以引用草稿(动作本身、它用到的决策表),正式提议仍只认已发布的
from ..kernel import service as ksvc
with ksvc.draft_runtime():
return actions.prepare(ref, body.params, body.object_key)
return actions.prepare(ref, body.params, body.object_key, strict=False)
@router.post("/actions/{ref}/propose")
......
......@@ -66,6 +66,8 @@ class ApprovalTask(Base):
workspace: Mapped[str] = mapped_column(String(64), default="default", index=True)
run_id: Mapped[str] = mapped_column(String(64), index=True)
approver_roles_json: Mapped[str] = mapped_column(Text, default="[]")
stage: Mapped[int] = mapped_column(Integer, default=0) # 第几段审批(从 0 起)
stage_name: Mapped[str] = mapped_column(String(64), default="")
status: Mapped[str] = mapped_column(String(16), default="pending", index=True)
decided_by: Mapped[str] = mapped_column(String(128), default="")
comment: Mapped[str] = mapped_column(Text, default="")
......
......@@ -143,21 +143,15 @@ def object_properties(ot_ref: str, writable_only: bool = False) -> list[dict]:
def function_inputs(fn_ref: str, category: str | None = None) -> list[dict]:
"""函数的输入(按类型化签名,六类函数同一个样子)。"""
from ..kernel import signature
fn = lookup(fn_ref, "function", category)
if not fn:
return []
spec = fn.get("spec") or {}
cat = spec.get("category")
if cat == "rule":
return [{"value": p, "label": p} for p in spec.get("params") or []]
if cat in ("decision", "ml", "ai"):
return [{"value": i["name"], "label": i.get("label") or i["name"], "type": i.get("type") or ""}
for i in spec.get("inputs") or [] if i.get("name")]
if cat == "calendar":
return [{"value": "ref", "label": "哪一期"}]
if cat == "aggregate":
return [{"value": "time", "label": "统计时间"}, {"value": "object_key", "label": "对象主键"}]
return []
return [{"value": i["name"], "label": i["label"], "type": i["type"], "required": bool(i.get("required")),
"options": i.get("options") or [], "object_type": i.get("object_type") or "",
"hint": i.get("description") or "", "default": i.get("default")}
for i in signature.signature(fn)["inputs"]]
def options(ref: str, of: str = "") -> list[dict]:
......
......@@ -59,7 +59,8 @@ def run(skill_ref: str, inputs: dict, emit: Emit | None = None,
messages = [
{"role": "system", "content": SKILL_SYSTEM.format(
instructions=spec["instructions"], functions=_fn_catalog(allowed),
output_schema=json.dumps(spec.get("output_schema") or {}, ensure_ascii=False),
output_schema=output_shape(spec.get("output_fields")) if spec.get("output_fields")
else json.dumps({**(spec.get("output_schema") or {}), "confidence": "0~1"}, ensure_ascii=False),
max_steps=spec["max_steps"])},
{"role": "user", "content": "输入:\n" + _trim(inputs, 6000)}]
trace: list[dict] = []
......@@ -96,8 +97,12 @@ def run(skill_ref: str, inputs: dict, emit: Emit | None = None,
{"role": "user", "content": f"函数 {fname} 的结果:\n{content}"}]
audit.record("skill.run", "capability", sk["id"], f"运行技能「{sk['name']}」",
after={"inputs": inputs, "trace": trace})
return {"skill": sk["name"], "output": final, "trace": trace,
"summary": (final or {}).get("conclusion", "") if isinstance(final, dict) else str(final)[:200]}
fields = spec.get("output_fields") or []
final = coerce_output(final, fields) if fields else {**(final if isinstance(final, dict) else {"conclusion": str(final)}),
"ai_judged": True}
return {"skill": sk["name"], "output": final, "trace": trace, "confidence": final.get("confidence"),
"ai_judged": True,
"summary": str(final.get("conclusion") or final.get("reason") or "")[:200]}
INLINE_SYSTEM = """你在流程里做一步业务分析。只根据给你的数据下结论,不要编造数据;数据不够就明说缺什么。
......@@ -105,22 +110,75 @@ INLINE_SYSTEM = """雿瘚甇乩蝏
【要求】
{instruction}
只输出一个 JSON 对象:{{"conclusion": "一两句话的结论", "points": ["要点 1", "要点 2"]}}
只输出一个 JSON 对象:{shape}
confidence 是你对结论的把握程度(0~1 的小数):数据充分、结论明确给 0.8 以上;数据缺失或模棱两可给 0.5 以下。
"""
_TYPE_HINT = {"string": "文字", "number": "数字", "boolean": "true/false", "date": "YYYY-MM-DD", "list": "数组", "any": "任意"}
def run_inline(instruction: str, inputs: dict) -> dict:
"""流程卡里直接写的一段分析要求(不必先登记成 AI 分析函数):只读给它的数据,不调用任何函数。"""
def output_shape(fields: list[dict] | None) -> str:
"""结构化输出 → 给大模型看的 JSON 形状说明。"""
if not fields:
return '{"conclusion": "一两句话的结论", "points": ["要点 1", "要点 2"], "confidence": 0.8}'
parts = []
for f in fields:
hint = f.get("label") or f["name"]
if f.get("options"):
hint += ",只能是 " + " / ".join(f["options"])
else:
hint += f",{_TYPE_HINT.get(f.get('type') or 'any', '任意')}"
parts.append(f'"{f["name"]}": <{hint}>')
return "{" + ", ".join(parts) + ', "confidence": <0~1>, "reason": "一句话说明依据"}'
def coerce_output(out: Any, fields: list[dict] | None) -> dict:
"""按定义的输出字段收拾大模型的回答:类型转一下、可选值之外的置空,免得后面的条件分支被脏值带偏。"""
if not isinstance(out, dict):
out = {"conclusion": str(out)[:500]}
res: dict[str, Any] = {}
if not fields:
res = {"conclusion": str(out.get("conclusion") or ""), "points": [str(x) for x in out.get("points") or []]}
for f in fields or []:
v = out.get(f["name"])
t = f.get("type") or "any"
if t == "number":
try:
v = float(v) if v not in (None, "") else None
except (TypeError, ValueError):
v = None
elif t == "boolean" and not isinstance(v, bool):
v = str(v).strip().lower() in ("true", "1", "是", "yes") if v not in (None, "") else None
elif t == "list" and not isinstance(v, list):
v = [] if v in (None, "") else [v]
if f.get("options") and v not in f["options"]:
v = None
res[f["name"]] = v
try:
conf = float(out.get("confidence"))
except (TypeError, ValueError):
conf = None
res["confidence"] = max(0.0, min(1.0, conf)) if conf is not None else None
if out.get("reason"):
res["reason"] = str(out["reason"])[:300]
res["ai_judged"] = True
return res
def run_inline(instruction: str, inputs: dict, outputs: list[dict] | None = None) -> dict:
"""流程卡里直接写的一段分析要求(不必先登记成 AI 分析函数):只读给它的数据,不调用任何函数。
outputs:要它按哪些字段回答(结构化输出),后面的条件分支可以直接用这些字段。"""
if not (instruction or "").strip():
raise HTTPException(422, "AI 分析步骤还没写要它分析什么")
messages = [{"role": "system", "content": INLINE_SYSTEM.format(instruction=instruction.strip())},
raise HTTPException(422, "AI 步骤还没写要它分析什么")
messages = [{"role": "system", "content": INLINE_SYSTEM.format(instruction=instruction.strip(),
shape=output_shape(outputs))},
{"role": "user", "content": "数据:\n" + _trim(inputs, 6000)}]
with llmlog.feature("skill"):
try:
out = llm.chat_json(messages, temperature=0.1)
except Exception as e: # noqa: BLE001
raise HTTPException(502, f"AI 分析调用大模型失败:{str(e)[:200]}") from e
if not isinstance(out, dict):
out = {"conclusion": str(out)[:500], "points": []}
final = {"conclusion": str(out.get("conclusion") or ""), "points": [str(x) for x in out.get("points") or []]}
return {"skill": "", "output": final, "trace": [], "summary": final["conclusion"][:200]}
final = coerce_output(out, outputs)
summary = final.get("conclusion") or final.get("reason") or ",".join(
f"{f.get('label') or f['name']}:{final.get(f['name'])}" for f in (outputs or [])[:3])
return {"skill": "", "output": final, "trace": [], "summary": str(summary)[:200]}
......@@ -67,6 +67,8 @@ DEFAULT_RUNTIME: dict[str, str] = {
"EMBED_DIM": "1024",
"RERANK_MODEL": "gte-rerank-v2",
"LLM_BASE_URL": "",
"LLM_THINKING": "auto",
"LLM_THINKING_BUDGET": "8192", # 建模类步骤最多想多少 token(0 = 不限)
"LLM_CACHE": "1", # LLM 响应缓存开关
# --- 分块 ---
"CHUNK_TOKENS": "600", # 每块目标 token 数
......@@ -158,6 +160,10 @@ RUNTIME_META: dict[str, dict] = {
"EMBED_DIM": {"group": "模型", "label": "向量维度", "type": "int", "min": 64, "max": 4096},
"RERANK_MODEL": {"group": "模型", "label": "重排模型", "type": "text", "help": "留空则不重排"},
"LLM_BASE_URL": {"group": "模型", "label": "OpenAI 兼容地址", "type": "text", "help": "留空 = 用 DashScope SDK"},
"LLM_THINKING": {"group": "模型", "label": "让模型先思考再回答", "type": "text",
"help": "只对带思考能力的模型有用。auto = 提问和起草时思考(更准),有校验兜底的小步骤不思考;on = 总是;off = 从不(快几倍,但会答错、会凑数)"},
"LLM_THINKING_BUDGET": {"group": "模型", "label": "建模时最多思考多少", "type": "int", "min": 0, "max": 32768,
"help": "AI 建模、起草时每次最多思考的 token 数,0 = 不限。不限时读一批文档要三四分钟,大多花在反复斟酌上"},
"LLM_CACHE": {"group": "模型", "label": "LLM 响应缓存", "type": "bool", "help": "相同请求直接复用,省额度"},
"CHUNK_TOKENS": {"group": "分块", "label": "每块 token 数", "type": "int", "min": 128, "max": 4000},
"CHUNK_OVERLAP_TOKENS": {"group": "分块", "label": "块间重叠 token", "type": "int", "min": 0, "max": 1000},
......
......@@ -18,6 +18,7 @@ from sqlalchemy import (
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session
from .config import get_settings, DEFAULT_RUNTIME
from .reqcache import per_request
log = logging.getLogger(__name__)
_settings = get_settings()
......@@ -102,6 +103,9 @@ _ADD_COLUMNS: dict[str, dict[str, str]] = {
"parent_run_id": "VARCHAR(64) NOT NULL DEFAULT ''"},
"otlg_mem_case": {"voters_json": "TEXT"},
"otlg_document": {"workspace": "VARCHAR(64) NOT NULL DEFAULT ''"},
"otlg_approval": {"stage": "INT NOT NULL DEFAULT 0", "stage_name": "VARCHAR(64) NOT NULL DEFAULT ''"},
"otlg_watch_state": {"label": "VARCHAR(255) NOT NULL DEFAULT ''", "first_seen_at": "DATETIME NULL",
"recovered_at": "DATETIME NULL", "detail_json": "LONGTEXT"},
}
......@@ -163,6 +167,7 @@ def init_db() -> None:
# ---------- 运行时配置 ----------
@per_request
def get_all_config() -> dict[str, str]:
with Session(get_engine()) as s:
rows = s.scalars(select(Config)).all()
......@@ -171,6 +176,7 @@ def get_all_config() -> dict[str, str]:
return cfg
@per_request
def get_config(key: str, default: str | None = None) -> str:
with Session(get_engine()) as s:
row = s.get(Config, key)
......@@ -201,9 +207,13 @@ def create_document(filename: str, stored_path: str, size_bytes: int, file_hash:
return d.id
def find_document_by_hash(file_hash: str) -> Optional[dict]:
def find_document_by_hash(file_hash: str, workspace: str | None = None) -> Optional[dict]:
"""同一个文件只存一份 —— 按本体空间算:别的空间传过同一份文件,这里看不到它,要能再传一次。"""
with Session(get_engine()) as s:
r = s.scalars(select(Document).where(Document.file_hash == file_hash)).first()
q = select(Document).where(Document.file_hash == file_hash)
if workspace is not None:
q = q.where(Document.workspace.in_(["", workspace]))
r = s.scalars(q).first()
return _doc_dict(r) if r else None
......
......@@ -10,6 +10,8 @@ v2 新增:
BPE 词表,容器内会失败。这里用对中文足够准的启发式估算。
"""
from __future__ import annotations
import contextlib
import contextvars
import json
import logging
import re
......@@ -89,6 +91,39 @@ def _prompt_text(messages: list[dict]) -> str:
return "\n".join(str(m.get("content", "")) for m in messages)
# ---------------- 调用追踪 ----------------
class Cancelled(BaseException):
"""调用方要求中断正在进行的调用(如终止一次 AI 建模)。
继承 BaseException:各处兜底的 `except Exception` 不会把它吞掉,chat() 也不会拿它重试。"""
_trace: contextvars.ContextVar[tuple[Any, str] | None] = contextvars.ContextVar("llm_trace", default=None)
@contextlib.contextmanager
def tracing(sink: Any, label: str = ""):
"""在这个范围里的每次 chat() 都报给 sink:开始、思考过程与输出(流式,约每 1.5 秒一次)、结束。
sink 要有 begin(label, feature, model, prompt) -> handle、update(handle, reasoning, output)、
end(handle, **result) 三个方法;begin / update 里可以抛 Cancelled 或别的 BaseException 来停下。"""
tok = _trace.set((sink, label))
try:
yield
finally:
_trace.reset(tok)
def trace_label(label: str):
"""已经在追踪里时,只给接下来的调用换个名字(如「读文档 · 第 2/4 批」);没在追踪就什么也不做。"""
cur = _trace.get()
return tracing(cur[0], label) if cur else contextlib.nullcontext()
def _feature() -> str:
from ..governance import llmlog
return llmlog.current_feature()
# ---------------- Chat ----------------
def chat(messages: list[dict], temperature: float = 0.2, max_retries: int = 3,
use_cache: bool | None = None) -> str:
......@@ -97,26 +132,47 @@ def chat(messages: list[dict], temperature: float = 0.2, max_retries: int = 3,
cache_on = _cache_on() if use_cache is None else use_cache
ck = KVCache.key({"m": model, "msgs": messages, "t": temperature, "u": base_url})
started = time.time()
traced = _trace.get()
if cache_on:
hit = _cache.get(ck)
if isinstance(hit, str):
_observe("chat", model, _prompt_text(messages), hit, started, cached=True)
if traced:
sink, label = traced
sink.end(sink.begin(label, _feature(), model, _prompt_text(messages)), output=hit, cached=True)
return hit
last_err = ""
for attempt in range(max_retries):
handle = None
try:
if traced:
sink, label = traced
handle = sink.begin(label + (f"(第 {attempt + 1} 次)" if attempt else ""), _feature(), model,
_prompt_text(messages))
with _sem:
out = (_chat_openai(base_url, model, messages, temperature) if base_url
else _chat_dashscope(model, messages, temperature))
if traced and not base_url:
out, reasoning, usage = _chat_dashscope_traced(model, messages, temperature, traced[0], handle)
else:
out = (_chat_openai(base_url, model, messages, temperature) if base_url
else _chat_dashscope(model, messages, temperature))
reasoning, usage = "", {}
if cache_on:
_cache.set(ck, out)
_observe("chat", model, _prompt_text(messages), out, started)
if handle is not None:
traced[0].end(handle, output=out, reasoning=reasoning, usage=usage)
return out
except Exception as e: # noqa: BLE001
last_err = str(e)
if handle is not None:
traced[0].end(handle, ok=False, error=last_err[:500])
log.warning("chat 第 %d 次失败:%s", attempt + 1, last_err[:200])
time.sleep(1.2 * (attempt + 1))
except BaseException:
if handle is not None:
traced[0].end(handle, ok=False, error="已终止")
raise
_observe("chat", model, _prompt_text(messages), "", started, ok=False)
raise RuntimeError(f"chat 调用失败:{last_err}")
......@@ -169,20 +225,76 @@ def chat_stream_cached(messages: list[dict], temperature: float = 0.2) -> Iterat
_cache.set(ck, out)
# 这些步骤不思考会答错数、会凑数;其余(抽实体、写说明等)有校验兜底或不要紧,直接答
_THINK = {"ask", "eval_judge", "ontology_propose", "ontology_dedupe", "ontology_draft", "modeling_action", "modeling_sop",
"sop_draft", "modeling_deepen", "modeling_metric", "modeling_action_fix", "sop_draft_fix"}
# 起草类步骤:要思考,但不让它无限斟酌 —— 不限时读一批文档能想出四五万字、三四分钟,结果并不更好。
# 提问(ask)不限,答对数比快重要。
_BUDGETED = {"ontology_propose", "ontology_dedupe", "ontology_draft", "modeling_action", "modeling_sop", "sop_draft",
"modeling_deepen", "modeling_metric", "modeling_action_fix", "sop_draft_fix"}
def _thinking() -> dict:
"""带思考能力的模型默认会先想一大段再答:回答问题时这样更准,但批量起草一批元素要七八分钟。
auto(默认):只在 _THINK 列出的步骤思考;on / off:总是 / 从不。
起草类步骤再加 LLM_THINKING_BUDGET 的上限(0 = 不限)。"""
mode = (db.get_config("LLM_THINKING") or "auto").strip().lower()
if mode in ("off", "0", "false"):
return {"enable_thinking": False}
from ..governance import llmlog
feat = llmlog.current_feature()
if mode not in ("on", "1", "true") and feat not in _THINK:
return {"enable_thinking": False}
try:
budget = int(db.get_config("LLM_THINKING_BUDGET") or "0")
except ValueError:
budget = 0
return {"thinking_budget": budget} if budget > 0 and feat in _BUDGETED else {}
def _chat_dashscope(model: str, messages: list[dict], temperature: float) -> str:
from dashscope import Generation
r = Generation.call(model=model, api_key=_key(), messages=messages,
result_format="message", temperature=temperature)
result_format="message", temperature=temperature, **_thinking())
if getattr(r, "status_code", None) != 200:
raise RuntimeError(f"DashScope code={getattr(r, 'status_code', None)} msg={getattr(r, 'message', '')}")
return r.output.choices[0].message.content
def _chat_dashscope_traced(model: str, messages: list[dict], temperature: float,
sink: Any, handle: Any) -> tuple[str, str, dict]:
"""流式拿思考过程和输出,边收边报给 sink(它可以借机抛 Cancelled 打断)。返回 (输出, 思考, usage)。"""
from dashscope import Generation
resp = Generation.call(model=model, api_key=_key(), messages=messages,
result_format="message", temperature=temperature,
stream=True, incremental_output=True, **_thinking())
think: list[str] = []
out: list[str] = []
usage: dict = {}
last = time.time()
for chunk in resp:
if getattr(chunk, "status_code", None) != 200:
raise RuntimeError(f"DashScope code={getattr(chunk, 'status_code', None)} "
f"msg={getattr(chunk, 'message', '')}")
try:
msg = chunk.output.choices[0].message
except Exception: # noqa: BLE001
continue
think.append(getattr(msg, "reasoning_content", "") or "")
out.append(getattr(msg, "content", "") or "")
if getattr(chunk, "usage", None):
usage = dict(chunk.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_dashscope(model: str, messages: list[dict], temperature: float) -> Iterator[str]:
from dashscope import Generation
resp = Generation.call(model=model, api_key=_key(), messages=messages,
result_format="message", temperature=temperature,
stream=True, incremental_output=True)
stream=True, incremental_output=True, **_thinking())
for chunk in resp:
if getattr(chunk, "status_code", None) != 200:
raise RuntimeError(f"DashScope stream code={getattr(chunk, 'status_code', None)}")
......
"""一次请求之内的小缓存。
一次「动作预检」「对象详情」会查几十次业务数据,每查一次都要重新读数据源、表结构、系统设置 ——
这些在一次请求里不会变。在请求开始时打开缓存、结束时丢掉;请求之外(后台任务、测试)不缓存。
期间只要执行了任何写语句(系统库或业务库),缓存立刻清空,所以读到的不会是旧值。
"""
from __future__ import annotations
import contextvars
import copy
import functools
from typing import Any, Callable
from sqlalchemy import event
from sqlalchemy.engine import Engine
_store: contextvars.ContextVar[dict | None] = contextvars.ContextVar("reqcache", default=None)
def begin():
return _store.set({})
def end(token) -> None:
_store.reset(token)
def clear() -> None:
d = _store.get()
if d:
d.clear()
def per_request(fn: Callable) -> Callable:
"""同一次请求里,同样的参数只算一次。返回的是副本,调用方随便改不会污染缓存。"""
@functools.wraps(fn)
def wrapper(*args: Any, **kwargs: Any):
d = _store.get()
if d is None:
return fn(*args, **kwargs)
try:
key = (fn.__module__, fn.__qualname__, args, tuple(sorted(kwargs.items())))
hash(key)
except TypeError:
return fn(*args, **kwargs)
if key not in d:
d[key] = fn(*args, **kwargs)
return copy.deepcopy(d[key])
return wrapper
_READ = ("select", "set ", "show", "with", "pragma", "explain", "describe")
@event.listens_for(Engine, "before_cursor_execute")
def _on_statement(conn, cursor, statement, parameters, context, executemany) -> None: # noqa: ARG001
# 任何写语句(不管走 ORM 还是直接执行)都让缓存失效
if _store.get() and not statement.lstrip().lower().startswith(_READ):
clear()
......@@ -67,6 +67,14 @@ async def delete_role(role_id: int, _: identity.Actor = Depends(require("admin")
return {"ok": True}
# ---------- 来龙去脉 ----------
@router.get("/trace")
async def trace_of(kind: str, id: str, _: identity.Actor = Depends(require("view"))):
"""一条记录的上游和下游(监控 → 流程运行 → 审批单 → 对象),每一项都带链接。"""
from . import trace
return trace.trace(kind, id)
# ---------- 审计 ----------
@router.get("/audit")
async def audit_query(actor_id: str = "", event: str = "", target_type: str = "",
......@@ -104,7 +112,7 @@ async def audit_get(audit_id: int, _: identity.Actor = Depends(require("view")))
@router.get("/review")
async def review_list(status: str = "pending", kind: str = "", q: str = "", limit: int = 200,
offset: int = 0, _: identity.Actor = Depends(require("view"))):
return review.list_items(status=status, kind=kind, q=q, limit=limit, offset=offset)
return review.list_items(status=status, kind=kind, q=q, limit=limit, offset=offset, inbox=True)
@router.get("/review/counts")
......
......@@ -53,14 +53,15 @@ def _dict(r: ReviewItem) -> dict:
def propose(kind: str, title: str, payload: dict, *, source: str = "user",
confidence: float = 0.0, target_ref: str = "", assignee_role: str = "builder",
dedupe: bool = True) -> dict:
"""提一条待审核项。同 kind + 同 target_ref + 同标题的未决项不重复提。"""
"""提一条待审核项。同来源 + 同 kind + 同 target_ref + 同标题的未决项不重复提。
来源不同不算重复:两次 AI 建模各有各的草案,否则后一次会「借用」前一次还没决定的条目,自己一条都没有。"""
actor = identity.current()
with session() as s:
if dedupe:
dup = s.scalars(select(ReviewItem).where(
ReviewItem.workspace == actor.workspace, ReviewItem.kind == kind,
ReviewItem.status == "pending", ReviewItem.title == title[:500],
ReviewItem.target_ref == target_ref)).first()
ReviewItem.target_ref == target_ref, ReviewItem.source == source)).first()
if dup:
dup.payload_json = jdump(payload)
dup.confidence = max(dup.confidence or 0.0, confidence)
......@@ -78,11 +79,19 @@ def propose(kind: str, title: str, payload: dict, *, source: str = "user",
return out
# AI 建模的草案在建模页里由人自己决定采纳与否,不进「审批与待办」
PRIVATE_SOURCES = ("modeling:",)
def list_items(*, status: str = "pending", kind: str = "", q: str = "", source: str = "",
limit: int = 200, offset: int = 0) -> dict:
limit: int = 200, offset: int = 0, inbox: bool = False) -> dict:
"""inbox=True:审批与待办里看的队列,去掉 PRIVATE_SOURCES 来源的条目。"""
ws = identity.current().workspace
with session() as s:
stmt = select(ReviewItem).where(ReviewItem.workspace == ws)
if inbox:
for p in PRIVATE_SOURCES:
stmt = stmt.where(ReviewItem.source.notlike(f"{p}%"))
if status:
stmt = stmt.where(ReviewItem.status == status)
if kind:
......@@ -98,11 +107,14 @@ def list_items(*, status: str = "pending", kind: str = "", q: str = "", source:
def counts() -> dict[str, int]:
"""审批与待办的角标:只数要别人处理的(不含 PRIVATE_SOURCES)。"""
ws = identity.current().workspace
with session() as s:
rows = s.execute(select(ReviewItem.kind, func.count(ReviewItem.id))
.where(ReviewItem.workspace == ws, ReviewItem.status == "pending")
.group_by(ReviewItem.kind)).all()
stmt = select(ReviewItem.kind, func.count(ReviewItem.id)).where(
ReviewItem.workspace == ws, ReviewItem.status == "pending")
for p in PRIVATE_SOURCES:
stmt = stmt.where(ReviewItem.source.notlike(f"{p}%"))
rows = s.execute(stmt.group_by(ReviewItem.kind)).all()
return {k: int(n) for k, n in rows}
......@@ -126,7 +138,8 @@ def get(item_id: str) -> dict | None:
def decide(item_id: str, accept: bool, comment: str = "",
payload: dict | None = None) -> dict:
payload: dict | None = None, perm: str = "review") -> dict:
"""perm:需要的权限。审核队列是 review;AI 建模的草案由搭建的人自己定,传 build。"""
actor = identity.current()
with session() as s:
r = s.get(ReviewItem, item_id)
......@@ -138,7 +151,7 @@ def decide(item_id: str, accept: bool, comment: str = "",
if not accept and not comment.strip():
raise HTTPException(422, "驳回时请填写意见,方便提议方改进")
from . import permissions
why = permissions.can_decide(actor, perm="review", allow_self=True, what="审核项")
why = permissions.can_decide(actor, perm=perm, allow_self=True, what="审核项")
if why:
raise HTTPException(403, why)
if accept and permissions.self_decided(actor, [item.get("created_by") or ""]):
......
"""来龙去脉:任意一条记录(审批单、流程运行、待办、监控)是从哪来的、又引出了什么。
各模块自己只存了一个来源编号(`sop_step:…`、`watch:…`),界面上没法点。这里把这些编号解析成
「类型 + 标题 + 状态 + 链接」,所有详情页用同一个组件画出来:上游在左,下游在右。
"""
from __future__ import annotations
import logging
from typing import Any
from sqlalchemy import select
from ..core.dbx import iso, jload, session
log = logging.getLogger(__name__)
KIND_LABEL = {"watch": "监控", "sop_run": "流程运行", "action_run": "审批单", "task": "待办",
"object": "对象", "ask": "提问", "user": "人工发起", "mcp": "外部助手"}
def _node(kind: str, id_: str, title: str, status: str = "", link: str = "", at: Any = None, note: str = "") -> dict:
return {"kind": kind, "kind_label": KIND_LABEL.get(kind, kind), "id": id_, "title": title, "status": status,
"link": link, "at": iso(at) if at is not None and not isinstance(at, str) else (at or ""), "note": note}
def _watch(wid: str) -> dict | None:
from ..watch.models import Watch
with session() as s:
w = s.get(Watch, wid)
return _node("watch", wid, w.title, "启用" if w.enabled else "停用", f"#/watch?id={wid}") if w else None
def _sop_run(rid: str) -> dict | None:
from ..sop.models import SopRun
with session() as s:
r = s.get(SopRun, rid)
while r is not None and r.kind == "row" and r.parent_run_id: # 逐条处理里的一行 → 它所在的那次运行
r = s.get(SopRun, r.parent_run_id)
return _node("sop_run", r.id, r.title, r.status, f"#/sop?run={r.id}", r.created_at) if r else None
def _action(aid: str) -> dict | None:
from ..capability.models import ActionRun
with session() as s:
r = s.get(ActionRun, aid)
return _node("action_run", r.id, r.action_name, r.status, f"#/inbox?run={r.id}", r.created_at) if r else None
def _task(tid: str) -> dict | None:
from ..capability.models import Task
with session() as s:
t = s.get(Task, tid)
return _node("task", t.id, t.title, t.status, f"#/inbox?tab=tasks&task={t.id}", t.created_at) if t else None
def _object(ref: str) -> dict | None:
"""ref:object:<type_id>:<key> 或 <type_id>:<key>。"""
from ..kernel import objects, service as ksvc
parts = ref.split(":")
if parts and parts[0] == "object":
parts = parts[1:]
if len(parts) < 2 or not parts[1]:
return None
type_id, key = parts[0], ":".join(parts[1:])
ot = ksvc.rt_find(type_id, "object_type")
if not ot:
return None
label = objects.labels(ot["id"], [key]).get(key, key)
return _node("object", f"{ot['id']}:{key}", f"{ot['name']}「{label}」", "",
f"#/objects?type={ot['id']}&key={key}")
def _step_run(sid: str) -> dict | None:
from ..sop.models import SopStepRun
with session() as s:
st = s.get(SopStepRun, sid)
if st is None:
return None
rid, title = st.run_id, st.title
n = _sop_run(rid)
if n:
n["note"] = f"步骤「{title}」"
return n
def source(ref: str) -> dict | None:
"""把一个来源编号变成能点的节点;不认识的返回 None(界面上就不显示)。"""
ref = str(ref or "")
try:
if ref.startswith("watch:"):
return _watch(ref.split(":")[1])
if ref.startswith("sop_step:"):
return _step_run(ref.split(":", 1)[1])
if ref.startswith("sop:"):
return _sop_run(ref.split(":", 1)[1])
if ref.startswith(("turn:", "ask")):
return _node("ask", ref, "提问里的建议", "", "#/ask")
if ref == "mcp":
return _node("mcp", ref, "外部助手经接口发起")
except Exception: # noqa: BLE001
log.debug("解析来源失败 %s", ref, exc_info=True)
return None
def trace(kind: str, id_: str) -> dict:
"""返回 {up: [上游…], down: [下游…]},都是能点的节点。"""
up: list[dict] = []
down: list[dict] = []
def add(lst: list[dict], n: dict | None) -> None:
if n and not any(x["kind"] == n["kind"] and x["id"] == n["id"] for x in lst):
lst.append(n)
try:
if kind == "action_run":
from ..capability.models import ActionRun, Task
with session() as s:
r = s.get(ActionRun, id_)
if r is None:
return {"up": [], "down": []}
src, target = r.source_ref, r.target_ref
effects = (jload(r.result_json, {}) or {}).get("effects") or []
tasks = [t.id for t in s.scalars(select(Task).where(Task.source_type == "action",
Task.source_id == id_)).all()]
add(up, source(src))
if target:
add(up, _object(target))
for e in effects:
res = (e or {}).get("result") or {}
if e.get("ok") and res.get("type_id") and res.get("key"):
add(down, _object(f"{res['type_id']}:{res['key']}"))
for t in tasks:
add(down, _task(t))
elif kind == "sop_run":
from ..sop.models import SopRun, SopStepRun
with session() as s:
r = s.get(SopRun, id_)
if r is None:
return {"up": [], "down": []}
trig, parent = r.trigger or "", r.parent_step_run
ids = [id_] + [c.id for c in s.scalars(select(SopRun).where(SopRun.parent_run_id == id_)).all()]
steps = s.scalars(select(SopStepRun).where(SopStepRun.run_id.in_(ids))
.order_by(SopStepRun.started_at)).all()
refs = [(x.action_run_id, x.task_id, x.child_run_id, x.step_type) for x in steps]
if trig.startswith("watch"):
add(up, source(trig))
elif trig == "ask":
add(up, _node("ask", "ask", "提问里确认发起", "", "#/ask"))
if parent:
add(up, _step_run(parent))
for aid, tid, cid, stype in refs:
if aid:
add(down, _action(aid))
if tid:
add(down, _task(tid))
if cid and stype == "subprocess":
add(down, _sop_run(cid))
elif kind == "task":
from ..capability.models import Task
with session() as s:
t = s.get(Task, id_)
if t is None:
return {"up": [], "down": []}
st, sid, obj = t.source_type, t.source_id, t.object_ref
if st == "sop":
add(up, _step_run(sid))
elif st == "watch":
add(up, _watch(sid))
elif st == "action":
add(up, _action(sid))
if obj:
add(up, _object(obj))
except Exception: # noqa: BLE001
log.exception("取来龙去脉失败 %s %s", kind, id_)
return {"up": up, "down": down}
......@@ -19,7 +19,7 @@ from ..jobs.queue import submit_background
from . import autobind
from . import calendar as cal
from . import draft as drafting
from . import (graphlink, linker, metrics, modeling, objects, pipeline, propose, rules, schema,
from . import (graphlink, linker, metrics, modeling, objects, pipeline, rules, schema,
service, templates, traverse, workspaces)
router = APIRouter(prefix="/api/kernel", tags=["kernel"])
......@@ -290,6 +290,39 @@ async def try_concept(cid: str, body: TryIn, actor: identity.Actor = Depends(req
return _try(c, body.args, body.object_key)
@router.post("/concepts/{cid}/tests")
def run_tests(cid: str, body: dict | None = None, _: identity.Actor = Depends(require("view"))):
"""跑函数的测试用例(工作副本)。body.tests 给了就跑这些(编辑器里还没保存的),否则跑已保存的。"""
from . import fntests
c = service.get_concept(cid)
if c["kind"] != "function":
raise HTTPException(422, "只有函数有测试用例")
tests = (body or {}).get("tests")
if (body or {}).get("spec"):
try:
c = {**c, "spec": schema.normalize_spec("function", body["spec"])}
except schema.SpecError as e:
raise HTTPException(422, str(e)) from e
return fntests.run(c, schema._tests(tests) if tests is not None else None)
@router.post("/decision/check")
async def decision_check(body: dict, _: identity.Actor = Depends(require("view"))):
"""决策表体检:缺口、重叠、永远走不到的行。"""
from . import decision
try:
return decision.check(body.get("spec") or body)
except decision.DecisionError as e:
raise HTTPException(422, str(e)) from e
@router.get("/concepts/{cid}/signature")
async def fn_signature(cid: str, _: identity.Actor = Depends(require("view"))):
"""函数的类型化签名:输入(带类型)与输出结构。"""
from . import signature
return signature.signature(service.get_concept(cid))
@router.post("/try")
async def try_spec(body: TryIn, actor: identity.Actor = Depends(require("view"))):
"""试跑还没保存的草稿(一句话生成的结果)。"""
......@@ -301,6 +334,9 @@ async def try_spec(body: TryIn, actor: identity.Actor = Depends(require("view"))
body.args, body.object_key)
from . import fntests as _fntests # noqa: E402,F401 注册「函数用例没过不让发布」的闸门
def _try(c: dict, args: dict, object_key: str) -> dict:
from ..capability import actions, builtins
if c["kind"] == "function":
......@@ -512,12 +548,6 @@ async def metric_compile(body: MetricQueryIn, _: identity.Actor = Depends(requir
calendar_ref=body.calendar, limit=body.limit)
# ---------- 提议 ----------
@router.post("/propose/datasource/{ds_id}")
async def propose_from_datasource(ds_id: int, _: identity.Actor = Depends(require("build"))):
return propose.from_datasource(ds_id)
@router.post("/graph-link")
async def graph_link(_: identity.Actor = Depends(require("build"))):
return graphlink.link_graph(deps.graph())
......@@ -648,10 +678,15 @@ async def dataset(type_ref: str, q: str = "", limit: int = 50, offset: int = 0,
return pipeline.dataset(type_ref, q, limit, offset)
# ---------- 业务建模 ----------
# ---------- AI 建模 ----------
class ModelingPickIn(BaseModel):
item_ids: list[str] = Field(default_factory=list)
sop_ids: list[str] = Field(default_factory=list)
@router.get("/modeling/stages")
async def modeling_stages(_: identity.Actor = Depends(require("view"))):
return {"stages": modeling.STAGES, "templates": templates.list_templates()}
return {"stages": modeling.STAGES}
@router.get("/modeling/runs")
......@@ -660,8 +695,8 @@ async def modeling_runs(_: identity.Actor = Depends(require("view"))):
@router.post("/modeling/runs")
async def create_modeling_run(title: str = Form("业务建模"), doc_ids: str = Form("[]"),
template: str = Form(""), stages: str = Form(""), ds_ids: str = Form(""),
async def create_modeling_run(title: str = Form("AI 建模"), doc_ids: str = Form("[]"),
stages: str = Form(""), ds_ids: str = Form(""),
start: bool = Form(True), files: list[UploadFile] | None = File(None),
_: identity.Actor = Depends(require("build"))):
try:
......@@ -669,30 +704,62 @@ async def create_modeling_run(title: str = Form("业务建模"), doc_ids: str =
st = json.loads(stages) if stages else None
dss = [int(x) for x in json.loads(ds_ids)] if ds_ids else None
except (ValueError, TypeError) as e:
raise HTTPException(422, "doc_ids / stages 应为 JSON 数组") from e
raise HTTPException(422, "doc_ids / stages / ds_ids 应为 JSON 数组") from e
ups = [(f.filename or "upload.txt", await f.read()) for f in files or []]
run = modeling.create(title, doc_ids=ids, files=ups, template=template, stages=st, ds_ids=dss)
run = modeling.create(title, doc_ids=ids, files=ups, stages=st, ds_ids=dss)
return modeling.start(run["id"]) if start else run
@router.get("/modeling/runs/{run_id}")
async def get_modeling_run(run_id: str, _: identity.Actor = Depends(require("view"))):
def get_modeling_run(run_id: str, _: identity.Actor = Depends(require("view"))):
return modeling.get(run_id)
@router.post("/modeling/runs/{run_id}/start")
async def start_modeling_run(run_id: str, _: identity.Actor = Depends(require("build"))):
return modeling.start(run_id)
def start_modeling_run(run_id: str, from_stage: str = "", _: identity.Actor = Depends(require("build"))):
"""开始 / 继续;from_stage 给了就从这一步重跑。"""
return modeling.start(run_id, from_stage)
@router.post("/modeling/runs/{run_id}/stop")
def stop_modeling_run(run_id: str, _: identity.Actor = Depends(require("build"))):
return modeling.control(run_id, "stop")
@router.post("/modeling/runs/{run_id}/cancel")
def cancel_modeling_run(run_id: str, _: identity.Actor = Depends(require("build"))):
return modeling.control(run_id, "cancel")
@router.get("/modeling/runs/{run_id}/calls")
def modeling_calls(run_id: str, stage: str = "", _: identity.Actor = Depends(require("view"))):
return modeling.calls(run_id, stage)
@router.get("/modeling/runs/{run_id}/calls/{call_id}")
def modeling_call(run_id: str, call_id: int, _: identity.Actor = Depends(require("view"))):
return modeling.call_detail(run_id, call_id)
@router.post("/modeling/runs/{run_id}/adopt")
def adopt_modeling(run_id: str, body: ModelingPickIn, _: identity.Actor = Depends(require("build"))):
"""采纳即上线:不建变更提案,也不进审批与待办。"""
return modeling.adopt(run_id, body.item_ids, body.sop_ids)
@router.post("/modeling/runs/{run_id}/discard")
def discard_modeling(run_id: str, body: ModelingPickIn, _: identity.Actor = Depends(require("build"))):
return modeling.discard(run_id, body.item_ids, body.sop_ids)
@router.delete("/modeling/runs/{run_id}")
async def delete_modeling_run(run_id: str, _: identity.Actor = Depends(require("build"))):
def delete_modeling_run(run_id: str, _: identity.Actor = Depends(require("build"))):
modeling.delete(run_id)
return {"ok": True}
@router.get("/modeling/runs/{run_id}/export", response_class=PlainTextResponse)
async def export_modeling_run(run_id: str, _: identity.Actor = Depends(require("view"))):
def export_modeling_run(run_id: str, _: identity.Actor = Depends(require("view"))):
return PlainTextResponse(modeling.export_md(run_id), media_type="text/markdown; charset=utf-8")
......@@ -700,8 +767,8 @@ async def export_modeling_run(run_id: str, _: identity.Actor = Depends(require("
async def object_360(type_ref: str, key: str, _: identity.Actor = Depends(require("view"))):
ot = objects.object_type(type_ref)
obj = objects.get(ot["id"], key)
out: dict[str, Any] = {"object": obj, "object_type": {"id": ot["id"], "name": ot["name"],
"spec": ot.get("spec")}}
out: dict[str, Any] = {"object": obj, "fields": objects.columns(ot),
"object_type": {"id": ot["id"], "name": ot["name"], "spec": ot.get("spec")}}
try:
out["links"] = objects.linked(ot["id"], key)
except HTTPException:
......@@ -722,7 +789,8 @@ async def object_360(type_ref: str, key: str, _: identity.Actor = Depends(requir
elif isinstance(r, Exception):
out["metrics"].append({"metric": {"id": m["id"], "name": m["name"]}, "error": str(r)[:200]})
else:
out["metrics"].append({"metric": r["metric"], "value": r["value"], "period": r["period"], "run_id": r["run_id"]})
out["metrics"].append({"metric": {**r["metric"], "format": (m.get("spec") or {}).get("format") or ""},
"value": r["value"], "period": r["period"], "run_id": r["run_id"]})
# 可以对它发起的动作:动作的「作用于对象」可能存的是 id 也可能是名称(业务建模存名称),统一按 same_ref 比
from ..capability import defs
out["actions"] = [a for a in defs.list_defs("action", "published")
......
......@@ -87,15 +87,72 @@ def relative(ref: str, today: dt.date | None = None) -> dict | None:
return {"period": label, "start": s.isoformat(), "end": e.isoformat()}
GRAINS = {"day": "日", "week": "周", "month": "月", "quarter": "季", "year": "年"}
def _offset(ref: str) -> int | None:
if ref in ("current", ""):
return 0
if ref == "last":
return -1
if ref == "next":
return 1
if ref.startswith("prev:"):
try:
return -int(ref.split(":", 1)[1] or 1)
except ValueError:
return None
return None
def _grain_period(spec: dict, ref: str, today: dt.date) -> dict | None:
"""按日 / 周 / 季 / 年(财年可以不从 1 月开始)切的周期。ref 同 resolve。"""
grain = spec.get("grain")
off = _offset(ref)
anchor = today
if off is None:
if re.fullmatch(r"\d{4}-\d{1,2}-\d{1,2}", ref):
anchor, off = dt.date(*(int(x) for x in ref.split("-"))), 0
elif re.fullmatch(r"\d{4}-\d{1,2}", ref):
y, m = (int(x) for x in ref.split("-"))
anchor, off = dt.date(y, m, 1), 0
else:
return None
if grain == "day":
d = anchor + dt.timedelta(days=off)
return {"period": d.isoformat(), "start": d.isoformat(), "end": d.isoformat()}
if grain == "week":
ws = int(spec.get("week_start") or 1) # 1 = 周一 … 7 = 周日
start = anchor - dt.timedelta(days=(anchor.isoweekday() - ws) % 7) + dt.timedelta(weeks=off)
end = start + dt.timedelta(days=6)
return {"period": f"{start.isoformat()} 起的一周", "start": start.isoformat(), "end": end.isoformat()}
if grain in ("quarter", "year"):
sm = int(spec.get("start_month") or 1) # 财年 / 财季从几月开始
months = 3 if grain == "quarter" else 12
idx = (anchor.year * 12 + anchor.month - 1 - (sm - 1)) // months + off
y, m = divmod(idx * months + (sm - 1), 12)
start = dt.date(y, m + 1, 1)
ey, em = _shift(y, m + 1, months - 1)
end = _day(ey, em, "last")
label = (f"{y}年第{(m - (sm - 1)) % 12 // 3 + 1}季" if grain == "quarter" else
(f"{y}年" if sm == 1 else f"{y}财年({sm}月起)"))
return {"period": label, "start": start.isoformat(), "end": end.isoformat()}
return None
def resolve(spec: dict | None, ref: str = "current", today: dt.date | None = None) -> dict:
"""ref: current / last / prev:N / next / YYYY-MM / YYYY-MM-DD(该日所在期),
以及与周期无关的相对时间(见 relative)。"""
以及与周期无关的相对时间(见 relative)。spec.grain 是 day / week / quarter / year 时按那个粒度切。"""
today = today or dt.date.today()
spec = spec or NATURAL_MONTH
ref = (ref or "current").strip()
rel = relative(ref, today)
if rel:
return rel
if spec.get("grain") in ("day", "week", "quarter", "year"):
got = _grain_period(spec, ref, today)
if got:
return got
if re.fullmatch(r"\d{4}-\d{1,2}", ref):
y, m = (int(x) for x in ref.split("-"))
elif re.fullmatch(r"\d{4}-\d{1,2}-\d{1,2}", ref):
......
......@@ -24,7 +24,8 @@ from typing import Any
from . import rules
HIT_POLICIES = ("first", "collect")
HIT_POLICIES = {"first": "第一条命中的", "unique": "只能命中一条(多条命中算错)", "priority": "命中的里取优先级最高的",
"collect": "全部命中的(列表)"}
_OPS = ("<=", ">=", "!=", "==", "<", ">", "≥", "≤", "≠")
_VAR = re.compile(r"^[A-Za-z_一-鿿][\w一-鿿]*$")
_RANGE = re.compile(r"^\s*\[?\s*(-?[\d.]+)\s*(?:,|\.\.|~)\s*(-?[\d.]+)\s*\]?\s*$")
......@@ -99,7 +100,7 @@ def normalize(spec: dict) -> dict:
if not n or n in oseen:
continue
oseen.add(n)
outputs.append({"name": n, "label": str(o.get("label") or n)})
outputs.append({"name": n, "label": str(o.get("label") or n), "type": str(o.get("type") or "string")})
if not inputs:
raise DecisionError("决策表至少要有一个输入列")
if not outputs:
......@@ -121,7 +122,13 @@ def normalize(spec: dict) -> dict:
rules.parse(v[1:])
except rules.RuleError as e:
raise DecisionError(f"第 {idx} 行输出「{k}」的表达式有误:{e}") from e
rows.append({"when": when, "then": then, "note": str(r.get("note") or "")})
row = {"when": when, "then": then, "note": str(r.get("note") or "")}
if r.get("priority") not in (None, ""):
try:
row["priority"] = float(r["priority"])
except (TypeError, ValueError) as e:
raise DecisionError(f"第 {idx} 行的优先级要填数字") from e
rows.append(row)
policy = str(spec.get("hit_policy") or "first")
if policy not in HIT_POLICIES:
policy = "first"
......@@ -130,6 +137,83 @@ def normalize(spec: dict) -> dict:
"default": default, "text": str(spec.get("text") or "")}
def _row_ok(row: dict, env: dict) -> bool:
for k, cell in (row.get("when") or {}).items():
expr = cell_expr(k, cell)
if not expr:
continue
try:
if not rules.evaluate(expr, env):
return False
except rules.RuleError:
return False
return True
def _samples(spec: dict) -> list[dict]:
"""检查用的样本点:每个输入取条件里出现的边界值、边界两侧、出现过的取值,外加一个「别的值」,做笛卡尔积(有上限)。"""
import itertools
per: dict[str, list] = {}
for i in spec.get("inputs") or []:
n = i["name"]
vals: set = set()
for row in spec.get("rows") or []:
cell = (row.get("when") or {}).get(n)
if cell in (None, "", "-", "*", "任意"):
continue
s = str(cell)
for x in re.findall(r"-?\d+(?:\.\d+)?", s):
f = float(x)
vals.update({f, f - 0.5, f + 0.5})
for x in re.findall(r"'([^']*)'|\"([^\"]*)\"", s):
vals.add(x[0] or x[1])
if not re.search(r"[<>=!\[\]~]|\.\.|\bin\b", s) and not _is_number(s.strip()):
vals.add(s.strip().strip("'\""))
if not vals:
vals = {0.0}
if i.get("type") != "number" or any(isinstance(v, str) for v in vals):
vals.add("(别的值)")
per[n] = sorted(vals, key=lambda v: (isinstance(v, str), v))[:12]
names = list(per)
out = []
for combo in itertools.product(*(per[n] for n in names)):
out.append(dict(zip(names, combo)))
if len(out) >= 3000:
break
return out
def check(spec: dict) -> dict:
"""决策表体检:哪些取值组合一行都不命中(缺口)、哪些同时命中多行(重叠,对「第一条 / 唯一」策略要注意)、
哪些行永远轮不到(被前面的行完全挡住)。按样本点检查,给出例子,不保证穷尽。"""
spec = normalize(spec)
gaps, overlaps = [], []
hit_rows: set[int] = set()
first_rows: set[int] = set()
for env in _samples(spec):
hits = [i for i, r in enumerate(spec["rows"], 1) if _row_ok(r, env)]
hit_rows.update(hits)
if hits:
first_rows.add(hits[0])
if not hits and not spec.get("default") and len(gaps) < 5:
gaps.append(env)
if len(hits) > 1 and len(overlaps) < 5:
overlaps.append({"inputs": env, "rows": hits})
shadowed = [i for i in range(1, len(spec["rows"]) + 1) if i in hit_rows and i not in first_rows] \
if spec["hit_policy"] == "first" else []
never = [i for i in range(1, len(spec["rows"]) + 1) if i not in hit_rows]
issues = []
if gaps:
issues.append(f"有 {len(gaps)} 组以上取值一行都不命中,又没有默认值")
if overlaps and spec["hit_policy"] in ("first", "unique"):
issues.append("有取值同时命中多行" + ("(「唯一」策略下这会报错)" if spec["hit_policy"] == "unique" else ",只会取第一条"))
if shadowed:
issues.append(f"第 {'、'.join(map(str, shadowed))} 行被前面的行挡住了,永远走不到")
if never:
issues.append(f"第 {'、'.join(map(str, never))} 行在检查的取值里没有命中过,看看条件是不是写错了")
return {"ok": not issues, "issues": issues, "gaps": gaps, "overlaps": overlaps, "shadowed": shadowed, "never": never}
def _output(v: Any, env: dict) -> Any:
if isinstance(v, str) and v.startswith("="):
return rules.evaluate(v[1:], env)
......@@ -143,26 +227,22 @@ def evaluate(spec: dict, values: dict) -> dict:
matched: list[int] = []
results: list[dict] = []
trace = []
policy = spec.get("hit_policy", "first")
for idx, row in enumerate(spec.get("rows") or [], 1):
ok = True
for k, cell in (row.get("when") or {}).items():
expr = cell_expr(k, cell)
if not expr:
continue
try:
if not rules.evaluate(expr, env):
ok = False
break
except rules.RuleError:
ok = False
break
ok = _row_ok(row, env)
trace.append({"row": idx, "ok": ok})
if ok:
matched.append(idx)
results.append({k: _output(v, env) for k, v in (row.get("then") or {}).items()})
if spec.get("hit_policy", "first") == "first":
if policy == "first":
break
if spec.get("hit_policy") == "collect":
if policy == "unique" and len(matched) > 1:
raise DecisionError(f"按「唯一命中」策略只能命中一行,但第 {'、'.join(map(str, matched))} 行都命中了")
if policy == "priority" and len(matched) > 1:
rows = spec.get("rows") or []
best = max(range(len(matched)), key=lambda j: float(rows[matched[j] - 1].get("priority") or 0))
matched, results = [matched[best]], [results[best]]
if policy == "collect":
result: Any = results or ([dict(spec.get("default") or {})] if spec.get("default") else [])
else:
result = results[0] if results else dict(spec.get("default") or {})
......
......@@ -89,13 +89,26 @@ samples.input 是 {"ref":"current|last|YYYY-MM"}。""",
samples 留空数组。""",
"action": """类别:动作(审批方式按动作上的策略:人工审批 / 自动执行 / 满足条件时自动)。spec = {
"target_type":"作用的对象名或空",
"params":[{"name":"英文参数名","label":"中文","type":"string|text|number|boolean|enum","required":true,"enum":[]}],
"criteria":[{"expression":"前置条件表达式,可用参数名与 obj.属性","message":"不满足时的提示"}],
"effects":[{"tool":"系统效果名","args":{...}}],
"approval":{"mode":"manual","approver_roles":["业务角色名"]},"reversible":true}
效果只能从下面的系统效果里选,args 按其参数填写;引用参数写 "$参数名",引用对象写 "$obj_key"、"$obj.属性"、"$obj.label"。
以 "=" 开头的值是表达式,可做计算,如 "=qty * obj.unit_price";内置 "$today"(今天)、"$now_id"(时间戳编号,新单号写 "PO$now_id")。
object.write 改已有对象的属性(会自动开放写回);新建单据(采购单、工单等)用 object.create,values 写全主键和必填属性。
"params":[{"name":"英文参数名","label":"中文","type":"string|text|number|integer|boolean|enum|object","required":true,
"enum":[],"description":"告诉填的人这一项怎么填","default":"默认值(可省)","object_type":"type=object 时填对象名"}],
"lookups":[{"name":"英文名","label":"中文叫法","object_type":"对象名",
"where":[{"property":"它的属性","op":"eq","value":"$obj.某属性 或 $参数 或 $this_month"}]}],
"criteria":[{"label":"校验什么","expression":"必须满足的条件","message":"不满足时的提示,可以带 $obj.属性 显示实际的数"}],
"effects":[{"tool":"系统效果名","label":"这一步叫什么","args":{...},"when":"只在这个条件成立时才做(可省)"}],
"on_reject":[{"tool":"object.write","args":{...}}],
"approval":{"mode":"manual|auto|conditional",
"stages":[{"name":"环节名","approver_roles":["业务角色名"],"skip_when":"什么情况下这一段不用批(可省)"}]},
"reversible":true}
- lookups:校验或执行时还要用到的其他对象(如「这个客户本月的额度」),按条件查出一个;之后用 英文名.属性 引用,英文名.key 是它的主键。
规则里提到别的对象上的限制(额度、配额、上级库存)时,必须先用 lookups 把它找出来再校验。
- criteria:业务规则里「不满足就不许做」的条件都写成校验,一条规则一条;表达式里可用参数名、obj.属性、lookups 的英文名.属性。
- effects 只能从下面的系统效果里选。引用参数写 "$参数名",引用对象写 "$obj_key"、"$obj.属性";
以 "=" 开头的值是公式,如 "=qty * obj.unit_price";内置 "$today"、"$this_month"(YYYY-MM)、"$now_id"(不重复的编号,新单号写 "PO$now_id")。
object.write 改一个对象的属性:args = {"object_type","key","property","op":"set|add|sub","value"},
op=add / sub 是在当前值上加减(如在途数量 + 订货量),key 可以是 "$obj_key" 或 "$英文名.key";
新建单据用 object.create,values 写全主键和必填属性。一个业务动作要改几处就写几个 effect。
- on_reject:被驳回时要做的事,可以用 "$reject_reason"(如把驳回原因写回单据)。
- approval.stages:先后要过几个人就写几段,一段批完才到下一段;eff.amount 是这一单的金额。不需要审批的写 mode=auto、不写 stages。
【系统效果】
{tools}
【业务角色】{roles}
......
......@@ -127,7 +127,7 @@ def scope_sql(ds_id: int, sql: str, dialect: str = "mysql") -> str:
for tid, t in _tables_by_type(ds_id).items():
if tid not in scope:
continue
conds = _scope_where(t["concept"], t["ref"])
conds = [c.replace("t.`", "`", 1) for c in _scope_where(t["concept"], t["ref"])]
if conds:
restricted[t["table"].lower()] = conds
if not restricted:
......
......@@ -137,7 +137,12 @@ def _aggregate(c: dict, rep: _Report) -> None:
for dim, ot in (ref.get("dimension_types") or {}).items():
if _ref(ot, "object_type") is None:
rep.error(c, "bad_ref", f"维度「{dim}」对应的对象「{ot}」不存在或还没发布")
if not rep.columns(c, b, ref.get("base_table") or "", cols):
if ref.get("base_object"):
# 建在对象上的指标:对象在就行,列由对象自己的绑定保证
if _ref(ref["base_object"], "object_type") is None:
rep.error(c, "bad_ref", f"统计的对象「{ref['base_object']}」不存在或还没发布")
return
elif not rep.columns(c, b, ref.get("base_table") or "", cols):
return
from . import metrics
from ..text2sql import executor, semantic
......
......@@ -55,11 +55,27 @@ def compile_sql(m: dict, *, dimensions: list[str] | None = None, filters: dict |
if b is None:
raise HTTPException(422, f"指标「{m['name']}」还没有绑定取数表达式")
ref = b["ref"]
dim_map: dict[str, str] = ref.get("dimensions") or {}
dim_map: dict[str, str] = dict(ref.get("dimensions") or {})
ds_id = b["ds_id"]
source = ident(ref["base_table"]) if ref.get("base_table") else ""
base_ot = None
if ref.get("base_object"):
# 指标建在对象上:把对象(含算出来的属性)当成一张表来聚合,对象的每个属性都能当维度
from . import objects
base_ot = service.rt_find(ref["base_object"], "object_type")
if base_ot is None:
raise HTTPException(422, f"指标「{m['name']}」统计的对象「{ref['base_object']}」还没有发布")
ds_id, sub = objects.source_sql(base_ot)
source = f"{sub} AS t"
tcols = (objects.table_binding(base_ot)["ref"].get("columns") or {})
for p in (base_ot.get("spec") or {}).get("properties") or []:
dim_map.setdefault(p["name"], p["name"] if p.get("expression") else tcols.get(p["name"], p["name"]))
if not source:
raise HTTPException(422, f"指标「{m['name']}」还没有选统计哪张表或哪个对象")
# 维度就是对象的属性:属性的显示名也能用来拆分(「按大区」→ 属性「区域」显示名「大区」)
alias: dict[str, str] = {}
ot = service.rt_get((m.get("spec") or {}).get("object_type") or "") or {}
ot = base_ot or service.rt_find((m.get("spec") or {}).get("object_type") or "", "object_type") or {}
for p in (ot.get("spec") or {}).get("properties") or []:
if p.get("display_name"):
alias[p["display_name"]] = p["name"]
......@@ -99,8 +115,8 @@ def compile_sql(m: dict, *, dimensions: list[str] | None = None, filters: dict |
tc = ident(ref["time_column"])
where.append(f"{tc} >= {lit(period['start'])} AND {tc} < "
f"DATE_ADD({lit(period['end'])}, INTERVAL 1 DAY)")
# 数据范围:对象键列 / 同名维度上的限制
ot_id = (m.get("spec") or {}).get("object_type")
# 数据范围:对象键列 / 同名维度上的限制(建在对象上的指标,范围已经在对象那一层过滤了)
ot_id = ot.get("id") if ot and not base_ot else None
scope = (identity.current().scope or {}).get(ot_id) if ot_id else None
for prop, vals in (scope or {}).items():
col = dim_map.get(prop)
......@@ -110,24 +126,35 @@ def compile_sql(m: dict, *, dimensions: list[str] | None = None, filters: dict |
col = ref["object_key_column"]
if col and vals:
where.append(f"{ident(col)} IN ({', '.join(lit(v) for v in vals)})")
sql = f"SELECT {', '.join(select_parts)} FROM {ident(ref['base_table'])}"
sql = f"SELECT {', '.join(select_parts)} FROM {source}"
if where:
sql += " WHERE " + " AND ".join(f"({w})" for w in where)
direction = "ASC" if order == "asc" else "DESC"
cap = int(max(1, min(limit, 5000)))
named: dict[str, str] = {} # 维度 → 名称列的列名(SQL 里已经带出来的)
types: dict[str, dict] = {} # 维度 → 它是哪类对象
dim_types: dict[str, dict] = {}
if base_ot:
from . import objects
b_ref = objects.table_binding(base_ot)["ref"]
c2p = {v: k for k, v in (b_ref.get("columns") or {}).items()}
for par in objects.parents(base_ot):
prop = c2p.get(par["my_col"], par["my_col"])
dim_types[prop] = par["other"]
dim_types.setdefault(prop_label(base_ot, prop), par["other"])
unnamed: dict[str, str] = {} # 维度 → 对象类型名(是对象,但名称要查完再补)
if dims:
sql += " GROUP BY " + ", ".join(ident(dim_col(d)) for d in dims)
joins, outer = [], []
for i, d in enumerate(dims):
outer.append(f"m.{ident(d)}")
ot_d = dim_object_type(ref, d)
ot_d = dim_types.get(d) or dim_object_type(ref, d)
if not ot_d:
continue
types[d] = {"type_id": ot_d["id"], "type_name": ot_d["name"]}
tb = service.rt_binding(ot_d, "table") or {}
tref = tb.get("ref") or {}
if tb.get("ds_id") == b["ds_id"] and tref.get("label_column") and tref.get("key_column"):
if tb.get("ds_id") == ds_id and tref.get("label_column") and tref.get("key_column"):
# 维度本身是对象(仓库、商品):同一个数据源里直接关联对象表带出名称,
# 「查看 SQL」拿去重跑能得到一模一样的结果
named[d] = f"{d}名称"
......@@ -142,8 +169,43 @@ def compile_sql(m: dict, *, dimensions: list[str] | None = None, filters: dict |
else:
sql += f" ORDER BY `value` {direction}"
sql += f" LIMIT {cap}"
return {"sql": sql, "ds_id": b["ds_id"], "period": period, "dimensions": dims,
"named": named, "unnamed": unnamed}
return {"sql": sql, "ds_id": ds_id, "period": period, "dimensions": dims,
"named": named, "unnamed": unnamed, "types": types}
def prop_label(ot: dict, prop: str) -> str:
for p in (ot.get("spec") or {}).get("properties") or []:
if p["name"] == prop:
return p.get("display_name") or prop
return prop
def value_label(m: dict) -> str:
unit = (m.get("spec") or {}).get("unit") or ""
name = m.get("display_name") or m["name"]
return f"{name}({unit})" if unit and unit not in name else name
def col_meta(m: dict, compiled: dict, columns: list[str]) -> list[dict]:
"""结果的每一列怎么显示:数值列叫指标的名字;对象维度的编号列和名称列合成一列。"""
ot = service.rt_find((m.get("spec") or {}).get("object_type") or "", "object_type") or {}
spec = m.get("spec") or {}
out = []
for c in columns:
if c == "value":
out.append({"name": c, "label": value_label(m), "role": "value", "unit": spec.get("unit") or "",
"format": spec.get("format") or ""})
continue
base = c[:-2] if c.endswith("名称") and c[:-2] in compiled["dimensions"] else ""
if base:
out.append({"name": c, "label": prop_label(ot, base) if ot else base, "role": "name", "of": base})
continue
meta = {"name": c, "label": prop_label(ot, c) if ot else c, "role": "dim"}
if c in (compiled.get("types") or {}):
meta.update(compiled["types"][c])
meta["name_col"] = f"{c}名称" if f"{c}名称" in columns else ""
out.append(meta)
return out
def dim_object_type(ref: dict, dim: str) -> dict | None:
......@@ -212,8 +274,8 @@ def query(ref: str | dict, *, dimensions: list[str] | None = None, filters: dict
return {"metric": {"id": m["id"], "name": m["name"], "unit": (m.get("spec") or {}).get("unit", ""),
"direction": (m.get("spec") or {}).get("direction", "neutral")},
"sql": out.guard.sql or compiled["sql"], "run_id": run_id,
"columns": columns, "rows": rows,
"value": value, "period": compiled["period"], "calibre": calibre, "notes": notes,
"columns": columns, "rows": rows, "col_meta": col_meta(m, compiled, columns),
"value_label": value_label(m), "value": value, "period": compiled["period"], "calibre": calibre, "notes": notes,
"truncated": bool(out.result and out.result.truncated)}
......
......@@ -47,9 +47,13 @@ def evaluate(fn: dict, inputs: dict) -> dict:
secret = defs.endpoint_secret(ep["id"])
headers = {"Content-Type": "application/json", **(jload(secret, {}) if secret else {})}
try:
# request_path:输入放在请求体的哪个字段下(如 inputs / data.features);空 = 整个请求体就是输入
body: dict = dict(args)
for part in reversed([p for p in str(spec.get("request_path", "inputs") or "").split(".") if p]):
body = {part: body}
resp = requests.request(ep["spec"].get("method", "POST"), ep["spec"]["url"],
json={"inputs": args}, headers=headers,
timeout=float(ep["spec"].get("timeout") or 15))
json=body, headers=headers,
timeout=float(spec.get("timeout") or ep["spec"].get("timeout") or 15))
except requests.RequestException as e:
raise HTTPException(502, f"模型端点调用失败:{str(e)[:200]}") from e
if resp.status_code >= 400:
......@@ -61,7 +65,8 @@ def evaluate(fn: dict, inputs: dict) -> dict:
data = _pick(body, spec.get("result_path") or "") if spec.get("result_path") else body
outs = spec.get("outputs") or []
if outs and isinstance(data, dict):
result = {o["name"]: data.get(o["name"]) for o in outs}
# 每个输出可以单独写取值路径(path),不写就按输出名取
result = {o["name"]: _pick(data, o.get("path") or o["name"]) for o in outs}
else:
result = data
return {"result": result, "inputs": args, "endpoint": ep["name"],
......
......@@ -167,9 +167,32 @@ class ModelRun(Base):
options_json: Mapped[str] = mapped_column(Text, default="{}")
stages_json: Mapped[str] = mapped_column(_LONGTEXT, default="[]")
counts_json: Mapped[str] = mapped_column(Text, default="{}")
status: Mapped[str] = mapped_column(String(16), default="draft", index=True) # draft/running/done/failed
# draft / running / stopped(暂停,可继续)/ cancelled(终止)/ done / failed
status: Mapped[str] = mapped_column(String(16), default="draft", index=True)
job_id: Mapped[int] = mapped_column(Integer, default=0)
error: Mapped[str] = mapped_column(Text, default="")
created_by: Mapped[str] = mapped_column(String(128), default="")
created_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now)
updated_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now, onupdate=now)
class ModelCall(Base):
"""建模流水线里的一次 AI 调用:哪个环节、花了多久、想了什么、答了什么。点开流水线节点看的就是这些。"""
__tablename__ = "otlg_model_call"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
run_id: Mapped[str] = mapped_column(String(64), index=True)
stage: Mapped[str] = mapped_column(String(24), default="")
feature: Mapped[str] = mapped_column(String(48), default="")
label: Mapped[str] = mapped_column(String(255), default="")
model: Mapped[str] = mapped_column(String(128), default="")
status: Mapped[str] = mapped_column(String(16), default="running") # running / done / failed / cancelled
started_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now)
duration_ms: Mapped[int] = mapped_column(Integer, default=0)
prompt_tokens: Mapped[int] = mapped_column(Integer, default=0)
output_tokens: Mapped[int] = mapped_column(Integer, default=0)
reasoning_tokens: Mapped[int] = mapped_column(Integer, default=0)
cached: Mapped[int] = mapped_column(Integer, default=0)
error: Mapped[str] = mapped_column(Text, default="")
prompt: Mapped[str] = mapped_column(_LONGTEXT, default="")
reasoning: Mapped[str] = mapped_column(_LONGTEXT, default="")
output: Mapped[str] = mapped_column(_LONGTEXT, default="")
......@@ -47,6 +47,9 @@ DATA_TYPES = ("string", "number", "integer", "boolean", "date", "datetime", "enu
RULE_KINDS = ("judgement", "calibre", "calculation")
DIRECTIONS = ("higher_better", "lower_better", "neutral")
CARDINALITY = ("1:1", "1:n", "n:1", "n:n")
# 属性怎么显示:金额 / 数量 / 百分比 / 状态(带颜色的标签);空 = 按数据类型的默认样子
FORMATS = ("", "money", "quantity", "percent", "status")
TONES = ("ok", "warn", "danger", "info", "neutral")
_IDENT = re.compile(r"^[A-Za-z_一-鿿][\w一-鿿$]*$")
......@@ -125,12 +128,25 @@ def _object_type(spec: dict) -> dict:
dt = _str(p.get("data_type"), "string") or "string"
if dt not in DATA_TYPES:
dt = "string"
fmt = _str(p.get("format"))
expr = _str(p.get("expression"))
if expr:
from . import rules
try:
rules.parse(expr)
except rules.RuleError as e:
raise SpecError(f"属性「{name}」的计算公式有误:{e}") from e
tones = {str(k): str(v) for k, v in (p.get("tones") or {}).items()
if str(v) in TONES} if isinstance(p.get("tones"), dict) else {}
props.append({"name": name, "display_name": _str(p.get("display_name")),
"data_type": dt, "description": _str(p.get("description")),
"is_key": bool(p.get("is_key")), "is_time": bool(p.get("is_time")),
"is_dimension": bool(p.get("is_dimension")),
"is_writable": bool(p.get("is_writable")),
"enum_values": _list_str(p.get("enum_values"))})
# 算出来的属性没有对应的列,不能被动作改
"is_writable": bool(p.get("is_writable")) and not expr,
"enum_values": _list_str(p.get("enum_values")),
"format": fmt if fmt in FORMATS else "", "unit": _str(p.get("unit"))[:16],
"expression": expr, "tones": tones})
keys = [p["name"] for p in props if p["is_key"]]
if len(keys) > 1:
raise SpecError("对象只能有一个主键属性")
......@@ -138,7 +154,7 @@ def _object_type(spec: dict) -> dict:
if label and props and label not in seen:
raise SpecError(f"显示属性 {label} 不在属性列表中")
return {"properties": props, "key_property": keys[0] if keys else "",
"label_property": label}
"label_property": label, "title_template": _str(spec.get("title_template"))[:200]}
_CARD_ALIAS = {"many_to_one": "n:1", "one_to_many": "1:n", "one_to_one": "1:1", "many_to_many": "n:n",
......@@ -159,10 +175,17 @@ def _fn_aggregate(spec: dict) -> dict:
direction = _str(spec.get("direction"), "neutral") or "neutral"
if direction not in DIRECTIONS:
direction = "neutral"
fmt = _str(spec.get("format"))
from .signature import norm_inputs
compare = _str(spec.get("compare"))
return {"unit": _str(spec.get("unit")), "direction": direction,
"format": fmt if fmt in FORMATS else "",
"calibre_rule": _str(spec.get("calibre_rule")), "calendar": _str(spec.get("calendar")),
"dimensions": _list_str(spec.get("dimensions")),
"formula_text": _str(spec.get("formula_text"))}
"formula_text": _str(spec.get("formula_text")),
# 参数化筛选:每个输入绑定到一个维度,调用时给值就按它过滤(如 某维度 = 输入的值)
"inputs": [i for i in norm_inputs(spec.get("inputs"), "string") if i.get("dimension")],
"compare": compare if compare in ("mom", "yoy") else ""}
def _fn_rule(spec: dict) -> dict:
......@@ -181,7 +204,13 @@ def _fn_rule(spec: dict) -> dict:
for n in names:
if n not in params:
params.append(n)
return {"rule_kind": kind, "expression": expr, "params": params,
from .signature import norm_inputs
typed = {i["name"]: i for i in norm_inputs(spec.get("inputs"), "any")}
inputs = [typed.get(n) or {"name": n, "label": n, "type": "any", "required": True, "description": ""} for n in params]
out_type = _str(spec.get("output_type"))
return {"rule_kind": kind, "expression": expr, "params": params, "inputs": inputs,
"output_type": out_type if out_type in ("boolean", "number", "string", "date", "any") else "",
"message": _str(spec.get("message")),
"text": _str(spec.get("text")), "examples": list(spec.get("examples") or [])}
......@@ -204,7 +233,11 @@ def _fn_calendar(spec: dict) -> dict:
return int(v or 0)
except (TypeError, ValueError):
return 0
return {"start_day": _day(spec.get("start_day"), 1),
grain = _str(spec.get("grain"), "month") or "month"
return {"grain": grain if grain in ("day", "week", "month", "quarter", "year") else "month",
"week_start": max(1, min(7, _off(spec.get("week_start")) or 1)),
"start_month": max(1, min(12, _off(spec.get("start_month")) or 1)),
"start_day": _day(spec.get("start_day"), 1),
"start_month_offset": _off(spec.get("start_month_offset")),
"end_day": _day(spec.get("end_day"), "last"),
"end_month_offset": _off(spec.get("end_month_offset")),
......@@ -238,12 +271,20 @@ def _fn_ml(spec: dict) -> dict:
x = {"name": x}
if not isinstance(x, dict) or not _str(x.get("name")):
continue
out.append({"name": check_ident(x["name"], what), "label": _str(x.get("label")),
"type": _str(x.get("type"), "number") or "number"})
item = {"name": check_ident(x["name"], what), "label": _str(x.get("label")),
"type": _str(x.get("type"), "number") or "number"}
if _str(x.get("path")):
item["path"] = _str(x.get("path"))
out.append(item)
return out
try:
timeout = max(1.0, min(float(spec.get("timeout") or 15), 120.0))
except (TypeError, ValueError):
timeout = 15.0
return {"endpoint": _str(spec.get("endpoint")), "inputs": fields(spec.get("inputs"), "输入名"),
"outputs": fields(spec.get("outputs"), "输出名"),
"result_path": _str(spec.get("result_path")), "text": _str(spec.get("text"))}
"request_path": _str(spec.get("request_path"), "inputs") if spec.get("request_path") is not None else "inputs",
"result_path": _str(spec.get("result_path")), "timeout": timeout, "text": _str(spec.get("text"))}
_FN = {"aggregate": _fn_aggregate, "rule": _fn_rule, "calendar": _fn_calendar,
......@@ -255,7 +296,20 @@ def _function(spec: dict) -> dict:
cat = LEGACY_FN.get(cat, cat)
if cat not in FN_CATEGORIES:
raise SpecError(f"函数类别只能是 {'/'.join(FN_CATEGORIES)}")
return {"category": cat, "object_type": _str(spec.get("object_type")), **_FN[cat](spec)}
return {"category": cat, "object_type": _str(spec.get("object_type")), **_FN[cat](spec),
"tests": _tests(spec.get("tests"))}
def _tests(v: Any) -> list[dict]:
"""函数的测试用例:给定输入,期望输出里某些字段等于某个值(expect 的键是输出里的路径,如 result / result.level)。"""
out = []
for i, t in enumerate(v or [], 1):
if not isinstance(t, dict):
continue
expect = t.get("expect") if isinstance(t.get("expect"), dict) else {}
out.append({"name": _str(t.get("name")) or f"用例 {i}", "inputs": dict(t.get("inputs") or {}),
"expect": {str(k): x for k, x in expect.items() if str(k).strip()}})
return out[:50]
def _action(spec: dict) -> dict:
......@@ -305,7 +359,11 @@ def normalize_binding(kind: str, ref: dict) -> dict:
raise SpecError("指标表达式不能为空")
if ";" in expr:
raise SpecError("指标表达式不能包含分号")
return {"base_table": check_ident(ref.get("base_table", ""), "基表"),
base_object = _str(ref.get("base_object"))
if not base_object and not _str(ref.get("base_table")):
raise SpecError("指标要选统计哪个对象(或哪张表)")
return {"base_table": check_ident(ref.get("base_table", ""), "基表") if _str(ref.get("base_table")) else "",
"base_object": base_object,
"expression": expr,
"time_column": (check_ident(ref["time_column"], "时间列")
if ref.get("time_column") else ""),
......
......@@ -396,6 +396,7 @@ def update_concept(cid: str, **fields: Any) -> dict:
c.dirty = 1
if c.status == "deprecated" and fields.get("restore"):
c.status = "draft"
_settle(s, c)
s.commit()
after = get_concept(cid)
audit.record("concept.update", "concept", cid, f"修改{after['kind_label']}「{after['name']}」",
......@@ -463,9 +464,28 @@ def _touch(cid: str) -> None:
if c is not None:
c.dirty = 1
c.version += 1
_settle(s, c)
s.commit()
def _settle(s, c: Concept) -> None:
"""保存后内容其实和线上一样(打开看了一眼点了保存、或改完又改回去):不算「有未发布的修改」。
以前这种情况会一直挂着「有未发布的修改」,而发布页又说没有可发布的变更,流程卡还因此发布不了。"""
if c.status != "published" or not c.published_json:
return
s.flush()
prev = jload(c.published_json, {})
cur = _publish_copy(s, c)
def binds(d: dict) -> list:
return sorted(([b.get("ds_id"), b.get("target_kind"), b.get("ref")] for b in d.get("bindings") or []),
key=lambda x: jdump(x))
same = all(jdump(_cmp(prev.get(f), f)) == jdump(_cmp(cur.get(f), f))
for f in ("name", "display_name", "description", "synonyms", "spec"))
if same and jdump(binds(prev)) == jdump(binds(cur)):
c.dirty = 0
# ---------------- 绑定 ----------------
def list_bindings(cid: str) -> list[dict]:
with session() as s:
......
......@@ -36,7 +36,7 @@ def _kpis() -> list[dict]:
ot = service.rt_get(sp.get("object_type") or "") or {}
label = {p["name"]: p.get("display_name") or p["name"] for p in (ot.get("spec") or {}).get("properties") or []}
dims = [label.get(d, d) for d in dims] # 维度用业务叫法(仓库编号),取数时按显示名也认
out.append({"name": m["name"], "value": v, "unit": sp.get("unit") or "",
out.append({"name": m["name"], "value": v, "unit": sp.get("unit") or "", "format": sp.get("format") or "",
"direction": sp.get("direction") or "neutral", "formula": sp.get("formula_text") or "",
"dimensions": dims, "run_id": r.get("run_id")})
return out
......@@ -47,12 +47,18 @@ def _questions(kpis: list[dict]) -> list[str]:
qs = []
for k in kpis[:3]:
qs.append(f"{k['name']}按{k['dimensions'][0]}拆开看是多少?" if k["dimensions"] else f"现在的{k['name']}是多少?")
for a in service.rt_by_kind("action")[:2]:
qs.append(f"哪些情况需要{a.get('display_name') or a['name']}?帮我发起")
objs = service.rt_by_kind("object_type")
if len(objs) >= 2:
qs.append(f"某个{objs[0]['name']}出问题会影响哪些对象?")
return qs[:6]
return qs[:4]
def _alerts() -> list[dict]:
"""正在发生的预警(最多 6 条),工作台上直接看到。"""
try:
from ..watch import engine as watch_engine
return [{"id": a["id"], "watch": a["watch"], "watch_id": a["watch_id"], "label": a["label"],
"first_seen_at": a["first_seen_at"]} for a in watch_engine.alerts("firing", limit=6)]
except Exception: # noqa: BLE001
log.debug("读取预警失败", exc_info=True)
return []
def _merge_questions(pinned: list[str], generated: list[str]) -> list[str]:
......@@ -83,8 +89,10 @@ def workbench() -> dict:
pinned, habits = [], []
def brief(r: dict) -> dict:
pv = r.get("preview") or {}
return {"id": r["id"], "action_name": r["action_name"], "priority": r["priority"], "status": r["status"],
"summary": (r.get("preview") or {}).get("summary") or r.get("reason") or "",
"summary": pv.get("target_label") or pv.get("summary") or r.get("reason") or "",
"submitted_name": r.get("submitted_name") or "",
"created_at": r["created_at"], "initiator_id": r["initiator_id"]}
return {"user": {"id": actor.id, "name": actor.name, "roles": actor.roles, "biz_roles": actor.biz_roles,
"can_run": actor.can("operate")},
......@@ -96,6 +104,6 @@ def workbench() -> dict:
"role": t.get("role")} for t in my_tasks]},
"mine": [brief(r) for r in mine], "sops": sops,
"questions": _merge_questions(pinned, _questions(kpis)),
"pinned": pinned, "habits": habits,
"pinned": pinned, "habits": habits, "alerts": _alerts(),
"feed": [{"ts": x.get("ts"), "actor": x.get("actor_name") or x.get("actor_id"),
"summary": x.get("summary")} for x in feed]}
......@@ -80,6 +80,9 @@ def create(ws_id: str, display_name: str, description: str = "", industry: str =
with session() as s:
if s.get(Workspace, ws_id) is not None:
raise HTTPException(409, f"本体空间「{ws_id}」已存在")
name = (display_name or ws_id).strip()
if any((w.display_name or w.id) == name for w in s.scalars(select(Workspace)).all()):
raise HTTPException(409, f"已经有一个叫「{name}」的本体空间了,换个名字")
s.add(Workspace(id=ws_id, display_name=(display_name or ws_id)[:255],
description=description or "", industry=industry or "",
created_by=actor.id))
......@@ -162,11 +165,16 @@ def overview() -> dict:
if need:
steps.append({"key": "members", "title": f"给审批角色指派人员({'、'.join(need)})",
"hint": "动作要这些角色审批,现在没人担任,审批单会没人能批"})
from . import modeling
drafts = modeling.pending_count() if actor.can("build") else 0
if drafts:
steps.append({"key": "modeling", "title": f"决定 AI 建模草案({drafts} 条待定)",
"hint": "在 AI 建模页逐条查看,采纳即上线"})
if pending_reviews:
steps.append({"key": "modeling", "title": f"审核 AI 草案({pending_reviews} 条)",
"hint": "采纳后进入草稿,再走变更提案"})
steps.append({"key": "inbox", "title": f"处理审核队列({pending_reviews} 条)",
"hint": "别处提交给你审核的变更与草案"})
return {"workspace": get(ws), "counts": c,
"mapped": {"object_total": c["object_type"], "object_unmapped": len(unmapped)},
"revision": st["revision"], "dirty": st["dirty"], "datasources": len(dss),
"pipelines": pipe_info, "pending_approvals": actions.count_pending(actor),
"pending_reviews": pending_reviews, "next_steps": steps[:5]}
"pending_reviews": pending_reviews, "modeling_drafts": drafts, "next_steps": steps[:5]}
......@@ -24,7 +24,7 @@ from .memory import api as memory_api
from .agents import api as ask_api
from .sop import api as sop_api
from .watch import api as watch_api, scheduler as watch_scheduler
from .core import db, envs
from .core import db, envs, reqcache
from .core.config import get_settings
from .ingest.parse import ParseError
......@@ -74,15 +74,21 @@ async def request_context(request: Request, call_next):
# 演示版本:请求头 X-Onto-Env(直链可用 ?env=)决定这次请求读写哪个库,不认识的一律回开发环境
env_tok = envs.set_current(envs.resolve(
request.headers.get("x-onto-env", "") or request.query_params.get("env", "")))
cache_tok = reqcache.begin()
try:
response = await call_next(request)
except Exception:
log.exception("[%s] %s %s 未捕获异常", rid, request.method, request.url.path)
raise
finally:
reqcache.end(cache_tok)
envs.reset(env_tok)
cost = int((time.time() - started) * 1000)
response.headers["X-Request-Id"] = rid
# 页面本身不许缓存:重新构建后浏览器必须拿到新的 index.html,才会加载新的前端包
# (带 hash 的 /assets 照常缓存)。否则旧页面会拿旧前端去调新接口。
if response.headers.get("content-type", "").startswith("text/html"):
response.headers["Cache-Control"] = "no-cache"
if not request.url.path.startswith(("/assets", "/favicon")):
log.info("[%s] %s %s -> %s %dms", rid, request.method, request.url.path,
response.status_code, cost)
......
......@@ -19,8 +19,9 @@ class CaseIn(BaseModel):
class FactIn(BaseModel):
text: str = ""
kind: str = "fact"
kind: str = "" # 空 = 不改(只改状态时别把类型冲成 fact);新增时空按 fact 处理
scope: str = ""
scope_ref: str | None = None # 取数提示:适用的数据源 id,空 = 全部数据源
status: str | None = None
......@@ -64,13 +65,14 @@ async def add_fact(body: FactIn, actor: identity.Actor = Depends(require("ask"))
# 组织口径只有搭建者能直接写;其他人写的都是个人偏好
scope = body.scope if actor.can("build") else "user"
kind = body.kind if actor.can("build") else "preference"
return service.add_fact(body.text.strip(), kind, scope=scope, source="manual")
scope_ref = (body.scope_ref or "") if kind == "sql_hint" else ""
return service.add_fact(body.text.strip(), kind, scope=scope, scope_ref=scope_ref, source="manual")
@router.put("/facts/{fact_id}")
async def update_fact(fact_id: str, body: FactIn, _: identity.Actor = Depends(require("build"))):
return service.update_fact(fact_id, text=body.text or None, status=body.status, kind=body.kind,
scope=body.scope or None)
scope=body.scope or None, scope_ref=body.scope_ref)
@router.delete("/facts/{fact_id}")
......
......@@ -244,16 +244,35 @@ def facts_text(mem: dict) -> str:
or "(无)"
def sql_hints_text(limit: int = 12) -> str:
def sql_hints(ds_id: int | None = None, limit: int = 20) -> list[dict]:
"""「取数提示」:建模的人写给问数用的约定(哪张表才是准的、某个状态码是什么意思、默认排除什么)。
只要生效就每次都带上 —— 它是写 SQL 的规矩,不是靠相似度碰运气的记忆。"""
只要生效就每次都带上 —— 它是写 SQL 的规矩,不是靠相似度碰运气的记忆。
scope_ref 为空 = 对所有数据源生效;填了数据源 id = 只对那个数据源生效。"""
if not enabled():
return ""
return []
refs = ["", str(ds_id)] if ds_id else [""]
with session() as s:
rows = s.scalars(select(MemFact).where(
MemFact.workspace == _ws(), MemFact.status == "active", MemFact.kind == "sql_hint",
MemFact.scope == "workspace").order_by(MemFact.created_at).limit(limit)).all()
return "\n".join(f"- {f.text}" for f in rows)
MemFact.scope == "workspace", MemFact.scope_ref.in_(refs))
.order_by(MemFact.created_at).limit(limit)).all()
# 每带进一次就记一次命中:知识库里「用过 N 次」靠它
for f in rows:
f.hits = (f.hits or 0) + 1
out = [{"id": f.id, "text": f.text, "ds_id": int(f.scope_ref) if f.scope_ref else 0} for f in rows]
s.commit()
return out
def drop_sql_hints_of(ds_id: int) -> int:
"""数据源删了,只对它生效的取数提示也一起删掉,别留着孤儿规则。"""
with session() as s:
rows = s.scalars(select(MemFact).where(
MemFact.workspace == _ws(), MemFact.kind == "sql_hint", MemFact.scope_ref == str(ds_id))).all()
for f in rows:
s.delete(f)
s.commit()
return len(rows)
def preferences_text() -> str:
......@@ -480,7 +499,7 @@ def add_fact(text: str, kind: str = "fact", *, scope: str = "", scope_ref: str =
if kind == "sql_hint":
if not actor.can("build"):
raise HTTPException(403, "取数提示会影响所有人的问数结果,只有建模的人可以写")
scope = "workspace"
scope = "workspace" # scope_ref = 适用的数据源 id,空 = 全部数据源
if not scope:
scope = "user" if kind == "preference" else "workspace"
if scope == "user" and not scope_ref:
......@@ -505,7 +524,7 @@ def add_fact(text: str, kind: str = "fact", *, scope: str = "", scope_ref: str =
def update_fact(fact_id: str, *, text: str | None = None, status: str | None = None, kind: str | None = None,
scope: str | None = None, _review: bool = False) -> dict:
scope: str | None = None, scope_ref: str | None = None, _review: bool = False) -> dict:
actor = identity.current()
with session() as s:
f = s.get(MemFact, fact_id)
......@@ -522,6 +541,8 @@ def update_fact(fact_id: str, *, text: str | None = None, status: str | None = N
f.kind = kind
if scope in ("workspace", "user", "role"):
f.scope = scope
if scope_ref is not None and f.kind == "sql_hint":
f.scope_ref = scope_ref
s.commit()
out = _fact_dict(f)
if _review and out["status"] == "pending":
......
from __future__ import annotations
from typing import Literal
from typing import Any, Literal
from pydantic import BaseModel, Field
......@@ -91,11 +91,6 @@ class ColumnUpdate(BaseModel):
enabled: bool | None = None
class EnableModelsRequest(BaseModel):
ids: list[int]
enabled: bool = True
class RelationUpsert(BaseModel):
id: int | None = None
from_model_id: int
......@@ -109,6 +104,57 @@ class RelationUpsert(BaseModel):
enabled: bool = True
class ProbeRequest(BaseModel):
"""新建 / 编辑数据源时「测试连接」:不落库,只连一下、列出表。编辑时口令留空就用已存的(带 ds_id)。"""
ds_id: int = 0
ds_type: Literal["mysql", "postgres"] = "mysql"
host: str = Field(min_length=1, max_length=255)
port: int = Field(default=3306, ge=1, le=65535)
db_name: str = Field(min_length=1, max_length=128)
username: str = Field(min_length=1, max_length=128)
password: str = ""
extra: dict = Field(default_factory=dict)
class AskRequest(BaseModel):
ds_id: int
question: str = Field(min_length=1, max_length=4000)
history: list[dict[str, str]] = Field(default_factory=list)
overrides: dict[str, Any] = Field(default_factory=dict)
thread_id: str = ""
scope: Literal["ask", "debug"] = "ask" # debug = 数据连接里的调试台,可查「表与字段」启用的表
class ExplainRequest(BaseModel):
"""按需解释一条 SQL。折叠着的东西不值得占用问答链路的时间。"""
ds_id: int
question: str = ""
sql: str = Field(min_length=1, max_length=200000)
class SummarizeRequest(BaseModel):
"""重跑手改 SQL 之后补一份结论用。行数不大,直接把结果回传,服务端不重查。"""
ds_id: int
question: str = Field(min_length=1, max_length=4000)
columns: list[str] = Field(default_factory=list)
rows: list[list[Any]] = Field(default_factory=list)
row_count: int = 0
run_id: int = 0 # 调试台会话里的那一轮:结论写回它的回放快照
class ThreadUpsert(BaseModel):
ds_id: int = 0
title: str = Field(default="", max_length=200)
class PairUpsert(BaseModel):
ds_id: int | None = None
question: str | None = None
sql: str | None = None
note: str | None = None
status: Literal["draft", "verified", "deprecated"] | None = None
class RunSqlRequest(BaseModel):
ds_id: int = 0
run_id: int = 0 # 在某次取数的基础上改:数据源、原问题、原 SQL 都从那条记录里取
......@@ -116,6 +162,8 @@ class RunSqlRequest(BaseModel):
question: str = ""
thread_id: str = ""
origin_sql: str = "" # 模型原本生成的 SQL,用户改过才填,用来做 diff 学习
scope: Literal["ask", "debug"] = "ask"
replaces: int = 0 # 调试台会话里「改 SQL 重跑」:替换掉哪一轮(取数记录 id)
class DescribeRequest(BaseModel):
......
......@@ -6,7 +6,7 @@ from pydantic import BaseModel, Field
from ..core import identity
from ..core.identity import require
from . import draft, engine, recipes, service, spec as sop_spec, tree as sop_tree
from . import cond as sop_cond, draft, engine, recipes, service, spec as sop_spec, types as sop_types
router = APIRouter(prefix="/api/sop", tags=["sop"])
......@@ -14,8 +14,7 @@ router = APIRouter(prefix="/api/sop", tags=["sop"])
class DefIn(BaseModel):
title: str | None = None
description: str | None = None
tree: dict | None = None # 步骤树(编辑器保存的就是它)
spec: dict | None = None # 已经是图的定义(脚本 / 导入用)
spec: dict | None = None # 流程定义(画布上编辑的就是它)
process_concept_id: str | None = None
owner_role: str | None = None
etag: str = "" # 打开时拿到的 draft_hash;别处改过就拒绝保存
......@@ -42,7 +41,7 @@ async def list_defs(q: str = "", status: str = "", _: identity.Actor = Depends(r
@router.post("/defs")
async def create_def(body: DefIn, _: identity.Actor = Depends(require("build"))):
return service.create(body.title or "", body.description or "", body.spec,
body.process_concept_id or "", body.owner_role or "", tree=body.tree)
body.process_concept_id or "", body.owner_role or "")
@router.post("/defs/draft")
......@@ -53,10 +52,61 @@ def ai_draft(body: DraftIn, _: identity.Actor = Depends(require("build"))):
@router.get("/meta")
async def meta(_: identity.Actor = Depends(require("view"))):
"""编辑器要的静态信息:步骤种类与「+」菜单分组、条件的比较方式、表单字段类型。"""
return {"kinds": sop_tree.KINDS, "groups": sop_tree.GROUPS, "ops": sop_tree.OPS,
"""编辑器要的静态信息:节点种类与面板分组、条件 / 查询的比较方式、表单字段类型、公式里能用的函数。"""
from ..kernel import objects, rules
return {"types": sop_spec.STEP_TYPES, "groups": sop_spec.GROUPS, "ops": sop_cond.OPS,
"query_ops": objects.QUERY_OPS, "write_ops": objects.WRITE_OPS, "agg_fns": objects.AGG_FNS,
"field_types": list(sop_spec.FIELD_TYPES), "param_types": list(sop_spec.PARAM_TYPES),
"foreach_limit": sop_spec.FOREACH_LIMIT}
"value_types": list(sop_spec.VALUE_TYPES), "error_modes": sop_spec.ERROR_MODES,
"foreach_limit": sop_spec.FOREACH_LIMIT, "functions": sorted(rules.FUNCS),
"list_functions": FUNCTION_HELP}
# 公式编辑器里的函数提示(补全 + 说明)
FUNCTION_HELP = [
{"name": "count", "sig": "count(列表)", "desc": "有几条"},
{"name": "sum_by", "sig": "sum_by(列表, '字段')", "desc": "某个字段求和"},
{"name": "avg_by", "sig": "avg_by(列表, '字段')", "desc": "某个字段的平均值"},
{"name": "max_by", "sig": "max_by(列表, '字段')", "desc": "某个字段的最大值"},
{"name": "min_by", "sig": "min_by(列表, '字段')", "desc": "某个字段的最小值"},
{"name": "where", "sig": "where(列表, '字段', '>', 值)", "desc": "只留下满足条件的行(比较:== != > >= < <= in contains empty not_empty)"},
{"name": "pluck", "sig": "pluck(列表, '字段')", "desc": "取出每一行的某个字段,得到一个列表"},
{"name": "first", "sig": "first(列表)", "desc": "第一条"},
{"name": "last", "sig": "last(列表)", "desc": "最后一条"},
{"name": "sort_by", "sig": "sort_by(列表, '字段', True)", "desc": "按字段排序,第三个参数 True 表示从大到小"},
{"name": "unique", "sig": "unique(列表, '字段')", "desc": "某个字段去重后的取值"},
{"name": "group_sum", "sig": "group_sum(列表, '分组字段', '求和字段')", "desc": "分组求和,得到 [{key, value}]"},
{"name": "pick", "sig": "pick(列表, '字段1', '字段2')", "desc": "每一行只留下这几个字段"},
{"name": "merge", "sig": "merge(对象1, 对象2)", "desc": "合并成一个对象"},
{"name": "join", "sig": "join(列表, ',')", "desc": "拼成一段文字"},
{"name": "any_of", "sig": "any_of(列表, '字段')", "desc": "有没有一行这个字段为真"},
{"name": "all_of", "sig": "all_of(列表, '字段')", "desc": "是不是每一行这个字段都为真"},
{"name": "coalesce", "sig": "coalesce(a, b)", "desc": "第一个不为空的值"},
{"name": "round", "sig": "round(数, 2)", "desc": "四舍五入"},
{"name": "days_between", "sig": "days_between(开始, 结束)", "desc": "相差几天"},
{"name": "add_days", "sig": "add_days(日期, 天数)", "desc": "几天后的日期"},
{"name": "today", "sig": "today()", "desc": "今天"},
{"name": "contains", "sig": "contains(文字或列表, 值)", "desc": "是否包含"},
{"name": "safe_div", "sig": "safe_div(a, b, 默认值)", "desc": "除法,除数为 0 时给默认值"},
]
@router.get("/links")
async def links(object_type: str, _: identity.Actor = Depends(require("view"))):
"""查数据节点「带出关联对象」用:这类对象能沿哪些关系走到哪些对象(含草稿),对方有哪些字段。"""
from ..kernel import objects
from ..kernel import service as ksvc
with ksvc.draft_runtime():
ot = ksvc.rt_find(object_type, "object_type")
if ot is None:
return []
out = []
for side in objects.link_sides(ot):
other = side["other"]
out.append({"link": side["link"], "label": side["label"], "direction": side["direction"],
"single": side["single"], "object_type": other["name"],
"fields": sop_types.object_fields(other["name"])})
return out
@router.get("/defs/{def_id}")
......@@ -68,7 +118,7 @@ async def get_def(def_id: str, _: identity.Actor = Depends(require("view"))):
async def update_def(def_id: str, body: DefIn, _: identity.Actor = Depends(require("build"))):
return service.update(def_id, title=body.title, description=body.description, spec=body.spec,
process_concept_id=body.process_concept_id, owner_role=body.owner_role,
tree=body.tree, etag=body.etag)
etag=body.etag)
@router.post("/defs/{def_id}/archive")
......@@ -88,17 +138,12 @@ async def unarchive(def_id: str, _: identity.Actor = Depends(require("build"))):
@router.post("/validate")
def validate(body: dict, _: identity.Actor = Depends(require("view"))):
"""校验一份还没保存的定义:给 tree 就先编译,返回编译后的图、问题清单和「每一步产出什么」。"""
if body.get("tree") is not None:
try:
norm = sop_tree.compile_tree(body["tree"])
except sop_tree.TreeError as e:
return {"spec": None, "errors": [str(e)], "warnings": [], "draft_refs": [],
"issues": [{"level": "error", "step_id": "", "message": str(e)}], "outputs": []}
return {"spec": norm, **sop_spec.validate(norm, def_id=str(body.get("def_id") or "")),
"outputs": sop_tree.outputs(body["tree"])}
norm = sop_spec.normalize(body.get("spec") or body)
return {"spec": norm, **sop_spec.validate(norm)}
"""校验一份还没保存的定义:返回规整后的图、问题清单和「每一步产出什么」(带类型的输出结构)。"""
from ..kernel import service as ksvc
norm = sop_spec.normalize(body.get("spec") or {})
with ksvc.draft_runtime():
outputs = sop_types.outputs(norm)
return {"spec": norm, **sop_spec.validate(norm, def_id=str(body.get("def_id") or "")), "outputs": outputs}
@router.post("/defs/{def_id}/dry-run")
......@@ -112,8 +157,16 @@ def dry_run(def_id: str, body: RunIn, _: identity.Actor = Depends(require("build
@router.post("/defs/{def_id}/steps/{step_id}/try")
def try_step(def_id: str, step_id: str, body: dict | None = None,
_: identity.Actor = Depends(require("build"))):
"""单步试跑:只跑这一个步骤,上游数据可以手填模拟值。动作类只出预览。"""
return engine.try_step(def_id, step_id, (body or {}).get("env") or {})
"""单步试跑:只跑这一个步骤,上游数据可以手填模拟值。改数据的只出预览。
body.step:编辑器里还没保存的这一步。"""
return engine.try_step(def_id, step_id, (body or {}).get("env") or {}, (body or {}).get("step"))
@router.post("/defs/{def_id}/steps/{step_id}/save-as-action")
def save_as_action(def_id: str, step_id: str, body: dict | None = None,
_: identity.Actor = Depends(require("build"))):
"""把一个写数据步骤另存为本体里的动作(草稿),别的流程、提问、监控就都能复用它。"""
return engine.save_write_as_action(def_id, step_id, (body or {}).get("name") or "", (body or {}).get("step"))
@router.post("/defs/{def_id}/submit")
......@@ -171,12 +224,17 @@ async def list_runs(def_id: str = "", status: str = "", mode: str = "", limit: i
return engine.list_runs(def_id, status, mode, limit, started_by=started_by)
@router.get("/runs-page")
async def list_runs_page(def_id: str = "", status: str = "", trigger: str = "", q: str = "", days: int = 0,
limit: int = 30, offset: int = 0, _: identity.Actor = Depends(require("view"))):
return engine.list_runs_page(def_id, status, trigger, q, days, limit, offset)
@router.get("/runs/{run_id}")
async def get_run(run_id: str, _: identity.Actor = Depends(require("view"))):
"""运行详情:带上逐条处理各行的运行、定义的步骤树(详情页按同样的形状画时间线),
以及每个在等人的步骤「当前这个人能不能直接办」。"""
run = engine.get_run(run_id, rows=True)
run["tree"], _err = sop_tree.load(run["spec"])
engine.annotate_waiting(run, identity.current())
return run
......
......@@ -20,32 +20,47 @@ from . import spec as sop_spec
log = logging.getLogger(__name__)
DRAFT_SYSTEM = """你是流程设计专家,要把业务文档里描述的流程写成一份**可执行的 SOP**(JSON)。
DRAFT_SYSTEM = """你是流程设计专家,要把业务文档里描述的流程写成一份**可执行的流程卡**(JSON)。
SOP 结构:
结构:
{
"title": "流程名", "description": "一句话说明",
"params": [{"name":"英文变量名","label":"中文名","type":"string|number|date|object|period","object_type":"对象类型名(type=object时)","calendar":"统计周期名(type=period时)","required":true}],
"roles": ["参与角色"],
"params": [{"name":"英文变量名","label":"中文名","type":"string|number|date|object|period|list","object_type":"对象类型名(type=object时)",
"columns":[{"name":"英文","label":"中文","type":"string|number"}](type=list 明细行时),"required":true}],
"start": "第一步id",
"steps": [ 步骤... ],
"evidence": ["出处片段编号"]
}
步骤类型(type)与字段,每步都有 id(英文)、title(中文)、description、lane(执行角色):
- function:调用只读函数取数/求值。{"function":"函数名","args":{...},"output":"变量名","next":"下一步id"}
- skill:调用 AI 技能分析。{"skill":"技能名","inputs":{...},"output":"变量名","next":"..."}
- decision:判断分支。{"branches":[{"when":"表达式,如 rate.value < 0.8","next":"...","label":"是"}],"default":"..."}
- human_task:派给人做的事。{"role":"角色","instructions":"要做什么","form":[{"name":"英文","label":"中文","type":"text","required":true}],"checklist":["..."],"sla_hours":24,"output":"变量名","next":"..."}
- action:提议一个需要审批的业务动作。{"action":"动作名","params":{...},"object_key":"$obj.key","on_reject":"驳回时去哪","next":"批准后去哪"}
- foreach:逐行处理 —— 对前面取数结果的每一行各提议一次动作(每条缺货各提一张补货单)。
{"items":"$前一步输出变量","action":"动作名","params":{"qty":"$item.建议补货量"},"object_key":"$item.编号","limit":20,"output":"变量名","next":"..."}
params / object_key 里用 $item.列名 引用当前行
- end:结束。{"outcome":"结果说明"}
引用变量用 "$变量名.字段"(在 args/inputs/params 里);decision 的 when 里直接写变量名。
每一步都有 id(英文)、type、title(中文)、description、next(下一步 id)、output(结果变量名,默认就是 id)。步骤类型:
- query 查数据:{"object_type":"对象名","mode":"one|list","where":{"mode":"all","items":[{"left":"属性名","op":"eq","right":"$工单号"}]},
"include":[{"link":"关系名或对方对象名","as":"放在哪个字段","mode":"list|one","where":{...},"aggs":[{"fn":"count|sum","field":"属性","as":"名字"}]}],
"limit":50}。mode=one 时结果就是那个对象($变量.属性、$变量.found);list 时是 {items:[...], total}。
op 可用:eq ne gt ge lt le contains in empty not_empty。一次就能把主对象和关联对象(明细、关联单据)都查回来。
- function 调用函数:{"function":"metric.query","args":{"metric":"指标名","dimensions":[...]}} 取指标;
{"function":"function.eval","args":{"name":"规则 / 决策表 / 周期函数名","args":{"输入名":"$变量.字段"}}} 调本体函数。
- compute 计算:{"assign":[{"name":"英文","label":"中文","type":"number|string|boolean|list","expr":"表达式"}]}
表达式可用:sum_by(列表,'字段') count(列表) where(列表,'字段','>',值) pluck(列表,'字段') first(列表) 及 + - * / 比较、and/or。
- decision 条件:{"branches":[{"label":"情况名","when":"表达式,如 count(q.items) > 0 and calc.total < 5000","next":"..."}],"default":"..."}
- foreach 循环:{"items":"$前一步.items","when":"只处理满足条件的行(表达式,item.列名)","limit":50,
"body":{"start":"循环体第一步","steps":[循环体里的步骤,最后一步 type=end]}},循环体里用 $item.列名 引用当前行。
- write 写数据(同一事务,要审批):{"ops":[
{"op":"create","object_type":"对象名","as":"po","values":{"属性":"$变量.字段","单号":"=('PO' + now_id)"}},
{"op":"create_rows","object_type":"明细对象名","rows":"$明细数据","values":{"所属单号":"$ops.po.key","数量":"$row.数量"}},
{"op":"update","object_type":"对象名","key":"$item.key","values":{"状态":"处理中"}}],
"approval":{"mode":"manual|auto|conditional","approver_roles":["角色"],"auto_when":"表达式"}}
$ops.<as>.key 引用同一次写入里前面新建出来的主键;$row.列 是按行新建时的这一行;$now_id 是不重复编号。
- action 执行动作:{"action":"动作名","params":{...},"object_key":"$obj.key","on_reject":"驳回时去哪"}
- skill AI 分析:{"instruction":"让 AI 判断什么","inputs":{"数据名":"$变量"},"outputs":[{"name":"level","label":"等级","type":"string","options":["高","中","低"]}]}
- human_task 人工任务:{"role":"角色","instructions":"要做什么,可嵌 $变量.字段","form":[{"name":"英文","label":"中文","type":"text|number|boolean|choice|date","options":[],"required":true}],"sla_hours":24}
- notify 通知:{"role":"角色","subject":"标题","body":"内容"}
- end 结束:{"outcome":"结果说明","outputs":[{"name":"英文","label":"中文","value":"$变量.字段"}]}
引用变量用 "$变量名.字段"、"$变量.items[0].字段";when / expr 表达式里直接写变量名(不加 $)。
规则:
1. 只能使用下面列出的函数、技能、动作;没有合适动作时,用 human_task 让人去做,不要编造动作。
2. 流程必须能从第一个步骤走到 end,不能有循环;每个 decision 必须有 default。
3. 取数优先用 metric.query(写指标名,结果确定可复现),规则判断用 rule.eval(写规则名),分档查表用 decision.eval(写决策表名)。
4. 只输出 JSON。
1. 只能使用下面列出的对象、关系、函数、动作;写数据只能写列出的对象和属性,不要编造。没有合适的就用 human_task 让人去做。
2. 流程必须能从第一步走到 end,不能有环(要重复用 foreach);每个 decision 必须有 default。
3. 查数据优先用 query(一次带出关联对象),取统计数用 metric.query;判断写成 decision;新建 / 修改业务数据用 write。
4. 一张流程卡只管一件事,步骤控制在 15 步以内;description 一句话写清即可,不要复述原文。
5. 只输出 JSON。
"""
DRAFT_USER = """要生成的流程:{topic}
......@@ -62,9 +77,11 @@ DRAFT_USER = """要生成的流程:{topic}
【本体】
角色:{roles}
指标:{metrics}
规则:{rules}
统计周期:{calendars}
对象类型:{object_types}
规则 / 决策表 / 周期:{rules};{decisions};{calendars}
对象类型(属性):
{object_types}
关系:
{links}
【文档依据】
{evidence}
......@@ -86,10 +103,23 @@ def _catalog(extra: dict | None = None) -> dict:
return "、".join(c["name"] for c in ksvc.list_concepts(kind=kind, limit=300)
if not category or c.get("category") == category) or "(无)"
from ..governance import roles
def objects_text() -> str:
lines = []
for c in ksvc.list_full("object_type", limit=200):
props = [f"{p['name']}{'(可改)' if p.get('is_writable') else ''}" for p in (c.get("spec") or {}).get("properties") or []]
lines.append(f"- {c['name']}:{'、'.join(props[:30])}")
return "\n".join(lines) or "(无)"
def links_text() -> str:
return "\n".join(f"- {c['name']}:{(c.get('spec') or {}).get('from_type')} → {(c.get('spec') or {}).get('to_type')}"
f"({(c.get('spec') or {}).get('cardinality')})"
for c in ksvc.list_full("link_type", limit=300)) or "(无)"
out = {"functions": fns, "skills": sk, "actions": ac,
"roles": "、".join(roles.names()) or "(无)",
"metrics": names("function", "aggregate"), "rules": names("function", "rule"),
"calendars": names("function", "calendar"), "object_types": names("object_type")}
"decisions": names("function", "decision"),
"calendars": names("function", "calendar"), "object_types": objects_text(), "links": links_text()}
for k, v in (extra or {}).items():
if v:
base = "" if out.get(k) in ("(无)", "", None) else out[k]
......@@ -133,7 +163,8 @@ def generate(topic: str, process_concept_id: str = "", chunks: list[dict] | None
{"role": "user", "content": "校验发现以下错误,请修正后重新输出完整 JSON:\n- "
+ "\n- ".join(v["errors"][:12])}]
try:
raw2 = llm.chat_json(messages, temperature=0.1)
with llmlog.feature("sop_draft_fix"): # 只是照着校验错误改,不用再长考
raw2 = llm.chat_json(messages, temperature=0.1)
spec2 = sop_spec.normalize(raw2 if isinstance(raw2, dict) else {})
if len(sop_spec.validate(spec2)["errors"]) < len(v["errors"]):
raw, spec = raw2, spec2
......
......@@ -89,7 +89,7 @@ def build(recipe_id: str, fields: dict) -> dict:
"args": {"metric": metric, **({"dimensions": dims} if dims else {})},
"output": "data", "next": "check", "lane": "系统"},
{"id": "check", "type": "decision", "title": "有没有要处理的行",
"branches": [{"when": "len(data.rows) > 0", "next": "each", "label": "有"}],
"branches": [{"when": "count(data.items) > 0", "next": "each", "label": "有"}],
"default": "none"},
{"id": "each", "type": "foreach", "title": f"逐行{act['display_name'] or act['name']}",
"items": "$data", "action": act["name"], "params": _map_params(act, cols, "item"),
......@@ -136,11 +136,11 @@ def build(recipe_id: str, fields: dict) -> dict:
"spec": {"params": [], "start": "fetch", "steps": [
{"id": "fetch", "type": "function", "title": f"取{metric}", "function": "metric.query",
"args": {"metric": metric}, "output": "m", "next": "grade", "lane": "系统"},
{"id": "grade", "type": "function", "title": f"按{table}分级", "function": "decision.eval",
"args": {"table": table, "inputs": {first: "$m.value"}}, "output": "level",
{"id": "grade", "type": "function", "title": f"按{table}分级", "function": "function.eval",
"args": {"name": table, "args": {first: "$m.value"}}, "output": "level",
"next": "gate", "lane": "系统"},
{"id": "gate", "type": "decision", "title": "要不要处理",
"branches": [{"when": "level.matched", "next": "handle", "label": "命中分级"}],
"branches": [{"when": "level.hit", "next": "handle", "label": "命中分级"}],
"default": "ok"},
{"id": "handle", "type": "human_task", "title": "处理", "role": role,
"instructions": f"「{metric}」当前为 $m.value,分级结果 $level.result,请处理。",
......
"""SOP 定义的管理:草稿编辑、试运行记录、发布(直接发布或进审核队列)、版本。
人编辑的是步骤树(tree.py),保存时编译成引擎执行的图存进 draft_spec_json;读出来时再从图还原成树。
编辑器在画布上直接编辑引擎执行的图(spec.py),存进 draft_spec_json。
发布规则:结构校验通过、引用的本体元素都已发布,就可以发布(没试运行只是提醒)。
管理员、或属于这张流程卡负责角色的实施人员直接发布;其他人提交审核,审核人不能是提交人自己。
......@@ -18,7 +18,6 @@ from ..core import identity
from ..core.dbx import iso, jdump, jload, new_id, now, session
from ..governance import audit, notify, permissions, review
from . import spec as sop_spec
from . import tree as sop_tree
from .models import SopDefinition, SopRun, SopVersion
......@@ -28,15 +27,12 @@ def _hash(spec: dict) -> str:
def _steps(spec: dict) -> list[dict]:
"""图里所有「人看得到的」步骤:含循环体里的,不含编译时补的隐含结束。"""
"""图里所有步骤,含循环体里的。"""
out = []
for st in spec.get("steps") or []:
if st.get("type") == "end" and str(st.get("id") or "").endswith("__end"):
continue
out.append(st)
if st.get("type") == "foreach":
out += [b for b in (st.get("body") or {}).get("steps") or []
if not (b.get("type") == "end" and str(b.get("id") or "").endswith("__end"))]
out += _steps(st.get("body") or {})
return out
......@@ -59,7 +55,6 @@ def _dict(d: SopDefinition, full: bool = True) -> dict:
out["dry_run_ok"] = bool(dr.get("ok") and dr.get("hash") == d.draft_hash)
if full:
out["spec"] = spec
out["tree"], out["tree_error"] = sop_tree.load(spec)
out["validation"] = sop_spec.validate(spec, def_id=d.id)
if not out["dry_run_ok"]:
out["validation"]["warnings"].append(
......@@ -115,24 +110,17 @@ def get(def_id: str) -> dict:
return out
def _compile(tree: dict) -> dict:
try:
return sop_tree.compile_tree(tree)
except sop_tree.TreeError as e:
raise HTTPException(422, str(e)) from e
# 空白流程卡:开始 → 查数据 → 结束,画布上摆好位置
BLANK = {"start": "q1", "ui": {"start": {"x": 0, "y": 0}},
"steps": [{"id": "q1", "type": "query", "title": "查数据", "next": "end", "ui": {"x": 0, "y": 140}},
{"id": "end", "type": "end", "title": "结束", "ui": {"x": 0, "y": 280}}]}
def create(title: str, description: str = "", spec: dict | None = None,
process_concept_id: str = "", owner_role: str = "", ai_generated: bool = False,
tree: dict | None = None) -> dict:
"""tree:步骤树(编辑器、模板);spec:已经是图的(AI 起草、场景配方)。都不给就是一张空白卡。"""
process_concept_id: str = "", owner_role: str = "", ai_generated: bool = False) -> dict:
"""spec 不给就是一张空白卡。"""
actor = identity.current()
if tree is not None:
norm = _compile(tree)
else:
# 空白流程卡从「查指标」开始:选一个指标就能试跑
norm = sop_spec.normalize(spec) if spec else _compile(
{"steps": [{"id": "fetch", "kind": "metric", "title": "查指标"}]})
norm = sop_spec.normalize(spec or BLANK)
with session() as s:
d = SopDefinition(id=new_id("sop"), workspace=actor.workspace,
title=(title or "未命名流程")[:255], description=description or "",
......@@ -143,19 +131,17 @@ def create(title: str, description: str = "", spec: dict | None = None,
s.commit()
did = d.id
out = get(did)
audit.record("sop.create", "sop", did, f"新建 SOP「{out['title']}」"
audit.record("sop.create", "sop", did, f"新建 流程卡「{out['title']}」"
+ ("(AI 起草)" if ai_generated else ""), after={"spec": norm})
return out
def update(def_id: str, *, title: str | None = None, description: str | None = None,
spec: dict | None = None, process_concept_id: str | None = None,
owner_role: str | None = None, tree: dict | None = None, etag: str = "") -> dict:
owner_role: str | None = None, etag: str = "") -> dict:
"""保存草稿。etag 是打开时拿到的 draft_hash:别处(另一个标签页 / 另一个人)已经改过就拒绝,
不让后保存的悄悄盖掉先保存的。编辑不写审计 —— 自动保存每几秒一次,全记下来审计就没法看了;
发布时记一条带前后差异的。"""
if tree is not None:
spec = _compile(tree)
with session() as s:
d = s.get(SopDefinition, def_id)
if d is None or d.workspace != _ws():
......@@ -211,7 +197,7 @@ def archive(def_id: str) -> dict:
d = s.get(SopDefinition, def_id)
d.status = "archived"
s.commit()
audit.record("sop.archive", "sop", def_id, f"归档 SOP「{d0['title']}」")
audit.record("sop.archive", "sop", def_id, f"归档 流程卡「{d0['title']}」")
return get(def_id)
......@@ -224,7 +210,7 @@ def unarchive(def_id: str) -> dict:
d = s.get(SopDefinition, def_id)
d.status = "published" if d.current_version else "draft"
s.commit()
audit.record("sop.unarchive", "sop", def_id, f"恢复 SOP「{d0['title']}」")
audit.record("sop.unarchive", "sop", def_id, f"恢复 流程卡「{d0['title']}」")
return get(def_id)
......@@ -265,10 +251,10 @@ def can_publish_directly(actor: identity.Actor, d: dict) -> bool:
def submit_publish(def_id: str, note: str = "") -> dict:
"""提交发布审核。"""
d = _ready(def_id)
item = review.propose("sop_publish", f"发布 SOP「{d['title']}」第 {d['current_version'] + 1} 版", {
item = review.propose("sop_publish", f"发布 流程卡「{d['title']}」第 {d['current_version'] + 1} 版", {
"def_id": def_id, "hash": d["draft_hash"], "note": note,
"warnings": d["validation"]["warnings"], "dry_run": d["last_dry_run"],
"outline": sop_tree.outline(d["tree"]) if d.get("tree") else [],
"outline": sop_spec.outline(d["spec"]),
"changes": version_changes(d)},
source="user", target_ref=def_id, assignee_role=d["owner_role"] or "builder")
notify.send(f"role:{d['owner_role'] or 'builder'}", f"流程卡「{d['title']}」等你审核发布",
......@@ -285,6 +271,12 @@ def publish(def_id: str, note: str = "") -> dict:
return {"published": None, "review": submit_publish(def_id, note)}
def publish_unreviewed(def_id: str, note: str = "") -> dict:
"""AI 建模里由搭建的人自己采纳的流程卡:不走发布审核,直接上线(结构、引用检查照样要过)。"""
d = _ready(def_id)
return _do_publish(d, note, d["draft_hash"])
def version_changes(d: dict) -> list[dict]:
"""当前草稿相对线上版本改了哪些步骤:[{id, title, change: added|removed|changed}]。"""
if not d["current_version"]:
......@@ -311,7 +303,7 @@ def _do_publish(d: dict, note: str, expect_hash: str) -> dict:
row.current_version = ver
row.status = "published"
s.commit()
audit.record("sop.publish", "sop", d["id"], f"发布 SOP「{d['title']}」第 {ver} 版"
audit.record("sop.publish", "sop", d["id"], f"发布 流程卡「{d['title']}」第 {ver} 版"
+ (f"({note})" if note else ""), after={"changes": changes})
return {"def_id": d["id"], "version": ver}
......@@ -348,8 +340,7 @@ def version_spec(def_id: str, version: int | None = None) -> tuple[str, int, dic
def get_version(def_id: str, version: int) -> dict:
vid, ver, spec = version_spec(def_id, version)
tree, err = sop_tree.load(spec)
return {"id": vid, "version": ver, "spec": spec, "tree": tree, "tree_error": err}
return {"id": vid, "version": ver, "spec": spec}
def resolve_published(ref: str) -> dict | None:
......@@ -381,12 +372,7 @@ def require_published(ref: str) -> dict:
def published_outline(d: dict) -> list[dict]:
"""线上版本的步骤大纲(给人看「发起之后会发生什么」)。"""
_, _, spec = version_spec(d["id"])
tree, _ = sop_tree.load(spec)
if tree:
return [o for o in sop_tree.outline(tree) if o["kind"] != "case"]
return [{"id": st["id"], "title": st["title"], "kind": st["type"],
"kind_label": sop_spec.STEP_TYPES.get(st["type"], st["type"]), "depth": 0}
for st in _steps(spec) if st["type"] != "end"]
return [o for o in sop_spec.outline(spec) if o["kind"] not in ("case", "end")]
def find_published(q: str, limit: int = 5) -> list[dict]:
......
......@@ -78,6 +78,11 @@ class Connector:
def introspect(self) -> Introspection:
raise NotImplementedError
def list_tables(self) -> list[TableInfo]:
"""只列表(名称、类型、注释、行数估计),不读列。新建数据源时给人勾选用,要快。"""
return [TableInfo(name=t.name, kind=t.kind, comment=t.comment, row_count_est=t.row_count_est)
for t in self.introspect().tables]
def sample_values(self, table: str, column: str, limit: int, max_distinct: int) -> tuple[list[str], int]:
"""返回 (取值列表, distinct 总数)。distinct 超过 max_distinct 就认为不是枚举列,返回空列表。"""
raise NotImplementedError
......@@ -93,27 +98,55 @@ class Connector:
def run_sql(self, sql: str, row_limit: int, timeout_ms: int) -> QueryResult:
raise NotImplementedError
def write_row(self, table: str, values: dict[str, Any], key_column: str = "", key: Any = None) -> int:
def transaction(self):
"""一个写事务(SQLAlchemy 连接,退出时提交,出异常回滚)。多张表的写入放进同一个事务:
新建采购单 + 明细行 + 改缺件单,任何一步失败就全部回滚,业务库里不会留下半张单子。"""
engine = getattr(self, "engine", None)
if engine is None:
raise QueryFailed(f"{self.dialect} 数据源不支持写回")
return engine.begin()
def write_row(self, table: str, values: dict[str, Any], key_column: str = "", key: Any = None,
conn: Any = None) -> int:
"""写回业务库:key 为 None 时 INSERT,否则按主键 UPDATE。返回影响行数。
conn:已经开着的事务(transaction()),不给就自己开一个只含这一句的事务。
run_sql 永远只读;只有数据源开启了「写回业务库」、并且是审批通过的动作,才会走到这里
(调用方 kernel/objects 负责校验)。表名、列名走 SQLAlchemy 的标识符转义,值全部参数化。
"""
from sqlalchemy import column, insert, table as sa_table, update
from sqlalchemy import column, table as sa_table, update
if key is None:
return 1 if self.insert_row(table, values, conn=conn) is not False else 0
t = sa_table(table, *[column(c) for c in dict.fromkeys([*values, key_column]) if c])
engine = getattr(self, "engine", None)
if engine is None:
raise QueryFailed(f"{self.dialect} 数据源不支持写回")
with engine.begin() as c:
if key is None:
return c.execute(insert(t).values(**values)).rowcount or 0
if conn is not None:
return conn.execute(update(t).where(t.c[key_column] == key).values(**values)).rowcount or 0
with self.transaction() as c:
return c.execute(update(t).where(t.c[key_column] == key).values(**values)).rowcount or 0
def delete_row(self, table: str, key_column: str, key: Any) -> int:
def insert_row(self, table: str, values: dict[str, Any], key_column: str = "", conn: Any = None) -> Any:
"""INSERT 一行,返回这一行的主键:values 里给了主键就是它,没给(自增)就取数据库生成的。"""
from sqlalchemy import column, insert, table as sa_table
t = sa_table(table, *[column(c) for c in dict.fromkeys([*values, key_column]) if c])
def go(c: Any) -> Any:
if key_column and key_column not in values and self.dialect == "postgres":
return c.execute(insert(t).values(**values).returning(t.c[key_column])).scalar()
res = c.execute(insert(t).values(**values))
if key_column and key_column in values:
return values[key_column]
return getattr(res, "lastrowid", None)
if conn is not None:
return go(conn)
with self.transaction() as c:
return go(c)
def delete_row(self, table: str, key_column: str, key: Any, conn: Any = None) -> int:
"""只用于撤销「在业务库新建」的动作。"""
from sqlalchemy import column, delete, table as sa_table
t = sa_table(table, column(key_column))
with self.engine.begin() as c: # type: ignore[attr-defined]
if conn is not None:
return conn.execute(delete(t).where(t.c[key_column] == key)).rowcount or 0
with self.transaction() as c:
return c.execute(delete(t).where(t.c[key_column] == key)).rowcount or 0
def dispose(self) -> None:
......
......@@ -80,19 +80,31 @@ class MySQLConnector(Connector):
"table_count": int(tables), "account_writable": writable}
# ---------- 内省 ----------
@staticmethod
def _tables(c) -> dict[str, TableInfo]:
tables: dict[str, TableInfo] = {}
for name, ttype, comment, rows in c.execute(sa_text(
"SELECT TABLE_NAME, TABLE_TYPE, TABLE_COMMENT, TABLE_ROWS "
"FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() "
"ORDER BY TABLE_NAME"
)).fetchall():
tables[name] = TableInfo(
name=name,
kind="view" if str(ttype).upper().endswith("VIEW") else "table",
comment=(comment or ""), row_count_est=int(rows or 0))
return tables
def list_tables(self) -> list[TableInfo]:
try:
with self.engine.connect() as c:
return list(self._tables(c).values())
except SQLAlchemyError as e:
raise ConnectionFailed(_clean(e)) from e
def introspect(self) -> Introspection:
try:
with self.engine.connect() as c:
tables: dict[str, TableInfo] = {}
for name, ttype, comment, rows in c.execute(sa_text(
"SELECT TABLE_NAME, TABLE_TYPE, TABLE_COMMENT, TABLE_ROWS "
"FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() "
"ORDER BY TABLE_NAME"
)).fetchall():
tables[name] = TableInfo(
name=name,
kind="view" if str(ttype).upper().endswith("VIEW") else "table",
comment=(comment or ""), row_count_est=int(rows or 0))
tables = self._tables(c)
for (tname, cname, dtype, nullable, comment, default, key) in c.execute(sa_text(
"SELECT TABLE_NAME, COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, "
......
......@@ -71,21 +71,32 @@ class PostgresConnector(Connector):
return {"version": str(version).split(",")[0], "database": str(db), "table_count": int(n),
"account_writable": bool(writable)}
def _tables(self, c) -> dict[str, TableInfo]:
tables: dict[str, TableInfo] = {}
for name, ttype in c.execute(sa_text(
"SELECT table_name, table_type FROM information_schema.tables "
"WHERE table_schema = :s ORDER BY table_name"), {"s": self.schema}).fetchall():
tables[name] = TableInfo(name=name, kind="view" if "VIEW" in str(ttype) else "table")
for name, comment, rows in c.execute(sa_text(
"SELECT c.relname, obj_description(c.oid), c.reltuples::bigint FROM pg_class c "
"JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = :s"),
{"s": self.schema}).fetchall():
if name in tables:
tables[name].comment = comment or ""
tables[name].row_count_est = max(0, int(rows or 0))
return tables
def list_tables(self) -> list[TableInfo]:
try:
with self.engine.connect() as c:
return list(self._tables(c).values())
except SQLAlchemyError as e:
raise ConnectionFailed(_clean(e)) from e
def introspect(self) -> Introspection:
try:
with self.engine.connect() as c:
tables: dict[str, TableInfo] = {}
for name, ttype in c.execute(sa_text(
"SELECT table_name, table_type FROM information_schema.tables "
"WHERE table_schema = :s ORDER BY table_name"), {"s": self.schema}).fetchall():
tables[name] = TableInfo(name=name, kind="view" if "VIEW" in str(ttype) else "table")
for name, comment, rows in c.execute(sa_text(
"SELECT c.relname, obj_description(c.oid), c.reltuples::bigint FROM pg_class c "
"JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = :s"),
{"s": self.schema}).fetchall():
if name in tables:
tables[name].comment = comment or ""
tables[name].row_count_est = max(0, int(rows or 0))
tables = self._tables(c)
for t, col, dtype, nullable, default, comment in c.execute(sa_text(
"SELECT c.table_name, c.column_name, c.data_type, c.is_nullable, c.column_default, "
"col_description((quote_ident(c.table_schema)||'.'||quote_ident(c.table_name))::regclass, "
......
......@@ -39,7 +39,9 @@ def limits() -> tuple[int, int]:
# 校验策略:
# - catalog:确定性编译出来的 SQL(指标、对象读取、数据同步、建模试跑)。表和列对照内省目录,不查关联白名单;
# - ask :模型写的或人手改的 SQL。只能碰本空间已发布绑定覆盖到的表、列和关联,范围为空就拒绝。
POLICIES = ("catalog", "ask")
# - debug :数据连接里的 SQL 调试台(只有建模的人能用)。在 ask 范围之外,再加上「表与字段」里启用的表
# 和登记的关联 —— 本体还没建好时,实施人员也要能先把取数调通。
POLICIES = ("catalog", "ask", "debug")
# ask 策略的范围提供者:(ds_id) -> (表, {表: 列}, JOIN 键)。默认取本体已发布绑定;测试里可以换掉。
scope_provider: Optional[Callable[[int], tuple[set[str], dict[str, set[str]], set[str]]]] = None
......@@ -52,6 +54,32 @@ def ask_scope(ds_id: int) -> tuple[set[str], dict[str, set[str]], set[str]]:
return grounding.ask_scope(ds_id)
def debug_scope(ds_id: int) -> tuple[set[str], dict[str, set[str]], set[str]]:
"""调试台的可查范围 = 本体已发布绑定的范围 ∪ 「表与字段」启用的表(及登记的关联)。"""
tables, columns, joins = ask_scope(ds_id)
tables, columns, joins = set(tables), dict(columns), set(joins)
_, cat_cols = semantic.catalog_context(ds_id, usable_columns_only=True)
deny = semantic.system_tables()
by_id: dict[int, str] = {}
for m in semantic.list_models(ds_id, enabled_only=True):
t = (m["physical_table"] or m["name"]).lower()
if t in deny:
continue
by_id[m["id"]] = t
tables.add(t)
if t in cat_cols:
columns[t] = cat_cols[t]
pairs = [(f"{by_id[r['from_model_id']]}.{r['from_column'].lower()}", f"{by_id[r['to_model_id']]}.{r['to_column'].lower()}")
for r in semantic.list_relations(ds_id, enabled_only=True)
if r["from_model_id"] in by_id and r["to_model_id"] in by_id]
joins |= semantic.conformed_joins(pairs)
return tables, columns, joins
def scope_for(ds_id: int, policy: str = "ask") -> tuple[set[str], dict[str, set[str]], set[str]]:
return debug_scope(ds_id) if policy == "debug" else ask_scope(ds_id)
def validate(ds_id: int, sql: str, dialect: str = "mysql", policy: str = "ask") -> guard.GuardResult:
row_limit, _ = limits()
if policy == "catalog":
......@@ -65,12 +93,10 @@ def validate(ds_id: int, sql: str, dialect: str = "mysql", policy: str = "ask")
row_limit=row_limit)
joins: set[str] = set()
else:
tables, columns, joins = ask_scope(ds_id)
tables, columns, joins = scope_for(ds_id, policy)
if not tables:
return guard.GuardResult(False, (sql or "").strip(), [guard.Issue(
"error", "empty_scope",
"这个数据源在当前本体空间里还没有任何已发布的对象或指标绑定,不能直接写 SQL 查询。",
"先把对象类型绑定到数据表(指标绑定取数表达式)并发布,再来提问。")])
"error", "empty_scope", *EMPTY_SCOPE[policy])])
res = guard.check(
sql, dialect=dialect,
allowed_tables=tables,
......@@ -83,6 +109,13 @@ def validate(ds_id: int, sql: str, dialect: str = "mysql", policy: str = "ask")
return res
EMPTY_SCOPE = {
"ask": ("这个数据源在当前本体空间里还没有任何已发布的对象或指标绑定,不能直接写 SQL 查询。",
"先把对象类型绑定到数据表(指标绑定取数表达式)并发布,再来提问。"),
"debug": ("这个数据源还没有可查的表。", "到「表与字段」勾选要查的表(或在「数据源」里点「选表」),再来调试。"),
}
def _deny_system_tables(res: guard.GuardResult) -> None:
"""任何策略下都不许碰元数据库自己的表(数据源指向元数据库所在的库时才会遇到)。"""
hit = sorted(set(res.tables) & semantic.system_tables())
......
......@@ -18,7 +18,7 @@ import logging
import datetime as dt
from typing import Iterator
from sqlalchemy import select
from sqlalchemy import delete, or_, select
from sqlalchemy.orm import Session
from ..core import db as core_db
......@@ -68,8 +68,8 @@ def run_introspection(ds_id: int, resample: bool = False) -> Iterator[dict]:
yield {"stage": "error", "error": f"读取表结构失败:{str(e)[:400]}"}
return
# 表范围:业务库往往有几百张表,只内省用户圈定的那些(如 otlg_dm_*)。
# 圈定过范围就说明这些表是要用的,直接启用,省掉再去逐张勾选。
# 表范围:业务库往往有几百张表,只内省用户在数据源里勾选的那些。
# 接入范围就是「参与问数」的范围:读进来的表一律启用,不再逐张勾选。
scope = table_scope(semantic.get_datasource(ds_id) or {})
# 数据源指向元数据库所在的库时,系统自己的表(用户、会话、审计…)不当业务表内省
deny = semantic.system_tables()
......@@ -98,15 +98,13 @@ def run_introspection(ds_id: int, resample: bool = False) -> Iterator[dict]:
ds_id=ds_id, name=t.name, physical_table=t.name,
kind=t.kind, description=t.comment or "",
primary_key=",".join(t.primary_key),
row_count_est=t.row_count_est,
# 新表默认不启用:几百张表全打开会把提示词撑爆,
# 也让「启用 = 授权可查」这个语义站不住。让用户显式挑。
enabled=1 if scope else 0)
row_count_est=t.row_count_est, enabled=1)
s.add(m)
stats["new_models"] += 1
else:
# 只覆盖物理事实,描述这类人工内容保持不动
m.kind = t.kind
m.enabled = 1
m.row_count_est = t.row_count_est
m.primary_key = ",".join(t.primary_key)
if t.comment and not (m.description or "").strip():
......@@ -147,6 +145,11 @@ def run_introspection(ds_id: int, resample: bool = False) -> Iterator[dict]:
"i": i, "total": len(tables),
"message": f"表结构 {i}/{len(tables)}:{t.name}"}
# ---------- 移出范围 / 库里已删掉的表 ----------
# 数据源里取消勾选、或者业务库里删掉的表,连同它的列和关联一起下线,否则还会被拿去生成 SQL
if not truncated:
stats["dropped_models"] = _drop_models_except(ds_id, {t.name for t in tables})
# ---------- 值采样 ----------
# 这一步是整个内省里最值钱的:模型得看见 brand_name 里存的是中文品牌名,
# 才知道「某品牌的网点」该翻译成什么过滤条件。
......@@ -196,13 +199,26 @@ def run_introspection(ds_id: int, resample: bool = False) -> Iterator[dict]:
f"推导出 {stats['new_relations']} 条关系。")
if stats.get("disabled_empty_columns"):
msg += f" 另有 {stats['disabled_empty_columns']} 个整列全空的列已自动停用。"
if stats["new_models"] and not scope:
msg += " 新表默认是停用的,请在建模页里挑出要查的表并启用。"
if stats.get("dropped_models"):
msg += f" 移除了 {stats['dropped_models']} 张不在接入范围内的表。"
if truncated:
msg += f" 注意:表数超过 {MAX_TABLES},只处理了前 {MAX_TABLES} 张。"
yield {"stage": "done", "progress": 100, "message": msg, "stats": stats}
def _drop_models_except(ds_id: int, keep: set[str]) -> int:
with Session(get_engine()) as s:
gone = [m.id for m in s.scalars(select(SmModel).where(SmModel.ds_id == ds_id)).all()
if m.physical_table not in keep]
if gone:
s.execute(delete(SmRelation).where(SmRelation.ds_id == ds_id, or_(
SmRelation.from_model_id.in_(gone), SmRelation.to_model_id.in_(gone))))
s.execute(delete(SmColumn).where(SmColumn.model_id.in_(gone)))
s.execute(delete(SmModel).where(SmModel.id.in_(gone)))
s.commit()
return len(gone)
def table_scope(ds: dict) -> list[str]:
"""数据源的表范围:extra.tables,逗号或换行分隔的通配符(如 otlg_dm_*)。空 = 全部表。"""
raw = str((ds.get("extra") or {}).get("tables") or "")
......
......@@ -44,7 +44,7 @@ def _score(terms: list[str], text: str, weight: float = 1.0) -> float:
return hit
def retrieve(ds_id: int, question: str, overrides: dict | None = None) -> dict:
def retrieve(ds_id: int, question: str, overrides: dict | None = None, policy: str = "ask") -> dict:
"""返回要送进提示词的一切,以及给 trace 展示的命中明细。
结构(P1 换实现时必须保持一致):
......@@ -57,8 +57,8 @@ def retrieve(ds_id: int, question: str, overrides: dict | None = None) -> dict:
budget = int(cfg.get("SQL_CONTEXT_BUDGET") or "8000")
terms = _tok(question)
# 候选表 = 本空间已发布绑定覆盖到的表(和 executor 校验用的是同一个范围)
scope_tables, _, _ = executor.ask_scope(ds_id)
# 候选表 = 本空间已发布绑定覆盖到的表(和 executor 校验用的是同一个范围;调试台再加上启用的表)
scope_tables, _, _ = executor.scope_for(ds_id, policy)
all_models = [m for m in semantic.list_models(ds_id)
if (m["physical_table"] or m["name"]).lower() in scope_tables]
cols = semantic.list_columns([m["id"] for m in all_models], enabled_only=True)
......
......@@ -144,3 +144,14 @@ class SqlRun(Base):
trace_json: Mapped[str] = mapped_column(_LONGTEXT, default="[]")
rating: Mapped[int] = mapped_column(Integer, default=0) # 1 赞 / -1 踩
created_at: Mapped[dt.datetime] = mapped_column(DateTime, server_default=_NOW)
class SqlThread(Base):
"""SQL 调试台的会话:一串连续追问。每一轮就是一条同 thread_id 的 SqlRun。"""
__tablename__ = "otlg_sql_thread"
id: Mapped[str] = mapped_column(String(64), primary_key=True)
ds_id: Mapped[int] = mapped_column(Integer, index=True, default=0)
title: Mapped[str] = mapped_column(String(255), default="")
created_by: Mapped[str] = mapped_column(String(64), default="", index=True)
created_at: Mapped[dt.datetime] = mapped_column(DateTime, server_default=_NOW)
updated_at: Mapped[dt.datetime] = mapped_column(DateTime, server_default=_NOW)
......@@ -31,7 +31,7 @@ SUMMARY_ROWS = 20 # 送去做结论的行数上限。全量塞进去既贵
def run_ask(ds_id: int, question: str, history: list[dict] | None = None,
overrides: dict | None = None, thread_id: str = "",
summarize: bool = True) -> Iterator[dict]:
summarize: bool = True, policy: str = "ask") -> Iterator[dict]:
"""主入口。
`summarize=False` 时不生成结论 —— 统一提问把它当作一个取数函数调用,
......@@ -55,23 +55,22 @@ def run_ask(ds_id: int, question: str, history: list[dict] | None = None,
"database": ds["db_name"]}}
# ---------- 1) 召回 ----------
ctx = linker.retrieve(ds_id, question, overrides)
ctx = linker.retrieve(ds_id, question, overrides, policy)
if not ctx["models"]:
yield {"type": "error", "stage": "retrieve",
"error": "这个数据源在当前本体空间里还没有任何已发布的对象或指标绑定。"
"请先把对象类型绑定到数据表并发布。"}
msg, fix = executor.EMPTY_SCOPE.get(policy, executor.EMPTY_SCOPE["ask"])
yield {"type": "error", "stage": "retrieve", "error": f"{msg}{fix}"}
yield _done(thread_id, "failed", started)
return
schema = semantic.render_schema(ctx["models"], ctx["metrics"], semantic.ontology_overlay(ds_id))
try:
from ..memory import service as memory
hints = memory.sql_hints_text()
hints = memory.sql_hints(ds_id)
except Exception: # noqa: BLE001 经验中枢出问题不能挡住问数
hints = ""
hints = []
if hints:
schema += "\n\n## 取数约定(必须遵守)\n" + hints
yield {"type": "retrieve", **ctx["hits"],
schema += "\n\n## 取数约定(必须遵守)\n" + "\n".join(f"- {h['text']}" for h in hints)
yield {"type": "retrieve", **ctx["hits"], "hints": hints,
"schema_tokens": llm.count_tokens(schema), "flags": ctx["flags"]}
# ---------- 2) 计划 ----------
......@@ -135,14 +134,14 @@ def run_ask(ds_id: int, question: str, history: list[dict] | None = None,
error_repairs = 0
while True:
g = executor.validate(ds_id, sql, dialect)
g = executor.validate(ds_id, sql, dialect, policy)
yield {"type": "validate", "attempt": attempt, "ok": g.ok,
"issues": [i.as_dict() for i in g.issues],
"tables": g.tables, "limited": g.limited,
"sql": g.sql if g.ok else sql}
if g.ok:
outcome = executor.execute(ds_id, sql, dialect)
outcome = executor.execute(ds_id, sql, dialect, policy)
if outcome.ok:
if not _is_blank(outcome.result):
best = outcome
......
......@@ -18,6 +18,7 @@ from sqlalchemy import delete, select, update
from sqlalchemy.orm import Session
from ..core.db import get_engine
from ..core.reqcache import per_request
from . import crypto
from .connectors import registry
from .connectors.base import Connector
......@@ -66,6 +67,7 @@ def list_datasources() -> list[dict]:
return [_ds_dict(r) for r in rows]
@per_request
def get_datasource(ds_id: int, with_secret: bool = False) -> Optional[dict]:
with Session(get_engine()) as s:
r = s.get(DataSource, ds_id)
......@@ -146,6 +148,7 @@ def _col_dict(r: SmColumn) -> dict:
"sort_order": r.sort_order, "ontology_node_id": r.ontology_node_id or ""}
@per_request
def list_models(ds_id: int, enabled_only: bool = False) -> list[dict]:
with Session(get_engine()) as s:
q = select(SmModel).where(SmModel.ds_id == ds_id)
......@@ -286,6 +289,7 @@ def system_tables() -> set[str]:
return {t.lower() for t in Base.metadata.tables}
@per_request
def catalog_context(ds_id: int, usable_columns_only: bool = False) -> tuple[set[str], dict[str, set[str]]]:
"""(内省到的全部物理表, {表: 列集合}),全部小写。
......@@ -418,18 +422,6 @@ def render_schema(models: list[dict], metrics: list[dict] | None = None,
return out
# ---------------- 导出 ----------------
def export_mdl(ds_id: int) -> dict:
"""导出完整语义模型。既是备份,也是给人看的「我到底建了什么」。"""
ds = get_datasource(ds_id)
return {
"datasource": {"name": ds["name"], "type": ds["ds_type"], "database": ds["db_name"]} if ds else {},
"models": models_with_columns(ds_id, enabled_only=False),
"relations": list_relations(ds_id, enabled_only=False),
"metrics": list_metrics(ds_id, enabled_only=False),
}
# ---------------- 关系推荐 ----------------
# 这类命名的列到处都有,但它们不构成业务关联 —— 拿 id/name 去连表只会连出笛卡尔积
_GENERIC_COLUMNS = {
......@@ -467,7 +459,18 @@ def recommend_relations(ds_id: int, min_overlap: float = 0.5,
def keyish(name: str) -> bool:
low = name.lower()
return (low not in _GENERIC_COLUMNS
and (low.endswith("_id") or low.endswith("_code") or low.endswith("_uuid")))
and low.endswith(("_id", "_code", "_uuid", "_no")))
def home_rank(h: tuple[dict, dict]) -> tuple:
"""同一个键列在好几张表里都唯一时,哪张才是它的「本家」:
先看它是不是那张表的主键,再看表名是不是以列名的词干结尾(part_id → …_part),最后才比行数。"""
m, c = h
col = (c["physical_column"] or c["name"]).lower()
stem = col.rsplit("_", 1)[0]
table = (m["physical_table"] or m["name"]).lower()
is_pk = (m.get("primary_key") or "").split(",")[0].strip().lower() == col
named = table == stem or table.endswith("_" + stem) or table.endswith("_" + stem + "s")
return (-round(uniqueness(m, c), 2), 0 if is_pk else 1, 0 if named else 1, len(table), m["row_count_est"] or 0)
# ---- 候选:所有像键的列 ----
holders: dict[str, list[tuple[dict, dict]]] = {}
......@@ -486,19 +489,29 @@ def recommend_relations(ds_id: int, min_overlap: float = 0.5,
return uniq_cache[key]
pairs: list[tuple[dict, dict, dict, dict]] = [] # (src_m, src_c, dst_m, dst_c)
homes: dict[str, tuple[dict, dict]] = {} # 键列名 → 它的本家(表, 列)
# ---- 同名匹配:目标端取唯一度最高的那张表 ----
for _, hs in holders.items():
for key_col, hs in holders.items():
if len(hs) < 2:
continue
ranked = sorted(hs, key=lambda h: (-uniqueness(h[0], h[1]), h[0]["row_count_est"] or 0))
ranked = sorted(hs, key=home_rank)
dst_m, dst_c = ranked[0]
if uniqueness(dst_m, dst_c) < min_uniqueness:
continue # 这个列在哪张表里都不唯一,不是关联键
homes[key_col] = (dst_m, dst_c)
for src_m, src_c in ranked[1:]:
if src_m["id"] != dst_m["id"]:
pairs.append((src_m, src_c, dst_m, dst_c))
# ---- 带角色前缀的键:from_dealer_id / to_dealer_id → dealer_id 的本家 ----
for key_col, (dst_m, dst_c) in homes.items():
for m in models:
for c in m["columns"]:
name = (c["physical_column"] or c["name"]).lower()
if name != key_col and name.endswith("_" + key_col):
pairs.append((m, c, dst_m, dst_c))
# ---- 命名约定:foo_id → 名字含 foo 的表的主键 ----
for m in models:
for c in m["columns"]:
......
......@@ -59,6 +59,22 @@ async def create(body: WatchIn, _: identity.Actor = Depends(require("build"))):
return service.create(body.model_dump())
@router.get("/alerts")
async def alerts(state: str = "firing", watch_id: str = "", _: identity.Actor = Depends(require("view"))):
"""预警列表:正在命中的(或已恢复的)每一条,带命中时的数据和它触发了什么。"""
from . import engine
return engine.alerts(state, watch_id)
@router.post("/fields")
async def row_fields(body: dict, _: identity.Actor = Depends(require("view"))):
"""按「看什么」给出每一行能用来写条件的字段。"""
from ..kernel import service as ksvc
from . import engine
with ksvc.draft_runtime():
return engine.fields(body.get("source") or {})
@router.get("/runs")
async def runs(watch_id: str = "", limit: int = 50,
_: identity.Actor = Depends(require("view"))):
......
......@@ -91,7 +91,7 @@ def _fire(w: dict, row: dict, run_id: str) -> list[dict]:
# 流程以监控创建人的名义发起:运行记录、通知、后续动作的发起人都落在他身上
r = sop_engine.start(target["id"], params, mode="live", trigger="watch:" + w["id"],
started_by=w.get("created_by") or "", note="监控「" + w["title"] + "」触发")
fired.append({"kind": kind, "ok": True, "ref": r["id"],
fired.append({"kind": kind, "ok": True, "ref": r["id"], "ref_kind": "sop_run",
"text": "启动流程卡「" + target["title"] + "」"})
elif kind == "propose_action":
params = {k: actions.render(v, row) for k, v in (st.get("params") or {}).items()}
......@@ -100,10 +100,11 @@ def _fire(w: dict, row: dict, run_id: str) -> list[dict]:
st["action"], params, object_key=okey,
reason=st.get("reason") or ("监控「" + w["title"] + "」命中"),
initiator_kind="watch", source_ref="watch:" + w["id"] + ":" + run_id,
evidence=[{"kind": "watch", "text": "监控「" + w["title"] + "」条件 "
+ w["condition"] + " 命中:" + str(row)[:180], "ref": run_id}])
fired.append({"kind": kind, "ok": True, "ref": ar["id"],
"text": "生成审批单 " + str(ar.get("priority") or "")})
evidence=[{"kind": "watch", "text": "监控「" + w["title"] + "」命中:"
+ str(row.get("label") or row.get("key") or ""), "ref": "watch:" + w["id"]}])
fired.append({"kind": kind, "ok": True, "ref": ar["id"], "ref_kind": "action_run",
"text": ("已自动执行「" if ar.get("status") == "done" else "生成审批单「")
+ str(ar.get("action_name") or "") + "」"})
elif kind == "task":
t = tasks.create(
title=str(actions.render(st.get("title") or "", row) or "") or ("监控「" + w["title"] + "」命中"),
......@@ -111,7 +112,8 @@ def _fire(w: dict, row: dict, run_id: str) -> list[dict]:
description=str(actions.render(st.get("instructions") or "", row) or ""),
source_type="watch", source_id=w["id"],
context={"row": row, "watch": w["title"], "run_id": run_id})
fired.append({"kind": kind, "ok": True, "ref": t["id"], "text": "派了一条任务"})
fired.append({"kind": kind, "ok": True, "ref": t["id"], "ref_kind": "task",
"text": "派给" + (st.get("role") or w.get("owner_role") or "相关角色") + "一条待办"})
else:
# 通知只是让人知道,不占待办、不需要谁来「完成」
subject = str(actions.render(st.get("subject") or "", row) or "") \
......@@ -119,7 +121,8 @@ def _fire(w: dict, row: dict, run_id: str) -> list[dict]:
nid = notify.send("role:" + st["role"], subject[:200],
str(actions.render(st.get("body") or "", row) or ""),
link="#/watch?id=" + w["id"])
fired.append({"kind": kind, "ok": True, "ref": str(nid), "text": "通知了 " + st["role"]})
fired.append({"kind": kind, "ok": True, "ref": str(nid), "ref_kind": "notification",
"text": "通知了" + st["role"]})
except HTTPException as e:
fired.append({"kind": kind, "ok": False, "text": str(e.detail)[:200]})
except Exception as e: # noqa: BLE001
......@@ -191,10 +194,11 @@ def _scan(wid: str, *, dry: bool, trigger: str, force: bool) -> dict:
key = _hit_key(w["dedup"]["key"], row)
if not force and _suppressed(wid, key, cooldown):
suppressed += 1
_mark_seen(wid, key)
continue
res = _fire(w, row, run_id)
fired.extend([{**r, "key": key} for r in res])
_mark_fired(wid, key)
fired.extend([{**r, "key": key, "label": str(row.get("label") or key)} for r in res])
_mark_fired(w, key, row, res)
notes = []
if over:
notes.append("命中过多,本次只处理前 " + str(MAX_HITS) + " 条,还有 " + str(over) + " 条没处理")
......@@ -284,7 +288,8 @@ def _suppressed(wid: str, key: str, cooldown_hours: int) -> bool:
return (now() - st.last_fired_at) < dt.timedelta(hours=cooldown_hours)
def _mark_fired(wid: str, key: str) -> None:
def _mark_fired(w: dict, key: str, row: dict | None = None, fired: list[dict] | None = None) -> None:
wid = w["id"]
with session() as s:
sid = _state_id(wid, key)
st = s.get(WatchState, sid)
......@@ -292,17 +297,93 @@ def _mark_fired(wid: str, key: str) -> None:
st = WatchState(id=sid, workspace=identity.current().workspace, watch_id=wid,
hit_key=key)
s.add(st)
st.firing, st.last_fired_at, st.last_seen_at = 1, now(), now()
if not st.firing or st.first_seen_at is None:
st.first_seen_at = now() # 新的一轮命中
st.firing, st.last_fired_at, st.last_seen_at, st.recovered_at = 1, now(), now(), None
st.fire_count = (st.fire_count or 0) + 1
row = row or {}
st.label = str(row.get("label") or row.get("key") or key)[:255]
detail: dict[str, Any] = {"row": {k: v for k, v in list(row.items())[:40]}, "fired": fired or []}
if w["source"].get("kind") == "object":
detail["object"] = {"type_id": w["source"].get("object_type"), "key": str(row.get("key") or "")}
st.detail_json = jdump(detail)
s.commit()
def _mark_seen(wid: str, key: str) -> None:
"""还在命中,只是在冷却期里没有再触发:更新「最近一次看到」的时间。"""
with session() as s:
st = s.get(WatchState, _state_id(wid, key))
if st is not None:
st.last_seen_at = now()
s.commit()
def fields(source: dict) -> list[dict]:
"""命中的每一行有哪些字段(写条件、看命中明细时用):[{path, label, type, enum}]。"""
kind = source.get("kind")
if kind == "object":
ot = ksvc.rt_find(source.get("object_type") or "", "object_type")
if not ot:
return []
out = []
for c in objects.columns(ot):
t = "boolean" if c["data_type"] == "boolean" else \
"number" if c["data_type"] in ("number", "integer") else "text"
out.append({"path": c["name"], "label": c["label"], "type": t, "enum": c["enum"] or list(c["tones"]),
"format": c["format"], "unit": c["unit"]})
return out
if kind == "metric":
m = ksvc.rt_fn(source.get("metric") or "", "aggregate")
if not m:
return []
out = [{"path": d, "label": d, "type": "text", "enum": []} for d in source.get("dimensions") or []]
out.append({"path": "value", "label": metrics.value_label(m), "type": "number", "enum": []})
return out
return []
def alerts(state: str = "firing", watch_id: str = "", limit: int = 200) -> list[dict]:
"""预警:哪些正在命中、从什么时候开始、触发了什么;state=recovered 看已经恢复的。"""
from ..core.dbx import iso
with session() as s:
ws = {w.id: w for w in s.scalars(select(Watch).where(Watch.workspace == identity.current().workspace)).all()}
stmt = select(WatchState).where(WatchState.workspace == identity.current().workspace)
if watch_id:
stmt = stmt.where(WatchState.watch_id == watch_id)
if state == "firing":
stmt = stmt.where(WatchState.firing == 1)
elif state == "recovered":
stmt = stmt.where(WatchState.firing == 0)
rows = s.scalars(stmt.order_by(WatchState.last_fired_at.desc()).limit(limit)).all()
cache: dict[str, list[dict]] = {}
out = []
for r in rows:
w = ws.get(r.watch_id)
if w is None or jload(w.source_json, {}).get("kind") == "sop":
continue
src = jload(w.source_json, {})
if r.watch_id not in cache:
try:
cache[r.watch_id] = fields(src)
except Exception: # noqa: BLE001
cache[r.watch_id] = []
d = jload(r.detail_json, {}) or {}
out.append({"id": r.id, "watch_id": r.watch_id, "watch": w.title, "key": r.hit_key,
"label": r.label or r.hit_key, "firing": bool(r.firing), "fire_count": r.fire_count or 0,
"first_seen_at": iso(r.first_seen_at or r.last_fired_at), "last_seen_at": iso(r.last_seen_at),
"last_fired_at": iso(r.last_fired_at), "recovered_at": iso(r.recovered_at),
"row": d.get("row") or {}, "fired": d.get("fired") or [], "object": d.get("object"),
"fields": cache[r.watch_id]})
return out
def _mark_recovered(wid: str, key: str) -> None:
"""这一轮没再命中:标成已恢复,下次命中重新算冷却(而不是继续被压着)。"""
with session() as s:
st = s.get(WatchState, _state_id(wid, key))
if st is not None and st.firing:
st.firing, st.last_seen_at = 0, now()
st.firing, st.last_seen_at, st.recovered_at = 0, now(), now()
s.commit()
......
......@@ -66,3 +66,7 @@ class WatchState(Base):
last_fired_at: Mapped[dt.datetime | None] = mapped_column(DateTime, nullable=True)
last_seen_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now)
fire_count: Mapped[int] = mapped_column(Integer, default=0)
label: Mapped[str] = mapped_column(String(255), default="") # 命中的是谁(给人看)
first_seen_at: Mapped[dt.datetime | None] = mapped_column(DateTime, nullable=True) # 这一轮从什么时候开始命中
recovered_at: Mapped[dt.datetime | None] = mapped_column(DateTime, nullable=True)
detail_json: Mapped[str] = mapped_column(_LONGTEXT, default="{}") # 命中时的数据、触发了什么
......@@ -78,13 +78,29 @@ def normalize(body: dict) -> dict:
raise HTTPException(422, "要选一张流程卡")
source["sop"] = str(src["sop"]).strip()
cond = str(body.get("condition") or "").strip()
# 界面上用条件构建器拼出来的条件({mode, items[{left, op, right}]}):存一份原样的,方便下次打开接着改
tree = src.get("cond") if isinstance(src.get("cond"), dict) else None
if tree and tree.get("items"):
from ..sop import cond as sop_cond
try:
# 条件是对「命中的这一行」写的:界面上选的是「这一行.字段」,求值时直接就是字段名
flat = {**tree, "items": [{**i, "left": str(i.get("left") or "").replace("$item.", "$", 1)}
for i in tree["items"]]}
built = sop_cond.to_expr(flat)
except sop_cond.CondError as e:
raise HTTPException(422, "触发条件写得不对:" + str(e)) from e
if built:
cond = built
source["cond"] = {"mode": "any" if tree.get("mode") == "any" else "all",
"items": [{"left": str(i.get("left") or ""), "op": str(i.get("op") or "eq"),
"right": i.get("right")} for i in tree["items"] if i.get("left")]}
if cond:
try:
rules.free_names(cond)
except rules.RuleError as e:
raise HTTPException(422, "触发条件写得不对:" + str(e)) from e
elif kind != "sop":
raise HTTPException(422, "要写触发条件,例如 value > 0")
raise HTTPException(422, "要写满足什么条件才算命中")
strategies = []
for st in upgrade_strategies(body.get("strategies") or []):
k = str(st.get("kind") or "")
......
"""界面文案检查:防止开发用语和大段解释文字又长回界面上。
./.venv/Scripts/python.exe scripts/check_ui_copy.py # 有问题时退出码 1
查两件事(只看界面上会显示的字符串,不看注释和代码里的名字):
1. 禁用词:开发概念不该让使用者看到;
2. 说明文字过长:hint / desc 超过 MAX_HINT 个字,多半是在解释系统原理。
"""
from __future__ import annotations
import re
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
SRC = ROOT / "web" / "src"
sys.stdout.reconfigure(encoding="utf-8")
BANNED = ["骨架", "写回层", "四元组", "工作副本", "提示词", "内省", "SOP", "Agent", "eval", "审批中心", "LLM", "大模型"]
# 这些地方就是给实施人员看技术细节的,允许出现技术词
ALLOW_FILES = {"features/mcp", "features/settings", "features/evals", "features/runtime/AuditPage"}
MAX_HINT = 40
COMMENT = re.compile(r"/\*.*?\*/|//[^\n]*", re.S)
STRING = re.compile(r'"((?:[^"\\\n]|\\.)*)"|`((?:[^`\\]|\\.)*)`|>([^<>{}\n]*[一-鿿][^<>{}\n]*)<')
HINT = re.compile(r'\b(?:hint|desc|help)=(?:"([^"]*)"|\{"([^"]*)"\})')
CJK = re.compile(r"[一-鿿]")
def main() -> int:
bad: list[str] = []
for f in sorted(SRC.rglob("*.tsx")):
rel = f.relative_to(SRC).as_posix()
if any(rel.startswith(a) for a in ALLOW_FILES) or ".test." in rel:
continue
raw = f.read_text(encoding="utf-8")
# 注释换成等长空白,行号不变
text = COMMENT.sub(lambda m: re.sub(r"[^\n]", " ", m.group(0)), raw)
for m in STRING.finditer(text):
s = next(g for g in m.groups() if g is not None)
if not CJK.search(s):
continue # 没有中文的是代码里的标识,不是界面文案
line = text.count("\n", 0, m.start()) + 1
for w in BANNED:
if w in s:
bad.append(f"{rel}:{line} 禁用词「{w}」:{s.strip()[:60]}")
for m in HINT.finditer(text):
s = m.group(1) or m.group(2) or ""
if len(s) > MAX_HINT:
line = text.count("\n", 0, m.start()) + 1
bad.append(f"{rel}:{line} 说明过长({len(s)} 字):{s[:50]}…")
for b in bad:
print(b)
print(f"\n{'没有问题' if not bad else f'共 {len(bad)} 处'}")
return 1 if bad else 0
if __name__ == "__main__":
raise SystemExit(main())
......@@ -49,6 +49,8 @@ def main() -> None:
n += s.execute(delete(SopStepRun).where(SopStepRun.run_id.in_(runs))).rowcount or 0
defs = select(SopDefinition.id).where(SopDefinition.workspace == args.workspace)
n += s.execute(delete(SopVersion).where(SopVersion.def_id.in_(defs))).rowcount or 0
model_runs = select(km.ModelRun.id).where(km.ModelRun.workspace == args.workspace)
n += s.execute(delete(km.ModelCall).where(km.ModelCall.run_id.in_(model_runs))).rowcount or 0
actions = select(ActionRun.id).where(ActionRun.workspace == args.workspace)
n += s.execute(delete(ApprovalTask).where(ApprovalTask.run_id.in_(actions))).rowcount or 0
for table in (km.Concept, km.Binding, km.Evidence, km.Revision, km.ObjectEdit, km.InstanceCache,
......
"""启动 9101 实例:一套干净的环境,给人从头走一遍用。
- 元数据库是独立的 `ai_ontology_9101`(和 9100 用的 ai_ontology_dev 互不影响);
- 数据目录 `data_9101/`(上传的文档、知识索引都在这里);
- 前端产物和 9100 共用 `web/dist_9100`。
第一次用、或者想清空重来:
./.venv/Scripts/python.exe scripts/setup_9101.py # 建库(已有就清空)、灌 4S 场景的业务表
./.venv/Scripts/python.exe scripts/serve_9101.py
"""
from __future__ import annotations
import os
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
os.chdir(ROOT)
sys.path.insert(0, str(ROOT))
os.environ["DB_NAME"] = os.environ.get("DB_NAME_9101", "ai_ontology_9101")
os.environ["DATA_DIR"] = "./data_9101"
os.environ.setdefault("WEB_DIST", "dist_9100")
if __name__ == "__main__":
import uvicorn
uvicorn.run("app.main:app", host="0.0.0.0", port=int(os.environ.get("PORT", "9101")))
"""准备 9101 的干净环境:独立的元数据库 + 4S 场景的 10 张业务表。本体、数据源、流程卡一概不建,留给人自己走。
./.venv/Scripts/python.exe scripts/setup_9101.py # 库不存在就建;存在就只重灌业务表
./.venv/Scripts/python.exe scripts/setup_9101.py --wipe # 连系统数据一起清空,回到全新状态(要先停掉 9101)
会从开发库把「系统设置」(用哪个模型等)抄过来,免得新环境里模型没配好、提问用不了。
"""
from __future__ import annotations
import argparse
import os
import shutil
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
sys.stdout.reconfigure(encoding="utf-8")
DB = os.environ.get("DB_NAME_9101", "ai_ontology_9101")
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--wipe", action="store_true", help="清空系统数据,回到全新状态")
args = ap.parse_args()
from sqlalchemy import create_engine, text
from app.core.config import get_settings
st = get_settings()
dev = st.db_name
if DB == dev:
raise SystemExit("9101 的库不能和开发库同名")
root = create_engine(st.url_for(dev), future=True)
with root.begin() as c:
exists = c.execute(text("SELECT COUNT(*) FROM information_schema.schemata WHERE schema_name = :n"), {"n": DB}).scalar()
if exists and args.wipe:
c.execute(text(f"DROP DATABASE `{DB}`"))
exists = 0
print(f"已删除旧库 {DB}")
if not exists:
c.execute(text(f"CREATE DATABASE `{DB}` DEFAULT CHARACTER SET utf8mb4"))
print(f"已建库 {DB}")
if args.wipe:
shutil.rmtree(ROOT / "data_9101", ignore_errors=True)
# 建表、放默认成员:用 9101 的库名起一个进程跑初始化
env = {**os.environ, "DB_NAME": DB, "DATA_DIR": "./data_9101"}
subprocess.run([sys.executable, "-c",
"from app.core import db; db.init_db(); from app.governance import users; users.seed(); print('ok')"],
cwd=ROOT, env=env, check=True)
# 系统设置抄开发库的(模型、检索参数)
with root.begin() as c:
c.execute(text(f"REPLACE INTO `{DB}`.otlg_config SELECT * FROM `{dev}`.otlg_config"))
print("系统设置已从开发库同步")
# 业务表
subprocess.run([sys.executable, str(ROOT / "scripts" / "seed_dealer_parts_demo.py")], cwd=ROOT, env=env, check=True)
print(f"\n9101 准备好了。启动:./.venv/Scripts/python.exe scripts/serve_9101.py,然后打开 http://localhost:9101\n"
f"接数据源时库名填 {DB},表范围填 otlg_dm2_*。")
if __name__ == "__main__":
main()
......@@ -345,8 +345,8 @@ def test_业务建模管道_上传文档到四元组草案(env, monkeypatch):
out = review.decide(g["items"]["object_type"][0]["id"], True)
from app.kernel import service
assert service.get_concept(out["result"]["concept_id"])["origin"] == "modeling"
with pytest.raises(HTTPException):
modeling.create("空", doc_ids=[])
with pytest.raises(HTTPException): # 文档和数据库一样都没选
modeling.create("空", doc_ids=[], ds_ids=[])
def test_业务建模_数据对齐_指标绑定_动作补全_写回业务库(env, monkeypatch):
......@@ -411,21 +411,17 @@ def test_业务建模_数据对齐_指标绑定_动作补全_写回业务库(env
service.publish("门店建模")
# 已经有文档命名的同一条关系:再从数据源「提议到本体」不会冒出重复的「订单成交明细-门店主数据」
from app.kernel import propose
assert propose.from_datasource(env["ds_id"])["proposed"] == 0
assert propose.submit_proposals(propose.datasource_proposals(env["ds_id"]), "introspect")["proposed"] == 0
from app.kernel import metrics, workbench
assert metrics.query("成交额")["rows"][0][0] == 2100.0
wb = workbench.workbench() # 工作台:已发布指标的当前值 + 能直接问的问题
assert [k["name"] for k in wb["kpis"]] == ["成交额"] and wb["kpis"][0]["value"] == 2100.0
assert any("成交额" in q for q in wb["questions"])
# 数据源没开写回:审批通过也执行失败,并说清楚原因
run1 = actions.propose("补录订单", {"order_id": 99, "amount": 88}, object_key="1", reason="补录")
tok = as_user("approver")
try:
failed = actions.decide(run1["id"], True)
finally:
identity.reset(tok)
assert failed["status"] == "failed" and "写回业务库" in failed["error"], failed
# 数据源没开写回:提交时就拦下并说清楚原因(不用等审批通过了才失败)
with pytest.raises(HTTPException) as e:
actions.propose("补录订单", {"order_id": 99, "amount": 88}, object_key="1", reason="补录")
assert "写回业务库" in e.value.detail
semantic.update_datasource(env["ds_id"], extra={"writeback": True})
run2 = actions.propose("补录订单", {"order_id": 100, "amount": 66}, object_key="2", reason="补录")
tok = as_user("approver")
......
......@@ -197,10 +197,10 @@ def test_指标确定性取数与对象读写回(env):
o = objects.get("网点", "1")
assert o["label"] == "杭州体验中心" and o["properties"]["等级"] == "A"
with pytest.raises(HTTPException): # 不可写属性
objects.write(b["ot"]["id"], "1", "名称", "x")
e = objects.write(b["ot"]["id"], "1", "等级", "S")
objects.apply_ops([{"op": "update", "object_type": b["ot"]["id"], "key": "1", "values": {"名称": "x"}}])
e = objects.apply_ops([{"op": "update", "object_type": b["ot"]["id"], "key": "1", "values": {"等级": "S"}}])
assert objects.get("网点", "1")["properties"]["等级"] == "S"
objects.revert_edit(e["id"])
objects.revert_edits(e["edit_ids"])
assert objects.get("网点", "1")["properties"]["等级"] == "A"
......@@ -334,7 +334,7 @@ def test_SOP校验(env):
{"id": "c", "type": "end"},
]})
errs = " ".join(spec.validate(bad)["errors"])
assert "变量「nope」" in errs and "默认分支" in errs and "有误" in errs
assert "变量「nope」" in errs and "「否则」" in errs and "有误" in errs
cyc = spec.normalize({"steps": [
{"id": "a", "type": "function", "function": "ontology.overview", "next": "b"},
{"id": "b", "type": "function", "function": "ontology.overview", "next": "a"}]})
......
......@@ -68,13 +68,13 @@ def test_逐行处理与子流程的校验(env):
{"id": "each", "type": "foreach", "title": "逐行", "action": "", "next": "end"},
{"id": "end", "type": "end"}]})
errs = " ".join(spec.validate(bad)["errors"])
assert "还没有步骤" in errs and "按哪份数据" in errs
assert "还没有步骤" in errs and "哪份数据" in errs
nested = spec.normalize({"steps": [
{"id": "each", "type": "foreach", "title": "逐行", "items": "$x", "next": "end", "body": {"steps": [
{"id": "sub", "type": "subprocess", "title": "子流程", "sop": "x", "next": "re"},
{"id": "re", "type": "end"}]}},
{"id": "end", "type": "end"}]})
assert "不能再放" in " ".join(spec.validate(nested, check_refs=False)["errors"])
assert "不能放" in " ".join(spec.validate(nested, check_refs=False)["errors"])
d = service.create("自己调自己", spec={"steps": [{"id": "s", "type": "subprocess", "title": "子", "next": "e"},
{"id": "e", "type": "end"}]})
service.update(d["id"], spec={"steps": [{"id": "s", "type": "subprocess", "title": "子", "sop": d["id"], "next": "e"},
......
......@@ -226,9 +226,16 @@ def test_内省采到枚举列的真实取值(env):
assert "问界" in brand["sample_values"]
def test_新表默认不启用(env):
def test_接入的表读进来就启用(env):
# 接入范围在数据源里勾选,读进来的表全部参与问数,不再逐张启用
list(introspect.run_introspection(env["ds_id"]))
assert all(not m["enabled"] for m in semantic.list_models(env["ds_id"]))
assert all(m["enabled"] for m in semantic.list_models(env["ds_id"]))
def _introspect_empty_scope(ds_id: int) -> None:
"""内省后把范围清空(模拟本体里一张表都没绑定)。"""
list(introspect.run_introspection(ds_id))
semantic.set_models_enabled(ds_id, [m["id"] for m in semantic.list_models(ds_id)], False)
def test_外键推导出关系(env):
......@@ -338,7 +345,7 @@ def test_自愈次数不超过配置上限(env):
def test_提问范围为空时给明确提示(env):
list(introspect.run_introspection(env["ds_id"])) # 只内省,范围里一张表都没有
_introspect_empty_scope(env["ds_id"]) # 只内省,范围里一张表都没有
events = run(env["ds_id"], "门店有哪些")
err = by_type(events, "error")[0]
assert "还没有任何已发布的对象或指标绑定" in err["error"]
......@@ -525,7 +532,7 @@ def test_每条出口都以done收尾(env):
# 2) 一张表都没启用
def no_models():
list(introspect.run_introspection(ds_id))
_introspect_empty_scope(ds_id)
return run(ds_id, "门店有哪些")
cases.append(("没有启用的表", no_models))
......
......@@ -104,10 +104,10 @@ def test_流程卡引用草稿_试运行能跑_发布被拦并列出草稿(env):
def test_流程卡参数没填或名字不存在_编辑时就报出来(env):
from app.sop import service
build_basics(env["ds_id"])
d = service.create("空取数") # 新建的空白流程卡从「取数」开始
assert d["spec"]["steps"][0]["function"] == "metric.query"
d = service.create("空取数") # 新建的空白流程卡:开始 → 查数据 → 结束
assert d["spec"]["steps"][0]["type"] == "query" and d["spec"]["steps"][0]["ui"]
errs = service.get(d["id"])["validation"]["errors"]
assert any("还没填" in e for e in errs)
assert any("还没选查哪类对象" in e for e in errs)
service.update(d["id"], spec={"steps": [
{"id": "q", "type": "function", "title": "取数", "function": "metric.query",
"args": {"metric": "不存在的指标"}, "next": "end"}, {"id": "end", "type": "end", "title": "完"}]})
......
[
{
"name": "01_workbench",
"hash": "desk",
"user": "parts_mgr",
"expect": [
"等我处理",
"预警"
]
},
{
"name": "02_objects_stock",
"hash": "objects",
"expect": [
"门店库存"
]
},
{
"name": "03_objects_stock_filter",
"hash": "objects",
"steps": [
{
"click": "门店库存",
"exact": true
},
{
"click": "囤货预警",
"exact": true
}
]
},
{
"name": "04_object_detail",
"hash": "objects",
"steps": [
{
"click": "缺件单",
"exact": true
},
{
"click": "SH20260013",
"wait": 2500
}
],
"full": true,
"expect": [
"基本信息",
"SH20260013"
]
},
{
"name": "05_object_action",
"hash": "objects",
"user": "parts_mgr",
"steps": [
{
"click": "缺件单",
"exact": true
},
{
"click": "SH20260013"
},
{
"click": "下缺件专订"
},
{
"fill": "input[type=number]",
"value": 4,
"wait": 1800
}
]
},
{
"name": "06_inbox",
"hash": "inbox",
"user": "region_mgr",
"expect": [
"待我审批",
"会做什么"
]
},
{
"name": "07_inbox_history",
"hash": "inbox?tab=runs",
"user": "planner"
},
{
"name": "08_sop_list",
"hash": "sop",
"expect": [
"缺件处理",
"每日补货巡检"
]
},
{
"name": "09_sop_runs",
"hash": "sop?tab=runs",
"expect": [
"进行到",
"怎么发起的"
]
},
{
"name": "10_sop_editor",
"hash": "sop",
"steps": [
{
"click": "缺件处理",
"exact": true
}
]
},
{
"name": "11_sop_run",
"hash": "sop?tab=runs",
"steps": [
{
"click": "td:has-text('每日补货巡检')",
"css": true
}
],
"full": true,
"expect": [
"查可以订货的配件",
"逐条下订单"
]
},
{
"name": "12_watch",
"hash": "watch",
"expect": [
"囤货预警"
]
},
{
"name": "13_watch_editor",
"hash": "watch",
"steps": [
{
"click": "囤货预警",
"exact": true
}
],
"expect": [
"盯什么",
"多久看一次"
]
},
{
"name": "14_alerts",
"hash": "alerts",
"expect": [
"正在发生",
"囤货预警"
]
},
{
"name": "15_ask",
"hash": "ask"
},
{
"name": "16_b_object",
"hash": "b_object",
"steps": [
{
"click": "门店库存",
"exact": true
}
],
"full": true,
"expect": [
"属性"
]
},
{
"name": "17_b_function",
"hash": "b_function",
"steps": [
{
"click": "库存金额",
"exact": true
}
],
"full": true
},
{
"name": "18_b_action",
"hash": "b_action",
"steps": [
{
"click": "下常规订单",
"exact": true
}
],
"full": true,
"expect": [
"要填什么"
]
},
{
"name": "19_b_link",
"hash": "b_link"
},
{
"name": "20_data",
"hash": "data"
},
{
"name": "21_publish",
"hash": "publish",
"expect": [
"线上版本"
]
},
{
"name": "22_modeling",
"hash": "modeling"
},
{
"name": "23_members",
"hash": "members",
"expect": [
"配件主管"
]
},
{
"name": "24_monitor",
"hash": "monitor"
},
{
"name": "25_canvas",
"hash": "canvas"
},
{
"name": "18b_action_mid",
"hash": "b_action",
"steps": [
{
"click": "下常规订单",
"exact": true
},
{
"scroll": 900
}
]
},
{
"name": "18c_action_low",
"hash": "b_action",
"steps": [
{
"click": "下常规订单",
"exact": true
},
{
"scroll": 2300
}
]
},
{
"name": "18d_action_end",
"hash": "b_action",
"steps": [
{
"click": "下常规订单",
"exact": true
},
{
"scroll": 4200
}
]
},
{
"name": "16b_object_mid",
"hash": "b_object",
"steps": [
{
"click": "门店库存",
"exact": true
},
{
"scroll": 700
}
]
},
{
"name": "16c_object_low",
"hash": "b_object",
"steps": [
{
"click": "门店库存",
"exact": true
},
{
"scroll": 1500
}
]
},
{
"name": "18e_action_try",
"hash": "b_action",
"steps": [
{
"click": "下常规订单",
"exact": true
},
{
"click": "试一试",
"exact": true
}
]
},
{
"name": "17b_function_data",
"hash": "b_function",
"steps": [
{
"click": "库存金额",
"exact": true
},
{
"click": "怎么取数",
"exact": true
}
]
}
]
\ No newline at end of file
/**
* 逐页截图:用本机的 Edge 打开系统,按清单走一遍,每页存一张图。改完界面用它看一眼实际效果。
*
* node web/e2e/shots.mjs # 9100、dealer_parts 空间、全部页面
* node web/e2e/shots.mjs objects inbox # 只截名字里带这些词的
* PORT=9101 WS=default node web/e2e/shots.mjs
*
* 清单里每一项:name、hash、user(以谁的身份看)、可选的 steps(点哪里)、expect(页面上必须出现的字)。
*
* 同时是冒烟检查,下面任何一条不满足就以退出码 1 结束:
* - 浏览器控制台没有报错,接口没有返回 4xx / 5xx;
* - 页面上没有露出 undefined / NaN / [object Object];
* - 截图时页面不在转圈(数据加载完了);
* - 清单里 expect 的字都在页面上。
*/
import { chromium } from "playwright-core";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const here = path.dirname(fileURLToPath(import.meta.url));
const PORT = process.env.PORT || "9100";
const WS = process.env.WS || "dealer_parts";
const OUT = process.env.OUT || path.join(here, "shots");
const BASE = `http://127.0.0.1:${PORT}`;
const only = process.argv.slice(2);
/** @type {{name: string, hash: string, user?: string, steps?: (page: import('playwright-core').Page) => Promise<void>, full?: boolean, width?: number}[]} */
export const PAGES = JSON.parse(fs.readFileSync(path.join(here, "pages.json"), "utf-8"));
const browser = await chromium.launch({ channel: "msedge", headless: true });
const errors = [];
for (const p of PAGES) {
if (only.length && !only.some((w) => p.name.includes(w))) continue;
const ctx = await browser.newContext({ viewport: { width: p.width || 1440, height: p.height || 900 }, deviceScaleFactor: 1 });
await ctx.addInitScript(([ws, user]) => {
localStorage.setItem("onto.workspace", ws);
localStorage.setItem("onto.user", user);
}, [WS, p.user || "admin"]);
const page = await ctx.newPage();
page.on("console", (m) => { if (m.type() === "error") errors.push(`${p.name}: ${m.text().slice(0, 200)}`); });
page.on("pageerror", (e) => errors.push(`${p.name}: ${String(e).slice(0, 200)}`));
page.on("response", (r) => {
if (r.status() >= 400 && r.url().includes("/api/")) errors.push(`${p.name}: 接口 ${r.status()} ${r.url().replace(BASE, "").slice(0, 120)}`);
});
await page.goto(`${BASE}/#/${p.hash}`);
await page.waitForTimeout(p.wait || 1800);
for (const s of p.steps || []) {
try {
if (s.click && s.css) await page.locator(s.click).first().click({ timeout: 4000 });
else if (s.click) await page.getByText(s.click, { exact: !!s.exact }).first().click({ timeout: 4000 });
if (s.clickRole) await page.getByRole(s.clickRole, { name: s.name }).first().click({ timeout: 4000 });
if (s.fill) await page.locator(s.fill).first().fill(String(s.value));
if (s.press) await page.keyboard.press(s.press);
if (s.scroll !== undefined) await page.evaluate((y) => document.querySelectorAll('.overflow-auto').forEach((e) => { e.scrollTop = y; }), s.scroll);
await page.waitForTimeout(s.wait || 900);
} catch (e) {
errors.push(`${p.name}: 步骤 ${JSON.stringify(s)} 没做成 —— ${String(e).split("\n")[0].slice(0, 160)}`);
}
}
if (await page.locator("main .animate-spin").count()) {
await page.waitForTimeout(2500);
if (await page.locator("main .animate-spin").count()) errors.push(`${p.name}: 截图时还在转圈`);
}
const text = await page.locator("body").innerText();
for (const bad of ["undefined", "NaN", "[object Object]"]) {
if (text.includes(bad)) errors.push(`${p.name}: 页面上出现了「${bad}」`);
}
for (const want of p.expect || []) {
if (!text.includes(want)) errors.push(`${p.name}: 页面上没有「${want}」`);
}
fs.mkdirSync(OUT, { recursive: true });
await page.screenshot({ path: path.join(OUT, `${p.name}.png`), fullPage: !!p.full });
console.log("✓", p.name);
await ctx.close();
}
await browser.close();
if (errors.length) {
console.log("\n页面上的错误:");
for (const e of [...new Set(errors)]) console.log(" -", e);
process.exitCode = 1;
} else {
console.log("冒烟检查通过");
}
......@@ -12,8 +12,10 @@
"build:9100": "tsc -b && vite build --outDir dist_9100 --emptyOutDir"
},
"dependencies": {
"@codemirror/lang-sql": "^6.10.0",
"@sigma/edge-curve": "^3.1.0",
"@sigma/node-border": "^3.0.0",
"@uiw/react-codemirror": "^4.25.12",
"@xyflow/react": "^12.3.6",
"clsx": "^2.1.1",
"graphology": "^0.26.0",
......@@ -33,6 +35,7 @@
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.3",
"autoprefixer": "^10.4.20",
"playwright-core": "^1.64.0",
"postcss": "^8.4.47",
"tailwindcss": "^3.4.14",
"typescript": "^5.6.3",
......
import { describe, expect, it } from "vitest";
import type { FlowOutput, FlowTree } from "@/lib/onto";
import {
allSteps, allowedIn, condText, findStep, insertStep, locate, loopOf, moveStep, newStep, refLabel, removeStep,
summarize, updateStep, visibleOutputs,
} from "@/features/sop/flowModel";
const tree = (): FlowTree => ({
params: [], priority: "P2", domain: "",
steps: [
{ id: "gap", kind: "metric", title: "核对库存缺口", var: "gap", metric: "库存缺口", by: ["仓库", "商品"], filters: {}, where: null },
{ id: "each", kind: "foreach", title: "逐条补货", var: "each", items: "$gap", filter: null, limit: 20, steps: [
{ id: "big", kind: "branch", title: "缺口大吗", otherwise: [
{ id: "tell", kind: "notify", title: "知会", to: { kind: "role", value: "采购员" }, subject: "$item.商品名称 缺 $item.value" }],
branches: [{ label: "大", when: { mode: "all", items: [{ left: "$item.value", op: "ge", right: 100 }] }, steps: [
{ id: "po", kind: "action", title: "建采购单", var: "po", action: "创建补货采购单", target: "$item.商品", params: {}, on_reject: "stop" }] }] }] },
{ id: "fin", kind: "end", title: "完成", outcome: "已处理" },
],
});
const outputs: FlowOutput[] = [
{ id: "gap", var: "gap", title: "核对库存缺口", kind: "metric", scope: "", fields: [{ path: "rows", label: "每一行", type: "rows" }],
row_fields: [{ path: "仓库", label: "仓库", type: "text" }, { path: "商品名称", label: "商品名称", type: "text" }, { path: "value", label: "库存缺口(件)", type: "number" }] },
{ id: "each:item", var: "item", title: "当前这一条", kind: "item", scope: "each",
fields: [{ path: "商品名称", label: "商品名称", type: "text" }, { path: "value", label: "库存缺口(件)", type: "number" }], row_fields: [] },
{ id: "po", var: "po", title: "建采购单", kind: "action", scope: "each", fields: [{ path: "status", label: "动作结果", type: "text" }], row_fields: [] },
{ id: "each", var: "each", title: "逐条补货", kind: "foreach", scope: "", fields: [{ path: "ok", label: "完成几条", type: "number" }], row_fields: [] },
];
describe("流程卡步骤树", () => {
it("遍历出所有步骤,包括分支和循环体里的", () => {
expect(allSteps(tree().steps).map((s) => s.id)).toEqual(["gap", "each", "big", "po", "tell", "fin"]);
});
it("在任意位置插入一步,id 不重复", () => {
const t = tree();
const s = newStep(t, "notify");
const next = insertStep(t, { at: "branch", step: "big", index: 0 }, 1, s);
const branch = findStep(next, "big")!.branches![0].steps;
expect(branch.map((x) => x.id)).toEqual(["po", s.id]);
expect(newStep(next, "notify").id).not.toBe(s.id);
expect(findStep(t, "big")!.branches![0].steps).toHaveLength(1); // 原树没被改
});
it("改一步、删一步、同一串里上下移动", () => {
let t = updateStep(tree(), "po", { title: "下采购单" });
expect(findStep(t, "po")!.title).toBe("下采购单");
t = removeStep(t, "tell");
expect(findStep(t, "tell")).toBeUndefined();
t = moveStep(t, "fin", -1);
expect(t.steps.map((s) => s.id)).toEqual(["gap", "fin", "each"]);
expect(moveStep(t, "gap", -1).steps.map((s) => s.id)).toEqual(["gap", "fin", "each"]); // 已在最前,不动
});
it("知道一步在哪儿、在不在循环体里", () => {
const t = tree();
expect(locate(t, "tell")).toEqual({ path: { at: "otherwise", step: "big" }, index: 0 });
expect(loopOf(t, "po")).toBe("each");
expect(loopOf(t, "fin")).toBe("");
expect(allowedIn("foreach", true)).toBe(false);
expect(allowedIn("action", true)).toBe(true);
});
it("每一步只能引用排在前面、且看得见的数据", () => {
const t = tree();
const at = (id: string) => visibleOutputs(t, id, outputs).map((o) => o.id);
expect(at("gap")).toEqual([]);
expect(at("each")).toEqual(["gap"]);
expect(at("po")).toEqual(["gap", "each:item"]); // 循环体里多一个「当前这一条」
expect(at("tell")).toEqual(["gap", "each:item"]); // 「建采购单」在另一个分支里,这条路没走到它
expect(at("fin")).toEqual(["gap", "each"]); // 出了循环体,里面的结果看不到,只有汇总
});
it("把引用和步骤说成人话", () => {
const t = tree();
expect(refLabel("$gap.value", outputs)).toBe("核对库存缺口 · 库存缺口(件)");
expect(refLabel("$nope.x", outputs)).toBe("$nope.x");
expect(condText(findStep(t, "big")!.branches![0].when, outputs)).toBe("库存缺口(件) 大于等于 100");
expect(summarize(findStep(t, "gap")!, outputs)).toBe("查 库存缺口,按 仓库、商品");
expect(summarize(findStep(t, "each")!, outputs)).toBe("对 核对库存缺口 的每一条(最多 20 条)");
expect(summarize(findStep(t, "tell")!, outputs)).toContain("通知 采购员");
expect(summarize(newStep(t, "metric"), outputs)).toBe("还没选指标");
});
});
......@@ -2,6 +2,7 @@ import {
AlertTriangle, Check, CheckCircle2, ChevronRight, Copy, Info, Loader2, RotateCcw, X, XCircle,
} from "lucide-react";
import React, { useEffect, useRef, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { cn } from "@/lib/utils";
import { useAppStore } from "@/store/useAppStore";
......@@ -13,10 +14,10 @@ export function CardHeader({ title, desc, right, className }: {
title: ReactNode; desc?: ReactNode; right?: ReactNode; className?: string;
}) {
return (
<div className={cn("flex items-start justify-between gap-3 px-4 py-3 border-b border-line", className)}>
<div className={cn("flex items-start justify-between gap-3 border-b border-line px-5 py-3.5", className)}>
<div className="min-w-0">
<h3 className="text-body font-semibold leading-tight truncate">{title}</h3>
{desc && <p className="text-xs text-muted mt-0.5">{desc}</p>}
<h3 className="truncate text-title font-semibold leading-snug">{title}</h3>
{desc && <p className="mt-0.5 text-caption text-muted">{desc}</p>}
</div>
{right && <div className="flex items-center gap-1.5 shrink-0">{right}</div>}
</div>
......@@ -92,7 +93,7 @@ export function Empty({ icon, title, desc, action }: {
<div className="flex flex-col items-center justify-center gap-2 px-6 py-12 text-center">
{icon && <div className="mb-1 text-muted/50">{icon}</div>}
<p className="text-title font-medium">{title}</p>
{desc && <p className="max-w-sm text-xs text-muted leading-relaxed">{desc}</p>}
{desc && <p className="max-w-sm text-label leading-relaxed text-muted">{desc}</p>}
{action && <div className="mt-3">{action}</div>}
</div>
);
......@@ -233,7 +234,7 @@ export function Field({ label, hint, required, children, className }: {
{required && <span className="ml-0.5 text-bad">*</span>}
</label>
{children}
{hint && <p className="mt-1 text-label leading-relaxed text-muted">{hint}</p>}
{hint && <p className="hint">{hint}</p>}
</div>
);
}
......@@ -342,9 +343,33 @@ export class PageErrorBoundary extends React.Component<
/** 术语表:搭建页面里绕不开的专业词,悬停给一句大白话。 */
export const GLOSSARY: Record<string, string> = {
本体: "把业务里的「东西」(门店、商品)、「关系」(供货)、「算法」(指标、规则)和「能做的事」(补货、标记)描述清楚的一套模型,系统按它理解问题、取数和执行",
元素: "本体由四种元素搭成:对象、关系、指标与规则(函数)、动作",
本体: "把业务里的「东西」(门店、配件)、「关系」(供货)、「算法」(指标、规则)和「能做的事」(补货、标记)描述清楚的一套模型,系统按它理解问题、取数和执行",
元素: "本体由四种元素搭成:对象、关系、函数(指标与规则)、动作",
四元组: "对象、关系、函数(指标与规则)、动作这四种元素",
对象: "业务里能一个个指认出来的东西,比如门店、配件、采购单。每个对象有若干属性,通常对应一张数据表",
关系: "两类对象之间怎么关联,比如「采购单属于供应商」。系统靠它从一个对象找到相关的另一个",
函数: "对对象做的计算或判断,分聚合(指标)、规则、决策表、周期等几类",
动作: "会改变业务数据的操作,比如「下发补货单」「标记缺件」。有参数、执行前的检查条件和执行效果,可以要求审批",
聚合: "算出一个数的指标,比如「缺件率」「库存周转天数」。接上取数表达式后,系统自动生成 SQL 去业务库里算",
规则: "一条判断或计算公式,比如「库存 + 在途 < 安全库存 就算缺货」。结果是 是 / 否,或者一个数",
决策表: "按几个条件查表得出结论,一行一条规则,比如「缺件超过 3 天且是事故车 → 优先级 高」",
周期: "统计用的时间窗口,比如自然月,或「上月 26 日到本月 25 日」这样的业务月",
模型推理: "调用已经登记的机器学习模型,按输入算出预测值,比如预测下个月的销量",
"AI 分析(参考)": "让 AI 读取数据后给出结论,只读不改,结果仅供参考",
基数: "两类对象各有几个对应:1:n 是一个 A 对应多个 B(一个供应商有多张采购单),n:1 反过来,1:1 一一对应,n:n 多对多",
绑定: "把元素接到真实数据上:对象对应哪张表、关系用哪两列关联、指标怎么取数",
取数表达式: "指标在数据库里怎么算的 SQL 片段,比如 SUM(amount)。AI 写出来后会在业务库里实际跑一次,跑通才采用",
前置条件: "动作执行前要满足的检查,比如「库存数量 > 0 才能出库」,不满足就不能执行",
效果: "动作执行后真正做的事:改某个字段、新建一条记录、发通知、派待办",
参数: "执行动作或流程卡时要人填的内容,比如补货数量、原因",
属性: "对象上的一个字段,比如配件的「库存数量」",
主键: "能唯一确定一条记录的属性,比如配件编号",
可分组: "能用来分组统计的属性,比如门店、品类、状态",
可写: "允许动作修改的属性",
可信度: "AI 对这条草案有多大把握。高的默认勾选;低的往往还没落到数据上(没绑表、没公式、动作没补全),建议看过再定",
深化: "AI 把文档里的文字规则进一步写成能直接计算的公式或决策表",
草案: "AI 起草、还没决定的元素。采纳后才会真正建出来并上线",
采纳: "确认这条草案没问题:建成元素并直接发布上线;体检没过的会留在草稿里并说明原因",
骨架: "对象的主键、名称和关系键。只同步这些,明细数据仍然实时查业务库",
口径: "一个指标到底怎么算:统计哪些数据、分子分母是什么、按什么周期",
流程卡: "可以运行的标准流程:取数、判断、派任务、发起动作,按顺序自动推进",
......@@ -352,12 +377,41 @@ export const GLOSSARY: Record<string, string> = {
变更提案: "改动本体后提交给别人审批,批准后才正式发布生效",
};
/**
* 悬停说明气泡。挂在 body 上(fixed 定位),不会被滚动区、overflow:hidden 的卡片裁掉;
* 比原生 title 出得快、能换行。tip 为空时只渲染 children。
*/
export function Tip({ tip, children, className, style }: {
tip?: ReactNode; children: ReactNode; className?: string; style?: React.CSSProperties;
}) {
const ref = useRef<HTMLSpanElement>(null);
const [at, setAt] = useState<{ x: number; top: number; bottom: number } | null>(null);
const show = () => {
const r = ref.current?.getBoundingClientRect();
if (r) setAt({ x: r.left + r.width / 2, top: r.top, bottom: r.bottom });
};
const hide = () => setAt(null);
if (!tip) return <span className={className} style={style}>{children}</span>;
const below = at ? at.top < 90 : false;
const x = at ? Math.max(170, Math.min(window.innerWidth - 170, at.x)) : 0;
return (
<span ref={ref} className={className} style={style} onMouseEnter={show} onMouseLeave={hide} onFocus={show} onBlur={hide}>
{children}
{at && createPortal(
<div role="tooltip"
className="pointer-events-none fixed z-[200] w-max max-w-[320px] rounded-lg bg-ink px-2.5 py-1.5 text-caption font-normal leading-relaxed text-surface shadow-lg"
style={{ left: x, top: below ? at.bottom + 6 : at.top - 6, transform: `translate(-50%, ${below ? "0" : "-100%"})` }}>
{tip}
</div>, document.body)}
</span>
);
}
/** 术语:带虚下划线,悬停看大白话解释(取自 GLOSSARY,或直接给 tip)。 */
export function Term({ children, tip }: { children: string; tip?: string }) {
const text = tip || GLOSSARY[children];
if (!text) return <>{children}</>;
return (
<span className="cursor-help border-b border-dotted border-muted/60" title={text}>{children}</span>
);
return <Tip tip={text} className="cursor-help border-b border-dotted border-muted/60">{children}</Tip>;
}
/**
......@@ -377,7 +431,6 @@ export function PageShell({ title, desc, actions, toolbar, aside, asideWidth = 7
<div className="flex flex-wrap items-start gap-3">
<div className="min-w-0 flex-1">
{title && <h2 className="truncate text-section font-semibold">{title}</h2>}
{desc && <p className="mt-0.5 text-label text-muted">{desc}</p>}
</div>
{actions && <div className="flex shrink-0 flex-wrap items-center gap-2">{actions}</div>}
</div>
......
import { AlertTriangle, ExternalLink, ListChecks, ShieldCheck, Undo2, Zap } from "lucide-react";
import { PreviewView } from "@/features/actions/ActionParts";
import { useEffect, useState } from "react";
import { Badge, Spinner } from "@/components/ui";
import { go } from "@/lib/nav";
......@@ -13,6 +14,11 @@ const RISK_TONE: Record<string, string> = {
/** 动作预览:将调用哪些工具、改什么。审批人与提议人看到的是同一份预览。 */
export function EffectList({ preview }: { preview: ActionPreview }) {
return <PreviewView preview={preview} />;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function LegacyEffectList({ preview }: { preview: ActionPreview }) {
return (
<ul className="space-y-1.5">
{preview.auto && (
......
......@@ -21,10 +21,10 @@ import { DataTable } from "./DataTable";
import { buildGraph, traceSummary, type AgentNode, type ToolNode, type TraceState } from "./trace";
export const AGENT_STYLE: Record<string, { color: string; icon: React.ReactNode; label: string }> = {
lead: { color: "#6366f1", icon: <Brain className="h-3.5 w-3.5" />, label: "主 Agent" },
knowledge: { color: "#10b981", icon: <BookOpen className="h-3.5 w-3.5" />, label: "知识 Agent" },
data: { color: "#0ea5e9", icon: <Database className="h-3.5 w-3.5" />, label: "问数 Agent" },
action: { color: "#f43f5e", icon: <Zap className="h-3.5 w-3.5" />, label: "行动 Agent" },
lead: { color: "#6366f1", icon: <Brain className="h-3.5 w-3.5" />, label: "主持" },
knowledge: { color: "#10b981", icon: <BookOpen className="h-3.5 w-3.5" />, label: "查资料" },
data: { color: "#0ea5e9", icon: <Database className="h-3.5 w-3.5" />, label: "查数据" },
action: { color: "#f43f5e", icon: <Zap className="h-3.5 w-3.5" />, label: "给办法" },
};
const styleOf = (agent: string) => AGENT_STYLE[agent] || { color: "#64748b", icon: <CircleDot className="h-3.5 w-3.5" />, label: agent };
......@@ -175,7 +175,7 @@ export function TraceView({ trace, onOpenChunk }: { trace: TraceState; onOpenChu
const lead = trace.order.map((s) => trace.agents[s]).find((a) => a?.agent === "lead");
const subs = trace.order.map((s) => trace.agents[s]).filter((a) => a && a.agent !== "lead");
if (!lead && !subs.length && !trace.links) {
return <Empty icon={<Brain className="h-8 w-8" />} title="还没有推理过程" desc="提问后,这里会实时显示每个智能体在想什么、调了什么、看到了什么。" />;
return <Empty icon={<Brain className="h-8 w-8" />} title="提问后这里会显示过程" />;
}
return (
<div className="space-y-3">
......@@ -192,7 +192,7 @@ export function TraceView({ trace, onOpenChunk }: { trace: TraceState; onOpenChu
))}
{trace.links.time && <Badge tone="bg-ok/10 text-ok">时间:{trace.links.time.phrase || trace.links.time.ref}</Badge>}
{!trace.links.concepts.length && !trace.links.instances.length && !trace.links.time &&
<span className="text-label text-muted">没有直接命中本体概念,交给主 Agent 理解</span>}
<span className="text-label text-muted">没有直接对上已有的定义,按问题本身理解</span>}
</div>
</Section>
)}
......@@ -236,7 +236,7 @@ export function TraceView({ trace, onOpenChunk }: { trace: TraceState; onOpenChu
</div>
)}
{trace.reflect.map((r, i) => (
<Section key={i} icon={<RotateCw className="h-3.5 w-3.5" />} title="主 Agent 反思">
<Section key={i} icon={<RotateCw className="h-3.5 w-3.5" />} title="复查">
<p className="text-label">
{r.sufficient ? <span className="text-ok">✔ 信息足够,开始作答</span>
: <span className="text-warn">↻ 信息不足:{r.missing || "需要补充"},追加分派</span>}
......@@ -268,7 +268,7 @@ function AgentBlock({ a, trace, plan, onOpenChunk }: {
<span className="text-label font-semibold" style={{ color: st.color }}>{a.label || st.label}</span>
<StatusIcon status={a.status} />
{typeof a.confidence === "number" && a.status !== "running" && (
<span className="ml-auto flex items-center gap-1 text-caption text-muted" title="子 Agent 自评的把握">
<span className="ml-auto flex items-center gap-1 text-caption text-muted" title="对这一步结果的把握">
把握
<span className="h-1.5 w-12 overflow-hidden rounded-full bg-ink/10">
<span className="block h-full rounded-full" style={{ width: `${Math.round(a.confidence * 100)}%`, background: st.color }} />
......
......@@ -138,7 +138,7 @@ export function DataRefView({ d }: { d: DataRef }) {
<button className="btn btn-primary btn-sm" disabled={busy || !sql.trim()} onClick={() => void rerun()}>
{busy ? "执行中…" : "执行"}</button>
<button className="btn btn-sm" onClick={() => { setEditing(false); setSql(d.sql); setMine(null); setErr(""); }}>不改了</button>
<span className="text-caption text-muted">只能查询、只能查已发布对象绑定的表;改过又跑通的 SQL 会记下来供以后参考。</span>
<span className="text-caption text-muted">只能查询,不能改数据。</span>
</div>
{err && <p className="whitespace-pre-wrap rounded-md bg-bad/5 p-2 text-label text-bad">{err}</p>}
</div>
......
......@@ -6,7 +6,7 @@ import { go, useHashParams } from "@/lib/nav";
import type { ChunkRecord } from "@/lib/types";
import { errText, onto, type Turn } from "@/lib/onto";
import { streamSSE, type SSEHandle } from "@/lib/sse";
import { toast } from "@/store/useAppStore";
import { toast, loadFailed } from "@/store/useAppStore";
import { Welcome, TurnView } from "./AskTurn";
import { ConversationList } from "./ConversationList";
import { ReasoningPanel, type PanelTab } from "./ReasoningPanel";
......@@ -20,7 +20,7 @@ const newKey = () => `t${Date.now()}-${seq++}`;
function legacyTrace(t: Turn): { trace: TraceState; events: any[] } {
const events: any[] = [{ type: "link", ...t.links, ts: 0 }];
if (t.plan && Object.keys(t.plan).length) events.push({ type: "plan", span: "lead", ...t.plan, ts: 1 });
events.push({ type: "agent_start", span: "lead", agent: "lead", label: "主 Agent", task: t.question, ts: 1 });
events.push({ type: "agent_start", span: "lead", agent: "lead", label: "主持", task: t.question, ts: 1 });
t.steps.forEach((s: any, i: number) => {
const span = s.id || `s${i + 1}`;
events.push({ type: "tool_start", span, parent: "lead", agent: s.agent || "lead", tool: s.call, label: s.call,
......@@ -88,7 +88,7 @@ export function AskPage() {
const bottom = useRef<HTMLDivElement>(null);
const liveKey = useRef("");
const loadConvs = useCallback(() => { void onto.conversations().then((c) => setConvs(Array.isArray(c) ? c : [])).catch(() => setConvs([])); }, []);
const loadConvs = useCallback(() => { void onto.conversations().then((c) => setConvs(Array.isArray(c) ? c : [])).catch((e) => { setConvs([]); loadFailed(e); }); }, []);
useEffect(() => {
loadConvs();
// 示例问题和工作台同一份:按本体里真有的指标、维度、动作生成
......@@ -287,9 +287,9 @@ export function AskPage() {
<div className="flex items-center justify-end gap-2 pb-2">
<button className="btn btn-ghost btn-sm lg:hidden" onClick={newConv}><MessageSquarePlus className="h-3.5 w-3.5" /> 新对话</button>
<button className="btn btn-ghost btn-sm text-muted" onClick={() => (showPanel ? closePanel() : openPanel())}
title={showPanel ? "收起推理面板" : "展开推理面板:推理链、本体图谱、取数"}>
title={showPanel ? "收起右边的过程" : "看这个答案是怎么得出来的"}>
{showPanel ? <PanelRightClose className="h-4 w-4" /> : <PanelRightOpen className="h-4 w-4" />}
{showPanel ? "收起推理面板" : "推理面板"}
{showPanel ? "收起" : "看过程"}
</button>
</div>
<div className="min-h-0 flex-1 overflow-auto pr-1">
......
......@@ -16,14 +16,14 @@ import type { LiveTurn } from "./askTypes";
export function Welcome({ examples, onAsk }: { examples: string[]; onAsk: (q: string) => void }) {
const cards = [
{ icon: <BookOpen className="h-4 w-4" />, color: "#10b981", title: "知识 Agent", desc: "查口径与规则原文,沿知识图谱多跳推理,做影响分析" },
{ icon: <Database className="h-4 w-4" />, color: "#0ea5e9", title: "问数 Agent", desc: "实时取数,发现异常并自动下钻,每个数字可追溯到 SQL" },
{ icon: <Zap className="h-4 w-4" />, color: "#f43f5e", title: "行动 Agent", desc: "把结论变成可提交审批的动作与可运行的流程卡" },
{ icon: <BookOpen className="h-4 w-4" />, color: "#10b981", title: "查资料", desc: "指标怎么算、规则怎么定,从业务文档里找原文" },
{ icon: <Database className="h-4 w-4" />, color: "#0ea5e9", title: "查数据", desc: "现在的数是多少,按不同维度拆开看" },
{ icon: <Zap className="h-4 w-4" />, color: "#f43f5e", title: "给办法", desc: "该做什么动作、跑哪张流程卡,核对后一键发起" },
];
return (
<div className="mx-auto mt-6 max-w-2xl">
<Empty icon={<Sparkles className="h-10 w-10" />} title="问知识、问数据、问怎么办"
desc="主 Agent 先把问题对应到本体,再分派给知识、问数、行动三个智能体并行处理;每一步想了什么、查了什么都在右侧实时可见。系统会记住答得好的问题,越用越快、越用越准。" />
/>
<div className="mt-1 grid gap-2 sm:grid-cols-3">
{cards.map((c) => (
<div key={c.title} className="rounded-xl border border-line bg-surface p-3">
......@@ -227,7 +227,7 @@ function Feedback({ turnId, question, initial }: { turnId: string; question: str
<Workflow className="h-3.5 w-3.5" /> 做成流程卡
</button>
<Modal open={open} onClose={() => setOpen(false)} title="这个回答哪里不对?"
desc="你的纠正会进入审核,采纳后系统会学会:更新口径与同义词、以后不再参考这次的答法,并加入回归评测。"
desc="会交给管理员确认,确认后系统以后按正确的答"
footer={<>
<button className="btn" onClick={() => setOpen(false)}>取消</button>
<button className="btn btn-primary" disabled={!comment.trim()} onClick={() => {
......
......@@ -20,13 +20,13 @@ export function ReasoningPanel({ turn: sel, wide, tab, onTab, onClose, onToggleR
wide ? "w-[420px] shrink-0" : "fixed inset-y-2 right-2 z-50 w-[min(440px,94vw)] animate-fade-up")}>
<div className="flex items-center gap-2 border-b border-line px-3 py-2">
<Brain className="h-4 w-4 text-brand" />
<span className="text-body font-semibold">推理过程</span>
<span className="text-title font-semibold">怎么得出来的</span>
{sel?.replaying && <Badge tone="bg-warn/10 text-warn">回放中</Badge>}
<div className="ml-auto flex items-center gap-1">
{sel && sel.status !== "running" && sel.events.length > 0 && (
<button className="btn btn-ghost btn-sm" onClick={onToggleReplay}
title="按原节奏重播这一轮的推理过程">
<History className="h-3.5 w-3.5" /> {sel.replaying ? "停止回放" : "演示回放"}
<History className="h-3.5 w-3.5" /> {sel.replaying ? "停止" : "重放一遍"}
</button>
)}
<button className="btn btn-ghost btn-sm" onClick={onClose} aria-label="收起推理面板"><PanelRightClose className="h-4 w-4" /></button>
......@@ -41,7 +41,7 @@ export function ReasoningPanel({ turn: sel, wide, tab, onTab, onClose, onToggleR
]} />
</div>
<div className={cn("min-h-0 flex-1", tab === "graph" ? "overflow-hidden" : "overflow-auto p-3")}>
{!sel ? <Empty icon={<Brain className="h-8 w-8" />} title="还没有提问" desc="提问后,这里实时显示每个智能体的思考、调用与发现。" />
{!sel ? <Empty icon={<Brain className="h-8 w-8" />} title="还没有提问" />
: tab === "chain" ? <TraceView trace={sel.trace} onOpenChunk={onOpenChunk} />
: tab === "graph" ? <GraphView trace={sel.trace} /> : <DataView trace={sel.trace} />}
</div>
......
......@@ -6,7 +6,7 @@ import { toast } from "@/store/useAppStore";
const EVENT_GROUPS: [string, string][] = [
["", "全部"], ["action", "动作"], ["review", "审核"], ["concept", "概念"], ["ontology", "本体发布"],
["binding", "绑定"], ["sop", "SOP"], ["task", "任务"], ["object", "对象写回"], ["capability", "能力"],
["binding", "绑定"], ["sop", "流程卡"], ["task", "任务"], ["object", "对象写回"], ["capability", "能力"],
["ask", "提问"], ["eval", "评测"], ["mcp", "MCP"], ["user", "用户"],
];
const ACTOR_TONE: Record<string, string> = { user: "bg-ink/5 text-muted", ai: "bg-brand/10 text-brand", system: "bg-brand2/10 text-brand2" };
......
......@@ -7,18 +7,16 @@ import { cn } from "@/lib/utils";
import { confirmDialog } from "@/lib/dialog";
import { toast } from "@/store/useAppStore";
type Tab = "endpoint" | "builtin";
const RISK_TONE: Record<string, string> = { low: "bg-ok/10 text-ok", medium: "bg-warn/10 text-warn", high: "bg-bad/10 text-bad" };
/**
* 外部系统 / API(数据连接页的一个页签):动作通过 webhook.call 回写外部系统、模型推理函数调用推理服务时用的
* 外部端点(地址 + 加密凭据),以及系统内置函数与效果的参考清单。
* 外部端点(地址 + 加密凭据)。
* 动作、AI 分析函数已经是本体元素,在「动作类型」「函数类型」里编辑。
*/
export function CapabilityPage({ me }: { me: Me | null }) {
const params = useHashParams();
const canEdit = !!me?.permissions.includes("build");
const [tab, setTab] = useState<Tab>("endpoint");
const [cat, setCat] = useState<{ functions: FunctionBrief[]; tools: ToolBrief[]; defs: CapDef[] } | null>(null);
const [sel, setSel] = useState<string>(params.get("id") || "");
const load = useCallback(() => { void onto.catalog().then(setCat).catch((e) => toast("error", errText(e))); }, []);
......@@ -27,14 +25,12 @@ export function CapabilityPage({ me }: { me: Me | null }) {
const defs = cat.defs.filter((d) => d.kind === "endpoint");
return (
<div className="space-y-4">
<Segmented value={tab} onChange={(t) => { setTab(t); setSel(""); }} options={[
{ key: "endpoint", label: "外部端点" }, { key: "builtin", label: "系统函数与效果(参考)" }]} />
{tab === "builtin" ? <Builtins cat={cat} /> : (
{(
<div className="grid gap-4 lg:grid-cols-[280px_minmax(0,1fr)]">
<Card className="self-start">
<CardHeader title="外部端点" right={canEdit && <button className="btn btn-sm" onClick={() => setSel("new")}><Plus className="h-3.5 w-3.5" />新建</button>} />
<div className="divide-y divide-line">
{!defs.length && <Empty title="还没有外部端点" desc="动作要通知企业微信、调用 ERP 之类的外部系统时,在这里登记地址与凭据。" />}
{!defs.length && <Empty title="还没有外部端点" />}
{defs.map((d) => (
<button key={d.id} onClick={() => setSel(d.id)}
className={cn("block w-full px-3 py-2 text-left hover:bg-ink/[0.03]", sel === d.id && "bg-brand/5")}>
......@@ -58,55 +54,6 @@ export function CapabilityPage({ me }: { me: Me | null }) {
);
}
function Builtins({ cat }: { cat: { functions: FunctionBrief[]; tools: ToolBrief[] } }) {
const [open, setOpen] = useState("");
const [args, setArgs] = useState("{}");
const [out, setOut] = useState<any>(null);
return (
<div className="grid gap-4 xl:grid-cols-2">
<Card>
<CardHeader title={<span className="flex items-center gap-1.5"><Wrench className="h-4 w-4" />函数(只读)</span>}
desc="AI、SOP、技能都能直接调用。没有副作用。" />
<div className="divide-y divide-line">
{cat.functions.map((f) => (
<div key={f.name} className="px-4 py-2.5">
<button className="w-full text-left" onClick={() => { setOpen(open === f.name ? "" : f.name); setOut(null); setArgs("{}"); }}>
<p className="text-body font-medium">{f.title} <code className="ml-1 text-caption text-muted">{f.name}</code></p>
<p className="text-label text-muted">{f.description}</p>
</button>
{open === f.name && (
<div className="mt-2 space-y-2">
<p className="text-caption text-muted">参数:{Object.entries(f.input_schema.properties || {}).map(([k, v]: any) =>
`${k}${(f.input_schema.required || []).includes(k) ? "*" : ""}(${v.description || v.type})`).join(";")}</p>
<textarea className="input min-h-[60px] font-mono text-label" value={args} onChange={(e) => setArgs(e.target.value)} />
<button className="btn btn-sm" onClick={async () => {
try { setOut(await onto.callFunction(f.name, JSON.parse(args || "{}"))); } catch (e) { setOut({ error: errText(e) }); }
}}><Play className="h-3.5 w-3.5" />试调用</button>
{out && <pre className="max-h-64 overflow-auto rounded bg-ink/5 p-2 text-caption">{JSON.stringify(out, null, 2)}</pre>}
</div>
)}
</div>
))}
</div>
</Card>
<Card className="self-start">
<CardHeader title={<span className="flex items-center gap-1.5"><Zap className="h-4 w-4" />工具(有副作用)</span>}
desc="只能被经过人工审批的动作调用,AI 与 SOP 不能直接用。" />
<div className="divide-y divide-line">
{cat.tools.map((t) => (
<div key={t.name} className="px-4 py-2.5">
<p className="flex items-center gap-2 text-body font-medium">{t.title} <code className="text-caption text-muted">{t.name}</code>
<Badge tone={RISK_TONE[t.risk_level]}>{t.risk_level}</Badge>
{t.reversible && <Badge>可撤销</Badge>}{t.external && <Badge tone="bg-bad/10 text-bad">外部</Badge>}</p>
<p className="text-label text-muted">{t.description}</p>
</div>
))}
</div>
</Card>
</div>
);
}
function EndpointEditor({ def, canEdit, onSaved, onDeleted }: {
def: CapDef | null; canEdit: boolean; onSaved: (id: string) => void; onDeleted: () => void;
}) {
......@@ -152,7 +99,7 @@ function EndpointEditor({ def, canEdit, onSaved, onDeleted }: {
<Field label="方法"><select className="input" value={spec.method} disabled={!canEdit} onChange={(e) => set("method", e.target.value)}>
{["POST", "PUT", "PATCH"].map((m) => <option key={m}>{m}</option>)}</select></Field>
</div>
<Field label="凭据请求头(JSON)" hint="加密保存、永不回显、AI 看不到。留空表示不修改">
<Field label="凭据请求头(JSON)" hint="加密保存;不填就不改">
<textarea className="input min-h-[60px] font-mono text-label" value={secret} disabled={!canEdit} placeholder='{"Authorization": "Bearer ..."}'
onChange={(e) => setSecret(e.target.value)} />
</Field>
......
......@@ -7,7 +7,7 @@ import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { api, ApiError } from "@/lib/api";
import { cn, formatBytes, formatTime, shortHeading, STATUS_TEXT, STATUS_TONE } from "@/lib/utils";
import { toast } from "@/store/useAppStore";
import { toast, loadFailed } from "@/store/useAppStore";
import { Badge, Card, CardHeader, Confirm, Empty, ErrorNote, Modal, Progress, Skeleton } from "@/components/ui";
import type { ChunkRecord, DocumentItem } from "@/lib/types";
import { useJobStream } from "./useJobStream";
......@@ -139,7 +139,7 @@ export function DocumentsPage({ onExtracted }: { onExtracted?: () => void }) {
)}
{docs?.length === 0 && (
<Empty icon={<FileText className="h-8 w-8" />} title="还没有文档"
desc="上传一份业务文档(md / txt / pdf / docx / xlsx / pptx / csv / html),系统会抽取实体与关系并建成图谱。"
desc="支持 md、txt、pdf、docx、xlsx、pptx、csv、html"
action={<button className="btn btn-primary btn-sm" onClick={() => setShowUpload(true)}>
<Upload className="h-3.5 w-3.5" />上传文档</button>} />
)}
......@@ -368,7 +368,7 @@ function JobCard({ doc, job, onClose }: {
{quality && (
<div className="grid grid-cols-2 gap-2 rounded-lg border border-line bg-elevated p-2.5 text-xs sm:grid-cols-4">
<QualityStat label="片段数" value={quality.chunks} hint={`平均 ${quality.avg_chunk_tokens} token`} />
<QualityStat label="LLM 调用" value={quality.llm_calls} />
<QualityStat label="模型调用" value={quality.llm_calls} />
<QualityStat label="过滤噪声实体" value={quality.dropped_noise} />
<QualityStat label="消歧合并" value={quality.resolve?.merged ?? 0}
hint={`候选 ${quality.resolve?.candidates ?? 0} 组`} />
......@@ -426,7 +426,7 @@ function DocDetailModal({ doc, onClose }: { doc: DocumentItem | null; onClose: (
useEffect(() => {
if (!doc) { setChunks(null); setEntities(null); setContent(null); setContentError(null); return; }
setTab("preview");
void api.documentChunks(doc.id).then((r) => setChunks(r.chunks)).catch(() => setChunks([]));
void api.documentChunks(doc.id).then((r) => setChunks(r.chunks)).catch((e) => { setChunks([]); loadFailed(e); });
void api.documentEntities(doc.id).then(setEntities).catch(() => undefined);
}, [doc]);
......
......@@ -155,7 +155,7 @@ function CaseModal({ c, suite, onClose, onDone }: { c: EvalCase | null; suite: s
{Object.entries(KIND_LABEL).map(([k, l]) => <option key={k} value={k}>{l}</option>)}</select></Field>
</div>
<Field label="问题" required><input className="input" value={v.question} onChange={(e) => setV({ ...v, question: e.target.value })} /></Field>
<Field label="参考答案要点(给大模型裁判)"><textarea className="input" value={v.expected} onChange={(e) => setV({ ...v, expected: e.target.value })} /></Field>
<Field label="参考答案要点(评分时对照)"><textarea className="input" value={v.expected} onChange={(e) => setV({ ...v, expected: e.target.value })} /></Field>
<Field label="答案必须包含的关键词(逗号分隔)"><input className="input" value={v.must_include} onChange={(e) => setV({ ...v, must_include: e.target.value })} /></Field>
<div className="grid grid-cols-2 gap-3">
<Field label="期望调用的函数"><input className="input" value={v.expected_calls} onChange={(e) => setV({ ...v, expected_calls: e.target.value })} placeholder="metric.query" /></Field>
......
......@@ -58,7 +58,7 @@ export function DuplicatesPanel({ onMerged }: { onMerged: () => void }) {
if (!visible.length) {
return (
<Empty icon={<Merge className="h-8 w-8" />} title="没有发现疑似重复实体"
desc="抽取时已经做过自动消歧。新增文档后可以再来复查一次。"
action={<button className="btn btn-sm" onClick={load}>
<RefreshCw className="h-3.5 w-3.5" />重新检测</button>} />
);
......
......@@ -69,7 +69,7 @@ export function FilterPanel({ stats, documents, filters, onChange, communities,
{stats && stats.leaf > 0 && (
<p className="mt-1 text-caption text-muted">
当前图里有 <b className="tabular-nums">{stats.leaf}</b> 个度=1 的叶子节点
({(stats.leaf_ratio * 100).toFixed(0)}%),调到 ≥2 可以先看骨架。
({(stats.leaf_ratio * 100).toFixed(0)}%),调到 2 以上可以先看主干。
</p>
)}
</div>
......
......@@ -121,7 +121,7 @@ export function GraphEditor({ open, kind, onto, onClose, onSaved }: {
return (
<Modal open={open} onClose={onClose}
title={kind === "node" ? "新增节点" : "新增关系"}
desc="人工内容会用「人工」徽标区分,参与深挖检索但不会产生原文引用"
footer={
<>
<button className="btn" onClick={onClose}><X className="h-3.5 w-3.5" />取消</button>
......
......@@ -77,7 +77,7 @@ export function PropertyPanel({ selection, entityTypes, onSelect, onExpand, onCh
<Empty
icon={<Maximize2 className="h-8 w-8" />}
title="点击节点或关系查看详情"
desc="悬停会高亮它的邻居;双击节点可以展开它的邻域;拖拽可以调整位置。按 / 打开搜索。"
/>
);
}
......
......@@ -8,7 +8,7 @@ import { setCurrentWorkspace } from "@/lib/identity";
import { go } from "@/lib/nav";
import { errText, fmtTime, onto, type HomeOverview, type Me, type WorkspaceRec } from "@/lib/onto";
import { cn } from "@/lib/utils";
import { toast } from "@/store/useAppStore";
import { toast, loadFailed } from "@/store/useAppStore";
const ASSETS: { key: keyof WorkspaceRec["counts"]; label: string; page: string; icon: React.ReactNode; color: string }[] = [
{ key: "object_type", label: "对象类型", page: "b_object", icon: <Boxes className="h-4 w-4" />, color: "#6366f1" },
......@@ -18,7 +18,6 @@ const ASSETS: { key: keyof WorkspaceRec["counts"]; label: string; page: string;
{ key: "sop", label: "流程卡", page: "sop", icon: <ListChecks className="h-4 w-4" />, color: "#10b981" },
];
const CAPS = [
{ page: "pipeline", title: "数据同步", tag: "集成", desc: "同步对象的主键和关系,支撑对象搜索与影响分析", icon: <Workflow className="h-4 w-4" /> },
{ page: "canvas", title: "本体画布", tag: "建模", desc: "对象、关系、函数、动作同图管理", icon: <LayoutGrid className="h-4 w-4" /> },
{ page: "b_object", title: "对象", tag: "建模", desc: "实体 · 属性 · 映射到数据表", icon: <Boxes className="h-4 w-4" /> },
{ page: "monitor", title: "运行总览", tag: "运行", desc: "调用记录、MCP 接入、审计与模型成本", icon: <Bot className="h-4 w-4" /> },
......@@ -35,7 +34,7 @@ export function HomePage({ me }: { me: Me | null }) {
const [home, setHome] = useState<HomeOverview | null>(null);
const [creating, setCreating] = useState(false);
const load = useCallback(() => {
void onto.workspaces().then(setList).catch(() => setList([]));
void onto.workspaces().then(setList).catch((e) => { setList([]); loadFailed(e); });
void onto.home().then(setHome).catch((e) => toast("error", "加载失败", errText(e)));
}, []);
useEffect(load, [load]);
......@@ -109,22 +108,22 @@ export function HomePage({ me }: { me: Me | null }) {
<span className="mt-0.5 grid h-5 w-5 shrink-0 place-items-center rounded-full bg-brand/10 text-caption font-semibold text-brand">{i + 1}</span>
<span className="min-w-0"><span className="block text-label font-medium">{s.title}</span><span className="block text-caption text-muted">{s.hint}</span></span>
</button>
)) : <p className="px-2 py-3 text-label text-muted">一切就绪。可以去「提问」,或在「MCP 服务」把本体接给你的 AI 助手。</p>}
)) : <p className="px-2 py-3 text-label text-muted">都准备好了,可以去「提问」试试。</p>}
</div>
</Card>
<Card className="grid grid-cols-2 gap-3 p-4 text-label">
<button className="text-left" onClick={() => go("inbox")}><p className="text-muted">待审批动作</p><p className="text-page font-semibold">{home?.pending_approvals ?? "-"}</p></button>
<button className="text-left" onClick={() => go("modeling")}><p className="text-muted">待审核草案</p><p className="text-page font-semibold">{home?.pending_reviews ?? "-"}</p></button>
<button className="text-left" onClick={() => go("modeling")}><p className="text-muted">AI 建模待定草案</p><p className="text-page font-semibold">{home?.modeling_drafts ?? "-"}</p></button>
<button className="text-left" onClick={() => go("data")}><p className="text-muted">数据连接</p><p className="text-page font-semibold">{home?.datasources ?? "-"}</p></button>
<button className="text-left" onClick={() => go("pipeline")}><p className="text-muted">数据管道</p><p className="text-page font-semibold">{home?.pipelines.total ?? "-"}</p>
<p className="text-caption text-muted">{home?.pipelines.last_run_at ? `同步于 ${fmtTime(home.pipelines.last_run_at)}` : "未同步"}</p></button>
<div title="对象之间的关系索引,发布后和每小时自动刷新"><p className="text-muted">关系索引</p><p className="text-page font-semibold">{home?.pipelines.total ?? "-"}</p>
<p className="text-caption text-muted">{home?.pipelines.last_run_at ? `刷新于 ${fmtTime(home.pipelines.last_run_at)}` : "未刷新"}</p></div>
</Card>
</div>
</div>
<Card>
<CardHeader title={<span className="flex items-center gap-2"><Blocks className="h-4 w-4" />全部本体 · {list?.length ?? 0}</span>}
desc="一个行业 / 业务域一套本体;对象、指标、版本、动作、审计、数据连接都按本体隔离"
right={canBuild && <button className="btn btn-primary btn-sm" onClick={() => setCreating(true)}><Plus className="h-3.5 w-3.5" />新建本体</button>} />
<div className="grid gap-3 p-4 sm:grid-cols-2 xl:grid-cols-3">
{!list ? <Spinner /> : list.map((w) => (
......@@ -166,7 +165,7 @@ function NewWorkspace({ onClose, onDone }: { onClose: () => void; onDone: (id: s
<div className="space-y-3">
<div className="grid gap-3 sm:grid-cols-2">
<Field label="名称" required><input className="input" placeholder="如:半导体高端制造" value={f.display_name} onChange={(e) => setF({ ...f, display_name: e.target.value })} /></Field>
<Field label="标识" hint="可不填,系统自动生成;填的话用小写字母开头的字母数字下划线"><input className="input font-mono" placeholder="自动生成" value={f.id}
<Field label="标识" hint="不填会自动生成"><input className="input font-mono" placeholder="自动生成" value={f.id}
onChange={(e) => setF({ ...f, id: e.target.value.toLowerCase() })} /></Field>
</div>
<Field label="行业"><input className="input" placeholder="制造 / 零售 / 金融 / 医药…" value={f.industry} onChange={(e) => setF({ ...f, industry: e.target.value })} /></Field>
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!