Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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