enhanced_redis_api.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. """
  2. enhanced_redis_api.py - 完整的Redis直接访问API
  3. 支持include_tools开关参数,可以控制是否包含工具调用信息
  4. """
  5. import redis
  6. import json
  7. from typing import List, Dict, Any, Optional
  8. from datetime import datetime
  9. import logging
  10. logger = logging.getLogger(__name__)
  11. def get_conversation_detail_from_redis(thread_id: str, include_tools: bool = False) -> Dict[str, Any]:
  12. """
  13. 直接从Redis获取对话详细信息
  14. Args:
  15. thread_id: 线程ID,格式为 user_id:timestamp
  16. include_tools: 是否包含工具调用信息
  17. - True: 返回所有消息(human/ai/tool/system)
  18. - False: 只返回human和ai消息,且清理ai消息中的工具调用信息
  19. Returns:
  20. 包含对话详细信息的字典
  21. """
  22. try:
  23. # 创建Redis连接
  24. redis_client = redis.Redis(host='localhost', port=6379, decode_responses=True)
  25. redis_client.ping()
  26. # 扫描该thread的所有checkpoint keys
  27. pattern = f"checkpoint:{thread_id}:*"
  28. logger.info(f"🔍 扫描模式: {pattern}, include_tools: {include_tools}")
  29. keys = []
  30. cursor = 0
  31. while True:
  32. cursor, batch = redis_client.scan(cursor=cursor, match=pattern, count=1000)
  33. keys.extend(batch)
  34. if cursor == 0:
  35. break
  36. logger.info(f"📋 找到 {len(keys)} 个keys")
  37. if not keys:
  38. redis_client.close()
  39. return {
  40. "success": False,
  41. "error": f"未找到对话 {thread_id}",
  42. "data": None
  43. }
  44. # 获取最新的checkpoint(按key排序,最大的是最新的)
  45. latest_key = max(keys)
  46. logger.info(f"🔍 使用最新key: {latest_key}")
  47. # 检查key类型并获取数据
  48. key_type = redis_client.type(latest_key)
  49. logger.info(f"🔍 Key类型: {key_type}")
  50. data = None
  51. if key_type == 'string':
  52. data = redis_client.get(latest_key)
  53. elif key_type == 'ReJSON-RL':
  54. # RedisJSON类型
  55. try:
  56. data = redis_client.execute_command('JSON.GET', latest_key)
  57. except Exception as json_error:
  58. logger.error(f"❌ JSON.GET 失败: {json_error}")
  59. redis_client.close()
  60. return {
  61. "success": False,
  62. "error": f"无法读取RedisJSON数据: {json_error}",
  63. "data": None
  64. }
  65. else:
  66. redis_client.close()
  67. return {
  68. "success": False,
  69. "error": f"不支持的key类型: {key_type}",
  70. "data": None
  71. }
  72. if not data:
  73. redis_client.close()
  74. return {
  75. "success": False,
  76. "error": "没有找到有效数据",
  77. "data": None
  78. }
  79. # 解析JSON数据
  80. try:
  81. checkpoint_data = json.loads(data)
  82. logger.info(f"🔍 JSON顶级keys: {list(checkpoint_data.keys())}")
  83. except json.JSONDecodeError as e:
  84. redis_client.close()
  85. return {
  86. "success": False,
  87. "error": f"JSON解析失败: {e}",
  88. "data": None
  89. }
  90. # 提取消息数据
  91. messages = extract_messages_from_checkpoint(checkpoint_data)
  92. logger.info(f"🔍 找到 {len(messages)} 条原始消息")
  93. # 🔑 关键改进:构建消息ID到时间戳的映射(模仿LangGraph API)
  94. logger.debug(f"🔍 开始构建消息时间戳映射...")
  95. message_timestamps = _build_message_timestamp_map_from_redis(redis_client, thread_id)
  96. # 提取最新checkpoint时间戳作为备用
  97. checkpoint_ts = None
  98. if ('checkpoint' in checkpoint_data and
  99. isinstance(checkpoint_data['checkpoint'], dict) and
  100. 'ts' in checkpoint_data['checkpoint']):
  101. ts_value = checkpoint_data['checkpoint']['ts']
  102. if isinstance(ts_value, str):
  103. try:
  104. # 转换为中国时区格式
  105. from datetime import datetime
  106. import pytz
  107. dt = datetime.fromisoformat(ts_value.replace('Z', '+00:00'))
  108. china_tz = pytz.timezone('Asia/Shanghai')
  109. china_dt = dt.astimezone(china_tz)
  110. checkpoint_ts = china_dt.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
  111. logger.debug(f"🕒 备用checkpoint时间戳: {checkpoint_ts}")
  112. except Exception as e:
  113. logger.warning(f"⚠️ 时间戳转换失败: {e}")
  114. # 解析并过滤消息 - 使用消息时间戳映射
  115. parsed_messages = parse_and_filter_messages(messages, include_tools, checkpoint_ts, message_timestamps)
  116. # 提取用户ID
  117. user_id = thread_id.split(':')[0] if ':' in thread_id else 'unknown'
  118. # 解析created_at时间(从thread_id中提取)
  119. created_at = None
  120. if ':' in thread_id:
  121. try:
  122. timestamp_str = thread_id.split(':')[1]
  123. # 转换为中国时区格式
  124. from datetime import datetime
  125. import pytz
  126. # 假设timestamp是YYYYMMDDHHmmssSSS格式
  127. dt = datetime.strptime(timestamp_str, '%Y%m%d%H%M%S%f')
  128. china_tz = pytz.timezone('Asia/Shanghai')
  129. china_dt = china_tz.localize(dt)
  130. created_at = china_dt.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
  131. logger.info(f"🕒 解析created_at: {created_at}")
  132. except Exception as e:
  133. logger.warning(f"⚠️ 解析created_at失败: {e}")
  134. # 生成对话统计信息
  135. stats = generate_conversation_stats(parsed_messages, include_tools)
  136. redis_client.close()
  137. return {
  138. "success": True,
  139. "data": {
  140. "thread_id": thread_id,
  141. "conversation_id": thread_id, # 添加conversation_id字段
  142. "created_at": created_at, # 添加created_at字段
  143. "user_id": user_id,
  144. "include_tools": include_tools,
  145. "message_count": len(parsed_messages),
  146. "messages": parsed_messages,
  147. "stats": stats,
  148. "metadata": {
  149. "latest_checkpoint_key": latest_key,
  150. "total_raw_messages": len(messages),
  151. "filtered_message_count": len(parsed_messages),
  152. "filter_mode": "full_conversation" if include_tools else "human_ai_only"
  153. }
  154. }
  155. }
  156. except Exception as e:
  157. logger.error(f"❌ 获取对话详情失败: {e}")
  158. import traceback
  159. traceback.print_exc()
  160. return {
  161. "success": False,
  162. "error": str(e),
  163. "data": None
  164. }
  165. def extract_messages_from_checkpoint(checkpoint_data: Dict[str, Any]) -> List[Any]:
  166. """
  167. 从checkpoint数据中提取消息列表
  168. """
  169. messages = []
  170. # 尝试不同的数据结构路径
  171. if 'checkpoint' in checkpoint_data:
  172. checkpoint = checkpoint_data['checkpoint']
  173. if isinstance(checkpoint, dict) and 'channel_values' in checkpoint:
  174. channel_values = checkpoint['channel_values']
  175. if isinstance(channel_values, dict) and 'messages' in channel_values:
  176. messages = channel_values['messages']
  177. # 如果没有找到,尝试直接路径
  178. if not messages and 'channel_values' in checkpoint_data:
  179. channel_values = checkpoint_data['channel_values']
  180. if isinstance(channel_values, dict) and 'messages' in channel_values:
  181. messages = channel_values['messages']
  182. return messages
  183. def _build_message_timestamp_map_from_redis(redis_client, thread_id: str) -> Dict[str, str]:
  184. """
  185. 构建消息ID到时间戳的映射,模仿LangGraph API的逻辑
  186. 遍历所有历史checkpoint,为每条消息记录其首次出现的时间戳
  187. """
  188. message_timestamps = {}
  189. try:
  190. # 获取所有checkpoint keys
  191. pattern = f"checkpoint:{thread_id}:*"
  192. keys = []
  193. cursor = 0
  194. while True:
  195. cursor, batch = redis_client.scan(cursor=cursor, match=pattern, count=1000)
  196. keys.extend(batch)
  197. if cursor == 0:
  198. break
  199. if not keys:
  200. logger.warning(f"⚠️ 未找到任何checkpoint keys: {pattern}")
  201. return message_timestamps
  202. # 获取所有checkpoint数据并按时间戳排序
  203. checkpoints_with_ts = []
  204. for key in keys:
  205. try:
  206. # 检查key类型并获取数据
  207. key_type = redis_client.type(key)
  208. data = None
  209. if key_type == 'string':
  210. data = redis_client.get(key)
  211. elif key_type == 'ReJSON-RL':
  212. data = redis_client.execute_command('JSON.GET', key)
  213. else:
  214. continue
  215. if not data:
  216. continue
  217. # 解析checkpoint数据
  218. checkpoint_data = json.loads(data)
  219. # 提取时间戳
  220. checkpoint_ts = None
  221. if ('checkpoint' in checkpoint_data and
  222. isinstance(checkpoint_data['checkpoint'], dict) and
  223. 'ts' in checkpoint_data['checkpoint']):
  224. ts_value = checkpoint_data['checkpoint']['ts']
  225. if isinstance(ts_value, str):
  226. try:
  227. # 转换为中国时区格式
  228. from datetime import datetime
  229. import pytz
  230. dt = datetime.fromisoformat(ts_value.replace('Z', '+00:00'))
  231. china_tz = pytz.timezone('Asia/Shanghai')
  232. china_dt = dt.astimezone(china_tz)
  233. checkpoint_ts = china_dt.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
  234. except Exception as e:
  235. logger.warning(f"⚠️ 解析时间戳失败 {key}: {e}")
  236. continue
  237. if checkpoint_ts:
  238. checkpoints_with_ts.append({
  239. 'key': key,
  240. 'timestamp': checkpoint_ts,
  241. 'data': checkpoint_data,
  242. 'raw_ts': ts_value # 用于排序
  243. })
  244. except Exception as e:
  245. logger.warning(f"⚠️ 处理checkpoint失败 {key}: {e}")
  246. continue
  247. # 按时间戳排序(最早的在前)
  248. checkpoints_with_ts.sort(key=lambda x: x['raw_ts'])
  249. logger.debug(f"🔍 找到 {len(checkpoints_with_ts)} 个有效checkpoint,按时间排序")
  250. # 遍历每个checkpoint,为新消息分配时间戳
  251. for checkpoint_info in checkpoints_with_ts:
  252. checkpoint_data = checkpoint_info['data']
  253. checkpoint_ts = checkpoint_info['timestamp']
  254. # 提取消息
  255. messages = extract_messages_from_checkpoint(checkpoint_data)
  256. # 为这个checkpoint中的新消息分配时间戳
  257. for msg in messages:
  258. if isinstance(msg, dict) and 'kwargs' in msg:
  259. msg_id = msg['kwargs'].get('id')
  260. if msg_id and msg_id not in message_timestamps:
  261. message_timestamps[msg_id] = checkpoint_ts
  262. logger.debug(f"🕒 消息 {msg_id} 分配时间戳: {checkpoint_ts}")
  263. logger.debug(f"✅ 成功构建消息时间戳映射,包含 {len(message_timestamps)} 条消息")
  264. except Exception as e:
  265. logger.error(f"❌ 构建消息时间戳映射失败: {e}")
  266. import traceback
  267. traceback.print_exc()
  268. return message_timestamps
  269. def parse_and_filter_messages(raw_messages: List[Any], include_tools: bool, checkpoint_ts: str = None, message_timestamps: Dict[str, str] = None) -> List[Dict[str, Any]]:
  270. """
  271. 解析和过滤消息列表 - 关键的开关逻辑实现
  272. Args:
  273. raw_messages: 原始消息列表
  274. include_tools: 是否包含工具消息
  275. - True: 返回所有消息类型
  276. - False: 只返回human/ai,且清理ai消息中的工具信息
  277. Returns:
  278. 解析后的消息列表
  279. """
  280. parsed_messages = []
  281. for msg in raw_messages:
  282. try:
  283. # 获取消息ID,用于查找其真实时间戳
  284. msg_id = None
  285. if isinstance(msg, dict) and 'kwargs' in msg:
  286. msg_id = msg['kwargs'].get('id')
  287. # 使用消息映射中的时间戳,如果没有则使用checkpoint时间戳
  288. msg_timestamp = checkpoint_ts
  289. if message_timestamps and msg_id and msg_id in message_timestamps:
  290. msg_timestamp = message_timestamps[msg_id]
  291. logger.debug(f"🕒 使用消息映射时间戳: {msg_id} -> {msg_timestamp}")
  292. parsed_msg = parse_single_message(msg, msg_timestamp)
  293. if not parsed_msg:
  294. continue
  295. msg_type = parsed_msg['role'] # 使用新的字段名
  296. if include_tools:
  297. # 完整模式:包含所有消息类型
  298. parsed_messages.append(parsed_msg)
  299. logger.debug(f"✅ [完整模式] 包含消息: {msg_type}")
  300. else:
  301. # 简化模式:只包含human和ai消息
  302. if msg_type == 'human':
  303. parsed_messages.append(parsed_msg)
  304. logger.debug(f"✅ [简化模式] 包含human消息")
  305. elif msg_type == 'ai':
  306. # 清理AI消息,移除工具调用信息
  307. cleaned_msg = clean_ai_message_for_simple_mode(parsed_msg)
  308. # 只包含有实际内容的AI消息
  309. if cleaned_msg['content'].strip() and not cleaned_msg.get('is_intermediate_step', False):
  310. parsed_messages.append(cleaned_msg)
  311. logger.debug(f"✅ [简化模式] 包含有内容的ai消息")
  312. else:
  313. logger.debug(f"⏭️ [简化模式] 跳过空的ai消息或中间步骤")
  314. else:
  315. # 跳过tool、system等消息
  316. logger.debug(f"⏭️ [简化模式] 跳过 {msg_type} 消息")
  317. except Exception as e:
  318. logger.warning(f"⚠️ 解析消息失败: {e}")
  319. continue
  320. logger.info(f"📊 解析结果: {len(parsed_messages)} 条消息 (include_tools={include_tools})")
  321. return parsed_messages
  322. def parse_single_message(msg: Any, checkpoint_ts: str = None) -> Optional[Dict[str, Any]]:
  323. """
  324. 解析单个消息,支持LangChain序列化格式
  325. Args:
  326. msg: 原始消息数据
  327. checkpoint_ts: checkpoint的时间戳,用作消息的真实时间(备用)
  328. """
  329. if isinstance(msg, dict):
  330. # LangChain序列化格式
  331. if (msg.get('lc') == 1 and
  332. msg.get('type') == 'constructor' and
  333. 'id' in msg and
  334. isinstance(msg['id'], list) and
  335. 'kwargs' in msg):
  336. kwargs = msg['kwargs']
  337. msg_class = msg['id'][-1] if msg['id'] else 'Unknown'
  338. # 确定消息类型
  339. if msg_class == 'HumanMessage':
  340. msg_type = 'human'
  341. elif msg_class == 'AIMessage':
  342. msg_type = 'ai'
  343. elif msg_class == 'ToolMessage':
  344. msg_type = 'tool'
  345. elif msg_class == 'SystemMessage':
  346. msg_type = 'system'
  347. else:
  348. msg_type = 'unknown'
  349. # 使用传入的时间戳(现在将通过消息ID映射获得)
  350. final_timestamp = checkpoint_ts or datetime.now().isoformat()
  351. # 构建基础消息对象 - 修改字段名称
  352. parsed_msg = {
  353. "role": msg_type, # type -> role
  354. "content": kwargs.get('content', ''),
  355. "message_id": kwargs.get('id'), # id -> message_id
  356. "timestamp": final_timestamp # 使用消息自己的时间戳或备用时间戳
  357. }
  358. # 处理AI消息的特殊字段
  359. if msg_type == 'ai':
  360. # 工具调用信息
  361. tool_calls = kwargs.get('tool_calls', [])
  362. parsed_msg['tool_calls'] = tool_calls
  363. parsed_msg['has_tool_calls'] = len(tool_calls) > 0
  364. # 额外的AI消息元数据
  365. additional_kwargs = kwargs.get('additional_kwargs', {})
  366. if additional_kwargs:
  367. parsed_msg['additional_kwargs'] = additional_kwargs
  368. response_metadata = kwargs.get('response_metadata', {})
  369. if response_metadata:
  370. parsed_msg['response_metadata'] = response_metadata
  371. # 处理工具消息的特殊字段
  372. elif msg_type == 'tool':
  373. parsed_msg['tool_name'] = kwargs.get('name')
  374. parsed_msg['tool_call_id'] = kwargs.get('tool_call_id')
  375. parsed_msg['status'] = kwargs.get('status', 'unknown')
  376. return parsed_msg
  377. # 简单字典格式
  378. elif 'type' in msg:
  379. return {
  380. "role": msg.get('type', 'unknown'), # type -> role
  381. "content": msg.get('content', ''),
  382. "message_id": msg.get('id'), # id -> message_id
  383. "timestamp": checkpoint_ts or datetime.now().isoformat() # 使用真实时间戳
  384. }
  385. return None
  386. def clean_ai_message_for_simple_mode(ai_msg: Dict[str, Any]) -> Dict[str, Any]:
  387. """
  388. 调试版本:清理AI消息用于简化模式
  389. """
  390. original_content = ai_msg.get("content", "")
  391. logger.debug(f"🔍 清理AI消息,原始内容: '{original_content}', 长度: {len(original_content)}")
  392. cleaned_msg = {
  393. "role": ai_msg["role"], # 使用新的字段名
  394. "content": original_content,
  395. "message_id": ai_msg.get("message_id"), # 使用新的字段名
  396. "timestamp": ai_msg.get("timestamp")
  397. }
  398. # 处理内容格式化
  399. content = original_content.strip()
  400. # 注释掉 [Formatted Output] 清理逻辑 - 源头已不生成前缀
  401. # if '[Formatted Output]' in content:
  402. # logger.info(f"🔍 发现 [Formatted Output] 标记")
  403. #
  404. # if content.startswith('[Formatted Output]\n'):
  405. # # 去掉标记,保留后面的实际内容
  406. # actual_content = content.replace('[Formatted Output]\n', '')
  407. # logger.info(f"🔍 去除标记后的内容: '{actual_content}', 长度: {len(actual_content)}")
  408. # cleaned_msg["content"] = actual_content
  409. # content = actual_content
  410. # elif content == '[Formatted Output]' or content == '[Formatted Output]\n':
  411. # # 如果只有标记没有内容
  412. # logger.info(f"🔍 只有标记没有实际内容")
  413. # cleaned_msg["content"] = ""
  414. # cleaned_msg["is_intermediate_step"] = True
  415. # content = ""
  416. # 如果清理后内容为空或只有空白,标记为中间步骤
  417. if not content.strip():
  418. logger.debug(f"🔍 内容为空,标记为中间步骤")
  419. cleaned_msg["is_intermediate_step"] = True
  420. cleaned_msg["content"] = ""
  421. # 添加简化模式标记
  422. cleaned_msg["simplified"] = True
  423. logger.debug(f"🔍 清理结果: '{cleaned_msg['content']}', 是否中间步骤: {cleaned_msg.get('is_intermediate_step', False)}")
  424. return cleaned_msg
  425. def generate_conversation_stats(messages: List[Dict[str, Any]], include_tools: bool) -> Dict[str, Any]:
  426. """
  427. 生成对话统计信息
  428. Args:
  429. messages: 解析后的消息列表
  430. include_tools: 是否包含工具信息(影响统计内容)
  431. Returns:
  432. 统计信息字典
  433. """
  434. stats = {
  435. "total_messages": len(messages),
  436. "human_messages": 0,
  437. "ai_messages": 0,
  438. "conversation_rounds": 0,
  439. "include_tools_mode": include_tools
  440. }
  441. # 添加工具相关统计(仅在include_tools=True时)
  442. if include_tools:
  443. stats.update({
  444. "tool_messages": 0,
  445. "system_messages": 0,
  446. "messages_with_tools": 0,
  447. "unique_tools_used": set()
  448. })
  449. for msg in messages:
  450. msg_type = msg.get('type', 'unknown')
  451. if msg_type == 'human':
  452. stats["human_messages"] += 1
  453. elif msg_type == 'ai':
  454. stats["ai_messages"] += 1
  455. # 工具相关统计
  456. if include_tools and msg.get('has_tool_calls', False):
  457. stats["messages_with_tools"] += 1
  458. # 统计使用的工具
  459. tool_calls = msg.get('tool_calls', [])
  460. for tool_call in tool_calls:
  461. if isinstance(tool_call, dict) and 'name' in tool_call:
  462. stats["unique_tools_used"].add(tool_call['name'])
  463. elif include_tools:
  464. if msg_type == 'tool':
  465. stats["tool_messages"] += 1
  466. # 记录工具名称
  467. tool_name = msg.get('tool_name')
  468. if tool_name:
  469. stats["unique_tools_used"].add(tool_name)
  470. elif msg_type == 'system':
  471. stats["system_messages"] += 1
  472. # 计算对话轮次
  473. stats["conversation_rounds"] = stats["human_messages"]
  474. # 转换set为list(JSON序列化)
  475. if include_tools and "unique_tools_used" in stats:
  476. stats["unique_tools_used"] = list(stats["unique_tools_used"])
  477. return stats
  478. def format_timestamp_readable(timestamp: str) -> str:
  479. """格式化时间戳为可读格式"""
  480. try:
  481. if len(timestamp) >= 14:
  482. year = timestamp[:4]
  483. month = timestamp[4:6]
  484. day = timestamp[6:8]
  485. hour = timestamp[8:10]
  486. minute = timestamp[10:12]
  487. second = timestamp[12:14]
  488. return f"{year}-{month}-{day} {hour}:{minute}:{second}"
  489. except Exception:
  490. pass
  491. return timestamp
  492. # =================== 测试函数 ===================
  493. def test_conversation_detail_with_switch():
  494. """
  495. 测试对话详情获取功能,重点测试include_tools开关
  496. """
  497. print("🧪 测试对话详情获取(开关参数测试)...")
  498. # 测试thread_id(请替换为实际存在的thread_id)
  499. test_thread_id = "wang:20250709195048728323"
  500. print(f"\n1. 测试完整模式(include_tools=True)...")
  501. result_full = get_conversation_detail_from_redis(test_thread_id, include_tools=True)
  502. if result_full['success']:
  503. data = result_full['data']
  504. print(f" ✅ 成功获取完整对话")
  505. print(f" 📊 消息数量: {data['message_count']}")
  506. print(f" 📈 统计信息: {data['stats']}")
  507. print(f" 🔧 包含工具: {data['stats'].get('tool_messages', 0)} 条工具消息")
  508. # 显示消息类型分布
  509. message_types = {}
  510. for msg in data['messages']:
  511. msg_type = msg['type']
  512. message_types[msg_type] = message_types.get(msg_type, 0) + 1
  513. print(f" 📋 消息类型分布: {message_types}")
  514. else:
  515. print(f" ❌ 获取失败: {result_full['error']}")
  516. print(f"\n2. 测试简化模式(include_tools=False)...")
  517. result_simple = get_conversation_detail_from_redis(test_thread_id, include_tools=False)
  518. if result_simple['success']:
  519. data = result_simple['data']
  520. print(f" ✅ 成功获取简化对话")
  521. print(f" 📊 消息数量: {data['message_count']}")
  522. print(f" 📈 统计信息: {data['stats']}")
  523. # 显示消息类型分布
  524. message_types = {}
  525. for msg in data['messages']:
  526. msg_type = msg['type']
  527. message_types[msg_type] = message_types.get(msg_type, 0) + 1
  528. print(f" 📋 消息类型分布: {message_types}")
  529. # 显示前几条消息示例
  530. print(f" 💬 消息示例:")
  531. for i, msg in enumerate(data['messages'][:4]):
  532. content_preview = str(msg['content'])[:50] + "..." if len(str(msg['content'])) > 50 else str(msg['content'])
  533. simplified_mark = " [简化]" if msg.get('simplified') else ""
  534. print(f" [{i+1}] {msg['type']}: {content_preview}{simplified_mark}")
  535. else:
  536. print(f" ❌ 获取失败: {result_simple['error']}")
  537. # 比较两种模式
  538. if result_full['success'] and result_simple['success']:
  539. full_count = result_full['data']['message_count']
  540. simple_count = result_simple['data']['message_count']
  541. difference = full_count - simple_count
  542. print(f"\n3. 模式比较:")
  543. print(f" 📊 完整模式消息数: {full_count}")
  544. print(f" 📊 简化模式消息数: {simple_count}")
  545. print(f" 📊 过滤掉的消息数: {difference}")
  546. print(f" 🎯 过滤效果: {'有效' if difference > 0 else '无差异'}")
  547. if __name__ == "__main__":
  548. test_conversation_detail_with_switch()