api.py 37 KB

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