builtins.py 17.1 KB
"""内置函数(只读)与工具(有副作用)。

函数的 input_schema 用 JSON-Schema 的子集(properties / required / type / enum / description),
编排层把它原样给大模型看,MCP 也原样暴露出去。
"""
from __future__ import annotations

import datetime as dt
import logging
from typing import Any

import requests
from fastapi import HTTPException

from ..core import identity
from ..core.dbx import jload
from ..governance import notify
from ..kernel import calendar as cal
from ..kernel import metrics, objects, rules, service
from .registry import Emit, function, tool

log = logging.getLogger(__name__)


def _s(desc: str, **kw) -> dict:
    return {"type": "string", "description": desc, **kw}


# =====================================================================
# 函数(只读)
# =====================================================================
@function("knowledge.search", "检索知识", "在文档知识图谱里多跳检索,返回相关原文片段、实体与关系。"
          "适合回答定义、规则原文、流程说明、为什么这类问题。",
          {"type": "object", "properties": {
              "query": _s("检索问题,用完整的自然语言"),
              "concepts": {"type": "array", "description": "已识别的相关概念名,帮助定位"}},
           "required": ["query"]}, category="knowledge",
          output_desc="chunks[{id,heading,text}]、entities、relations")
def knowledge_search(args: dict, emit: Emit | None) -> dict:
    from ..api import deps
    from ..retrieve.engine import run_query
    result: dict = {}
    for ev in run_query(args["query"], deps.graph(), deps.index(), deps.communities(),
                        mode="agentic", answer=False,
                        seeds_hint=[str(x) for x in args.get("concepts") or []]):
        if ev.get("type") == "retrieved":
            result = ev
        elif emit and ev.get("type") in ("understand", "link", "hop", "evidence", "reflect", "community"):
            emit(ev)
    chunks = result.get("chunks") or []
    return {"chunks": chunks, "entities": result.get("entities") or [],
            "relations": result.get("relations") or [], "subgraph": result.get("subgraph"),
            "summary": f"命中 {len(chunks)} 个原文片段"}


@function("concept.lookup", "查概念定义", "查本体里某个概念(指标、规则、周期、对象类型、流程等)的定义、口径与出处。"
          "问「X 是什么 / 怎么算 / 口径是什么」时优先用它。",
          {"type": "object", "properties": {"name": _s("概念名称或别名")}, "required": ["name"]},
          category="knowledge", output_desc="概念定义 + spec + 出处")
def concept_lookup(args: dict, emit: Emit | None) -> dict:
    c = service.rt_find(args["name"])
    if c is None:
        return {"found": False, "summary": f"本体中没有「{args['name']}」"}
    ev = service.evidence_for([c["id"]]).get(c["id"], [])[:5]
    return {"found": True, "concept": {k: c.get(k) for k in
                                       ("id", "kind", "kind_label", "name", "description",
                                        "synonyms", "spec")},
            "evidence": ev, "summary": f"{c.get('kind_label', c['kind'])}「{c['name']}」"}


@function("metric.query", "指标取数", "按已发布指标的定义确定性地取数(不让模型写 SQL)。"
          "可按维度拆分、按维度值过滤、按时间(current/last/YYYY-MM 或 {start,end})过滤、按单个对象取值。",
          {"type": "object", "properties": {
              "metric": _s("指标名称"),
              "dimensions": {"type": "array", "description": "拆分维度名列表"},
              "filters": {"type": "object", "description": "{维度名: 值或值列表}"},
              "time": {"type": ["string", "object"], "description": "current / last / YYYY-MM / {start,end}"},
              "object_key": _s("只取某个对象的值时填对象主键"),
              "calendar": _s("按哪个统计周期解析时间,不填用指标默认"),
              "limit": {"type": "integer"}},
           "required": ["metric"]}, category="data",
          output_desc="columns/rows/value/period/sql/run_id")
def metric_query(args: dict, emit: Emit | None) -> dict:
    r = metrics.query(args["metric"], dimensions=args.get("dimensions") or [],
                      filters=args.get("filters") or {}, time=args.get("time"),
                      object_key=str(args.get("object_key") or ""),
                      calendar_ref=args.get("calendar") or "",
                      limit=int(args.get("limit") or 200))
    if emit:
        emit({"type": "sql", "sql": r["sql"], "run_id": r["run_id"]})
        emit({"type": "rows", "columns": r["columns"], "rows": r["rows"][:200]})
    r["summary"] = (f"{r['metric']['name']} = {r['value']}{r['metric']['unit']}"
                    if r["value"] is not None else f"{r['metric']['name']} 共 {len(r['rows'])} 行")
    return r


def default_ds_id() -> int:
    from ..text2sql import semantic
    items = semantic.list_datasources()
    if not items:
        raise HTTPException(422, "还没有接入任何数据源")
    return int(items[0]["id"])


@function("sql.free", "自由取数", "指标覆盖不到时,让模型基于数据源语义模型生成只读 SQL 取数(有校验与自愈)。"
          "能用 metric.query 时不要用它。",
          {"type": "object", "properties": {
              "question": _s("取数需求,用完整自然语言,把时间、对象、口径都写清楚"),
              "ds_id": {"type": "integer", "description": "数据源编号,不填用默认"}},
           "required": ["question"]}, category="data", output_desc="sql/columns/rows/run_id")
def sql_free(args: dict, emit: Emit | None) -> dict:
    from ..text2sql.pipeline import run_ask
    ds_id = int(args.get("ds_id") or default_ds_id())
    out: dict[str, Any] = {"ds_id": ds_id, "columns": [], "rows": []}
    for ev in run_ask(ds_id, args["question"], summarize=False):
        t = ev.get("type")
        if t == "rows":
            out["columns"], out["rows"] = ev["columns"], ev["rows"]
        elif t == "execute":
            out["sql"] = ev.get("sql")
        elif t == "plan":
            out["plan"] = ev.get("plan")
            out["calibre"] = ev.get("calibre")
        elif t == "answer":
            out["answer"] = ev.get("text")
        elif t == "error":
            out["error"] = ev.get("error")
        elif t == "done":
            out["run_id"] = ev.get("run_id") or 0
            out["outcome"] = ev.get("outcome")
            if ev.get("clarify"):
                out["clarify"] = ev["clarify"]
        if emit and t in ("plan", "sql_draft", "validate", "repair", "execute", "rows", "error"):
            emit(ev)
    if out.get("error") and not out["rows"]:
        raise HTTPException(422, f"取数失败:{out['error']}")
    out["summary"] = f"返回 {len(out['rows'])} 行"
    return out


@function("object.get", "查对象", "读取一个对象实例的全部属性(业务库 + 写回层)。",
          {"type": "object", "properties": {"object_type": _s("对象类型名"),
                                            "key": _s("对象主键")},
           "required": ["object_type", "key"]}, category="data")
def object_get(args: dict, emit: Emit | None) -> dict:
    o = objects.get(args["object_type"], str(args["key"]))
    o["summary"] = f"{o['type_name']}「{o['label']}」"
    return o


@function("object.search", "找对象", "按名称模糊查找对象实例。",
          {"type": "object", "properties": {"object_type": _s("对象类型名"), "q": _s("关键词"),
                                            "limit": {"type": "integer"}},
           "required": ["object_type"]}, category="data")
def object_search(args: dict, emit: Emit | None) -> dict:
    items = objects.search(args["object_type"], str(args.get("q") or ""),
                           int(args.get("limit") or 20))
    return {"items": items, "summary": f"找到 {len(items)} 个"}


@function("object.linked", "查关联对象", "按本体里的关系类型查某个对象的关联对象。",
          {"type": "object", "properties": {"object_type": _s("对象类型名"), "key": _s("对象主键")},
           "required": ["object_type", "key"]}, category="data")
def object_linked(args: dict, emit: Emit | None) -> dict:
    groups = objects.linked(args["object_type"], str(args["key"]))
    return {"groups": groups, "summary": f"{len(groups)} 组关联"}


@function("rule.eval", "规则求值", "用本体里的规则(口径/判定/计算)对给定变量求值。",
          {"type": "object", "properties": {"rule": _s("规则名称"),
                                            "vars": {"type": "object", "description": "{变量名: 值}"}},
           "required": ["rule"]}, category="logic")
def rule_eval(args: dict, emit: Emit | None) -> dict:
    r = service.rt_find(args["rule"], "rule")
    if r is None:
        raise HTTPException(404, f"找不到已发布的规则「{args['rule']}」")
    expr = (r.get("spec") or {}).get("expression") or ""
    if not expr:
        return {"rule": r["name"], "result": None, "text": (r.get("spec") or {}).get("text", ""),
                "summary": "该规则只有文字描述,没有可求值表达式"}
    try:
        val = rules.evaluate(expr, args.get("vars") or {})
    except rules.RuleError as e:
        raise HTTPException(422, f"规则求值失败:{e}") from e
    return {"rule": r["name"], "expression": expr, "result": val,
            "summary": f"{r['name']} → {val}"}


@function("calendar.resolve", "解析周期", "把「本期 / 上期 / 某年某月」按统计周期定义解析成起止日期。",
          {"type": "object", "properties": {"calendar": _s("统计周期名称,不填为自然月"),
                                            "ref": _s("current / last / prev:N / YYYY-MM / YYYY-MM-DD")},
           "required": []}, category="logic")
def calendar_resolve(args: dict, emit: Emit | None) -> dict:
    spec = None
    if args.get("calendar"):
        c = service.rt_find(args["calendar"], "calendar")
        if c is None:
            raise HTTPException(404, f"找不到已发布的统计周期「{args['calendar']}」")
        spec = c.get("spec")
    r = cal.resolve(spec, str(args.get("ref") or "current"))
    r["summary"] = f"{r['period']}:{r['start']} ~ {r['end']}"
    return r


@function("ontology.overview", "本体概览", "列出本体里有哪些对象类型、指标、规则、流程、动作,回答「能问什么 / 有哪些指标」。",
          {"type": "object", "properties": {"kind": _s("只看某类:object_type/metric/rule/calendar/role/process")},
           "required": []}, category="knowledge")
def ontology_overview(args: dict, emit: Emit | None) -> dict:
    kinds = [args["kind"]] if args.get("kind") else ["object_type", "metric", "rule", "calendar",
                                                      "role", "process"]
    out = {k: [{"name": c["name"], "description": c.get("description", "")[:80]}
               for c in service.rt_by_kind(k)][:80] for k in kinds}
    return {"concepts": out, "summary": "、".join(f"{k}:{len(v)}" for k, v in out.items())}


# =====================================================================
# 工具(有副作用,只能被审批通过的动作调用)
# =====================================================================
def _object_write_preview(args: dict) -> dict:
    ot = objects.object_type(args["object_type"])
    cur = objects.current_value(ot["id"], str(args["key"]), args["property"])
    return {"summary": f"把 {ot['name']}「{args['key']}」的「{args['property']}」从 "
                       f"{cur!r} 改为 {args.get('value')!r}",
            "changes": [{"object": f"{ot['name']}:{args['key']}", "property": args["property"],
                         "from": cur, "to": args.get("value")}]}


def _object_write_revert(args: dict, result: dict) -> None:
    if result.get("edit_id"):
        objects.revert_edit(int(result["edit_id"]))


@tool("object.write", "写回对象属性", "修改对象的可写属性(写在本系统写回层,业务库不动)。",
      {"type": "object", "properties": {"object_type": _s("对象类型"), "key": _s("对象主键"),
                                        "property": _s("属性名"), "value": {"description": "新值"}},
       "required": ["object_type", "key", "property"]},
      preview=_object_write_preview, revert=_object_write_revert, risk_level="medium")
def object_write(args: dict, ctx: dict) -> dict:
    e = objects.write(args["object_type"], str(args["key"]), args["property"], args.get("value"),
                      action_run_id=ctx.get("run_id", ""))
    return {"edit_id": e["id"], "from": e["prev"], "to": e["value"]}


def _task_preview(args: dict) -> dict:
    who = args.get("assignee") or f"角色「{args.get('role') or '未指定'}」"
    return {"summary": f"给 {who} 派发任务「{args.get('title')}」"
                       + (f",{args['due_hours']} 小时内完成" if args.get("due_hours") else ""),
            "changes": [{"task": args.get("title"), "assignee": who}]}


def _task_revert(args: dict, result: dict) -> None:
    from . import tasks
    if result.get("task_id"):
        tasks.cancel(result["task_id"], "动作已撤销")


@tool("task.create", "派发人工任务", "给某个角色或人派一项待办,可带表单与检查清单。",
      {"type": "object", "properties": {
          "title": _s("任务标题"), "description": _s("任务说明"),
          "role": _s("派给哪个角色"), "assignee": _s("派给具体用户 id"),
          "form": {"type": "array", "description": "[{name,label,type,required}]"},
          "checklist": {"type": "array", "description": "检查项列表"},
          "due_hours": {"type": "number"}, "object_ref": _s("关联对象 type:key")},
       "required": ["title"]},
      preview=_task_preview, revert=_task_revert, risk_level="low")
def task_create(args: dict, ctx: dict) -> dict:
    from . import tasks
    due = None
    if args.get("due_hours"):
        due = dt.datetime.now() + dt.timedelta(hours=float(args["due_hours"]))
    t = tasks.create(title=args["title"], description=args.get("description", ""),
                     role=args.get("role", ""), assignee=args.get("assignee", ""),
                     form=args.get("form") or [], checklist=args.get("checklist") or [],
                     due_at=due, object_ref=args.get("object_ref", ""),
                     source_type="action", source_id=ctx.get("run_id", ""),
                     context={"action_run": ctx.get("run_id", "")})
    return {"task_id": t["id"]}


def _notify_preview(args: dict) -> dict:
    return {"summary": f"给 {args.get('recipient')} 发站内通知「{args.get('title')}」",
            "changes": [{"notify": args.get("recipient"), "title": args.get("title")}]}


@tool("notify.send", "站内通知", "给用户或角色(role:角色名)发一条站内通知。",
      {"type": "object", "properties": {"recipient": _s("用户 id 或 role:角色名"),
                                        "title": _s("标题"), "body": _s("正文")},
       "required": ["recipient", "title"]},
      preview=_notify_preview, risk_level="low")
def notify_send(args: dict, ctx: dict) -> dict:
    nid = notify.send(args["recipient"], args["title"], args.get("body", ""),
                      link=f"#/inbox?run={ctx.get('run_id', '')}")
    return {"notification_id": nid}


def _endpoint(ref: str) -> dict:
    from . import defs
    ep = defs.find(ref, "endpoint")
    if ep is None or ep["status"] != "published":
        raise HTTPException(422, f"外部端点「{ref}」不存在或未发布")
    return ep


def _webhook_preview(args: dict) -> dict:
    ep = _endpoint(args["endpoint"])
    spec = ep["spec"]
    return {"summary": f"调用外部端点「{ep['display_name'] or ep['name']}」"
                       f"({spec.get('method', 'POST')} {spec.get('url', '')})",
            "changes": [{"external": ep["name"], "payload": args.get("payload")}],
            "external": True}


@tool("webhook.call", "调用外部系统", "调用在能力库里登记过的外部 HTTP 端点(凭据由系统保管)。",
      {"type": "object", "properties": {"endpoint": _s("端点名称"),
                                        "payload": {"type": "object", "description": "请求体"}},
       "required": ["endpoint"]},
      preview=_webhook_preview, risk_level="high", external=True)
def webhook_call(args: dict, ctx: dict) -> dict:
    from . import defs
    ep = _endpoint(args["endpoint"])
    spec = ep["spec"]
    secret = defs.endpoint_secret(ep["id"])
    headers = {"Content-Type": "application/json", **(jload(secret, {}) if secret else {}),
               "X-Onto-Action-Run": ctx.get("run_id", "")}
    resp = requests.request(spec.get("method", "POST"), spec["url"], json=args.get("payload") or {},
                            headers=headers, timeout=float(spec.get("timeout") or 15))
    body = resp.text[:2000]
    if resp.status_code >= 400:
        raise RuntimeError(f"外部端点返回 {resp.status_code}:{body[:300]}")
    return {"status": resp.status_code, "body": body}


def actor_label() -> str:
    a = identity.current()
    return a.name or a.id