Changesets · Branches · Tags · Compare
| Changeset | c83424aa778cafbf2ecceb95bd396e00c328fd6e9ee97dd0c5a0a85a8d17ac7f |
|---|---|
| Author | WaylandYang <145302500+WaylandYang@users.noreply.github.com> · 2026-09-02 14:28 +08:00 |
| Committer | GitHub <noreply@github.com> · 2026-09-02 14:28 +08:00 |
| Parents | 35e8565cc9bd |
3 files changed
modified crates/utopia-server/src/api/chat.rs +47 −19
| @@ -386,12 +386,10 @@ | ||
| 386 | 386 | conversation_id, |
| 387 | 387 | "user", |
| 388 | 388 | &query, |
| 389 | - &json!([]), | |
| 390 | - &json!([]), | |
| 391 | - &json!([]), | |
| 389 | + &utopia_store::conversations::TurnRecord::empty(), | |
| 392 | 390 | ) |
| 393 | 391 | .await?; |
| 394 | - let (history, known_entities) = utopia_store::conversations::recent_context( | |
| 392 | + let history = utopia_store::conversations::recent_context( | |
| 395 | 393 | &state.pool, |
| 396 | 394 | conversation_id, |
| 397 | 395 | MAX_HISTORY as i64, |
| @@ -463,7 +461,22 @@ | ||
| 463 | 461 | } |
| 464 | 462 | let mut msgs: Vec<serde_json::Value> = |
| 465 | 463 | vec![json!({ "role": "system", "content": system_prompt })]; |
| 466 | - for (role, content) in &history { | |
| 464 | + /* **上一轮做过什么,按它当时发生的位置放回去。** | |
| 465 | + 最后那条助手消息是它的结论;带 `tool_calls` 的消息与 tool 结果 | |
| 466 | + 发生在它之前,所以插在它前面——顺序就是真实顺序,模型读起来 | |
| 467 | + 就是「我问了、我查了、我答了」。 | |
| 468 | + 少了这一段,跨轮之后它只看得见自己写的散文,于是接着说「翻译」 | |
| 469 | + 时重查一遍(还可能落到另一批同名实体上)。 */ | |
| 470 | + let last_assistant = history | |
| 471 | + .turns | |
| 472 | + .iter() | |
| 473 | + .rposition(|(role, _)| role == "assistant"); | |
| 474 | + for (i, (role, content)) in history.turns.iter().enumerate() { | |
| 475 | + if Some(i) == last_assistant { | |
| 476 | + for m in &history.last_tool_exchange { | |
| 477 | + msgs.push(m.clone()); | |
| 478 | + } | |
| 479 | + } | |
| 467 | 480 | msgs.push(json!({ "role": role, "content": content })); |
| 468 | 481 | } |
| 469 | 482 | // **前几轮已经认下的实体,连 id 一起交回去。** |
| @@ -474,8 +487,8 @@ | ||
| 474 | 487 | // |
| 475 | 488 | // 贴在历史之后、当前问题之前——位置就是服从性,跟抽取里 known_block |
| 476 | 489 | // 紧挨正文是同一条理由。 |
| 477 | - if !known_entities.is_empty() { | |
| 478 | - let lines: Vec<String> = known_entities | |
| 490 | + if !history.entities.is_empty() { | |
| 491 | + let lines: Vec<String> = history.entities | |
| 479 | 492 | .iter() |
| 480 | 493 | .take(KNOWN_ENTITY_LIMIT) |
| 481 | 494 | .map(|e| { |
| @@ -507,6 +520,8 @@ | ||
| 507 | 520 | // 落库累积:assistant 全文与行动轨迹(历史回放用) |
| 508 | 521 | let mut answer_acc = String::new(); |
| 509 | 522 | let mut steps_acc: Vec<serde_json::Value> = Vec::new(); |
| 523 | + // 这一轮的工具往返,原样留一份落库:下一轮回放它,模型才知道自己做过什么 | |
| 524 | + let mut exchange_acc: Vec<serde_json::Value> = Vec::new(); | |
| 510 | 525 | // 这一轮认下的实体,落库供下一轮回放。**只记身份不记正文**—— |
| 511 | 526 | // 工具结果里是 chunk 全文,每轮重复堆进上下文几轮就把窗口吃光 |
| 512 | 527 | let mut resolved_acc: Vec<serde_json::Value> = Vec::new(); |
| @@ -530,9 +545,12 @@ | ||
| 530 | 545 | } |
| 531 | 546 | let _ = utopia_store::conversations::append_message( |
| 532 | 547 | &state.pool, conversation_id, "assistant", &answer_acc, |
| 533 | - &serde_json::Value::Array(steps_acc.clone()), | |
| 534 | - &serde_json::Value::Array(sources.clone()), | |
| 535 | - &serde_json::Value::Array(resolved_acc.clone()), | |
| 548 | + &utopia_store::conversations::TurnRecord { | |
| 549 | + steps: serde_json::Value::Array(steps_acc.clone()), | |
| 550 | + sources: serde_json::Value::Array(sources.clone()), | |
| 551 | + resolved: serde_json::Value::Array(resolved_acc.clone()), | |
| 552 | + tool_exchange: serde_json::Value::Array(exchange_acc.clone()), | |
| 553 | + }, | |
| 536 | 554 | ).await; |
| 537 | 555 | yield done_event(); |
| 538 | 556 | } |
| @@ -563,7 +581,7 @@ | ||
| 563 | 581 | ); |
| 564 | 582 | let mut lmsgs = |
| 565 | 583 | vec![json!({ "role": "system", "content": legacy_system_prompt(&chunks) })]; |
| 566 | - for (role, content) in &history { | |
| 584 | + for (role, content) in &history.turns { | |
| 567 | 585 | lmsgs.push(json!({ "role": role, "content": content })); |
| 568 | 586 | } |
| 569 | 587 | match client.chat_stream_raw(&lmsgs).await { |
| @@ -577,9 +595,12 @@ | ||
| 577 | 595 | } |
| 578 | 596 | let _ = utopia_store::conversations::append_message( |
| 579 | 597 | &state.pool, conversation_id, "assistant", &answer_acc, |
| 580 | - &serde_json::Value::Array(steps_acc.clone()), | |
| 581 | - &serde_json::Value::Array(legacy_sources.clone()), | |
| 582 | - &serde_json::Value::Array(resolved_acc.clone()), | |
| 598 | + &utopia_store::conversations::TurnRecord { | |
| 599 | + steps: serde_json::Value::Array(steps_acc.clone()), | |
| 600 | + sources: serde_json::Value::Array(legacy_sources.clone()), | |
| 601 | + resolved: serde_json::Value::Array(resolved_acc.clone()), | |
| 602 | + tool_exchange: serde_json::Value::Array(exchange_acc.clone()), | |
| 603 | + }, | |
| 583 | 604 | ).await; |
| 584 | 605 | yield done_event(); |
| 585 | 606 | } |
| @@ -619,9 +640,12 @@ | ||
| 619 | 640 | } else { |
| 620 | 641 | let _ = utopia_store::conversations::append_message( |
| 621 | 642 | &state.pool, conversation_id, "assistant", &answer_acc, |
| 622 | - &serde_json::Value::Array(steps_acc.clone()), | |
| 623 | - &serde_json::Value::Array(sources.clone()), | |
| 624 | - &serde_json::Value::Array(resolved_acc.clone()), | |
| 643 | + &utopia_store::conversations::TurnRecord { | |
| 644 | + steps: serde_json::Value::Array(steps_acc.clone()), | |
| 645 | + sources: serde_json::Value::Array(sources.clone()), | |
| 646 | + resolved: serde_json::Value::Array(resolved_acc.clone()), | |
| 647 | + tool_exchange: serde_json::Value::Array(exchange_acc.clone()), | |
| 648 | + }, | |
| 625 | 649 | ).await; |
| 626 | 650 | yield done_event(); |
| 627 | 651 | } |
| @@ -634,7 +658,9 @@ | ||
| 634 | 658 | yield delta_event("\n\n"); |
| 635 | 659 | } |
| 636 | 660 | |
| 637 | - msgs.push(turn.to_message()); | |
| 661 | + let call_msg = turn.to_message(); | |
| 662 | + exchange_acc.push(call_msg.clone()); | |
| 663 | + msgs.push(call_msg); | |
| 638 | 664 | for call in &turn.tool_calls { |
| 639 | 665 | // **说不清自己要做什么的调用不执行。** 把话回给模型,让它重来 |
| 640 | 666 | let args = match check_call(&tools, &call.name, &call.arguments) { |
| @@ -942,7 +968,9 @@ | ||
| 942 | 968 | serde_json::to_string(&sources).unwrap_or_else(|_| "[]".into()), |
| 943 | 969 | ); |
| 944 | 970 | } |
| 945 | - msgs.push(tool_result_message(&call.id, &result)); | |
| 971 | + let result_msg = tool_result_message(&call.id, &result); | |
| 972 | + exchange_acc.push(result_msg.clone()); | |
| 973 | + msgs.push(result_msg); | |
| 946 | 974 | } |
| 947 | 975 | rounds += 1; |
| 948 | 976 | } |
modified crates/utopia-store/src/conversations.rs +81 −26
| @@ -126,20 +126,40 @@ | ||
| 126 | 126 | Ok(rows) |
| 127 | 127 | } |
| 128 | 128 | |
| 129 | -/// 服务端拼上下文用:最近 n 条的 (role, content),按时间正序。 | |
| 130 | -/// 回放最近几轮:角色、正文,**以及那几轮认下的实体**。 | |
| 129 | +/// 一轮回放的历史。 | |
| 131 | 130 | /// |
| 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 | |
| 131 | +/// 三样东西,各自回答一个不同的问题:正文(说过什么)、实体(认下了谁)、 | |
| 132 | +/// 最近一轮的工具往返(**做过什么**)。 | |
| 133 | +/// | |
| 134 | +/// 第三样是后加的。原先的判断是「回放身份足矣:有了 id,下一轮直接调 | |
| 135 | +/// entity_facts」——省下的是每轮堆积的 chunk 正文,那个考虑没错。但它把 | |
| 136 | +/// 「我已经查过了」这件事也一起省掉了:跨轮之后模型只看得见自己写的散文, | |
| 137 | +/// 于是接着说「翻译」时重查一遍,还落到了另一批同名实体上。 | |
| 138 | +/// | |
| 139 | +/// 折中是**只回放最近一轮**:需要的是「我刚做过什么」,不是二十轮的输出。 | |
| 140 | +pub 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 | + | |
| 154 | +pub 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 | |
| 143 | 163 | WHERE conversation_id = $1 ORDER BY created_at DESC LIMIT $2", |
| 144 | 164 | ) |
| 145 | 165 | .bind(conversation_id) |
| @@ -151,7 +171,7 @@ | ||
| 151 | 171 | // 每轮各列一遍只是把同一件事说三遍 |
| 152 | 172 | let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new(); |
| 153 | 173 | let mut entities: Vec<serde_json::Value> = Vec::new(); |
| 154 | - for (_, _, res, _) in &rows { | |
| 174 | + for (_, _, res, _, _) in &rows { | |
| 155 | 175 | for e in res.as_array().into_iter().flatten() { |
| 156 | 176 | let Some(id) = e["id"].as_str() else { continue }; |
| 157 | 177 | if seen.insert(id.to_string()) { |
| @@ -159,10 +179,47 @@ | ||
| 159 | 179 | } |
| 160 | 180 | } |
| 161 | 181 | } |
| 162 | - Ok(( | |
| 163 | - rows.into_iter().map(|(r, c, _, _)| (r, c)).collect(), | |
| 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(), | |
| 164 | 191 | entities, |
| 165 | - )) | |
| 192 | + last_tool_exchange, | |
| 193 | + }) | |
| 194 | +} | |
| 195 | + | |
| 196 | +/// 一轮除了正文之外留下的东西。 | |
| 197 | +/// | |
| 198 | +/// **四个都是 `serde_json::Value`,散着传编译器帮不上忙**——传错顺序会得到 | |
| 199 | +/// 一条能落库、也能读回来、只是内容张冠李戴的记录。与 `RelationAxioms` 同一条理由。 | |
| 200 | +#[derive(Default)] | |
| 201 | +pub 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 | + | |
| 213 | +impl 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 | + } | |
| 166 | 223 | } |
| 167 | 224 | |
| 168 | 225 | pub async fn append_message( |
| @@ -170,25 +227,23 @@ | ||
| 170 | 227 | conversation_id: Uuid, |
| 171 | 228 | role: &str, |
| 172 | 229 | content: &str, |
| 173 | - steps: &serde_json::Value, | |
| 174 | - sources: &serde_json::Value, | |
| 175 | - // 这一轮认下的实体(id / 名字 / 类型)。下一轮回放,让模型接着走而不是重搜 | |
| 176 | - resolved: &serde_json::Value, | |
| 230 | + rec: &TurnRecord, | |
| 177 | 231 | ) -> AppResult<Uuid> { |
| 178 | 232 | let id = Uuid::now_v7(); |
| 179 | 233 | let mut tx = pool.begin().await?; |
| 180 | 234 | sqlx::query( |
| 181 | 235 | "INSERT INTO conversation_messages |
| 182 | - (id, conversation_id, role, content, steps, sources, resolved) | |
| 183 | - VALUES ($1, $2, $3, $4, $5, $6, $7)", | |
| 236 | + (id, conversation_id, role, content, steps, sources, resolved, tool_exchange) | |
| 237 | + VALUES ($1, $2, $3, $4, $5, $6, $7, $8)", | |
| 184 | 238 | ) |
| 185 | 239 | .bind(id) |
| 186 | 240 | .bind(conversation_id) |
| 187 | 241 | .bind(role) |
| 188 | 242 | .bind(content) |
| 189 | - .bind(steps) | |
| 190 | - .bind(sources) | |
| 191 | - .bind(resolved) | |
| 243 | + .bind(&rec.steps) | |
| 244 | + .bind(&rec.sources) | |
| 245 | + .bind(&rec.resolved) | |
| 246 | + .bind(&rec.tool_exchange) | |
| 192 | 247 | .execute(&mut *tx) |
| 193 | 248 | .await?; |
| 194 | 249 | sqlx::query("UPDATE conversations SET updated_at = now() WHERE id = $1") |
added migrations/0015_what_it_did_not_just_what_it_said.sql +28 −0
| @@ -0,0 +1,28 @@ | ||
| 1 | +-- 助手那一轮**做了什么**,而不只是最后说了什么。 | |
| 2 | +-- | |
| 3 | +-- 起因是一个看着像提示词问题的 bug:接着上一轮说「翻译」,助手把整轮工具 | |
| 4 | +-- 重新跑了一遍,而且因为同名实体有八个,第二遍落到了另一批上——要的是同一段话 | |
| 5 | +-- 换个语言,拿到的是另一段内容。 | |
| 6 | +-- | |
| 7 | +-- 真正的原因不在提示词。`conversations::recent_context` 回的是 `(role, content)`: | |
| 8 | +-- 一轮之内模型看得见自己调过什么(那些消息还在 `msgs` 里),**跨轮之后全丢了**, | |
| 9 | +-- 只剩它自己写的那段散文。于是下一轮它并不知道自己查过——重查是它能做的 | |
| 10 | +-- 最合理的判断。用提示词去压一个正确的推断,压得赢一部分:实测四次里三次。 | |
| 11 | +-- | |
| 12 | +-- 所以别丢。这一列存那一轮完整的消息尾巴——带 `tool_calls` 的助手消息, | |
| 13 | +-- 以及配套的 tool 结果消息——回放时原样发回去。 | |
| 14 | +ALTER TABLE conversation_messages | |
| 15 | + -- 形如 `[{"role":"assistant","tool_calls":[...]}, {"role":"tool","tool_call_id":...}, ...]`。 | |
| 16 | + -- | |
| 17 | + -- **存已经截断过的那一份**:工具结果在发给模型之前就按 | |
| 18 | + -- `TOOL_CHUNK_CHARS` 截过,这里存的是同一份,不是原始返回。存原始的等于 | |
| 19 | + -- 让回放比当初那一轮还占地方。 | |
| 20 | + -- | |
| 21 | + -- 只对 assistant 行有意义;user 行恒为空数组 | |
| 22 | + ADD COLUMN tool_exchange JSONB NOT NULL DEFAULT '[]'::jsonb; | |
| 23 | + | |
| 24 | +-- **只回放最近一轮。** 这一列是为了让模型知道「我刚做过什么」, | |
| 25 | +-- 而不是把二十轮的工具输出都搬回上下文——那正是当初只存正文的理由。 | |
| 26 | +-- 所以没有索引:查的时候本来就带着 conversation_id 和时间序。 | |
| 27 | +COMMENT ON COLUMN conversation_messages.tool_exchange IS | |
| 28 | + 'The assistant turn''s tool calls and their results, replayed for the most recent turn so the model knows what it already did.'; |