Elffuss BraidHub

kikocis/utopia public

dev · 9.4 KiBRawPermalink
1//! Chat 会话持久化:对话/消息仓储。轨迹(steps)与引用(sources)随
2//! assistant 消息落库,历史回放与实时流共用同一数据形状。
3
4use chrono::{DateTime, Utc};
5use sqlx::PgPool;
6use utopia_core::models::{ConversationMessage, ConversationView};
7use utopia_core::{AppError, AppResult};
8use uuid::Uuid;
9
10pub async fn create(pool: &PgPool, kb_id: Uuid, user_id: Uuid, title: &str) -> AppResult<Uuid> {
11 let id = Uuid::now_v7();
12 sqlx::query("INSERT INTO conversations (id, kb_id, user_id, title) VALUES ($1, $2, $3, $4)")
13 .bind(id)
14 .bind(kb_id)
15 .bind(user_id)
16 .bind(title.chars().take(80).collect::<String>())
17 .execute(pool)
18 .await?;
19 Ok(id)
20}
21
22/// 我在这个库里的会话。**可搜、可翻页**——标题会重(同一个问题问两次就重了),
23/// 而固定一百条之后的会话界面上根本不存在。
24///
25/// 搜的是标题与消息正文两处:人记得住的往往是「我问过那个关于 Q3 的」,
26/// 而那句话在正文里,标题可能被截成了别的样子。
27pub async fn list(
28 pool: &PgPool,
29 kb_id: Uuid,
30 user_id: Uuid,
31 q: Option<&str>,
32 limit: i64,
33 offset: i64,
34) -> AppResult<(Vec<ConversationView>, i64)> {
35 const WHERE: &str = "WHERE c.kb_id = $1 AND c.user_id = $2
36 AND ($3::text IS NULL
37 OR c.title ILIKE '%' || $3 || '%'
38 OR EXISTS (SELECT 1 FROM conversation_messages m
39 WHERE m.conversation_id = c.id
40 AND m.content ILIKE '%' || $3 || '%'))";
41 let rows: Vec<ConversationView> = sqlx::query_as(&format!(
42 "SELECT c.id, c.title, c.created_at, c.updated_at,
43 (SELECT count(*) FROM conversation_messages m
44 WHERE m.conversation_id = c.id) AS message_count
45 FROM conversations c
46 {WHERE}
47 ORDER BY c.updated_at DESC
48 LIMIT $4 OFFSET $5"
49 ))
50 .bind(kb_id)
51 .bind(user_id)
52 .bind(q)
53 .bind(limit)
54 .bind(offset)
55 .fetch_all(pool)
56 .await?;
57 let (total,): (i64,) = sqlx::query_as(&format!("SELECT count(*) FROM conversations c {WHERE}"))
58 .bind(kb_id)
59 .bind(user_id)
60 .bind(q)
61 .fetch_one(pool)
62 .await?;
63 Ok((rows, total))
64}
65
66/// 改一个会话的标题。
67///
68/// **标题本来是从第一句话自动取的**,而那句话往往不是它后来变成的样子——
69/// 一段对话跑偏是常态,改名让人能按自己记得的方式找回它。
70pub async fn rename(
71 pool: &PgPool,
72 kb_id: Uuid,
73 user_id: Uuid,
74 conversation_id: Uuid,
75 title: &str,
76) -> AppResult<()> {
77 let title = title.trim();
78 if title.is_empty() || title.chars().count() > 120 {
79 return Err(AppError::invalid(
80 "bad_title",
81 "Title must be 1-120 characters",
82 ));
83 }
84 let res = sqlx::query(
85 "UPDATE conversations SET title = $4
86 WHERE id = $3 AND kb_id = $1 AND user_id = $2",
87 )
88 .bind(kb_id)
89 .bind(user_id)
90 .bind(conversation_id)
91 .bind(title)
92 .execute(pool)
93 .await?;
94 if res.rows_affected() == 0 {
95 return Err(AppError::NotFound);
96 }
97 Ok(())
98}
99
100/// 归属校验:会话必须属于本 KB 本人。
101pub async fn require_owned(
102 pool: &PgPool,
103 kb_id: Uuid,
104 user_id: Uuid,
105 conversation_id: Uuid,
106) -> AppResult<()> {
107 let found: Option<(Uuid,)> = sqlx::query_as(
108 "SELECT id FROM conversations WHERE id = $1 AND kb_id = $2 AND user_id = $3",
109 )
110 .bind(conversation_id)
111 .bind(kb_id)
112 .bind(user_id)
113 .fetch_optional(pool)
114 .await?;
115 found.map(|_| ()).ok_or(AppError::NotFound)
116}
117
118pub async fn messages(pool: &PgPool, conversation_id: Uuid) -> AppResult<Vec<ConversationMessage>> {
119 let rows: Vec<ConversationMessage> = sqlx::query_as(
120 "SELECT id, role, content, steps, sources, created_at
121 FROM conversation_messages WHERE conversation_id = $1 ORDER BY created_at",
122 )
123 .bind(conversation_id)
124 .fetch_all(pool)
125 .await?;
126 Ok(rows)
127}
128
129/// 一轮回放的历史。
130///
131/// 三样东西,各自回答一个不同的问题:正文(说过什么)、实体(认下了谁)、
132/// 最近一轮的工具往返(**做过什么**)。
133///
134/// 第三样是后加的。原先的判断是「回放身份足矣:有了 id,下一轮直接调
135/// entity_facts」——省下的是每轮堆积的 chunk 正文,那个考虑没错。但它把
136/// 「我已经查过了」这件事也一起省掉了:跨轮之后模型只看得见自己写的散文,
137/// 于是接着说「翻译」时重查一遍,还落到了另一批同名实体上。
138///
139/// 折中是**只回放最近一轮**:需要的是「我刚做过什么」,不是二十轮的输出。
140pub struct History {
141 /// `(role, content)`,按时间序
142 pub turns: Vec<(String, String)>,
143 /// 这场对话里已经认下的实体(去重)
144 pub entities: Vec<serde_json::Value>,
145 /// **最近一轮助手做过什么**:带 `tool_calls` 的助手消息与配套的 tool 结果。
146 ///
147 /// 只有最近一轮。这一段是为了让模型知道自己刚做过什么——接着说
148 /// 「翻译」「短一点」的时候,证据就在眼前,不必重查(也就不会重查成
149 /// 另一批同名实体)。搬二十轮的工具输出回来是另一回事,那正是当初
150 /// 只存正文的理由。
151 pub last_tool_exchange: Vec<serde_json::Value>,
152}
153
154pub async fn recent_context(pool: &PgPool, conversation_id: Uuid, n: i64) -> AppResult<History> {
155 let mut rows: Vec<(
156 String,
157 String,
158 serde_json::Value,
159 serde_json::Value,
160 DateTime<Utc>,
161 )> = sqlx::query_as(
162 "SELECT role, content, resolved, tool_exchange, created_at FROM conversation_messages
163 WHERE conversation_id = $1 ORDER BY created_at DESC LIMIT $2",
164 )
165 .bind(conversation_id)
166 .bind(n)
167 .fetch_all(pool)
168 .await?;
169 rows.reverse();
170 // 实体按 id 去重、保持首次出现的顺序:同一个实体在几轮里反复出现是常态,
171 // 每轮各列一遍只是把同一件事说三遍
172 let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
173 let mut entities: Vec<serde_json::Value> = Vec::new();
174 for (_, _, res, _, _) in &rows {
175 for e in res.as_array().into_iter().flatten() {
176 let Some(id) = e["id"].as_str() else { continue };
177 if seen.insert(id.to_string()) {
178 entities.push(e.clone());
179 }
180 }
181 }
182 // 最后一条助手消息的那一段。**倒着找**——最后一条通常是刚落库的用户消息
183 let last_tool_exchange = rows
184 .iter()
185 .rev()
186 .find(|(role, _, _, _, _)| role == "assistant")
187 .and_then(|(_, _, _, ex, _)| ex.as_array().cloned())
188 .unwrap_or_default();
189 Ok(History {
190 turns: rows.into_iter().map(|(r, c, _, _, _)| (r, c)).collect(),
191 entities,
192 last_tool_exchange,
193 })
194}
195
196/// 一轮除了正文之外留下的东西。
197///
198/// **四个都是 `serde_json::Value`,散着传编译器帮不上忙**——传错顺序会得到
199/// 一条能落库、也能读回来、只是内容张冠李戴的记录。与 `RelationAxioms` 同一条理由。
200#[derive(Default)]
201pub struct TurnRecord {
202 /// 行动轨迹:调了什么、拿到多少(界面显示)
203 pub steps: serde_json::Value,
204 /// 引用清单
205 pub sources: serde_json::Value,
206 /// 这一轮认下的实体(id / 名字 / 类型)。下一轮回放,让模型接着走而不是重搜
207 pub resolved: serde_json::Value,
208 /// 这一轮调了什么、拿回什么(已截断的那一份)。下一轮回放最近的一段——
209 /// 没有它,模型跨轮之后就不知道自己查过,于是重查
210 pub tool_exchange: serde_json::Value,
211}
212
213impl TurnRecord {
214 /// 用户消息:四样都空。
215 pub fn empty() -> Self {
216 Self {
217 steps: serde_json::json!([]),
218 sources: serde_json::json!([]),
219 resolved: serde_json::json!([]),
220 tool_exchange: serde_json::json!([]),
221 }
222 }
223}
224
225pub async fn append_message(
226 pool: &PgPool,
227 conversation_id: Uuid,
228 role: &str,
229 content: &str,
230 rec: &TurnRecord,
231) -> AppResult<Uuid> {
232 let id = Uuid::now_v7();
233 let mut tx = pool.begin().await?;
234 sqlx::query(
235 "INSERT INTO conversation_messages
236 (id, conversation_id, role, content, steps, sources, resolved, tool_exchange)
237 VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
238 )
239 .bind(id)
240 .bind(conversation_id)
241 .bind(role)
242 .bind(content)
243 .bind(&rec.steps)
244 .bind(&rec.sources)
245 .bind(&rec.resolved)
246 .bind(&rec.tool_exchange)
247 .execute(&mut *tx)
248 .await?;
249 sqlx::query("UPDATE conversations SET updated_at = now() WHERE id = $1")
250 .bind(conversation_id)
251 .execute(&mut *tx)
252 .await?;
253 tx.commit().await?;
254 Ok(id)
255}
256
257pub async fn delete(
258 pool: &PgPool,
259 kb_id: Uuid,
260 user_id: Uuid,
261 conversation_id: Uuid,
262) -> AppResult<()> {
263 let res =
264 sqlx::query("DELETE FROM conversations WHERE id = $1 AND kb_id = $2 AND user_id = $3")
265 .bind(conversation_id)
266 .bind(kb_id)
267 .bind(user_id)
268 .execute(pool)
269 .await?;
270 if res.rows_affected() == 0 {
271 return Err(AppError::NotFound);
272 }
273 Ok(())
274}