Elffuss BraidHub

kikocis/utopia public

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