Elffuss BraidHub

kikocis/utopia public

de93f0eb4620 · 48.6 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///
34/// 它今天会把一句话直接变成图上一条活边,而中间那一步没人看得见:实测里
35/// 「记住 Acme 把总部搬到了深圳」落成的是一条 **空谓词、0.9 置信** 的边——
36/// 本体里没有「搬迁到」这类关系,抽取落不上就留空(按 0010 这是对的),
37/// 于是助手宣称的和图里得到的不是一回事。
38///
39/// 0018 建好了 `pending_facts`:抽出来的先等人点头。**抽取侧接上那张表
40/// 之后,把这里改回 true。** 在那之前宁可没有这个工具,也不要一个会
41/// 悄悄改图的工具。
42pub(super) const REMEMBER_ENABLED: bool = false;
43
44#[derive(Deserialize)]
45pub struct ChatReq {
46 /// 缺省 = 新建会话(SSE 首个 `conversation` 事件回传 id)
47 #[serde(default)]
48 pub conversation_id: Option<Uuid>,
49 pub message: String,
50}
51
52fn tools_schema(can_write: bool, data_source_names: &[String]) -> serde_json::Value {
53 let mut tools = base_tools();
54 if !data_source_names.is_empty() {
55 if let Some(arr) = tools.as_array_mut() {
56 arr.push(json!({
57 "type": "function",
58 "function": {
59 "name": "query_data",
60 "description": format!(
61 "Run a read-only SQL query against a mounted database. Available sources: \
62 {}. Search the source's schema document first (search_chunks) if unsure \
63 of tables/columns. Only a single SELECT/WITH statement is allowed; a \
64 LIMIT is enforced server-side; results come back as JSON lines. If the \
65 query errors, fix the SQL and retry once.",
66 data_source_names.join(", ")
67 ),
68 "parameters": {
69 "type": "object",
70 "properties": {
71 "data_source": {
72 "type": "string",
73 "description": "Name of the mounted data source to query."
74 },
75 "sql": {
76 "type": "string",
77 "description": "One SELECT/WITH statement (PostgreSQL dialect)."
78 },
79 "purpose": {
80 "type": "string",
81 "description": "One short phrase: what this query answers (shown to the user)."
82 }
83 },
84 "required": ["data_source", "sql"]
85 }
86 }
87 }));
88 }
89 }
90 if can_write && REMEMBER_ENABLED {
91 if let Some(arr) = tools.as_array_mut() {
92 arr.push(json!({
93 "type": "function",
94 "function": {
95 "name": "remember",
96 "description": "Record one memory episode into the knowledge base's temporal \
97 memory. Use ONLY when the user explicitly asks to remember/record \
98 something, or clearly states a decision or fact to keep. The episode is \
99 extracted into the knowledge graph; if it contradicts an existing \
100 single-valued fact, the old fact's validity is closed automatically \
101 (never deleted). Do not use for casual conversation.",
102 "parameters": {
103 "type": "object",
104 "properties": {
105 "text": {
106 "type": "string",
107 "description": "The episode to remember, one self-contained \
108 statement (who/what, with names spelled out)."
109 },
110 "occurred_at": {
111 "type": "string",
112 "description": "Optional date the stated fact took effect \
113 (YYYY-MM-DD). Omit to use today."
114 }
115 },
116 "required": ["text"]
117 }
118 }
119 }));
120 }
121 }
122 tools
123}
124
125/// 执行之前先看这次调用说清楚了没有。
126///
127/// **两种「没说清」以前都会安静地变成一次正常调用。**
128///
129/// 一是参数解析不出来。模型的输出撞上 token 上限时,`arguments` 会在半路断掉,
130/// 那串 JSON 不完整。从前这里是 `unwrap_or_else(|_| json!({}))`——空对象,
131/// 接着 `search_chunks` 里 `args["query"].as_str().unwrap_or(&query)` 回落到
132/// **用户那句原话**,于是一次被截断的调用变成「拿用户的原问题去检索」,
133/// 而轨迹上显示的是一条完全正常的 `search · 6 sources`。
134///
135/// 二是必填参数干脆没给。同一个回落,同一个结果。
136///
137/// 两种都不该猜。**回落产出的是一个看起来没问题的错误答案**,那比报错坏得多——
138/// 报错模型会重试,猜出来的答案没有人会去核。
139///
140/// 判据直接取自工具表里的 `required`:加一个必填参数,这里自动跟上,
141/// 不必记得来改第二处。
142fn check_call(
143 tools: &serde_json::Value,
144 name: &str,
145 raw_args: &str,
146) -> Result<serde_json::Value, (String, serde_json::Value)> {
147 let refuse = |detail: &str, message: String| {
148 (
149 message,
150 json!({ "kind": "tool", "label": name, "detail": detail }),
151 )
152 };
153 let Ok(args) = serde_json::from_str::<serde_json::Value>(raw_args) else {
154 return Err(refuse(
155 "bad arguments",
156 format!(
157 "The arguments for {name} were not valid JSON, so the call was not run. \
158 They were probably cut off. Call it again with complete arguments."
159 ),
160 ));
161 };
162 let required = tools
163 .as_array()
164 .into_iter()
165 .flatten()
166 .find(|t| t["function"]["name"] == name)
167 .and_then(|t| t["function"]["parameters"]["required"].as_array());
168 for key in required.into_iter().flatten().filter_map(|k| k.as_str()) {
169 // 空串与 null 都算没给:`{"query": ""}` 检索出来的东西与问题无关,
170 // 而它同样会显示成一条正常的轨迹
171 let missing = match args.get(key) {
172 None | Some(serde_json::Value::Null) => true,
173 Some(serde_json::Value::String(s)) => s.trim().is_empty(),
174 Some(_) => false,
175 };
176 if missing {
177 return Err(refuse(
178 &format!("missing {key}"),
179 format!(
180 "{name} needs `{key}`, and it was missing or empty, so the call was not \
181 run. Call it again with `{key}` set."
182 ),
183 ));
184 }
185 }
186 Ok(args)
187}
188
189const MEMORY_PROMPT: &str = "\
190 Memory: you can persist knowledge with the remember tool. Use it when the user says \
191 \"remember/record this\" or states a decision meant to last. Confirm in your reply what \
192 was recorded. 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 (PostgreSQL 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 };
691 let (result, step) = tools::dispatch(&ctx, &mut sink, &call.name, &args).await;
692 // **这一步发生在正文的哪个位置。**
693 //
694 // 模型是边说边调的:说一句、查一下、再说一句。SSE 上 `delta` 与
695 // `step` 本来就是交替发出去的,顺序不用额外记;而**历史回放没有
696 // 那条时间线**——落库的只有拼好的整段正文和一个扁平的 steps 数组,
697 // 于是重新打开一场对话,所有调用都堆在正文最前面,读起来像是
698 // 先查了七次再一口气说完。记下偏移,回放才能把话再断开。
699 //
700 // 单位是 **UTF-16 码元**,因为切分发生在浏览器里,而 JS 的
701 // `String.prototype.length` 数的就是它。用字节数或 `chars()`
702 // 在中文和 emoji 上都会切歪
703 let mut step = step;
704 if let Some(obj) = step.as_object_mut() {
705 obj.insert("at".into(), json!(answer_acc.encode_utf16().count()));
706 }
707 steps_acc.push(step.clone());
708 yield Frame::new("step", serde_json::to_string(&step).unwrap_or_default());
709 if step["kind"] == "search" || step["kind"] == "docs" {
710 yield Frame::new(
711 "sources",
712 serde_json::to_string(&sink.sources).unwrap_or_else(|_| "[]".into()),
713 );
714 }
715 let result_msg = tool_result_message(&call.id, &result);
716 exchange_acc.push(result_msg.clone());
717 msgs.push(result_msg);
718 }
719 rounds += 1;
720 }
721 };
722
723 // 生成登记在案,然后**这条连接也只是去「接上」它**——与刷新之后
724 // 那条重连走的是同一段代码。两条路分开写的话,迟早只有一条是对的
725 let handle = live.begin(conversation_id).await;
726 let attached = live.attach(conversation_id).await;
727 tokio::spawn(async move {
728 let mut producer = std::pin::pin!(producer);
729 while let Some(frame) = producer.next().await {
730 // 没有订阅者是常态(人走了)。**照发不误**:这里中断就等于
731 // 把「切走一次丢一个回答」原样搬回来
732 handle.emit(frame).await;
733 }
734 // 注销之后再接上的人得到「没有在跑的」,那时答案已经落库
735 handle.finish().await;
736 });
737
738 Ok(sse_from(attached))
739}
740
741/// 把一次「接上」变成 SSE:先补一份快照,再照常收增量。
742///
743/// `None` = 这个会话没有在跑的生成。回一条 `idle` 而不是 404——**客户端
744/// 每次打开会话都会问一次**,而「没有在跑」是最常见的答案,不是错误
745fn sse_from(
746 attached: Option<(
747 crate::live::Snapshot,
748 tokio::sync::broadcast::Receiver<Frame>,
749 )>,
750) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
751 let stream = async_stream::stream! {
752 let Some((snapshot, mut rx)) = attached else {
753 yield to_event(&Frame::new("idle", "{}".into()));
754 return;
755 };
756 yield to_event(&snapshot.to_frame());
757 loop {
758 match rx.recv().await {
759 Ok(frame) => {
760 let done = frame.event == "done" || frame.event == "error";
761 yield to_event(&frame);
762 if done { return; }
763 }
764 // 生成结束、发送端销毁:正常收尾
765 Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
766 // 这个客户端读得太慢,被广播缓冲甩下了。**说出来**——
767 // 静默继续会让它少掉中间一段而毫不知情
768 Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
769 yield to_event(&Frame::new(
770 "error",
771 format!("Fell behind the stream by {n} messages; reopen the conversation"),
772 ));
773 return;
774 }
775 }
776 }
777 };
778 Sse::new(stream).keep_alive(KeepAlive::default())
779}
780
781fn to_event(frame: &Frame) -> Result<Event, Infallible> {
782 Ok(Event::default().event(frame.event).data(&frame.data))
783}
784
785/// 接上一次正在跑的生成(刷新页面之后走这里)。
786pub async fn reattach(
787 State(state): State<AppState>,
788 AuthUser(user): AuthUser,
789 Path((kb_id, conversation_id)): Path<(Uuid, Uuid)>,
790) -> ApiResult<Sse<impl Stream<Item = Result<Event, Infallible>>>> {
791 utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
792 // **归属要查。** 会话 id 是可以猜的,而这条流会把别人的回答一字不差地念出来
793 utopia_store::conversations::require_owned(&state.pool, kb_id, user.id, conversation_id)
794 .await?;
795 Ok(sse_from(state.live.attach(conversation_id).await))
796}
797
798/// 生成器产出的是 `Frame`,不是 `axum` 的 `Event`。
799/// **广播与快照都要读回事件的内容**,而 `Event` 读不回来(见 `live`)
800fn delta_event(text: &str) -> Frame {
801 Frame::new(
802 "delta",
803 serde_json::to_string(&json!({ "text": text })).unwrap_or_default(),
804 )
805}
806
807fn done_event() -> Frame {
808 Frame::new("done", "{}".into())
809}
810
811fn error_event(message: &str) -> Frame {
812 Frame::new("error", message.into())
813}
814
815fn source_json(n: usize, c: &ChunkView) -> serde_json::Value {
816 json!({
817 "n": n,
818 "chunk_id": c.id,
819 "document_id": c.document_id,
820 "filename": c.filename,
821 "excerpt": truncate(&c.text, 160),
822 })
823}
824
825/// 降级路径的系统提示(tool-calling 不可用时的一次性注入)。
826fn legacy_system_prompt(chunks: &[ChunkView]) -> String {
827 if chunks.is_empty() {
828 return "You are an enterprise knowledge base assistant. No relevant sources were \
829 retrieved for this question. Tell the user the knowledge base lacks material \
830 on this topic, answer cautiously from general knowledge, and clearly separate \
831 sourced statements from speculation. Always respond in the same language as \
832 the user's question."
833 .to_string();
834 }
835 let mut prompt = String::from(
836 "You are an enterprise knowledge base assistant. Answer strictly based on the \
837 numbered sources below. When a source supports a statement, append its citation \
838 number, e.g. [1] or [2], at the end of the sentence. If the sources are \
839 insufficient, say so explicitly — never fabricate. Always respond in the same \
840 language as the user's question.\n\n### Sources\n",
841 );
842 for (i, c) in chunks.iter().enumerate() {
843 prompt.push_str(&format!(
844 "\n[{}] \"{}\" section {}:\n{}\n",
845 i + 1,
846 c.filename,
847 c.seq + 1,
848 c.text
849 ));
850 }
851 prompt
852}
853
854fn truncate(text: &str, max_chars: usize) -> String {
855 let t = text.trim();
856 if t.chars().count() <= max_chars {
857 t.to_string()
858 } else {
859 let cut: String = t.chars().take(max_chars).collect();
860 format!("{cut}…")
861 }
862}
863
864// ---------------------------------------------------------------------------
865// 会话管理(列表 / 回放 / 删除)
866// ---------------------------------------------------------------------------
867
868#[derive(serde::Deserialize)]
869pub struct ConversationsQuery {
870 /// 搜标题与消息正文两处:人记得住的往往是问过的那句话,不是标题
871 #[serde(default)]
872 pub q: Option<String>,
873 #[serde(default)]
874 pub limit: Option<i64>,
875 #[serde(default)]
876 pub offset: Option<i64>,
877}
878
879pub async fn list_conversations(
880 State(state): State<AppState>,
881 AuthUser(user): AuthUser,
882 Path(kb_id): Path<Uuid>,
883 Query(q): Query<ConversationsQuery>,
884) -> ApiResult<Json<serde_json::Value>> {
885 utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
886 let (conversations, total) = utopia_store::conversations::list(
887 &state.pool,
888 kb_id,
889 user.id,
890 q.q.as_deref().map(str::trim).filter(|s| !s.is_empty()),
891 q.limit.unwrap_or(30).clamp(1, 100),
892 q.offset.unwrap_or(0).max(0),
893 )
894 .await?;
895 Ok(Json(
896 json!({ "conversations": conversations, "total": total }),
897 ))
898}
899
900#[derive(serde::Deserialize)]
901pub struct RenameConversationReq {
902 pub title: String,
903}
904
905/// 改会话标题。
906///
907/// **标题本来是从第一句话自动取的**,而一段对话跑偏是常态——改名让人能按
908/// 自己记得的方式找回它。
909pub async fn rename_conversation(
910 State(state): State<AppState>,
911 AuthUser(user): AuthUser,
912 Path((kb_id, conversation_id)): Path<(Uuid, Uuid)>,
913 Json(req): Json<RenameConversationReq>,
914) -> ApiResult<Json<serde_json::Value>> {
915 utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
916 utopia_store::conversations::rename(&state.pool, kb_id, user.id, conversation_id, &req.title)
917 .await?;
918 Ok(Json(json!({ "ok": true })))
919}
920
921/// 历史回放:消息含落库的行动轨迹(steps)与引用(sources)。
922pub async fn conversation_detail(
923 State(state): State<AppState>,
924 AuthUser(user): AuthUser,
925 Path((kb_id, conversation_id)): Path<(Uuid, Uuid)>,
926) -> ApiResult<Json<serde_json::Value>> {
927 utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
928 utopia_store::conversations::require_owned(&state.pool, kb_id, user.id, conversation_id)
929 .await?;
930 let messages = utopia_store::conversations::messages(&state.pool, conversation_id).await?;
931 Ok(Json(json!({ "messages": messages })))
932}
933
934pub async fn delete_conversation(
935 State(state): State<AppState>,
936 AuthUser(user): AuthUser,
937 Path((kb_id, conversation_id)): Path<(Uuid, Uuid)>,
938) -> ApiResult<Json<serde_json::Value>> {
939 utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
940 utopia_store::conversations::delete(&state.pool, kb_id, user.id, conversation_id).await?;
941 Ok(Json(json!({ "ok": true })))
942}
943
944#[cfg(test)]
945mod tests {
946 use super::*;
947
948 // --- check_call ---------------------------------------------------------
949
950 /// 参数在半路断掉——模型撞上 token 上限时就长这样。
951 ///
952 /// **从前这里回落成空对象,然后 `search_chunks` 拿用户那句原话去检索。**
953 /// 得到的是一条看起来完全正常的 `search · 6 sources`,和一个基于错误输入
954 /// 的答案。没人会去核一个看起来正常的答案,所以这一条必须是拒绝
955 #[test]
956 fn arguments_cut_off_mid_json_do_not_become_a_search() {
957 let tools = tools_schema(false, &[]);
958 let err = check_call(&tools, "search_chunks", "{\"query\": \"Acme reven")
959 .expect_err("残缺 JSON 必须拒绝,而不是回落");
960 assert_eq!(err.1["kind"], "tool", "轨迹上要显示成一次没做成的调用");
961 assert_eq!(err.1["detail"], "bad arguments");
962 assert!(
963 err.0.contains("not valid JSON") && err.0.contains("again"),
964 "回给模型的话要说清没执行、并让它重来:{}",
965 err.0
966 );
967 }
968
969 /// 空串与缺字段是同一件事:`{"query": ""}` 检索回来的东西与问题无关,
970 /// 而它同样会显示成一条正常轨迹
971 #[test]
972 fn an_empty_required_argument_counts_as_missing() {
973 let tools = tools_schema(false, &[]);
974 for raw in [
975 "{}",
976 "{\"query\": \"\"}",
977 "{\"query\": \" \"}",
978 "{\"query\": null}",
979 ] {
980 let Err(err) = check_call(&tools, "search_chunks", raw) else {
981 panic!("{raw} 应当被拒");
982 };
983 assert_eq!(err.1["detail"], "missing query", "{raw}");
984 }
985 }
986
987 /// **判据取自工具表本身。** 这条守的是「加了必填参数却忘了改校验」——
988 /// query_data 只在挂了数据源时才出现在表里,它的两个必填参数
989 /// 从没在别处被单独写过一遍
990 #[test]
991 fn the_schema_is_the_only_place_required_is_written_down() {
992 let tools = tools_schema(false, &["warehouse".into()]);
993 let err = check_call(&tools, "query_data", "{\"data_source\": \"warehouse\"}")
994 .expect_err("缺 sql 必须拒绝");
995 assert_eq!(err.1["detail"], "missing sql");
996 check_call(
997 &tools,
998 "query_data",
999 "{\"data_source\": \"warehouse\", \"sql\": \"SELECT 1\"}",
1000 )
1001 .expect("两个都给了就该放行");
1002 }
1003
1004 /// 合规的调用原样通过,**可选参数一个不少**。
1005 ///
1006 /// 这一关只判「说清了没有」,不做过滤——把 args 重新组装一遍的话,
1007 /// 加一个可选参数就得记得来这里加一次,而忘记的后果是它安静地失效
1008 #[test]
1009 fn a_well_formed_call_passes_through_untouched() {
1010 let tools = tools_schema(false, &[]);
1011 let args = check_call(
1012 &tools,
1013 "entity_facts",
1014 "{\"entity_id\": \"1f8ac10b-58cc-4372-a567-0e02b2c3d479\", \"at\": \"2026-03-15\"}",
1015 )
1016 .expect("必填给了就该放行");
1017 assert_eq!(args["at"], "2026-03-15", "可选参数不能在这一关被吃掉");
1018 }
1019
1020 /// `changes` 早就在自己那一支里拒绝缺失的 `since`——**它是唯一做对的一个**。
1021 /// 这条钉住两件事:新的统一关卡与它一致,而它自己那道对日期格式的检查
1022 /// (`2026-13-45` 这种)仍然要留着,因为 check_call 只看有没有、不看对不对
1023 #[test]
1024 fn the_one_tool_that_already_refused_still_refuses() {
1025 let tools = tools_schema(false, &[]);
1026 assert!(check_call(&tools, "changes", "{}").is_err());
1027 check_call(&tools, "changes", "{\"since\": \"2026-13-45\"}")
1028 .expect("格式错的日期不归这一关管,交给 changes_window");
1029 }
1030}