Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. #
  2. # Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import logging
  17. import requests
  18. from bridge.context import ContextType # Import Context, ContextType
  19. from bridge.reply import Reply, ReplyType # Import Reply, ReplyType
  20. from plugins import Plugin, register # Import Plugin and register
  21. from plugins.event import Event, EventContext, EventAction # Import event-related classes
  22. @register(name="RAGFlowChat", desc="Use RAGFlow API to chat", version="1.0", author="Your Name")
  23. class RAGFlowChat(Plugin):
  24. def __init__(self):
  25. super().__init__()
  26. # Load plugin configuration
  27. self.cfg = self.load_config()
  28. # Bind event handling function
  29. self.handlers[Event.ON_HANDLE_CONTEXT] = self.on_handle_context
  30. # Store conversation_id for each user
  31. self.conversations = {}
  32. logging.info("[RAGFlowChat] Plugin initialized")
  33. def on_handle_context(self, e_context: EventContext):
  34. context = e_context['context']
  35. if context.type != ContextType.TEXT:
  36. return # Only process text messages
  37. user_input = context.content.strip()
  38. session_id = context['session_id']
  39. # Call RAGFlow API to get a reply
  40. reply_text = self.get_ragflow_reply(user_input, session_id)
  41. if reply_text:
  42. reply = Reply()
  43. reply.type = ReplyType.TEXT
  44. reply.content = reply_text
  45. e_context['reply'] = reply
  46. e_context.action = EventAction.BREAK_PASS # Skip the default processing logic
  47. else:
  48. # If no reply is received, pass to the next plugin or default logic
  49. e_context.action = EventAction.CONTINUE
  50. def get_ragflow_reply(self, user_input, session_id):
  51. # Get API_KEY and host address from the configuration
  52. api_key = self.cfg.get("api_key")
  53. host_address = self.cfg.get("host_address")
  54. user_id = session_id # Use session_id as user_id
  55. if not api_key or not host_address:
  56. logging.error("[RAGFlowChat] Missing configuration")
  57. return "The plugin configuration is incomplete. Please check the configuration."
  58. headers = {
  59. "Authorization": f"Bearer {api_key}",
  60. "Content-Type": "application/json"
  61. }
  62. # Step 1: Get or create conversation_id
  63. conversation_id = self.conversations.get(user_id)
  64. if not conversation_id:
  65. # Create a new conversation
  66. url_new_conversation = f"http://{host_address}/v1/api/new_conversation"
  67. params_new_conversation = {
  68. "user_id": user_id
  69. }
  70. try:
  71. response = requests.get(url_new_conversation, headers=headers, params=params_new_conversation)
  72. logging.debug(f"[RAGFlowChat] New conversation response: {response.text}")
  73. if response.status_code == 200:
  74. data = response.json()
  75. if data.get("code") == 0:
  76. conversation_id = data["data"]["id"]
  77. self.conversations[user_id] = conversation_id
  78. else:
  79. logging.error(f"[RAGFlowChat] Failed to create conversation: {data.get('message')}")
  80. return f"Sorry, unable to create a conversation: {data.get('message')}"
  81. else:
  82. logging.error(f"[RAGFlowChat] HTTP error when creating conversation: {response.status_code}")
  83. return f"Sorry, unable to connect to RAGFlow API (create conversation). HTTP status code: {response.status_code}"
  84. except Exception as e:
  85. logging.exception("[RAGFlowChat] Exception when creating conversation")
  86. return f"Sorry, an internal error occurred: {str(e)}"
  87. # Step 2: Send the message and get a reply
  88. url_completion = f"http://{host_address}/v1/api/completion"
  89. payload_completion = {
  90. "conversation_id": conversation_id,
  91. "messages": [
  92. {
  93. "role": "user",
  94. "content": user_input
  95. }
  96. ],
  97. "quote": False,
  98. "stream": False
  99. }
  100. try:
  101. response = requests.post(url_completion, headers=headers, json=payload_completion)
  102. logging.debug(f"[RAGFlowChat] Completion response: {response.text}")
  103. if response.status_code == 200:
  104. data = response.json()
  105. if data.get("code") == 0:
  106. answer = data["data"]["answer"]
  107. return answer
  108. else:
  109. logging.error(f"[RAGFlowChat] Failed to get answer: {data.get('message')}")
  110. return f"Sorry, unable to get a reply: {data.get('message')}"
  111. else:
  112. logging.error(f"[RAGFlowChat] HTTP error when getting answer: {response.status_code}")
  113. return f"Sorry, unable to connect to RAGFlow API (get reply). HTTP status code: {response.status_code}"
  114. except Exception as e:
  115. logging.exception("[RAGFlowChat] Exception when getting answer")
  116. return f"Sorry, an internal error occurred: {str(e)}"