Elffuss BraidHub

kikocis/utopia public

dev · 38.5 KiBRawPermalink
1//! utopia-extract: LLM 抽取(实体/关系/时间归一化)。
2//! 提示词注入本体类型与文档元时间;输出严格 JSON;证据引句强制(无引句降置信度)。
3
4use chrono::{DateTime, NaiveDate, TimeZone, Utc};
5use serde::Deserialize;
6use utopia_llm::ChatMessage;
7
8#[derive(Debug, Deserialize)]
9pub struct Extraction {
10 #[serde(default)]
11 pub entities: Vec<ExtractedEntity>,
12 #[serde(default)]
13 pub facts: Vec<ExtractedFact>,
14 /// 逐项解析时被跳过的条目数。**必须报给调用方**——不报就是一次静默丢弃,
15 /// 与 #108「部分抽取报告成完成」同一类错
16 #[serde(skip)]
17 pub skipped_entities: usize,
18 #[serde(skip)]
19 pub skipped_facts: usize,
20 /// 模型的输出被截断,这里是修补后解析的
21 #[serde(skip)]
22 pub truncated: bool,
23}
24
25#[derive(Debug, Deserialize)]
26pub struct ExtractedEntity {
27 pub name: String,
28 #[serde(rename = "type")]
29 pub type_key: String,
30 /// 模型自己的说法:它认为这最具体是个什么。**不校验、不入本体**。
31 ///
32 /// 存在的理由是清单里总有个"差不多"的:本体有 product,模型觉得够用就选了,
33 /// 心里那个"向量数据库软件"就此丢失。实测 17 个实体的 proposed_type
34 /// 全是空的,正是这个原因——而事后消解最需要的恰是这个名字:
35 /// 短名字对短标签,比拿一段中文散文去匹配 "A software application." 近得多。
36 #[serde(default)]
37 pub specific_type: Option<String>,
38}
39
40#[derive(Debug, Deserialize)]
41pub struct ExtractedFact {
42 pub subject: String,
43 pub predicate: String,
44 /// 关系事实的宾语实体名;属性事实为空
45 #[serde(default)]
46 pub object: Option<String>,
47 /// 属性事实的字面值(谓词是 attribute 时)
48 #[serde(default)]
49 pub value: Option<serde_json::Value>,
50 #[serde(default)]
51 pub valid_from: Option<String>,
52 #[serde(default)]
53 pub valid_to: Option<String>,
54 #[serde(default)]
55 pub confidence: Option<f32>,
56 #[serde(default)]
57 pub quote: Option<String>,
58}
59
60/// 提示词里的一条关系。
61///
62/// 比类多一样东西:**类型签名**。它是给模型的签名,不是闸门——在模型落笔那一刻
63/// 减少"Alice works_at 西雅图",而不是等错了再拦。事后校验面对的是既成事实
64///(丢掉可惜、留着是脏数据),签名是在写出来之前掰正。本体写错时模型看到原文
65/// 说了别的仍可覆盖;硬闸门会系统性丢数据,`part_of` 烧我们的正是那种方式。
66pub struct PromptRelation {
67 pub key: String,
68 pub label: String,
69 pub description: String,
70 /// 形如 `person|organization → vendor`,`*` 表示那一侧不限。空串 = 两侧都不限。
71 /// **一律用 key**:模型要输出的就是 key,中文库里 person 的 label 是"人物",
72 /// 写进签名等于教它输出一个不存在的类型(docs/decisions/0004)
73 pub signature: String,
74}
75
76/// 构造抽取提示词。`types` 为 (key, label, description) 三元组;
77/// description 非空时按行列出——本体里的语义指引直接决定抽取质量。
78/// `attributes` 为调用方预排版的属性行("person.salary (number, CNY): 月薪");
79/// 为空时提示词一字不变——没定义属性的库零成本。
80pub fn build_messages(
81 types: &[(String, String, String)],
82 relations: &[PromptRelation],
83 attributes: &[String],
84 doc_time: Option<&str>,
85 filename: &str,
86 // 本文档前面几块已经认下的 (类型 key, 实体名),按首次出现排序。
87 // 第一块为空——那时还没有"前面"
88 known: &[(String, String)],
89 chunk_text: &str,
90) -> Vec<ChatMessage> {
91 // **有描述时不送 label**。label 是给人看的显示名,而且它跟界面无关、
92 // 跟这个库的语料语言走——中文库里 person 的 label 是"人物"。
93 // `- person (人物): 有名有姓的具体的人…` 里那个"人物"相对 key 近乎零信息量,
94 // 却让提示词在语料语言与标识符之间来回跳。描述为空时才拿它兜底:
95 // 光一个 key 太单薄。见 docs/decisions/0004
96 let fmt_list = |items: &[(String, String, String)]| {
97 items
98 .iter()
99 .map(|(k, l, d)| {
100 let d = d.trim();
101 if d.is_empty() {
102 format!("- {k} ({l})")
103 } else {
104 format!("- {k}: {d}")
105 }
106 })
107 .collect::<Vec<_>>()
108 .join("\n")
109 };
110 let type_list = fmt_list(types);
111 // 关系行:有签名时括号里放签名,没有才退回 label。
112 // `- works_at (person → organization): 一个人受雇于某个组织。`
113 let rel_list = relations
114 .iter()
115 .map(|r| {
116 let d = r.description.trim();
117 let paren = if !r.signature.is_empty() {
118 r.signature.clone()
119 } else if d.is_empty() {
120 r.label.clone()
121 } else {
122 String::new()
123 };
124 match (paren.is_empty(), d.is_empty()) {
125 (false, false) => format!("- {} ({paren}): {d}", r.key),
126 (false, true) => format!("- {} ({paren})", r.key),
127 (true, false) => format!("- {}: {d}", r.key),
128 (true, true) => format!("- {}", r.key),
129 }
130 })
131 .collect::<Vec<_>>()
132 .join("\n");
133 // 记号只在真有签名时解释一次;没有签名的库,提示词一字不变。
134 // 说明用英文——提示词的**指令语言**是英文,只有 description 跟语料走
135 //
136 // **签名管两件事,而它们的可覆盖性不同。** 第一版把两件事混成了一句
137 // "It is a hint, not a rule — when the text says otherwise, write what the
138 // text says",于是模型连参数顺序也一并按原文的说法写:
139 //
140 // Elon Musk (person) --employee--> Microsoft
141 //
142 // 而 schema.org 声明的是 employee (organization → person)。实测一次跑里
143 // 130 条可校验的事实有 102 条这样反着落库——**恰恰是本体包最主要的卖点失效**,
144 // 选 schema.org 的理由就是「方向是声明的不是描述的」。
145 //
146 // 两件事分开说:
147 //
148 // - **哪些类型能参与**:提示不是闸门。本体可能写错,原文说西雅图就写西雅图。
149 // 0001 的判断在这里不变——硬闸门会系统性丢数据,part_of 烧我们的正是那样。
150 // - **参数顺序**:由签名定。顺序不是关于世界的断言,是这个 key 的编码约定;
151 // 原文从来没有「说了别的方向」,它只说两个实体之间存在某种关系。
152 // 反着说时该交换主宾,而不是反过来用这个关系。
153 let sig_note = if relations.iter().any(|r| !r.signature.is_empty()) {
154 ". A parenthesis after the key is the type signature, subject then object; \
155 \"|\" means or, \"*\" means unconstrained. Which kinds of things may take part \
156 is a hint, not a rule — when the text says otherwise, write what the text says. \
157 The order is not a hint: the signature fixes which side is the subject. If the \
158 text puts them the other way round, swap subject and object so that the subject \
159 matches the left side — do not reverse the relation. For example, given \
160 \"employee (organization → person)\" and a text saying \"X is an employee of Y\", \
161 write Y as the subject and X as the object"
162 } else {
163 ""
164 };
165 let time_ctx = doc_time
166 .map(|t| {
167 format!(
168 "Document date: {t}. Resolve relative time expressions (e.g. \"last year\", \
169 \"this March\") to absolute dates using it as the reference."
170 )
171 })
172 .unwrap_or_else(|| {
173 "Document date unknown — only output dates explicitly written in the text.".into()
174 });
175
176 // 属性段按需注入:清单 + 输出说明 + 取值规则。没定义属性时完全不出现
177 let attr_section = if attributes.is_empty() {
178 String::new()
179 } else {
180 format!(
181 "\nAttributes (literal-valued fields, listed as class.attribute_key; as \"predicate\" \
182 use the attribute_key alone — e.g. \"salary\", not \"person.salary\" — with a \
183 \"value\" instead of \"object\"):\n{}\n",
184 attributes.join("\n")
185 )
186 };
187 let attr_rules = if attributes.is_empty() {
188 String::new()
189 } else {
190 "\n10. Attribute facts carry \"value\" (no \"object\"): number = plain number without \
191 thousands separators or unit symbols; date = \"YYYY[-MM[-DD]]\"; bool = true/false; \
192 text = a short string. Only attach an attribute to a subject of its listed class. \
193 valid_from = when this value took effect, if the text says so."
194 .to_string()
195 };
196 let system = format!(
197 "You are a knowledge-graph extraction engine. Extract entities and factual relations \
198 from the given text. Output exactly one JSON object and nothing else.\n\
199 \n\
200 Entity types (prefer these keys):\n{type_list}\n\
201 \n\
202 Relation types (prefer these keys){sig_note}:\n{rel_list}\n\
203 {attr_section}\
204 \n\
205 Output format:\n\
206 {{\"entities\":[{{\"name\":\"entity name\",\"type\":\"type key\",\"specific_type\":\"what you would call it\"}}],\n\
207 \"facts\":[{{\"subject\":\"subject entity name\",\"predicate\":\"relation key\",\"object\":\"object entity name\",\n\
208 \"valid_from\":\"2023-01\",\"valid_to\":null,\"confidence\":0.9,\"quote\":\"verbatim supporting quote\"}}]}}\n\
209 \n\
210 Rules:\n\
211 1. Use the canonical full name as written in the text, in the text's original language; \
212 list each entity once. Text introduces a full name and then shortens it — \
213 \"星云科技上海研究院\" becomes \"上海研究院\", \"Nebula Technologies Inc.\" becomes \
214 \"Nebula\" — and both forms mean one entity, listed once under the fuller form. \
215 Two names are two entities only when the text is talking about two things.\n\
216 2. Every fact's subject/object must appear in entities.\n\
217 3. Dates must be \"YYYY\", \"YYYY-MM\", \"YYYY-MM-DD\", or null — never invent dates.\n\
218 3a. valid_to takes a third value: \"unknown\". Use it when the text says the relation \
219 has ended but does not say when — \"former CEO of X\", \"stepped down\", \"left the \
220 company\", \"no longer available\", \"until recently\". Use null only for something \
221 still going on. These are not interchangeable: null asserts it still holds, and \
222 writing null for a relation the text says is over makes us claim the opposite of \
223 the source.\n\
224 4. {time_ctx}\n\
225 5. quote must be a contiguous excerpt from the source text; every fact needs one.\n\
226 6. confidence in 0~1: 0.9 explicitly stated, 0.7 inferred, 0.5 uncertain.\n\
227 7. If nothing can be extracted, output {{\"entities\":[],\"facts\":[]}}.\n\
228 8. If no listed relation fits, do not force the nearest one — write the predicate the \
229 text itself uses, in snake_case (e.g. \"available_on\", \"runs_on\"). A relation \
230 named after the text is worth more than a listed one that says something false.\n\
231 9. The same holds for entity types: if none of the listed types fits, write the type \
232 the text implies, in snake_case (e.g. \"model\", \"technology\"). Do not fall back \
233 to a broad listed type such as \"thing\" or \"creative_work\" merely because \
234 nothing specific matched — that hides the gap instead of reporting it.\n\
235 10. specific_type is required on every entity and is never checked against the list. \
236 Name the most specific kind the thing is, in the words you would use for it. Write \
237 it even when \"type\" already fits, and make it narrower than \"type\" wherever the \
238 text supports it — type \"product\", specific_type \"vector database software\". \
239 Repeat the listed type only when the text genuinely says nothing more precise.\
240 {attr_rules}"
241 );
242
243 // 已知实体紧挨着正文:服从性靠位置,理由见 known_block 的注释
244 let user = format!(
245 "Source file: \"{filename}\"\n{}\nText:\n{chunk_text}",
246 known_block(known)
247 );
248
249 vec![
250 ChatMessage {
251 role: "system".into(),
252 content: system,
253 },
254 ChatMessage {
255 role: "user".into(),
256 content: user,
257 },
258 ]
259}
260
261/// 已在本文档中出现过的实体,放进提示词的字符预算。
262///
263/// 超出就截断(保留先出现的)。中文商业文本先出全称、主角先出场,所以
264/// **首次出现顺序天然偏向那些后面会被简称的名字**。
265const KNOWN_BUDGET_CHARS: usize = 1200;
266
267/// 把「本文档已经认下的实体」排版成提示词里的一段。空则返回空串。
268///
269/// **为什么在正文之前、指令贴着清单**:抽象规则打不过挨着它的具体块——本体建议
270/// 那次,语言要求就输给了紧随其后的英文 JSON 骨架,挪到骨架之后并点名它才生效。
271/// 服从性靠位置,所以指令挨着它管的数据放,两者一起挨着正文。
272///
273/// **顺带一条与放哪条消息无关的规矩:逐块变化的内容一律放最后。** 前缀缓存匹配的是
274/// token 前缀,而消息按 system→user 拼接,所以「system 末尾」与「user 开头」几乎等价;
275/// 真正会打碎缓存的是把它塞在**中间**(本体之后、规则之前),那会把规则挤出前缀。
276/// 缓存本身不归我们管——供应商开不开、报不报都由它,本部署实测 `cached=0`——
277/// 我们只负责别把它弄碎。自部署 vLLM 默认开着自动前缀缓存,那省的是算力不是钱。
278fn known_block(known: &[(String, String)]) -> String {
279 if known.is_empty() {
280 return String::new();
281 }
282 // 按类型分组:更紧凑,而且顺带压住跨块类型漂移
283 //(同一个"沧海"在一块里是 product、另一块里是 project)
284 let mut by_type: Vec<(&str, Vec<&str>)> = Vec::new();
285 let mut used = 0usize;
286 for (type_key, name) in known {
287 used += name.chars().count() + 2;
288 if used > KNOWN_BUDGET_CHARS {
289 break;
290 }
291 match by_type.iter_mut().find(|(k, _)| *k == type_key.as_str()) {
292 Some((_, names)) => names.push(name),
293 None => by_type.push((type_key, vec![name])),
294 }
295 }
296 if by_type.is_empty() {
297 return String::new();
298 }
299 let lines = by_type
300 .iter()
301 .map(|(k, names)| format!(" {k}: {}", names.join(", ")))
302 .collect::<Vec<_>>()
303 .join("\n");
304 format!(
305 "\nAlready recorded from earlier parts of this same document:\n{lines}\n\
306 \n\
307 If something in the text below refers to one of these, write that exact string as \
308 the name, and give it that same type — documents abbreviate after first mention \
309 (\"星云科技上海研究院\" later becomes \"上海研究院\"), and the shortened form must \
310 not become a second entity. If it is a different thing, name it as the text does; \
311 do not force it onto this list.\n"
312 )
313}
314
315/// 从 LLM 回复中稳健地取出 JSON 块(容忍代码围栏与前后废话)。
316pub fn json_block(raw: &str) -> anyhow::Result<String> {
317 let text = raw.trim();
318 let cleaned = text
319 .strip_prefix("```json")
320 .or_else(|| text.strip_prefix("```"))
321 .map(|s| s.trim_end_matches("```"))
322 .unwrap_or(text);
323 let start = cleaned.find('{');
324 let end = cleaned.rfind('}');
325 match (start, end) {
326 (Some(s), Some(e)) if e > s => Ok(cleaned[s..=e].to_string()),
327 _ => anyhow::bail!("No JSON found in LLM reply"),
328 }
329}
330
331/// 把 head 后面缺的括号补上。字符串字面量里的括号不算——`"a[b"` 不是一个开括号。
332///
333/// 返回 None = 结构本身就不对(比如括号已经多了),不是"没写完"。
334fn close_brackets(head: &str) -> Option<String> {
335 let mut stack: Vec<char> = Vec::new();
336 let (mut in_str, mut esc) = (false, false);
337 for c in head.chars() {
338 if in_str {
339 if esc {
340 esc = false;
341 } else if c == '\\' {
342 esc = true;
343 } else if c == '"' {
344 in_str = false;
345 }
346 continue;
347 }
348 match c {
349 '"' => in_str = true,
350 '[' | '{' => stack.push(c),
351 // 不写成两条带守卫的分支:那样 stack.pop() 的副作用藏在守卫里,
352 // 碰巧是对的,但读的人不会预期守卫会改状态
353 ']' | '}' => {
354 let want = if c == ']' { '[' } else { '{' };
355 if stack.pop() != Some(want) {
356 return None;
357 }
358 }
359 _ => {}
360 }
361 }
362 if in_str {
363 return None; // 断在字符串中间,这一截不可用
364 }
365 let mut out = String::from(head);
366 for c in stack.iter().rev() {
367 out.push(if *c == '[' { ']' } else { '}' });
368 }
369 Some(out)
370}
371
372/// 输出被截断时,退到**最后一个完整对象**的结尾再把括号补齐。
373///
374/// 模型写到一半没了(撞上 max_tokens)时,前面那些对象是完整且正确的。
375/// 整块作废等于把已经抽对的十几条事实一起扔掉——实测 246 次调用里 4 次是这种。
376fn repair_truncated(json: &str) -> Option<String> {
377 let mut cut = json.len();
378 for _ in 0..64 {
379 let idx = json[..cut].rfind('}')?;
380 if let Some(closed) = close_brackets(&json[..=idx]) {
381 if serde_json::from_str::<serde_json::Value>(&closed).is_ok() {
382 return Some(closed);
383 }
384 }
385 cut = idx;
386 }
387 None
388}
389
390/// **一条坏记录不该毁掉一整块。**
391///
392/// 从前这里是 `serde_json::from_str::<Extraction>`——全有或全无。一个缺 `predicate`
393/// 的对象、或者一次输出截断,整块的实体和事实一起作废,而一块里常有二十条好事实。
394/// 实测 246 次调用里 5 次这样丢掉(2%),并且会让整个 `extract_document` 任务失败、
395/// 走重试,三次之后文档标记失败。
396///
397/// 现在:先解成 `Value`(截断就先补齐括号),再逐项 `from_value`,好的收下、
398/// 坏的计数。**计数必须往外传**——静默跳过就是另一种"报告成完成"。
399pub fn parse_response(raw: &str) -> anyhow::Result<Extraction> {
400 let json_str = json_block(raw)?;
401 let (value, truncated) = match serde_json::from_str::<serde_json::Value>(&json_str) {
402 Ok(v) => (v, false),
403 Err(e) => match repair_truncated(&json_str) {
404 Some(fixed) => (
405 serde_json::from_str::<serde_json::Value>(&fixed)
406 .map_err(|e| anyhow::anyhow!("Failed to parse extraction JSON: {e}"))?,
407 true,
408 ),
409 // 补不回来才是真解析失败:连一个完整对象都没有
410 None => anyhow::bail!("Failed to parse extraction JSON: {e}"),
411 },
412 };
413
414 fn take<T: serde::de::DeserializeOwned>(
415 value: &serde_json::Value,
416 key: &str,
417 ) -> (Vec<T>, usize) {
418 let Some(arr) = value.get(key).and_then(|v| v.as_array()) else {
419 return (Vec::new(), 0);
420 };
421 let mut out = Vec::with_capacity(arr.len());
422 let mut skipped = 0;
423 for item in arr {
424 match serde_json::from_value::<T>(item.clone()) {
425 Ok(v) => out.push(v),
426 Err(_) => skipped += 1,
427 }
428 }
429 (out, skipped)
430 }
431
432 let (entities, skipped_entities) = take::<ExtractedEntity>(&value, "entities");
433 let (facts, skipped_facts) = take::<ExtractedFact>(&value, "facts");
434 Ok(Extraction {
435 entities,
436 facts,
437 skipped_entities,
438 skipped_facts,
439 truncated,
440 })
441}
442
443// ---------------------------------------------------------------------------
444// 实体消解裁决(攒批:一次调用裁多对,LLM 只处理 embedding 分不出的灰区)
445// ---------------------------------------------------------------------------
446
447/// 待裁决的一侧:名字 + 类型 + 事实摘要行。
448pub struct AdjudicationSide {
449 pub name: String,
450 pub type_label: String,
451 pub facts: Vec<String>,
452}
453
454pub struct AdjudicationPair {
455 pub left: AdjudicationSide,
456 pub right: AdjudicationSide,
457}
458
459#[derive(Debug, Deserialize)]
460pub struct AdjudicationVerdict {
461 pub i: usize,
462 pub verdict: String,
463 #[serde(default)]
464 pub confidence: Option<f32>,
465}
466
467#[derive(Debug, Deserialize)]
468struct AdjudicationReply {
469 #[serde(default)]
470 verdicts: Vec<AdjudicationVerdict>,
471}
472
473/// 构造攒批裁决提示词。保守偏置:证据不足答 unsure(宁分勿合,合并要证据)。
474pub fn build_adjudication_messages(pairs: &[AdjudicationPair]) -> Vec<ChatMessage> {
475 let system = "You are an entity-resolution adjudicator for a knowledge graph. \
476 For each numbered pair, decide whether the two records refer to the SAME real-world \
477 entity or are namesakes (different entities that share a name).\n\
478 \n\
479 Judge by the facts attached to each record: employer/affiliation, role, time ranges, \
480 and connected entities. Identical names alone are NEVER sufficient evidence of sameness. \
481 Contradictory affiliations in overlapping time periods indicate different entities \
482 (but people do change jobs — non-overlapping periods can belong to one person).\n\
483 \n\
484 One name containing the other is a different case, and the rule above does not apply \
485 to it: \"星云科技上海研究院\" against \"上海研究院\", \"Nebula Technologies Inc.\" \
486 against \"Nebula\". Documents drop the qualifier after first mention, so the shorter \
487 form is usually the longer one abbreviated — treat the containment as evidence FOR \
488 sameness and let the facts settle it. Shared people, parent or location confirm one \
489 entity; a different parent or conflicting leadership means the shorter name belongs \
490 to something else.\n\
491 Abbreviation removes a qualifier from the FRONT. It never adds a noun or a \
492 prepositional phrase at the end, so those are different entities however much text \
493 they share: \"the operator library for the Canghai Platform\" is not the Canghai \
494 Platform, \"Qiming X7 programme\" is not the Qiming X7, and \"沧海平台项目\" is not \
495 \"沧海平台\" — a project, a programme, a team or a component is its own record.\n\
496 \n\
497 Output exactly one JSON object and nothing else:\n\
498 {\"verdicts\":[{\"i\":0,\"verdict\":\"same|different|unsure\",\"confidence\":0.9}]}\n\
499 \n\
500 Rules:\n\
501 1. One verdict per pair, using the pair's number as \"i\".\n\
502 2. confidence in 0~1.\n\
503 3. Be conservative: if the evidence is insufficient to decide, answer \"unsure\" — \
504 a wrong merge is far more damaging than leaving two records separate."
505 .to_string();
506
507 let mut user = String::new();
508 for (i, p) in pairs.iter().enumerate() {
509 let fmt = |s: &AdjudicationSide| {
510 let facts = if s.facts.is_empty() {
511 " (no recorded facts)".to_string()
512 } else {
513 s.facts
514 .iter()
515 .map(|f| format!(" - {f}"))
516 .collect::<Vec<_>>()
517 .join("\n")
518 };
519 format!("\"{}\" ({})\n{}", s.name, s.type_label, facts)
520 };
521 user.push_str(&format!(
522 "Pair {i}:\nRecord A: {}\nRecord B: {}\n\n",
523 fmt(&p.left),
524 fmt(&p.right)
525 ));
526 }
527
528 vec![
529 ChatMessage {
530 role: "system".into(),
531 content: system,
532 },
533 ChatMessage {
534 role: "user".into(),
535 content: user,
536 },
537 ]
538}
539
540pub fn parse_adjudication(raw: &str) -> anyhow::Result<Vec<AdjudicationVerdict>> {
541 let json_str = json_block(raw)?;
542 let reply: AdjudicationReply = serde_json::from_str(&json_str)
543 .map_err(|e| anyhow::anyhow!("Failed to parse adjudication JSON: {e}"))?;
544 Ok(reply.verdicts)
545}
546
547/// 属性值按 datatype 归一。失败返回 None——宁缺勿脏,调用方跳过并记日志。
548/// number 容忍千分位/空格;date 要求 YYYY[-MM[-DD]] 且保留原精度;bool 宽容 yes/no。
549pub fn normalize_attr_value(datatype: &str, raw: &serde_json::Value) -> Option<serde_json::Value> {
550 match datatype {
551 "number" => match raw {
552 serde_json::Value::Number(n) => Some(serde_json::Value::Number(n.clone())),
553 serde_json::Value::String(s) => {
554 let cleaned: String = s
555 .chars()
556 .filter(|c| !matches!(c, ',' | ' ' | '_'))
557 .collect();
558 cleaned
559 .parse::<f64>()
560 .ok()
561 .filter(|f| f.is_finite())
562 .and_then(serde_json::Number::from_f64)
563 .map(serde_json::Value::Number)
564 }
565 _ => None,
566 },
567 "date" => {
568 let s = raw.as_str()?.trim();
569 parse_time(s).map(|_| serde_json::Value::String(s.to_string()))
570 }
571 "bool" => match raw {
572 serde_json::Value::Bool(b) => Some(serde_json::Value::Bool(*b)),
573 serde_json::Value::String(s) => match s.trim().to_ascii_lowercase().as_str() {
574 "true" | "yes" | "是" => Some(serde_json::Value::Bool(true)),
575 "false" | "no" | "否" => Some(serde_json::Value::Bool(false)),
576 _ => None,
577 },
578 _ => None,
579 },
580 _ => {
581 let s = match raw {
582 serde_json::Value::String(s) => s.trim().to_string(),
583 serde_json::Value::Number(n) => n.to_string(),
584 _ => return None,
585 };
586 (!s.is_empty()).then(|| serde_json::Value::String(s.chars().take(500).collect()))
587 }
588 }
589}
590
591/// 解析时间字符串 → (UTC 时间, 精度)。支持 YYYY / YYYY-MM / YYYY-MM-DD。
592pub fn parse_time(s: &str) -> Option<(DateTime<Utc>, &'static str)> {
593 let s = s.trim();
594 if s.is_empty() || s.eq_ignore_ascii_case("null") {
595 return None;
596 }
597 if let Ok(d) = NaiveDate::parse_from_str(s, "%Y-%m-%d") {
598 return Some((Utc.from_utc_datetime(&d.and_hms_opt(0, 0, 0)?), "day"));
599 }
600 if let Ok(d) = NaiveDate::parse_from_str(&format!("{s}-01"), "%Y-%m-%d") {
601 return Some((Utc.from_utc_datetime(&d.and_hms_opt(0, 0, 0)?), "month"));
602 }
603 if s.len() == 4 {
604 if let Ok(year) = s.parse::<i32>() {
605 let d = NaiveDate::from_ymd_opt(year, 1, 1)?;
606 return Some((Utc.from_utc_datetime(&d.and_hms_opt(0, 0, 0)?), "year"));
607 }
608 }
609 None
610}
611
612#[cfg(test)]
613mod prompt_shape_tests {
614 use super::*;
615
616 fn rel(key: &str, description: &str, signature: &str) -> PromptRelation {
617 PromptRelation {
618 key: key.into(),
619 label: key.replace('_', " "),
620 description: description.into(),
621 signature: signature.into(),
622 }
623 }
624
625 /// 签名进括号,而且**一律是 key**:中文库的 label 是"人物",
626 /// 写进提示词等于教模型输出一个不存在的类型。
627 #[test]
628 fn a_signature_takes_the_parenthesis_and_uses_keys() {
629 let rels = vec![rel("works_at", "受雇于某个组织。", "person → organization")];
630 let msgs = build_messages(&[], &rels, &[], None, "a.txt", &[], "text");
631 assert!(msgs[0]
632 .content
633 .contains("- works_at (person → organization): 受雇于某个组织。"));
634 }
635
636 /// 多值用 `|`,空的一侧用 `*` —— 都是 key 层面的记号,不是类型名
637 #[test]
638 fn several_classes_join_with_a_pipe_and_an_empty_side_is_a_star() {
639 let rels = vec![rel("buys_from", "", "employee|team → *")];
640 let msgs = build_messages(&[], &rels, &[], None, "a.txt", &[], "text");
641 assert!(msgs[0].content.contains("- buys_from (employee|team → *)"));
642 }
643
644 /// **没有签名的库,提示词一字不变**:记号说明也不出现。
645 /// 大多数库不会声明 domain/range,不该为此付每块的 token
646 #[test]
647 fn a_base_without_signatures_pays_nothing() {
648 let rels = vec![rel("works_at", "受雇于某个组织。", "")];
649 let msgs = build_messages(&[], &rels, &[], None, "a.txt", &[], "text");
650 assert!(msgs[0].content.contains("- works_at: 受雇于某个组织。"));
651 assert!(!msgs[0].content.contains("type signature"));
652 assert!(!msgs[0].content.contains('→'));
653 }
654
655 /// 签名是提示不是闸门。这句话必须在提示词里 —— 少了它,
656 /// 模型会把签名当硬规则,本体写错时就系统性丢数据(part_of 那种方式)
657 #[test]
658 fn the_prompt_says_the_signature_is_a_hint() {
659 let rels = vec![rel("works_at", "d", "person → organization")];
660 let msgs = build_messages(&[], &rels, &[], None, "a.txt", &[], "text");
661 assert!(msgs[0].content.contains("hint, not a rule"));
662 }
663
664 /// **但顺序不是提示。**
665 ///
666 /// 两句话必须同时在场,少哪一句都退回一种老毛病:少了「提示不是闸门」,
667 /// 本体写错时系统性丢数据(part_of 那种方式);少了「顺序由签名定」,
668 /// 模型按英语直觉写 `Musk --employee--> Microsoft`,而 schema.org 声明的是
669 /// `employee (organization → person)`——实测一次跑里 130 条可校验的事实
670 /// 有 102 条这样反着落库。
671 #[test]
672 fn the_prompt_says_the_order_is_not_a_hint() {
673 let rels = vec![rel("employee", "d", "organization → person")];
674 let msgs = build_messages(&[], &rels, &[], None, "a.txt", &[], "text");
675 let c = &msgs[0].content;
676 assert!(c.contains("hint, not a rule"), "类型那句丢了");
677 assert!(c.contains("The order is not a hint"), "顺序那句丢了");
678 assert!(
679 c.contains("swap subject and object"),
680 "只说了顺序重要,没说反着写时该怎么办"
681 );
682 assert!(
683 c.contains("do not reverse the relation"),
684 "少了这句,模型可能去找一个反向关系而不是交换主宾"
685 );
686 }
687
688 /// 已知实体必须落在 **user** 消息里、紧挨着正文。
689 ///
690 /// 理由是服从性不是缓存:抽象规则打不过挨着它的具体块。清单放进 system 的
691 /// 规则区,就会隔着输出格式、十条规则、文件名,离它要管的正文最远。
692 #[test]
693 fn known_entities_stay_out_of_the_system_message() {
694 // 用一个规则 1 的例子里没有的名字:规则 1 也提"星云科技上海研究院",
695 // 拿它断言等于测不出清单到底在哪条消息里
696 let known = vec![(
697 "organization".to_string(),
698 "华瑞集团智能制造研究院".to_string(),
699 )];
700 let msgs = build_messages(&[], &[], &[], None, "a.txt", &known, "text");
701 assert_eq!(msgs[0].role, "system");
702 assert!(!msgs[0].content.contains("Already recorded"));
703 assert!(!msgs[0].content.contains("华瑞集团智能制造研究院"));
704 assert!(msgs[1]
705 .content
706 .contains("organization: 华瑞集团智能制造研究院"));
707 }
708
709 /// 第一块没有"前面",那一段应当完全不出现——成本为零,而不是一段空标题
710 #[test]
711 fn the_first_chunk_carries_no_block() {
712 let msgs = build_messages(&[], &[], &[], None, "a.txt", &[], "text");
713 assert!(!msgs[1].content.contains("Already recorded"));
714 }
715
716 /// 反向护栏必须在:给了参照物就会有人硬套(`concept` 那次的教训)
717 #[test]
718 fn the_block_tells_the_model_not_to_force_a_match() {
719 let known = vec![("person".to_string(), "陈立".to_string())];
720 let msgs = build_messages(&[], &[], &[], None, "a.txt", &known, "text");
721 assert!(msgs[1].content.contains("do not force it onto this list"));
722 }
723
724 /// 有描述就不送 label——中文库的 label 是中文,混进提示词只会让
725 /// 标识符与语料语言来回跳,而它相对 key 近乎零信息量。
726 #[test]
727 fn described_types_drop_the_label() {
728 let types = vec![
729 (
730 "person".into(),
731 "人物".into(),
732 "有名有姓的具体的人。".into(),
733 ),
734 ("event".into(), "事件".into(), String::new()),
735 ];
736 let msgs = build_messages(&types, &[], &[], None, "a.txt", &[], "text");
737 let prompt = format!("{:?}", msgs);
738 assert!(prompt.contains("- person: 有名有姓的具体的人。"));
739 assert!(!prompt.contains("person (人物)"));
740 // 描述为空时 label 仍是唯一的额外线索,留着
741 assert!(prompt.contains("- event (事件)"));
742 }
743}
744
745#[cfg(test)]
746mod tests {
747 use super::*;
748
749 #[test]
750 fn parse_time_precisions() {
751 assert_eq!(parse_time("2024").unwrap().1, "year");
752 assert_eq!(parse_time("2024-07").unwrap().1, "month");
753 assert_eq!(parse_time("2024-07-15").unwrap().1, "day");
754 assert!(parse_time("null").is_none());
755 assert!(parse_time("").is_none());
756 assert!(parse_time("下个月").is_none());
757 }
758
759 #[test]
760 fn parse_adjudication_reply() {
761 let raw = "```json\n{\"verdicts\":[{\"i\":0,\"verdict\":\"same\",\"confidence\":0.92},{\"i\":1,\"verdict\":\"unsure\"}]}\n```";
762 let v = parse_adjudication(raw).unwrap();
763 assert_eq!(v.len(), 2);
764 assert_eq!(v[0].verdict, "same");
765 assert_eq!(v[1].confidence, None);
766 }
767
768 #[test]
769 fn normalize_attr_values() {
770 use serde_json::json;
771 assert_eq!(
772 normalize_attr_value("number", &json!("35,000")),
773 Some(json!(35000.0))
774 );
775 assert_eq!(normalize_attr_value("number", &json!(42)), Some(json!(42)));
776 assert_eq!(normalize_attr_value("number", &json!("about ten")), None);
777 assert_eq!(
778 normalize_attr_value("date", &json!("2024-07")),
779 Some(json!("2024-07"))
780 );
781 assert_eq!(normalize_attr_value("date", &json!("下个月")), None);
782 assert_eq!(
783 normalize_attr_value("bool", &json!("yes")),
784 Some(json!(true))
785 );
786 assert_eq!(
787 normalize_attr_value("text", &json!(" CTO ")),
788 Some(json!("CTO"))
789 );
790 assert_eq!(normalize_attr_value("text", &json!([1])), None);
791 }
792
793 /// **一条坏记录不该毁掉一整块。**
794 ///
795 /// 形态取自真实日志:`missing field \`predicate\``。模型偶尔会漏写这个字段
796 /// (`related_to` 退场后它没有万能选项可挑),从前 serde 会让整块作废,
797 /// 而这一块里另外两条事实是好的。
798 #[test]
799 fn one_malformed_fact_does_not_take_the_whole_chunk() {
800 let raw = r#"{
801 "entities": [{"name": "OpenAI", "type": "organization"}],
802 "facts": [
803 {"subject": "OpenAI", "predicate": "produces", "object": "GPT-4"},
804 {"subject": "OpenAI", "object": "ChatGPT"},
805 {"subject": "Sam Altman", "predicate": "leads", "object": "OpenAI"}
806 ]
807 }"#;
808 let x = parse_response(raw).unwrap();
809 assert_eq!(x.facts.len(), 2, "好的两条该留下");
810 assert_eq!(x.skipped_facts, 1, "跳过的那条要报出来,不能静默");
811 assert_eq!(x.entities.len(), 1);
812 assert!(!x.truncated);
813 }
814
815 /// **输出被截断时,已经完整的那些要救回来。**
816 ///
817 /// 撞上 max_tokens 时模型写到一半就没了(真实日志:`EOF while parsing a list`)。
818 /// 前面的对象是完整且正确的,整块作废等于把抽对的十几条一起扔掉。
819 #[test]
820 fn a_cut_off_reply_keeps_what_was_complete() {
821 let raw = r#"{
822 "entities": [{"name": "Anthropic", "type": "organization"}],
823 "facts": [
824 {"subject": "Anthropic", "predicate": "produces", "object": "Claude"},
825 {"subject": "Dario Amodei", "predicate": "leads", "object": "Anthropic"},
826 {"subject": "Anthropic", "predicate": "loca"#;
827 let x = parse_response(raw).unwrap();
828 assert!(x.truncated, "截断要标出来");
829 assert_eq!(x.facts.len(), 2, "断点之前的两条是完整的");
830 assert_eq!(x.entities.len(), 1);
831 }
832
833 /// 括号出现在字符串里不算结构——`"a[b"` 不是一个开括号。
834 #[test]
835 fn brackets_inside_strings_are_not_structure() {
836 let raw =
837 r#"{"entities": [], "facts": [{"subject": "a[b{c", "predicate": "p", "object": "o"}]}"#;
838 let x = parse_response(raw).unwrap();
839 assert_eq!(x.facts.len(), 1);
840 assert!(!x.truncated, "结构完整,不该判成截断");
841 }
842
843 /// 连一个完整对象都没有时,仍然要报失败——**容错不是把空结果说成成功**。
844 #[test]
845 fn a_reply_with_nothing_complete_still_fails() {
846 assert!(parse_response(r#"{"facts": [{"subject": "a"#).is_err());
847 }
848
849 #[test]
850 fn parse_response_with_fence() {
851 let raw = "好的,结果如下:\n```json\n{\"entities\":[{\"name\":\"张三\",\"type\":\"person\"}],\"facts\":[]}\n```";
852 let e = parse_response(raw).unwrap();
853 assert_eq!(e.entities.len(), 1);
854 assert_eq!(e.entities[0].type_key, "person");
855 }
856
857 /// specific_type 在骨架里、也在规则里,且两处都说"永远要填"。
858 ///
859 /// 只写进骨架是不够的:**规则与骨架冲突时骨架赢**(语言那条就栽过一次)。
860 /// 这里两边一致,所以要一起钉住。
861 #[test]
862 fn every_entity_is_asked_for_its_own_words() {
863 let msgs = build_messages(&[], &[], &[], None, "a.txt", &[], "text");
864 let sys = &msgs[0].content;
865 assert!(sys.contains("\"specific_type\":\"what you would call it\""));
866 assert!(sys.contains("required on every entity"));
867 // 关键的一句:不校验。校验它就等于又造了一个词表
868 assert!(sys.contains("never checked against the list"));
869 // 与 type 的关系必须说清楚,否则模型会把粗类抄一遍
870 assert!(sys.contains("narrower than"));
871 }
872}