ingest.py
46.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
import asyncio
import ast
import os
import json
import re
import frontmatter
import yaml
from datetime import datetime
from decimal import Decimal
import logging
logger = logging.getLogger(__name__)
from sqlalchemy import select, delete
from fastapi import APIRouter, HTTPException, BackgroundTasks, Body
from src.database.session import AsyncSessionLocal
from src.database.models import WikiFile, WikiFilePage, WikiOperationLog
from config import RAW_DIR, SKILLS_DIR, WIKI_DIR, BASE_DIR, INGEST_MODEL_NAME
from src.utils.llm_tracker import current_task_tokens, print_thinking, get_llm_model, load_skill_prompt
from src.tools.document_parser import extract_text_from_file
from src.tools.wiki_tools import (
execute_terminal_command,
read_local_file,
write_wiki_file,
append_wiki_file,
rebuild_index,
normalize_br_tags,
)
from agentscope.agent import ReActAgent
from agentscope.message import Msg
from agentscope.formatter import DashScopeChatFormatter
from agentscope.tool import Toolkit
router = APIRouter()
@router.post("/wiki/batch_ingest")
async def batch_ingest(
data: dict = Body(...), background_tasks: BackgroundTasks = None
):
"""批量开始摄入任务,接受 ids 列表。
依赖 global_ingest_lock 保证同一时间只有一个文件在摄入(串行执行)。
"""
ids = data.get("ids", [])
if not ids:
raise HTTPException(status_code=400, detail="ids 不能为空")
logger.info(f"请求批量摄入文件: ids={ids}")
count = 0
to_process = []
async with AsyncSessionLocal() as session:
for fid in ids:
result = await session.execute(select(WikiFile).where(WikiFile.id == fid))
db_file = result.scalar_one_or_none()
if db_file and db_file.status not in ("Ingesting", "Uploading"):
db_file.status = "Ingesting"
to_process.append(db_file.id)
count += 1
await session.commit()
# 问题11:每个文件独立加入 background_tasks,各自竞争 global_ingest_lock,保证串行
for fid in to_process:
background_tasks.add_task(run_ingest_agent, fid)
return {"status": "batch ingest started", "count": count}
@router.delete("/wiki/egress/{file_id}")
async def egress_wiki(file_id: str):
"""摄出:仅抹掉该文件自身在 wiki 中的全部足迹——它生成的页面、各页中本源的
SOURCE 块、以及本源在 frontmatter(含 5 结构化字段)的所有贡献;其他来源贡献的
内容与字段完整保留。状态回 Pending、保留原文以便重摄;彻底删原文+DB 走 delete_file。
跨文件断链(其他页指向被删 slug)由 lint 统一修复,不在此处全库扫描。
"""
logger.info(f"请求摄出(Egress)知识库文件: file_id={file_id}")
# 与摄入串行,消除竞态窗口
async with global_ingest_lock:
async with AsyncSessionLocal() as session:
result = await session.execute(select(WikiFile).where(WikiFile.id == file_id))
db_file = result.scalar_one_or_none()
if not db_file:
raise HTTPException(status_code=404, detail="File not found")
if db_file.status in ("Ingesting", "Uploading"):
raise HTTPException(status_code=409, detail="文件正在摄入/上传中,无法摄出")
name = db_file.name
result_pages = await session.execute(select(WikiFilePage).where(WikiFilePage.file_id == file_id))
pages = result_pages.scalars().all()
generated_pages = [p.page_path for p in pages]
source_ref = f"ware/raw/{name}"
count = 0
deleted_files = []
touched_dirs = set()
targets = [os.path.abspath(os.path.join(BASE_DIR, p)) for p in generated_pages] if generated_pages else []
block_pattern = re.compile(
rf"<!-- SOURCE_START: {re.escape(source_ref)} -->.*?<!-- SOURCE_END: {re.escape(source_ref)} -->",
re.DOTALL,
)
for file_path in targets:
if not os.path.exists(file_path):
continue
try:
post = frontmatter.load(file_path)
sources = _as_value_list(post.metadata.get("sources"))
if source_ref not in sources:
# 本源未贡献该页(理论上不该发生),跳过以免误伤
continue
remaining_sources = [s for s in sources if s != source_ref]
post.metadata["sources"] = remaining_sources
# 统一回收:移除本源在所有受追踪字段的贡献,按剩余来源重算/删除字段
_recompute_after_source_removal(post.metadata, source_ref)
# 正文:删除本源 SOURCE 块 + 兜底清理
updated_content = block_pattern.sub("", post.content)
updated_content = re.sub(
rf"^>\s*原始依据:\[\[{re.escape(source_ref)}\]\].*$",
"", updated_content, flags=re.MULTILINE,
)
updated_content = re.sub(r"\n{3,}", "\n\n", updated_content)
updated_content = re.sub(r"(?m)^---\s*\n(?=---|\s*$)", "", updated_content)
updated_content = updated_content.strip()
if not remaining_sources or not updated_content:
os.remove(file_path)
deleted_files.append(file_path)
touched_dirs.add(os.path.dirname(file_path))
count += 1
else:
post.content = updated_content
save_post_with_formatting(post, file_path)
count += 1
except Exception as e:
logger.error(f"[Egress] 处理文件 {file_path} 时发生错误: {e}", exc_info=True)
# 空目录清理(如 sources/极狐/ 删空后移除)
for d in touched_dirs:
try:
if (os.path.isdir(d) and not os.listdir(d)
and os.path.abspath(d) != os.path.abspath(WIKI_DIR)):
os.rmdir(d)
except OSError:
pass
# index.md 确定性全量重建(删页的索引行自动消失)
rebuild_index(WIKI_DIR)
async with AsyncSessionLocal() as session:
result = await session.execute(select(WikiFile).where(WikiFile.id == file_id))
db_f = result.scalar_one_or_none()
if db_f:
db_f.status = "Pending"
await session.execute(delete(WikiFilePage).where(WikiFilePage.file_id == file_id))
log = WikiOperationLog(
file_id=file_id,
file_name=name,
operation="EGRESS",
details=json.dumps({
"cleaned_pages_count": count,
"deleted_pages_count": len(deleted_files)
}, ensure_ascii=False)
)
session.add(log)
await session.commit()
if count > 0 or deleted_files:
date_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log_entry = f"- [{date_str}] 摄出 [[ware/raw/{name}]],清理了 {count} 个相关页面的内容,移除了 {len(deleted_files)} 个空页面。\n"
log_path = os.path.join(WIKI_DIR, "log.md")
with open(log_path, "a", encoding="utf-8") as f:
f.write(log_entry)
logger.info(f"[Egress] 摄出完成: {name},清理 {count} 个页面,删除 {len(deleted_files)} 个空页面")
return {"status": "success", "deleted": count}
return {"status": "success", "deleted": 0, "message": "已重置为待处理,但未发现相关生成的 Wiki 页面"}
@router.post("/wiki/ingest/{file_id}")
async def ingest_file(file_id: str, background_tasks: BackgroundTasks):
"""根据 ID 为单个文件启动摄入流程。"""
logger.info(f"请求摄入单个文件: file_id={file_id}")
async with AsyncSessionLocal() as session:
result = await session.execute(select(WikiFile).where(WikiFile.id == file_id))
db_file = result.scalar_one_or_none()
if not db_file:
raise HTTPException(status_code=404, detail="数据库中未找到该文件")
if db_file.status == "Ingesting":
return {"status": "already ingesting", "file_id": file_id}
db_file.status = "Ingesting"
await session.commit()
background_tasks.add_task(run_ingest_agent, file_id)
return {"status": "ingest started", "file_id": file_id}
# ==================================================================================
# 引入全局的摄入锁,保证任何时刻只能有一个文件在后台进行摄取
# ==================================================================================
global_ingest_lock = asyncio.Lock()
def save_post_with_formatting(post, fpath):
import frontmatter
import yaml
meta_copy = dict(post.metadata)
fs = meta_copy.pop("field_sources", None)
new_post = frontmatter.Post(post.content, **meta_copy)
raw_text = frontmatter.dumps(new_post)
if fs:
# 强制使用 yaml 格式化 field_sources
fs_yaml = yaml.dump({"field_sources": fs}, allow_unicode=True, sort_keys=False, default_flow_style=False).strip()
# 将 field_sources 插入到 Frontmatter 的末尾(也就是最后一个 --- 之前)
if raw_text.startswith("---\n"):
parts = raw_text.split("\n---\n", 1)
if len(parts) == 2:
raw_text = parts[0] + "\n\n" + fs_yaml + "\n---\n" + parts[1]
with open(fpath, "w", encoding="utf-8") as f_out:
f_out.write(raw_text)
# ==================================================================================
# 统一字段级溯源 (field_sources) 机制
# ----------------------------------------------------------------------------------
# 每个「受追踪字段」都在 field_sources 里记录其每个值由哪些来源贡献。
# 列表字段与标量字段一视同仁(标量内部按单值列表处理)。
# - 摄入:把新页面的字段贡献并入目标页 → _merge_field_sources
# - 摄出:移除某来源的贡献并按剩余来源重算字段值 → _recompute_after_source_removal
# 这样摄出只需「去掉自身的 field_sources 条目」即可保证 frontmatter 无残留。
# ==================================================================================
# 不参与来源追踪的字段(页面级元数据,不随单个来源增删)
SOURCE_TRACKED_EXCLUDE = {
"schema_version", "type", "sources", "created", "updated", "field_sources",
}
# 默认按列表语义处理的字段(即便某次只给了单值,也维持列表形态)
LIST_TRACKED_FIELDS = {"brand", "role", "tags", "related", "skill_tag"}
def _as_value_list(v):
"""把字段值归一为「值列表」:列表原样、标量包成单元素、空值返回空列表。"""
if isinstance(v, list):
return list(v)
if v in (None, ""):
return []
return [v]
def _merge_field_sources(target_md: dict, new_md: dict, canonical_source: str) -> None:
"""将 new_md 各受追踪字段的贡献并入 target_md,并维护 target_md['field_sources']。"""
fs = target_md.get("field_sources", {}) or {}
for key, val in new_md.items():
if key in SOURCE_TRACKED_EXCLUDE:
continue
new_vals = _as_value_list(val)
if not new_vals:
continue
is_list = isinstance(val, list) or isinstance(target_md.get(key), list) or key in LIST_TRACKED_FIELDS
fs.setdefault(key, {})
for item in new_vals:
fs[key].setdefault(item, [])
if canonical_source not in fs[key][item]:
fs[key][item].append(canonical_source)
if is_list:
old_list = _as_value_list(target_md.get(key))
for item in new_vals:
if item not in old_list:
old_list.append(item)
target_md[key] = old_list
else:
# 标量:保留已有值,仅在缺失时填入;冲突由 lint 兜底
if target_md.get(key) in (None, ""):
target_md[key] = new_vals[0]
target_md["field_sources"] = fs
def _recompute_after_source_removal(md: dict, removed_source: str) -> None:
"""从 field_sources 移除某来源贡献,并按剩余来源重算字段值;无来源支撑的字段删除。"""
fs = md.get("field_sources", {}) or {}
for field, srcmap in list(fs.items()):
for item in list(srcmap.keys()):
if removed_source in srcmap.get(item, []):
srcmap[item] = [s for s in srcmap[item] if s != removed_source]
if not srcmap.get(item):
srcmap.pop(item, None)
surviving = list(srcmap.keys())
if not surviving:
fs.pop(field, None)
md.pop(field, None)
elif isinstance(md.get(field), list) or field in LIST_TRACKED_FIELDS:
md[field] = surviving
else:
if md.get(field) not in surviving:
md[field] = surviving[0]
if fs:
md["field_sources"] = fs
else:
md.pop("field_sources", None)
async def run_ingest_agent(file_id: str):
async with global_ingest_lock:
await _run_ingest_agent_impl(file_id)
async def _run_ingest_agent_impl(file_id: str):
async with AsyncSessionLocal() as session:
result = await session.execute(select(WikiFile).where(WikiFile.id == file_id))
db_file = result.scalar_one_or_none()
if not db_file:
logger.error(f"[Ingest] File ID {file_id} not found in database.")
return
# 双重检查:防止并发情况下的重复摄入
if db_file.status != "Ingesting":
logger.warning(f"[Ingest] File {file_id} status is '{db_file.status}', skipped.")
return
filename = db_file.name
"""
核心摄入 Agent 业务逻辑(精简重构版 3-Phase 架构)。
工作流详解:
1. 【Phase 1: 统筹规划与全局打标】加载所有基线约束文件(静态上下文注入),进行宏观分析,输出全局5维标签和页面结构(含段落分配)。
2. 【Phase 2: 并发写作与网关自检】依据规划信息和基线示例,使用大批并发 Writer 独立写作;使用代码拦截产出,严格校验 Frontmatter 和清理 <think> 标签,失败则局部重试。
3. 【Phase 3: 合并保存与同步】执行文件 Upsert(支持防覆盖追加),并同步索引文件。
"""
start_time = datetime.now()
current_task_tokens.set([0])
logger.info(f"[{filename if 'filename' in dir() else file_id}] 摄入任务启动")
try:
file_path = os.path.join(RAW_DIR, db_file.format.lower(), filename)
raw_content = extract_text_from_file(file_path)
# 加载摄入专用提示词及所有相关基线文件(静态上下文注入)
skill_prompt = load_skill_prompt("llm-ingest")
schema_summary = ""
golden_examples = ""
brand_baseline = ""
# 尝试读取各类基线文件
schema_path = os.path.join(SKILLS_DIR, "llm-ingest", "references", "schema.md")
if os.path.exists(schema_path):
with open(schema_path, "r", encoding="utf-8") as f:
schema_summary = f.read()
golden_path = os.path.join(SKILLS_DIR, "llm-ingest", "references", "golden-examples.md")
if os.path.exists(golden_path):
with open(golden_path, "r", encoding="utf-8") as f:
golden_examples = f.read()
brand_path = os.path.join(SKILLS_DIR, "llm-ingest", "references", "brand-baseline.md")
if os.path.exists(brand_path):
with open(brand_path, "r", encoding="utf-8") as f:
brand_baseline = f.read()
# ==================================================================================
# 阶段一:统筹规划与全局打标 (Phase 1: Macro Planning & Tagging)
# ==================================================================================
print_thinking.set(True)
logger.info(f"[{filename}] [阶段一] 开始统筹规划与全局打标... 使用模型: {INGEST_MODEL_NAME}")
# 构建现有 slug 注册表(供 Planner 复用已有页、避免同义碎片化与跨目录撞名)
existing_slugs = {}
_skip_dirs = {os.path.join(WIKI_DIR, "metadata"), os.path.join(WIKI_DIR, "lint_reports")}
for _root, _dirs, _files in os.walk(WIKI_DIR):
_dirs[:] = [d for d in _dirs if os.path.join(_root, d) not in _skip_dirs]
for _f in _files:
if _f.endswith(".md") and _f not in ("index.md", "log.md"):
_slug = os.path.splitext(_f)[0]
try:
_post = frontmatter.load(os.path.join(_root, _f))
_title = str(_post.metadata.get("title") or _slug)
_ptype = str(_post.metadata.get("type") or "")
except Exception:
_title, _ptype = _slug, ""
existing_slugs[_slug] = (_ptype, _title)
slug_registry_text = "\n".join(
f"- [[{s}]] ({t[0]}) — {t[1]}" for s, t in sorted(existing_slugs.items())
) or "(当前知识库为空,无既有页面)"
planner_sys_prompt = f"""你是一个高级的知识库架构师。
你的任务是根据提供的原始文档,按照 LLM Wiki 方法论进行深度摄入规划。
【规则与基线说明】
1. 摄入规则:
{skill_prompt}
2. Schema 字段说明:
{schema_summary}
3. 品牌基线:
{brand_baseline}
【现有知识库页面注册表(用于复用与防撞名)】
{slug_registry_text}
【规划阶段指令】
1. 提取文档的 5 个结构化过滤维度(global_dims):
- series(品牌系列,单值,如「鸿蒙智行」;无系列填「通用品牌」)
- brand(适用品牌,列表,系列级产品可含多个,如 ["问界","智界","享界"])
- business_category(业务大类,单值:轻改类 | 权益类 | 二手车类)
- sub_business(子业务,单值)
- role(适用岗位,列表,如 ["驻店销售"];面向所有岗位用 ["通用"])
不确定或基线中没有的,填「未知[待确认]」;基线外的新品牌,值后附「[待审批]」。
2. 规划要生成的页面列表:必须含 1 个 sources 页面 + 0..N 个其他类型页面。
3. 【规范命名规则(极重要,杜绝同义碎片化)】每个页面的 slug 必须按「作用域实体 + 产品线/主题」确定性命名:
- 系列级产品(一个产品跨多个同系品牌,如鸿蒙智行官方延保覆盖问界/智界/享界/尊界/尚界)→ **按品牌系列建一页**,slug = 「{{品牌系列}}{{产品线}}」(如「鸿蒙智行官方延保」),不同车型的价格/参数在**页内分节**,brand 字段列全部适用品牌。
- 单品牌产品 → **按品牌建页**,slug = 「{{品牌}}{{产品线}}」(如「岚图整车延保」)。
- 实体/政策/流程/话术同理带作用域前缀,**严禁裸名**(如不要叫「整车延保」,要叫「岚图整车延保」或「鸿蒙智行官方延保」)。
- **复用优先**:若上方注册表中已存在描述同一真实产品/实体的页面,直接复用其 slug(走内容合并),不要新建同义页。
- **slug 全局唯一**:不允许与注册表中**不同主题**的页面撞 slug;同一 slug 在全库只能对应一个页面(即一个 file_path)。
4. 【核心约束·按主题完整归集,杜绝跨页丢失】每个页面用 `source_content_range` 描述它的**主题归属**(用产品/主题关键词,不要用「第X页」这类物理位置)。判定原则:
- **同一主题/产品的内容必须全部归入同一页**,哪怕它们在原文中**跨页、分散在多处、或分成常规价表 + 限时礼惠/赠送/活动等多个子表**——全部算这一页的范围。
- 切分以**主题**区分,不以原文物理位置区分;务必覆盖原文的每一处内容,**不要遗漏页边/跨页/表格末尾的零散行**。
- 各页主题应尽量不重叠(同一条事实只在其主题页展开),但当某段内容同时关联多个主题时,**宁可完整归入最相关的那一页,也不要让它落空**。
5. 输出的 related_links 必须使用 **slug 简写形式** `[[页面slug]]`(如 `[[岚图整车延保]]`),**禁止全路径、禁止带 .md**;且只能引用你本次规划出的 slug 或注册表中已存在的 slug。
6. 【目录结构】`file_path` 一律扁平:**只有 sources 类用 `ware/wiki/sources/{{品牌系列}}/{{slug}}.md`,其余所有 type 一律 `ware/wiki/{{type}}/{{slug}}.md`(不加任何品牌/系列子目录)**。(注:系统会按此规则强制确定性归一化路径,请勿自行添加子目录。)
请务必直接输出一段合法的 JSON,格式如下:
{{
"global_dims": {{
"series": "鸿蒙智行",
"brand": ["问界", "智界", "享界"],
"business_category": "权益类",
"sub_business": "售后延保",
"role": ["驻店销售"]
}},
"pages": [
{{
"type": "products",
"slug": "鸿蒙智行官方延保",
"file_path": "ware/wiki/products/鸿蒙智行官方延保.md",
"title": "鸿蒙智行官方延保",
"related_links": ["[[整车延保免责条款]]"],
"source_content_range": "从第2章xxx到第3章yyy的内容"
}}
]
}}
切记:只能输出 JSON,不要输出 Markdown 代码块,也不要有任何前言或解释!
"""
planner_agent = ReActAgent(
name="PlannerAgent",
model=get_llm_model(INGEST_MODEL_NAME),
formatter=DashScopeChatFormatter(),
sys_prompt=planner_sys_prompt
)
# 规划时不开启终端并发打印干扰
planner_agent.set_console_output_enabled(False)
msg_plan = Msg("user", f"原始文档内容如下:\n{raw_content}", role="user")
plan_res = await planner_agent(msg_plan)
# 将大模型可能返回的复杂混合格式统一处理
plan_content = plan_res.content
pages = []
# 健壮的 JSON 解析逻辑
plan_text = ""
if isinstance(plan_content, list):
parts = []
for item in plan_content:
if isinstance(item, str):
parts.append(item)
elif isinstance(item, dict):
if item.get("type") == "thinking":
logger.debug(f"[{filename}] [Phase 1] Planner 思考过程 (partial): {item.get('thinking', '')[:200]}")
elif "text" in item:
parts.append(item["text"])
plan_text = "".join(parts)
elif not isinstance(plan_content, str):
plan_text = str(plan_content)
else:
plan_text = plan_content
json_match = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", plan_text, re.DOTALL)
if json_match:
clean_json = json_match.group(1)
else:
start_idx = plan_text.find('{')
end_idx = plan_text.rfind('}')
if start_idx != -1 and end_idx != -1:
clean_json = plan_text[start_idx:end_idx+1]
else:
raise ValueError(f"未找到合法的 JSON 格式: {plan_text[:200]}...")
try:
plan_data = json.loads(clean_json)
except json.JSONDecodeError:
try:
safe_str = clean_json.replace('true', 'True').replace('false', 'False').replace('null', 'None')
plan_data = ast.literal_eval(safe_str)
except Exception as e:
raise ValueError(f"无法解析 JSON 格式: {clean_json[:200]}..., error: {e}")
pages = plan_data.get("pages", [])
# 解析结构化 5 维(兼容旧 global_tags 数组格式做兜底)
raw_dims = plan_data.get("global_dims") or {}
def _norm_scalar(v, default):
if isinstance(v, list):
return v[0] if v else default
return v if v not in (None, "") else default
def _norm_list(v):
if isinstance(v, list):
out = []
for x in v:
if x and x not in out:
out.append(x)
return out
return [] if v in (None, "") else [v]
if not raw_dims and isinstance(plan_data.get("global_tags"), list):
gt = plan_data["global_tags"] + ["", "", "", "", ""]
raw_dims = {"series": gt[1], "brand": gt[0], "business_category": gt[2],
"sub_business": gt[3], "role": gt[4]}
global_dims = {
"series": _norm_scalar(raw_dims.get("series"), "未知系列[待确认]"),
"brand": _norm_list(raw_dims.get("brand")) or ["未知品牌[待确认]"],
"business_category": _norm_scalar(raw_dims.get("business_category"), "未知业务[待确认]"),
"sub_business": _norm_scalar(raw_dims.get("sub_business"), "未知子业务[待确认]"),
"role": _norm_list(raw_dims.get("role")) or ["通用"],
}
logger.info(f"[{filename}] [Phase 1] 规划完成。全局维度: {global_dims},规划页面数: {len(pages)}")
# ==================================================================================
# 阶段二:并发写作与网关自检 (Phase 2: Concurrent Writing & Validation)
# ==================================================================================
print_thinking.set(False)
async def write_single_page_with_retry(page_info, max_retries=4):
"""
包含 Python 级强校验的并发写作任务。
"""
writer_sys_prompt = f"""你是一个专业的知识库写作专家。
请根据原始文档、规划要求和给定的基线示例,严格按照 LLM Wiki 规范生成单个页面的内容。
【基线示例 (Golden Examples)】
{golden_examples}
【本页写作任务】
目标路径: {page_info.get('file_path')}
核心主题: {page_info.get('title')}
页面类型 (type): {page_info.get('type')}
必须包含的关联链接: {', '.join(page_info.get('related_links', []))}
本页主题范围 (source_content_range): {page_info.get('source_content_range')}
全局锁定的 5 维过滤字段(必须原样写入 frontmatter):
series: {global_dims['series']}
brand: {global_dims['brand']}
business_category: {global_dims['business_category']}
sub_business: {global_dims['sub_business']}
role: {global_dims['role']}
【强制要求】
1. **结构要求**:必须在文件最开头包含 YAML frontmatter (由 --- 包裹),且必须包含以下 12 个字段,缺一不可:
schema_version (填 v1.3)、type、title、series、brand、business_category、sub_business、role、related、sources (填 ware/raw/{filename})、created、updated。
其中 series/brand/business_category/sub_business/role 必须使用上方「全局锁定」的值;brand 与 role 为列表(YAML 数组)。
2. **tags 字段(可选,自由标注)**:仅用于横切检索关键词(功能场景如 异议处理/合规红线/产品参数;辅助标签如 FAQ/错误码/案例研究/对比分析)。没有合适的就写成空列表 `tags: []`,**严禁**把品牌/系列/业务/岗位等 5 维内容塞进 tags。
3. **关联链接**:related 字段与正文 wikilink 一律使用 **slug 简写** `[[页面slug]]`,**禁止全路径、禁止带 .md 后缀**;只能使用「必须包含的关联链接」中给定的 slug。
4. **按主题完整归集(务必避免跨页丢失)**:以**主题归属**判断内容是否属于本页,**不要以原文物理位置/页码判断**。凡是属于本页主题的内容,**无论它在原文中跨页、分散在多处、还是分成常规价表 + 限时礼惠/赠送/活动等多个子表,都必须全部纳入**——尤其注意页边、跨页接续、表格末尾的零散行,极易遗漏,请逐一核对收齐。属于其他主题的内容则不要写入(由对应页面负责),避免重复展开同一事实。若本主题确实在原文中无内容,才输出极短内容。
5. **数值零丢失**:价格、金额、年限、里程、折扣、活动日期等核心数值与表格行必须 100% 全量保留,不得精简、省略或四舍五入。
6. **输出净化**:绝对不要输出 `<think>...</think>` 标签和推理过程!直接输出最终的 Markdown 文本!不需要任何前言和代码块包裹!
"""
writer_agent = ReActAgent(
name=f"Writer_{page_info.get('slug', 'page')}",
model=get_llm_model(INGEST_MODEL_NAME),
formatter=DashScopeChatFormatter(),
sys_prompt=writer_sys_prompt
)
writer_agent.set_console_output_enabled(False)
msg_prompt = f"原始文档内容:\n{raw_content}"
msg_write = Msg("user", msg_prompt, role="user")
for attempt in range(max_retries + 1):
try:
res_write = await writer_agent(msg_write)
# 1. 解析内容
content = res_write.content
if isinstance(content, list):
parts = []
for item in content:
if isinstance(item, str):
parts.append(item)
elif isinstance(item, dict):
if item.get("type") == "thinking":
pass
elif "text" in item:
parts.append(item["text"])
content = "".join(parts)
content = str(content)
# 2. 净化 <think> 标签(Python 级硬删除)
content = re.sub(r"<(?:think|thinking)>.*?</(?:think|thinking)>", "", content, flags=re.DOTALL)
# 3. 净化 Markdown 代码块包裹符
content = content.strip()
content = re.sub(r"^```[a-zA-Z]*\s*\n", "", content)
content = re.sub(r"\n```\s*$", "", content)
content = content.strip()
# 3.5 规范化 <br> 标签(表格内→空格,正文→换行)
content = normalize_br_tags(content)
# 4. Frontmatter 严格检查(frontmatter 已在文件顶部导入)
try:
post = frontmatter.loads(content)
md = post.metadata
required_fields = [
"schema_version", "type", "title",
"series", "brand", "business_category", "sub_business", "role",
"related", "sources", "created", "updated",
]
missing = [f for f in required_fields if f not in md]
if missing:
raise ValueError(f"YAML 缺少必填字段: {missing}")
if md.get("schema_version") != "v1.3":
raise ValueError(f"schema_version 必须是 v1.3,当前为: {md.get('schema_version')}")
except Exception as parse_err:
raise ValueError(f"Frontmatter 解析失败: {str(parse_err)}")
retry_info = "首次尝试" if attempt == 0 else f"第 {attempt} 次重试后"
logger.info(f"[{filename}] [Phase 2] 页面校验成功: {page_info.get('file_path')} ({retry_info}成功)")
return {
"file_path": page_info.get("file_path"),
"content": content
}
except Exception as check_err:
logger.warning(f"[{filename}] [Phase 2] 页面校验失败 {page_info.get('file_path')} (第 {attempt+1} 次): {check_err}")
if attempt < max_retries:
msg_write = Msg("user", f"你上一次的输出未通过规范校验!错误原因:{str(check_err)}。请修复后重新输出完整的 Markdown 页面。", role="user")
else:
error_msg = f"页面 {page_info.get('file_path')} 连续重试校验失败,摄入中止。"
logger.error(f"[{filename}] [Phase 2] {error_msg}")
raise ValueError(error_msg)
# 引入 asyncio.Semaphore(20) 作为并发信号量控制器
sem = asyncio.Semaphore(20)
async def sem_write_single_page(page_info):
async with sem:
return await write_single_page_with_retry(page_info)
logger.info(f"[{filename}] [Phase 2] 开始并发写作与自检,共 {len(pages)} 个页面...")
write_tasks = [asyncio.create_task(sem_write_single_page(p)) for p in pages]
# 使用 asyncio.wait 实现 fail-fast,如果任一页面发生异常立即阻断
done, pending = await asyncio.wait(write_tasks, return_when=asyncio.FIRST_EXCEPTION)
# 问题8:先取消未完成任务,再 await gather 确保资源干净释放
for task in pending:
task.cancel()
if pending:
await asyncio.gather(*pending, return_exceptions=True)
generated_results = []
first_exception = None
for task in done:
exc = task.exception()
if exc and first_exception is None:
first_exception = exc
elif not exc:
generated_results.append(task.result())
if first_exception:
raise first_exception
valid_files = [res for res in generated_results if res is not None]
logger.info(f"[{filename}] [Phase 2] 并发写作完成。成功生成 {len(valid_files)} / {len(pages)} 个页面。")
# ==================================================================================
# 阶段三:合并保存与同步 (Phase 3: Batch Save & Sync)
# ==================================================================================
if valid_files:
logger.info(f"[{filename}] [Phase 3] 开始批量安全保存...")
# 构建磁盘上现有 slug -> 路径 映射,用于 slug 全局唯一性预检
disk_slug_paths = {}
for _r, _ds, _fs in os.walk(WIKI_DIR):
_ds[:] = [d for d in _ds if os.path.join(_r, d) not in _skip_dirs]
for _ff in _fs:
if _ff.endswith(".md") and _ff not in ("index.md", "log.md"):
disk_slug_paths[os.path.splitext(_ff)[0]] = os.path.abspath(os.path.join(_r, _ff))
canonical_source = f"ware/raw/{filename}"
def _type_dir_of(rel_or_abs_path: str) -> str:
"""从 wiki 相对/绝对路径取 type 目录(ware/wiki 之后的第一段)。"""
p = str(rel_or_abs_path).replace("\\", "/")
if "ware/wiki/" in p:
tail = p.split("ware/wiki/", 1)[1]
else:
tail = os.path.relpath(p, WIKI_DIR).replace("\\", "/")
segs = [s for s in tail.split("/") if s]
return segs[0] if segs else "misc"
for vf in valid_files:
slug = os.path.splitext(os.path.basename(vf["file_path"]))[0]
# 解析失败兜底用的预备落点(Planner 原始路径)
fpath = os.path.join(BASE_DIR, vf["file_path"])
try:
post = frontmatter.loads(vf["content"])
# —— 路径确定性化:按 type 推导落点,忽略 Planner 自加的子目录 ——
page_type = str(post.metadata.get("type") or _type_dir_of(vf["file_path"])).strip()
if page_type == "sources":
series = str(post.metadata.get("series") or "未分类").strip()
series = re.sub(r'[\\/:*?"<>|]', "_", series) or "未分类"
rel_path = f"ware/wiki/sources/{series}/{slug}.md"
else:
rel_path = f"ware/wiki/{page_type}/{slug}.md"
fpath = os.path.join(BASE_DIR, rel_path)
# —— slug 冲突 → 合并而非报错 ——
conflict = disk_slug_paths.get(slug)
if conflict and os.path.abspath(conflict) != os.path.abspath(fpath):
if _type_dir_of(conflict) == page_type:
# 同类型:同一 slug = 同一页面,重定向合并到既有页面
logger.info(
f"[{filename}] [Phase 3] slug '{slug}' 已存在于 "
f"{os.path.relpath(conflict, BASE_DIR)},本次内容合并入既有页面"
)
fpath = conflict
rel_path = os.path.relpath(conflict, BASE_DIR).replace("\\", "/")
else:
# 跨类型撞名:真正的命名歧义,保证 [[slug]] 可解析
raise ValueError(
f"slug 跨类型冲突:'{slug}' 已存在于 "
f"{os.path.relpath(conflict, BASE_DIR)}(type={_type_dir_of(conflict)}),"
f"无法作为 {page_type} 重复创建"
)
# 记录真实落点,供后续 DB(WikiFilePage)/log/摄出精确定位
vf["file_path"] = rel_path
os.makedirs(os.path.dirname(fpath), exist_ok=True)
# 归一化 sources 为规范路径 ware/raw/{filename}
sources = _as_value_list(post.metadata.get("sources"))
sources = [s for s in sources if s not in (
f"raw/{filename}", canonical_source
) and not s.startswith("ware/raw/sources/")]
sources.append(canonical_source)
post.metadata["sources"] = sources
# 被 HTML 注释包裹的正文块
wrapped_content = f"\n<!-- SOURCE_START: {canonical_source} -->\n{post.content.strip()}\n<!-- SOURCE_END: {canonical_source} -->\n"
block_re = re.compile(
rf"<!-- SOURCE_START: {re.escape(canonical_source)} -->.*?<!-- SOURCE_END: {re.escape(canonical_source)} -->",
re.DOTALL,
)
if os.path.exists(fpath):
old_post = frontmatter.load(fpath)
# 1. 合并 sources
old_sources = _as_value_list(old_post.metadata.get("sources"))
if canonical_source not in old_sources:
old_sources.append(canonical_source)
old_post.metadata["sources"] = old_sources
# 2. 统一字段级溯源合并(含 5 结构化字段 + title/tags/related 等)
_merge_field_sources(old_post.metadata, post.metadata, canonical_source)
# 3. 正文:已存在本源 SOURCE 块则替换(避免重复摄入叠加),否则追加
old_body = old_post.content
if block_re.search(old_body):
old_body = block_re.sub(wrapped_content.strip(), old_body)
else:
old_body = old_body.strip() + "\n" + wrapped_content
old_post.content = old_body
save_post_with_formatting(old_post, fpath)
else:
# 新建:从零初始化 field_sources(覆盖全部受追踪字段)
fs = {}
for key, val in post.metadata.items():
if key in SOURCE_TRACKED_EXCLUDE:
continue
vals = _as_value_list(val)
if not vals:
continue
fs[key] = {item: [canonical_source] for item in vals}
if fs:
post.metadata["field_sources"] = fs
post.content = wrapped_content.strip()
save_post_with_formatting(post, fpath)
# 记录新落盘的 slug,供后续页面的唯一性预检
disk_slug_paths[slug] = os.path.abspath(fpath)
except ValueError:
raise
except Exception as e:
logger.error(f"[{filename}] [Phase 3] 解析或保存文件时发生错误,退化为直接写入: {e}", exc_info=True)
wrapped_raw = f"\n<!-- SOURCE_START: {canonical_source} -->\n{vf['content']}\n<!-- SOURCE_END: {canonical_source} -->\n"
os.makedirs(os.path.dirname(fpath), exist_ok=True)
if os.path.exists(fpath):
with open(fpath, "a", encoding="utf-8") as f_out:
f_out.write(wrapped_raw)
else:
with open(fpath, "w", encoding="utf-8") as f_out:
f_out.write(wrapped_raw)
logger.info(f"[{filename}] [Phase 3] 文件保存完成。")
# 统计本次生成内容中的 wikilink 总数(供 lint 增量模式使用)
total_wikilinks = sum(
len(re.findall(r'\[\[', vf.get('content', '')))
for vf in valid_files
)
pages_list = ", ".join([vf.get('file_path', '') for vf in valid_files])
print(f"[{filename}] [阶段三] 正在重建 index.md 并写入 log.md...")
# index.md 确定性全量重建(替换历史的「只追加」方式)
rebuild_index(WIKI_DIR)
date_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log_entry = (
f"- [{date_str}] 摄入 [[raw/{filename}]]\n"
f" - 生成页面: {len(valid_files)} 个({pages_list})\n"
f" - wikilink总数: {total_wikilinks}\n"
f" - 模式: 3-phase\n"
)
append_wiki_file("ware/wiki/log.md", log_entry)
print(f"[{filename}] [阶段三] 数据同步完成,摄入流水线整体结束。")
# ==================================================================================
# 任务后处理:元数据与统计指标记录
# ==================================================================================
end_time = datetime.now()
duration = (end_time - start_time).total_seconds()
total_tokens = current_task_tokens.get([0])[0]
# 1. 更新数据库状态与指标
async with AsyncSessionLocal() as session:
result = await session.execute(select(WikiFile).where(WikiFile.id == file_id))
db_file_cur = result.scalar_one_or_none()
if db_file_cur:
db_file_cur.status = "Indexed"
db_file_cur.total_tokens = total_tokens
db_file_cur.ingest_duration = Decimal(str(round(duration, 2)))
db_file_cur.ingest_time = end_time
db_file_cur.error_message = None
# 写入生成的关联页面到数据库
await session.execute(delete(WikiFilePage).where(WikiFilePage.file_id == file_id))
pages_list = []
for vf in valid_files:
page_path = vf.get('file_path')
if page_path:
pages_list.append(page_path)
wiki_file_page = WikiFilePage(
file_id=file_id,
page_path=page_path
)
session.add(wiki_file_page)
log = WikiOperationLog(
file_id=file_id,
file_name=filename,
operation="INGEST_SUCCESS",
details=json.dumps({
"total_tokens": total_tokens,
"duration_seconds": round(duration, 1),
"generated_wiki_pages": pages_list
}, ensure_ascii=False)
)
session.add(log)
await session.commit()
except Exception as e:
logger.error(f"[{filename if 'filename' in dir() else file_id}] 摄入流程发生严重错误: {e}", exc_info=True)
# 1. 更新数据库状态为 Failed
try:
async with AsyncSessionLocal() as session:
result = await session.execute(select(WikiFile).where(WikiFile.id == file_id))
db_file_cur = result.scalar_one_or_none()
if db_file_cur:
db_file_cur.status = "Failed"
db_file_cur.error_message = str(e)
log = WikiOperationLog(
file_id=file_id,
file_name=filename,
operation="INGEST_FAIL",
details=json.dumps({"error": str(e)}, ensure_ascii=False)
)
session.add(log)
await session.commit()
except Exception as db_err:
logger.error(f"[{file_id}] 更新数据库 Failed 状态时发生错误: {db_err}", exc_info=True)