You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ragflow_chat.py 5.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. import requests
  2. import json
  3. from bridge.context import Context, ContextType # Import Context, ContextType
  4. from bridge.reply import Reply, ReplyType # Import Reply, ReplyType
  5. from bridge import *
  6. from common.log import logger
  7. from config import conf
  8. from plugins import Plugin, register # Import Plugin and register
  9. from plugins.event import Event, EventContext, EventAction # Import event-related classes
  10. @register(name="RAGFlowChat", desc="Use RAGFlow API to chat", version="1.0", author="Your Name")
  11. class RAGFlowChat(Plugin):
  12. def __init__(self):
  13. super().__init__()
  14. # Load plugin configuration
  15. self.cfg = self.load_config()
  16. # Bind event handling function
  17. self.handlers[Event.ON_HANDLE_CONTEXT] = self.on_handle_context
  18. # Store conversation_id for each user
  19. self.conversations = {}
  20. logger.info("[RAGFlowChat] Plugin initialized")
  21. def on_handle_context(self, e_context: EventContext):
  22. context = e_context['context']
  23. if context.type != ContextType.TEXT:
  24. return # Only process text messages
  25. user_input = context.content.strip()
  26. session_id = context['session_id']
  27. # Call RAGFlow API to get a reply
  28. reply_text = self.get_ragflow_reply(user_input, session_id)
  29. if reply_text:
  30. reply = Reply()
  31. reply.type = ReplyType.TEXT
  32. reply.content = reply_text
  33. e_context['reply'] = reply
  34. e_context.action = EventAction.BREAK_PASS # Skip the default processing logic
  35. else:
  36. # If no reply is received, pass to the next plugin or default logic
  37. e_context.action = EventAction.CONTINUE
  38. def get_ragflow_reply(self, user_input, session_id):
  39. # Get API_KEY and host address from the configuration
  40. api_key = self.cfg.get("api_key")
  41. host_address = self.cfg.get("host_address")
  42. user_id = session_id # Use session_id as user_id
  43. if not api_key or not host_address:
  44. logger.error("[RAGFlowChat] Missing configuration")
  45. return "The plugin configuration is incomplete. Please check the configuration."
  46. headers = {
  47. "Authorization": f"Bearer {api_key}",
  48. "Content-Type": "application/json"
  49. }
  50. # Step 1: Get or create conversation_id
  51. conversation_id = self.conversations.get(user_id)
  52. if not conversation_id:
  53. # Create a new conversation
  54. url_new_conversation = f"http://{host_address}/v1/api/new_conversation"
  55. params_new_conversation = {
  56. "user_id": user_id
  57. }
  58. try:
  59. response = requests.get(url_new_conversation, headers=headers, params=params_new_conversation)
  60. logger.debug(f"[RAGFlowChat] New conversation response: {response.text}")
  61. if response.status_code == 200:
  62. data = response.json()
  63. if data.get("retcode") == 0:
  64. conversation_id = data["data"]["id"]
  65. self.conversations[user_id] = conversation_id
  66. else:
  67. logger.error(f"[RAGFlowChat] Failed to create conversation: {data.get('retmsg')}")
  68. return f"Sorry, unable to create a conversation: {data.get('retmsg')}"
  69. else:
  70. logger.error(f"[RAGFlowChat] HTTP error when creating conversation: {response.status_code}")
  71. return f"Sorry, unable to connect to RAGFlow API (create conversation). HTTP status code: {response.status_code}"
  72. except Exception as e:
  73. logger.exception(f"[RAGFlowChat] Exception when creating conversation: {e}")
  74. return f"Sorry, an internal error occurred: {str(e)}"
  75. # Step 2: Send the message and get a reply
  76. url_completion = f"http://{host_address}/v1/api/completion"
  77. payload_completion = {
  78. "conversation_id": conversation_id,
  79. "messages": [
  80. {
  81. "role": "user",
  82. "content": user_input
  83. }
  84. ],
  85. "quote": False,
  86. "stream": False
  87. }
  88. try:
  89. response = requests.post(url_completion, headers=headers, json=payload_completion)
  90. logger.debug(f"[RAGFlowChat] Completion response: {response.text}")
  91. if response.status_code == 200:
  92. data = response.json()
  93. if data.get("retcode") == 0:
  94. answer = data["data"]["answer"]
  95. return answer
  96. else:
  97. logger.error(f"[RAGFlowChat] Failed to get answer: {data.get('retmsg')}")
  98. return f"Sorry, unable to get a reply: {data.get('retmsg')}"
  99. else:
  100. logger.error(f"[RAGFlowChat] HTTP error when getting answer: {response.status_code}")
  101. return f"Sorry, unable to connect to RAGFlow API (get reply). HTTP status code: {response.status_code}"
  102. except Exception as e:
  103. logger.exception(f"[RAGFlowChat] Exception when getting answer: {e}")
  104. return f"Sorry, an internal error occurred: {str(e)}"