run_comparison.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. #!/usr/bin/env python3
  2. """
  3. 海事问答智能体对比实验
  4. RAG 模式 vs Wiki 模式
  5. """
  6. import json
  7. import time
  8. import sys
  9. sys.path.insert(0, '/home/67/knowledge/maritime')
  10. sys.path.insert(0, '/home/67/lambdagentpaas')
  11. from search_engine import search
  12. from lambdagent.providers import create_provider
  13. # 初始化 LLM
  14. provider = create_provider('ollama', model='qwen2.5:32b', timeout=600)
  15. SEP = '=' * 70
  16. LINE = '-' * 70
  17. # RAG 模式
  18. def rag_answer(question, top_k=5):
  19. t0 = time.time()
  20. results = search(question, top_k=top_k)
  21. context_parts = []
  22. for i, r in enumerate(results):
  23. context_parts.append(f'[doc{i+1}: {r["source"]}]\n{r["text"]}')
  24. context = '\n\n'.join(context_parts)
  25. prompt = f"""你是一个海事领域问答助手。请严格基于以下参考文档回答问题。
  26. 如果文档中没有相关信息,请说明"文档中未找到相关信息"。
  27. 回答要具体,引用文档中的原文,标注来源 [来源: 文件名]。
  28. ## 参考文档
  29. {context}
  30. ## 问题
  31. {question}
  32. ## 回答"""
  33. answer = provider.chat([{'role': 'user', 'content': prompt}])
  34. elapsed = time.time() - t0
  35. return {
  36. 'answer': answer,
  37. 'sources': [r['source'] for r in results],
  38. 'elapsed': round(elapsed, 1),
  39. 'chunks_used': len(results),
  40. }
  41. # Wiki 模式
  42. WIKI_DIR = '/home/67/lambdagentpaas/agentexample/qaagent67wiki/wiki'
  43. def wiki_answer(question, top_k=5):
  44. t0 = time.time()
  45. from pathlib import Path
  46. wiki_path = Path(WIKI_DIR)
  47. # Step 1: 检查 wiki 中是否有相关页面
  48. wiki_pages = []
  49. for subdir in ['sources', 'entities', 'topics', 'analyses']:
  50. d = wiki_path / subdir
  51. if d.exists():
  52. for f in d.glob('*.md'):
  53. content = f.read_text(encoding='utf-8')
  54. q_chars = set(question)
  55. match_score = sum(1 for c in q_chars if c in content)
  56. if match_score > len(question) * 0.3:
  57. wiki_pages.append({
  58. 'path': str(f),
  59. 'name': f.stem,
  60. 'content': content[:1500],
  61. 'score': match_score,
  62. })
  63. wiki_pages.sort(key=lambda x: x['score'], reverse=True)
  64. wiki_pages = wiki_pages[:3]
  65. if wiki_pages:
  66. wiki_context = '\n\n'.join([
  67. f'[Wiki: {p["name"]}]\n{p["content"]}'
  68. for p in wiki_pages
  69. ])
  70. source_type = 'wiki'
  71. else:
  72. results = search(question, top_k=top_k)
  73. compile_context = '\n\n'.join([
  74. f'[doc: {r["source"]}]\n{r["text"]}'
  75. for r in results
  76. ])
  77. compile_prompt = f"""请阅读以下文档片段,提炼出与问题相关的核心知识点。
  78. 用结构化的方式组织,标注来源。这将作为 wiki 知识页面保存。
  79. 文档:
  80. {compile_context}
  81. 问题: {question}
  82. 请输出结构化的知识摘要:"""
  83. compiled = provider.chat([{'role': 'user', 'content': compile_prompt}])
  84. wiki_context = compiled
  85. source_type = 'compiled'
  86. # 保存到 wiki analyses 目录
  87. safe_name = question[:30].replace('/', '_').replace(' ', '_')
  88. analysis_path = wiki_path / 'analyses' / f'{safe_name}.md'
  89. analysis_path.parent.mkdir(parents=True, exist_ok=True)
  90. with open(analysis_path, 'w', encoding='utf-8') as f:
  91. f.write(f'# {question}\n\n{compiled}\n')
  92. answer_prompt = f"""你是一个海事领域 wiki 知识库问答助手。
  93. 基于以下已编译的 wiki 知识回答问题。回答要具体,标注来源。
  94. ## Wiki 知识
  95. {wiki_context}
  96. ## 问题
  97. {question}
  98. ## 回答"""
  99. answer = provider.chat([{'role': 'user', 'content': answer_prompt}])
  100. elapsed = time.time() - t0
  101. return {
  102. 'answer': answer,
  103. 'source_type': source_type,
  104. 'wiki_pages_used': len(wiki_pages),
  105. 'elapsed': round(elapsed, 1),
  106. }
  107. # 运行对比
  108. def run_comparison():
  109. with open('/home/67/knowledge/maritime/test_questions.json') as f:
  110. data = json.load(f)
  111. questions = data['questions']
  112. results = []
  113. print(SEP)
  114. print(' Maritime QA Comparison: RAG vs Wiki')
  115. print(SEP)
  116. for q in questions:
  117. print(f'\n{LINE}')
  118. print(f'Q{q["id"]} [{q["difficulty"]}] {q["question"]}')
  119. print(LINE)
  120. # RAG
  121. print('\n[RAG] answering...')
  122. try:
  123. rag = rag_answer(q['question'])
  124. print(f' time: {rag["elapsed"]}s | chunks: {rag["chunks_used"]}')
  125. print(f' sources: {", ".join(rag["sources"][:3])}')
  126. ans_preview = rag["answer"][:300]
  127. print(f' answer: {ans_preview}{"..." if len(rag["answer"]) > 300 else ""}')
  128. except Exception as e:
  129. rag = {'answer': f'ERROR: {e}', 'elapsed': 0}
  130. print(f' ERROR: {e}')
  131. # Wiki
  132. print('\n[Wiki] answering...')
  133. try:
  134. wiki = wiki_answer(q['question'])
  135. print(f' time: {wiki["elapsed"]}s | source: {wiki.get("source_type", "wiki")}')
  136. ans_preview = wiki["answer"][:300]
  137. print(f' answer: {ans_preview}{"..." if len(wiki["answer"]) > 300 else ""}')
  138. except Exception as e:
  139. wiki = {'answer': f'ERROR: {e}', 'elapsed': 0}
  140. print(f' ERROR: {e}')
  141. results.append({
  142. 'question': q,
  143. 'rag': rag,
  144. 'wiki': wiki,
  145. })
  146. out_path = '/home/67/knowledge/maritime/comparison_results.json'
  147. with open(out_path, 'w', encoding='utf-8') as f:
  148. json.dump(results, f, ensure_ascii=False, indent=2)
  149. print(f'\n{SEP}')
  150. print(f'Done! Results saved to: {out_path}')
  151. print(f'\nSummary:')
  152. print(f' {"Question":<40} {"RAG":>8} {"Wiki":>8}')
  153. for r in results:
  154. q_text = r['question']['question'][:36]
  155. print(f' {q_text:<40} {r["rag"]["elapsed"]:>6.1f}s {r["wiki"]["elapsed"]:>6.1f}s')
  156. if __name__ == '__main__':
  157. run_comparison()