Commit 4b8700b6 by 黄南光

长文档摄入优化,修复前端流式输出气泡泄露问题

1 parent 6e37812d
......@@ -97,9 +97,14 @@ INGEST_MAP_CONCURRENCY = int(os.environ.get("INGEST_MAP_CONCURRENCY", "10"))
INGEST_CHUNK_TARGET_CHARS = int(os.environ.get("INGEST_CHUNK_TARGET_CHARS", "8000"))
INGEST_CHUNK_MAX_CHARS = int(os.environ.get("INGEST_CHUNK_MAX_CHARS", "12000"))
# 单个页面允许认领的原文总量上限:超过说明 Planner 把过多内容压进一页,
# 会同时打爆 Writer 上下文与输出上限,须回喂 Planner 拆页。
INGEST_PAGE_SOURCE_MAX_CHARS = int(os.environ.get("INGEST_PAGE_SOURCE_MAX_CHARS", "50000"))
# 单个页面允许认领的原文总量上限:超过说明 Planner 把过多内容压进一页,须回喂 Planner 拆页。
#
# 该值直接决定产出保真度。实测(KB_信任疑虑.md,源小节→生成小节的压缩比):
# 单页 ~46K 字符 → 58 小节压成 3 小节(19.3:1,几乎废页)
# 单页 ~30K 字符 → 38 小节出 18 小节(2.1:1,正常)
# 原因是 Writer 的有效输出预算基本固定(正文 1700-3500 字符),**投喂越多只会压得越狠**,
# 而不是产出更多。所以宁可多分页,也不要把大量原文塞进一页。
INGEST_PAGE_SOURCE_MAX_CHARS = int(os.environ.get("INGEST_PAGE_SOURCE_MAX_CHARS", "30000"))
def is_multimodal(model_name: str) -> bool:
"""是否为带视觉的多模态模型(content 走 list-of-blocks)。
......
This diff could not be displayed because it is too large.
......@@ -243,6 +243,7 @@ read_local_file(file_path="ware/wiki/concepts/算账法.md")
- 禁止在知识库无命中时编造答案
- 禁止跳过检索直接回答(必须至少调用一次工具)
- 禁止修改知识库内容
- 禁止把推理过程与工具调用细节写进正文(正文会原样展示给用户);调用工具前如需说明,**控制在一句话以内**,且不要复述工具返回的原始内容
---
......
......@@ -234,6 +234,7 @@ def build_planner_system_prompt_chunked(
chunk_inventory_text: str,
chunk_count: int,
sources_slug: str,
max_chunks_per_page: int,
) -> str:
"""长文档分块模式的 Planner prompt:不含全文,只含全部块的内容清单。
......@@ -265,7 +266,11 @@ JSON 对象必须包含:
- Writer 写作时只能读到本页 source_chunks 对应的原文块,漏认领的内容会永久丢失;
- 除 sources 页外,全部 {chunk_count} 个块都必须被至少一个**下游主题页**认领;
- 一个块常包含多个主题:不同页面可以认领同一个块,一个页面也可以认领多个块;
- 单页认领的原文总量不得超过 {PAGE_SOURCE_MAX_CHARS} 字符(约 6-7 个块)。
- **单页认领最多约 {max_chunks_per_page} 个块**(总字符必须 ≤ {PAGE_SOURCE_MAX_CHARS})。
上方清单每行都标了该块字符数,认领前请逐块累加核对;**宁可少认领一块,也不要超**。
超限会让整份规划被打回重做,浪费一次完整调用。
- 为什么限制这么严:Writer 的输出预算基本固定,**一页塞太多原文只会被压缩得更狠、丢掉大量内容**,
而不是产出更多。宁可多分几页,每页写透。
【分页原则(务必遵守,直接决定 wiki 质量)】
- **按语义主题聚合块**:一个连贯主题 = 一个页面,可跨多个块(只要不超上限),slug 用语义化名称;
......@@ -279,9 +284,13 @@ JSON 对象必须包含:
- **严禁**把同一主题机械切成 `xxx-01`、`xxx-02`、`xxx-03` 这类顺序编号页;
- 页面标题必须**忠实反映该页实际聚合的主题**;也不要把不相关的多个主题硬塞进一页。
【slug 复用(避免近重复页)】
- 规划某主题前先查上方【现有知识库页面注册表】;若命中同一实体/主题,**直接复用其现有 slug**,
系统会按同 slug 合并归并,而不是新建一个措辞略不同的近重复页。
【slug 复用(硬要求,避免近重复页)】
- 规划**每一个**页面前,**必须先逐条比对**上方【现有知识库页面注册表】;
- 若某产品/实体 + 异议类型**已有页面**,**必须复用它现有的 slug**(系统会自动合并内容与维度),
**不得**新建一个仅措辞不同的近重复页。
反例:注册表里已有 `漆面保护膜价值论证与材质解析异议处理`,就**不要**再建
`漆面保护膜信任疑虑与材质论证异议处理话术`——这两个讲的是同一件事,应复用前者;
- 只有当该主题在注册表中**确实不存在**时,才允许新建页面。
【type=sources 摘要页的特别约束(重要,务必遵守)】
- sources 页 source_chunks **必须是空数组 []**:它不认领任何原文块;
......@@ -1322,6 +1331,18 @@ def _check_page_source_budget(pages: list[dict], chunks: tuple[DocChunk, ...]) -
)
def _max_chunks_per_page(chunks: tuple[DocChunk, ...]) -> int:
"""把单页字符预算折算成「最多认领几块」,用于 Planner prompt。
实测让 LLM 精确累加字符数不可靠(多次因超限被打回重试),而数块很稳。
按平均块大小折算并至少留 1 块,避免出现 0。
"""
if not chunks:
return 1
avg = max(1, sum(len(c.text) for c in chunks) // len(chunks))
return max(1, PAGE_SOURCE_MAX_CHARS // avg)
def _check_chunk_coverage(pages: list[dict], chunks: tuple[DocChunk, ...]) -> None:
"""全部块必须被至少一个下游页认领;漏块即抛 ValueError 走 Planner 重试回路反思重规划。
......@@ -1380,6 +1401,8 @@ async def _phase1_plan(
chunk_inventory_text=_format_map_inventories(map_inventories or [], ctx.chunks),
chunk_count=len(ctx.chunks),
sources_slug=_sources_slug_for_file(ctx.filename),
# 让 LLM 数块比让它累加字符数可靠得多:把预算同时折算成块数上限给它
max_chunks_per_page=_max_chunks_per_page(ctx.chunks),
)
else:
planner_sys_prompt = build_planner_system_prompt(
......@@ -1468,6 +1491,13 @@ async def _phase1_plan(
f"pages_count={len(pages)}{_covered}, "
f"page_paths={[p.get('file_path') for p in pages if isinstance(p, dict)]}"
)
# slug 复用决策:观察"复用已有页 vs 新建近重复页"的实际比例,判断复用提示是否生效
_planned = [str(p.get("slug")) for p in pages if isinstance(p, dict) and p.get("slug")]
_reused = [s for s in _planned if s in slug_registry]
logger.info(
f"[{filename}] [Phase 1] slug_reuse reused={_reused} "
f"new={[s for s in _planned if s not in slug_registry]}"
)
break # 成功,跳出重试循环
except (ValueError, json.JSONDecodeError) as parse_err:
......
from pathlib import Path
import ast
import unittest
def _function_source(path: str, name: str) -> str:
source = Path(path).read_text(encoding="utf-8")
tree = ast.parse(source)
for node in tree.body:
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == name:
return ast.get_source_segment(source, node) or ""
raise AssertionError(f"Function not found: {name}")
class FilesPreviewStaticTest(unittest.TestCase):
def test_pptx_view_uses_existing_preview_without_generating(self):
view_source = _function_source("src/api/routes/files.py", "view_file")
self.assertIn("get_existing_office_preview_pdf", view_source)
self.assertNotIn("get_or_create_office_preview_pdf", view_source)
self.assertIn("preview_status", view_source)
self.assertIn("missing", view_source)
self.assertIn("status_code=202", view_source)
def test_document_parser_exposes_existing_preview_helper(self):
parser_source = Path("src/tools/document_parser.py").read_text(encoding="utf-8")
self.assertIn("def get_existing_office_preview_pdf", parser_source)
self.assertIn("return str(cache_path)", parser_source)
if __name__ == "__main__":
unittest.main()
from pathlib import Path
import unittest
class IngestContractStaticTest(unittest.TestCase):
def test_ingest_uses_schema_contract_instead_of_split_reference_files(self):
source = Path("src/api/routes/ingest.py").read_text(encoding="utf-8")
self.assertIn("def build_planner_system_prompt", source)
self.assertIn("def build_writer_system_prompt", source)
self.assertNotIn("src.utils.ingest_prompts", source)
self.assertFalse(Path("src/utils/ingest_prompts.py").exists())
self.assertIn("contract_prompt_text", source)
self.assertIn("current_schema_version", source)
self.assertIn("canonicalize_type", source)
self.assertIn("merge_field_sources", source)
self.assertIn("recompute_after_source_removal", source)
self.assertNotIn("brand-baseline.md", source)
self.assertNotIn("golden-examples.md", source)
self.assertNotIn('"v1.3"', source)
hardcoded_prompt_fragments = [
"轻改类 | 权益类 | 二手车类",
"杜绝同义碎片化",
"按主题完整归集",
"数值零丢失",
"作用域实体 + 产品线/主题",
]
for fragment in hardcoded_prompt_fragments:
self.assertNotIn(fragment, source)
def test_lint_uses_schema_contract_instead_of_markdown_regex_baselines(self):
source = Path("src/api/routes/lint.py").read_text(encoding="utf-8")
self.assertIn("brand_baseline_set", source)
self.assertIn("canonicalize_type", source)
self.assertIn("load_ingest_contract", source)
self.assertNotIn("brand-baseline.md", source)
self.assertNotIn("schema_version[:\\s]+", source)
def test_llm_ingest_skill_has_single_reference_document(self):
references = sorted(p.name for p in Path("skills/llm-ingest/references").glob("*.md"))
skill = Path("skills/llm-ingest/SKILL.md").read_text(encoding="utf-8")
self.assertEqual(references, ["schema.md"])
self.assertNotIn("brand-baseline.md", skill)
self.assertNotIn("golden-examples.md", skill)
self.assertNotIn("v1.3", skill)
if __name__ == "__main__":
unittest.main()
from pathlib import Path
import unittest
class IngestFileLocksStaticTest(unittest.TestCase):
def test_ingest_is_global_serial_but_egress_only_uses_file_lock(self):
source = Path("src/api/routes/ingest.py").read_text(encoding="utf-8")
self.assertIn("ingest_global_lock = asyncio.Lock()", source)
self.assertIn("async with ingest_global_lock:", source)
self.assertIn("file_operation_locks", source)
self.assertIn("def _get_file_operation_lock(file_id: str)", source)
self.assertIn("async with _get_file_operation_lock(file_id):", source)
self.assertIn("[Egress] waiting_for_file_lock", source)
self.assertNotIn("[Egress] waiting_for_ingest_global_lock", source)
self.assertNotIn("[Egress] acquired_ingest_global_lock", source)
self.assertIn("[IngestTask] waiting_for_file_lock", source)
self.assertIn("[IngestTask] waiting_for_ingest_global_lock", source)
if __name__ == "__main__":
unittest.main()
import unittest
from pathlib import Path
class IngestTokenStatsStaticTest(unittest.TestCase):
def test_wiki_file_schema_tracks_input_output_and_total_tokens(self):
model_source = Path("src/database/models.py").read_text(encoding="utf-8")
ddl_source = Path("src/database/sql/create_tables.sql").read_text(encoding="utf-8")
for field in ("input_tokens", "output_tokens", "total_tokens"):
with self.subTest(field=field):
self.assertIn(field, model_source)
self.assertIn(f"`{field}`", ddl_source)
def test_ingest_success_persists_token_breakdown(self):
source = Path("src/api/routes/ingest.py").read_text(encoding="utf-8")
self.assertIn("token_usage = current_task_token_usage()", source)
self.assertIn("db_file_cur.input_tokens = token_usage[\"input_tokens\"]", source)
self.assertIn("db_file_cur.output_tokens = token_usage[\"output_tokens\"]", source)
self.assertIn("db_file_cur.total_tokens = token_usage[\"total_tokens\"]", source)
self.assertIn('"input_tokens": token_usage["input_tokens"]', source)
self.assertIn('"output_tokens": token_usage["output_tokens"]', source)
def test_ingest_success_persists_word_count_and_vlm_tokens(self):
source = Path("src/api/routes/ingest.py").read_text(encoding="utf-8")
# 字数与 VLM token 也须落库(此前 word_count 恒为 0、vlm_total_tokens 从不写入)。
self.assertIn("db_file_cur.word_count = len(ctx.raw_content", source)
self.assertIn("db_file_cur.vlm_total_tokens = vlm_total_tokens", source)
def test_schema_sync_covers_vlm_total_tokens(self):
source = Path("src/database/schema_sync.py").read_text(encoding="utf-8")
# 兜底补列,保证既有库有 vlm_total_tokens,否则摄入落库会 ALTER 缺失列报错。
self.assertIn("vlm_total_tokens", source)
self.assertIn("ADD COLUMN vlm_total_tokens", source)
def test_schema_sync_covers_ingest_mode_and_cached_tokens(self):
source = Path("src/database/schema_sync.py").read_text(encoding="utf-8")
self.assertIn("ADD COLUMN cached_input_tokens", source)
self.assertIn("ADD COLUMN ingest_mode", source)
def test_ingest_success_persists_route_and_cache_stats(self):
source = Path("src/api/routes/ingest.py").read_text(encoding="utf-8")
self.assertIn("db_file_cur.cached_input_tokens = cached_input_tokens", source)
self.assertIn("db_file_cur.ingest_mode =", source)
def test_egress_resets_ingest_derived_stats(self):
# 摄出必须清空派生统计,否则列表按 token/字数排序时残留旧值会把空文件顶到前面。
source = Path("src/api/routes/ingest.py").read_text(encoding="utf-8")
self.assertIn("db_f.total_tokens = 0", source)
self.assertIn("db_f.word_count = 0", source)
self.assertIn("db_f.ingest_mode = None", source)
def test_coverage_enforced_in_planner_not_supplement_round(self):
# 覆盖校验前移到 Planner 重试回路,事后补充轮已删除(含其专用的合并函数)。
source = Path("src/api/routes/ingest.py").read_text(encoding="utf-8")
self.assertIn("def _check_chunk_coverage", source)
self.assertIn("未认领块", source)
self.assertIn("应当新增对应主题的页面来承接", source) # 允许新增页面
self.assertNotIn("_phase2_5_supplement", source)
self.assertNotIn("_merge_generated_pages", source)
self.assertNotIn("warmup_results", source) # 预热已按实测结论移除
def test_sources_synthesized_from_downstream_pages(self):
# sources 延后合成:从并发批次剔除 sources,下游写完后据成品页合成、slug 由文件名确定性生成。
source = Path("src/api/routes/ingest.py").read_text(encoding="utf-8")
self.assertIn("async def _phase2_6_synthesize_sources", source)
self.assertIn("def _format_downstream_digest", source)
self.assertIn("def _sources_slug_for_file", source)
self.assertIn("if not _is_sources_page(p)", source) # _phase2_write 剔除 sources
self.assertIn("synthesis=True", source) # sources 走合成分支
def test_file_list_exposes_overall_token_including_vlm(self):
source = Path("src/api/routes/files.py").read_text(encoding="utf-8")
self.assertIn("overall_total_tokens", source)
self.assertIn("vlm_total_tokens", source)
def test_ingest_logs_llm_vlm_and_overall_token_breakdown(self):
source = Path("src/api/routes/ingest.py").read_text(encoding="utf-8")
self.assertIn("get_last_extract_stats", source)
self.assertIn("[IngestTokenUsage] parse_stage", source)
self.assertIn("[IngestTokenUsage] final_summary", source)
self.assertIn("overall_total_tokens", source)
self.assertIn("vlm_total_tokens", source)
def test_file_list_exposes_token_breakdown_without_removing_total(self):
source = Path("src/api/routes/files.py").read_text(encoding="utf-8")
self.assertIn('"total_tokens": db_file.total_tokens or 0', source)
self.assertIn('"input_tokens": db_file.input_tokens or 0', source)
self.assertIn('"output_tokens": db_file.output_tokens or 0', source)
def test_startup_syncs_existing_wiki_file_schema(self):
source = Path("main.py").read_text(encoding="utf-8")
self.assertIn("ensure_wiki_schema", source)
self.assertIn("await ensure_wiki_schema()", source)
if __name__ == "__main__":
unittest.main()
from pathlib import Path
import ast
import unittest
class UploadWordCountStaticTest(unittest.TestCase):
def test_upload_does_not_extract_text_or_run_vlm(self):
source = Path("src/api/routes/files.py").read_text(encoding="utf-8")
tree = ast.parse(source)
upload_fn = next(
node for node in tree.body
if isinstance(node, ast.AsyncFunctionDef) and node.name == "upload_file_chunk"
)
upload_source = ast.get_source_segment(source, upload_fn) or ""
self.assertNotIn("extract_text_from_file", upload_source)
self.assertNotIn("_load_pdf", upload_source)
self.assertIn("word_count = 0", upload_source)
self.assertIn('db_file.status = "Pending"', upload_source)
if __name__ == "__main__":
unittest.main()
from pathlib import Path
import unittest
RAG_PAGE = Path("frontend/src/app/rag/page.tsx")
RAG_API = Path("frontend/src/lib/rag-api.ts")
class RagChatStaticTest(unittest.TestCase):
def test_clear_history_does_not_enter_chat_loading_state(self):
source = RAG_PAGE.read_text(encoding="utf-8")
clear_start = source.index("const clearHistoryV2 = async () => {")
clear_end = source.index("const openSourcePreview", clear_start)
clear_block = source[clear_start:clear_end]
self.assertNotIn("runAction", clear_block)
self.assertIn("setLoading(false)", clear_block)
self.assertIn("setMessages([])", clear_block)
self.assertIn("const sessionToClear = sessionId", clear_block)
self.assertIn("clearRagHistory(sessionToClear)", clear_block)
def test_aborted_rag_stream_is_not_rendered_as_an_error_message(self):
source = RAG_API.read_text(encoding="utf-8")
self.assertIn('error.name === "AbortError"', source)
self.assertIn("return;", source[source.index('error.name === "AbortError"'):])
def test_rag_reasoning_steps_render_elapsed_time_per_step(self):
source = RAG_PAGE.read_text(encoding="utf-8")
self.assertIn("function formatElapsedSeconds", source)
self.assertIn("time: formatElapsedSeconds(step.elapsed_ms)", source)
self.assertIn("`耗时 ${", source)
if __name__ == "__main__":
unittest.main()
from pathlib import Path
import unittest
class WikiUploadPreviewStaticTest(unittest.TestCase):
def setUp(self):
self.source = Path("frontend/src/app/page.tsx").read_text(encoding="utf-8")
def test_ppt_preview_uses_controlled_state_not_direct_iframe(self):
self.assertIn("const canDirectIframePreview", self.source)
self.assertIn('return lowerName.endsWith(".pdf");', self.source)
self.assertIn("预览 PDF 尚未生成", self.source)
self.assertIn("previewStatus", self.source)
def test_upload_modal_distinguishes_file_saved_from_processing_done(self):
self.assertIn("保存中", self.source)
self.assertIn("已保存到文件库", self.source)
self.assertNotIn("稍后可在列表中发起摄入", self.source)
if __name__ == "__main__":
unittest.main()
"""rebuild_index 的分组契约。
注意:`src.tools.wiki_tools` 可以直接导入,不需要给 agentscope 打桩。
"""
import os
import importlib.util
import sys
import tempfile
import types
import unittest
from pathlib import Path
import frontmatter
from src.tools import wiki_tools
from src.utils.ingest_contract import load_ingest_contract
agentscope_tool = sys.modules.setdefault("agentscope.tool", types.ModuleType("agentscope.tool"))
agentscope_tool.ToolResponse = object
agentscope_message = sys.modules.setdefault("agentscope.message", types.ModuleType("agentscope.message"))
agentscope_message.TextBlock = object
_SPEC = importlib.util.spec_from_file_location(
"wiki_tools_contract_test_module",
Path("src/tools/wiki_tools.py"),
)
wiki_tools = importlib.util.module_from_spec(_SPEC)
assert _SPEC.loader is not None
_SPEC.loader.exec_module(wiki_tools)
def _write_page(wiki_dir: Path, folder: str, slug: str, page_type: str) -> None:
path = wiki_dir / folder / f"{slug}.md"
path.parent.mkdir(parents=True, exist_ok=True)
post = frontmatter.Post("正文", type=page_type, title=slug, series="测试", brand=["问界"])
with path.open("w", encoding="utf-8") as handle:
frontmatter.dump(post, handle)
class RebuildIndexContractTest(unittest.TestCase):
def test_wiki_tools_has_no_type_or_flat_sources_compatibility(self):
source = Path("src/tools/wiki_tools.py").read_text(encoding="utf-8")
class RebuildIndexGroupingTest(unittest.TestCase):
def test_singular_alias_groups_with_canonical_type(self):
"""单数别名(product)与规范名(products)必须归进同一分组,不能分裂成两组。
self.assertNotIn("_INDEX_TYPE_ALIAS", source)
self.assertNotIn("_normalize_index_type", source)
self.assertNotIn("_read_local_file_direct", source)
def test_index_uses_contract_order_and_rejects_singular_type(self):
这是有意为之的设计:摄入时模型偶尔写单数,靠别名归一。
注意 troubleshooting 在契约里**本身就是单数**,是个例外,勿"顺手改成复数"。
"""
with tempfile.TemporaryDirectory() as temp_dir:
wiki_dir = Path(temp_dir)
for folder, slug, page_type in (
("products", "plural", "products"),
("product", "singular", "product"),
("troubleshootings", "repair", "troubleshootings"),
):
path = wiki_dir / folder / f"{slug}.md"
path.parent.mkdir(parents=True, exist_ok=True)
post = frontmatter.Post("正文", type=page_type, title=slug, series="测试", brand=["问界"])
with path.open("w", encoding="utf-8") as handle:
frontmatter.dump(post, handle)
_write_page(wiki_dir, "products", "plural", "products")
_write_page(wiki_dir, "products", "singular", "product")
_write_page(wiki_dir, "troubleshooting", "repair", "troubleshooting")
count = wiki_tools.rebuild_index(os.fspath(wiki_dir))
index = (wiki_dir / "index.md").read_text(encoding="utf-8")
self.assertEqual(count, 3)
self.assertIn("## 产品(products/)", index)
self.assertIn("## 系统排障(troubleshootings/)", index)
self.assertIn("## 系统排障(troubleshooting/)", index)
self.assertIn("[[plural]]", index)
self.assertIn("[[singular]]", index)
self.assertNotIn("## 未分类", index, "合法 type 不该掉进未分类")
self.assertLess(
index.index("## 产品"), index.index("## 系统排障"),
"分组顺序应遵循 _INDEX_TYPE_GROUPS 的声明顺序",
)
def test_unknown_type_falls_into_uncategorized(self):
"""契约里没有的 type 要掉进「未分类」,而不是被静默塞进某个正常分组。"""
with tempfile.TemporaryDirectory() as temp_dir:
wiki_dir = Path(temp_dir)
_write_page(wiki_dir, "weird", "odd", "troubleshootings") # 复数形式不在契约里
wiki_tools.rebuild_index(os.fspath(wiki_dir))
index = (wiki_dir / "index.md").read_text(encoding="utf-8")
self.assertIn("## 未分类", index)
self.assertLess(index.index("## 产品"), index.index("## 系统排障"))
self.assertFalse(hasattr(wiki_tools, "_INDEX_TYPE_ALIAS"))
self.assertIn("[[odd]]", index)
class TypeTableConsistencyTest(unittest.TestCase):
def test_index_groups_match_contract_canonical_types(self):
"""wiki_tools 的 index 分组表与 ingest 契约的 canonical types 必须一一对应。
这两处各自维护了一份 type 表(wiki_tools._INDEX_TYPE_GROUPS/_INDEX_TYPE_ALIAS
vs ingest_contract.type_aliases)。一旦漂移,index.md 的分组与 lint 的校验就会
互相打架(页面通过 lint 却在 index 里掉进未分类,或反之)。本用例是那道护栏。
"""
contract_canonical = set(load_ingest_contract().type_aliases.values())
index_group_keys = {key for key, _heading in wiki_tools._INDEX_TYPE_GROUPS}
self.assertEqual(
index_group_keys,
contract_canonical,
"index 分组与契约 canonical types 已漂移:"
f"仅契约有={sorted(contract_canonical - index_group_keys)},"
f"仅 index 有={sorted(index_group_keys - contract_canonical)}",
)
def test_alias_normalization_agrees_with_contract(self):
"""对契约认识的每个别名,wiki_tools 的归一结果必须与契约一致。"""
contract = load_ingest_contract()
for raw, canonical in contract.type_aliases.items():
with self.subTest(raw=raw):
self.assertEqual(
wiki_tools._normalize_index_type(raw),
canonical,
f"别名 {raw!r} 在 wiki_tools 与契约中归一结果不同",
)
if __name__ == "__main__":
......
import sys
import types
import unittest
from importlib.machinery import ModuleSpec
from types import SimpleNamespace
"""llm_tracker 的 usage 归一化与日志契约。
agentscope_stub = types.ModuleType("agentscope")
agentscope_stub.__spec__ = ModuleSpec("agentscope", loader=None)
agentscope_stub.init = lambda: None
sys.modules["agentscope"] = agentscope_stub
注意:`src.utils.llm_tracker` 可以直接导入,**不需要给 agentscope/config/llm_models 打桩**。
本文件早先在模块导入时用 `sys.modules[...] = 假模块` 打桩且从不还原,污染同进程内的其它
测试模块(`config` 会变成只有 3 个属性的桩)。桩已全部删除;若将来确需隔离依赖,请用
`unittest.mock.patch.dict(sys.modules, ...)` 这类出作用域自动还原的方式。
"""
formatter_stub = types.ModuleType("agentscope.formatter")
formatter_stub.__spec__ = ModuleSpec("agentscope.formatter", loader=None)
formatter_stub.DashScopeChatFormatter = type("DashScopeChatFormatter", (), {})
formatter_stub.OpenAIChatFormatter = type(
"OpenAIChatFormatter",
(),
{"_format": lambda self, msgs: msgs},
)
sys.modules["agentscope.formatter"] = formatter_stub
message_stub = types.ModuleType("agentscope.message")
message_stub.__spec__ = ModuleSpec("agentscope.message", loader=None)
class _Msg:
def __init__(self, name=None, content=None, role=None, metadata=None, timestamp=None, invocation_id=None):
self.name = name
self.content = content
self.role = role
self.metadata = metadata
self.timestamp = timestamp
self.invocation_id = invocation_id
self.id = None
message_stub.Msg = _Msg
sys.modules["agentscope.message"] = message_stub
model_stub = types.ModuleType("agentscope.model")
model_stub.__spec__ = ModuleSpec("agentscope.model", loader=None)
model_stub.DashScopeChatModel = type("DashScopeChatModel", (), {})
model_stub.OpenAIChatModel = type("OpenAIChatModel", (), {})
sys.modules["agentscope.model"] = model_stub
config_stub = types.ModuleType("config")
config_stub.__spec__ = ModuleSpec("config", loader=None)
config_stub.SKILLS_DIR = "skills"
config_stub.API_KEY = "test-key"
config_stub.BASE_DIR = "."
sys.modules["config"] = config_stub
llm_models_stub = types.ModuleType("src.utils.llm_models")
llm_models_stub.__spec__ = ModuleSpec("src.utils.llm_models", loader=None)
llm_models_stub.DASHSCOPE_CLIENT = "dashscope"
llm_models_stub.OPENAI_COMPATIBLE_CLIENT = "openai_compatible"
llm_models_stub.build_model_init_kwargs = lambda *_args, **_kwargs: {}
llm_models_stub.extract_thinking_content = lambda *_args, **_kwargs: ""
llm_models_stub.formatter_name_for_model = lambda *_args, **_kwargs: "dashscope"
llm_models_stub.get_chat_model_profile = lambda *_args, **_kwargs: SimpleNamespace(client="dashscope")
sys.modules["src.utils.llm_models"] = llm_models_stub
import unittest
from types import SimpleNamespace
from src.utils.llm_tracker import (
add_usage_tokens,
......@@ -72,12 +20,39 @@ from src.utils.llm_tracker import (
class LlmTrackerUsageTest(unittest.TestCase):
def test_extract_usage_tokens_accepts_prompt_completion_field_names(self):
"""OpenAI 口径的 prompt_tokens/completion_tokens 要能归一到统一字段名。"""
usage = SimpleNamespace(prompt_tokens=12, completion_tokens=3, total_tokens=20)
self.assertEqual(
extract_usage_tokens(usage),
{"input_tokens": 12, "output_tokens": 3, "total_tokens": 20},
{"input_tokens": 12, "output_tokens": 3, "total_tokens": 20, "cached_input_tokens": 0},
)
def test_extract_usage_tokens_derives_total_when_absent(self):
usage = SimpleNamespace(input_tokens=5, output_tokens=7)
tokens = extract_usage_tokens(usage)
self.assertEqual(tokens["total_tokens"], 12)
def test_extract_usage_tokens_reads_nested_cached_tokens(self):
"""命中缓存量藏在 prompt_tokens_details.cached_tokens(DashScope/OpenAI 兼容口径)。
agentscope 会把原始 usage 包成 ChatUsage 并塞进 .metadata,故两处都要能找到。
"""
raw = SimpleNamespace(
prompt_tokens=100,
completion_tokens=10,
prompt_tokens_details=SimpleNamespace(cached_tokens=64),
)
self.assertEqual(extract_usage_tokens(raw)["cached_input_tokens"], 64)
wrapped = SimpleNamespace(input_tokens=100, output_tokens=10, metadata=raw)
self.assertEqual(extract_usage_tokens(wrapped)["cached_input_tokens"], 64)
def test_extract_usage_tokens_is_idempotent(self):
"""自身输出再喂一次结果不变——add_usage_tokens 会二次抽取,必须幂等。"""
once = extract_usage_tokens(SimpleNamespace(input_tokens=5, output_tokens=7))
self.assertEqual(extract_usage_tokens(once), once)
def test_add_usage_tokens_accumulates_input_output_and_total(self):
counter = new_token_counter()
......@@ -87,9 +62,18 @@ class LlmTrackerUsageTest(unittest.TestCase):
self.assertEqual(
counter,
{"input_tokens": 16, "output_tokens": 20, "total_tokens": 36},
{"input_tokens": 16, "output_tokens": 20, "total_tokens": 36, "cached_input_tokens": 0},
)
def test_add_usage_tokens_accumulates_cached_tokens(self):
counter = new_token_counter()
add_usage_tokens(counter, {"input_tokens": 100, "output_tokens": 5, "cached_input_tokens": 64})
add_usage_tokens(counter, {"input_tokens": 100, "output_tokens": 5, "cached_input_tokens": 96})
self.assertEqual(counter["cached_input_tokens"], 160)
self.assertEqual(counter["input_tokens"], 200, "cached 是 input 的子集,不得重复计入 input")
def test_log_usage_tokens_includes_call_and_task_breakdown(self):
counter = new_token_counter()
ctx_token = current_llm_call_context.set({"phase": "writer", "page_path": "ware/wiki/a.md"})
......@@ -113,5 +97,14 @@ class LlmTrackerUsageTest(unittest.TestCase):
self.assertIn("phase=writer", line)
class LlmTrackerModuleHygieneTest(unittest.TestCase):
def test_real_config_is_still_importable(self):
"""锁死:导入本模块不得把 `config` 换成残缺的桩。"""
import config
self.assertTrue(hasattr(config, "QUERY_MODEL_NAME"), "config 被替换成了桩")
self.assertIsNotNone(getattr(config, "__file__", None), "config 不是真实文件模块")
if __name__ == "__main__":
unittest.main()
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!