session.py
9.76 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
"""会话、轮次、推理轨迹的读写与反馈。"""
from __future__ import annotations
import datetime as dt
import time
from typing import Any
from fastapi import HTTPException
from sqlalchemy import func, select
from ..core import identity
from ..core.dbx import iso, jdump, jload, new_id, now, session
from ..governance import audit
from .models import AskTrace, Conversation, Turn
EMPTY_LINKS = {"concepts": [], "instances": [], "time": None}
# 服务重启等原因留下的「running」轮次,超过这个时间就当作已中断显示
STALE_RUNNING = dt.timedelta(minutes=10)
def ensure_conversation(conv_id: str, question: str) -> str:
actor = identity.current()
with session() as s:
if conv_id:
c = s.get(Conversation, conv_id)
if c is not None and c.workspace == actor.workspace:
c.updated_at = now()
s.commit()
return c.id
c = Conversation(id=new_id("cv"), workspace=actor.workspace, title=question[:60],
created_by=actor.id)
s.add(c)
s.commit()
return c.id
def new_turn(conv_id: str, question: str) -> str:
actor = identity.current()
with session() as s:
seq = (s.scalar(select(func.max(Turn.seq)).where(Turn.conversation_id == conv_id)) or 0) + 1
turn = Turn(id=new_id("tn"), conversation_id=conv_id, seq=seq, question=question,
created_by=actor.id, links_json=jdump(EMPTY_LINKS))
s.add(turn)
s.commit()
return turn.id
def history(conv_id: str, limit: int = 3) -> list[dict]:
with session() as s:
rows = s.scalars(select(Turn).where(Turn.conversation_id == conv_id,
Turn.status == "done")
.order_by(Turn.seq.desc()).limit(limit)).all()
return [{"question": t.question, "answer": (t.answer or "")[:500],
"plan": jload(t.plan_json, {})} for t in reversed(rows)]
def _links(raw: str) -> dict:
v = jload(raw, {})
if not isinstance(v, dict):
v = {}
return {"concepts": v.get("concepts") or [], "instances": v.get("instances") or [],
"time": v.get("time")}
def _status(t: Turn) -> str:
if t.status == "running" and t.created_at and now() - t.created_at > STALE_RUNNING:
return "aborted"
return t.status or "done"
def turn_dict(t: Turn) -> dict:
return {"id": t.id, "conversation_id": t.conversation_id, "seq": t.seq,
"question": t.question, "status": _status(t), "links": _links(t.links_json),
"plan": jload(t.plan_json, {}) or {}, "steps": jload(t.steps_json, []) or [],
"answer": t.answer or "", "citations": jload(t.citations_json, []) or [],
"data_refs": jload(t.data_refs_json, []) or [], "actions": jload(t.actions_json, []) or [],
"sops": jload(t.sops_json, []) or [], "rating": t.rating or 0, "feedback": t.feedback or "",
"duration_ms": t.duration_ms or 0, "created_at": iso(t.created_at)}
def list_conversations(limit: int = 50) -> list[dict]:
actor = identity.current()
with session() as s:
rows = s.scalars(select(Conversation).where(
Conversation.workspace == actor.workspace, Conversation.created_by == actor.id)
.order_by(Conversation.pinned.desc(), Conversation.updated_at.desc()).limit(limit)).all()
counts = dict(s.execute(select(Turn.conversation_id, func.count(Turn.id))
.where(Turn.conversation_id.in_([r.id for r in rows] or ["-"]))
.group_by(Turn.conversation_id)).all())
return [{"id": c.id, "title": c.title, "turns": int(counts.get(c.id, 0)), "pinned": bool(c.pinned),
"updated_at": iso(c.updated_at)} for c in rows]
def update_conversation(conv_id: str, *, title: str | None = None, pinned: bool | None = None) -> dict:
"""改名 / 置顶。只能动自己的对话。"""
actor = identity.current()
with session() as s:
c = s.get(Conversation, conv_id)
if c is None or c.workspace != actor.workspace or c.created_by != actor.id:
raise HTTPException(404, "对话不存在")
updated = c.updated_at
if title is not None and title.strip():
c.title = title.strip()[:255]
if pinned is not None:
c.pinned = 1 if pinned else 0
c.updated_at = updated # 改名、置顶不算「最近聊过」,不改变它在列表里的时间位置
s.commit()
return {"id": c.id, "title": c.title, "pinned": bool(c.pinned)}
def get_conversation(conv_id: str) -> dict:
with session() as s:
c = s.get(Conversation, conv_id)
if c is None or c.workspace != identity.current().workspace:
raise HTTPException(404, "会话不存在")
rows = s.scalars(select(Turn).where(Turn.conversation_id == conv_id).order_by(Turn.seq)).all()
stats = {r.turn_id: jload(r.stats_json, {}) for r in s.scalars(
select(AskTrace).where(AskTrace.turn_id.in_([t.id for t in rows] or ["-"]))).all()}
turns = []
for t in rows:
d = turn_dict(t)
d["stats"] = stats.get(t.id) or {}
d["has_trace"] = t.id in stats
turns.append(d)
return {"id": c.id, "title": c.title, "turns": turns}
def delete_conversation(conv_id: str) -> None:
get_conversation(conv_id)
with session() as s:
for t in s.scalars(select(Turn).where(Turn.conversation_id == conv_id)).all():
tr = s.get(AskTrace, t.id)
if tr is not None:
s.delete(tr)
s.delete(t)
s.delete(s.get(Conversation, conv_id))
s.commit()
def get_turn(turn_id: str) -> dict:
with session() as s:
t = s.get(Turn, turn_id)
if t is None:
raise HTTPException(404, "记录不存在")
return turn_dict(t)
def mark_card(turn_id: str, kind: str, index: int, ref: str) -> dict:
"""记下「这张卡已经提交 / 已经确认发起」:刷新页面、换个设备回来看,都不会再让人点第二次。
kind: action(ref = 审批单编号)/ sop(ref = 流程运行编号)。同一张卡只认第一次。"""
actor = identity.current()
with session() as s:
t = s.get(Turn, turn_id)
if t is None:
raise HTTPException(404, "记录不存在")
cards = jload(t.sops_json if kind == "sop" else t.actions_json, []) or []
if not 0 <= index < len(cards):
raise HTTPException(404, "这张卡片不存在")
if not cards[index].get("submitted"):
cards[index]["submitted"] = {"ref": ref, "by": actor.id, "at": iso(now())}
if kind == "sop":
t.sops_json = jdump(cards)
else:
t.actions_json = jdump(cards)
s.commit()
return cards[index]
def get_trace(turn_id: str) -> dict:
get_turn(turn_id)
with session() as s:
tr = s.get(AskTrace, turn_id)
if tr is None:
return {"turn_id": turn_id, "events": [], "stats": {}, "memory": {}}
return {"turn_id": turn_id, "events": jload(tr.events_json, []) or [],
"stats": jload(tr.stats_json, {}) or {}, "memory": jload(tr.memory_json, {}) or {}}
def save_turn(turn_id: str, status: str, *, links: dict | None = None, plan: dict | None = None,
steps: list | None = None, answer: str | None = None, citations: list | None = None,
data_refs: list | None = None, cards: list | None = None, sops: list | None = None,
started: float | None = None) -> None:
with session() as s:
t = s.get(Turn, turn_id)
if t is None:
return
t.status = status
if links is not None:
t.links_json = jdump({**EMPTY_LINKS, **links})
if plan is not None:
t.plan_json = jdump(plan)
if steps is not None:
t.steps_json = jdump(steps)
if answer is not None:
t.answer = answer
if citations is not None:
t.citations_json = jdump(citations)
if data_refs is not None:
t.data_refs_json = jdump(data_refs)
if cards is not None:
t.actions_json = jdump(cards)
if sops is not None:
t.sops_json = jdump(sops)
if started is not None:
t.duration_ms = int((time.time() - started) * 1000)
s.commit()
def save_trace(turn_id: str, events: list[dict], stats: dict, memory: dict | None = None) -> None:
with session() as s:
tr = s.get(AskTrace, turn_id)
if tr is None:
tr = AskTrace(turn_id=turn_id)
s.add(tr)
tr.events_json = jdump(events)
tr.stats_json = jdump(stats)
tr.memory_json = jdump(memory or {})
s.commit()
def feedback(turn_id: str, rating: int, comment: str = "", correction: str = "") -> dict:
from ..governance import review
from ..memory import service as memory
t = get_turn(turn_id)
with session() as s:
row = s.get(Turn, turn_id)
row.rating = 1 if rating > 0 else -1 if rating < 0 else 0
row.feedback = (comment or "")[:4000]
s.commit()
audit.record("ask.feedback", "turn", turn_id, f"{'👍' if rating > 0 else '👎'} {comment[:200]}")
learned: dict[str, Any] = memory.on_feedback(turn_id, rating, comment, correction)
item = None
if rating < 0 or correction:
item = review.propose("feedback", f"答案纠错:{t['question'][:80]}", {
"turn_id": turn_id, "question": t["question"], "answer": t["answer"][:3000],
"comment": comment, "correction": correction,
"plan": t["plan"], "links": t["links"]}, source="feedback", target_ref=turn_id)
return {"ok": True, "review_item": item, "learned": learned}