api.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  1. """
  2. Custom React Agent API 服务
  3. 提供RESTful接口用于智能问答
  4. """
  5. import asyncio
  6. import logging
  7. import atexit
  8. import os
  9. import sys
  10. from datetime import datetime
  11. from typing import Optional, Dict, Any
  12. # 🔧 修复模块路径问题:添加项目根目录到 sys.path
  13. CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
  14. PROJECT_ROOT = os.path.abspath(os.path.join(CURRENT_DIR, '..', '..'))
  15. sys.path.insert(0, CURRENT_DIR) # 当前目录优先
  16. sys.path.insert(1, PROJECT_ROOT) # 项目根目录
  17. from flask import Flask, request, jsonify
  18. import redis.asyncio as redis
  19. try:
  20. # 尝试相对导入(当作为模块导入时)
  21. from .agent import CustomReactAgent
  22. except ImportError:
  23. # 如果相对导入失败,尝试绝对导入(直接运行时)
  24. from agent import CustomReactAgent
  25. # 配置日志
  26. logging.basicConfig(level=logging.INFO)
  27. logger = logging.getLogger(__name__)
  28. # 全局Agent实例
  29. _agent_instance: Optional[CustomReactAgent] = None
  30. _redis_client: Optional[redis.Redis] = None
  31. def validate_request_data(data: Dict[str, Any]) -> Dict[str, Any]:
  32. """验证请求数据"""
  33. errors = []
  34. # 验证 question(必填)
  35. question = data.get('question', '')
  36. if not question or not question.strip():
  37. errors.append('问题不能为空')
  38. elif len(question) > 2000:
  39. errors.append('问题长度不能超过2000字符')
  40. # 验证 user_id(可选,默认为"guest")
  41. user_id = data.get('user_id', 'guest')
  42. if user_id and len(user_id) > 50:
  43. errors.append('用户ID长度不能超过50字符')
  44. # thread_id 和 conversation_id 处理:如果thread_id没有值,就使用conversation_id的值
  45. thread_id = data.get('thread_id') or data.get('conversation_id')
  46. # 用户ID与会话ID一致性校验
  47. if thread_id and user_id != 'guest':
  48. if ':' not in thread_id:
  49. errors.append('会话ID格式无效,期望格式为 user_id:timestamp')
  50. else:
  51. thread_user_id = thread_id.split(':', 1)[0] # 取冒号前的部分作为用户ID
  52. if thread_user_id != user_id:
  53. errors.append(f'会话归属验证失败:会话ID [{thread_id}] 不属于当前用户 [{user_id}]')
  54. if errors:
  55. raise ValueError('; '.join(errors))
  56. return {
  57. 'question': question.strip(),
  58. 'user_id': user_id or 'guest',
  59. 'thread_id': thread_id # 可选,不传则自动生成新会话
  60. }
  61. async def initialize_agent():
  62. """异步初始化Agent"""
  63. global _agent_instance, _redis_client
  64. if _agent_instance is None:
  65. logger.info("🚀 正在异步初始化 Custom React Agent...")
  66. try:
  67. # 设置环境变量(checkpointer内部需要)
  68. os.environ['REDIS_URL'] = 'redis://localhost:6379'
  69. # 初始化共享的Redis客户端
  70. _redis_client = redis.from_url('redis://localhost:6379', decode_responses=True)
  71. await _redis_client.ping()
  72. logger.info("✅ Redis客户端连接成功")
  73. _agent_instance = await CustomReactAgent.create()
  74. logger.info("✅ Agent 异步初始化完成")
  75. except Exception as e:
  76. logger.error(f"❌ Agent 异步初始化失败: {e}")
  77. raise
  78. async def ensure_agent_ready():
  79. """异步确保Agent实例可用"""
  80. global _agent_instance
  81. if _agent_instance is None:
  82. await initialize_agent()
  83. # 测试Agent是否还可用
  84. try:
  85. # 简单测试 - 尝试获取一个不存在用户的对话(应该返回空列表)
  86. test_result = await _agent_instance.get_user_recent_conversations("__test__", 1)
  87. return True
  88. except Exception as e:
  89. logger.warning(f"⚠️ Agent实例不可用: {e}")
  90. # 重新创建Agent实例
  91. _agent_instance = None
  92. await initialize_agent()
  93. return True
  94. # 删除复杂的事件循环管理函数 - 不再需要
  95. async def cleanup_agent():
  96. """异步清理Agent资源"""
  97. global _agent_instance, _redis_client
  98. if _agent_instance:
  99. await _agent_instance.close()
  100. logger.info("✅ Agent 资源已异步清理")
  101. _agent_instance = None
  102. if _redis_client:
  103. await _redis_client.aclose()
  104. logger.info("✅ Redis客户端已异步关闭")
  105. _redis_client = None
  106. # 创建Flask应用
  107. app = Flask(__name__)
  108. # 简化的退出处理
  109. def cleanup_on_exit():
  110. """程序退出时的清理函数"""
  111. logger.info("程序退出,资源清理将在异步上下文中进行")
  112. atexit.register(cleanup_on_exit)
  113. @app.route("/")
  114. def root():
  115. """健康检查端点"""
  116. return jsonify({"message": "Custom React Agent API 服务正在运行"})
  117. @app.route('/health', methods=['GET'])
  118. def health_check():
  119. """健康检查端点"""
  120. try:
  121. health_status = {
  122. "status": "healthy",
  123. "agent_initialized": _agent_instance is not None,
  124. "timestamp": datetime.now().isoformat()
  125. }
  126. return jsonify(health_status), 200
  127. except Exception as e:
  128. logger.error(f"健康检查失败: {e}")
  129. return jsonify({"status": "unhealthy", "error": str(e)}), 500
  130. @app.route("/api/chat", methods=["POST"])
  131. async def chat_endpoint():
  132. """异步智能问答接口"""
  133. global _agent_instance
  134. # 确保Agent已初始化
  135. if not await ensure_agent_ready():
  136. return jsonify({
  137. "code": 503,
  138. "message": "服务未就绪",
  139. "success": False,
  140. "error": "Agent 初始化失败"
  141. }), 503
  142. try:
  143. # 获取请求数据,处理JSON解析错误
  144. try:
  145. data = request.get_json(force=True)
  146. except Exception as json_error:
  147. logger.warning(f"⚠️ JSON解析失败: {json_error}")
  148. return jsonify({
  149. "code": 400,
  150. "message": "请求格式错误",
  151. "success": False,
  152. "error": "无效的JSON格式,请检查请求体中是否存在语法错误(如多余的逗号、引号不匹配等)",
  153. "details": str(json_error)
  154. }), 400
  155. if not data:
  156. return jsonify({
  157. "code": 400,
  158. "message": "请求参数错误",
  159. "success": False,
  160. "error": "请求体不能为空"
  161. }), 400
  162. # 验证请求数据
  163. validated_data = validate_request_data(data)
  164. logger.info(f"📨 收到请求 - User: {validated_data['user_id']}, Question: {validated_data['question'][:50]}...")
  165. # 直接调用异步方法,不需要事件循环包装
  166. agent_result = await _agent_instance.chat(
  167. message=validated_data['question'],
  168. user_id=validated_data['user_id'],
  169. thread_id=validated_data['thread_id']
  170. )
  171. if not agent_result.get("success", False):
  172. # Agent处理失败
  173. error_msg = agent_result.get("error", "Agent处理失败")
  174. logger.error(f"❌ Agent处理失败: {error_msg}")
  175. return jsonify({
  176. "code": 500,
  177. "message": "处理失败",
  178. "success": False,
  179. "error": error_msg,
  180. "data": {
  181. "conversation_id": agent_result.get("thread_id"), # 新增:conversation_id等于thread_id
  182. "user_id": validated_data['user_id'], # 新增:返回用户ID
  183. "react_agent_meta": {
  184. "thread_id": agent_result.get("thread_id"),
  185. "agent_version": "custom_react_v1_async",
  186. "execution_path": ["error"]
  187. },
  188. "timestamp": datetime.now().isoformat()
  189. }
  190. }), 500
  191. # Agent处理成功,按照设计文档格式化响应
  192. api_data = agent_result.get("api_data", {})
  193. # 构建符合设计文档的响应数据
  194. response_data = {
  195. "response": api_data.get("response", ""),
  196. "conversation_id": agent_result.get("thread_id"), # 新增:conversation_id等于thread_id
  197. "user_id": validated_data['user_id'], # 新增:返回用户ID
  198. "react_agent_meta": api_data.get("react_agent_meta", {
  199. "thread_id": agent_result.get("thread_id"),
  200. "agent_version": "custom_react_v1"
  201. }),
  202. "timestamp": datetime.now().isoformat()
  203. }
  204. # 可选字段:SQL(仅当执行SQL时存在)
  205. if "sql" in api_data:
  206. response_data["sql"] = api_data["sql"]
  207. # 可选字段:records(仅当有查询结果时存在)
  208. if "records" in api_data:
  209. response_data["records"] = api_data["records"]
  210. logger.info(f"✅ 请求处理成功 - Thread: {response_data['react_agent_meta'].get('thread_id')}")
  211. return jsonify({
  212. "code": 200,
  213. "message": "操作成功",
  214. "success": True,
  215. "data": response_data
  216. })
  217. except ValueError as e:
  218. # 参数验证错误
  219. error_msg = str(e)
  220. logger.warning(f"⚠️ 参数验证失败: {error_msg}")
  221. # 根据错误类型提供更友好的消息
  222. if "会话归属验证失败" in error_msg:
  223. message = "会话归属验证失败"
  224. elif "会话ID格式无效" in error_msg:
  225. message = "会话ID格式无效"
  226. elif "JSON格式" in error_msg:
  227. message = "请求格式错误"
  228. else:
  229. message = "请求参数错误"
  230. return jsonify({
  231. "code": 400,
  232. "message": message,
  233. "success": False,
  234. "error": error_msg,
  235. "error_type": "validation_error"
  236. }), 400
  237. except Exception as e:
  238. # 其他未预期的错误
  239. logger.error(f"❌ 未预期的错误: {e}", exc_info=True)
  240. return jsonify({
  241. "code": 500,
  242. "message": "服务器内部错误",
  243. "success": False,
  244. "error": "系统异常,请稍后重试"
  245. }), 500
  246. @app.route('/api/v0/react/users/<user_id>/conversations', methods=['GET'])
  247. async def get_user_conversations(user_id: str):
  248. """异步获取用户的聊天记录列表"""
  249. global _agent_instance
  250. try:
  251. # 获取查询参数
  252. limit = request.args.get('limit', 10, type=int)
  253. # 限制limit的范围
  254. limit = max(1, min(limit, 50)) # 限制在1-50之间
  255. logger.info(f"📋 异步获取用户 {user_id} 的对话列表,限制 {limit} 条")
  256. # 确保Agent可用
  257. if not await ensure_agent_ready():
  258. return jsonify({
  259. "success": False,
  260. "error": "Agent 未就绪",
  261. "timestamp": datetime.now().isoformat()
  262. }), 503
  263. # 直接调用异步方法
  264. conversations = await _agent_instance.get_user_recent_conversations(user_id, limit)
  265. return jsonify({
  266. "success": True,
  267. "data": {
  268. "user_id": user_id,
  269. "conversations": conversations,
  270. "total_count": len(conversations),
  271. "limit": limit
  272. },
  273. "timestamp": datetime.now().isoformat()
  274. }), 200
  275. except Exception as e:
  276. logger.error(f"❌ 异步获取用户 {user_id} 对话列表失败: {e}")
  277. return jsonify({
  278. "success": False,
  279. "error": str(e),
  280. "timestamp": datetime.now().isoformat()
  281. }), 500
  282. @app.route('/api/v0/react/users/<user_id>/conversations/<thread_id>', methods=['GET'])
  283. async def get_user_conversation_detail(user_id: str, thread_id: str):
  284. """异步获取特定对话的详细历史"""
  285. global _agent_instance
  286. try:
  287. # 验证thread_id格式是否匹配user_id
  288. if not thread_id.startswith(f"{user_id}:"):
  289. return jsonify({
  290. "success": False,
  291. "error": f"Thread ID {thread_id} 不属于用户 {user_id}",
  292. "timestamp": datetime.now().isoformat()
  293. }), 400
  294. logger.info(f"📖 异步获取用户 {user_id} 的对话 {thread_id} 详情")
  295. # 确保Agent可用
  296. if not await ensure_agent_ready():
  297. return jsonify({
  298. "success": False,
  299. "error": "Agent 未就绪",
  300. "timestamp": datetime.now().isoformat()
  301. }), 503
  302. # 直接调用异步方法
  303. history = await _agent_instance.get_conversation_history(thread_id)
  304. logger.info(f"✅ 异步成功获取对话历史,消息数量: {len(history)}")
  305. if not history:
  306. return jsonify({
  307. "success": False,
  308. "error": f"未找到对话 {thread_id}",
  309. "timestamp": datetime.now().isoformat()
  310. }), 404
  311. return jsonify({
  312. "success": True,
  313. "data": {
  314. "user_id": user_id,
  315. "thread_id": thread_id,
  316. "message_count": len(history),
  317. "messages": history
  318. },
  319. "timestamp": datetime.now().isoformat()
  320. }), 200
  321. except Exception as e:
  322. import traceback
  323. logger.error(f"❌ 异步获取对话 {thread_id} 详情失败: {e}")
  324. logger.error(f"❌ 详细错误信息: {traceback.format_exc()}")
  325. return jsonify({
  326. "success": False,
  327. "error": str(e),
  328. "timestamp": datetime.now().isoformat()
  329. }), 500
  330. # 简单Redis查询函数(测试用)
  331. def get_user_conversations_simple_sync(user_id: str, limit: int = 10):
  332. """直接从Redis获取用户对话,测试版本"""
  333. import redis
  334. import json
  335. try:
  336. # 创建Redis连接
  337. redis_client = redis.Redis(host='localhost', port=6379, decode_responses=True)
  338. redis_client.ping()
  339. # 扫描用户的checkpoint keys
  340. pattern = f"checkpoint:{user_id}:*"
  341. logger.info(f"🔍 扫描模式: {pattern}")
  342. keys = []
  343. cursor = 0
  344. while True:
  345. cursor, batch = redis_client.scan(cursor=cursor, match=pattern, count=1000)
  346. keys.extend(batch)
  347. if cursor == 0:
  348. break
  349. logger.info(f"📋 找到 {len(keys)} 个keys")
  350. # 解析thread信息
  351. thread_data = {}
  352. for key in keys:
  353. try:
  354. parts = key.split(':')
  355. if len(parts) >= 4:
  356. thread_id = f"{parts[1]}:{parts[2]}" # user_id:timestamp
  357. timestamp = parts[2]
  358. if thread_id not in thread_data:
  359. thread_data[thread_id] = {
  360. "thread_id": thread_id,
  361. "timestamp": timestamp,
  362. "keys": []
  363. }
  364. thread_data[thread_id]["keys"].append(key)
  365. except Exception as e:
  366. logger.warning(f"解析key失败 {key}: {e}")
  367. continue
  368. logger.info(f"📊 找到 {len(thread_data)} 个thread")
  369. # 按时间戳排序
  370. sorted_threads = sorted(
  371. thread_data.values(),
  372. key=lambda x: x["timestamp"],
  373. reverse=True
  374. )[:limit]
  375. # 获取每个thread的详细信息
  376. conversations = []
  377. for thread_info in sorted_threads:
  378. try:
  379. thread_id = thread_info["thread_id"]
  380. # 获取最新的checkpoint数据
  381. latest_key = max(thread_info["keys"])
  382. # 先检查key的数据类型
  383. key_type = redis_client.type(latest_key)
  384. logger.info(f"🔍 Key {latest_key} 的类型: {key_type}")
  385. data = None
  386. if key_type == 'string':
  387. data = redis_client.get(latest_key)
  388. elif key_type == 'hash':
  389. # 如果是hash类型,获取所有字段
  390. hash_data = redis_client.hgetall(latest_key)
  391. logger.info(f"🔍 Hash字段: {list(hash_data.keys())}")
  392. # 尝试获取可能的数据字段
  393. for field in ['data', 'state', 'value', 'checkpoint']:
  394. if field in hash_data:
  395. data = hash_data[field]
  396. break
  397. if not data and hash_data:
  398. # 如果没找到预期字段,取第一个值试试
  399. data = list(hash_data.values())[0]
  400. elif key_type == 'list':
  401. # 如果是list类型,获取最后一个元素
  402. data = redis_client.lindex(latest_key, -1)
  403. elif key_type == 'ReJSON-RL':
  404. # 这是RedisJSON类型,使用JSON.GET命令
  405. logger.info(f"🔍 使用JSON.GET获取RedisJSON数据")
  406. try:
  407. # 使用JSON.GET命令获取整个JSON对象
  408. json_data = redis_client.execute_command('JSON.GET', latest_key)
  409. if json_data:
  410. data = json_data # JSON.GET返回的就是JSON字符串
  411. logger.info(f"🔍 JSON数据长度: {len(data)} 字符")
  412. else:
  413. logger.warning(f"⚠️ JSON.GET 返回空数据")
  414. continue
  415. except Exception as json_error:
  416. logger.error(f"❌ JSON.GET 失败: {json_error}")
  417. continue
  418. else:
  419. logger.warning(f"⚠️ 未知的key类型: {key_type}")
  420. continue
  421. if data:
  422. try:
  423. checkpoint_data = json.loads(data)
  424. # 调试:查看JSON数据结构
  425. logger.info(f"🔍 JSON顶级keys: {list(checkpoint_data.keys())}")
  426. # 根据您提供的JSON结构,消息在 checkpoint.channel_values.messages
  427. messages = []
  428. # 首先检查是否有checkpoint字段
  429. if 'checkpoint' in checkpoint_data:
  430. checkpoint = checkpoint_data['checkpoint']
  431. if isinstance(checkpoint, dict) and 'channel_values' in checkpoint:
  432. channel_values = checkpoint['channel_values']
  433. if isinstance(channel_values, dict) and 'messages' in channel_values:
  434. messages = channel_values['messages']
  435. logger.info(f"🔍 找到messages: {len(messages)} 条消息")
  436. # 如果没有checkpoint字段,尝试直接在channel_values
  437. if not messages and 'channel_values' in checkpoint_data:
  438. channel_values = checkpoint_data['channel_values']
  439. if isinstance(channel_values, dict) and 'messages' in channel_values:
  440. messages = channel_values['messages']
  441. logger.info(f"🔍 找到messages(直接路径): {len(messages)} 条消息")
  442. # 生成对话预览
  443. preview = "空对话"
  444. if messages:
  445. for msg in messages:
  446. # 处理LangChain消息格式:{"lc": 1, "type": "constructor", "id": ["langchain", "schema", "messages", "HumanMessage"], "kwargs": {"content": "...", "type": "human"}}
  447. if isinstance(msg, dict):
  448. # 检查是否是LangChain格式的HumanMessage
  449. if (msg.get('lc') == 1 and
  450. msg.get('type') == 'constructor' and
  451. 'id' in msg and
  452. isinstance(msg['id'], list) and
  453. len(msg['id']) >= 4 and
  454. msg['id'][3] == 'HumanMessage' and
  455. 'kwargs' in msg):
  456. kwargs = msg['kwargs']
  457. if kwargs.get('type') == 'human' and 'content' in kwargs:
  458. content = str(kwargs['content'])
  459. preview = content[:50] + "..." if len(content) > 50 else content
  460. break
  461. # 兼容其他格式
  462. elif msg.get('type') == 'human' and 'content' in msg:
  463. content = str(msg['content'])
  464. preview = content[:50] + "..." if len(content) > 50 else content
  465. break
  466. conversations.append({
  467. "thread_id": thread_id,
  468. "user_id": user_id,
  469. "timestamp": thread_info["timestamp"],
  470. "message_count": len(messages),
  471. "conversation_preview": preview
  472. })
  473. except json.JSONDecodeError:
  474. logger.error(f"❌ JSON解析失败,数据类型: {type(data)}, 长度: {len(str(data))}")
  475. logger.error(f"❌ 数据开头: {str(data)[:200]}...")
  476. continue
  477. except Exception as e:
  478. logger.error(f"处理thread {thread_info['thread_id']} 失败: {e}")
  479. continue
  480. redis_client.close()
  481. logger.info(f"✅ 返回 {len(conversations)} 个对话")
  482. return conversations
  483. except Exception as e:
  484. logger.error(f"❌ Redis查询失败: {e}")
  485. return []
  486. @app.route('/api/test/redis', methods=['GET'])
  487. def test_redis_connection():
  488. """测试Redis连接和基本查询"""
  489. try:
  490. import redis
  491. # 创建Redis连接
  492. r = redis.Redis(host='localhost', port=6379, decode_responses=True)
  493. r.ping()
  494. # 扫描checkpoint keys
  495. pattern = "checkpoint:*"
  496. keys = []
  497. cursor = 0
  498. count = 0
  499. while True:
  500. cursor, batch = r.scan(cursor=cursor, match=pattern, count=100)
  501. keys.extend(batch)
  502. count += len(batch)
  503. if cursor == 0 or count > 500: # 限制扫描数量
  504. break
  505. # 统计用户
  506. users = {}
  507. for key in keys:
  508. try:
  509. parts = key.split(':')
  510. if len(parts) >= 2:
  511. user_id = parts[1]
  512. users[user_id] = users.get(user_id, 0) + 1
  513. except:
  514. continue
  515. r.close()
  516. return jsonify({
  517. "success": True,
  518. "data": {
  519. "redis_connected": True,
  520. "total_checkpoint_keys": len(keys),
  521. "users_found": list(users.keys()),
  522. "user_key_counts": users,
  523. "sample_keys": keys[:5] if keys else []
  524. },
  525. "timestamp": datetime.now().isoformat()
  526. }), 200
  527. except Exception as e:
  528. logger.error(f"❌ Redis测试失败: {e}")
  529. return jsonify({
  530. "success": False,
  531. "error": str(e),
  532. "timestamp": datetime.now().isoformat()
  533. }), 500
  534. @app.route('/api/v0/react/direct/users/<user_id>/conversations', methods=['GET'])
  535. def test_get_user_conversations_simple(user_id: str):
  536. """测试简单Redis查询获取用户对话列表"""
  537. try:
  538. limit = request.args.get('limit', 10, type=int)
  539. limit = max(1, min(limit, 50))
  540. logger.info(f"🧪 测试获取用户 {user_id} 的对话列表(简单Redis方式)")
  541. # 使用简单Redis查询
  542. conversations = get_user_conversations_simple_sync(user_id, limit)
  543. return jsonify({
  544. "success": True,
  545. "method": "simple_redis_query",
  546. "data": {
  547. "user_id": user_id,
  548. "conversations": conversations,
  549. "total_count": len(conversations),
  550. "limit": limit
  551. },
  552. "timestamp": datetime.now().isoformat()
  553. }), 200
  554. except Exception as e:
  555. logger.error(f"❌ 测试简单Redis查询失败: {e}")
  556. return jsonify({
  557. "success": False,
  558. "error": str(e),
  559. "timestamp": datetime.now().isoformat()
  560. }), 500
  561. # 在 api.py 文件顶部的导入部分添加:
  562. from enhanced_redis_api import get_conversation_detail_from_redis
  563. # 在 api.py 文件中添加以下新路由:
  564. @app.route('/api/v0/react/direct/conversations/<thread_id>', methods=['GET'])
  565. def get_conversation_detail_api(thread_id: str):
  566. """
  567. 获取特定对话的详细信息 - 支持include_tools开关参数
  568. Query Parameters:
  569. - include_tools: bool, 是否包含工具调用信息,默认false
  570. true: 返回完整对话(human/ai/tool/system)
  571. false: 只返回human/ai消息,清理工具调用信息
  572. - user_id: str, 可选的用户ID验证
  573. Examples:
  574. GET /api/conversations/wang:20250709195048728?include_tools=true # 完整模式
  575. GET /api/conversations/wang:20250709195048728?include_tools=false # 简化模式(默认)
  576. GET /api/conversations/wang:20250709195048728 # 简化模式(默认)
  577. """
  578. try:
  579. # 获取查询参数
  580. include_tools = request.args.get('include_tools', 'false').lower() == 'true'
  581. user_id = request.args.get('user_id')
  582. # 验证thread_id格式
  583. if ':' not in thread_id:
  584. return jsonify({
  585. "success": False,
  586. "error": "Invalid thread_id format. Expected format: user_id:timestamp",
  587. "timestamp": datetime.now().isoformat()
  588. }), 400
  589. # 如果提供了user_id,验证thread_id是否属于该用户
  590. thread_user_id = thread_id.split(':')[0]
  591. if user_id and thread_user_id != user_id:
  592. return jsonify({
  593. "success": False,
  594. "error": f"Thread ID {thread_id} does not belong to user {user_id}",
  595. "timestamp": datetime.now().isoformat()
  596. }), 400
  597. logger.info(f"📖 获取对话详情 - Thread: {thread_id}, Include Tools: {include_tools}")
  598. # 从Redis获取对话详情(使用我们的新函数)
  599. result = get_conversation_detail_from_redis(thread_id, include_tools)
  600. if not result['success']:
  601. logger.warning(f"⚠️ 获取对话详情失败: {result['error']}")
  602. return jsonify({
  603. "success": False,
  604. "error": result['error'],
  605. "timestamp": datetime.now().isoformat()
  606. }), 404
  607. # 添加API元数据
  608. result['data']['api_metadata'] = {
  609. "timestamp": datetime.now().isoformat(),
  610. "api_version": "v1",
  611. "endpoint": "get_conversation_detail",
  612. "query_params": {
  613. "include_tools": include_tools,
  614. "user_id": user_id
  615. }
  616. }
  617. mode_desc = "完整模式" if include_tools else "简化模式"
  618. logger.info(f"✅ 成功获取对话详情 - Messages: {result['data']['message_count']}, Mode: {mode_desc}")
  619. return jsonify({
  620. "success": True,
  621. "data": result['data'],
  622. "timestamp": datetime.now().isoformat()
  623. }), 200
  624. except Exception as e:
  625. import traceback
  626. logger.error(f"❌ 获取对话详情异常: {e}")
  627. logger.error(f"❌ 详细错误信息: {traceback.format_exc()}")
  628. return jsonify({
  629. "success": False,
  630. "error": str(e),
  631. "timestamp": datetime.now().isoformat()
  632. }), 500
  633. @app.route('/api/v0/react/direct/conversations/<thread_id>/compare', methods=['GET'])
  634. def compare_conversation_modes_api(thread_id: str):
  635. """
  636. 比较完整模式和简化模式的对话内容
  637. 用于调试和理解两种模式的差异
  638. Examples:
  639. GET /api/conversations/wang:20250709195048728/compare
  640. """
  641. try:
  642. logger.info(f"🔍 比较对话模式 - Thread: {thread_id}")
  643. # 获取完整模式
  644. full_result = get_conversation_detail_from_redis(thread_id, include_tools=True)
  645. # 获取简化模式
  646. simple_result = get_conversation_detail_from_redis(thread_id, include_tools=False)
  647. if not (full_result['success'] and simple_result['success']):
  648. return jsonify({
  649. "success": False,
  650. "error": "无法获取对话数据进行比较",
  651. "timestamp": datetime.now().isoformat()
  652. }), 404
  653. # 构建比较结果
  654. comparison = {
  655. "thread_id": thread_id,
  656. "full_mode": {
  657. "message_count": full_result['data']['message_count'],
  658. "stats": full_result['data']['stats'],
  659. "sample_messages": full_result['data']['messages'][:3] # 只显示前3条作为示例
  660. },
  661. "simple_mode": {
  662. "message_count": simple_result['data']['message_count'],
  663. "stats": simple_result['data']['stats'],
  664. "sample_messages": simple_result['data']['messages'][:3] # 只显示前3条作为示例
  665. },
  666. "comparison_summary": {
  667. "message_count_difference": full_result['data']['message_count'] - simple_result['data']['message_count'],
  668. "tools_filtered_out": full_result['data']['stats'].get('tool_messages', 0),
  669. "ai_messages_with_tools": full_result['data']['stats'].get('messages_with_tools', 0),
  670. "filtering_effectiveness": "有效" if (full_result['data']['message_count'] - simple_result['data']['message_count']) > 0 else "无差异"
  671. },
  672. "metadata": {
  673. "timestamp": datetime.now().isoformat(),
  674. "note": "sample_messages 只显示前3条消息作为示例,完整消息请使用相应的详情API"
  675. }
  676. }
  677. logger.info(f"✅ 模式比较完成 - 完整: {comparison['full_mode']['message_count']}, 简化: {comparison['simple_mode']['message_count']}")
  678. return jsonify({
  679. "success": True,
  680. "data": comparison,
  681. "timestamp": datetime.now().isoformat()
  682. }), 200
  683. except Exception as e:
  684. logger.error(f"❌ 对话模式比较失败: {e}")
  685. return jsonify({
  686. "success": False,
  687. "error": str(e),
  688. "timestamp": datetime.now().isoformat()
  689. }), 500
  690. @app.route('/api/v0/react/direct/conversations/<thread_id>/summary', methods=['GET'])
  691. def get_conversation_summary_api(thread_id: str):
  692. """
  693. 获取对话摘要信息(只包含基本统计,不返回具体消息)
  694. Query Parameters:
  695. - include_tools: bool, 影响统计信息的计算方式
  696. Examples:
  697. GET /api/conversations/wang:20250709195048728/summary?include_tools=true
  698. """
  699. try:
  700. include_tools = request.args.get('include_tools', 'false').lower() == 'true'
  701. # 验证thread_id格式
  702. if ':' not in thread_id:
  703. return jsonify({
  704. "success": False,
  705. "error": "Invalid thread_id format. Expected format: user_id:timestamp",
  706. "timestamp": datetime.now().isoformat()
  707. }), 400
  708. logger.info(f"📊 获取对话摘要 - Thread: {thread_id}, Include Tools: {include_tools}")
  709. # 获取完整对话信息
  710. result = get_conversation_detail_from_redis(thread_id, include_tools)
  711. if not result['success']:
  712. return jsonify({
  713. "success": False,
  714. "error": result['error'],
  715. "timestamp": datetime.now().isoformat()
  716. }), 404
  717. # 只返回摘要信息,不包含具体消息
  718. data = result['data']
  719. summary = {
  720. "thread_id": data['thread_id'],
  721. "user_id": data['user_id'],
  722. "include_tools": data['include_tools'],
  723. "message_count": data['message_count'],
  724. "stats": data['stats'],
  725. "metadata": data['metadata'],
  726. "first_message_preview": None,
  727. "last_message_preview": None,
  728. "conversation_preview": None
  729. }
  730. # 添加消息预览
  731. messages = data.get('messages', [])
  732. if messages:
  733. # 第一条human消息预览
  734. for msg in messages:
  735. if msg['type'] == 'human':
  736. content = str(msg['content'])
  737. summary['first_message_preview'] = content[:100] + "..." if len(content) > 100 else content
  738. break
  739. # 最后一条ai消息预览
  740. for msg in reversed(messages):
  741. if msg['type'] == 'ai' and msg.get('content', '').strip():
  742. content = str(msg['content'])
  743. summary['last_message_preview'] = content[:100] + "..." if len(content) > 100 else content
  744. break
  745. # 生成对话预览(第一条human消息)
  746. summary['conversation_preview'] = summary['first_message_preview']
  747. # 添加API元数据
  748. summary['api_metadata'] = {
  749. "timestamp": datetime.now().isoformat(),
  750. "api_version": "v1",
  751. "endpoint": "get_conversation_summary"
  752. }
  753. logger.info(f"✅ 成功获取对话摘要")
  754. return jsonify({
  755. "success": True,
  756. "data": summary,
  757. "timestamp": datetime.now().isoformat()
  758. }), 200
  759. except Exception as e:
  760. logger.error(f"❌ 获取对话摘要失败: {e}")
  761. return jsonify({
  762. "success": False,
  763. "error": str(e),
  764. "timestamp": datetime.now().isoformat()
  765. }), 500
  766. # 为了支持独立运行
  767. if __name__ == "__main__":
  768. try:
  769. # 尝试使用ASGI模式启动(推荐)
  770. import uvicorn
  771. from asgiref.wsgi import WsgiToAsgi
  772. logger.info("🚀 使用ASGI模式启动异步Flask应用...")
  773. logger.info(" 这将解决事件循环冲突问题,支持LangGraph异步checkpoint保存")
  774. # 将Flask WSGI应用转换为ASGI应用
  775. asgi_app = WsgiToAsgi(app)
  776. # 信号处理
  777. import signal
  778. def signal_handler(signum, frame):
  779. logger.info("🛑 收到关闭信号,开始清理...")
  780. print("正在关闭服务...")
  781. exit(0)
  782. signal.signal(signal.SIGINT, signal_handler)
  783. signal.signal(signal.SIGTERM, signal_handler)
  784. # 使用uvicorn启动ASGI应用
  785. uvicorn.run(
  786. asgi_app,
  787. host="0.0.0.0",
  788. port=8000,
  789. log_level="info",
  790. access_log=True
  791. )
  792. except ImportError as e:
  793. # 如果缺少ASGI依赖,fallback到传统Flask模式
  794. logger.warning("⚠️ ASGI依赖缺失,使用传统Flask模式启动")
  795. logger.warning(" 建议安装: pip install uvicorn asgiref")
  796. logger.warning(" 传统模式可能存在异步事件循环冲突问题")
  797. # 信号处理
  798. import signal
  799. def signal_handler(signum, frame):
  800. logger.info("🛑 收到关闭信号,开始清理...")
  801. print("正在关闭服务...")
  802. exit(0)
  803. signal.signal(signal.SIGINT, signal_handler)
  804. signal.signal(signal.SIGTERM, signal_handler)
  805. # 启动传统Flask应用
  806. app.run(host="0.0.0.0", port=8000, debug=False, threaded=True)