pipeline.py 15.8 KB
"""数据问答的生成管线。

写法和 `retrieve/engine.py:run_query` 完全同构:同步生成器 yield 事件 dict,
由 `api/deps.py:sse()` 桥接成 SSE。前端复用同一套 trace 卡片渲染。

只用 2 次 LLM 主调用(计划 + SQL),不学 WrenAI 拆成 intent / reasoning / generation
三次往返 —— 那是三倍延迟换一点点边界情况的准确率,不划算。

事件序列:
  start → retrieve → plan →(clarify/metadata 在这里结束)
  → sql_delta* → sql_draft → validate →(失败则 repair → validate,最多 SQL_MAX_REPAIR 轮)
  → execute → rows → summary_delta* → summary → explain_delta* → explain → done

出场顺序就是用户关心的顺序:**先给结论,再给解释**。
解释(「这条 SQL 在做什么」)是审计用的,放在结论前面等于让用户多干等一轮。
"""
from __future__ import annotations
import logging
import time
import uuid
from typing import Iterator

from ..core import db as core_db
from ..core import llm
from . import executor, library, linker, prompts, semantic

log = logging.getLogger(__name__)

SUMMARY_ROWS = 20       # 送去做结论的行数上限。全量塞进去既贵又没用


def run_ask(ds_id: int, question: str, history: list[dict] | None = None,
            overrides: dict | None = None, thread_id: str = "",
            approved_plan: dict | None = None) -> Iterator[dict]:
    """主入口。`approved_plan` 非空表示用户已确认过计划,直接跳到生成 SQL。"""
    started = time.time()
    cfg = core_db.get_all_config()
    cfg.update({k: str(v) for k, v in (overrides or {}).items()})
    max_repair = int(cfg.get("SQL_MAX_REPAIR") or "2")
    require_plan = (cfg.get("SQL_REQUIRE_PLAN") or "0") == "1"
    thread_id = thread_id or uuid.uuid4().hex[:16]

    ds = semantic.get_datasource(ds_id)
    if ds is None:
        yield {"type": "error", "stage": "start", "error": f"数据源 {ds_id} 不存在"}
        yield _done(thread_id, "failed", started)
        return
    dialect = ds["ds_type"]

    yield {"type": "start", "thread_id": thread_id,
           "datasource": {"id": ds["id"], "name": ds["name"], "type": ds["ds_type"],
                          "database": ds["db_name"]}}

    # ---------- 1) 召回 ----------
    ctx = linker.retrieve(ds_id, question, overrides)
    if not ctx["models"]:
        yield {"type": "error", "stage": "retrieve",
               "error": "这个数据源还没有启用任何表。请先到建模页做一次内省,"
                        "然后勾选要参与问答的表。"}
        yield _done(thread_id, "failed", started)
        return

    schema = semantic.render_schema(ctx["models"], ctx["relations"], ctx["metrics"])
    yield {"type": "retrieve", **ctx["hits"],
           "schema_tokens": llm.count_tokens(schema), "flags": ctx["flags"]}

    # ---------- 2) 计划 ----------
    if approved_plan:
        plan = approved_plan
        yield {"type": "plan", "kind": "data_query", "plan": plan,
               "calibre": plan.get("calibre", ""), "approved": True}
    else:
        try:
            decision = llm.chat_json(prompts.build_plan_messages(
                question, schema, ctx["pairs"], ctx["instructions"], history))
        except Exception as e:  # noqa: BLE001
            yield {"type": "error", "stage": "plan", "error": f"生成查询计划失败:{str(e)[:300]}"}
            yield _done(thread_id, "failed", started)
            return
        if not isinstance(decision, dict):
            decision = {}
        kind = str(decision.get("kind") or "data_query")
        plan = decision.get("plan") if isinstance(decision.get("plan"), dict) else {}
        calibre = str(decision.get("calibre") or "")

        yield {"type": "plan", "kind": kind, "plan": plan, "calibre": calibre,
               "clarify": str(decision.get("clarify") or ""),
               "answer": str(decision.get("answer") or ""), "approved": False}

        if kind == "clarify":
            yield {"type": "done", "thread_id": thread_id, "outcome": "clarify",
                   "clarify": str(decision.get("clarify") or ""),
                   "duration_ms": int((time.time() - started) * 1000)}
            return
        if kind in ("metadata", "not_data"):
            # answer 必须跟着 done 一起出去。只发 plan 事件的话,前端把它当轨迹
            # 渲染掉,用户看到的是一张空卡片 —— 问「有哪些表」永远没有回答。
            answer = str(decision.get("answer") or "")
            if not answer and kind == "not_data":
                answer = "这个问题和已接入的业务数据没有关系,我只能回答能从这些表里查出来的问题。"
            yield {"type": "answer", "text": answer, "kind": kind}
            yield {"type": "done", "thread_id": thread_id, "outcome": kind,
                   "answer": answer,
                   "duration_ms": int((time.time() - started) * 1000)}
            return
        if require_plan:
            # 停在这里等用户确认或修改计划。前端拿着 plan 再调一次 /ask,
            # 带上 approved_plan 就会从生成 SQL 继续。
            yield {"type": "done", "thread_id": thread_id, "outcome": "await_plan",
                   "plan": plan, "duration_ms": int((time.time() - started) * 1000)}
            return

    # ---------- 3) 生成 SQL ----------
    out: dict = {}
    yield from _draft(prompts.build_sql_messages(
        question, schema, plan, ctx["pairs"], ctx["instructions"], dialect, ctx["flags"]),
        cfg, 1, out)
    if out.get("error"):
        yield {"type": "error", "stage": "sql_draft", "error": f"生成 SQL 失败:{out['error']}"}
        yield _done(thread_id, "failed", started)
        return
    sql = out.get("sql", "")
    first_sql = sql

    # ---------- 4) 校验 → 执行 → 自愈 ----------
    # 两种失败分开给预算:
    # - 报错类(校验不过 / 执行异常)用 SQL_MAX_REPAIR 轮;
    # - **空结果**额外给 1 轮。跑通但 0 行几乎总是过滤条件写错(时间区间算错、
    #   枚举值写错、关联过严),而模型被明确告知后多半能自己修好。
    #   实测踩过:模型把「最近一个完整月」写成了 >= '2026-08-01' AND < '2026-08-01'。
    #   这一轮不占报错预算,否则一个空结果会把自愈额度吃光。
    attempt = 1
    best: executor.ExecOutcome | None = None
    last_error = ""
    empty_retried = False
    error_repairs = 0

    while True:
        g = executor.validate(ds_id, sql, dialect)
        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)
            if outcome.ok:
                if not _is_blank(outcome.result):
                    best = outcome
                    break
                # 空结果:先留着兜底,再给一次自我修正的机会
                if best is None or not best.ok:
                    best = outcome
                if empty_retried or error_repairs > max_repair:
                    break
                empty_retried = True
                attempt += 1
                blank_kind = ("返回 0 行" if outcome.result.row_count == 0
                              else "只返回了一行,而且每一列都是 NULL(聚合函数没匹配到任何行时就是这样)")
                reason = (f"查询执行成功但{blank_kind}。这通常不是「没有数据」,"
                          "而是过滤条件写错了。请逐条检查:\n"
                          "1. **时间区间是不是空的**:上下界写成了同一个表达式"
                          "(例如 `>= DATE_FORMAT(MAX(d),'%Y-%m-01') AND < DATE_FORMAT(MAX(d),'%Y-%m-01')`)"
                          "时,区间恒为空。要么只写下界,要么把上界换成真正更大的那个值。\n"
                          "2. 枚举值写法对不对(品牌名一律用 LIKE 模糊匹配)。\n"
                          "3. 关联条件是不是过严。\n"
                          "修正后重新输出;如果确认业务上就是没有数据,可以放宽条件再试一次。")
                last_error = reason
                yield {"type": "repair", "attempt": attempt, "reason": reason, "kind": "empty"}
                yield from _draft(prompts.build_repair_messages(
                    question, schema, g.sql, reason, dialect), cfg, attempt, out)
                if out.get("error"):
                    break
                sql = out.get("sql", "")
                continue

            last_error = outcome.error
            if outcome.error_kind == "connect":
                # 连不上库,重试多少次都没用
                yield {"type": "error", "stage": "execute", "error": f"连接数据源失败:{last_error}"}
                run_id = _log(ds_id, question, first_sql, sql, "error", thread_id, plan,
                              last_error, 0, 0, attempt - 1)
                yield _done(thread_id, "failed", started, run_id=run_id)
                return
        else:
            last_error = ";".join(i.msg + (f"({i.fix})" if i.fix else "") for i in g.errors)

        if error_repairs >= max_repair:
            break

        error_repairs += 1
        attempt += 1
        yield {"type": "repair", "attempt": attempt, "reason": last_error[:400], "kind": "error"}
        yield from _draft(prompts.build_repair_messages(
            question, schema, sql, last_error, dialect), cfg, attempt, out)
        if out.get("error"):
            last_error = f"自愈重试调用失败:{out['error']}"
            break
        sql = out.get("sql", "")

    outcome = best
    if outcome is None or not outcome.ok:
        status = "invalid" if (outcome is None or outcome.error_kind == "guard") else "error"
        yield {"type": "error", "stage": "validate" if status == "invalid" else "execute",
               "error": last_error or "SQL 校验未通过", "sql": sql, "attempts": attempt}
        run_id = _log(ds_id, question, first_sql, sql, status, thread_id, plan,
                      last_error, 0, 0, attempt - 1)
        yield {"type": "done", "thread_id": thread_id, "outcome": "failed", "run_id": run_id,
               "duration_ms": int((time.time() - started) * 1000)}
        return

    result = outcome.result
    executed_sql = outcome.guard.sql
    yield {"type": "execute", "row_count": result.row_count, "duration_ms": result.duration_ms,
           "truncated": result.truncated, "sql": executed_sql, "attempts": attempt}
    yield {"type": "rows", "columns": result.columns, "rows": result.rows}

    # ---------- 5) 留痕 + 自动沉淀 ----------
    run_id = _log(ds_id, question, first_sql, executed_sql, "ok", thread_id, plan,
                  "", result.row_count, result.duration_ms, attempt - 1)
    pair_id = 0
    try:
        # 跑成功了就自动存一条草稿。要不要当示例用,等人点「采纳」。
        pair_id = library.capture(ds_id, question, executed_sql, source="auto",
                                  run_id=run_id, models_used=outcome.guard.tables)
    except Exception:  # noqa: BLE001
        log.exception("沉淀问答对失败 ds=%s", ds_id)
    if ctx["hits"]["pairs"]:
        library.mark_hit([p["id"] for p in ctx["hits"]["pairs"]])

    # ---------- 6) 结论(流式)----------
    # 只做结论。「这条 SQL 在做什么」改成按需生成(POST /api/sql/explain)——
    # 它是审计信息,默认折叠着没人看,却要占掉一整轮大模型往返(3~5 秒),
    # 而且这段时间里 done 发不出去,输入框一直锁着,下一个问题都没法问。
    yield from _stream(prompts.build_summary_messages(
        question, result.columns, result.rows, result.row_count, SUMMARY_ROWS),
        "summary", cfg)

    yield {"type": "done", "thread_id": thread_id, "outcome": "ok", "run_id": run_id,
           "pair_id": pair_id, "duration_ms": int((time.time() - started) * 1000)}


# ---------------- 内部 ----------------
def _done(thread_id: str, outcome: str, started: float, **extra) -> dict:
    """管线的每一条出口都要走它。前端靠 done 关掉 running,漏发就会一直转圈。"""
    return {"type": "done", "thread_id": thread_id, "outcome": outcome,
            "duration_ms": int((time.time() - started) * 1000), **extra}


def _is_blank(result) -> bool:
    """这次查询算不算「什么也没查到」。

    0 行是显而易见的那种。真正阴的是**聚合查询没匹配到任何行** ——
    `SELECT SUM(x) ... WHERE 条件恒假` 会老老实实返回一行,值是 NULL。
    row_count=1 看着像成功,空结果自愈压根不会触发,用户拿到的是一格 NULL。
    实测踩过:模型把「上个月」的上下界写成同一个表达式,区间恒空,
    界面上就是一行 NULL 外加一段"可能确实没有数据"的结论 —— 全是错的。
    """
    if result.row_count == 0:
        return True
    return (result.row_count == 1
            and bool(result.rows)
            and all(v is None for v in result.rows[0]))


def _draft(messages: list[dict], cfg: dict, attempt: int, out: dict) -> Iterator[dict]:
    """流式起草一版 SQL,结果写进 `out`(`sql` 或 `error`)。

    生成 SQL 是整条链路里最长的一次等待(十几秒)。以前是阻塞调用,界面上
    只有一个「处理中…」在转 —— 用户无从判断是在干活还是卡死了。改成边写边吐,
    等待时间没变,但它现在是**可见的**,而且看得见就能提前发现取数取错了。

    最后一定补一条完整的 `sql_draft`:前端的编辑器认它,重跑和沉淀也认它。
    """
    out.clear()
    try:
        if (cfg.get("SQL_STREAM_DRAFT") or "1") != "1":
            out["sql"] = prompts.strip_sql_fence(llm.chat(messages))
            yield {"type": "sql_draft", "sql": out["sql"], "attempt": attempt}
            return
        buf: list[str] = []
        for piece in llm.chat_stream_cached(messages, temperature=0.2):
            buf.append(piece)
            yield {"type": "sql_delta", "text": piece, "attempt": attempt}
        out["sql"] = prompts.strip_sql_fence("".join(buf))
        yield {"type": "sql_draft", "sql": out["sql"], "attempt": attempt}
    except Exception as e:  # noqa: BLE001
        out["error"] = str(e)[:300]


def _stream(messages: list[dict], kind: str, cfg: dict) -> Iterator[dict]:
    """流式吐一段文本。失败不致命 —— SQL 和结果才是主产物,解释缺了也能用。"""
    if (cfg.get("STREAM_ANSWER") or "1") != "1":
        try:
            text = llm.chat(messages, temperature=0.3)
        except Exception as e:  # noqa: BLE001
            log.warning("%s 生成失败:%s", kind, str(e)[:200])
            return
        yield {"type": kind, "text": text}
        return

    buf: list[str] = []
    try:
        for piece in llm.chat_stream(messages, temperature=0.3):
            buf.append(piece)
            yield {"type": f"{kind}_delta", "text": piece}
    except Exception as e:  # noqa: BLE001
        log.warning("%s 流式生成失败:%s", kind, str(e)[:200])
        if not buf:
            return
    yield {"type": kind, "text": "".join(buf)}


def _log(ds_id: int, question: str, sql_text: str, sql_final: str, status: str,
         thread_id: str, plan: dict, error: str, row_count: int,
         duration_ms: int, retry_count: int) -> int:
    try:
        return executor.log_run(
            ds_id, question, sql_text, sql_final, status, thread_id=thread_id,
            plan=plan, error=error, row_count=row_count,
            duration_ms=duration_ms, retry_count=retry_count)
    except Exception:  # noqa: BLE001
        log.exception("写执行审计失败 ds=%s", ds_id)
        return 0