Elffuss BraidHub

kikocis/utopia public

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