test_api_analysis.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. #!/usr/bin/env python3
  2. """
  3. 测试当前API的真实输出,分析数据结构以确定是否能满足需求
  4. """
  5. import requests
  6. import json
  7. from datetime import datetime
  8. def test_current_api():
  9. """测试当前的对话历史API"""
  10. print("=" * 60)
  11. print("测试当前API的真实输出")
  12. print("=" * 60)
  13. # API URL
  14. api_url = "http://localhost:8084/api/v0/react/users/wang10/conversations/wang10:20250717211620915"
  15. try:
  16. print(f"📡 调用API: {api_url}")
  17. response = requests.get(api_url, timeout=30)
  18. print(f"📊 状态码: {response.status_code}")
  19. print(f"📄 响应头: {dict(response.headers)}")
  20. if response.status_code == 200:
  21. data = response.json()
  22. print(f"✅ API调用成功")
  23. print(f"📋 响应数据结构分析:")
  24. analyze_response_structure(data)
  25. # 分析消息结构
  26. if 'data' in data and 'messages' in data['data']:
  27. analyze_messages(data['data']['messages'])
  28. # 保存完整响应到文件
  29. with open('api_response_full.json', 'w', encoding='utf-8') as f:
  30. json.dump(data, f, ensure_ascii=False, indent=2)
  31. print(f"💾 完整响应已保存到 api_response_full.json")
  32. else:
  33. print(f"❌ API调用失败: {response.status_code}")
  34. print(f"📄 错误响应: {response.text}")
  35. except requests.exceptions.RequestException as e:
  36. print(f"❌ 网络请求失败: {e}")
  37. except Exception as e:
  38. print(f"❌ 其他错误: {e}")
  39. def analyze_response_structure(data):
  40. """分析响应数据结构"""
  41. print(f" 🔍 顶级键: {list(data.keys())}")
  42. if 'data' in data:
  43. data_section = data['data']
  44. print(f" 🔍 data部分键: {list(data_section.keys())}")
  45. if 'message_count' in data_section:
  46. print(f" 📊 消息总数: {data_section['message_count']}")
  47. if 'messages' in data_section:
  48. messages = data_section['messages']
  49. print(f" 📊 消息列表长度: {len(messages)}")
  50. def analyze_messages(messages):
  51. """详细分析消息结构"""
  52. print(f"\n📨 消息详细分析:")
  53. print(f" 总消息数: {len(messages)}")
  54. # 统计消息类型
  55. message_types = {}
  56. has_id_count = 0
  57. has_timestamp_count = 0
  58. has_tool_calls_count = 0
  59. print(f"\n 前5条消息样例:")
  60. for i, msg in enumerate(messages[:5]):
  61. print(f" 消息 {i+1}:")
  62. print(f" 类型: {msg.get('type', 'unknown')}")
  63. print(f" 内容长度: {len(str(msg.get('content', '')))}")
  64. print(f" 是否有ID: {'id' in msg}")
  65. print(f" 是否有时间戳: {'timestamp' in msg}")
  66. print(f" 是否有工具调用: {'tool_calls' in msg}")
  67. if 'id' in msg:
  68. print(f" ID值: {msg['id']}")
  69. if 'timestamp' in msg:
  70. print(f" 时间戳: {msg['timestamp']}")
  71. if 'tool_calls' in msg and msg['tool_calls']:
  72. print(f" 工具调用数量: {len(msg['tool_calls']) if isinstance(msg['tool_calls'], list) else 'non-list'}")
  73. print(f" 所有字段: {list(msg.keys())}")
  74. print()
  75. # 统计所有消息的类型和字段
  76. for msg in messages:
  77. msg_type = msg.get('type', 'unknown')
  78. message_types[msg_type] = message_types.get(msg_type, 0) + 1
  79. if 'id' in msg:
  80. has_id_count += 1
  81. if 'timestamp' in msg:
  82. has_timestamp_count += 1
  83. if 'tool_calls' in msg:
  84. has_tool_calls_count += 1
  85. print(f" 📊 消息类型统计: {message_types}")
  86. print(f" 📊 包含ID的消息数: {has_id_count}/{len(messages)}")
  87. print(f" 📊 包含时间戳的消息数: {has_timestamp_count}/{len(messages)}")
  88. print(f" 📊 包含工具调用的消息数: {has_tool_calls_count}/{len(messages)}")
  89. def test_with_parameters():
  90. """测试带参数的API调用(虽然可能不支持)"""
  91. print("\n" + "=" * 60)
  92. print("测试带参数的API调用")
  93. print("=" * 60)
  94. base_url = "http://localhost:8084/api/v0/react/users/wang10/conversations/wang10:20250717211620915"
  95. test_params = [
  96. {},
  97. {"include_tools": "false"},
  98. {"simplified": "true"},
  99. {"include_tools": "false", "simplified": "true"}
  100. ]
  101. for i, params in enumerate(test_params):
  102. print(f"\n🧪 测试 {i+1}: 参数 = {params}")
  103. try:
  104. response = requests.get(base_url, params=params, timeout=10)
  105. print(f" 状态码: {response.status_code}")
  106. if response.status_code == 200:
  107. data = response.json()
  108. message_count = data.get('data', {}).get('message_count', 0)
  109. print(f" 消息数量: {message_count}")
  110. # 检查是否有参数相关的字段
  111. data_section = data.get('data', {})
  112. if 'mode' in data_section:
  113. print(f" 模式: {data_section['mode']}")
  114. if 'include_tools' in data_section:
  115. print(f" include_tools: {data_section['include_tools']}")
  116. if 'simplified' in data_section:
  117. print(f" simplified: {data_section['simplified']}")
  118. else:
  119. print(f" 失败: {response.text[:100]}")
  120. except Exception as e:
  121. print(f" 错误: {e}")
  122. def analyze_feasibility():
  123. """基于实际数据分析可行性"""
  124. print("\n" + "=" * 60)
  125. print("需求可行性分析")
  126. print("=" * 60)
  127. try:
  128. with open('api_response_full.json', 'r', encoding='utf-8') as f:
  129. data = json.load(f)
  130. messages = data.get('data', {}).get('messages', [])
  131. print(f"📋 基于 {len(messages)} 条消息的分析:")
  132. # 需求1: 过滤消息类型
  133. human_messages = [msg for msg in messages if msg.get('type') == 'human']
  134. ai_messages = [msg for msg in messages if msg.get('type') == 'ai']
  135. tool_messages = [msg for msg in messages if msg.get('type') == 'tool']
  136. print(f"\n🎯 需求1 - 消息过滤:")
  137. print(f" Human消息: {len(human_messages)} 条")
  138. print(f" AI消息: {len(ai_messages)} 条")
  139. print(f" Tool消息: {len(tool_messages)} 条")
  140. # 分析AI消息中哪些有实际内容
  141. ai_with_content = [msg for msg in ai_messages if msg.get('content', '').strip()]
  142. ai_with_tools = [msg for msg in ai_messages if msg.get('tool_calls')]
  143. print(f" 有内容的AI消息: {len(ai_with_content)} 条")
  144. print(f" 有工具调用的AI消息: {len(ai_with_tools)} 条")
  145. # 需求2: 时间戳分析
  146. print(f"\n🕐 需求2 - 时间戳分析:")
  147. messages_with_timestamp = [msg for msg in messages if 'timestamp' in msg]
  148. messages_with_id = [msg for msg in messages if 'id' in msg]
  149. print(f" 有时间戳的消息: {len(messages_with_timestamp)} 条")
  150. print(f" 有ID的消息: {len(messages_with_id)} 条")
  151. if messages_with_timestamp:
  152. sample_timestamp = messages_with_timestamp[0]['timestamp']
  153. print(f" 时间戳样例: {sample_timestamp}")
  154. if messages_with_id:
  155. sample_id = messages_with_id[0]['id']
  156. print(f" ID样例: {sample_id}")
  157. # 可行性结论
  158. print(f"\n✅ 可行性结论:")
  159. print(f" 需求1 (消息过滤): {'✅ 可行' if human_messages and ai_with_content else '❌ 不可行'}")
  160. print(f" 需求2 (真实时间戳): {'✅ 可行' if messages_with_timestamp else '❌ 需要进一步分析'}")
  161. except FileNotFoundError:
  162. print("❌ 请先运行主测试获取数据")
  163. except Exception as e:
  164. print(f"❌ 分析失败: {e}")
  165. if __name__ == "__main__":
  166. print(f"🚀 开始API分析测试 - {datetime.now()}")
  167. # 测试当前API
  168. test_current_api()
  169. # 测试参数支持
  170. test_with_parameters()
  171. # 分析可行性
  172. analyze_feasibility()
  173. print(f"\n🏁 测试完成 - {datetime.now()}")