Elffuss BraidHub

kikocis/utopia public

2aaf42ceca19 · 47.5 KiBRawPermalink
1//! Agentic 对话:模型自主调用工具(文档检索 / 实体查找 / 时态事实)收集证据后作答。
2//! 事件序列:step*(行动轨迹)| sources(引用清单,随检索增量更新)| delta*(增量文本)→ done | error。
3//! 模型不支持 tool-calling 时自动降级为一次性 RAG 注入。
4
5use super::tools;
6use crate::live::Frame;
7use axum::extract::{Path, Query, State};
8use axum::response::sse::{Event, KeepAlive, Sse};
9use axum::Json;
10use futures_util::{Stream, StreamExt};
11use serde::Deserialize;
12use serde_json::json;
13use std::convert::Infallible;
14use utopia_core::models::{ChunkView, Role};
15use utopia_core::AppError;
16use utopia_llm::tool_result_message;
17use uuid::Uuid;
18
19use crate::auth::AuthUser;
20use crate::error::ApiResult;
21use crate::llm_util;
22use crate::retrieval;
23use crate::state::AppState;
24
25/// 回放几个已认下的实体。上限是因为长会话会攒出几十个,全贴回去就把
26/// 省下来的上下文又花掉了;按首次出现排序,早认下的通常是这场对话的主角。
27const KNOWN_ENTITY_LIMIT: usize = 20;
28
29const MAX_HISTORY: usize = 20;
30const MAX_ROUNDS: usize = 6;
31
32#[derive(Deserialize)]
33pub struct ChatReq {
34 /// 缺省 = 新建会话(SSE 首个 `conversation` 事件回传 id)
35 #[serde(default)]
36 pub conversation_id: Option<Uuid>,
37 pub message: String,
38}
39
40fn tools_schema(can_write: bool, data_source_names: &[String]) -> serde_json::Value {
41 let mut tools = base_tools();
42 if !data_source_names.is_empty() {
43 if let Some(arr) = tools.as_array_mut() {
44 arr.push(json!({
45 "type": "function",
46 "function": {
47 "name": "query_data",
48 "description": format!(
49 "Run a read-only SQL query against a mounted database. Available sources: \
50 {}. Search the source's schema document first (search_chunks) if unsure \
51 of tables/columns. Only a single SELECT/WITH statement is allowed; a \
52 LIMIT is enforced server-side; results come back as JSON lines. If the \
53 query errors, fix the SQL and retry once.",
54 data_source_names.join(", ")
55 ),
56 "parameters": {
57 "type": "object",
58 "properties": {
59 "data_source": {
60 "type": "string",
61 "description": "Name of the mounted data source to query."
62 },
63 "sql": {
64 "type": "string",
65 "description": "One SELECT/WITH statement (PostgreSQL dialect)."
66 },
67 "purpose": {
68 "type": "string",
69 "description": "One short phrase: what this query answers (shown to the user)."
70 }
71 },
72 "required": ["data_source", "sql"]
73 }
74 }
75 }));
76 }
77 }
78 if can_write {
79 if let Some(arr) = tools.as_array_mut() {
80 arr.push(json!({
81 "type": "function",
82 "function": {
83 "name": "remember",
84 "description": "Record one memory episode into the knowledge base's temporal \
85 memory. Use ONLY when the user explicitly asks to remember/record \
86 something, or clearly states a decision or fact to keep. The episode is \
87 extracted into the knowledge graph; if it contradicts an existing \
88 single-valued fact, the old fact's validity is closed automatically \
89 (never deleted). Do not use for casual conversation.",
90 "parameters": {
91 "type": "object",
92 "properties": {
93 "text": {
94 "type": "string",
95 "description": "The episode to remember, one self-contained \
96 statement (who/what, with names spelled out)."
97 },
98 "occurred_at": {
99 "type": "string",
100 "description": "Optional date the stated fact took effect \
101 (YYYY-MM-DD). Omit to use today."
102 }
103 },
104 "required": ["text"]
105 }
106 }
107 }));
108 }
109 }
110 tools
111}
112
113/// 执行之前先看这次调用说清楚了没有。
114///
115/// **两种「没说清」以前都会安静地变成一次正常调用。**
116///
117/// 一是参数解析不出来。模型的输出撞上 token 上限时,`arguments` 会在半路断掉,
118/// 那串 JSON 不完整。从前这里是 `unwrap_or_else(|_| json!({}))`——空对象,
119/// 接着 `search_chunks` 里 `args["query"].as_str().unwrap_or(&query)` 回落到
120/// **用户那句原话**,于是一次被截断的调用变成「拿用户的原问题去检索」,
121/// 而轨迹上显示的是一条完全正常的 `search · 6 sources`。
122///
123/// 二是必填参数干脆没给。同一个回落,同一个结果。
124///
125/// 两种都不该猜。**回落产出的是一个看起来没问题的错误答案**,那比报错坏得多——
126/// 报错模型会重试,猜出来的答案没有人会去核。
127///
128/// 判据直接取自工具表里的 `required`:加一个必填参数,这里自动跟上,
129/// 不必记得来改第二处。
130fn check_call(
131 tools: &serde_json::Value,
132 name: &str,
133 raw_args: &str,
134) -> Result<serde_json::Value, (String, serde_json::Value)> {
135 let refuse = |detail: &str, message: String| {
136 (
137 message,
138 json!({ "kind": "tool", "label": name, "detail": detail }),
139 )
140 };
141 let Ok(args) = serde_json::from_str::<serde_json::Value>(raw_args) else {
142 return Err(refuse(
143 "bad arguments",
144 format!(
145 "The arguments for {name} were not valid JSON, so the call was not run. \
146 They were probably cut off. Call it again with complete arguments."
147 ),
148 ));
149 };
150 let required = tools
151 .as_array()
152 .into_iter()
153 .flatten()
154 .find(|t| t["function"]["name"] == name)
155 .and_then(|t| t["function"]["parameters"]["required"].as_array());
156 for key in required.into_iter().flatten().filter_map(|k| k.as_str()) {
157 // 空串与 null 都算没给:`{"query": ""}` 检索出来的东西与问题无关,
158 // 而它同样会显示成一条正常的轨迹
159 let missing = match args.get(key) {
160 None | Some(serde_json::Value::Null) => true,
161 Some(serde_json::Value::String(s)) => s.trim().is_empty(),
162 Some(_) => false,
163 };
164 if missing {
165 return Err(refuse(
166 &format!("missing {key}"),
167 format!(
168 "{name} needs `{key}`, and it was missing or empty, so the call was not \
169 run. Call it again with `{key}` set."
170 ),
171 ));
172 }
173 }
174 Ok(args)
175}
176
177const MEMORY_PROMPT: &str = "\
178 Memory: you can persist knowledge with the remember tool. Use it when the user says \
179 \"remember/record this\" or states a decision meant to last. Confirm in your reply what \
180 was recorded. Never invent memories, and never call it for small talk.";
181
182fn base_tools() -> serde_json::Value {
183 json!([
184 {
185 "type": "function",
186 "function": {
187 "name": "search_chunks",
188 "description": "Full-text + semantic search over the knowledge base documents. \
189 Returns numbered source excerpts you can cite as [n].",
190 "parameters": {
191 "type": "object",
192 "properties": {
193 "query": { "type": "string", "description": "Search query, phrased in the corpus language." }
194 },
195 "required": ["query"]
196 }
197 }
198 },
199 {
200 "type": "function",
201 "function": {
202 "name": "search_docs",
203 "description": "Search Utopia's own user manual (the Charter): how the platform \
204 itself works — sources and ingestion, sync semantics (missing markers, \
205 tombstones, versions), the knowledge graph and review flow, roles and \
206 permissions, settings. Use ONLY for questions about using or understanding \
207 Utopia itself, or to explain platform concepts that appear in other tool \
208 results (e.g. why a document is marked missing). NEVER use it to answer \
209 questions about the content stored in the knowledge base.",
210 "parameters": {
211 "type": "object",
212 "properties": {
213 "query": { "type": "string", "description": "What to look up in the manual." }
214 },
215 "required": ["query"]
216 }
217 }
218 },
219 {
220 "type": "function",
221 "function": {
222 "name": "find_entities",
223 "description": "Look up entities in the knowledge graph by (partial) name. \
224 Returns id, name, type and a disambiguator when several entities share a name.",
225 "parameters": {
226 "type": "object",
227 "properties": {
228 "name": { "type": "string", "description": "Entity name or a fragment of it." }
229 },
230 "required": ["name"]
231 }
232 }
233 },
234 {
235 "type": "function",
236 "function": {
237 "name": "entity_facts",
238 "description": "Facts about one entity from the bi-temporal knowledge graph: \
239 relations with validity ranges (from → to; 'now' = still ongoing). \
240 The best tool for who/when/history questions. Use after find_entities. \
241 Pass `at` to see the world as of that date (server-side filter) — \
242 always do this for \"who was X in <year/month>\" questions.",
243 "parameters": {
244 "type": "object",
245 "properties": {
246 "entity_id": { "type": "string", "description": "Entity id (uuid) from find_entities." },
247 "at": {
248 "type": "string",
249 "description": "Optional as-of date (YYYY-MM-DD). Only facts valid on \
250 this date are returned. Omit for the full history."
251 }
252 },
253 "required": ["entity_id"]
254 }
255 }
256 },
257 {
258 "type": "function",
259 "function": {
260 "name": "changes",
261 "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.",
262 "parameters": {
263 "type": "object",
264 "properties": {
265 "since": {
266 "type": "string",
267 "description": "Start of the window (YYYY-MM-DD), inclusive."
268 },
269 "until": {
270 "type": "string",
271 "description": "End of the window (YYYY-MM-DD), inclusive of that whole day. Omit for 'up to now'."
272 },
273 "entity_id": {
274 "type": "string",
275 "description": "Optional entity id from find_entities, to narrow the window to changes touching that one entity."
276 },
277 "kinds": {
278 "type": "array",
279 "items": {
280 "type": "string",
281 "enum": ["asserted", "corrected", "rejected", "merged"]
282 },
283 "description": "Optional filter. A freshly ingested corpus is nearly all 'asserted'; pass [\"corrected\", \"rejected\"] to isolate the places we actually changed our mind."
284 }
285 },
286 "required": ["since"]
287 }
288 }
289 }
290 ])
291}
292
293const SYSTEM_PROMPT: &str = "You are the assistant of Utopia, a temporal knowledge platform. \
294 You have tools: search_chunks (document search), find_entities, entity_facts and \
295 changes (a bi-temporal knowledge graph), and search_docs (Utopia's own manual, the \
296 Charter).\n\
297 The graph has TWO independent time axes, and each graph tool reads exactly one:\n\
298 - World time — when something was true. Read with entity_facts (`at` = as of that date).\n\
299 - Record time — when we came to believe it, and when we revised it. Read with changes.\n\
300 \"Who was CTO in 2019\" is world time; \"what did we learn last month\" and \"what did \
301 we get wrong\" are record time. The same fact has a position on both.\n\
302 Boundary: search_docs answers questions about Utopia itself (features, ingestion, \
303 permissions, what fields like 'missing' or validity ranges mean); the other tools answer \
304 questions about the knowledge stored in it. Never mix the manual into answers about the \
305 user's data unless they asked about Utopia's behavior.\n\
306 \n\
307 Method:\n\
308 First decide what the message is about. A message about THIS CONVERSATION — translate it, \
309 say it shorter, rephrase it, \"what did you just say\", \"why\" — is answered from the \
310 transcript above with NO tool calls: the evidence is already in it. Gathering it again is \
311 not merely wasted work — with several entities sharing a name the second pass can land on \
312 a different one, and the \"translation\" then says something else. Just deliver it — no \
313 preamble about what you are or are not looking up. Everything below is for messages about \
314 the user's data.\n\
315 1. For factual questions — questions about the user's data, never one about this \
316 conversation — ALWAYS gather evidence with tools before answering. Prefer the \
317 graph tools for questions about people/organizations/projects and time (\"who was X \
318 when\", \"what changed\"), search_chunks for content and detail questions. Combine both \
319 when useful.\n\
320 2. Facts carry validity ranges (from → to). For \"as of <date>\" questions pass `at` to \
321 entity_facts and the server filters to that moment; for history questions omit `at` \
322 to see the full timeline. State dates in the answer.\n\
323 2b. For \"what changed / what is new / what did we get wrong since <date>\", call changes — \
324 it needs no entity. Name the document a correction came from in plain prose. Graph tools \
325 return no [n] numbers and no URLs, so never write a bracketed citation or a placeholder \
326 like [Link] after one — the document's name IS the attribution.\n\
327 3. Several entities can share one name — check the disambiguator and pick the right one; \
328 if genuinely ambiguous, ask the user which one they mean.\n\
329 4. Stop calling tools as soon as you have enough evidence. Then answer concisely: cite \
330 document sources with [n] (numbers from search results) at the end of supported \
331 sentences. If the evidence is insufficient, say so explicitly — never fabricate.\n\
332 5. Always respond in the same language as the user's question.";
333
334pub async fn chat(
335 State(state): State<AppState>,
336 AuthUser(user): AuthUser,
337 Path(kb_id): Path<Uuid>,
338 Json(req): Json<ChatReq>,
339) -> ApiResult<Sse<impl Stream<Item = Result<Event, Infallible>>>> {
340 let kb = utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
341 // 写工具跟人走:editor 及以上的对话才带 remember,viewer 纯只读
342 // 挂载的数据源决定 query_data 是否入列(问数是读,viewer 亦可用)
343 let mounted_sources = utopia_store::datasources::mounted(&state.pool, kb_id).await?;
344 // 语义层:人确认过的 指标/维度 → 数据资产 映射,直接进 system prompt——
345 // 问数优先用确认口径,而不是每次从 schema 猜。
346 //
347 // 从前这里按 `confidence >= 0.75` 捞事实,而那个阈值是拿浮点数编码一个
348 // 二值状态(提议 0.6 / 确认 1.0)。现在读 `status = confirmed`(0011)
349 let mappings = if mounted_sources.is_empty() {
350 Vec::new()
351 } else {
352 utopia_store::mappings::confirmed(&state.pool, kb_id, 30).await?
353 };
354 let can_write = utopia_store::access::kb_role(&state.pool, &user, &kb)
355 .await?
356 .is_some_and(|r| r >= Role::Editor);
357
358 const NO_MODEL: &str = "Chat model not configured. Go to Settings → Models.";
359 let settings = utopia_store::settings::get(&state.pool, kb.workspace_id)
360 .await?
361 .ok_or_else(|| AppError::invalid("no_chat_model", NO_MODEL))?;
362 let client = llm_util::chat_client(&settings)
363 .ok_or_else(|| AppError::invalid("no_chat_model", NO_MODEL))?;
364
365 let query = req.message.trim().to_string();
366 if query.is_empty() {
367 return Err(AppError::Validation("Missing user message".into()).into());
368 }
369
370 // 会话持久化:有 id 则校验归属,无则以首句为题新建;用户消息即刻落库,
371 // 上下文由服务端从库里拼——前端只送新消息
372 let conversation_id = match req.conversation_id {
373 Some(id) => {
374 utopia_store::conversations::require_owned(&state.pool, kb_id, user.id, id).await?;
375 id
376 }
377 None => utopia_store::conversations::create(&state.pool, kb_id, user.id, &query).await?,
378 };
379 utopia_store::conversations::append_message(
380 &state.pool,
381 conversation_id,
382 "user",
383 &query,
384 &utopia_store::conversations::TurnRecord::empty(),
385 )
386 .await?;
387 let history = utopia_store::conversations::recent_context(
388 &state.pool,
389 conversation_id,
390 MAX_HISTORY as i64,
391 )
392 .await?;
393 let workspace_id = kb.workspace_id;
394
395 // 注册表在生成器之前取出来:下面那个 `async_stream!` 会把 `state` 整个搬走
396 let live = state.live.clone();
397
398 // 生成过程不挂在这条连接上。
399 //
400 // **切走一次就丢一个回答**,而且丢得比看上去彻底:整段生成住在下面这个
401 // 生成器里,助手消息只在走完时落库;浏览器一导航,axum 丢掉响应体、
402 // 生成器 future 被丢弃,于是 LLM 调用当场取消,那句 `append_message`
403 // 永远不执行。实测掐断连接时已经收到 1219 字节的正文,二十秒后库里
404 // 只剩用户那一行——**那个回答不是存在但没显示,是根本没被生成完**。
405 //
406 // 所以把生成器交给一个独立任务去驱动,这条连接降级成一个订阅者。
407 // 任务不随连接消失,答案照常写完、照常落库,人回来就在。
408 //
409 // 代价说清楚:**没人看的时候仍然在花钱**。这是有意的——丢答案比多跑一轮贵,
410 // 而 `MAX_ROUNDS` 已经给了上限。send 失败(接收端没了)不中断,那正是要点。
411 let producer = async_stream::stream! {
412 let ds_names: Vec<String> = mounted_sources.iter().map(|d| d.name.clone()).collect();
413 let tools = tools_schema(can_write, &ds_names);
414 let mut system_prompt = if can_write {
415 format!("{SYSTEM_PROMPT}\n{MEMORY_PROMPT}")
416 } else {
417 SYSTEM_PROMPT.to_string()
418 };
419 if !ds_names.is_empty() {
420 system_prompt.push_str(&format!(
421 "\nData: query_data runs read-only SQL (PostgreSQL dialect) against: {}. \
422 For questions about numbers/metrics, search for the source's schema document \
423 first, then query. State units and the time range you used in the answer.",
424 ds_names.join(", ")
425 ));
426 if !mappings.is_empty() {
427 system_prompt.push_str(
428 "\nSemantic layer (confirmed definitions — use these instead of guessing from schema):",
429 );
430 // 从前这里直接把整份 JSON 打进去。现在字段是列,只挑问数用得上的
431 // 那几样铺开——`sql` 与 `expr` 是「怎么算」,`unit` 是答里必须带的
432 // 量纲,`summary` 是给模型的一句人话
433 for m in &mappings {
434 let how = m
435 .sql
436 .as_deref()
437 .or(m.expr.as_deref())
438 .or(m.table_name.as_deref())
439 .unwrap_or("-");
440 let unit = m
441 .unit
442 .as_deref()
443 .map(|u| format!(" [{u}]"))
444 .unwrap_or_default();
445 let note = m
446 .summary
447 .as_deref()
448 .map(|s| format!(" — {s}"))
449 .unwrap_or_default();
450 system_prompt.push_str(&format!(
451 "\n- {} ({}){unit}: {how}{note}",
452 m.concept_name, m.source
453 ));
454 }
455 }
456 }
457 let mut msgs: Vec<serde_json::Value> =
458 vec![json!({ "role": "system", "content": system_prompt })];
459 /* **上一轮做过什么,按它当时发生的位置放回去。**
460 最后那条助手消息是它的结论;带 `tool_calls` 的消息与 tool 结果
461 发生在它之前,所以插在它前面——顺序就是真实顺序,模型读起来
462 就是「我问了、我查了、我答了」。
463 少了这一段,跨轮之后它只看得见自己写的散文,于是接着说「翻译」
464 时重查一遍(还可能落到另一批同名实体上)。 */
465 let last_assistant = history
466 .turns
467 .iter()
468 .rposition(|(role, _)| role == "assistant");
469 for (i, (role, content)) in history.turns.iter().enumerate() {
470 if Some(i) == last_assistant {
471 for m in &history.last_tool_exchange {
472 msgs.push(m.clone());
473 }
474 }
475 msgs.push(json!({ "role": role, "content": content }));
476 }
477 // **前几轮已经认下的实体,连 id 一起交回去。**
478 //
479 // 少了这一段,模型只看得见上一轮的最终答案文字,不知道自己搜过什么、
480 // 拿到过哪些 id,于是从名字重搜一遍。更隐蔽的是同名歧义时两轮可能落到
481 // **不同的实体**上,前后两个答案讲的不是同一个节点。
482 //
483 // 贴在历史之后、当前问题之前——位置就是服从性,跟抽取里 known_block
484 // 紧挨正文是同一条理由。
485 if !history.entities.is_empty() {
486 let lines: Vec<String> = history.entities
487 .iter()
488 .take(KNOWN_ENTITY_LIMIT)
489 .map(|e| {
490 format!(
491 "{} | {} | {}",
492 e["id"].as_str().unwrap_or("?"),
493 e["name"].as_str().unwrap_or("?"),
494 e["type"].as_str().unwrap_or("?")
495 )
496 })
497 .collect();
498 msgs.push(json!({
499 "role": "user",
500 "content": format!(
501 "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:
502 {}",
503 lines.join("
504 ")
505 )
506 }));
507 }
508
509 // 会话 id 先行下发(新会话由此告知前端)
510 yield Frame::new("conversation", json!({ "id": conversation_id }).to_string());
511
512 // 引用清单与这一轮认下的实体。**攒在工具外面**——`[3]` 里的 3 取决于
513 // 之前已经引过几个,各个工具各算各的会让同一个 chunk 拿到两个号
514 let mut sink = tools::ToolSink::default();
515 // 落库累积:assistant 全文与行动轨迹(历史回放用)
516 let mut answer_acc = String::new();
517 let mut steps_acc: Vec<serde_json::Value> = Vec::new();
518 // 这一轮的工具往返,原样留一份落库:下一轮回放它,模型才知道自己做过什么
519 let mut exchange_acc: Vec<serde_json::Value> = Vec::new();
520
521 let mut rounds = 0usize;
522 loop {
523 if rounds >= MAX_ROUNDS {
524 // 弹药耗尽:命令模型就现有证据作答(流式)
525 msgs.push(json!({
526 "role": "user",
527 "content": "(system) Tool budget exhausted. Answer now from the evidence gathered above.",
528 }));
529 match client.chat_stream_raw(&msgs).await {
530 Ok(deltas) => {
531 let mut deltas = std::pin::pin!(deltas);
532 while let Some(item) = deltas.next().await {
533 match item {
534 Ok(text) => { answer_acc.push_str(&text); yield delta_event(&text); }
535 Err(e) => { yield error_event(&e.to_string()); return; }
536 }
537 }
538 let _ = utopia_store::conversations::append_message(
539 &state.pool, conversation_id, "assistant", &answer_acc,
540 &utopia_store::conversations::TurnRecord {
541 steps: serde_json::Value::Array(steps_acc.clone()),
542 sources: serde_json::Value::Array(sink.sources.clone()),
543 resolved: serde_json::Value::Array(sink.resolved.clone()),
544 tool_exchange: serde_json::Value::Array(exchange_acc.clone()),
545 },
546 ).await;
547 yield done_event();
548 }
549 Err(e) => yield error_event(&e.to_string()),
550 }
551 return;
552 }
553
554 // 主链路全程流式:正文增量即时转发,工具调用在流末归并到达
555 let deltas = match client.chat_tools_stream(&msgs, &tools).await {
556 Ok(s) => s,
557 Err(e) => {
558 if rounds == 0 {
559 // 模型可能不支持 tool-calling:降级为一次性 RAG 注入
560 tracing::warn!(error = %e, "tool-calling 不可用,降级为一次性 RAG");
561 let chunks =
562 retrieval::hybrid(&state, kb_id, workspace_id, &query, 8)
563 .await
564 .unwrap_or_default();
565 let legacy_sources: Vec<serde_json::Value> = chunks
566 .iter()
567 .enumerate()
568 .map(|(i, c)| source_json(i + 1, c))
569 .collect();
570 yield Frame::new(
571 "sources",
572 serde_json::to_string(&legacy_sources).unwrap_or_else(|_| "[]".into()),
573 );
574 let mut lmsgs =
575 vec![json!({ "role": "system", "content": legacy_system_prompt(&chunks) })];
576 for (role, content) in &history.turns {
577 lmsgs.push(json!({ "role": role, "content": content }));
578 }
579 match client.chat_stream_raw(&lmsgs).await {
580 Ok(deltas) => {
581 let mut deltas = std::pin::pin!(deltas);
582 while let Some(item) = deltas.next().await {
583 match item {
584 Ok(text) => { answer_acc.push_str(&text); yield delta_event(&text); }
585 Err(e2) => { yield error_event(&e2.to_string()); return; }
586 }
587 }
588 let _ = utopia_store::conversations::append_message(
589 &state.pool, conversation_id, "assistant", &answer_acc,
590 &utopia_store::conversations::TurnRecord {
591 steps: serde_json::Value::Array(steps_acc.clone()),
592 sources: serde_json::Value::Array(legacy_sources.clone()),
593 resolved: serde_json::Value::Array(sink.resolved.clone()),
594 tool_exchange: serde_json::Value::Array(exchange_acc.clone()),
595 },
596 ).await;
597 yield done_event();
598 }
599 Err(e2) => yield error_event(&e2.to_string()),
600 }
601 return;
602 }
603 yield error_event(&e.to_string());
604 return;
605 }
606 };
607 let mut turn: Option<utopia_llm::AssistantTurn> = None;
608 {
609 let mut deltas = std::pin::pin!(deltas);
610 while let Some(item) = deltas.next().await {
611 match item {
612 Ok(utopia_llm::ToolStreamItem::Delta(text)) => {
613 answer_acc.push_str(&text);
614 yield delta_event(&text);
615 }
616 Ok(utopia_llm::ToolStreamItem::Turn(t)) => turn = Some(t),
617 Err(e) => {
618 yield error_event(&e.to_string());
619 return;
620 }
621 }
622 }
623 }
624 let Some(turn) = turn else {
625 yield error_event("LLM stream ended unexpectedly");
626 return;
627 };
628
629 if turn.tool_calls.is_empty() {
630 if answer_acc.is_empty() {
631 yield error_event("Model returned an empty answer");
632 } else {
633 let _ = utopia_store::conversations::append_message(
634 &state.pool, conversation_id, "assistant", &answer_acc,
635 &utopia_store::conversations::TurnRecord {
636 steps: serde_json::Value::Array(steps_acc.clone()),
637 sources: serde_json::Value::Array(sink.sources.clone()),
638 resolved: serde_json::Value::Array(sink.resolved.clone()),
639 tool_exchange: serde_json::Value::Array(exchange_acc.clone()),
640 },
641 ).await;
642 yield done_event();
643 }
644 return;
645 }
646
647 // 工具轮带了叙述文本:与后续轮次的正文之间补一个段落分隔
648 if turn.content.is_some() && !answer_acc.is_empty() {
649 answer_acc.push_str("\n\n");
650 yield delta_event("\n\n");
651 }
652
653 let call_msg = turn.to_message();
654 exchange_acc.push(call_msg.clone());
655 msgs.push(call_msg);
656 for call in &turn.tool_calls {
657 // **说不清自己要做什么的调用不执行。** 把话回给模型,让它重来
658 let args = match check_call(&tools, &call.name, &call.arguments) {
659 Ok(args) => args,
660 Err((message, step)) => {
661 steps_acc.push(step.clone());
662 yield Frame::new("step", serde_json::to_string(&step).unwrap_or_default());
663 msgs.push(tool_result_message(&call.id, &message));
664 continue;
665 }
666 };
667 let ctx = tools::ToolCtx {
668 state: &state,
669 kb_id,
670 workspace_id,
671 mounted_sources: &mounted_sources,
672 can_write,
673 };
674 let (result, step) = tools::dispatch(&ctx, &mut sink, &call.name, &args).await;
675 // **这一步发生在正文的哪个位置。**
676 //
677 // 模型是边说边调的:说一句、查一下、再说一句。SSE 上 `delta` 与
678 // `step` 本来就是交替发出去的,顺序不用额外记;而**历史回放没有
679 // 那条时间线**——落库的只有拼好的整段正文和一个扁平的 steps 数组,
680 // 于是重新打开一场对话,所有调用都堆在正文最前面,读起来像是
681 // 先查了七次再一口气说完。记下偏移,回放才能把话再断开。
682 //
683 // 单位是 **UTF-16 码元**,因为切分发生在浏览器里,而 JS 的
684 // `String.prototype.length` 数的就是它。用字节数或 `chars()`
685 // 在中文和 emoji 上都会切歪
686 let mut step = step;
687 if let Some(obj) = step.as_object_mut() {
688 obj.insert("at".into(), json!(answer_acc.encode_utf16().count()));
689 }
690 steps_acc.push(step.clone());
691 yield Frame::new("step", serde_json::to_string(&step).unwrap_or_default());
692 if step["kind"] == "search" || step["kind"] == "docs" {
693 yield Frame::new(
694 "sources",
695 serde_json::to_string(&sink.sources).unwrap_or_else(|_| "[]".into()),
696 );
697 }
698 let result_msg = tool_result_message(&call.id, &result);
699 exchange_acc.push(result_msg.clone());
700 msgs.push(result_msg);
701 }
702 rounds += 1;
703 }
704 };
705
706 // 生成登记在案,然后**这条连接也只是去「接上」它**——与刷新之后
707 // 那条重连走的是同一段代码。两条路分开写的话,迟早只有一条是对的
708 let handle = live.begin(conversation_id).await;
709 let attached = live.attach(conversation_id).await;
710 tokio::spawn(async move {
711 let mut producer = std::pin::pin!(producer);
712 while let Some(frame) = producer.next().await {
713 // 没有订阅者是常态(人走了)。**照发不误**:这里中断就等于
714 // 把「切走一次丢一个回答」原样搬回来
715 handle.emit(frame).await;
716 }
717 // 注销之后再接上的人得到「没有在跑的」,那时答案已经落库
718 handle.finish().await;
719 });
720
721 Ok(sse_from(attached))
722}
723
724/// 把一次「接上」变成 SSE:先补一份快照,再照常收增量。
725///
726/// `None` = 这个会话没有在跑的生成。回一条 `idle` 而不是 404——**客户端
727/// 每次打开会话都会问一次**,而「没有在跑」是最常见的答案,不是错误
728fn sse_from(
729 attached: Option<(
730 crate::live::Snapshot,
731 tokio::sync::broadcast::Receiver<Frame>,
732 )>,
733) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
734 let stream = async_stream::stream! {
735 let Some((snapshot, mut rx)) = attached else {
736 yield to_event(&Frame::new("idle", "{}".into()));
737 return;
738 };
739 yield to_event(&snapshot.to_frame());
740 loop {
741 match rx.recv().await {
742 Ok(frame) => {
743 let done = frame.event == "done" || frame.event == "error";
744 yield to_event(&frame);
745 if done { return; }
746 }
747 // 生成结束、发送端销毁:正常收尾
748 Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
749 // 这个客户端读得太慢,被广播缓冲甩下了。**说出来**——
750 // 静默继续会让它少掉中间一段而毫不知情
751 Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
752 yield to_event(&Frame::new(
753 "error",
754 format!("Fell behind the stream by {n} messages; reopen the conversation"),
755 ));
756 return;
757 }
758 }
759 }
760 };
761 Sse::new(stream).keep_alive(KeepAlive::default())
762}
763
764fn to_event(frame: &Frame) -> Result<Event, Infallible> {
765 Ok(Event::default().event(frame.event).data(&frame.data))
766}
767
768/// 接上一次正在跑的生成(刷新页面之后走这里)。
769pub async fn reattach(
770 State(state): State<AppState>,
771 AuthUser(user): AuthUser,
772 Path((kb_id, conversation_id)): Path<(Uuid, Uuid)>,
773) -> ApiResult<Sse<impl Stream<Item = Result<Event, Infallible>>>> {
774 utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
775 // **归属要查。** 会话 id 是可以猜的,而这条流会把别人的回答一字不差地念出来
776 utopia_store::conversations::require_owned(&state.pool, kb_id, user.id, conversation_id)
777 .await?;
778 Ok(sse_from(state.live.attach(conversation_id).await))
779}
780
781/// 生成器产出的是 `Frame`,不是 `axum` 的 `Event`。
782/// **广播与快照都要读回事件的内容**,而 `Event` 读不回来(见 `live`)
783fn delta_event(text: &str) -> Frame {
784 Frame::new(
785 "delta",
786 serde_json::to_string(&json!({ "text": text })).unwrap_or_default(),
787 )
788}
789
790fn done_event() -> Frame {
791 Frame::new("done", "{}".into())
792}
793
794fn error_event(message: &str) -> Frame {
795 Frame::new("error", message.into())
796}
797
798fn source_json(n: usize, c: &ChunkView) -> serde_json::Value {
799 json!({
800 "n": n,
801 "chunk_id": c.id,
802 "document_id": c.document_id,
803 "filename": c.filename,
804 "excerpt": truncate(&c.text, 160),
805 })
806}
807
808/// 降级路径的系统提示(tool-calling 不可用时的一次性注入)。
809fn legacy_system_prompt(chunks: &[ChunkView]) -> String {
810 if chunks.is_empty() {
811 return "You are an enterprise knowledge base assistant. No relevant sources were \
812 retrieved for this question. Tell the user the knowledge base lacks material \
813 on this topic, answer cautiously from general knowledge, and clearly separate \
814 sourced statements from speculation. Always respond in the same language as \
815 the user's question."
816 .to_string();
817 }
818 let mut prompt = String::from(
819 "You are an enterprise knowledge base assistant. Answer strictly based on the \
820 numbered sources below. When a source supports a statement, append its citation \
821 number, e.g. [1] or [2], at the end of the sentence. If the sources are \
822 insufficient, say so explicitly — never fabricate. Always respond in the same \
823 language as the user's question.\n\n### Sources\n",
824 );
825 for (i, c) in chunks.iter().enumerate() {
826 prompt.push_str(&format!(
827 "\n[{}] \"{}\" section {}:\n{}\n",
828 i + 1,
829 c.filename,
830 c.seq + 1,
831 c.text
832 ));
833 }
834 prompt
835}
836
837fn truncate(text: &str, max_chars: usize) -> String {
838 let t = text.trim();
839 if t.chars().count() <= max_chars {
840 t.to_string()
841 } else {
842 let cut: String = t.chars().take(max_chars).collect();
843 format!("{cut}…")
844 }
845}
846
847// ---------------------------------------------------------------------------
848// 会话管理(列表 / 回放 / 删除)
849// ---------------------------------------------------------------------------
850
851#[derive(serde::Deserialize)]
852pub struct ConversationsQuery {
853 /// 搜标题与消息正文两处:人记得住的往往是问过的那句话,不是标题
854 #[serde(default)]
855 pub q: Option<String>,
856 #[serde(default)]
857 pub limit: Option<i64>,
858 #[serde(default)]
859 pub offset: Option<i64>,
860}
861
862pub async fn list_conversations(
863 State(state): State<AppState>,
864 AuthUser(user): AuthUser,
865 Path(kb_id): Path<Uuid>,
866 Query(q): Query<ConversationsQuery>,
867) -> ApiResult<Json<serde_json::Value>> {
868 utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
869 let (conversations, total) = utopia_store::conversations::list(
870 &state.pool,
871 kb_id,
872 user.id,
873 q.q.as_deref().map(str::trim).filter(|s| !s.is_empty()),
874 q.limit.unwrap_or(30).clamp(1, 100),
875 q.offset.unwrap_or(0).max(0),
876 )
877 .await?;
878 Ok(Json(
879 json!({ "conversations": conversations, "total": total }),
880 ))
881}
882
883#[derive(serde::Deserialize)]
884pub struct RenameConversationReq {
885 pub title: String,
886}
887
888/// 改会话标题。
889///
890/// **标题本来是从第一句话自动取的**,而一段对话跑偏是常态——改名让人能按
891/// 自己记得的方式找回它。
892pub async fn rename_conversation(
893 State(state): State<AppState>,
894 AuthUser(user): AuthUser,
895 Path((kb_id, conversation_id)): Path<(Uuid, Uuid)>,
896 Json(req): Json<RenameConversationReq>,
897) -> ApiResult<Json<serde_json::Value>> {
898 utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
899 utopia_store::conversations::rename(&state.pool, kb_id, user.id, conversation_id, &req.title)
900 .await?;
901 Ok(Json(json!({ "ok": true })))
902}
903
904/// 历史回放:消息含落库的行动轨迹(steps)与引用(sources)。
905pub async fn conversation_detail(
906 State(state): State<AppState>,
907 AuthUser(user): AuthUser,
908 Path((kb_id, conversation_id)): Path<(Uuid, Uuid)>,
909) -> ApiResult<Json<serde_json::Value>> {
910 utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
911 utopia_store::conversations::require_owned(&state.pool, kb_id, user.id, conversation_id)
912 .await?;
913 let messages = utopia_store::conversations::messages(&state.pool, conversation_id).await?;
914 Ok(Json(json!({ "messages": messages })))
915}
916
917pub async fn delete_conversation(
918 State(state): State<AppState>,
919 AuthUser(user): AuthUser,
920 Path((kb_id, conversation_id)): Path<(Uuid, Uuid)>,
921) -> ApiResult<Json<serde_json::Value>> {
922 utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
923 utopia_store::conversations::delete(&state.pool, kb_id, user.id, conversation_id).await?;
924 Ok(Json(json!({ "ok": true })))
925}
926
927#[cfg(test)]
928mod tests {
929 use super::*;
930
931 // --- check_call ---------------------------------------------------------
932
933 /// 参数在半路断掉——模型撞上 token 上限时就长这样。
934 ///
935 /// **从前这里回落成空对象,然后 `search_chunks` 拿用户那句原话去检索。**
936 /// 得到的是一条看起来完全正常的 `search · 6 sources`,和一个基于错误输入
937 /// 的答案。没人会去核一个看起来正常的答案,所以这一条必须是拒绝
938 #[test]
939 fn arguments_cut_off_mid_json_do_not_become_a_search() {
940 let tools = tools_schema(false, &[]);
941 let err = check_call(&tools, "search_chunks", "{\"query\": \"Acme reven")
942 .expect_err("残缺 JSON 必须拒绝,而不是回落");
943 assert_eq!(err.1["kind"], "tool", "轨迹上要显示成一次没做成的调用");
944 assert_eq!(err.1["detail"], "bad arguments");
945 assert!(
946 err.0.contains("not valid JSON") && err.0.contains("again"),
947 "回给模型的话要说清没执行、并让它重来:{}",
948 err.0
949 );
950 }
951
952 /// 空串与缺字段是同一件事:`{"query": ""}` 检索回来的东西与问题无关,
953 /// 而它同样会显示成一条正常轨迹
954 #[test]
955 fn an_empty_required_argument_counts_as_missing() {
956 let tools = tools_schema(false, &[]);
957 for raw in [
958 "{}",
959 "{\"query\": \"\"}",
960 "{\"query\": \" \"}",
961 "{\"query\": null}",
962 ] {
963 let Err(err) = check_call(&tools, "search_chunks", raw) else {
964 panic!("{raw} 应当被拒");
965 };
966 assert_eq!(err.1["detail"], "missing query", "{raw}");
967 }
968 }
969
970 /// **判据取自工具表本身。** 这条守的是「加了必填参数却忘了改校验」——
971 /// query_data 只在挂了数据源时才出现在表里,它的两个必填参数
972 /// 从没在别处被单独写过一遍
973 #[test]
974 fn the_schema_is_the_only_place_required_is_written_down() {
975 let tools = tools_schema(false, &["warehouse".into()]);
976 let err = check_call(&tools, "query_data", "{\"data_source\": \"warehouse\"}")
977 .expect_err("缺 sql 必须拒绝");
978 assert_eq!(err.1["detail"], "missing sql");
979 check_call(
980 &tools,
981 "query_data",
982 "{\"data_source\": \"warehouse\", \"sql\": \"SELECT 1\"}",
983 )
984 .expect("两个都给了就该放行");
985 }
986
987 /// 合规的调用原样通过,**可选参数一个不少**。
988 ///
989 /// 这一关只判「说清了没有」,不做过滤——把 args 重新组装一遍的话,
990 /// 加一个可选参数就得记得来这里加一次,而忘记的后果是它安静地失效
991 #[test]
992 fn a_well_formed_call_passes_through_untouched() {
993 let tools = tools_schema(false, &[]);
994 let args = check_call(
995 &tools,
996 "entity_facts",
997 "{\"entity_id\": \"1f8ac10b-58cc-4372-a567-0e02b2c3d479\", \"at\": \"2026-03-15\"}",
998 )
999 .expect("必填给了就该放行");
1000 assert_eq!(args["at"], "2026-03-15", "可选参数不能在这一关被吃掉");
1001 }
1002
1003 /// `changes` 早就在自己那一支里拒绝缺失的 `since`——**它是唯一做对的一个**。
1004 /// 这条钉住两件事:新的统一关卡与它一致,而它自己那道对日期格式的检查
1005 /// (`2026-13-45` 这种)仍然要留着,因为 check_call 只看有没有、不看对不对
1006 #[test]
1007 fn the_one_tool_that_already_refused_still_refuses() {
1008 let tools = tools_schema(false, &[]);
1009 assert!(check_call(&tools, "changes", "{}").is_err());
1010 check_call(&tools, "changes", "{\"since\": \"2026-13-45\"}")
1011 .expect("格式错的日期不归这一关管,交给 changes_window");
1012 }
1013}