| 1 | //! Chat 会话持久化:对话/消息仓储。轨迹(steps)与引用(sources)随 |
| 2 | //! assistant 消息落库,历史回放与实时流共用同一数据形状。 |
| 3 | |
| 4 | use chrono::{DateTime, Utc}; |
| 5 | use sqlx::PgPool; |
| 6 | use utopia_core::models::{ConversationMessage, ConversationView}; |
| 7 | use utopia_core::{AppError, AppResult}; |
| 8 | use uuid::Uuid; |
| 9 | |
| 10 | pub 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 | /// 而那句话在正文里,标题可能被截成了别的样子。 |
| 27 | pub 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 | /// 一段对话跑偏是常态,改名让人能按自己记得的方式找回它。 |
| 70 | pub 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 本人。 |
| 101 | pub 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 | |
| 118 | pub 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 | /// 服务端拼上下文用:最近 n 条的 (role, content),按时间正序。 |
| 130 | /// 回放最近几轮:角色、正文,**以及那几轮认下的实体**。 |
| 131 | /// |
| 132 | /// 只回放角色与正文时,模型看不见自己上一轮搜过什么、拿到过哪些 id,只能从 |
| 133 | /// 名字重搜一遍——实测就是这个样子。**但整段工具结果也不该回放**:那里面是 |
| 134 | /// chunk 正文,每轮重复堆进上下文,几轮就把窗口吃光。回放身份足矣:有了 id, |
| 135 | /// 下一轮直接调 entity_facts。 |
| 136 | pub async fn recent_context( |
| 137 | pool: &PgPool, |
| 138 | conversation_id: Uuid, |
| 139 | n: i64, |
| 140 | ) -> AppResult<(Vec<(String, String)>, Vec<serde_json::Value>)> { |
| 141 | let mut rows: Vec<(String, String, serde_json::Value, DateTime<Utc>)> = sqlx::query_as( |
| 142 | "SELECT role, content, resolved, created_at FROM conversation_messages |
| 143 | WHERE conversation_id = $1 ORDER BY created_at DESC LIMIT $2", |
| 144 | ) |
| 145 | .bind(conversation_id) |
| 146 | .bind(n) |
| 147 | .fetch_all(pool) |
| 148 | .await?; |
| 149 | rows.reverse(); |
| 150 | // 实体按 id 去重、保持首次出现的顺序:同一个实体在几轮里反复出现是常态, |
| 151 | // 每轮各列一遍只是把同一件事说三遍 |
| 152 | let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new(); |
| 153 | let mut entities: Vec<serde_json::Value> = Vec::new(); |
| 154 | for (_, _, res, _) in &rows { |
| 155 | for e in res.as_array().into_iter().flatten() { |
| 156 | let Some(id) = e["id"].as_str() else { continue }; |
| 157 | if seen.insert(id.to_string()) { |
| 158 | entities.push(e.clone()); |
| 159 | } |
| 160 | } |
| 161 | } |
| 162 | Ok(( |
| 163 | rows.into_iter().map(|(r, c, _, _)| (r, c)).collect(), |
| 164 | entities, |
| 165 | )) |
| 166 | } |
| 167 | |
| 168 | pub async fn append_message( |
| 169 | pool: &PgPool, |
| 170 | conversation_id: Uuid, |
| 171 | role: &str, |
| 172 | content: &str, |
| 173 | steps: &serde_json::Value, |
| 174 | sources: &serde_json::Value, |
| 175 | // 这一轮认下的实体(id / 名字 / 类型)。下一轮回放,让模型接着走而不是重搜 |
| 176 | resolved: &serde_json::Value, |
| 177 | ) -> AppResult<Uuid> { |
| 178 | let id = Uuid::now_v7(); |
| 179 | let mut tx = pool.begin().await?; |
| 180 | sqlx::query( |
| 181 | "INSERT INTO conversation_messages |
| 182 | (id, conversation_id, role, content, steps, sources, resolved) |
| 183 | VALUES ($1, $2, $3, $4, $5, $6, $7)", |
| 184 | ) |
| 185 | .bind(id) |
| 186 | .bind(conversation_id) |
| 187 | .bind(role) |
| 188 | .bind(content) |
| 189 | .bind(steps) |
| 190 | .bind(sources) |
| 191 | .bind(resolved) |
| 192 | .execute(&mut *tx) |
| 193 | .await?; |
| 194 | sqlx::query("UPDATE conversations SET updated_at = now() WHERE id = $1") |
| 195 | .bind(conversation_id) |
| 196 | .execute(&mut *tx) |
| 197 | .await?; |
| 198 | tx.commit().await?; |
| 199 | Ok(id) |
| 200 | } |
| 201 | |
| 202 | pub async fn delete( |
| 203 | pool: &PgPool, |
| 204 | kb_id: Uuid, |
| 205 | user_id: Uuid, |
| 206 | conversation_id: Uuid, |
| 207 | ) -> AppResult<()> { |
| 208 | let res = |
| 209 | sqlx::query("DELETE FROM conversations WHERE id = $1 AND kb_id = $2 AND user_id = $3") |
| 210 | .bind(conversation_id) |
| 211 | .bind(kb_id) |
| 212 | .bind(user_id) |
| 213 | .execute(pool) |
| 214 | .await?; |
| 215 | if res.rows_affected() == 0 { |
| 216 | return Err(AppError::NotFound); |
| 217 | } |
| 218 | Ok(()) |
| 219 | } |