Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

ragflow_chat.py 5.1KB

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