threads.py
7.37 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
"""SQL 调试台的会话。
一个会话 = 一串连续追问(同一个 thread_id 的取数记录)。每一轮在 `SqlRun.trace_json` 里存一份
回放快照(计划、SQL、结果前 200 行、结论……),重新打开会话直接还原,不用重跑。
「改 SQL 重跑」会记一条新的取数记录并标明它替换了哪一轮,会话里只显示最新的那一版。
"""
from __future__ import annotations
import datetime as dt
import json
import logging
import uuid
from typing import Any, Iterator
from fastapi import HTTPException
from sqlalchemy import select, update
from sqlalchemy.orm import Session
from ..core import identity
from ..core.db import get_engine
from . import executor
from .models import SqlRun, SqlThread
log = logging.getLogger(__name__)
SNAPSHOT_ROWS = 200
def _dict(t: SqlThread) -> dict:
return {"id": t.id, "ds_id": t.ds_id, "title": t.title or "新会话", "created_by": t.created_by,
"created_at": t.created_at.isoformat() if t.created_at else None,
"updated_at": t.updated_at.isoformat() if t.updated_at else None}
def _own(s: Session, thread_id: str) -> SqlThread:
t = s.get(SqlThread, thread_id)
if t is None or t.created_by != identity.current().id:
raise HTTPException(404, "会话不存在")
return t
def list_threads(ds_id: int) -> list[dict]:
with Session(get_engine()) as s:
rows = s.scalars(select(SqlThread).where(
SqlThread.ds_id == ds_id, SqlThread.created_by == identity.current().id)
.order_by(SqlThread.updated_at.desc()).limit(200)).all()
return [_dict(t) for t in rows]
def create(ds_id: int, title: str = "") -> dict:
with Session(get_engine()) as s:
t = SqlThread(id=uuid.uuid4().hex[:16], ds_id=ds_id, title=title[:200],
created_by=identity.current().id)
s.add(t)
s.commit()
return _dict(t)
def rename(thread_id: str, title: str) -> dict:
with Session(get_engine()) as s:
t = _own(s, thread_id)
t.title = title.strip()[:200]
s.commit()
return _dict(t)
def delete(thread_id: str) -> None:
"""删会话不删取数记录(那是审计),只是把它们从会话里摘掉。"""
with Session(get_engine()) as s:
t = _own(s, thread_id)
s.execute(update(SqlRun).where(SqlRun.thread_id == thread_id).values(thread_id=""))
s.delete(t)
s.commit()
def touch(thread_id: str, question: str = "") -> None:
"""有新一轮:更新时间;还没有标题就用第一句问题当标题。"""
if not thread_id:
return
with Session(get_engine()) as s:
t = s.get(SqlThread, thread_id)
if t is None:
return
if question and not (t.title or "").strip():
t.title = question.strip()[:60]
t.updated_at = dt.datetime.now()
s.commit()
def check(thread_id: str) -> None:
if thread_id:
with Session(get_engine()) as s:
_own(s, thread_id)
def get(thread_id: str) -> dict:
with Session(get_engine()) as s:
t = _own(s, thread_id)
runs = s.scalars(select(SqlRun).where(SqlRun.thread_id == thread_id).order_by(SqlRun.id)).all()
snaps = [(r, _load(r.trace_json)) for r in runs]
replaced = {int(sn.get("replaces") or 0) for _, sn in snaps}
turns = []
for r, sn in snaps:
if r.id in replaced or not sn.get("v"):
continue
turns.append({"run_id": r.id, "question": r.question or "", "status": r.status,
"rating": r.rating, "sql": r.sql_final or r.sql_text or "",
"duration_ms": r.duration_ms, "error": r.error or "",
"created_at": r.created_at.isoformat() if r.created_at else None, **sn})
return {**_dict(t), "turns": turns}
def _load(raw: str) -> dict:
try:
v = json.loads(raw or "{}")
except Exception: # noqa: BLE001
return {}
return v if isinstance(v, dict) else {}
def save_snapshot(run_id: int, snap: dict) -> None:
with Session(get_engine()) as s:
s.execute(update(SqlRun).where(SqlRun.id == run_id).values(
trace_json=json.dumps(snap, ensure_ascii=False, default=str)[:3_000_000]))
s.commit()
def patch_snapshot(run_id: int, **fields: Any) -> None:
with Session(get_engine()) as s:
r = s.get(SqlRun, run_id)
if r is None:
return
snap = _load(r.trace_json)
if not snap.get("v"):
return
snap.update(fields)
r.trace_json = json.dumps(snap, ensure_ascii=False, default=str)[:3_000_000]
s.commit()
def snapshot(**fields: Any) -> dict:
rows = fields.pop("rows", None) or []
return {"v": 1, "rows": rows[:SNAPSHOT_ROWS], **fields}
def record(gen: Iterator[dict], ds_id: int, question: str, thread_id: str) -> Iterator[dict]:
"""把管线事件原样往外推,同时攒一份回放快照,结束时存到这一轮的取数记录上。
管线只有跑到执行那一步才记取数记录;澄清、直接回答、半路失败这些结局在这里补记,
会话里每一轮都要留得住。"""
snap: dict = {"outcome": "", "plan": {}, "calibre": "", "clarify": "", "answer": "", "summary": "",
"columns": [], "rows": [], "truncated": False, "issues": [], "retrieve": None, "error": ""}
sql = ""
run_id = 0
for ev in gen:
t = ev.get("type")
if t == "retrieve":
snap["retrieve"] = ev
elif t == "plan":
snap["plan"], snap["calibre"] = ev.get("plan") or {}, ev.get("calibre") or ""
snap["clarify"] = ev.get("clarify") or ""
elif t == "answer":
snap["answer"] = ev.get("text") or ""
elif t == "sql_draft":
sql = ev.get("sql") or sql
elif t == "validate":
snap["issues"] = ev.get("issues") or []
if ev.get("ok"):
sql = ev.get("sql") or sql
elif t == "execute":
sql = ev.get("sql") or sql
snap["truncated"] = bool(ev.get("truncated"))
elif t == "rows":
snap["columns"], snap["rows"] = ev.get("columns") or [], ev.get("rows") or []
elif t == "summary":
snap["summary"] = ev.get("text") or ""
elif t == "error":
snap["error"] = ev.get("error") or ""
sql = ev.get("sql") or sql
elif t == "done":
snap["outcome"] = ev.get("outcome") or ""
snap["clarify"] = ev.get("clarify") or snap["clarify"]
snap["answer"] = ev.get("answer") or snap["answer"]
run_id = int(ev.get("run_id") or 0)
try:
full = snapshot(**snap)
if run_id:
save_snapshot(run_id, full)
else:
status = {"clarify": "clarify", "metadata": "answer", "not_data": "answer"}.get(
snap["outcome"], "failed")
run_id = executor.log_run(ds_id, question, sql, sql, status, thread_id=thread_id,
plan=snap["plan"], error=snap["error"], trace=full)
ev = {**ev, "run_id": run_id}
touch(thread_id, question)
except Exception: # noqa: BLE001 会话留痕失败不能影响这一轮的回答
log.exception("保存会话快照失败")
yield ev