text2sql.py 14.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
"""数据问答接口:数据源 / 建模 / 问答(SSE) / 执行 / 沉淀库 / 审计。"""
from __future__ import annotations
import logging

from fastapi import APIRouter, HTTPException, Request
from sse_starlette.sse import EventSourceResponse

from ..core import db, llm
from ..jobs.queue import runner
from ..schemas import (
    AskRequest, ColumnUpdate, DataSourceCreate, DataSourceUpdate, DescribeRequest,
    EnableModelsRequest, InstructionUpsert, MetricUpsert, ModelUpdate, PairUpsert,
    ExplainRequest, RelationUpsert, RunSqlRequest, SummarizeRequest,
)
from ..text2sql import crypto, describe, executor, introspect, library, prompts, semantic
from ..text2sql.connectors import registry
from ..text2sql.connectors.base import ConnectionFailed
from ..text2sql.pipeline import run_ask
from . import deps

log = logging.getLogger(__name__)
router = APIRouter(prefix="/api/sql", tags=["text2sql"])


def _need_ds(ds_id: int) -> dict:
    ds = semantic.get_datasource(ds_id)
    if ds is None:
        raise HTTPException(404, "数据源不存在")
    return ds


def _need_crypto() -> None:
    if not crypto.available():
        raise HTTPException(400, "未配置 SECRET_KEY,无法安全保存数据源口令。"
                                 "请在 .env 里设置一个足够长的随机串后重启服务。")


# ---------------- 元信息 ----------------
@router.get("/meta")
async def meta():
    return {"supported_types": registry.supported_types(),
            "crypto_ready": crypto.available(),
            "row_limit": executor.limits()[0],
            "timeout_ms": executor.limits()[1]}


# ---------------- 数据源 ----------------
@router.get("/datasources")
async def list_datasources():
    return semantic.list_datasources()


@router.post("/datasources")
async def create_datasource(payload: DataSourceCreate):
    _need_crypto()
    ds_id = semantic.create_datasource(**payload.model_dump())
    return semantic.get_datasource(ds_id)


@router.get("/datasources/{ds_id}")
async def get_datasource(ds_id: int):
    return _need_ds(ds_id)


@router.put("/datasources/{ds_id}")
async def update_datasource(ds_id: int, payload: DataSourceUpdate):
    _need_ds(ds_id)
    fields = payload.model_dump(exclude_unset=True)
    if "password" in fields:
        _need_crypto()
    semantic.update_datasource(ds_id, **fields)
    return semantic.get_datasource(ds_id)


@router.delete("/datasources/{ds_id}")
async def delete_datasource(ds_id: int):
    _need_ds(ds_id)
    semantic.delete_datasource(ds_id)
    return {"ok": True}


@router.post("/datasources/{ds_id}/test")
async def test_datasource(ds_id: int):
    _need_ds(ds_id)
    try:
        # 用 fresh 连接器:坏配置不该进连接池缓存
        info = semantic.connector_for(ds_id, fresh=True).test()
    except ConnectionFailed as e:
        semantic.mark_datasource(ds_id, "error", str(e))
        raise HTTPException(400, f"连接失败:{e}") from e
    except Exception as e:  # noqa: BLE001
        semantic.mark_datasource(ds_id, "error", str(e))
        raise HTTPException(400, str(e)[:500]) from e
    semantic.mark_datasource(ds_id, "ok", "")
    if info.get("account_writable"):
        info["warning"] = "这个账号有写权限。生成的 SQL 有只读校验兜底,但仍建议改用只读账号。"
    return info


@router.post("/datasources/{ds_id}/introspect")
async def start_introspect(ds_id: int, resample: bool = False):
    _need_ds(ds_id)
    job_id = db.create_job(0, job_type="introspect")
    ok = runner.submit(job_id, lambda: introspect.run_introspection(ds_id, resample))
    return {"job_id": job_id, "queued": ok, "queue_depth": runner.queue_depth()}


# ---------------- 建模 ----------------
@router.get("/datasources/{ds_id}/models")
async def list_models(ds_id: int, enabled_only: bool = False):
    _need_ds(ds_id)
    return semantic.models_with_columns(ds_id, enabled_only=enabled_only)


@router.put("/models/{model_id}")
async def update_model(model_id: int, payload: ModelUpdate):
    fields = payload.model_dump(exclude_unset=True)
    if "enabled" in fields:
        fields["enabled"] = 1 if fields["enabled"] else 0
    semantic.update_model(model_id, **fields)
    return {"ok": True}


@router.put("/columns/{column_id}")
async def update_column(column_id: int, payload: ColumnUpdate):
    fields = payload.model_dump(exclude_unset=True)
    for k in ("is_dimension", "is_measure", "enabled"):
        if k in fields:
            fields[k] = 1 if fields[k] else 0
    semantic.update_column(column_id, **fields)
    return {"ok": True}


@router.post("/datasources/{ds_id}/models/enable")
async def enable_models(ds_id: int, payload: EnableModelsRequest):
    _need_ds(ds_id)
    n = semantic.set_models_enabled(ds_id, payload.ids, payload.enabled)
    return {"ok": True, "changed": n}


@router.get("/datasources/{ds_id}/relations")
async def list_relations(ds_id: int):
    _need_ds(ds_id)
    return semantic.list_relations(ds_id)


@router.post("/datasources/{ds_id}/relations")
async def upsert_relation(ds_id: int, payload: RelationUpsert):
    _need_ds(ds_id)
    fields = payload.model_dump()
    fields["enabled"] = 1 if fields.pop("enabled", True) else 0
    models = {m["id"]: m for m in semantic.list_models(ds_id)}
    fm, tm = models.get(fields["from_model_id"]), models.get(fields["to_model_id"])
    if not fm or not tm:
        raise HTTPException(400, "关系两端必须是这个数据源下已存在的表")
    ft = fm["physical_table"] or fm["name"]
    tt = tm["physical_table"] or tm["name"]
    fields["condition_sql"] = f"{ft}.{fields['from_column']} = {tt}.{fields['to_column']}"
    if not fields.get("name"):
        fields["name"] = f"{ft}_{tt}"
    rel_id = semantic.upsert_relation(ds_id, **fields)
    return {"ok": True, "id": rel_id}


@router.delete("/relations/{rel_id}")
async def delete_relation(rel_id: int):
    semantic.delete_relation(rel_id)
    return {"ok": True}


@router.post("/datasources/{ds_id}/describe")
async def start_describe(ds_id: int, payload: DescribeRequest):
    """让大模型给已启用的表批量补描述与同义词(后台任务)。

    同义词是召回能不能命中的关键:物理列叫 sum_ax_package,
    业务同事说的是「安心包卖了多少」,中间这层映射得补上。
    """
    _need_ds(ds_id)
    job_id = db.create_job(0, job_type="describe")
    ok = runner.submit(job_id, lambda: describe.run_describe(
        ds_id, overwrite=payload.overwrite, model_ids=payload.model_ids or None))
    return {"job_id": job_id, "queued": ok, "queue_depth": runner.queue_depth()}


@router.get("/datasources/{ds_id}/relations/recommend")
async def recommend_relations(ds_id: int):
    """这个库没有外键,靠列名 + 真实取值重叠率推关联路径。"""
    _need_ds(ds_id)
    return semantic.recommend_relations(ds_id)


# ---------------- 指标 ----------------
@router.get("/datasources/{ds_id}/metrics")
async def list_metrics(ds_id: int, enabled_only: bool = False):
    _need_ds(ds_id)
    return semantic.list_metrics(ds_id, enabled_only=enabled_only)


@router.post("/datasources/{ds_id}/metrics")
async def upsert_metric(ds_id: int, payload: MetricUpsert):
    _need_ds(ds_id)
    fields = payload.model_dump()
    fields["enabled"] = 1 if fields.pop("enabled", True) else 0
    return {"ok": True, "id": semantic.upsert_metric(ds_id, **fields)}


@router.get("/datasources/{ds_id}/metrics/issues")
async def metric_issues(ds_id: int):
    """指标自检:表达式引用的列是不是都还可用。有问题的指标不会进提示词。"""
    _need_ds(ds_id)
    return semantic.metric_issues(ds_id)


@router.post("/datasources/{ds_id}/categorize")
async def categorize(ds_id: int):
    """给还没分类的指标和规则补一个分类。只填空,不动人工改过的。"""
    _need_ds(ds_id)
    return {"ok": True, **semantic.autocategorize(ds_id)}


@router.delete("/metrics/{metric_id}")
async def delete_metric(metric_id: int):
    semantic.delete_metric(metric_id)
    return {"ok": True}


# ---------------- 业务规则(指令)----------------
@router.get("/instructions")
async def list_instructions(ds_id: int = 0, scope: str = "sql"):
    return semantic.list_instructions(ds_id, scope=scope, enabled_only=False)


@router.post("/instructions")
async def upsert_instruction(payload: InstructionUpsert):
    fields = payload.model_dump()
    ds_id = fields.pop("ds_id", 0)
    fields["is_default"] = 1 if fields.pop("is_default", True) else 0
    fields["enabled"] = 1 if fields.pop("enabled", True) else 0
    return {"ok": True, "id": semantic.upsert_instruction(ds_id, **fields)}


@router.delete("/instructions/{ins_id}")
async def delete_instruction(ins_id: int):
    semantic.delete_instruction(ins_id)
    return {"ok": True}


@router.get("/datasources/{ds_id}/mdl")
async def export_mdl(ds_id: int):
    _need_ds(ds_id)
    return semantic.export_mdl(ds_id)


@router.post("/datasources/{ds_id}/snapshot")
async def take_snapshot(ds_id: int, note: str = ""):
    _need_ds(ds_id)
    return {"ok": True, "id": semantic.snapshot(ds_id, note)}


# ---------------- 问答 ----------------
@router.post("/ask")
async def ask(payload: AskRequest, request: Request):
    _need_ds(payload.ds_id)
    gen = run_ask(payload.ds_id, payload.question.strip(), history=payload.history,
                  overrides=payload.overrides, thread_id=payload.thread_id,
                  approved_plan=payload.approved_plan)
    return EventSourceResponse(deps.sse(gen, request))


@router.post("/validate")
async def validate_sql(payload: RunSqlRequest):
    """只校验不执行。SQL 编辑器里边打边给反馈用。"""
    _need_ds(payload.ds_id)
    ds = semantic.get_datasource(payload.ds_id)
    return executor.validate(payload.ds_id, payload.sql, ds["ds_type"]).as_dict()


@router.post("/run")
async def run_sql(payload: RunSqlRequest):
    """执行用户手改过的 SQL。和管线走同一套 guard —— 不能有第二条绕过校验的路径。"""
    ds = _need_ds(payload.ds_id)
    outcome = executor.execute(payload.ds_id, payload.sql, ds["ds_type"])
    if not outcome.ok:
        run_id = executor.log_run(
            payload.ds_id, payload.question, payload.sql, payload.sql,
            "invalid" if outcome.error_kind == "guard" else "error",
            thread_id=payload.thread_id, error=outcome.error)
        raise HTTPException(400, detail=outcome.error)

    r = outcome.result
    run_id = executor.log_run(
        payload.ds_id, payload.question, payload.origin_sql or payload.sql,
        outcome.guard.sql, "ok", thread_id=payload.thread_id,
        row_count=r.row_count, duration_ms=r.duration_ms)

    pair_id = 0
    if payload.question.strip():
        # 用户改过 SQL 再跑通,是最值钱的信号:它直接标出了模型的系统性偏差。
        edited = bool(payload.origin_sql and payload.origin_sql.strip() != payload.sql.strip())
        try:
            pair_id = library.capture(
                payload.ds_id, payload.question, outcome.guard.sql,
                source="user_edited" if edited else "auto", run_id=run_id,
                models_used=outcome.guard.tables,
                sql_before=payload.origin_sql if edited else "")
        except Exception:  # noqa: BLE001
            log.exception("沉淀问答对失败")

    return {"ok": True, "run_id": run_id, "pair_id": pair_id,
            "columns": r.columns, "rows": r.rows, "row_count": r.row_count,
            "duration_ms": r.duration_ms, "truncated": r.truncated,
            "sql": outcome.guard.sql, "limited": outcome.guard.limited,
            "issues": [i.as_dict() for i in outcome.guard.issues]}


@router.post("/explain")
async def explain(payload: ExplainRequest):
    """用业务语言解释一条 SQL。

    按需生成:这段话在界面上默认是折叠的,没人展开就不该为它多花一轮往返。
    管线里做完这件事再发 done,意味着用户看完结论还要等三五秒才能问下一句。
    """
    _need_ds(payload.ds_id)
    text = llm.chat(prompts.build_explain_messages(payload.question, payload.sql),
                    temperature=0.3)
    return {"ok": True, "text": text}


@router.post("/summarize")
async def summarize(payload: SummarizeRequest):
    """对一批结果重新出结论。

    用户在编辑器里改完 SQL 点重跑,数据换了,可上一轮的「结论」还挂在那儿 ——
    那是比没有结论更糟的东西:它看起来仍然在解释屏幕上的表格。
    重跑走的是 /run(不经管线,自然也没有结论),所以单独留这个出口补上。
    """
    _need_ds(payload.ds_id)
    text = llm.chat(prompts.build_summary_messages(
        payload.question, payload.columns, payload.rows,
        payload.row_count or len(payload.rows)), temperature=0.3)
    return {"ok": True, "text": text}


# ---------------- 审计 ----------------
@router.get("/runs")
async def list_runs(ds_id: int | None = None, limit: int = 30):
    return executor.list_runs(ds_id, limit)


@router.get("/runs/{run_id}")
async def get_run(run_id: int):
    r = executor.get_run(run_id)
    if not r:
        raise HTTPException(404, "记录不存在")
    return r


@router.post("/runs/{run_id}/rate")
async def rate_run(run_id: int, rating: int = 0):
    if not executor.get_run(run_id):
        raise HTTPException(404, "记录不存在")
    executor.rate_run(run_id, max(-1, min(1, rating)))
    return {"ok": True}


# ---------------- 沉淀库 ----------------
@router.get("/pairs")
async def list_pairs(ds_id: int | None = None, status: str | None = None,
                     keyword: str = "", limit: int = 100):
    return library.list_pairs(ds_id, status, keyword, limit)


@router.post("/pairs")
async def create_pair(payload: PairUpsert):
    if not payload.ds_id or not payload.question or not payload.sql:
        raise HTTPException(400, "ds_id、question、sql 都不能为空")
    _need_ds(payload.ds_id)
    pair_id = library.capture(payload.ds_id, payload.question, payload.sql,
                              source="user_saved", status=payload.status or "verified")
    if payload.status:
        library.set_status(pair_id, payload.status)
    return {"ok": True, "id": pair_id}


@router.put("/pairs/{pair_id}")
async def update_pair(pair_id: int, payload: PairUpsert):
    if not library.get_pair(pair_id):
        raise HTTPException(404, "记录不存在")
    fields = payload.model_dump(exclude_unset=True, exclude_none=True)
    fields.pop("ds_id", None)
    status = fields.pop("status", None)
    if fields:
        library.update_pair(pair_id, **fields)
    if status:
        library.set_status(pair_id, status)
    return library.get_pair(pair_id)


@router.post("/pairs/{pair_id}/adopt")
async def adopt_pair(pair_id: int):
    """把草稿升成已采纳。只有采纳过的才会进 few-shot。"""
    if not library.get_pair(pair_id):
        raise HTTPException(404, "记录不存在")
    library.set_status(pair_id, "verified")
    return library.get_pair(pair_id)


@router.delete("/pairs/{pair_id}")
async def delete_pair(pair_id: int):
    library.delete_pair(pair_id)
    return {"ok": True}