ingest.py
36.6 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
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,
)
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 内容。
支持"聚合页面"的局部删除,防止误删其他源文件贡献的内容。
缺陷4修复:通过 DB 状态检查实现幂等保护,防止并发重复摄出。
"""
logger.info(f"请求摄出(Egress)知识库文件: file_id={file_id}")
# 缺陷4:先检查状态,防止并发重复摄出
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 == "Ingesting":
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]
# 缺陷6:统一 source_ref 格式为 ware/raw/{name}
source_ref = f"ware/raw/{name}"
count = 0
deleted_files = []
targets = []
if generated_pages:
targets = [os.path.abspath(os.path.join(BASE_DIR, p)) for p in generated_pages]
for file_path in targets:
if not os.path.exists(file_path):
continue
try:
post = frontmatter.load(file_path)
sources = post.metadata.get("sources", [])
if source_ref in sources:
post.metadata["sources"] = [s for s in sources if s != source_ref]
field_sources = post.metadata.get("field_sources", {})
if field_sources:
for field_name, source_dict in list(field_sources.items()):
actual_list = post.metadata.get(field_name, [])
if isinstance(actual_list, str):
actual_list = [actual_list]
new_actual_list = []
for item in actual_list:
if item in source_dict:
if source_ref in source_dict[item]:
source_dict[item] = [s for s in source_dict[item] if s != source_ref]
if not source_dict[item]:
del source_dict[item]
else:
new_actual_list.append(item)
else:
new_actual_list.append(item)
post.metadata[field_name] = new_actual_list
if not source_dict:
del field_sources[field_name]
post.metadata["field_sources"] = field_sources
content = post.content
# source_ref 已是 ware/raw/{name} 格式,直接匹配
pattern = re.compile(rf"<!-- SOURCE_START: {re.escape(source_ref)} -->.*?<!-- SOURCE_END: {re.escape(source_ref)} -->", re.DOTALL)
updated_content = pattern.sub("", 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 updated_content or not post.metadata.get("sources"):
os.remove(file_path)
deleted_files.append(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)
if deleted_files:
index_path = os.path.join(WIKI_DIR, "index.md")
if os.path.exists(index_path):
with open(index_path, "r", encoding="utf-8") as f:
index_lines = f.readlines()
new_index_lines = []
for line in index_lines:
keep = True
for df in deleted_files:
rel_path = os.path.relpath(df, WIKI_DIR).replace("\\", "/")
slug = os.path.splitext(os.path.basename(df))[0]
if f"[[{rel_path}]]" in line or f"[[{slug}]]" in line:
keep = False
break
if keep:
new_index_lines.append(line)
with open(index_path, "w", encoding="utf-8") as f:
f.writelines(new_index_lines)
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")
# 缺陷6:log.md 引用使用规范路径 ware/raw/{name}
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)
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 = ""
ingest_instructions = ""
# 尝试读取各类基线文件
schema_path = os.path.join(SKILLS_DIR, "llm-ingest", "references", "schema-summary.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()
# 尝试从该文件所在目录的各级父目录寻找 .ingest-instructions.md
rel_dir = os.path.dirname(filename)
instruction_path = os.path.join(RAW_DIR, rel_dir, ".ingest-instructions.md")
if os.path.exists(instruction_path):
with open(instruction_path, "r", encoding="utf-8") as f:
ingest_instructions = f.read()
# ==================================================================================
# 阶段一:统筹规划与全局打标 (Phase 1: Macro Planning & Tagging)
# ==================================================================================
print_thinking.set(True)
logger.info(f"[{filename}] [阶段一] 开始统筹规划与全局打标... 使用模型: {INGEST_MODEL_NAME}")
planner_sys_prompt = f"""你是一个高级的知识库架构师。
你的任务是根据提供的原始文档,按照 LLM Wiki 方法论进行深度摄入规划。
【规则与基线说明】
1. 摄入规则:
{skill_prompt}
2. Schema 字段说明:
{schema_summary}
3. 品牌基线:
{brand_baseline}
4. 局部指导文件(可能为空):
{ingest_instructions}
【规划阶段指令】
1. 首先,你需要根据文档内容、路径、或局部指导文件,提取出文档的 5 维标签。如果某个标签不确定或基线中没有,请标注“[待确认]”。
2. 其次,你需要规划出要生成的页面列表。必须包含 1 个 sources 页面,以及按需划分的其他页面(遵循 1个 sources + 0..N 个其他的原则)。
3. 【核心约束】对于每个页面,你必须指定 `source_content_range`,明确该页面应该使用原文的哪一部分(可以用关键词、段落大意或章节名表示)。不同的页面 `source_content_range` 必须互斥,绝对不允许两个页面覆盖同样的原文段落!
4. 输出的 related_links 必须使用带 ware/wiki 的全路径格式,例如:[[ware/wiki/products/关联页面名.md]],不允许使用简写,且必须存在你所规划的所有 file_path 内。
请务必直接输出一段合法的 JSON,格式如下:
{{
"global_tags": ["品牌名", "品牌系列", "业务大类", "子业务", "岗位"],
"pages": [
{{
"type": "products",
"slug": "产品名",
"file_path": "ware/wiki/products/产品名.md",
"title": "具体产品名称",
"related_links": ["[[ware/wiki/products/关联页面名.md]]"],
"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 = []
global_tags = []
# 健壮的 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", [])
global_tags = plan_data.get("global_tags", ["未知品牌", "未知系列", "未知业务", "未知子业务", "未知岗位"])
logger.info(f"[{filename}] [Phase 1] 规划完成。全局标签: {global_tags},规划页面数: {len(pages)}")
# ==================================================================================
# 阶段二:并发写作与网关自检 (Phase 2: Concurrent Writing & Validation)
# ==================================================================================
print_thinking.set(False)
async def write_single_page_with_retry(page_info, max_retries=2):
"""
包含 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')}
全局锁定标签 (tags): {global_tags}
【强制要求】
1. **结构要求**:必须在文件最开头包含 YAML frontmatter (由 --- 包裹),并且必须包含 schema_version (填 v1.3)、type、title、tags (使用上述全局锁定标签)、related、sources (填 ware/raw/{filename})、created、updated 8个字段。缺一不可!
2. **范围约束**:严禁抓取或总结专属原文范围 (source_content_range) 以外的内容!如果你发现分配给你的范围里没东西,请输出极短的内容,不要去别的地方借内容!
3. **输出净化**:绝对不要输出 `<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()
# 4. Frontmatter 严格检查(frontmatter 已在文件顶部导入)
try:
post = frontmatter.loads(content)
md = post.metadata
required_fields = ["schema_version", "type", "title", "tags", "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] 开始批量安全保存...")
for vf in valid_files:
fpath = os.path.join(BASE_DIR, vf["file_path"])
os.makedirs(os.path.dirname(fpath), exist_ok=True)
try:
post = frontmatter.loads(vf["content"])
# 缺陷6:强制覆写 sources 字段为规范路径 ware/raw/{filename}
canonical_source = f"ware/raw/{filename}"
sources = post.metadata.get("sources", [])
if isinstance(sources, str):
sources = [sources]
# 过滤掉 LLM 生成的各种格式错误来源,统一归一化
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"
# 动态提取所有 List 类型的属性作为需要追踪的字段 (排除 sources 自己)
list_fields = {k: v for k, v in post.metadata.items() if isinstance(v, list) and k != "sources"}
if os.path.exists(fpath):
old_post = frontmatter.load(fpath)
# 1. 追加 Sources(缺陷6:使用规范格式)
old_sources = old_post.metadata.get("sources", [])
if isinstance(old_sources, str):
old_sources = [old_sources]
if canonical_source not in old_sources:
old_sources.append(canonical_source)
old_post.metadata["sources"] = old_sources
# 2. 通用追加 List 字段并写入 field_sources
field_sources = old_post.metadata.get("field_sources", {})
for field_name, new_list in list_fields.items():
old_list = old_post.metadata.get(field_name, [])
if isinstance(old_list, str):
old_list = [old_list]
if field_name not in field_sources:
field_sources[field_name] = {}
for item in new_list:
if item not in old_list:
old_list.append(item)
if item not in field_sources[field_name]:
field_sources[field_name][item] = []
# 缺陷6:field_sources 内路径也统一为规范格式
if canonical_source not in field_sources[field_name][item]:
field_sources[field_name][item].append(canonical_source)
old_post.metadata[field_name] = old_list
old_post.metadata["field_sources"] = field_sources
old_post.content = old_post.content.strip() + "\n" + wrapped_content
save_post_with_formatting(old_post, fpath)
else:
# 新建时初始化 field_sources
field_sources = {}
for field_name, new_list in list_fields.items():
field_sources[field_name] = {}
for item in new_list:
# 缺陷6:field_sources 初始化也统一使用规范格式
field_sources[field_name][item] = [canonical_source]
if field_sources:
post.metadata["field_sources"] = field_sources
post.content = wrapped_content.strip()
save_post_with_formatting(post, fpath)
except Exception as e:
logger.error(f"[{filename}] [Phase 3] 解析或保存文件时发生错误,退化为直接写入: {e}", exc_info=True)
wrapped_raw = f"\n<!-- SOURCE_START: ware/raw/{filename} -->\n{vf['content']}\n<!-- SOURCE_END: ware/raw/{filename} -->\n"
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] 文件保存完成。")
# 同步更新全站的全局索引 (index.md) 和摄入操作日志 (log.md)
index_entries = []
existing_index = ""
index_path = os.path.join(WIKI_DIR, "index.md")
if os.path.exists(index_path):
with open(index_path, "r", encoding="utf-8") as f:
existing_index = f.read()
for vf in valid_files:
# 提取 slug(文件名不含路径和 .md 后缀)
slug = os.path.splitext(os.path.basename(vf.get('file_path', '')))[0]
# 同时检查新格式(slug)和旧格式(路径)是否已存在,避免重复写入
rel_path = vf.get('file_path', '').replace('ware/wiki/', '').replace('\\', '/')
if f"[[{slug}]]" not in existing_index and f"[[{rel_path}]]" not in existing_index:
# 尝试从内容提取 title,如果没有则用 slug
try:
post = frontmatter.loads(vf["content"])
title = post.metadata.get("title", slug)
except:
title = slug
# 使用 slug 格式 + em dash(符合 lint 1.5 要求)
index_entries.append(f"- [[{slug}]] — {title}")
# 统计本次生成内容中的 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...")
if index_entries:
append_wiki_file("ware/wiki/index.md", "\n".join(index_entries))
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)