Elffuss BraidHub

kikocis/utopia public

834f8753ffd7 · 55.6 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 // 语义层:人确认过的 指标/维度 → 数据资产 映射(置信 ≥0.75,与 Review 阈值互补),
277 // 直接进 system prompt——问数优先用确认口径,而不是每次从 schema 猜
278 let mappings = if mounted_sources.is_empty() {
279 Vec::new()
280 } else {
281 utopia_store::graph::confirmed_mappings(&state.pool, kb_id, 0.75, 30).await?
282 };
283 let can_write = utopia_store::access::kb_role(&state.pool, &user, &kb)
284 .await?
285 .is_some_and(|r| r >= Role::Editor);
286
287 const NO_MODEL: &str = "Chat model not configured. Go to Settings → Models.";
288 let settings = utopia_store::settings::get(&state.pool, kb.workspace_id)
289 .await?
290 .ok_or_else(|| AppError::invalid("no_chat_model", NO_MODEL))?;
291 let client = llm_util::chat_client(&settings)
292 .ok_or_else(|| AppError::invalid("no_chat_model", NO_MODEL))?;
293
294 let query = req.message.trim().to_string();
295 if query.is_empty() {
296 return Err(AppError::Validation("Missing user message".into()).into());
297 }
298
299 // 会话持久化:有 id 则校验归属,无则以首句为题新建;用户消息即刻落库,
300 // 上下文由服务端从库里拼——前端只送新消息
301 let conversation_id = match req.conversation_id {
302 Some(id) => {
303 utopia_store::conversations::require_owned(&state.pool, kb_id, user.id, id).await?;
304 id
305 }
306 None => utopia_store::conversations::create(&state.pool, kb_id, user.id, &query).await?,
307 };
308 utopia_store::conversations::append_message(
309 &state.pool,
310 conversation_id,
311 "user",
312 &query,
313 &json!([]),
314 &json!([]),
315 &json!([]),
316 )
317 .await?;
318 let (history, known_entities) = utopia_store::conversations::recent_context(
319 &state.pool,
320 conversation_id,
321 MAX_HISTORY as i64,
322 )
323 .await?;
324 let workspace_id = kb.workspace_id;
325
326 let stream = async_stream::stream! {
327 let ds_names: Vec<String> = mounted_sources.iter().map(|d| d.name.clone()).collect();
328 let tools = tools_schema(can_write, &ds_names);
329 let mut system_prompt = if can_write {
330 format!("{SYSTEM_PROMPT}\n{MEMORY_PROMPT}")
331 } else {
332 SYSTEM_PROMPT.to_string()
333 };
334 if !ds_names.is_empty() {
335 system_prompt.push_str(&format!(
336 "\nData: query_data runs read-only SQL (PostgreSQL dialect) against: {}. \
337 For questions about numbers/metrics, search for the source's schema document \
338 first, then query. State units and the time range you used in the answer.",
339 ds_names.join(", ")
340 ));
341 if !mappings.is_empty() {
342 system_prompt.push_str(
343 "\nSemantic layer (confirmed definitions — use these instead of guessing from schema):",
344 );
345 for (name, def) in &mappings {
346 system_prompt.push_str(&format!("\n- {name}: {def}"));
347 }
348 }
349 }
350 let mut msgs: Vec<serde_json::Value> =
351 vec![json!({ "role": "system", "content": system_prompt })];
352 for (role, content) in &history {
353 msgs.push(json!({ "role": role, "content": content }));
354 }
355 // **前几轮已经认下的实体,连 id 一起交回去。**
356 //
357 // 少了这一段,模型只看得见上一轮的最终答案文字,不知道自己搜过什么、
358 // 拿到过哪些 id,于是从名字重搜一遍。更隐蔽的是同名歧义时两轮可能落到
359 // **不同的实体**上,前后两个答案讲的不是同一个节点。
360 //
361 // 贴在历史之后、当前问题之前——位置就是服从性,跟抽取里 known_block
362 // 紧挨正文是同一条理由。
363 if !known_entities.is_empty() {
364 let lines: Vec<String> = known_entities
365 .iter()
366 .take(KNOWN_ENTITY_LIMIT)
367 .map(|e| {
368 format!(
369 "{} | {} | {}",
370 e["id"].as_str().unwrap_or("?"),
371 e["name"].as_str().unwrap_or("?"),
372 e["type"].as_str().unwrap_or("?")
373 )
374 })
375 .collect();
376 msgs.push(json!({
377 "role": "user",
378 "content": format!(
379 "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:
380 {}",
381 lines.join("
382 ")
383 )
384 }));
385 }
386
387 // 会话 id 先行下发(新会话由此告知前端)
388 yield Ok(Event::default()
389 .event("conversation")
390 .data(json!({ "id": conversation_id }).to_string()));
391
392 // 引用清单:跨轮累积、去重、编号稳定。键 = chunk uuid 或 "charter:{slug}#{anchor}"
393 let mut source_ids: Vec<String> = Vec::new();
394 let mut sources: Vec<serde_json::Value> = Vec::new();
395 // 落库累积:assistant 全文与行动轨迹(历史回放用)
396 let mut answer_acc = String::new();
397 let mut steps_acc: Vec<serde_json::Value> = Vec::new();
398 // 这一轮认下的实体,落库供下一轮回放。**只记身份不记正文**——
399 // 工具结果里是 chunk 全文,每轮重复堆进上下文几轮就把窗口吃光
400 let mut resolved_acc: Vec<serde_json::Value> = Vec::new();
401
402 let mut rounds = 0usize;
403 loop {
404 if rounds >= MAX_ROUNDS {
405 // 弹药耗尽:命令模型就现有证据作答(流式)
406 msgs.push(json!({
407 "role": "user",
408 "content": "(system) Tool budget exhausted. Answer now from the evidence gathered above.",
409 }));
410 match client.chat_stream_raw(&msgs).await {
411 Ok(deltas) => {
412 let mut deltas = std::pin::pin!(deltas);
413 while let Some(item) = deltas.next().await {
414 match item {
415 Ok(text) => { answer_acc.push_str(&text); yield delta_event(&text); }
416 Err(e) => { yield error_event(&e.to_string()); return; }
417 }
418 }
419 let _ = utopia_store::conversations::append_message(
420 &state.pool, conversation_id, "assistant", &answer_acc,
421 &serde_json::Value::Array(steps_acc.clone()),
422 &serde_json::Value::Array(sources.clone()),
423 &serde_json::Value::Array(resolved_acc.clone()),
424 ).await;
425 yield done_event();
426 }
427 Err(e) => yield error_event(&e.to_string()),
428 }
429 return;
430 }
431
432 // 主链路全程流式:正文增量即时转发,工具调用在流末归并到达
433 let deltas = match client.chat_tools_stream(&msgs, &tools).await {
434 Ok(s) => s,
435 Err(e) => {
436 if rounds == 0 {
437 // 模型可能不支持 tool-calling:降级为一次性 RAG 注入
438 tracing::warn!(error = %e, "tool-calling 不可用,降级为一次性 RAG");
439 let chunks =
440 retrieval::hybrid(&state, kb_id, workspace_id, &query, 8)
441 .await
442 .unwrap_or_default();
443 let legacy_sources: Vec<serde_json::Value> = chunks
444 .iter()
445 .enumerate()
446 .map(|(i, c)| source_json(i + 1, c))
447 .collect();
448 yield Ok(Event::default().event("sources").data(
449 serde_json::to_string(&legacy_sources)
450 .unwrap_or_else(|_| "[]".into()),
451 ));
452 let mut lmsgs =
453 vec![json!({ "role": "system", "content": legacy_system_prompt(&chunks) })];
454 for (role, content) in &history {
455 lmsgs.push(json!({ "role": role, "content": content }));
456 }
457 match client.chat_stream_raw(&lmsgs).await {
458 Ok(deltas) => {
459 let mut deltas = std::pin::pin!(deltas);
460 while let Some(item) = deltas.next().await {
461 match item {
462 Ok(text) => { answer_acc.push_str(&text); yield delta_event(&text); }
463 Err(e2) => { yield error_event(&e2.to_string()); return; }
464 }
465 }
466 let _ = utopia_store::conversations::append_message(
467 &state.pool, conversation_id, "assistant", &answer_acc,
468 &serde_json::Value::Array(steps_acc.clone()),
469 &serde_json::Value::Array(legacy_sources.clone()),
470 &serde_json::Value::Array(resolved_acc.clone()),
471 ).await;
472 yield done_event();
473 }
474 Err(e2) => yield error_event(&e2.to_string()),
475 }
476 return;
477 }
478 yield error_event(&e.to_string());
479 return;
480 }
481 };
482 let mut turn: Option<utopia_llm::AssistantTurn> = None;
483 {
484 let mut deltas = std::pin::pin!(deltas);
485 while let Some(item) = deltas.next().await {
486 match item {
487 Ok(utopia_llm::ToolStreamItem::Delta(text)) => {
488 answer_acc.push_str(&text);
489 yield delta_event(&text);
490 }
491 Ok(utopia_llm::ToolStreamItem::Turn(t)) => turn = Some(t),
492 Err(e) => {
493 yield error_event(&e.to_string());
494 return;
495 }
496 }
497 }
498 }
499 let Some(turn) = turn else {
500 yield error_event("LLM stream ended unexpectedly");
501 return;
502 };
503
504 if turn.tool_calls.is_empty() {
505 if answer_acc.is_empty() {
506 yield error_event("Model returned an empty answer");
507 } else {
508 let _ = utopia_store::conversations::append_message(
509 &state.pool, conversation_id, "assistant", &answer_acc,
510 &serde_json::Value::Array(steps_acc.clone()),
511 &serde_json::Value::Array(sources.clone()),
512 &serde_json::Value::Array(resolved_acc.clone()),
513 ).await;
514 yield done_event();
515 }
516 return;
517 }
518
519 // 工具轮带了叙述文本:与后续轮次的正文之间补一个段落分隔
520 if turn.content.is_some() && !answer_acc.is_empty() {
521 answer_acc.push_str("\n\n");
522 yield delta_event("\n\n");
523 }
524
525 msgs.push(turn.to_message());
526 for call in &turn.tool_calls {
527 let args: serde_json::Value =
528 serde_json::from_str(&call.arguments).unwrap_or_else(|_| json!({}));
529 let (result, step) = match call.name.as_str() {
530 "search_chunks" => {
531 let q = args["query"].as_str().unwrap_or(&query).to_string();
532 let chunks = retrieval::hybrid(&state, kb_id, workspace_id, &q, SEARCH_TOP_K)
533 .await
534 .unwrap_or_default();
535 let mut lines = Vec::new();
536 for c in &chunks {
537 let key = c.id.to_string();
538 let n = match source_ids.iter().position(|id| *id == key) {
539 Some(i) => i + 1,
540 None => {
541 source_ids.push(key);
542 sources.push(source_json(source_ids.len(), c));
543 source_ids.len()
544 }
545 };
546 lines.push(format!(
547 "[{n}] \"{}\" section {}:\n{}",
548 c.filename,
549 c.seq + 1,
550 truncate(&c.text, TOOL_CHUNK_CHARS)
551 ));
552 }
553 let text = if lines.is_empty() {
554 "No results.".to_string()
555 } else {
556 lines.join("\n\n")
557 };
558 (text, json!({ "kind": "search", "label": q, "detail": format!("{} sources", chunks.len()) }))
559 }
560 "search_docs" => {
561 let q = args["query"].as_str().unwrap_or(&query).to_string();
562 let hits = state.docs.search(&q, 4).unwrap_or_default();
563 let mut lines = Vec::new();
564 for h in &hits {
565 let key = format!("charter:{}#{}", h.slug, h.anchor);
566 let n = match source_ids.iter().position(|id| *id == key) {
567 Some(i) => i + 1,
568 None => {
569 source_ids.push(key);
570 sources.push(charter_source_json(source_ids.len(), h));
571 source_ids.len()
572 }
573 };
574 lines.push(format!(
575 "[{n}] Utopia Charter — {} › {}:\n{}",
576 h.title,
577 h.heading,
578 truncate(&h.body, 1600)
579 ));
580 }
581 let text = if lines.is_empty() {
582 "No matching manual sections.".to_string()
583 } else {
584 lines.join("\n\n")
585 };
586 (text, json!({ "kind": "docs", "label": q, "detail": format!("{} sections", hits.len()) }))
587 }
588 "find_entities" => {
589 let name = args["name"].as_str().unwrap_or("").to_string();
590 let hits = utopia_store::graph::search_entities(&state.pool, kb_id, &name, 8)
591 .await
592 .unwrap_or_default();
593 let text = if hits.is_empty() {
594 "No matching entities.".to_string()
595 } else {
596 hits.iter()
597 .map(|n| {
598 let dis = n
599 .disambiguator
600 .as_deref()
601 .map(|d| format!(" ({d})"))
602 .unwrap_or_default();
603 format!(
604 "{} | {}{} | {} | {} facts",
605 n.id,
606 n.name,
607 dis,
608 // 没判出类型的实体照样能被搜到、被引用(0009)
609 n.type_label.as_deref().unwrap_or("untyped"),
610 n.degree
611 )
612 })
613 .collect::<Vec<_>>()
614 .join("\n")
615 };
616 for n in &hits {
617 resolved_acc.push(json!({
618 "id": n.id.to_string(), "name": n.name, "type": n.type_label
619 }));
620 }
621 (text, json!({ "kind": "entity", "label": name, "detail": format!("{} matches", hits.len()) }))
622 }
623 "entity_facts" => {
624 let id = args["entity_id"].as_str().and_then(|s| s.parse::<Uuid>().ok());
625 // as-of 过滤:T 时刻有效 = 起点不晚于 T(或未知)且终点晚于 T(或开放)
626 let at = args["at"]
627 .as_str()
628 .and_then(|s| chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok())
629 .map(|d| d.and_hms_opt(0, 0, 0).unwrap().and_utc());
630 match id {
631 Some(id) => match utopia_store::graph::entity_detail(&state.pool, kb_id, id).await {
632 Ok((node, mut facts)) => {
633 if let Some(t) = at {
634 facts.retain(|f| {
635 f.valid_from.is_none_or(|from| from <= t)
636 && f.valid_to.is_none_or(|to| to > t)
637 });
638 }
639 let text = if facts.is_empty() {
640 match at {
641 Some(t) => format!(
642 "{}: no facts valid as of {}.",
643 node.name,
644 t.format("%Y-%m-%d")
645 ),
646 None => format!("{}: no recorded facts.", node.name),
647 }
648 } else {
649 facts.iter().map(fact_line).collect::<Vec<_>>().join("\n")
650 };
651 let detail = match at {
652 Some(t) => format!(
653 "{} facts as of {}",
654 facts.len(),
655 t.format("%Y-%m-%d")
656 ),
657 None => format!("{} facts", facts.len()),
658 };
659 (text, json!({ "kind": "facts", "label": node.name, "detail": detail }))
660 }
661 Err(_) => (
662 "Entity not found.".to_string(),
663 json!({ "kind": "facts", "label": "?", "detail": "not found" }),
664 ),
665 },
666 None => (
667 "Invalid entity_id (expected the uuid returned by find_entities)."
668 .to_string(),
669 json!({ "kind": "facts", "label": "?", "detail": "invalid id" }),
670 ),
671 }
672 }
673 "changes" => {
674 let day = |k: &str| {
675 args[k]
676 .as_str()
677 .and_then(|s| chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok())
678 };
679 match changes_window(day("since"), day("until"), chrono::Utc::now()) {
680 None => (
681 "Invalid or missing `since` (expected YYYY-MM-DD).".to_string(),
682 json!({ "kind": "changes", "label": "?", "detail": "invalid since" }),
683 ),
684 Some((since, until, window)) => {
685 let entity = args["entity_id"]
686 .as_str()
687 .and_then(|s| s.parse::<Uuid>().ok());
688 let kinds: Option<Vec<String>> = args["kinds"].as_array().map(|a| {
689 a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()
690 });
691 let kinds = kinds.filter(|k: &Vec<String>| !k.is_empty());
692 let rows = utopia_store::graph::graph_changes(
693 &state.pool,
694 kb_id,
695 since,
696 until,
697 entity,
698 kinds.as_deref(),
699 CHANGES_LIMIT,
700 )
701 .await
702 .unwrap_or_default();
703 let text = if rows.is_empty() {
704 format!("No recorded changes in {window}.")
705 } else {
706 rows.iter().map(change_line).collect::<Vec<_>>().join("\n")
707 };
708 let detail = if rows.len() as i64 == CHANGES_LIMIT {
709 format!("{CHANGES_LIMIT}+ changes")
710 } else {
711 format!("{} changes", rows.len())
712 };
713 (text, json!({ "kind": "changes", "label": window, "detail": detail }))
714 }
715 }
716 }
717 "query_data" if !mounted_sources.is_empty() => {
718 let ds_name = args["data_source"].as_str().map(str::trim).unwrap_or("");
719 let sql = args["sql"].as_str().map(str::trim).unwrap_or("");
720 let purpose = args["purpose"].as_str().map(str::trim).unwrap_or("");
721 // 安全边界:只允许本 KB 挂载的源(凭据不出服务端)
722 let found = mounted_sources
723 .iter()
724 .find(|d| d.name.eq_ignore_ascii_case(ds_name));
725 let text = match found {
726 None => format!(
727 "Unknown data source '{ds_name}'. Mounted sources: {}",
728 mounted_sources
729 .iter()
730 .map(|d| d.name.as_str())
731 .collect::<Vec<_>>()
732 .join(", ")
733 ),
734 Some(ds) => {
735 match run_query(&state, ds.id, sql).await {
736 Ok(out) => out,
737 // 错误透传:模型可据此修正 SQL 重试
738 Err(e) => format!("Query failed: {e}"),
739 }
740 }
741 };
742 let detail = if purpose.is_empty() {
743 sql.chars().take(60).collect::<String>()
744 } else {
745 purpose.to_string()
746 };
747 (text, json!({ "kind": "query", "label": ds_name, "detail": detail }))
748 }
749 "remember" if can_write => {
750 let text = args["text"].as_str().map(str::trim).unwrap_or("");
751 let occurred_at = args["occurred_at"]
752 .as_str()
753 .and_then(|s| chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok())
754 .map(|d| d.and_hms_opt(12, 0, 0).unwrap().and_utc())
755 .unwrap_or_else(chrono::Utc::now);
756 if text.is_empty() {
757 (
758 "remember requires non-empty text.".to_string(),
759 json!({ "kind": "tool", "label": "remember", "detail": "empty" }),
760 )
761 } else {
762 match utopia_store::memory::append_episode(
763 &state.pool, kb_id, text, occurred_at,
764 )
765 .await
766 {
767 Ok((doc_id, _chunk)) => {
768 // 摄入(embedding/索引/增量抽取)异步走队列,不阻塞对话
769 let _ = utopia_store::jobs::enqueue(
770 &state.pool,
771 "memory_ingest",
772 json!({ "document_id": doc_id }),
773 )
774 .await;
775 state.emit_document(kb_id, doc_id);
776 (
777 format!(
778 "Recorded (effective {}): {text}",
779 occurred_at.format("%Y-%m-%d")
780 ),
781 json!({
782 "kind": "tool", "label": "remember",
783 "detail": text.chars().take(60).collect::<String>()
784 }),
785 )
786 }
787 Err(e) => (
788 format!("Failed to record: {e}"),
789 json!({ "kind": "tool", "label": "remember", "detail": "failed" }),
790 ),
791 }
792 }
793 }
794 other => (
795 format!("Unknown tool: {other}"),
796 json!({ "kind": "tool", "label": other, "detail": "unknown" }),
797 ),
798 };
799 steps_acc.push(step.clone());
800 yield Ok(Event::default()
801 .event("step")
802 .data(serde_json::to_string(&step).unwrap_or_default()));
803 if step["kind"] == "search" || step["kind"] == "docs" {
804 yield Ok(Event::default()
805 .event("sources")
806 .data(serde_json::to_string(&sources).unwrap_or_else(|_| "[]".into())));
807 }
808 msgs.push(tool_result_message(&call.id, &result));
809 }
810 rounds += 1;
811 }
812 };
813
814 Ok(Sse::new(stream).keep_alive(KeepAlive::default()))
815}
816
817fn delta_event(text: &str) -> Result<Event, Infallible> {
818 Ok(Event::default()
819 .event("delta")
820 .data(serde_json::to_string(&json!({ "text": text })).unwrap_or_default()))
821}
822
823fn done_event() -> Result<Event, Infallible> {
824 Ok(Event::default().event("done").data("{}"))
825}
826
827fn error_event(message: &str) -> Result<Event, Infallible> {
828 Ok(Event::default().event("error").data(message))
829}
830
831fn source_json(n: usize, c: &ChunkView) -> serde_json::Value {
832 json!({
833 "n": n,
834 "chunk_id": c.id,
835 "document_id": c.document_id,
836 "filename": c.filename,
837 "excerpt": truncate(&c.text, 160),
838 })
839}
840
841/// Charter 引用:前端渲染成手册行,链到 /docs/{slug}#{anchor}。
842fn charter_source_json(n: usize, h: &utopia_search::DocsSection) -> serde_json::Value {
843 json!({
844 "n": n,
845 "kind": "charter",
846 "slug": h.slug,
847 "anchor": h.anchor,
848 "heading": h.heading,
849 "filename": h.title,
850 "excerpt": truncate(&h.body, 160),
851 })
852}
853
854/// 事实行:"works at → 星云科技 (2023-08 → now) [90%]",in 方向用 ←。
855/// 问数执行:安全闸(解析白名单)→ 引擎执行(只读会话 + 强制 LIMIT + 超时)→ JSON 行。
856async fn run_query(state: &AppState, ds_id: Uuid, sql: &str) -> anyhow::Result<String> {
857 let guarded = crate::query_engine::guard_sql(sql)?;
858 let (engine, conn) = utopia_store::datasources::engine_and_conn(&state.pool, ds_id).await?;
859 let result = crate::query_engine::engine_for(&engine, &conn)?
860 .execute(&guarded)
861 .await?;
862 let mut out = String::new();
863 if result.rows.is_empty() {
864 out.push_str("(no rows)");
865 } else {
866 out.push_str(&result.rows.join("\n"));
867 out.push_str(&format!("\n({} rows", result.rows.len()));
868 if result.truncated {
869 out.push_str(&format!(
870 ", truncated at {} — aggregate in SQL for totals",
871 crate::query_engine::ROW_CAP
872 ));
873 }
874 out.push(')');
875 }
876 Ok(out)
877}
878
879fn fact_line(f: &EntityFact) -> String {
880 let other = f.other_name.as_deref().unwrap_or("?");
881 let core = if f.direction == "out" {
882 format!("{} → {}", f.predicate_label, other)
883 } else {
884 format!("{} ← {}", f.predicate_label, other)
885 };
886 let range = match (&f.valid_from, &f.valid_to) {
887 (Some(from), Some(to)) => {
888 format!(" ({} → {})", from.format("%Y-%m-%d"), to.format("%Y-%m-%d"))
889 }
890 (Some(from), None) => format!(" ({} → now)", from.format("%Y-%m-%d")),
891 (None, Some(to)) => format!(" (→ {})", to.format("%Y-%m-%d")),
892 (None, None) => String::new(),
893 };
894 format!("{core}{range} [{}%]", (f.confidence * 100.0).round() as i32)
895}
896
897/// changes 的时间窗:把两个可选日期变成 (SQL 用的半开区间, 展示用的窗口串)。
898///
899/// **抽成纯函数是因为这里出过一次错。** `until` 进 SQL 前要加一天(说"到 3 月 31 日
900/// 为止"的人要的是含 31 日,而 SQL 那头是 `< $3`),第一版把加过一天的值也印进了
901/// 展示串,模型于是照着答"截至 8 月 30 日"——问的是 29 日。两个值必须一起算、
902/// 一起被测住;分在两处写,迟早再次分叉。
903///
904/// `now` 从外面传进来而不是在里面取,纯粹是为了这个函数测得动。
905fn changes_window(
906 since: Option<chrono::NaiveDate>,
907 until: Option<chrono::NaiveDate>,
908 now: chrono::DateTime<chrono::Utc>,
909) -> Option<(
910 chrono::DateTime<chrono::Utc>,
911 chrono::DateTime<chrono::Utc>,
912 String,
913)> {
914 let from = since?;
915 let start = from.and_hms_opt(0, 0, 0).unwrap().and_utc();
916 let end = until
917 .and_then(|d| d.succ_opt())
918 .map(|d| d.and_hms_opt(0, 0, 0).unwrap().and_utc())
919 .unwrap_or(now);
920 // 展示用的是**问的那天**,没问就写 now——绝不是 end
921 let label = format!(
922 "{} → {}",
923 from.format("%Y-%m-%d"),
924 match until {
925 Some(d) => d.format("%Y-%m-%d").to_string(),
926 None => "now".to_string(),
927 }
928 );
929 Some((start, end, label))
930}
931
932/// 认知轴上的一行。
933///
934/// 排版把两根轴**分开写**:`at` 前面标事件类型,世界轴的区间夹在括号里跟在断言后。
935/// 若把它们排成一串日期,模型会把"2026 年记下的"读成"2026 年发生的"——那正是
936/// 这个工具要防的误读。
937fn change_line(c: &GraphChange) -> String {
938 let object = match (&c.object_name, &c.object_value) {
939 (Some(name), _) => name.clone(),
940 (None, Some(v)) => match v {
941 serde_json::Value::String(s) => s.clone(),
942 other => other.to_string(),
943 },
944 (None, None) => "?".to_string(),
945 };
946 let range = match (&c.valid_from, &c.valid_to) {
947 (Some(from), Some(to)) => {
948 format!(
949 " [valid {} → {}]",
950 from.format("%Y-%m-%d"),
951 to.format("%Y-%m-%d")
952 )
953 }
954 (Some(from), None) => format!(" [valid {} → now]", from.format("%Y-%m-%d")),
955 (None, Some(to)) => format!(" [valid → {}]", to.format("%Y-%m-%d")),
956 (None, None) => String::new(),
957 };
958 // 文件名不带 [n]:引证编号是 chunk 的,这里只有 document,发一个编号出去
959 // 会在界面上落成一条指不到东西的引证
960 let src = match (&c.filename, &c.quote) {
961 (Some(f), Some(q)) => format!(" — from \"{f}\": \"{}\"", truncate(q, 160)),
962 (Some(f), None) => format!(" — from \"{f}\""),
963 _ => String::new(),
964 };
965 format!(
966 "{} {}: {} {} {}{}{}",
967 c.at.format("%Y-%m-%d"),
968 c.kind,
969 c.subject_name,
970 c.predicate_label,
971 object,
972 range,
973 src
974 )
975}
976
977/// 降级路径的系统提示(tool-calling 不可用时的一次性注入)。
978fn legacy_system_prompt(chunks: &[ChunkView]) -> String {
979 if chunks.is_empty() {
980 return "You are an enterprise knowledge base assistant. No relevant sources were \
981 retrieved for this question. Tell the user the knowledge base lacks material \
982 on this topic, answer cautiously from general knowledge, and clearly separate \
983 sourced statements from speculation. Always respond in the same language as \
984 the user's question."
985 .to_string();
986 }
987 let mut prompt = String::from(
988 "You are an enterprise knowledge base assistant. Answer strictly based on the \
989 numbered sources below. When a source supports a statement, append its citation \
990 number, e.g. [1] or [2], at the end of the sentence. If the sources are \
991 insufficient, say so explicitly — never fabricate. Always respond in the same \
992 language as the user's question.\n\n### Sources\n",
993 );
994 for (i, c) in chunks.iter().enumerate() {
995 prompt.push_str(&format!(
996 "\n[{}] \"{}\" section {}:\n{}\n",
997 i + 1,
998 c.filename,
999 c.seq + 1,
1000 c.text
1001 ));
1002 }
1003 prompt
1004}
1005
1006fn truncate(text: &str, max_chars: usize) -> String {
1007 let t = text.trim();
1008 if t.chars().count() <= max_chars {
1009 t.to_string()
1010 } else {
1011 let cut: String = t.chars().take(max_chars).collect();
1012 format!("{cut}…")
1013 }
1014}
1015
1016// ---------------------------------------------------------------------------
1017// 会话管理(列表 / 回放 / 删除)
1018// ---------------------------------------------------------------------------
1019
1020pub async fn list_conversations(
1021 State(state): State<AppState>,
1022 AuthUser(user): AuthUser,
1023 Path(kb_id): Path<Uuid>,
1024) -> ApiResult<Json<serde_json::Value>> {
1025 utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
1026 let conversations = utopia_store::conversations::list(&state.pool, kb_id, user.id).await?;
1027 Ok(Json(json!({ "conversations": conversations })))
1028}
1029
1030/// 历史回放:消息含落库的行动轨迹(steps)与引用(sources)。
1031pub async fn conversation_detail(
1032 State(state): State<AppState>,
1033 AuthUser(user): AuthUser,
1034 Path((kb_id, conversation_id)): Path<(Uuid, Uuid)>,
1035) -> ApiResult<Json<serde_json::Value>> {
1036 utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
1037 utopia_store::conversations::require_owned(&state.pool, kb_id, user.id, conversation_id)
1038 .await?;
1039 let messages = utopia_store::conversations::messages(&state.pool, conversation_id).await?;
1040 Ok(Json(json!({ "messages": messages })))
1041}
1042
1043pub async fn delete_conversation(
1044 State(state): State<AppState>,
1045 AuthUser(user): AuthUser,
1046 Path((kb_id, conversation_id)): Path<(Uuid, Uuid)>,
1047) -> ApiResult<Json<serde_json::Value>> {
1048 utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
1049 utopia_store::conversations::delete(&state.pool, kb_id, user.id, conversation_id).await?;
1050 Ok(Json(json!({ "ok": true })))
1051}
1052
1053#[cfg(test)]
1054mod tests {
1055 use super::*;
1056
1057 fn d(s: &str) -> chrono::NaiveDate {
1058 chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d").unwrap()
1059 }
1060 fn t(s: &str) -> chrono::DateTime<chrono::Utc> {
1061 s.parse().unwrap()
1062 }
1063
1064 // --- changes_window -----------------------------------------------------
1065
1066 /// 说"到 3 月 31 日为止"的人要的是**含 31 日**。SQL 那头是 `< end`,
1067 /// 所以 end 必须落在 4 月 1 日零点——差这一天,问 31 日会安静地丢掉 31 日
1068 #[test]
1069 fn until_names_a_day_the_window_must_contain() {
1070 let (start, end, label) = changes_window(
1071 Some(d("2026-03-01")),
1072 Some(d("2026-03-31")),
1073 t("2026-06-01T00:00:00Z"),
1074 )
1075 .unwrap();
1076 assert_eq!(start, t("2026-03-01T00:00:00Z"));
1077 assert_eq!(end, t("2026-04-01T00:00:00Z"));
1078 // 但**展示串里绝不能出现 04-01**:那是半开区间的内部细节,
1079 // 印出去等于告诉模型窗口比它要的宽一天,模型会照着答(这条真的发生过)
1080 assert_eq!(label, "2026-03-01 → 2026-03-31");
1081 }
1082
1083 /// 没给 until 时,展示串写 now。写成 end 的格式化结果就等于把服务器时钟
1084 /// 当成用户问的边界——看着像个精确答案,其实只是"现在几点"
1085 #[test]
1086 fn an_open_window_says_now_rather_than_the_clock() {
1087 let now = t("2026-06-01T13:45:00Z");
1088 let (_, end, label) = changes_window(Some(d("2026-03-01")), None, now).unwrap();
1089 assert_eq!(end, now);
1090 assert_eq!(label, "2026-03-01 → now");
1091 }
1092
1093 #[test]
1094 fn without_since_there_is_no_window() {
1095 assert!(changes_window(None, Some(d("2026-03-31")), t("2026-06-01T00:00:00Z")).is_none());
1096 }
1097
1098 // --- change_line --------------------------------------------------------
1099
1100 fn change(kind: &str) -> GraphChange {
1101 GraphChange {
1102 fact_id: Uuid::nil(),
1103 at: t("2026-08-28T10:00:00Z"),
1104 kind: kind.to_string(),
1105 subject_id: Uuid::nil(),
1106 subject_name: "Acme".to_string(),
1107 predicate_label: "founded in".to_string(),
1108 object_name: None,
1109 object_value: None,
1110 valid_from: None,
1111 valid_to: None,
1112 // 两端都没日期就没有精度——夹具也得守这条不变量(迁移 0045)
1113 // 两端都没日期,所以两端都没有精度(迁移 0045 / 0046)
1114 valid_from_precision: None,
1115 valid_to_precision: None,
1116 confidence: 0.9,
1117 document_id: None,
1118 filename: None,
1119 quote: None,
1120 }
1121 }
1122
1123 /// 字面值要读成它自己。走 `Value::to_string()` 会把字符串连引号一起印出来,
1124 /// 模型于是把 `"1993"` 当成答案的一部分
1125 #[test]
1126 fn a_literal_value_reads_as_itself_not_as_json() {
1127 let mut c = change("asserted");
1128 c.object_value = Some(serde_json::json!("1993"));
1129 assert!(
1130 change_line(&c).ends_with("Acme founded in 1993"),
1131 "{}",
1132 change_line(&c)
1133 );
1134 }
1135
1136 /// 两根轴必须在同一行里**看得出是两样东西**:记录时刻在前、无标签,
1137 /// 世界轴区间在后、带 `valid` 字样。排成一串裸日期,模型会把
1138 /// "2026 年记下的"读成"2026 年发生的"——这个工具存在的理由就是防这个
1139 #[test]
1140 fn the_record_time_and_the_valid_range_do_not_read_as_one_date_run() {
1141 let mut c = change("corrected");
1142 c.object_name = Some("Berlin".to_string());
1143 c.predicate_label = "headquartered in".to_string();
1144 c.valid_from = Some(t("2019-01-01T00:00:00Z"));
1145 let line = change_line(&c);
1146 assert!(line.starts_with("2026-08-28 corrected: "), "{line}");
1147 assert!(line.contains("[valid 2019-01-01 → now]"), "{line}");
1148 }
1149
1150 /// 没有证据就什么都别说。凭空补一句 from "…" 会让一条无出处的断言
1151 /// 看起来有出处
1152 #[test]
1153 fn a_fact_with_no_evidence_claims_no_document() {
1154 let mut c = change("rejected");
1155 c.object_name = Some("Berlin".to_string());
1156 assert!(!change_line(&c).contains("from"), "{}", change_line(&c));
1157 }
1158
1159 #[test]
1160 fn evidence_carries_the_filename_and_the_quote() {
1161 let mut c = change("corrected");
1162 c.object_name = Some("Berlin".to_string());
1163 c.filename = Some("annual-report.pdf".to_string());
1164 c.quote = Some("moved its head office to Berlin".to_string());
1165 let line = change_line(&c);
1166 assert!(line.contains("from \"annual-report.pdf\""), "{line}");
1167 assert!(
1168 line.contains("\"moved its head office to Berlin\""),
1169 "{line}"
1170 );
1171 }
1172}