david commited on
Commit
70aabba
·
1 Parent(s): c8c0e6e

Integrating RAGFlow API as a Plugin into ChatGPT-on-WeChat (#2988)

Browse files

### What problem does this PR solve?

This PR introduces the `ragflow_chat` plugin for the ChatGPT-on-WeChat
project, extending its functionality by integrating Retrieval-Augmented
Generation (RAG) capabilities. It allows users to have more contextually
relevant conversations by retrieving information from external knowledge
sources (via the RAGFlow API) and incorporating it into their chat
interactions.

The primary goal of this PR is to enable seamless communication between
ChatGPT-on-WeChat and the RAGFlow server, improving response accuracy by
embedding knowledge-based data into conversational flows. This is
particularly useful for users who need more complex, data-driven
responses.

This PR adds a new plugin that enhances ChatGPT-on-WeChat with Ragflow
capabilities, allowing for a more enriched conversational experience
driven by external knowledge.

### Type of change

- [x] New Feature (non-breaking change which adds functionality)

intergrations/chatgpt-on-wechat/plugins/README.md ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ RAGFlow Chat Plugin for ChatGPT-on-WeChat
2
+ =========================================
3
+
4
+ This folder contains the source code for the `ragflow_chat` plugin, which extends the core functionality of the RAGFlow API to support conversational interactions using Retrieval-Augmented Generation (RAG). This plugin integrates seamlessly with the [ChatGPT-on-WeChat](https://github.com/zhayujie/chatgpt-on-wechat) project, enabling WeChat and other platforms to leverage the knowledge retrieval capabilities provided by RAGFlow in chat interactions.
5
+
6
+ ### Features
7
+ * **Conversational Interactions**: Combine WeChat's conversational interface with powerful RAG (Retrieval-Augmented Generation) capabilities.
8
+ * **Knowledge-Based Responses**: Enrich conversations by retrieving relevant data from external knowledge sources and incorporating them into chat responses.
9
+ * **Multi-Platform Support**: Works across WeChat, WeCom, and various other platforms supported by the ChatGPT-on-WeChat framework.
10
+
11
+ ### Plugin vs. ChatGPT-on-WeChat Configurations
12
+ **Note**: There are two distinct configuration files used in this setup—one for the ChatGPT-on-WeChat core project and another specific to the `ragflow_chat` plugin. It is important to configure both correctly to ensure smooth integration.
13
+
14
+ #### ChatGPT-on-WeChat Root Configuration (`config.json`)
15
+ This file is located in the root directory of the [ChatGPT-on-WeChat](https://github.com/zhayujie/chatgpt-on-wechat) project and is responsible for defining the communication channels and overall behavior. For example, it handles the configuration for WeChat, WeCom, and other services like Feishu and DingTalk.
16
+
17
+ Example `config.json` (for WeChat channel):
18
+ ```json
19
+ {
20
+ "channel_type": "wechatmp",
21
+ "wechatmp_app_id": "YOUR_APP_ID",
22
+ "wechatmp_app_secret": "YOUR_APP_SECRET",
23
+ "wechatmp_token": "YOUR_TOKEN",
24
+ "wechatmp_port": 80,
25
+ ...
26
+ }
27
+ ```
28
+
29
+ This file can also be modified to support other communication platforms, such as:
30
+ - **Personal WeChat** (`channel_type: wx`)
31
+ - **WeChat Public Account** (`wechatmp` or `wechatmp_service`)
32
+ - **WeChat Work (WeCom)** (`wechatcom_app`)
33
+ - **Feishu** (`feishu`)
34
+ - **DingTalk** (`dingtalk`)
35
+
36
+ For detailed configuration options, see the official [LinkAI documentation](https://docs.link-ai.tech/cow/multi-platform/wechat-mp).
37
+
38
+ #### RAGFlow Chat Plugin Configuration (`plugins/ragflow_chat/config.json`)
39
+ This configuration is specific to the `ragflow_chat` plugin and is used to set up communication with the RAGFlow server. Ensure that your RAGFlow server is running, and update the plugin's `config.json` file with your server details:
40
+
41
+ Example `config.json` (for `ragflow_chat`):
42
+ ```json
43
+ {
44
+ "ragflow_api_key": "YOUR_API_KEY",
45
+ "ragflow_host": "127.0.0.1:80"
46
+ }
47
+ ```
48
+
49
+ This file must be configured to point to your RAGFlow instance, with the `ragflow_api_key` and `ragflow_host` fields set appropriately. The `ragflow_host` is typically your server's address and port number, and the `ragflow_api_key` is obtained from your RAGFlow API setup.
50
+
51
+ ### Requirements
52
+ Before you can use this plugin, ensure the following are in place:
53
+
54
+ 1. You have installed and configured [ChatGPT-on-WeChat](https://github.com/zhayujie/chatgpt-on-wechat).
55
+ 2. You have deployed and are running the [RAGFlow](https://github.com/jina-ai/ragflow) server.
56
+
57
+ Make sure both `config.json` files (ChatGPT-on-WeChat and RAGFlow Chat Plugin) are correctly set up as per the examples above.
intergrations/chatgpt-on-wechat/plugins/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .ragflow_chat import *
intergrations/chatgpt-on-wechat/plugins/config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "api_key": "ragflow-***",
3
+ "host_address": "127.0.0.1:80"
4
+ }
intergrations/chatgpt-on-wechat/plugins/ragflow_chat.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
11
+ @register(name="RAGFlowChat", desc="Use RAGFlow API to chat", version="1.0", author="Your Name")
12
+ class RAGFlowChat(Plugin):
13
+ def __init__(self):
14
+ super().__init__()
15
+ # Load plugin configuration
16
+ self.cfg = self.load_config()
17
+ # Bind event handling function
18
+ self.handlers[Event.ON_HANDLE_CONTEXT] = self.on_handle_context
19
+ # Store conversation_id for each user
20
+ self.conversations = {}
21
+ logger.info("[RAGFlowChat] Plugin initialized")
22
+
23
+ def on_handle_context(self, e_context: EventContext):
24
+ context = e_context['context']
25
+ if context.type != ContextType.TEXT:
26
+ return # Only process text messages
27
+
28
+ user_input = context.content.strip()
29
+ session_id = context['session_id']
30
+
31
+ # Call RAGFlow API to get a reply
32
+ reply_text = self.get_ragflow_reply(user_input, session_id)
33
+ if reply_text:
34
+ reply = Reply()
35
+ reply.type = ReplyType.TEXT
36
+ reply.content = reply_text
37
+ e_context['reply'] = reply
38
+ e_context.action = EventAction.BREAK_PASS # Skip the default processing logic
39
+ else:
40
+ # If no reply is received, pass to the next plugin or default logic
41
+ e_context.action = EventAction.CONTINUE
42
+
43
+ def get_ragflow_reply(self, user_input, session_id):
44
+ # Get API_KEY and host address from the configuration
45
+ api_key = self.cfg.get("api_key")
46
+ host_address = self.cfg.get("host_address")
47
+ user_id = session_id # Use session_id as user_id
48
+
49
+ if not api_key or not host_address:
50
+ logger.error("[RAGFlowChat] Missing configuration")
51
+ return "The plugin configuration is incomplete. Please check the configuration."
52
+
53
+ headers = {
54
+ "Authorization": f"Bearer {api_key}",
55
+ "Content-Type": "application/json"
56
+ }
57
+
58
+ # Step 1: Get or create conversation_id
59
+ conversation_id = self.conversations.get(user_id)
60
+ if not conversation_id:
61
+ # Create a new conversation
62
+ url_new_conversation = f"http://{host_address}/v1/api/new_conversation"
63
+ params_new_conversation = {
64
+ "user_id": user_id
65
+ }
66
+ try:
67
+ response = requests.get(url_new_conversation, headers=headers, params=params_new_conversation)
68
+ logger.debug(f"[RAGFlowChat] New conversation response: {response.text}")
69
+ if response.status_code == 200:
70
+ data = response.json()
71
+ if data.get("retcode") == 0:
72
+ conversation_id = data["data"]["id"]
73
+ self.conversations[user_id] = conversation_id
74
+ else:
75
+ logger.error(f"[RAGFlowChat] Failed to create conversation: {data.get('retmsg')}")
76
+ return f"Sorry, unable to create a conversation: {data.get('retmsg')}"
77
+ else:
78
+ logger.error(f"[RAGFlowChat] HTTP error when creating conversation: {response.status_code}")
79
+ return f"Sorry, unable to connect to RAGFlow API (create conversation). HTTP status code: {response.status_code}"
80
+ except Exception as e:
81
+ logger.exception(f"[RAGFlowChat] Exception when creating conversation: {e}")
82
+ return f"Sorry, an internal error occurred: {str(e)}"
83
+
84
+ # Step 2: Send the message and get a reply
85
+ url_completion = f"http://{host_address}/v1/api/completion"
86
+ payload_completion = {
87
+ "conversation_id": conversation_id,
88
+ "messages": [
89
+ {
90
+ "role": "user",
91
+ "content": user_input
92
+ }
93
+ ],
94
+ "quote": False,
95
+ "stream": False
96
+ }
97
+
98
+ try:
99
+ response = requests.post(url_completion, headers=headers, json=payload_completion)
100
+ logger.debug(f"[RAGFlowChat] Completion response: {response.text}")
101
+ if response.status_code == 200:
102
+ data = response.json()
103
+ if data.get("retcode") == 0:
104
+ answer = data["data"]["answer"]
105
+ return answer
106
+ else:
107
+ logger.error(f"[RAGFlowChat] Failed to get answer: {data.get('retmsg')}")
108
+ return f"Sorry, unable to get a reply: {data.get('retmsg')}"
109
+ else:
110
+ logger.error(f"[RAGFlowChat] HTTP error when getting answer: {response.status_code}")
111
+ return f"Sorry, unable to connect to RAGFlow API (get reply). HTTP status code: {response.status_code}"
112
+ except Exception as e:
113
+ logger.exception(f"[RAGFlowChat] Exception when getting answer: {e}")
114
+ return f"Sorry, an internal error occurred: {str(e)}"
intergrations/chatgpt-on-wechat/plugins/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ requests