api.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  1. """
  2. Custom React Agent API 服务
  3. 提供RESTful接口用于智能问答
  4. """
  5. import asyncio
  6. import logging
  7. import atexit
  8. import os
  9. from datetime import datetime
  10. from typing import Optional, Dict, Any
  11. from flask import Flask, request, jsonify
  12. try:
  13. # 尝试相对导入(当作为模块导入时)
  14. from .agent import CustomReactAgent
  15. except ImportError:
  16. # 如果相对导入失败,尝试绝对导入(直接运行时)
  17. from agent import CustomReactAgent
  18. # 配置日志
  19. logging.basicConfig(level=logging.INFO)
  20. logger = logging.getLogger(__name__)
  21. # 全局Agent实例
  22. _agent_instance: Optional[CustomReactAgent] = None
  23. def validate_request_data(data: Dict[str, Any]) -> Dict[str, Any]:
  24. """验证请求数据"""
  25. errors = []
  26. # 验证 question
  27. question = data.get('question', '')
  28. if not question or not question.strip():
  29. errors.append('问题不能为空')
  30. elif len(question) > 2000:
  31. errors.append('问题长度不能超过2000字符')
  32. # 验证 user_id
  33. user_id = data.get('user_id', 'guest')
  34. if user_id and len(user_id) > 50:
  35. errors.append('用户ID长度不能超过50字符')
  36. if errors:
  37. raise ValueError('; '.join(errors))
  38. return {
  39. 'question': question.strip(),
  40. 'user_id': user_id or 'guest',
  41. 'thread_id': data.get('thread_id')
  42. }
  43. async def initialize_agent():
  44. """初始化Agent"""
  45. global _agent_instance
  46. if _agent_instance is None:
  47. logger.info("🚀 正在初始化 Custom React Agent...")
  48. try:
  49. # 设置环境变量(checkpointer内部需要)
  50. os.environ['REDIS_URL'] = 'redis://localhost:6379'
  51. _agent_instance = await CustomReactAgent.create()
  52. logger.info("✅ Agent 初始化完成")
  53. except Exception as e:
  54. logger.error(f"❌ Agent 初始化失败: {e}")
  55. raise
  56. async def ensure_agent_ready():
  57. """确保Agent实例可用"""
  58. global _agent_instance
  59. if _agent_instance is None:
  60. await initialize_agent()
  61. # 测试Agent是否还可用
  62. try:
  63. # 简单测试 - 尝试获取一个不存在用户的对话(应该返回空列表)
  64. test_result = await _agent_instance.get_user_recent_conversations("__test__", 1)
  65. return True
  66. except Exception as e:
  67. logger.warning(f"⚠️ Agent实例不可用: {e}")
  68. # 重新创建Agent实例
  69. _agent_instance = None
  70. await initialize_agent()
  71. return True
  72. def run_async_safely(async_func, *args, **kwargs):
  73. """安全地运行异步函数,处理事件循环问题"""
  74. try:
  75. # 检查是否已有事件循环
  76. loop = asyncio.get_event_loop()
  77. if loop.is_running():
  78. # 如果事件循环在运行,创建新的事件循环
  79. new_loop = asyncio.new_event_loop()
  80. asyncio.set_event_loop(new_loop)
  81. try:
  82. return new_loop.run_until_complete(async_func(*args, **kwargs))
  83. finally:
  84. new_loop.close()
  85. else:
  86. # 如果事件循环没有运行,直接使用
  87. return loop.run_until_complete(async_func(*args, **kwargs))
  88. except RuntimeError:
  89. # 如果没有事件循环,创建新的
  90. loop = asyncio.new_event_loop()
  91. asyncio.set_event_loop(loop)
  92. try:
  93. return loop.run_until_complete(async_func(*args, **kwargs))
  94. finally:
  95. loop.close()
  96. def ensure_agent_ready_sync():
  97. """同步版本的ensure_agent_ready,用于Flask路由"""
  98. global _agent_instance
  99. if _agent_instance is None:
  100. try:
  101. # 使用新的事件循环初始化
  102. loop = asyncio.new_event_loop()
  103. asyncio.set_event_loop(loop)
  104. try:
  105. loop.run_until_complete(initialize_agent())
  106. finally:
  107. loop.close()
  108. except Exception as e:
  109. logger.error(f"初始化Agent失败: {e}")
  110. return False
  111. return _agent_instance is not None
  112. async def cleanup_agent():
  113. """清理Agent资源"""
  114. global _agent_instance
  115. if _agent_instance:
  116. await _agent_instance.close()
  117. logger.info("✅ Agent 资源已清理")
  118. _agent_instance = None
  119. # 创建Flask应用
  120. app = Flask(__name__)
  121. # 注册清理函数
  122. def cleanup_on_exit():
  123. """程序退出时的清理函数"""
  124. try:
  125. loop = asyncio.new_event_loop()
  126. asyncio.set_event_loop(loop)
  127. try:
  128. loop.run_until_complete(cleanup_agent())
  129. finally:
  130. loop.close()
  131. except Exception as e:
  132. logger.error(f"清理资源时发生错误: {e}")
  133. atexit.register(cleanup_on_exit)
  134. @app.route("/")
  135. def root():
  136. """健康检查端点"""
  137. return jsonify({"message": "Custom React Agent API 服务正在运行"})
  138. @app.route('/health', methods=['GET'])
  139. def health_check():
  140. """健康检查端点"""
  141. try:
  142. health_status = {
  143. "status": "healthy",
  144. "agent_initialized": _agent_instance is not None,
  145. "timestamp": datetime.now().isoformat()
  146. }
  147. return jsonify(health_status), 200
  148. except Exception as e:
  149. logger.error(f"健康检查失败: {e}")
  150. return jsonify({"status": "unhealthy", "error": str(e)}), 500
  151. @app.route("/api/chat", methods=["POST"])
  152. def chat_endpoint():
  153. """智能问答接口"""
  154. global _agent_instance
  155. # 确保Agent已初始化
  156. if not _agent_instance:
  157. try:
  158. # 尝试初始化Agent(使用新的事件循环)
  159. loop = asyncio.new_event_loop()
  160. asyncio.set_event_loop(loop)
  161. try:
  162. loop.run_until_complete(initialize_agent())
  163. finally:
  164. loop.close()
  165. except Exception as e:
  166. return jsonify({
  167. "code": 503,
  168. "message": "服务未就绪",
  169. "success": False,
  170. "error": "Agent 初始化失败"
  171. }), 503
  172. try:
  173. # 获取请求数据
  174. data = request.get_json()
  175. if not data:
  176. return jsonify({
  177. "code": 400,
  178. "message": "请求参数错误",
  179. "success": False,
  180. "error": "请求体不能为空"
  181. }), 400
  182. # 验证请求数据
  183. validated_data = validate_request_data(data)
  184. logger.info(f"📨 收到请求 - User: {validated_data['user_id']}, Question: {validated_data['question'][:50]}...")
  185. # 调用Agent处理(使用新的事件循环)
  186. try:
  187. loop = asyncio.new_event_loop()
  188. asyncio.set_event_loop(loop)
  189. agent_result = loop.run_until_complete(_agent_instance.chat(
  190. message=validated_data['question'],
  191. user_id=validated_data['user_id'],
  192. thread_id=validated_data['thread_id']
  193. ))
  194. finally:
  195. loop.close()
  196. if not agent_result.get("success", False):
  197. # Agent处理失败
  198. error_msg = agent_result.get("error", "Agent处理失败")
  199. logger.error(f"❌ Agent处理失败: {error_msg}")
  200. return jsonify({
  201. "code": 500,
  202. "message": "处理失败",
  203. "success": False,
  204. "error": error_msg,
  205. "data": {
  206. "react_agent_meta": {
  207. "thread_id": agent_result.get("thread_id"),
  208. "agent_version": "custom_react_v1",
  209. "execution_path": ["error"]
  210. },
  211. "timestamp": datetime.now().isoformat()
  212. }
  213. }), 500
  214. # Agent处理成功,提取数据
  215. api_data = agent_result.get("api_data", {})
  216. # 构建最终响应
  217. response_data = {
  218. **api_data, # 包含Agent格式化的所有数据
  219. "timestamp": datetime.now().isoformat()
  220. }
  221. logger.info(f"✅ 请求处理成功 - Thread: {api_data.get('react_agent_meta', {}).get('thread_id')}")
  222. return jsonify({
  223. "code": 200,
  224. "message": "操作成功",
  225. "success": True,
  226. "data": response_data
  227. })
  228. except ValueError as e:
  229. # 参数验证错误
  230. logger.warning(f"⚠️ 参数验证失败: {e}")
  231. return jsonify({
  232. "code": 400,
  233. "message": "请求参数错误",
  234. "success": False,
  235. "error": str(e)
  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. 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 ensure_agent_ready_sync():
  258. return jsonify({
  259. "success": False,
  260. "error": "Agent 未就绪",
  261. "timestamp": datetime.now().isoformat()
  262. }), 503
  263. # 获取对话列表
  264. conversations = run_async_safely(_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. 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 ensure_agent_ready_sync():
  297. return jsonify({
  298. "success": False,
  299. "error": "Agent 未就绪",
  300. "timestamp": datetime.now().isoformat()
  301. }), 503
  302. # 获取对话历史
  303. history = run_async_safely(_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. # 在启动前初始化Agent
  769. try:
  770. loop = asyncio.new_event_loop()
  771. asyncio.set_event_loop(loop)
  772. try:
  773. loop.run_until_complete(initialize_agent())
  774. finally:
  775. loop.close()
  776. logger.info("✅ API 服务启动成功")
  777. except Exception as e:
  778. logger.error(f"❌ API 服务启动失败: {e}")
  779. # 启动Flask应用
  780. app.run(host="0.0.0.0", port=8000, debug=False)