| 1 | //! Agentic 对话:模型自主调用工具(文档检索 / 实体查找 / 时态事实)收集证据后作答。 |
| 2 | //! 事件序列:step*(行动轨迹)| sources(引用清单,随检索增量更新)| delta*(增量文本)→ done | error。 |
| 3 | //! 模型不支持 tool-calling 时自动降级为一次性 RAG 注入。 |
| 4 | |
| 5 | use axum::extract::{Path, Query, State}; |
| 6 | use axum::response::sse::{Event, KeepAlive, Sse}; |
| 7 | use axum::Json; |
| 8 | use futures_util::{Stream, StreamExt}; |
| 9 | use serde::Deserialize; |
| 10 | use serde_json::json; |
| 11 | use std::convert::Infallible; |
| 12 | use utopia_core::models::{ChunkView, EntityFact, GraphChange, Role}; |
| 13 | use utopia_core::AppError; |
| 14 | use utopia_llm::tool_result_message; |
| 15 | use uuid::Uuid; |
| 16 | |
| 17 | use crate::auth::AuthUser; |
| 18 | use crate::error::ApiResult; |
| 19 | use crate::llm_util; |
| 20 | use crate::retrieval; |
| 21 | use crate::state::AppState; |
| 22 | |
| 23 | /// 回放几个已认下的实体。上限是因为长会话会攒出几十个,全贴回去就把 |
| 24 | /// 省下来的上下文又花掉了;按首次出现排序,早认下的通常是这场对话的主角。 |
| 25 | const KNOWN_ENTITY_LIMIT: usize = 20; |
| 26 | |
| 27 | const MAX_HISTORY: usize = 20; |
| 28 | const MAX_ROUNDS: usize = 6; |
| 29 | const SEARCH_TOP_K: usize = 6; |
| 30 | const TOOL_CHUNK_CHARS: usize = 800; |
| 31 | /// 一次 changes 最多回多少条。刚灌完的库里 asserted 是成百上千条,全发出去 |
| 32 | /// 只会把上下文填满而不增加信息——有信息量的是 corrected/rejected,那类事件 |
| 33 | /// 本来就稀少。截断时 detail 写 "40+",模型据此知道该收窄窗口 |
| 34 | const CHANGES_LIMIT: i64 = 40; |
| 35 | |
| 36 | #[derive(Deserialize)] |
| 37 | pub struct ChatReq { |
| 38 | /// 缺省 = 新建会话(SSE 首个 `conversation` 事件回传 id) |
| 39 | #[serde(default)] |
| 40 | pub conversation_id: Option<Uuid>, |
| 41 | pub message: String, |
| 42 | } |
| 43 | |
| 44 | fn tools_schema(can_write: bool, data_source_names: &[String]) -> serde_json::Value { |
| 45 | let mut tools = base_tools(); |
| 46 | if !data_source_names.is_empty() { |
| 47 | if let Some(arr) = tools.as_array_mut() { |
| 48 | arr.push(json!({ |
| 49 | "type": "function", |
| 50 | "function": { |
| 51 | "name": "query_data", |
| 52 | "description": format!( |
| 53 | "Run a read-only SQL query against a mounted database. Available sources: \ |
| 54 | {}. Search the source's schema document first (search_chunks) if unsure \ |
| 55 | of tables/columns. Only a single SELECT/WITH statement is allowed; a \ |
| 56 | LIMIT is enforced server-side; results come back as JSON lines. If the \ |
| 57 | query errors, fix the SQL and retry once.", |
| 58 | data_source_names.join(", ") |
| 59 | ), |
| 60 | "parameters": { |
| 61 | "type": "object", |
| 62 | "properties": { |
| 63 | "data_source": { |
| 64 | "type": "string", |
| 65 | "description": "Name of the mounted data source to query." |
| 66 | }, |
| 67 | "sql": { |
| 68 | "type": "string", |
| 69 | "description": "One SELECT/WITH statement (PostgreSQL dialect)." |
| 70 | }, |
| 71 | "purpose": { |
| 72 | "type": "string", |
| 73 | "description": "One short phrase: what this query answers (shown to the user)." |
| 74 | } |
| 75 | }, |
| 76 | "required": ["data_source", "sql"] |
| 77 | } |
| 78 | } |
| 79 | })); |
| 80 | } |
| 81 | } |
| 82 | if can_write { |
| 83 | if let Some(arr) = tools.as_array_mut() { |
| 84 | arr.push(json!({ |
| 85 | "type": "function", |
| 86 | "function": { |
| 87 | "name": "remember", |
| 88 | "description": "Record one memory episode into the knowledge base's temporal \ |
| 89 | memory. Use ONLY when the user explicitly asks to remember/record \ |
| 90 | something, or clearly states a decision or fact to keep. The episode is \ |
| 91 | extracted into the knowledge graph; if it contradicts an existing \ |
| 92 | single-valued fact, the old fact's validity is closed automatically \ |
| 93 | (never deleted). Do not use for casual conversation.", |
| 94 | "parameters": { |
| 95 | "type": "object", |
| 96 | "properties": { |
| 97 | "text": { |
| 98 | "type": "string", |
| 99 | "description": "The episode to remember, one self-contained \ |
| 100 | statement (who/what, with names spelled out)." |
| 101 | }, |
| 102 | "occurred_at": { |
| 103 | "type": "string", |
| 104 | "description": "Optional date the stated fact took effect \ |
| 105 | (YYYY-MM-DD). Omit to use today." |
| 106 | } |
| 107 | }, |
| 108 | "required": ["text"] |
| 109 | } |
| 110 | } |
| 111 | })); |
| 112 | } |
| 113 | } |
| 114 | tools |
| 115 | } |
| 116 | |
| 117 | const MEMORY_PROMPT: &str = "\ |
| 118 | Memory: you can persist knowledge with the remember tool. Use it when the user says \ |
| 119 | \"remember/record this\" or states a decision meant to last. Confirm in your reply what \ |
| 120 | was recorded. Never invent memories, and never call it for small talk."; |
| 121 | |
| 122 | fn base_tools() -> serde_json::Value { |
| 123 | json!([ |
| 124 | { |
| 125 | "type": "function", |
| 126 | "function": { |
| 127 | "name": "search_chunks", |
| 128 | "description": "Full-text + semantic search over the knowledge base documents. \ |
| 129 | Returns numbered source excerpts you can cite as [n].", |
| 130 | "parameters": { |
| 131 | "type": "object", |
| 132 | "properties": { |
| 133 | "query": { "type": "string", "description": "Search query, phrased in the corpus language." } |
| 134 | }, |
| 135 | "required": ["query"] |
| 136 | } |
| 137 | } |
| 138 | }, |
| 139 | { |
| 140 | "type": "function", |
| 141 | "function": { |
| 142 | "name": "search_docs", |
| 143 | "description": "Search Utopia's own user manual (the Charter): how the platform \ |
| 144 | itself works — sources and ingestion, sync semantics (missing markers, \ |
| 145 | tombstones, versions), the knowledge graph and review flow, roles and \ |
| 146 | permissions, settings. Use ONLY for questions about using or understanding \ |
| 147 | Utopia itself, or to explain platform concepts that appear in other tool \ |
| 148 | results (e.g. why a document is marked missing). NEVER use it to answer \ |
| 149 | questions about the content stored in the knowledge base.", |
| 150 | "parameters": { |
| 151 | "type": "object", |
| 152 | "properties": { |
| 153 | "query": { "type": "string", "description": "What to look up in the manual." } |
| 154 | }, |
| 155 | "required": ["query"] |
| 156 | } |
| 157 | } |
| 158 | }, |
| 159 | { |
| 160 | "type": "function", |
| 161 | "function": { |
| 162 | "name": "find_entities", |
| 163 | "description": "Look up entities in the knowledge graph by (partial) name. \ |
| 164 | Returns id, name, type and a disambiguator when several entities share a name.", |
| 165 | "parameters": { |
| 166 | "type": "object", |
| 167 | "properties": { |
| 168 | "name": { "type": "string", "description": "Entity name or a fragment of it." } |
| 169 | }, |
| 170 | "required": ["name"] |
| 171 | } |
| 172 | } |
| 173 | }, |
| 174 | { |
| 175 | "type": "function", |
| 176 | "function": { |
| 177 | "name": "entity_facts", |
| 178 | "description": "Facts about one entity from the bi-temporal knowledge graph: \ |
| 179 | relations with validity ranges (from → to; 'now' = still ongoing). \ |
| 180 | The best tool for who/when/history questions. Use after find_entities. \ |
| 181 | Pass `at` to see the world as of that date (server-side filter) — \ |
| 182 | always do this for \"who was X in <year/month>\" questions.", |
| 183 | "parameters": { |
| 184 | "type": "object", |
| 185 | "properties": { |
| 186 | "entity_id": { "type": "string", "description": "Entity id (uuid) from find_entities." }, |
| 187 | "at": { |
| 188 | "type": "string", |
| 189 | "description": "Optional as-of date (YYYY-MM-DD). Only facts valid on \ |
| 190 | this date are returned. Omit for the full history." |
| 191 | } |
| 192 | }, |
| 193 | "required": ["entity_id"] |
| 194 | } |
| 195 | } |
| 196 | }, |
| 197 | { |
| 198 | "type": "function", |
| 199 | "function": { |
| 200 | "name": "changes", |
| 201 | "description": "What the graph LEARNED or REVISED in a window of record time — the belief axis. Answers \"what changed since X\", \"what did we get wrong\", \"what is new this quarter\", and needs no entity, so use it when the question names a period rather than a subject. Events: asserted (new claim), corrected (a claim replaced by a revised one), rejected (a claim withdrawn), merged (folded into another claim) — each with the document it came from. NOT the same axis as entity_facts(at): that asks \"what was true on date D\"; this asks \"what did we change our mind about between D1 and D2\". A fact about 2019 can be recorded in 2026 — this windows on when we recorded it.", |
| 202 | "parameters": { |
| 203 | "type": "object", |
| 204 | "properties": { |
| 205 | "since": { |
| 206 | "type": "string", |
| 207 | "description": "Start of the window (YYYY-MM-DD), inclusive." |
| 208 | }, |
| 209 | "until": { |
| 210 | "type": "string", |
| 211 | "description": "End of the window (YYYY-MM-DD), inclusive of that whole day. Omit for 'up to now'." |
| 212 | }, |
| 213 | "entity_id": { |
| 214 | "type": "string", |
| 215 | "description": "Optional entity id from find_entities, to narrow the window to changes touching that one entity." |
| 216 | }, |
| 217 | "kinds": { |
| 218 | "type": "array", |
| 219 | "items": { |
| 220 | "type": "string", |
| 221 | "enum": ["asserted", "corrected", "rejected", "merged"] |
| 222 | }, |
| 223 | "description": "Optional filter. A freshly ingested corpus is nearly all 'asserted'; pass [\"corrected\", \"rejected\"] to isolate the places we actually changed our mind." |
| 224 | } |
| 225 | }, |
| 226 | "required": ["since"] |
| 227 | } |
| 228 | } |
| 229 | } |
| 230 | ]) |
| 231 | } |
| 232 | |
| 233 | const SYSTEM_PROMPT: &str = "You are the assistant of Utopia, a temporal knowledge platform. \ |
| 234 | You have tools: search_chunks (document search), find_entities, entity_facts and \ |
| 235 | changes (a bi-temporal knowledge graph), and search_docs (Utopia's own manual, the \ |
| 236 | Charter).\n\ |
| 237 | The graph has TWO independent time axes, and each graph tool reads exactly one:\n\ |
| 238 | - World time — when something was true. Read with entity_facts (`at` = as of that date).\n\ |
| 239 | - Record time — when we came to believe it, and when we revised it. Read with changes.\n\ |
| 240 | \"Who was CTO in 2019\" is world time; \"what did we learn last month\" and \"what did \ |
| 241 | we get wrong\" are record time. The same fact has a position on both.\n\ |
| 242 | Boundary: search_docs answers questions about Utopia itself (features, ingestion, \ |
| 243 | permissions, what fields like 'missing' or validity ranges mean); the other tools answer \ |
| 244 | questions about the knowledge stored in it. Never mix the manual into answers about the \ |
| 245 | user's data unless they asked about Utopia's behavior.\n\ |
| 246 | \n\ |
| 247 | Method:\n\ |
| 248 | 1. For factual questions, ALWAYS gather evidence with tools before answering. Prefer the \ |
| 249 | graph tools for questions about people/organizations/projects and time (\"who was X \ |
| 250 | when\", \"what changed\"), search_chunks for content and detail questions. Combine both \ |
| 251 | when useful.\n\ |
| 252 | 2. Facts carry validity ranges (from → to). For \"as of <date>\" questions pass `at` to \ |
| 253 | entity_facts and the server filters to that moment; for history questions omit `at` \ |
| 254 | to see the full timeline. State dates in the answer.\n\ |
| 255 | 2b. For \"what changed / what is new / what did we get wrong since <date>\", call changes — \ |
| 256 | it needs no entity. Name the document a correction came from in plain prose. Graph tools \ |
| 257 | return no [n] numbers and no URLs, so never write a bracketed citation or a placeholder \ |
| 258 | like [Link] after one — the document's name IS the attribution.\n\ |
| 259 | 3. Several entities can share one name — check the disambiguator and pick the right one; \ |
| 260 | if genuinely ambiguous, ask the user which one they mean.\n\ |
| 261 | 4. Stop calling tools as soon as you have enough evidence. Then answer concisely: cite \ |
| 262 | document sources with [n] (numbers from search results) at the end of supported \ |
| 263 | sentences. If the evidence is insufficient, say so explicitly — never fabricate.\n\ |
| 264 | 5. Always respond in the same language as the user's question."; |
| 265 | |
| 266 | pub async fn chat( |
| 267 | State(state): State<AppState>, |
| 268 | AuthUser(user): AuthUser, |
| 269 | Path(kb_id): Path<Uuid>, |
| 270 | Json(req): Json<ChatReq>, |
| 271 | ) -> ApiResult<Sse<impl Stream<Item = Result<Event, Infallible>>>> { |
| 272 | let kb = utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?; |
| 273 | // 写工具跟人走:editor 及以上的对话才带 remember,viewer 纯只读 |
| 274 | // 挂载的数据源决定 query_data 是否入列(问数是读,viewer 亦可用) |
| 275 | let mounted_sources = utopia_store::datasources::mounted(&state.pool, kb_id).await?; |
| 276 | // 语义层:人确认过的 指标/维度 → 数据资产 映射,直接进 system prompt—— |
| 277 | // 问数优先用确认口径,而不是每次从 schema 猜。 |
| 278 | // |
| 279 | // 从前这里按 `confidence >= 0.75` 捞事实,而那个阈值是拿浮点数编码一个 |
| 280 | // 二值状态(提议 0.6 / 确认 1.0)。现在读 `status = confirmed`(0011) |
| 281 | let mappings = if mounted_sources.is_empty() { |
| 282 | Vec::new() |
| 283 | } else { |
| 284 | utopia_store::mappings::confirmed(&state.pool, kb_id, 30).await? |
| 285 | }; |
| 286 | let can_write = utopia_store::access::kb_role(&state.pool, &user, &kb) |
| 287 | .await? |
| 288 | .is_some_and(|r| r >= Role::Editor); |
| 289 | |
| 290 | const NO_MODEL: &str = "Chat model not configured. Go to Settings → Models."; |
| 291 | let settings = utopia_store::settings::get(&state.pool, kb.workspace_id) |
| 292 | .await? |
| 293 | .ok_or_else(|| AppError::invalid("no_chat_model", NO_MODEL))?; |
| 294 | let client = llm_util::chat_client(&settings) |
| 295 | .ok_or_else(|| AppError::invalid("no_chat_model", NO_MODEL))?; |
| 296 | |
| 297 | let query = req.message.trim().to_string(); |
| 298 | if query.is_empty() { |
| 299 | return Err(AppError::Validation("Missing user message".into()).into()); |
| 300 | } |
| 301 | |
| 302 | // 会话持久化:有 id 则校验归属,无则以首句为题新建;用户消息即刻落库, |
| 303 | // 上下文由服务端从库里拼——前端只送新消息 |
| 304 | let conversation_id = match req.conversation_id { |
| 305 | Some(id) => { |
| 306 | utopia_store::conversations::require_owned(&state.pool, kb_id, user.id, id).await?; |
| 307 | id |
| 308 | } |
| 309 | None => utopia_store::conversations::create(&state.pool, kb_id, user.id, &query).await?, |
| 310 | }; |
| 311 | utopia_store::conversations::append_message( |
| 312 | &state.pool, |
| 313 | conversation_id, |
| 314 | "user", |
| 315 | &query, |
| 316 | &json!([]), |
| 317 | &json!([]), |
| 318 | &json!([]), |
| 319 | ) |
| 320 | .await?; |
| 321 | let (history, known_entities) = utopia_store::conversations::recent_context( |
| 322 | &state.pool, |
| 323 | conversation_id, |
| 324 | MAX_HISTORY as i64, |
| 325 | ) |
| 326 | .await?; |
| 327 | let workspace_id = kb.workspace_id; |
| 328 | |
| 329 | let stream = async_stream::stream! { |
| 330 | let ds_names: Vec<String> = mounted_sources.iter().map(|d| d.name.clone()).collect(); |
| 331 | let tools = tools_schema(can_write, &ds_names); |
| 332 | let mut system_prompt = if can_write { |
| 333 | format!("{SYSTEM_PROMPT}\n{MEMORY_PROMPT}") |
| 334 | } else { |
| 335 | SYSTEM_PROMPT.to_string() |
| 336 | }; |
| 337 | if !ds_names.is_empty() { |
| 338 | system_prompt.push_str(&format!( |
| 339 | "\nData: query_data runs read-only SQL (PostgreSQL dialect) against: {}. \ |
| 340 | For questions about numbers/metrics, search for the source's schema document \ |
| 341 | first, then query. State units and the time range you used in the answer.", |
| 342 | ds_names.join(", ") |
| 343 | )); |
| 344 | if !mappings.is_empty() { |
| 345 | system_prompt.push_str( |
| 346 | "\nSemantic layer (confirmed definitions — use these instead of guessing from schema):", |
| 347 | ); |
| 348 | // 从前这里直接把整份 JSON 打进去。现在字段是列,只挑问数用得上的 |
| 349 | // 那几样铺开——`sql` 与 `expr` 是「怎么算」,`unit` 是答里必须带的 |
| 350 | // 量纲,`summary` 是给模型的一句人话 |
| 351 | for m in &mappings { |
| 352 | let how = m |
| 353 | .sql |
| 354 | .as_deref() |
| 355 | .or(m.expr.as_deref()) |
| 356 | .or(m.table_name.as_deref()) |
| 357 | .unwrap_or("-"); |
| 358 | let unit = m |
| 359 | .unit |
| 360 | .as_deref() |
| 361 | .map(|u| format!(" [{u}]")) |
| 362 | .unwrap_or_default(); |
| 363 | let note = m |
| 364 | .summary |
| 365 | .as_deref() |
| 366 | .map(|s| format!(" — {s}")) |
| 367 | .unwrap_or_default(); |
| 368 | system_prompt.push_str(&format!( |
| 369 | "\n- {} ({}){unit}: {how}{note}", |
| 370 | m.concept_name, m.source |
| 371 | )); |
| 372 | } |
| 373 | } |
| 374 | } |
| 375 | let mut msgs: Vec<serde_json::Value> = |
| 376 | vec![json!({ "role": "system", "content": system_prompt })]; |
| 377 | for (role, content) in &history { |
| 378 | msgs.push(json!({ "role": role, "content": content })); |
| 379 | } |
| 380 | // **前几轮已经认下的实体,连 id 一起交回去。** |
| 381 | // |
| 382 | // 少了这一段,模型只看得见上一轮的最终答案文字,不知道自己搜过什么、 |
| 383 | // 拿到过哪些 id,于是从名字重搜一遍。更隐蔽的是同名歧义时两轮可能落到 |
| 384 | // **不同的实体**上,前后两个答案讲的不是同一个节点。 |
| 385 | // |
| 386 | // 贴在历史之后、当前问题之前——位置就是服从性,跟抽取里 known_block |
| 387 | // 紧挨正文是同一条理由。 |
| 388 | if !known_entities.is_empty() { |
| 389 | let lines: Vec<String> = known_entities |
| 390 | .iter() |
| 391 | .take(KNOWN_ENTITY_LIMIT) |
| 392 | .map(|e| { |
| 393 | format!( |
| 394 | "{} | {} | {}", |
| 395 | e["id"].as_str().unwrap_or("?"), |
| 396 | e["name"].as_str().unwrap_or("?"), |
| 397 | e["type"].as_str().unwrap_or("?") |
| 398 | ) |
| 399 | }) |
| 400 | .collect(); |
| 401 | msgs.push(json!({ |
| 402 | "role": "user", |
| 403 | "content": format!( |
| 404 | "Entities already identified earlier in this conversation (id | name | type). Call entity_facts with these ids directly; do not look them up by name again: |
| 405 | {}", |
| 406 | lines.join(" |
| 407 | ") |
| 408 | ) |
| 409 | })); |
| 410 | } |
| 411 | |
| 412 | // 会话 id 先行下发(新会话由此告知前端) |
| 413 | yield Ok(Event::default() |
| 414 | .event("conversation") |
| 415 | .data(json!({ "id": conversation_id }).to_string())); |
| 416 | |
| 417 | // 引用清单:跨轮累积、去重、编号稳定。键 = chunk uuid 或 "charter:{slug}#{anchor}" |
| 418 | let mut source_ids: Vec<String> = Vec::new(); |
| 419 | let mut sources: Vec<serde_json::Value> = Vec::new(); |
| 420 | // 落库累积:assistant 全文与行动轨迹(历史回放用) |
| 421 | let mut answer_acc = String::new(); |
| 422 | let mut steps_acc: Vec<serde_json::Value> = Vec::new(); |
| 423 | // 这一轮认下的实体,落库供下一轮回放。**只记身份不记正文**—— |
| 424 | // 工具结果里是 chunk 全文,每轮重复堆进上下文几轮就把窗口吃光 |
| 425 | let mut resolved_acc: Vec<serde_json::Value> = Vec::new(); |
| 426 | |
| 427 | let mut rounds = 0usize; |
| 428 | loop { |
| 429 | if rounds >= MAX_ROUNDS { |
| 430 | // 弹药耗尽:命令模型就现有证据作答(流式) |
| 431 | msgs.push(json!({ |
| 432 | "role": "user", |
| 433 | "content": "(system) Tool budget exhausted. Answer now from the evidence gathered above.", |
| 434 | })); |
| 435 | match client.chat_stream_raw(&msgs).await { |
| 436 | Ok(deltas) => { |
| 437 | let mut deltas = std::pin::pin!(deltas); |
| 438 | while let Some(item) = deltas.next().await { |
| 439 | match item { |
| 440 | Ok(text) => { answer_acc.push_str(&text); yield delta_event(&text); } |
| 441 | Err(e) => { yield error_event(&e.to_string()); return; } |
| 442 | } |
| 443 | } |
| 444 | let _ = utopia_store::conversations::append_message( |
| 445 | &state.pool, conversation_id, "assistant", &answer_acc, |
| 446 | &serde_json::Value::Array(steps_acc.clone()), |
| 447 | &serde_json::Value::Array(sources.clone()), |
| 448 | &serde_json::Value::Array(resolved_acc.clone()), |
| 449 | ).await; |
| 450 | yield done_event(); |
| 451 | } |
| 452 | Err(e) => yield error_event(&e.to_string()), |
| 453 | } |
| 454 | return; |
| 455 | } |
| 456 | |
| 457 | // 主链路全程流式:正文增量即时转发,工具调用在流末归并到达 |
| 458 | let deltas = match client.chat_tools_stream(&msgs, &tools).await { |
| 459 | Ok(s) => s, |
| 460 | Err(e) => { |
| 461 | if rounds == 0 { |
| 462 | // 模型可能不支持 tool-calling:降级为一次性 RAG 注入 |
| 463 | tracing::warn!(error = %e, "tool-calling 不可用,降级为一次性 RAG"); |
| 464 | let chunks = |
| 465 | retrieval::hybrid(&state, kb_id, workspace_id, &query, 8) |
| 466 | .await |
| 467 | .unwrap_or_default(); |
| 468 | let legacy_sources: Vec<serde_json::Value> = chunks |
| 469 | .iter() |
| 470 | .enumerate() |
| 471 | .map(|(i, c)| source_json(i + 1, c)) |
| 472 | .collect(); |
| 473 | yield Ok(Event::default().event("sources").data( |
| 474 | serde_json::to_string(&legacy_sources) |
| 475 | .unwrap_or_else(|_| "[]".into()), |
| 476 | )); |
| 477 | let mut lmsgs = |
| 478 | vec![json!({ "role": "system", "content": legacy_system_prompt(&chunks) })]; |
| 479 | for (role, content) in &history { |
| 480 | lmsgs.push(json!({ "role": role, "content": content })); |
| 481 | } |
| 482 | match client.chat_stream_raw(&lmsgs).await { |
| 483 | Ok(deltas) => { |
| 484 | let mut deltas = std::pin::pin!(deltas); |
| 485 | while let Some(item) = deltas.next().await { |
| 486 | match item { |
| 487 | Ok(text) => { answer_acc.push_str(&text); yield delta_event(&text); } |
| 488 | Err(e2) => { yield error_event(&e2.to_string()); return; } |
| 489 | } |
| 490 | } |
| 491 | let _ = utopia_store::conversations::append_message( |
| 492 | &state.pool, conversation_id, "assistant", &answer_acc, |
| 493 | &serde_json::Value::Array(steps_acc.clone()), |
| 494 | &serde_json::Value::Array(legacy_sources.clone()), |
| 495 | &serde_json::Value::Array(resolved_acc.clone()), |
| 496 | ).await; |
| 497 | yield done_event(); |
| 498 | } |
| 499 | Err(e2) => yield error_event(&e2.to_string()), |
| 500 | } |
| 501 | return; |
| 502 | } |
| 503 | yield error_event(&e.to_string()); |
| 504 | return; |
| 505 | } |
| 506 | }; |
| 507 | let mut turn: Option<utopia_llm::AssistantTurn> = None; |
| 508 | { |
| 509 | let mut deltas = std::pin::pin!(deltas); |
| 510 | while let Some(item) = deltas.next().await { |
| 511 | match item { |
| 512 | Ok(utopia_llm::ToolStreamItem::Delta(text)) => { |
| 513 | answer_acc.push_str(&text); |
| 514 | yield delta_event(&text); |
| 515 | } |
| 516 | Ok(utopia_llm::ToolStreamItem::Turn(t)) => turn = Some(t), |
| 517 | Err(e) => { |
| 518 | yield error_event(&e.to_string()); |
| 519 | return; |
| 520 | } |
| 521 | } |
| 522 | } |
| 523 | } |
| 524 | let Some(turn) = turn else { |
| 525 | yield error_event("LLM stream ended unexpectedly"); |
| 526 | return; |
| 527 | }; |
| 528 | |
| 529 | if turn.tool_calls.is_empty() { |
| 530 | if answer_acc.is_empty() { |
| 531 | yield error_event("Model returned an empty answer"); |
| 532 | } else { |
| 533 | let _ = utopia_store::conversations::append_message( |
| 534 | &state.pool, conversation_id, "assistant", &answer_acc, |
| 535 | &serde_json::Value::Array(steps_acc.clone()), |
| 536 | &serde_json::Value::Array(sources.clone()), |
| 537 | &serde_json::Value::Array(resolved_acc.clone()), |
| 538 | ).await; |
| 539 | yield done_event(); |
| 540 | } |
| 541 | return; |
| 542 | } |
| 543 | |
| 544 | // 工具轮带了叙述文本:与后续轮次的正文之间补一个段落分隔 |
| 545 | if turn.content.is_some() && !answer_acc.is_empty() { |
| 546 | answer_acc.push_str("\n\n"); |
| 547 | yield delta_event("\n\n"); |
| 548 | } |
| 549 | |
| 550 | msgs.push(turn.to_message()); |
| 551 | for call in &turn.tool_calls { |
| 552 | let args: serde_json::Value = |
| 553 | serde_json::from_str(&call.arguments).unwrap_or_else(|_| json!({})); |
| 554 | let (result, step) = match call.name.as_str() { |
| 555 | "search_chunks" => { |
| 556 | let q = args["query"].as_str().unwrap_or(&query).to_string(); |
| 557 | let chunks = retrieval::hybrid(&state, kb_id, workspace_id, &q, SEARCH_TOP_K) |
| 558 | .await |
| 559 | .unwrap_or_default(); |
| 560 | let mut lines = Vec::new(); |
| 561 | for c in &chunks { |
| 562 | let key = c.id.to_string(); |
| 563 | let n = match source_ids.iter().position(|id| *id == key) { |
| 564 | Some(i) => i + 1, |
| 565 | None => { |
| 566 | source_ids.push(key); |
| 567 | sources.push(source_json(source_ids.len(), c)); |
| 568 | source_ids.len() |
| 569 | } |
| 570 | }; |
| 571 | lines.push(format!( |
| 572 | "[{n}] \"{}\" section {}:\n{}", |
| 573 | c.filename, |
| 574 | c.seq + 1, |
| 575 | truncate(&c.text, TOOL_CHUNK_CHARS) |
| 576 | )); |
| 577 | } |
| 578 | let text = if lines.is_empty() { |
| 579 | "No results.".to_string() |
| 580 | } else { |
| 581 | lines.join("\n\n") |
| 582 | }; |
| 583 | (text, json!({ "kind": "search", "label": q, "detail": format!("{} sources", chunks.len()) })) |
| 584 | } |
| 585 | "search_docs" => { |
| 586 | let q = args["query"].as_str().unwrap_or(&query).to_string(); |
| 587 | let hits = state.docs.search(&q, 4).unwrap_or_default(); |
| 588 | let mut lines = Vec::new(); |
| 589 | for h in &hits { |
| 590 | let key = format!("charter:{}#{}", h.slug, h.anchor); |
| 591 | let n = match source_ids.iter().position(|id| *id == key) { |
| 592 | Some(i) => i + 1, |
| 593 | None => { |
| 594 | source_ids.push(key); |
| 595 | sources.push(charter_source_json(source_ids.len(), h)); |
| 596 | source_ids.len() |
| 597 | } |
| 598 | }; |
| 599 | lines.push(format!( |
| 600 | "[{n}] Utopia Charter — {} › {}:\n{}", |
| 601 | h.title, |
| 602 | h.heading, |
| 603 | truncate(&h.body, 1600) |
| 604 | )); |
| 605 | } |
| 606 | let text = if lines.is_empty() { |
| 607 | "No matching manual sections.".to_string() |
| 608 | } else { |
| 609 | lines.join("\n\n") |
| 610 | }; |
| 611 | (text, json!({ "kind": "docs", "label": q, "detail": format!("{} sections", hits.len()) })) |
| 612 | } |
| 613 | "find_entities" => { |
| 614 | let name = args["name"].as_str().unwrap_or("").to_string(); |
| 615 | let (hits, _) = |
| 616 | utopia_store::graph::search_entities(&state.pool, kb_id, &name, 8, 0) |
| 617 | .await |
| 618 | .unwrap_or_default(); |
| 619 | let text = if hits.is_empty() { |
| 620 | "No matching entities.".to_string() |
| 621 | } else { |
| 622 | hits.iter() |
| 623 | .map(|n| { |
| 624 | let dis = n |
| 625 | .disambiguator |
| 626 | .as_deref() |
| 627 | .map(|d| format!(" ({d})")) |
| 628 | .unwrap_or_default(); |
| 629 | format!( |
| 630 | "{} | {}{} | {} | {} facts", |
| 631 | n.id, |
| 632 | n.name, |
| 633 | dis, |
| 634 | // 没判出类型的实体照样能被搜到、被引用(0009) |
| 635 | n.type_label.as_deref().unwrap_or("untyped"), |
| 636 | n.degree |
| 637 | ) |
| 638 | }) |
| 639 | .collect::<Vec<_>>() |
| 640 | .join("\n") |
| 641 | }; |
| 642 | for n in &hits { |
| 643 | resolved_acc.push(json!({ |
| 644 | "id": n.id.to_string(), "name": n.name, "type": n.type_label |
| 645 | })); |
| 646 | } |
| 647 | (text, json!({ "kind": "entity", "label": name, "detail": format!("{} matches", hits.len()) })) |
| 648 | } |
| 649 | "entity_facts" => { |
| 650 | let id = args["entity_id"].as_str().and_then(|s| s.parse::<Uuid>().ok()); |
| 651 | // as-of 过滤:T 时刻有效 = 起点不晚于 T(或未知)且终点晚于 T(或开放) |
| 652 | let at = args["at"] |
| 653 | .as_str() |
| 654 | .and_then(|s| chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok()) |
| 655 | .map(|d| d.and_hms_opt(0, 0, 0).unwrap().and_utc()); |
| 656 | match id { |
| 657 | Some(id) => match utopia_store::graph::entity_detail(&state.pool, kb_id, id).await { |
| 658 | Ok((node, mut facts)) => { |
| 659 | if let Some(t) = at { |
| 660 | facts.retain(|f| { |
| 661 | f.valid_from.is_none_or(|from| from <= t) |
| 662 | && f.valid_to.is_none_or(|to| to > t) |
| 663 | }); |
| 664 | } |
| 665 | let text = if facts.is_empty() { |
| 666 | match at { |
| 667 | Some(t) => format!( |
| 668 | "{}: no facts valid as of {}.", |
| 669 | node.name, |
| 670 | t.format("%Y-%m-%d") |
| 671 | ), |
| 672 | None => format!("{}: no recorded facts.", node.name), |
| 673 | } |
| 674 | } else { |
| 675 | facts.iter().map(fact_line).collect::<Vec<_>>().join("\n") |
| 676 | }; |
| 677 | let detail = match at { |
| 678 | Some(t) => format!( |
| 679 | "{} facts as of {}", |
| 680 | facts.len(), |
| 681 | t.format("%Y-%m-%d") |
| 682 | ), |
| 683 | None => format!("{} facts", facts.len()), |
| 684 | }; |
| 685 | (text, json!({ "kind": "facts", "label": node.name, "detail": detail })) |
| 686 | } |
| 687 | Err(_) => ( |
| 688 | "Entity not found.".to_string(), |
| 689 | json!({ "kind": "facts", "label": "?", "detail": "not found" }), |
| 690 | ), |
| 691 | }, |
| 692 | None => ( |
| 693 | "Invalid entity_id (expected the uuid returned by find_entities)." |
| 694 | .to_string(), |
| 695 | json!({ "kind": "facts", "label": "?", "detail": "invalid id" }), |
| 696 | ), |
| 697 | } |
| 698 | } |
| 699 | "changes" => { |
| 700 | let day = |k: &str| { |
| 701 | args[k] |
| 702 | .as_str() |
| 703 | .and_then(|s| chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok()) |
| 704 | }; |
| 705 | match changes_window(day("since"), day("until"), chrono::Utc::now()) { |
| 706 | None => ( |
| 707 | "Invalid or missing `since` (expected YYYY-MM-DD).".to_string(), |
| 708 | json!({ "kind": "changes", "label": "?", "detail": "invalid since" }), |
| 709 | ), |
| 710 | Some((since, until, window)) => { |
| 711 | let entity = args["entity_id"] |
| 712 | .as_str() |
| 713 | .and_then(|s| s.parse::<Uuid>().ok()); |
| 714 | let kinds: Option<Vec<String>> = args["kinds"].as_array().map(|a| { |
| 715 | a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect() |
| 716 | }); |
| 717 | let kinds = kinds.filter(|k: &Vec<String>| !k.is_empty()); |
| 718 | let rows = utopia_store::graph::graph_changes( |
| 719 | &state.pool, |
| 720 | kb_id, |
| 721 | since, |
| 722 | until, |
| 723 | entity, |
| 724 | kinds.as_deref(), |
| 725 | CHANGES_LIMIT, |
| 726 | ) |
| 727 | .await |
| 728 | .unwrap_or_default(); |
| 729 | let text = if rows.is_empty() { |
| 730 | format!("No recorded changes in {window}.") |
| 731 | } else { |
| 732 | rows.iter().map(change_line).collect::<Vec<_>>().join("\n") |
| 733 | }; |
| 734 | let detail = if rows.len() as i64 == CHANGES_LIMIT { |
| 735 | format!("{CHANGES_LIMIT}+ changes") |
| 736 | } else { |
| 737 | format!("{} changes", rows.len()) |
| 738 | }; |
| 739 | (text, json!({ "kind": "changes", "label": window, "detail": detail })) |
| 740 | } |
| 741 | } |
| 742 | } |
| 743 | "query_data" if !mounted_sources.is_empty() => { |
| 744 | let ds_name = args["data_source"].as_str().map(str::trim).unwrap_or(""); |
| 745 | let sql = args["sql"].as_str().map(str::trim).unwrap_or(""); |
| 746 | let purpose = args["purpose"].as_str().map(str::trim).unwrap_or(""); |
| 747 | // 安全边界:只允许本 KB 挂载的源(凭据不出服务端) |
| 748 | let found = mounted_sources |
| 749 | .iter() |
| 750 | .find(|d| d.name.eq_ignore_ascii_case(ds_name)); |
| 751 | let text = match found { |
| 752 | None => format!( |
| 753 | "Unknown data source '{ds_name}'. Mounted sources: {}", |
| 754 | mounted_sources |
| 755 | .iter() |
| 756 | .map(|d| d.name.as_str()) |
| 757 | .collect::<Vec<_>>() |
| 758 | .join(", ") |
| 759 | ), |
| 760 | Some(ds) => { |
| 761 | match run_query(&state, ds.id, sql).await { |
| 762 | Ok(out) => out, |
| 763 | // 错误透传:模型可据此修正 SQL 重试 |
| 764 | Err(e) => format!("Query failed: {e}"), |
| 765 | } |
| 766 | } |
| 767 | }; |
| 768 | let detail = if purpose.is_empty() { |
| 769 | sql.chars().take(60).collect::<String>() |
| 770 | } else { |
| 771 | purpose.to_string() |
| 772 | }; |
| 773 | (text, json!({ "kind": "query", "label": ds_name, "detail": detail })) |
| 774 | } |
| 775 | "remember" if can_write => { |
| 776 | let text = args["text"].as_str().map(str::trim).unwrap_or(""); |
| 777 | let occurred_at = args["occurred_at"] |
| 778 | .as_str() |
| 779 | .and_then(|s| chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok()) |
| 780 | .map(|d| d.and_hms_opt(12, 0, 0).unwrap().and_utc()) |
| 781 | .unwrap_or_else(chrono::Utc::now); |
| 782 | if text.is_empty() { |
| 783 | ( |
| 784 | "remember requires non-empty text.".to_string(), |
| 785 | json!({ "kind": "tool", "label": "remember", "detail": "empty" }), |
| 786 | ) |
| 787 | } else { |
| 788 | match utopia_store::memory::append_episode( |
| 789 | &state.pool, kb_id, text, occurred_at, |
| 790 | ) |
| 791 | .await |
| 792 | { |
| 793 | Ok((doc_id, _chunk)) => { |
| 794 | // 摄入(embedding/索引/增量抽取)异步走队列,不阻塞对话 |
| 795 | let _ = utopia_store::jobs::enqueue( |
| 796 | &state.pool, |
| 797 | "memory_ingest", |
| 798 | json!({ "document_id": doc_id }), |
| 799 | ) |
| 800 | .await; |
| 801 | state.emit_document(kb_id, doc_id); |
| 802 | ( |
| 803 | format!( |
| 804 | "Recorded (effective {}): {text}", |
| 805 | occurred_at.format("%Y-%m-%d") |
| 806 | ), |
| 807 | json!({ |
| 808 | "kind": "tool", "label": "remember", |
| 809 | "detail": text.chars().take(60).collect::<String>() |
| 810 | }), |
| 811 | ) |
| 812 | } |
| 813 | Err(e) => ( |
| 814 | format!("Failed to record: {e}"), |
| 815 | json!({ "kind": "tool", "label": "remember", "detail": "failed" }), |
| 816 | ), |
| 817 | } |
| 818 | } |
| 819 | } |
| 820 | other => ( |
| 821 | format!("Unknown tool: {other}"), |
| 822 | json!({ "kind": "tool", "label": other, "detail": "unknown" }), |
| 823 | ), |
| 824 | }; |
| 825 | steps_acc.push(step.clone()); |
| 826 | yield Ok(Event::default() |
| 827 | .event("step") |
| 828 | .data(serde_json::to_string(&step).unwrap_or_default())); |
| 829 | if step["kind"] == "search" || step["kind"] == "docs" { |
| 830 | yield Ok(Event::default() |
| 831 | .event("sources") |
| 832 | .data(serde_json::to_string(&sources).unwrap_or_else(|_| "[]".into()))); |
| 833 | } |
| 834 | msgs.push(tool_result_message(&call.id, &result)); |
| 835 | } |
| 836 | rounds += 1; |
| 837 | } |
| 838 | }; |
| 839 | |
| 840 | Ok(Sse::new(stream).keep_alive(KeepAlive::default())) |
| 841 | } |
| 842 | |
| 843 | fn delta_event(text: &str) -> Result<Event, Infallible> { |
| 844 | Ok(Event::default() |
| 845 | .event("delta") |
| 846 | .data(serde_json::to_string(&json!({ "text": text })).unwrap_or_default())) |
| 847 | } |
| 848 | |
| 849 | fn done_event() -> Result<Event, Infallible> { |
| 850 | Ok(Event::default().event("done").data("{}")) |
| 851 | } |
| 852 | |
| 853 | fn error_event(message: &str) -> Result<Event, Infallible> { |
| 854 | Ok(Event::default().event("error").data(message)) |
| 855 | } |
| 856 | |
| 857 | fn source_json(n: usize, c: &ChunkView) -> serde_json::Value { |
| 858 | json!({ |
| 859 | "n": n, |
| 860 | "chunk_id": c.id, |
| 861 | "document_id": c.document_id, |
| 862 | "filename": c.filename, |
| 863 | "excerpt": truncate(&c.text, 160), |
| 864 | }) |
| 865 | } |
| 866 | |
| 867 | /// Charter 引用:前端渲染成手册行,链到 /docs/{slug}#{anchor}。 |
| 868 | fn charter_source_json(n: usize, h: &utopia_search::DocsSection) -> serde_json::Value { |
| 869 | json!({ |
| 870 | "n": n, |
| 871 | "kind": "charter", |
| 872 | "slug": h.slug, |
| 873 | "anchor": h.anchor, |
| 874 | "heading": h.heading, |
| 875 | "filename": h.title, |
| 876 | "excerpt": truncate(&h.body, 160), |
| 877 | }) |
| 878 | } |
| 879 | |
| 880 | /// 事实行:"works at → 星云科技 (2023-08 → now) [90%]",in 方向用 ←。 |
| 881 | /// 问数执行:安全闸(解析白名单)→ 引擎执行(只读会话 + 强制 LIMIT + 超时)→ JSON 行。 |
| 882 | async fn run_query(state: &AppState, ds_id: Uuid, sql: &str) -> anyhow::Result<String> { |
| 883 | let guarded = crate::query_engine::guard_sql(sql)?; |
| 884 | let (engine, conn) = utopia_store::datasources::engine_and_conn(&state.pool, ds_id).await?; |
| 885 | let result = crate::query_engine::engine_for(&engine, &conn)? |
| 886 | .execute(&guarded) |
| 887 | .await?; |
| 888 | let mut out = String::new(); |
| 889 | if result.rows.is_empty() { |
| 890 | out.push_str("(no rows)"); |
| 891 | } else { |
| 892 | out.push_str(&result.rows.join("\n")); |
| 893 | out.push_str(&format!("\n({} rows", result.rows.len())); |
| 894 | if result.truncated { |
| 895 | out.push_str(&format!( |
| 896 | ", truncated at {} — aggregate in SQL for totals", |
| 897 | crate::query_engine::ROW_CAP |
| 898 | )); |
| 899 | } |
| 900 | out.push(')'); |
| 901 | } |
| 902 | Ok(out) |
| 903 | } |
| 904 | |
| 905 | fn fact_line(f: &EntityFact) -> String { |
| 906 | let other = f.other_name.as_deref().unwrap_or("?"); |
| 907 | // 本体没认下、原文说法也没留下时用 "?"——与 other 同一个约定。 |
| 908 | // 不编一个"相关"出来:那正是删掉 related_to 要消灭的东西 |
| 909 | let pred = f.predicate_label.as_deref().unwrap_or("?"); |
| 910 | let core = if f.direction == "out" { |
| 911 | format!("{pred} → {other}") |
| 912 | } else { |
| 913 | format!("{pred} ← {other}") |
| 914 | }; |
| 915 | let range = match (&f.valid_from, &f.valid_to) { |
| 916 | (Some(from), Some(to)) => { |
| 917 | format!(" ({} → {})", from.format("%Y-%m-%d"), to.format("%Y-%m-%d")) |
| 918 | } |
| 919 | (Some(from), None) => format!(" ({} → now)", from.format("%Y-%m-%d")), |
| 920 | (None, Some(to)) => format!(" (→ {})", to.format("%Y-%m-%d")), |
| 921 | (None, None) => String::new(), |
| 922 | }; |
| 923 | format!("{core}{range} [{}%]", (f.confidence * 100.0).round() as i32) |
| 924 | } |
| 925 | |
| 926 | /// changes 的时间窗:把两个可选日期变成 (SQL 用的半开区间, 展示用的窗口串)。 |
| 927 | /// |
| 928 | /// **抽成纯函数是因为这里出过一次错。** `until` 进 SQL 前要加一天(说"到 3 月 31 日 |
| 929 | /// 为止"的人要的是含 31 日,而 SQL 那头是 `< $3`),第一版把加过一天的值也印进了 |
| 930 | /// 展示串,模型于是照着答"截至 8 月 30 日"——问的是 29 日。两个值必须一起算、 |
| 931 | /// 一起被测住;分在两处写,迟早再次分叉。 |
| 932 | /// |
| 933 | /// `now` 从外面传进来而不是在里面取,纯粹是为了这个函数测得动。 |
| 934 | fn changes_window( |
| 935 | since: Option<chrono::NaiveDate>, |
| 936 | until: Option<chrono::NaiveDate>, |
| 937 | now: chrono::DateTime<chrono::Utc>, |
| 938 | ) -> Option<( |
| 939 | chrono::DateTime<chrono::Utc>, |
| 940 | chrono::DateTime<chrono::Utc>, |
| 941 | String, |
| 942 | )> { |
| 943 | let from = since?; |
| 944 | let start = from.and_hms_opt(0, 0, 0).unwrap().and_utc(); |
| 945 | let end = until |
| 946 | .and_then(|d| d.succ_opt()) |
| 947 | .map(|d| d.and_hms_opt(0, 0, 0).unwrap().and_utc()) |
| 948 | .unwrap_or(now); |
| 949 | // 展示用的是**问的那天**,没问就写 now——绝不是 end |
| 950 | let label = format!( |
| 951 | "{} → {}", |
| 952 | from.format("%Y-%m-%d"), |
| 953 | match until { |
| 954 | Some(d) => d.format("%Y-%m-%d").to_string(), |
| 955 | None => "now".to_string(), |
| 956 | } |
| 957 | ); |
| 958 | Some((start, end, label)) |
| 959 | } |
| 960 | |
| 961 | /// 认知轴上的一行。 |
| 962 | /// |
| 963 | /// 排版把两根轴**分开写**:`at` 前面标事件类型,世界轴的区间夹在括号里跟在断言后。 |
| 964 | /// 若把它们排成一串日期,模型会把"2026 年记下的"读成"2026 年发生的"——那正是 |
| 965 | /// 这个工具要防的误读。 |
| 966 | fn change_line(c: &GraphChange) -> String { |
| 967 | let object = match (&c.object_name, &c.object_value) { |
| 968 | (Some(name), _) => name.clone(), |
| 969 | (None, Some(v)) => match v { |
| 970 | serde_json::Value::String(s) => s.clone(), |
| 971 | other => other.to_string(), |
| 972 | }, |
| 973 | (None, None) => "?".to_string(), |
| 974 | }; |
| 975 | let range = match (&c.valid_from, &c.valid_to) { |
| 976 | (Some(from), Some(to)) => { |
| 977 | format!( |
| 978 | " [valid {} → {}]", |
| 979 | from.format("%Y-%m-%d"), |
| 980 | to.format("%Y-%m-%d") |
| 981 | ) |
| 982 | } |
| 983 | (Some(from), None) => format!(" [valid {} → now]", from.format("%Y-%m-%d")), |
| 984 | (None, Some(to)) => format!(" [valid → {}]", to.format("%Y-%m-%d")), |
| 985 | (None, None) => String::new(), |
| 986 | }; |
| 987 | // 文件名不带 [n]:引证编号是 chunk 的,这里只有 document,发一个编号出去 |
| 988 | // 会在界面上落成一条指不到东西的引证 |
| 989 | let src = match (&c.filename, &c.quote) { |
| 990 | (Some(f), Some(q)) => format!(" — from \"{f}\": \"{}\"", truncate(q, 160)), |
| 991 | (Some(f), None) => format!(" — from \"{f}\""), |
| 992 | _ => String::new(), |
| 993 | }; |
| 994 | format!( |
| 995 | "{} {}: {} {} {}{}{}", |
| 996 | c.at.format("%Y-%m-%d"), |
| 997 | c.kind, |
| 998 | c.subject_name, |
| 999 | c.predicate_label.as_deref().unwrap_or("?"), |
| 1000 | object, |
| 1001 | range, |
| 1002 | src |
| 1003 | ) |
| 1004 | } |
| 1005 | |
| 1006 | /// 降级路径的系统提示(tool-calling 不可用时的一次性注入)。 |
| 1007 | fn legacy_system_prompt(chunks: &[ChunkView]) -> String { |
| 1008 | if chunks.is_empty() { |
| 1009 | return "You are an enterprise knowledge base assistant. No relevant sources were \ |
| 1010 | retrieved for this question. Tell the user the knowledge base lacks material \ |
| 1011 | on this topic, answer cautiously from general knowledge, and clearly separate \ |
| 1012 | sourced statements from speculation. Always respond in the same language as \ |
| 1013 | the user's question." |
| 1014 | .to_string(); |
| 1015 | } |
| 1016 | let mut prompt = String::from( |
| 1017 | "You are an enterprise knowledge base assistant. Answer strictly based on the \ |
| 1018 | numbered sources below. When a source supports a statement, append its citation \ |
| 1019 | number, e.g. [1] or [2], at the end of the sentence. If the sources are \ |
| 1020 | insufficient, say so explicitly — never fabricate. Always respond in the same \ |
| 1021 | language as the user's question.\n\n### Sources\n", |
| 1022 | ); |
| 1023 | for (i, c) in chunks.iter().enumerate() { |
| 1024 | prompt.push_str(&format!( |
| 1025 | "\n[{}] \"{}\" section {}:\n{}\n", |
| 1026 | i + 1, |
| 1027 | c.filename, |
| 1028 | c.seq + 1, |
| 1029 | c.text |
| 1030 | )); |
| 1031 | } |
| 1032 | prompt |
| 1033 | } |
| 1034 | |
| 1035 | fn truncate(text: &str, max_chars: usize) -> String { |
| 1036 | let t = text.trim(); |
| 1037 | if t.chars().count() <= max_chars { |
| 1038 | t.to_string() |
| 1039 | } else { |
| 1040 | let cut: String = t.chars().take(max_chars).collect(); |
| 1041 | format!("{cut}…") |
| 1042 | } |
| 1043 | } |
| 1044 | |
| 1045 | // --------------------------------------------------------------------------- |
| 1046 | // 会话管理(列表 / 回放 / 删除) |
| 1047 | // --------------------------------------------------------------------------- |
| 1048 | |
| 1049 | #[derive(serde::Deserialize)] |
| 1050 | pub struct ConversationsQuery { |
| 1051 | /// 搜标题与消息正文两处:人记得住的往往是问过的那句话,不是标题 |
| 1052 | #[serde(default)] |
| 1053 | pub q: Option<String>, |
| 1054 | #[serde(default)] |
| 1055 | pub limit: Option<i64>, |
| 1056 | #[serde(default)] |
| 1057 | pub offset: Option<i64>, |
| 1058 | } |
| 1059 | |
| 1060 | pub async fn list_conversations( |
| 1061 | State(state): State<AppState>, |
| 1062 | AuthUser(user): AuthUser, |
| 1063 | Path(kb_id): Path<Uuid>, |
| 1064 | Query(q): Query<ConversationsQuery>, |
| 1065 | ) -> ApiResult<Json<serde_json::Value>> { |
| 1066 | utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?; |
| 1067 | let (conversations, total) = utopia_store::conversations::list( |
| 1068 | &state.pool, |
| 1069 | kb_id, |
| 1070 | user.id, |
| 1071 | q.q.as_deref().map(str::trim).filter(|s| !s.is_empty()), |
| 1072 | q.limit.unwrap_or(30).clamp(1, 100), |
| 1073 | q.offset.unwrap_or(0).max(0), |
| 1074 | ) |
| 1075 | .await?; |
| 1076 | Ok(Json( |
| 1077 | json!({ "conversations": conversations, "total": total }), |
| 1078 | )) |
| 1079 | } |
| 1080 | |
| 1081 | #[derive(serde::Deserialize)] |
| 1082 | pub struct RenameConversationReq { |
| 1083 | pub title: String, |
| 1084 | } |
| 1085 | |
| 1086 | /// 改会话标题。 |
| 1087 | /// |
| 1088 | /// **标题本来是从第一句话自动取的**,而一段对话跑偏是常态——改名让人能按 |
| 1089 | /// 自己记得的方式找回它。 |
| 1090 | pub async fn rename_conversation( |
| 1091 | State(state): State<AppState>, |
| 1092 | AuthUser(user): AuthUser, |
| 1093 | Path((kb_id, conversation_id)): Path<(Uuid, Uuid)>, |
| 1094 | Json(req): Json<RenameConversationReq>, |
| 1095 | ) -> ApiResult<Json<serde_json::Value>> { |
| 1096 | utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?; |
| 1097 | utopia_store::conversations::rename(&state.pool, kb_id, user.id, conversation_id, &req.title) |
| 1098 | .await?; |
| 1099 | Ok(Json(json!({ "ok": true }))) |
| 1100 | } |
| 1101 | |
| 1102 | /// 历史回放:消息含落库的行动轨迹(steps)与引用(sources)。 |
| 1103 | pub async fn conversation_detail( |
| 1104 | State(state): State<AppState>, |
| 1105 | AuthUser(user): AuthUser, |
| 1106 | Path((kb_id, conversation_id)): Path<(Uuid, Uuid)>, |
| 1107 | ) -> ApiResult<Json<serde_json::Value>> { |
| 1108 | utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?; |
| 1109 | utopia_store::conversations::require_owned(&state.pool, kb_id, user.id, conversation_id) |
| 1110 | .await?; |
| 1111 | let messages = utopia_store::conversations::messages(&state.pool, conversation_id).await?; |
| 1112 | Ok(Json(json!({ "messages": messages }))) |
| 1113 | } |
| 1114 | |
| 1115 | pub async fn delete_conversation( |
| 1116 | State(state): State<AppState>, |
| 1117 | AuthUser(user): AuthUser, |
| 1118 | Path((kb_id, conversation_id)): Path<(Uuid, Uuid)>, |
| 1119 | ) -> ApiResult<Json<serde_json::Value>> { |
| 1120 | utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?; |
| 1121 | utopia_store::conversations::delete(&state.pool, kb_id, user.id, conversation_id).await?; |
| 1122 | Ok(Json(json!({ "ok": true }))) |
| 1123 | } |
| 1124 | |
| 1125 | #[cfg(test)] |
| 1126 | mod tests { |
| 1127 | use super::*; |
| 1128 | |
| 1129 | fn d(s: &str) -> chrono::NaiveDate { |
| 1130 | chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d").unwrap() |
| 1131 | } |
| 1132 | fn t(s: &str) -> chrono::DateTime<chrono::Utc> { |
| 1133 | s.parse().unwrap() |
| 1134 | } |
| 1135 | |
| 1136 | // --- changes_window ----------------------------------------------------- |
| 1137 | |
| 1138 | /// 说"到 3 月 31 日为止"的人要的是**含 31 日**。SQL 那头是 `< end`, |
| 1139 | /// 所以 end 必须落在 4 月 1 日零点——差这一天,问 31 日会安静地丢掉 31 日 |
| 1140 | #[test] |
| 1141 | fn until_names_a_day_the_window_must_contain() { |
| 1142 | let (start, end, label) = changes_window( |
| 1143 | Some(d("2026-03-01")), |
| 1144 | Some(d("2026-03-31")), |
| 1145 | t("2026-06-01T00:00:00Z"), |
| 1146 | ) |
| 1147 | .unwrap(); |
| 1148 | assert_eq!(start, t("2026-03-01T00:00:00Z")); |
| 1149 | assert_eq!(end, t("2026-04-01T00:00:00Z")); |
| 1150 | // 但**展示串里绝不能出现 04-01**:那是半开区间的内部细节, |
| 1151 | // 印出去等于告诉模型窗口比它要的宽一天,模型会照着答(这条真的发生过) |
| 1152 | assert_eq!(label, "2026-03-01 → 2026-03-31"); |
| 1153 | } |
| 1154 | |
| 1155 | /// 没给 until 时,展示串写 now。写成 end 的格式化结果就等于把服务器时钟 |
| 1156 | /// 当成用户问的边界——看着像个精确答案,其实只是"现在几点" |
| 1157 | #[test] |
| 1158 | fn an_open_window_says_now_rather_than_the_clock() { |
| 1159 | let now = t("2026-06-01T13:45:00Z"); |
| 1160 | let (_, end, label) = changes_window(Some(d("2026-03-01")), None, now).unwrap(); |
| 1161 | assert_eq!(end, now); |
| 1162 | assert_eq!(label, "2026-03-01 → now"); |
| 1163 | } |
| 1164 | |
| 1165 | #[test] |
| 1166 | fn without_since_there_is_no_window() { |
| 1167 | assert!(changes_window(None, Some(d("2026-03-31")), t("2026-06-01T00:00:00Z")).is_none()); |
| 1168 | } |
| 1169 | |
| 1170 | // --- change_line -------------------------------------------------------- |
| 1171 | |
| 1172 | fn change(kind: &str) -> GraphChange { |
| 1173 | GraphChange { |
| 1174 | fact_id: Uuid::nil(), |
| 1175 | at: t("2026-08-28T10:00:00Z"), |
| 1176 | kind: kind.to_string(), |
| 1177 | subject_id: Uuid::nil(), |
| 1178 | subject_name: "Acme".to_string(), |
| 1179 | predicate_label: Some("founded in".to_string()), |
| 1180 | object_name: None, |
| 1181 | object_value: None, |
| 1182 | valid_from: None, |
| 1183 | valid_to: None, |
| 1184 | // 两端都没日期就没有精度——夹具也得守这条不变量(见 `facts.valid_from_precision`) |
| 1185 | // 两端都没日期,所以两端都没有精度(见 facts 的两个精度列) |
| 1186 | valid_from_precision: None, |
| 1187 | valid_to_precision: None, |
| 1188 | confidence: 0.9, |
| 1189 | document_id: None, |
| 1190 | filename: None, |
| 1191 | quote: None, |
| 1192 | } |
| 1193 | } |
| 1194 | |
| 1195 | /// 字面值要读成它自己。走 `Value::to_string()` 会把字符串连引号一起印出来, |
| 1196 | /// 模型于是把 `"1993"` 当成答案的一部分 |
| 1197 | #[test] |
| 1198 | fn a_literal_value_reads_as_itself_not_as_json() { |
| 1199 | let mut c = change("asserted"); |
| 1200 | c.object_value = Some(serde_json::json!("1993")); |
| 1201 | assert!( |
| 1202 | change_line(&c).ends_with("Acme founded in 1993"), |
| 1203 | "{}", |
| 1204 | change_line(&c) |
| 1205 | ); |
| 1206 | } |
| 1207 | |
| 1208 | /// 两根轴必须在同一行里**看得出是两样东西**:记录时刻在前、无标签, |
| 1209 | /// 世界轴区间在后、带 `valid` 字样。排成一串裸日期,模型会把 |
| 1210 | /// "2026 年记下的"读成"2026 年发生的"——这个工具存在的理由就是防这个 |
| 1211 | #[test] |
| 1212 | fn the_record_time_and_the_valid_range_do_not_read_as_one_date_run() { |
| 1213 | let mut c = change("corrected"); |
| 1214 | c.object_name = Some("Berlin".to_string()); |
| 1215 | c.predicate_label = Some("headquartered in".to_string()); |
| 1216 | c.valid_from = Some(t("2019-01-01T00:00:00Z")); |
| 1217 | let line = change_line(&c); |
| 1218 | assert!(line.starts_with("2026-08-28 corrected: "), "{line}"); |
| 1219 | assert!(line.contains("[valid 2019-01-01 → now]"), "{line}"); |
| 1220 | } |
| 1221 | |
| 1222 | /// 没有证据就什么都别说。凭空补一句 from "…" 会让一条无出处的断言 |
| 1223 | /// 看起来有出处 |
| 1224 | #[test] |
| 1225 | fn a_fact_with_no_evidence_claims_no_document() { |
| 1226 | let mut c = change("rejected"); |
| 1227 | c.object_name = Some("Berlin".to_string()); |
| 1228 | assert!(!change_line(&c).contains("from"), "{}", change_line(&c)); |
| 1229 | } |
| 1230 | |
| 1231 | #[test] |
| 1232 | fn evidence_carries_the_filename_and_the_quote() { |
| 1233 | let mut c = change("corrected"); |
| 1234 | c.object_name = Some("Berlin".to_string()); |
| 1235 | c.filename = Some("annual-report.pdf".to_string()); |
| 1236 | c.quote = Some("moved its head office to Berlin".to_string()); |
| 1237 | let line = change_line(&c); |
| 1238 | assert!(line.contains("from \"annual-report.pdf\""), "{line}"); |
| 1239 | assert!( |
| 1240 | line.contains("\"moved its head office to Berlin\""), |
| 1241 | "{line}" |
| 1242 | ); |
| 1243 | } |
| 1244 | } |