redis_conversation_improvement_example.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. # Redis对话管理系统 - 无效conversation_id处理改进示例
  2. # 这个文件展示了如何改进处理无效对话ID的逻辑
  3. from typing import Optional, Tuple, Dict
  4. class ImprovedRedisConversationManager:
  5. """改进版的Redis对话管理器 - 专注于无效ID处理"""
  6. def resolve_conversation_id(self, user_id: str, conversation_id_input: Optional[str],
  7. continue_conversation: bool) -> Tuple[str, Dict]:
  8. """
  9. 智能解析对话ID - 改进版
  10. Args:
  11. user_id: 用户ID
  12. conversation_id_input: 用户请求的对话ID
  13. continue_conversation: 是否继续最近对话
  14. Returns:
  15. tuple: (conversation_id, status_info)
  16. status_info包含:
  17. - status: "existing" | "new" | "invalid_id_new" | "no_permission"
  18. - message: 状态说明
  19. - requested_id: 原始请求的ID(如果有)
  20. """
  21. # 1. 如果指定了conversation_id,验证后使用
  22. if conversation_id_input:
  23. validation_result = self._validate_conversation_access(conversation_id_input, user_id)
  24. if validation_result["valid"]:
  25. print(f"[REDIS_CONV] 使用指定对话: {conversation_id_input}")
  26. return conversation_id_input, {
  27. "status": "existing",
  28. "message": "继续已有对话"
  29. }
  30. else:
  31. # 根据不同的无效原因返回不同的状态
  32. if validation_result["reason"] == "not_found":
  33. print(f"[WARN] 对话不存在: {conversation_id_input},创建新对话")
  34. new_conversation_id = self.create_conversation(user_id)
  35. return new_conversation_id, {
  36. "status": "invalid_id_new",
  37. "message": "您请求的对话不存在或已过期,已为您创建新对话",
  38. "requested_id": conversation_id_input,
  39. "reason": "not_found"
  40. }
  41. elif validation_result["reason"] == "no_permission":
  42. print(f"[WARN] 无权访问对话: {conversation_id_input},创建新对话")
  43. new_conversation_id = self.create_conversation(user_id)
  44. return new_conversation_id, {
  45. "status": "no_permission",
  46. "message": "您没有权限访问该对话,已为您创建新对话",
  47. "requested_id": conversation_id_input,
  48. "reason": "no_permission"
  49. }
  50. # 2. 如果要继续最近对话
  51. if continue_conversation:
  52. recent_conversation = self._get_recent_conversation(user_id)
  53. if recent_conversation:
  54. print(f"[REDIS_CONV] 继续最近对话: {recent_conversation}")
  55. return recent_conversation, {
  56. "status": "existing",
  57. "message": "继续最近对话"
  58. }
  59. # 3. 创建新对话
  60. new_conversation_id = self.create_conversation(user_id)
  61. print(f"[REDIS_CONV] 创建新对话: {new_conversation_id}")
  62. return new_conversation_id, {
  63. "status": "new",
  64. "message": "创建新对话"
  65. }
  66. def _validate_conversation_access(self, conversation_id: str, user_id: str) -> Dict:
  67. """
  68. 验证对话访问权限
  69. Returns:
  70. dict: {
  71. "valid": bool,
  72. "reason": "not_found" | "no_permission" | None
  73. }
  74. """
  75. # 这里是示例实现
  76. # 实际实现需要查询Redis
  77. # 检查对话是否存在
  78. if not self._conversation_exists(conversation_id):
  79. return {"valid": False, "reason": "not_found"}
  80. # 检查用户权限
  81. if not self._user_has_permission(conversation_id, user_id):
  82. return {"valid": False, "reason": "no_permission"}
  83. return {"valid": True, "reason": None}
  84. def _conversation_exists(self, conversation_id: str) -> bool:
  85. """检查对话是否存在"""
  86. # 示例实现 - 根据ID模拟不同场景
  87. if "not_exist" in conversation_id:
  88. return False
  89. return True
  90. def _user_has_permission(self, conversation_id: str, user_id: str) -> bool:
  91. """检查用户是否有权限访问对话"""
  92. # 示例实现 - 根据ID模拟不同场景
  93. if "other_user" in conversation_id:
  94. return False
  95. return True
  96. def _get_recent_conversation(self, user_id: str) -> Optional[str]:
  97. """获取用户最近的对话"""
  98. # 示例实现
  99. return None
  100. def create_conversation(self, user_id: str) -> str:
  101. """创建新对话"""
  102. # 示例实现
  103. import uuid
  104. from datetime import datetime
  105. timestamp = int(datetime.now().timestamp())
  106. return f"conv_{timestamp}_{uuid.uuid4().hex[:8]}"
  107. # 使用示例
  108. def demo_usage():
  109. """演示如何使用改进版的对话管理器"""
  110. manager = ImprovedRedisConversationManager()
  111. # 场景1:请求不存在的对话
  112. print("=== 场景1:请求不存在的对话 ===")
  113. conv_id, status = manager.resolve_conversation_id(
  114. user_id="user_123",
  115. conversation_id_input="conv_not_exist",
  116. continue_conversation=False
  117. )
  118. print(f"返回的对话ID: {conv_id}")
  119. print(f"状态信息: {status}")
  120. print()
  121. # 场景2:请求无权限的对话
  122. print("=== 场景2:请求无权限的对话 ===")
  123. conv_id, status = manager.resolve_conversation_id(
  124. user_id="user_456",
  125. conversation_id_input="conv_belongs_to_other_user",
  126. continue_conversation=False
  127. )
  128. print(f"返回的对话ID: {conv_id}")
  129. print(f"状态信息: {status}")
  130. print()
  131. # 场景3:创建新对话
  132. print("=== 场景3:创建新对话 ===")
  133. conv_id, status = manager.resolve_conversation_id(
  134. user_id="user_789",
  135. conversation_id_input=None,
  136. continue_conversation=False
  137. )
  138. print(f"返回的对话ID: {conv_id}")
  139. print(f"状态信息: {status}")
  140. # API响应增强示例
  141. def enhanced_ask_agent_response(conversation_status: Dict) -> Dict:
  142. """展示如何在API响应中包含对话状态信息"""
  143. # 基础响应
  144. response = {
  145. "success": True,
  146. "code": 200,
  147. "message": "操作成功",
  148. "data": {
  149. "response": "这是AI的回答...",
  150. "type": "DATABASE",
  151. "conversation_id": "conv_1234567890_abc123",
  152. "user_id": "user_123"
  153. }
  154. }
  155. # 添加对话状态信息
  156. response["data"].update({
  157. "conversation_status": conversation_status["status"],
  158. "conversation_message": conversation_status["message"],
  159. "requested_conversation_id": conversation_status.get("requested_id")
  160. })
  161. return response
  162. # 前端处理示例(JavaScript风格的Python代码)
  163. def frontend_handling_example():
  164. """展示前端如何处理不同的对话状态"""
  165. # 模拟API响应
  166. api_responses = [
  167. {
  168. "data": {
  169. "conversation_status": "invalid_id_new",
  170. "conversation_message": "您请求的对话不存在或已过期,已为您创建新对话",
  171. "requested_conversation_id": "conv_old_123"
  172. }
  173. },
  174. {
  175. "data": {
  176. "conversation_status": "no_permission",
  177. "conversation_message": "您没有权限访问该对话,已为您创建新对话",
  178. "requested_conversation_id": "conv_other_user"
  179. }
  180. },
  181. {
  182. "data": {
  183. "conversation_status": "existing",
  184. "conversation_message": "继续已有对话"
  185. }
  186. }
  187. ]
  188. # 处理不同状态
  189. for response in api_responses:
  190. status = response["data"]["conversation_status"]
  191. message = response["data"]["conversation_message"]
  192. if status == "invalid_id_new":
  193. print(f"⚠️ 警告通知: {message}")
  194. print(f" 原请求ID: {response['data'].get('requested_conversation_id')}")
  195. print(" [更新本地conversation_id]")
  196. elif status == "no_permission":
  197. print(f"🚫 权限通知: {message}")
  198. print(f" 原请求ID: {response['data'].get('requested_conversation_id')}")
  199. print(" [清除本地无效的conversation_id]")
  200. elif status == "existing":
  201. print(f"✅ 成功: {message}")
  202. print()
  203. if __name__ == "__main__":
  204. # 运行演示
  205. demo_usage()
  206. print("\n" + "="*50 + "\n")
  207. # 展示API响应增强
  208. print("=== API响应增强示例 ===")
  209. status_info = {
  210. "status": "invalid_id_new",
  211. "message": "您请求的对话不存在或已过期,已为您创建新对话",
  212. "requested_id": "conv_old_123"
  213. }
  214. enhanced_response = enhanced_ask_agent_response(status_info)
  215. import json
  216. print(json.dumps(enhanced_response, indent=2, ensure_ascii=False))
  217. print("\n" + "="*50 + "\n")
  218. # 展示前端处理
  219. print("=== 前端处理示例 ===")
  220. frontend_handling_example()