test_rag_monitor.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. RAG监控装饰器使用示例和测试脚本
  5. 展示如何使用 rag_monitor 装饰器监控RAG链路
  6. """
  7. import sys
  8. import os
  9. import time
  10. import json
  11. import asyncio
  12. from pathlib import Path
  13. project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  14. from foundation.observability.monitoring.rag import rag_monitor
  15. from foundation.observability.logger.loggering import review_logger as logger
  16. # ========== 示例1: 同步函数监控 ==========
  17. @rag_monitor.monitor_step(
  18. step_name="example_sync_query_extract",
  19. capture_input=True,
  20. capture_output=True
  21. )
  22. def example_query_extract(content: str):
  23. """示例:查询提取函数"""
  24. logger.info(f"正在提取查询,内容长度: {len(content)}")
  25. time.sleep(0.5) # 模拟处理时间
  26. # 模拟提取结果
  27. return [
  28. {"query": "安全生产条件", "entity": "安全"},
  29. {"query": "施工管理制度", "entity": "施工"}
  30. ]
  31. @rag_monitor.monitor_step(
  32. step_name="example_sync_vector_search",
  33. capture_input=True,
  34. capture_output=True,
  35. output_transform=lambda x: { # 只保留关键信息
  36. "results_count": len(x),
  37. "has_results": bool(x)
  38. }
  39. )
  40. def example_vector_search(query_pairs: list):
  41. """示例:向量检索函数"""
  42. logger.info(f"正在进行向量检索,查询对数量: {len(query_pairs)}")
  43. time.sleep(1.0) # 模拟检索时间
  44. # 模拟检索结果
  45. results = []
  46. for pair in query_pairs:
  47. results.append({
  48. "query": pair["query"],
  49. "doc_id": f"doc_{hash(pair['query']) % 100}",
  50. "score": 0.85,
  51. "content": f"这是关于{pair['query']}的内容..."
  52. })
  53. return results
  54. # ========== 示例2: 异步函数监控 ==========
  55. @rag_monitor.monitor_step(
  56. step_name="example_async_rerank",
  57. capture_input=True,
  58. capture_output=True,
  59. input_transform=lambda x: { # 只记录输入统计信息
  60. "results_count": len(x["args"][0]) if x["args"] else 0
  61. }
  62. )
  63. async def example_async_rerank(results: list):
  64. """示例:异步重排序函数"""
  65. logger.info(f"正在进行重排序,结果数量: {len(results)}")
  66. await asyncio.sleep(0.8) # 模拟异步处理
  67. # 模拟重排序
  68. sorted_results = sorted(results, key=lambda x: x["score"], reverse=True)
  69. return sorted_results[:5] # 只返回前5个
  70. @rag_monitor.monitor_step(
  71. step_name="example_async_parent_enhance",
  72. capture_input=True,
  73. capture_output=True
  74. )
  75. async def example_async_parent_enhance(results: list):
  76. """示例:异步父文档增强函数"""
  77. logger.info(f"正在进行父文档增强,结果数量: {len(results)}")
  78. await asyncio.sleep(1.2) # 模拟异步处理
  79. # 模拟父文档增强
  80. enhanced = []
  81. for res in results:
  82. enhanced.append({
  83. **res,
  84. "parent_content": f"父文档内容: {res['content']}的完整上下文...",
  85. "enhanced": True
  86. })
  87. return enhanced
  88. # ========== 示例3: 完整的RAG链路测试 ==========
  89. def test_sync_rag_pipeline():
  90. """测试同步RAG链路"""
  91. print("\n" + "="*60)
  92. print("示例1: 同步RAG链路监控")
  93. print("="*60)
  94. # 开始追踪会话
  95. trace_id = f"test_sync_{int(time.time() * 1000)}"
  96. rag_monitor.start_trace(trace_id, metadata={
  97. "test_type": "sync",
  98. "description": "同步RAG链路测试"
  99. })
  100. try:
  101. # Step 1: 查询提取
  102. query_content = "请检查施工方案中的安全生产条件和施工管理制度是否符合规范要求。"
  103. query_pairs = example_query_extract(query_content)
  104. print(f"✅ 查询提取完成,提取到 {len(query_pairs)} 个查询对")
  105. # Step 2: 向量检索
  106. search_results = example_vector_search(query_pairs)
  107. print(f"✅ 向量检索完成,找到 {len(search_results)} 个结果")
  108. print(f"\n✅ 同步RAG链路测试完成")
  109. finally:
  110. # 结束追踪并保存
  111. trace_data = rag_monitor.end_trace(trace_id)
  112. print(f"\n📊 追踪数据已保存: temp/rag_monitoring/{trace_id}.json")
  113. print(f"⏱️ 总耗时: {trace_data['total_duration']}秒")
  114. print(f"📝 步骤数量: {len(trace_data['steps'])}")
  115. async def test_async_rag_pipeline():
  116. """测试异步RAG链路"""
  117. print("\n" + "="*60)
  118. print("示例2: 异步RAG链路监控")
  119. print("="*60)
  120. # 开始追踪会话
  121. trace_id = f"test_async_{int(time.time() * 1000)}"
  122. rag_monitor.start_trace(trace_id, metadata={
  123. "test_type": "async",
  124. "description": "异步RAG链路测试"
  125. })
  126. try:
  127. # 模拟一些初始数据
  128. initial_results = [
  129. {"query": "安全", "doc_id": "doc_1", "score": 0.82, "content": "安全内容..."},
  130. {"query": "施工", "doc_id": "doc_2", "score": 0.91, "content": "施工内容..."},
  131. {"query": "管理", "doc_id": "doc_3", "score": 0.75, "content": "管理内容..."}
  132. ]
  133. # Step 1: 异步重排序
  134. reranked_results = await example_async_rerank(initial_results)
  135. print(f"✅ 重排序完成,保留前 {len(reranked_results)} 个结果")
  136. # Step 2: 异步父文档增强
  137. enhanced_results = await example_async_parent_enhance(reranked_results)
  138. print(f"✅ 父文档增强完成,增强了 {len(enhanced_results)} 个结果")
  139. print(f"\n✅ 异步RAG链路测试完成")
  140. finally:
  141. # 结束追踪并保存
  142. trace_data = rag_monitor.end_trace(trace_id)
  143. print(f"\n📊 追踪数据已保存: temp/rag_monitoring/{trace_id}.json")
  144. print(f"⏱️ 总耗时: {trace_data['total_duration']}秒")
  145. print(f"📝 步骤数量: {len(trace_data['steps'])}")
  146. def test_mixed_rag_pipeline():
  147. """测试混合(同步+异步)RAG链路"""
  148. print("\n" + "="*60)
  149. print("示例3: 混合RAG链路监控(同步+异步)")
  150. print("="*60)
  151. # 开始追踪会话
  152. trace_id = f"test_mixed_{int(time.time() * 1000)}"
  153. rag_monitor.start_trace(trace_id, metadata={
  154. "test_type": "mixed",
  155. "description": "混合RAG链路测试"
  156. })
  157. try:
  158. # Step 1: 同步查询提取
  159. query_content = "检查项目的环境保护措施和质量管理体系。"
  160. query_pairs = example_query_extract(query_content)
  161. print(f"✅ [同步] 查询提取完成")
  162. # Step 2: 同步向量检索
  163. search_results = example_vector_search(query_pairs)
  164. print(f"✅ [同步] 向量检索完成")
  165. # Step 3: 异步重排序
  166. async def async_part():
  167. reranked = await example_async_rerank(search_results)
  168. print(f"✅ [异步] 重排序完成")
  169. # Step 4: 异步父文档增强
  170. enhanced = await example_async_parent_enhance(reranked)
  171. print(f"✅ [异步] 父文档增强完成")
  172. return enhanced
  173. # 运行异步部分
  174. final_results = asyncio.run(async_part())
  175. print(f"\n✅ 混合RAG链路测试完成,最终得到 {len(final_results)} 个结果")
  176. finally:
  177. # 结束追踪并保存
  178. trace_data = rag_monitor.end_trace(trace_id)
  179. print(f"\n📊 追踪数据已保存: temp/rag_monitoring/{trace_id}.json")
  180. print(f"⏱️ 总耗时: {trace_data['total_duration']}秒")
  181. print(f"📝 步骤数量: {len(trace_data['steps'])}")
  182. # ========== 示例4: 自定义输入输出转换 ==========
  183. @rag_monitor.monitor_step(
  184. step_name="example_sensitive_data",
  185. capture_input=True,
  186. capture_output=True,
  187. input_transform=lambda x: {
  188. # 过滤敏感信息,只保留统计数据
  189. "user_id": "***", # 隐藏用户ID
  190. "data_length": len(str(x))
  191. },
  192. output_transform=lambda x: {
  193. # 只保留关键指标
  194. "success": x.get("success"),
  195. "count": x.get("count")
  196. }
  197. )
  198. def example_process_sensitive_data(user_id: str, data: dict):
  199. """示例:处理敏感数据(自定义转换)"""
  200. time.sleep(0.3)
  201. return {
  202. "success": True,
  203. "user_id": user_id,
  204. "count": len(data),
  205. "details": data # 这些详细信息不会被记录
  206. }
  207. def test_custom_transform():
  208. """测试自定义输入输出转换"""
  209. print("\n" + "="*60)
  210. print("示例4: 自定义输入输出转换(敏感数据保护)")
  211. print("="*60)
  212. trace_id = f"test_transform_{int(time.time() * 1000)}"
  213. rag_monitor.start_trace(trace_id, metadata={
  214. "test_type": "custom_transform"
  215. })
  216. try:
  217. result = example_process_sensitive_data(
  218. user_id="user_12345",
  219. data={"key1": "value1", "key2": "value2"}
  220. )
  221. print(f"✅ 处理完成,成功: {result['success']}")
  222. print(f"ℹ️ 敏感信息已被过滤,只记录统计数据")
  223. finally:
  224. trace_data = rag_monitor.end_trace(trace_id)
  225. print(f"\n📊 追踪数据已保存: temp/rag_monitoring/{trace_id}.json")
  226. # ========== 查看监控结果 ==========
  227. def view_trace_result(trace_id: str):
  228. """查看追踪结果"""
  229. file_path = Path("temp/rag_monitoring") / f"{trace_id}.json"
  230. if file_path.exists():
  231. print(f"\n📄 追踪结果: {trace_id}")
  232. print("="*60)
  233. with open(file_path, 'r', encoding='utf-8') as f:
  234. data = json.load(f)
  235. print(f"⏱️ 总耗时: {data.get('total_duration')}秒")
  236. print(f"📝 步骤数量: {len(data.get('steps', {}))}")
  237. print(f"\n步骤详情:")
  238. for step_name, step_data in data.get('steps', {}).items():
  239. print(f"\n [{step_data.get('status', 'unknown').upper()}] {step_name}")
  240. print(f" 函数: {step_data.get('function_name')}")
  241. print(f" 耗时: {step_data.get('duration')}秒")
  242. if step_data.get('status') == 'error':
  243. print(f" ❌ 错误: {step_data.get('error', {}).get('message')}")
  244. else:
  245. print(f"❌ 找不到追踪文件: {file_path}")
  246. # ========== 主函数 ==========
  247. def main():
  248. """运行所有测试示例"""
  249. print("\n" + "🚀 RAG监控装饰器测试 🚀".center(60, "="))
  250. try:
  251. # 示例1: 同步RAG链路
  252. test_sync_rag_pipeline()
  253. # 示例2: 异步RAG链路
  254. asyncio.run(test_async_rag_pipeline())
  255. # 示例3: 混合RAG链路
  256. test_mixed_rag_pipeline()
  257. # 示例4: 自定义转换
  258. test_custom_transform()
  259. print("\n" + "✅ 所有测试完成!".center(60, "="))
  260. print(f"\n💡 提示: 查看监控数据文件在: temp/rag_monitoring/")
  261. print(f"💡 提示: 每个trace_id对应一个JSON文件,包含完整的执行链路信息")
  262. except Exception as e:
  263. print(f"\n❌ 测试失败: {e}")
  264. import traceback
  265. traceback.print_exc()
  266. if __name__ == "__main__":
  267. main()