Elffuss BraidHub

kikocis/utopia public

608af2bf35c5 · 56.9 KiBRawPermalink
1//! Agentic 对话:模型自主调用工具(文档检索 / 实体查找 / 时态事实)收集证据后作答。
2//! 事件序列:step*(行动轨迹)| sources(引用清单,随检索增量更新)| delta*(增量文本)→ done | error。
3//! 模型不支持 tool-calling 时自动降级为一次性 RAG 注入。
4
5use axum::extract::{Path, State};
6use axum::response::sse::{Event, KeepAlive, Sse};
7use axum::Json;
8use futures_util::{Stream, StreamExt};
9use serde::Deserialize;
10use serde_json::json;
11use std::convert::Infallible;
12use utopia_core::models::{ChunkView, EntityFact, GraphChange, Role};
13use utopia_core::AppError;
14use utopia_llm::tool_result_message;
15use uuid::Uuid;
16
17use crate::auth::AuthUser;
18use crate::error::ApiResult;
19use crate::llm_util;
20use crate::retrieval;
21use crate::state::AppState;
22
23/// 回放几个已认下的实体。上限是因为长会话会攒出几十个,全贴回去就把
24/// 省下来的上下文又花掉了;按首次出现排序,早认下的通常是这场对话的主角。
25const KNOWN_ENTITY_LIMIT: usize = 20;
26
27const MAX_HISTORY: usize = 20;
28const MAX_ROUNDS: usize = 6;
29const SEARCH_TOP_K: usize = 6;
30const TOOL_CHUNK_CHARS: usize = 800;
31/// 一次 changes 最多回多少条。刚灌完的库里 asserted 是成百上千条,全发出去
32/// 只会把上下文填满而不增加信息——有信息量的是 corrected/rejected,那类事件
33/// 本来就稀少。截断时 detail 写 "40+",模型据此知道该收窄窗口
34const CHANGES_LIMIT: i64 = 40;
35
36#[derive(Deserialize)]
37pub struct ChatReq {
38 /// 缺省 = 新建会话(SSE 首个 `conversation` 事件回传 id)
39 #[serde(default)]
40 pub conversation_id: Option<Uuid>,
41 pub message: String,
42}
43
44fn 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
117const 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
122fn 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
233const 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
266pub 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 = utopia_store::graph::search_entities(&state.pool, kb_id, &name, 8)
616 .await
617 .unwrap_or_default();
618 let text = if hits.is_empty() {
619 "No matching entities.".to_string()
620 } else {
621 hits.iter()
622 .map(|n| {
623 let dis = n
624 .disambiguator
625 .as_deref()
626 .map(|d| format!(" ({d})"))
627 .unwrap_or_default();
628 format!(
629 "{} | {}{} | {} | {} facts",
630 n.id,
631 n.name,
632 dis,
633 // 没判出类型的实体照样能被搜到、被引用(0009)
634 n.type_label.as_deref().unwrap_or("untyped"),
635 n.degree
636 )
637 })
638 .collect::<Vec<_>>()
639 .join("\n")
640 };
641 for n in &hits {
642 resolved_acc.push(json!({
643 "id": n.id.to_string(), "name": n.name, "type": n.type_label
644 }));
645 }
646 (text, json!({ "kind": "entity", "label": name, "detail": format!("{} matches", hits.len()) }))
647 }
648 "entity_facts" => {
649 let id = args["entity_id"].as_str().and_then(|s| s.parse::<Uuid>().ok());
650 // as-of 过滤:T 时刻有效 = 起点不晚于 T(或未知)且终点晚于 T(或开放)
651 let at = args["at"]
652 .as_str()
653 .and_then(|s| chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok())
654 .map(|d| d.and_hms_opt(0, 0, 0).unwrap().and_utc());
655 match id {
656 Some(id) => match utopia_store::graph::entity_detail(&state.pool, kb_id, id).await {
657 Ok((node, mut facts)) => {
658 if let Some(t) = at {
659 facts.retain(|f| {
660 f.valid_from.is_none_or(|from| from <= t)
661 && f.valid_to.is_none_or(|to| to > t)
662 });
663 }
664 let text = if facts.is_empty() {
665 match at {
666 Some(t) => format!(
667 "{}: no facts valid as of {}.",
668 node.name,
669 t.format("%Y-%m-%d")
670 ),
671 None => format!("{}: no recorded facts.", node.name),
672 }
673 } else {
674 facts.iter().map(fact_line).collect::<Vec<_>>().join("\n")
675 };
676 let detail = match at {
677 Some(t) => format!(
678 "{} facts as of {}",
679 facts.len(),
680 t.format("%Y-%m-%d")
681 ),
682 None => format!("{} facts", facts.len()),
683 };
684 (text, json!({ "kind": "facts", "label": node.name, "detail": detail }))
685 }
686 Err(_) => (
687 "Entity not found.".to_string(),
688 json!({ "kind": "facts", "label": "?", "detail": "not found" }),
689 ),
690 },
691 None => (
692 "Invalid entity_id (expected the uuid returned by find_entities)."
693 .to_string(),
694 json!({ "kind": "facts", "label": "?", "detail": "invalid id" }),
695 ),
696 }
697 }
698 "changes" => {
699 let day = |k: &str| {
700 args[k]
701 .as_str()
702 .and_then(|s| chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok())
703 };
704 match changes_window(day("since"), day("until"), chrono::Utc::now()) {
705 None => (
706 "Invalid or missing `since` (expected YYYY-MM-DD).".to_string(),
707 json!({ "kind": "changes", "label": "?", "detail": "invalid since" }),
708 ),
709 Some((since, until, window)) => {
710 let entity = args["entity_id"]
711 .as_str()
712 .and_then(|s| s.parse::<Uuid>().ok());
713 let kinds: Option<Vec<String>> = args["kinds"].as_array().map(|a| {
714 a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()
715 });
716 let kinds = kinds.filter(|k: &Vec<String>| !k.is_empty());
717 let rows = utopia_store::graph::graph_changes(
718 &state.pool,
719 kb_id,
720 since,
721 until,
722 entity,
723 kinds.as_deref(),
724 CHANGES_LIMIT,
725 )
726 .await
727 .unwrap_or_default();
728 let text = if rows.is_empty() {
729 format!("No recorded changes in {window}.")
730 } else {
731 rows.iter().map(change_line).collect::<Vec<_>>().join("\n")
732 };
733 let detail = if rows.len() as i64 == CHANGES_LIMIT {
734 format!("{CHANGES_LIMIT}+ changes")
735 } else {
736 format!("{} changes", rows.len())
737 };
738 (text, json!({ "kind": "changes", "label": window, "detail": detail }))
739 }
740 }
741 }
742 "query_data" if !mounted_sources.is_empty() => {
743 let ds_name = args["data_source"].as_str().map(str::trim).unwrap_or("");
744 let sql = args["sql"].as_str().map(str::trim).unwrap_or("");
745 let purpose = args["purpose"].as_str().map(str::trim).unwrap_or("");
746 // 安全边界:只允许本 KB 挂载的源(凭据不出服务端)
747 let found = mounted_sources
748 .iter()
749 .find(|d| d.name.eq_ignore_ascii_case(ds_name));
750 let text = match found {
751 None => format!(
752 "Unknown data source '{ds_name}'. Mounted sources: {}",
753 mounted_sources
754 .iter()
755 .map(|d| d.name.as_str())
756 .collect::<Vec<_>>()
757 .join(", ")
758 ),
759 Some(ds) => {
760 match run_query(&state, ds.id, sql).await {
761 Ok(out) => out,
762 // 错误透传:模型可据此修正 SQL 重试
763 Err(e) => format!("Query failed: {e}"),
764 }
765 }
766 };
767 let detail = if purpose.is_empty() {
768 sql.chars().take(60).collect::<String>()
769 } else {
770 purpose.to_string()
771 };
772 (text, json!({ "kind": "query", "label": ds_name, "detail": detail }))
773 }
774 "remember" if can_write => {
775 let text = args["text"].as_str().map(str::trim).unwrap_or("");
776 let occurred_at = args["occurred_at"]
777 .as_str()
778 .and_then(|s| chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok())
779 .map(|d| d.and_hms_opt(12, 0, 0).unwrap().and_utc())
780 .unwrap_or_else(chrono::Utc::now);
781 if text.is_empty() {
782 (
783 "remember requires non-empty text.".to_string(),
784 json!({ "kind": "tool", "label": "remember", "detail": "empty" }),
785 )
786 } else {
787 match utopia_store::memory::append_episode(
788 &state.pool, kb_id, text, occurred_at,
789 )
790 .await
791 {
792 Ok((doc_id, _chunk)) => {
793 // 摄入(embedding/索引/增量抽取)异步走队列,不阻塞对话
794 let _ = utopia_store::jobs::enqueue(
795 &state.pool,
796 "memory_ingest",
797 json!({ "document_id": doc_id }),
798 )
799 .await;
800 state.emit_document(kb_id, doc_id);
801 (
802 format!(
803 "Recorded (effective {}): {text}",
804 occurred_at.format("%Y-%m-%d")
805 ),
806 json!({
807 "kind": "tool", "label": "remember",
808 "detail": text.chars().take(60).collect::<String>()
809 }),
810 )
811 }
812 Err(e) => (
813 format!("Failed to record: {e}"),
814 json!({ "kind": "tool", "label": "remember", "detail": "failed" }),
815 ),
816 }
817 }
818 }
819 other => (
820 format!("Unknown tool: {other}"),
821 json!({ "kind": "tool", "label": other, "detail": "unknown" }),
822 ),
823 };
824 steps_acc.push(step.clone());
825 yield Ok(Event::default()
826 .event("step")
827 .data(serde_json::to_string(&step).unwrap_or_default()));
828 if step["kind"] == "search" || step["kind"] == "docs" {
829 yield Ok(Event::default()
830 .event("sources")
831 .data(serde_json::to_string(&sources).unwrap_or_else(|_| "[]".into())));
832 }
833 msgs.push(tool_result_message(&call.id, &result));
834 }
835 rounds += 1;
836 }
837 };
838
839 Ok(Sse::new(stream).keep_alive(KeepAlive::default()))
840}
841
842fn delta_event(text: &str) -> Result<Event, Infallible> {
843 Ok(Event::default()
844 .event("delta")
845 .data(serde_json::to_string(&json!({ "text": text })).unwrap_or_default()))
846}
847
848fn done_event() -> Result<Event, Infallible> {
849 Ok(Event::default().event("done").data("{}"))
850}
851
852fn error_event(message: &str) -> Result<Event, Infallible> {
853 Ok(Event::default().event("error").data(message))
854}
855
856fn source_json(n: usize, c: &ChunkView) -> serde_json::Value {
857 json!({
858 "n": n,
859 "chunk_id": c.id,
860 "document_id": c.document_id,
861 "filename": c.filename,
862 "excerpt": truncate(&c.text, 160),
863 })
864}
865
866/// Charter 引用:前端渲染成手册行,链到 /docs/{slug}#{anchor}。
867fn charter_source_json(n: usize, h: &utopia_search::DocsSection) -> serde_json::Value {
868 json!({
869 "n": n,
870 "kind": "charter",
871 "slug": h.slug,
872 "anchor": h.anchor,
873 "heading": h.heading,
874 "filename": h.title,
875 "excerpt": truncate(&h.body, 160),
876 })
877}
878
879/// 事实行:"works at → 星云科技 (2023-08 → now) [90%]",in 方向用 ←。
880/// 问数执行:安全闸(解析白名单)→ 引擎执行(只读会话 + 强制 LIMIT + 超时)→ JSON 行。
881async fn run_query(state: &AppState, ds_id: Uuid, sql: &str) -> anyhow::Result<String> {
882 let guarded = crate::query_engine::guard_sql(sql)?;
883 let (engine, conn) = utopia_store::datasources::engine_and_conn(&state.pool, ds_id).await?;
884 let result = crate::query_engine::engine_for(&engine, &conn)?
885 .execute(&guarded)
886 .await?;
887 let mut out = String::new();
888 if result.rows.is_empty() {
889 out.push_str("(no rows)");
890 } else {
891 out.push_str(&result.rows.join("\n"));
892 out.push_str(&format!("\n({} rows", result.rows.len()));
893 if result.truncated {
894 out.push_str(&format!(
895 ", truncated at {} — aggregate in SQL for totals",
896 crate::query_engine::ROW_CAP
897 ));
898 }
899 out.push(')');
900 }
901 Ok(out)
902}
903
904fn fact_line(f: &EntityFact) -> String {
905 let other = f.other_name.as_deref().unwrap_or("?");
906 // 本体没认下、原文说法也没留下时用 "?"——与 other 同一个约定。
907 // 不编一个"相关"出来:那正是 0052 删掉 related_to 要消灭的东西
908 let pred = f.predicate_label.as_deref().unwrap_or("?");
909 let core = if f.direction == "out" {
910 format!("{pred} → {other}")
911 } else {
912 format!("{pred} ← {other}")
913 };
914 let range = match (&f.valid_from, &f.valid_to) {
915 (Some(from), Some(to)) => {
916 format!(" ({} → {})", from.format("%Y-%m-%d"), to.format("%Y-%m-%d"))
917 }
918 (Some(from), None) => format!(" ({} → now)", from.format("%Y-%m-%d")),
919 (None, Some(to)) => format!(" (→ {})", to.format("%Y-%m-%d")),
920 (None, None) => String::new(),
921 };
922 format!("{core}{range} [{}%]", (f.confidence * 100.0).round() as i32)
923}
924
925/// changes 的时间窗:把两个可选日期变成 (SQL 用的半开区间, 展示用的窗口串)。
926///
927/// **抽成纯函数是因为这里出过一次错。** `until` 进 SQL 前要加一天(说"到 3 月 31 日
928/// 为止"的人要的是含 31 日,而 SQL 那头是 `< $3`),第一版把加过一天的值也印进了
929/// 展示串,模型于是照着答"截至 8 月 30 日"——问的是 29 日。两个值必须一起算、
930/// 一起被测住;分在两处写,迟早再次分叉。
931///
932/// `now` 从外面传进来而不是在里面取,纯粹是为了这个函数测得动。
933fn changes_window(
934 since: Option<chrono::NaiveDate>,
935 until: Option<chrono::NaiveDate>,
936 now: chrono::DateTime<chrono::Utc>,
937) -> Option<(
938 chrono::DateTime<chrono::Utc>,
939 chrono::DateTime<chrono::Utc>,
940 String,
941)> {
942 let from = since?;
943 let start = from.and_hms_opt(0, 0, 0).unwrap().and_utc();
944 let end = until
945 .and_then(|d| d.succ_opt())
946 .map(|d| d.and_hms_opt(0, 0, 0).unwrap().and_utc())
947 .unwrap_or(now);
948 // 展示用的是**问的那天**,没问就写 now——绝不是 end
949 let label = format!(
950 "{} → {}",
951 from.format("%Y-%m-%d"),
952 match until {
953 Some(d) => d.format("%Y-%m-%d").to_string(),
954 None => "now".to_string(),
955 }
956 );
957 Some((start, end, label))
958}
959
960/// 认知轴上的一行。
961///
962/// 排版把两根轴**分开写**:`at` 前面标事件类型,世界轴的区间夹在括号里跟在断言后。
963/// 若把它们排成一串日期,模型会把"2026 年记下的"读成"2026 年发生的"——那正是
964/// 这个工具要防的误读。
965fn change_line(c: &GraphChange) -> String {
966 let object = match (&c.object_name, &c.object_value) {
967 (Some(name), _) => name.clone(),
968 (None, Some(v)) => match v {
969 serde_json::Value::String(s) => s.clone(),
970 other => other.to_string(),
971 },
972 (None, None) => "?".to_string(),
973 };
974 let range = match (&c.valid_from, &c.valid_to) {
975 (Some(from), Some(to)) => {
976 format!(
977 " [valid {} → {}]",
978 from.format("%Y-%m-%d"),
979 to.format("%Y-%m-%d")
980 )
981 }
982 (Some(from), None) => format!(" [valid {} → now]", from.format("%Y-%m-%d")),
983 (None, Some(to)) => format!(" [valid → {}]", to.format("%Y-%m-%d")),
984 (None, None) => String::new(),
985 };
986 // 文件名不带 [n]:引证编号是 chunk 的,这里只有 document,发一个编号出去
987 // 会在界面上落成一条指不到东西的引证
988 let src = match (&c.filename, &c.quote) {
989 (Some(f), Some(q)) => format!(" — from \"{f}\": \"{}\"", truncate(q, 160)),
990 (Some(f), None) => format!(" — from \"{f}\""),
991 _ => String::new(),
992 };
993 format!(
994 "{} {}: {} {} {}{}{}",
995 c.at.format("%Y-%m-%d"),
996 c.kind,
997 c.subject_name,
998 c.predicate_label.as_deref().unwrap_or("?"),
999 object,
1000 range,
1001 src
1002 )
1003}
1004
1005/// 降级路径的系统提示(tool-calling 不可用时的一次性注入)。
1006fn legacy_system_prompt(chunks: &[ChunkView]) -> String {
1007 if chunks.is_empty() {
1008 return "You are an enterprise knowledge base assistant. No relevant sources were \
1009 retrieved for this question. Tell the user the knowledge base lacks material \
1010 on this topic, answer cautiously from general knowledge, and clearly separate \
1011 sourced statements from speculation. Always respond in the same language as \
1012 the user's question."
1013 .to_string();
1014 }
1015 let mut prompt = String::from(
1016 "You are an enterprise knowledge base assistant. Answer strictly based on the \
1017 numbered sources below. When a source supports a statement, append its citation \
1018 number, e.g. [1] or [2], at the end of the sentence. If the sources are \
1019 insufficient, say so explicitly — never fabricate. Always respond in the same \
1020 language as the user's question.\n\n### Sources\n",
1021 );
1022 for (i, c) in chunks.iter().enumerate() {
1023 prompt.push_str(&format!(
1024 "\n[{}] \"{}\" section {}:\n{}\n",
1025 i + 1,
1026 c.filename,
1027 c.seq + 1,
1028 c.text
1029 ));
1030 }
1031 prompt
1032}
1033
1034fn truncate(text: &str, max_chars: usize) -> String {
1035 let t = text.trim();
1036 if t.chars().count() <= max_chars {
1037 t.to_string()
1038 } else {
1039 let cut: String = t.chars().take(max_chars).collect();
1040 format!("{cut}…")
1041 }
1042}
1043
1044// ---------------------------------------------------------------------------
1045// 会话管理(列表 / 回放 / 删除)
1046// ---------------------------------------------------------------------------
1047
1048pub async fn list_conversations(
1049 State(state): State<AppState>,
1050 AuthUser(user): AuthUser,
1051 Path(kb_id): Path<Uuid>,
1052) -> ApiResult<Json<serde_json::Value>> {
1053 utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
1054 let conversations = utopia_store::conversations::list(&state.pool, kb_id, user.id).await?;
1055 Ok(Json(json!({ "conversations": conversations })))
1056}
1057
1058/// 历史回放:消息含落库的行动轨迹(steps)与引用(sources)。
1059pub async fn conversation_detail(
1060 State(state): State<AppState>,
1061 AuthUser(user): AuthUser,
1062 Path((kb_id, conversation_id)): Path<(Uuid, Uuid)>,
1063) -> ApiResult<Json<serde_json::Value>> {
1064 utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
1065 utopia_store::conversations::require_owned(&state.pool, kb_id, user.id, conversation_id)
1066 .await?;
1067 let messages = utopia_store::conversations::messages(&state.pool, conversation_id).await?;
1068 Ok(Json(json!({ "messages": messages })))
1069}
1070
1071pub async fn delete_conversation(
1072 State(state): State<AppState>,
1073 AuthUser(user): AuthUser,
1074 Path((kb_id, conversation_id)): Path<(Uuid, Uuid)>,
1075) -> ApiResult<Json<serde_json::Value>> {
1076 utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
1077 utopia_store::conversations::delete(&state.pool, kb_id, user.id, conversation_id).await?;
1078 Ok(Json(json!({ "ok": true })))
1079}
1080
1081#[cfg(test)]
1082mod tests {
1083 use super::*;
1084
1085 fn d(s: &str) -> chrono::NaiveDate {
1086 chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d").unwrap()
1087 }
1088 fn t(s: &str) -> chrono::DateTime<chrono::Utc> {
1089 s.parse().unwrap()
1090 }
1091
1092 // --- changes_window -----------------------------------------------------
1093
1094 /// 说"到 3 月 31 日为止"的人要的是**含 31 日**。SQL 那头是 `< end`,
1095 /// 所以 end 必须落在 4 月 1 日零点——差这一天,问 31 日会安静地丢掉 31 日
1096 #[test]
1097 fn until_names_a_day_the_window_must_contain() {
1098 let (start, end, label) = changes_window(
1099 Some(d("2026-03-01")),
1100 Some(d("2026-03-31")),
1101 t("2026-06-01T00:00:00Z"),
1102 )
1103 .unwrap();
1104 assert_eq!(start, t("2026-03-01T00:00:00Z"));
1105 assert_eq!(end, t("2026-04-01T00:00:00Z"));
1106 // 但**展示串里绝不能出现 04-01**:那是半开区间的内部细节,
1107 // 印出去等于告诉模型窗口比它要的宽一天,模型会照着答(这条真的发生过)
1108 assert_eq!(label, "2026-03-01 → 2026-03-31");
1109 }
1110
1111 /// 没给 until 时,展示串写 now。写成 end 的格式化结果就等于把服务器时钟
1112 /// 当成用户问的边界——看着像个精确答案,其实只是"现在几点"
1113 #[test]
1114 fn an_open_window_says_now_rather_than_the_clock() {
1115 let now = t("2026-06-01T13:45:00Z");
1116 let (_, end, label) = changes_window(Some(d("2026-03-01")), None, now).unwrap();
1117 assert_eq!(end, now);
1118 assert_eq!(label, "2026-03-01 → now");
1119 }
1120
1121 #[test]
1122 fn without_since_there_is_no_window() {
1123 assert!(changes_window(None, Some(d("2026-03-31")), t("2026-06-01T00:00:00Z")).is_none());
1124 }
1125
1126 // --- change_line --------------------------------------------------------
1127
1128 fn change(kind: &str) -> GraphChange {
1129 GraphChange {
1130 fact_id: Uuid::nil(),
1131 at: t("2026-08-28T10:00:00Z"),
1132 kind: kind.to_string(),
1133 subject_id: Uuid::nil(),
1134 subject_name: "Acme".to_string(),
1135 predicate_label: Some("founded in".to_string()),
1136 object_name: None,
1137 object_value: None,
1138 valid_from: None,
1139 valid_to: None,
1140 // 两端都没日期就没有精度——夹具也得守这条不变量(迁移 0045)
1141 // 两端都没日期,所以两端都没有精度(迁移 0045 / 0046)
1142 valid_from_precision: None,
1143 valid_to_precision: None,
1144 confidence: 0.9,
1145 document_id: None,
1146 filename: None,
1147 quote: None,
1148 }
1149 }
1150
1151 /// 字面值要读成它自己。走 `Value::to_string()` 会把字符串连引号一起印出来,
1152 /// 模型于是把 `"1993"` 当成答案的一部分
1153 #[test]
1154 fn a_literal_value_reads_as_itself_not_as_json() {
1155 let mut c = change("asserted");
1156 c.object_value = Some(serde_json::json!("1993"));
1157 assert!(
1158 change_line(&c).ends_with("Acme founded in 1993"),
1159 "{}",
1160 change_line(&c)
1161 );
1162 }
1163
1164 /// 两根轴必须在同一行里**看得出是两样东西**:记录时刻在前、无标签,
1165 /// 世界轴区间在后、带 `valid` 字样。排成一串裸日期,模型会把
1166 /// "2026 年记下的"读成"2026 年发生的"——这个工具存在的理由就是防这个
1167 #[test]
1168 fn the_record_time_and_the_valid_range_do_not_read_as_one_date_run() {
1169 let mut c = change("corrected");
1170 c.object_name = Some("Berlin".to_string());
1171 c.predicate_label = Some("headquartered in".to_string());
1172 c.valid_from = Some(t("2019-01-01T00:00:00Z"));
1173 let line = change_line(&c);
1174 assert!(line.starts_with("2026-08-28 corrected: "), "{line}");
1175 assert!(line.contains("[valid 2019-01-01 → now]"), "{line}");
1176 }
1177
1178 /// 没有证据就什么都别说。凭空补一句 from "…" 会让一条无出处的断言
1179 /// 看起来有出处
1180 #[test]
1181 fn a_fact_with_no_evidence_claims_no_document() {
1182 let mut c = change("rejected");
1183 c.object_name = Some("Berlin".to_string());
1184 assert!(!change_line(&c).contains("from"), "{}", change_line(&c));
1185 }
1186
1187 #[test]
1188 fn evidence_carries_the_filename_and_the_quote() {
1189 let mut c = change("corrected");
1190 c.object_name = Some("Berlin".to_string());
1191 c.filename = Some("annual-report.pdf".to_string());
1192 c.quote = Some("moved its head office to Berlin".to_string());
1193 let line = change_line(&c);
1194 assert!(line.contains("from \"annual-report.pdf\""), "{line}");
1195 assert!(
1196 line.contains("\"moved its head office to Berlin\""),
1197 "{line}"
1198 );
1199 }
1200}