ragflow-cli-myfbee-test 0.27.2.dev0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ragflow_cli.py ADDED
@@ -0,0 +1,330 @@
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
+
17
+ import sys
18
+ import argparse
19
+ import base64
20
+ import getpass
21
+ import os
22
+ import atexit
23
+ import readline
24
+ from cmd import Cmd
25
+ from typing import Any, Dict, List
26
+
27
+ import requests
28
+ import warnings
29
+ from Cryptodome.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
30
+ from Cryptodome.PublicKey import RSA
31
+ from lark import Lark, Tree
32
+ from parser import GRAMMAR, RAGFlowCLITransformer
33
+ from http_client import HttpClient
34
+ from ragflow_client import RAGFlowClient, run_command
35
+ from user import login_user
36
+
37
+ warnings.filterwarnings("ignore", category=getpass.GetPassWarning)
38
+
39
+
40
+ def encrypt(input_string):
41
+ pub = "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArq9XTUSeYr2+N1h3Afl/z8Dse/2yD0ZGrKwx+EEEcdsBLca9Ynmx3nIB5obmLlSfmskLpBo0UACBmB5rEjBp2Q2f3AG3Hjd4B+gNCG6BDaawuDlgANIhGnaTLrIqWrrcm4EMzJOnAOI1fgzJRsOOUEfaS318Eq9OVO3apEyCCt0lOQK6PuksduOjVxtltDav+guVAA068NrPYmRNabVKRNLJpL8w4D44sfth5RvZ3q9t+6RTArpEtc5sh5ChzvqPOzKGMXW83C95TxmXqpbK6olN4RevSfVjEAgCydH6HN6OhtOQEcnrU97r9H0iZOWwbw3pVrZiUkuRD1R56Wzs2wIDAQAB\n-----END PUBLIC KEY-----"
42
+ pub_key = RSA.importKey(pub)
43
+ cipher = Cipher_pkcs1_v1_5.new(pub_key)
44
+ cipher_text = cipher.encrypt(base64.b64encode(input_string.encode("utf-8")))
45
+ return base64.b64encode(cipher_text).decode("utf-8")
46
+
47
+
48
+ def encode_to_base64(input_string):
49
+ base64_encoded = base64.b64encode(input_string.encode("utf-8"))
50
+ return base64_encoded.decode("utf-8")
51
+
52
+
53
+ class RAGFlowCLI(Cmd):
54
+ def __init__(self):
55
+ super().__init__()
56
+ self.parser = Lark(GRAMMAR, start="start", parser="lalr", transformer=RAGFlowCLITransformer())
57
+ self.command_history = []
58
+ self.account = "admin@ragflow.io"
59
+ self.account_password: str = "admin"
60
+ self.session = requests.Session()
61
+ self.host: str = ""
62
+ self.port: int = 0
63
+ self.mode: str = "admin"
64
+ self.ragflow_client = None
65
+ # History file for readline persistence
66
+ self.history_file = os.path.expanduser("~/.ragflow_cli_history")
67
+ # Load existing history
68
+ self._load_history()
69
+ # Register cleanup to save history on exit
70
+ atexit.register(self._save_history)
71
+
72
+ intro = r"""Type "\h" for help."""
73
+ prompt = "ragflow> "
74
+
75
+ def onecmd(self, command: str) -> bool:
76
+ try:
77
+ result = self.parse_command(command)
78
+
79
+ if isinstance(result, dict):
80
+ if "type" in result and result.get("type") == "empty":
81
+ return False
82
+
83
+ self.execute_command(result)
84
+
85
+ if isinstance(result, Tree):
86
+ return False
87
+
88
+ if result.get("type") == "meta" and result.get("command") in ["q", "quit", "exit"]:
89
+ return True
90
+
91
+ except KeyboardInterrupt:
92
+ print("\nUse '\\q' to quit")
93
+ except EOFError:
94
+ print("\nGoodbye!")
95
+ return True
96
+ return False
97
+
98
+ def emptyline(self) -> bool:
99
+ return False
100
+
101
+ def default(self, line: str) -> bool:
102
+ return self.onecmd(line)
103
+
104
+ def parse_command(self, command_str: str) -> dict[str, str]:
105
+ if not command_str.strip():
106
+ return {"type": "empty"}
107
+
108
+ self.command_history.append(command_str)
109
+ readline.add_history(command_str)
110
+
111
+ try:
112
+ result = self.parser.parse(command_str)
113
+ return result
114
+ except Exception as e:
115
+ return {"type": "error", "message": f"Parse error: {str(e)}"}
116
+
117
+ def verify_auth(self, arguments: dict, single_command: bool, auth: bool):
118
+ server_type = arguments.get("type", "admin")
119
+ http_client = HttpClient(arguments["host"], arguments["port"])
120
+ if not auth:
121
+ self.ragflow_client = RAGFlowClient(http_client, server_type)
122
+ return True
123
+
124
+ user_name = arguments["username"]
125
+ attempt_count = 3
126
+ if single_command:
127
+ attempt_count = 1
128
+
129
+ try_count = 0
130
+ while True:
131
+ try_count += 1
132
+ if try_count > attempt_count:
133
+ return False
134
+
135
+ if single_command:
136
+ user_password = arguments["password"]
137
+ else:
138
+ user_password = getpass.getpass(f"password for {user_name}: ").strip()
139
+
140
+ try:
141
+ token = login_user(http_client, server_type, user_name, user_password)
142
+ http_client.login_token = token
143
+ self.ragflow_client = RAGFlowClient(http_client, server_type)
144
+ return True
145
+ except Exception as e:
146
+ print(str(e))
147
+ print("Can't access server for login (connection failed)")
148
+
149
+ def _format_service_detail_table(self, data):
150
+ if isinstance(data, list):
151
+ return data
152
+ if not all([isinstance(v, list) for v in data.values()]):
153
+ # normal table
154
+ return data
155
+ # handle task_executor heartbeats map, for example {'name': [{'done': 2, 'now': timestamp1}, {'done': 3, 'now': timestamp2}]
156
+ task_executor_list = []
157
+ for k, v in data.items():
158
+ # display latest status
159
+ heartbeats = sorted(v, key=lambda x: x["now"], reverse=True)
160
+ task_executor_list.append(
161
+ {
162
+ "task_executor_name": k,
163
+ **heartbeats[0],
164
+ }
165
+ if heartbeats
166
+ else {"task_executor_name": k}
167
+ )
168
+ return task_executor_list
169
+
170
+ def _print_table_simple(self, data):
171
+ if not data:
172
+ print("No data to print")
173
+ return
174
+ if isinstance(data, dict):
175
+ # handle single row data
176
+ data = [data]
177
+
178
+ columns = list(set().union(*(d.keys() for d in data)))
179
+ columns.sort()
180
+ col_widths = {}
181
+
182
+ def get_string_width(text):
183
+ half_width_chars = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\t\n\r"
184
+ width = 0
185
+ for char in text:
186
+ if char in half_width_chars:
187
+ width += 1
188
+ else:
189
+ width += 2
190
+ return width
191
+
192
+ for col in columns:
193
+ max_width = get_string_width(str(col))
194
+ for item in data:
195
+ value_len = get_string_width(str(item.get(col, "")))
196
+ if value_len > max_width:
197
+ max_width = value_len
198
+ col_widths[col] = max(2, max_width)
199
+
200
+ # Generate delimiter
201
+ separator = "+" + "+".join(["-" * (col_widths[col] + 2) for col in columns]) + "+"
202
+
203
+ # Print header
204
+ print(separator)
205
+ header = "|" + "|".join([f" {col:<{col_widths[col]}} " for col in columns]) + "|"
206
+ print(header)
207
+ print(separator)
208
+
209
+ # Print data
210
+ for item in data:
211
+ row = "|"
212
+ for col in columns:
213
+ value = str(item.get(col, ""))
214
+ if get_string_width(value) > col_widths[col]:
215
+ value = value[: col_widths[col] - 3] + "..."
216
+ row += f" {value:<{col_widths[col] - (get_string_width(value) - len(value))}} |"
217
+ print(row)
218
+
219
+ print(separator)
220
+
221
+ def _load_history(self):
222
+ """Load command history from file."""
223
+ try:
224
+ if os.path.exists(self.history_file):
225
+ readline.read_history_file(self.history_file)
226
+ except Exception:
227
+ pass # Ignore errors loading history
228
+
229
+ def _save_history(self):
230
+ """Save command history to file."""
231
+ try:
232
+ readline.write_history_file(self.history_file)
233
+ except Exception:
234
+ pass # Ignore errors saving history
235
+
236
+ def run_interactive(self, args):
237
+ if self.verify_auth(args, single_command=False, auth=args["auth"]):
238
+ print(r"""
239
+ ____ ___ ______________ ________ ____
240
+ / __ \/ | / ____/ ____/ /___ _ __ / ____/ / / _/
241
+ / /_/ / /| |/ / __/ /_ / / __ \ | /| / / / / / / / /
242
+ / _, _/ ___ / /_/ / __/ / / /_/ / |/ |/ / / /___/ /____/ /
243
+ /_/ |_/_/ |_\____/_/ /_/\____/|__/|__/ \____/_____/___/
244
+ """)
245
+ self.cmdloop()
246
+
247
+ print("RAGFlow command line interface - Type '\\?' for help, '\\q' to quit")
248
+
249
+ def run_single_command(self, args):
250
+ if self.verify_auth(args, single_command=True, auth=args["auth"]):
251
+ command = args["command"]
252
+ result = self.parse_command(command)
253
+ self.execute_command(result)
254
+
255
+ def parse_connection_args(self, args: List[str]) -> Dict[str, Any]:
256
+ parser = argparse.ArgumentParser(description="RAGFlow CLI Client", add_help=False)
257
+ parser.add_argument("-h", "--host", default="127.0.0.1", help="Admin or RAGFlow service host")
258
+ parser.add_argument("-p", "--port", type=int, default=9381, help="Admin or RAGFlow service port")
259
+ parser.add_argument("-w", "--password", default="admin", type=str, help="Superuser password")
260
+ parser.add_argument("-t", "--type", default="admin", type=str, help="CLI mode, admin or user")
261
+ parser.add_argument("-u", "--username", default=None, help="Username (email). In admin mode defaults to admin@ragflow.io, in user mode required.")
262
+ parser.add_argument("command", nargs="?", help="Single command")
263
+ try:
264
+ parsed_args, remaining_args = parser.parse_known_args(args)
265
+ # Determine username based on mode
266
+ username = parsed_args.username
267
+ if parsed_args.type == "admin":
268
+ if username is None:
269
+ username = "admin@ragflow.io"
270
+
271
+ if remaining_args:
272
+ if remaining_args[0] == "command":
273
+ command_str = " ".join(remaining_args[1:]) + ";"
274
+ auth = True
275
+ if remaining_args[1] == "register":
276
+ auth = False
277
+ else:
278
+ if username is None:
279
+ print("Error: username (-u) is required in user mode")
280
+ return {"error": "Username required"}
281
+ return {"host": parsed_args.host, "port": parsed_args.port, "password": parsed_args.password, "type": parsed_args.type, "username": username, "command": command_str, "auth": auth}
282
+ else:
283
+ return {"error": "Invalid command"}
284
+ else:
285
+ auth = True
286
+ if username is None:
287
+ auth = False
288
+ return {"host": parsed_args.host, "port": parsed_args.port, "type": parsed_args.type, "username": username, "auth": auth}
289
+ except SystemExit:
290
+ return {"error": "Invalid connection arguments"}
291
+
292
+ def execute_command(self, parsed_command: Dict[str, Any]):
293
+ command_dict: dict
294
+ if isinstance(parsed_command, Tree):
295
+ command_dict = parsed_command.children[0]
296
+ else:
297
+ if parsed_command["type"] == "error":
298
+ print(f"Error: {parsed_command['message']}")
299
+ return
300
+ else:
301
+ command_dict = parsed_command
302
+
303
+ # print(f"Parsed command: {command_dict}")
304
+ run_command(self.ragflow_client, command_dict)
305
+
306
+
307
+ def main():
308
+
309
+ cli = RAGFlowCLI()
310
+
311
+ args = cli.parse_connection_args(sys.argv)
312
+ if "error" in args:
313
+ print("Error: Invalid connection arguments")
314
+ return
315
+
316
+ if "command" in args:
317
+ # single command mode
318
+ # for user mode, api key or password is ok
319
+ # for admin mode, only password
320
+ if "password" not in args:
321
+ print("Error: password is missing")
322
+ return
323
+
324
+ cli.run_single_command(args)
325
+ else:
326
+ cli.run_interactive(args)
327
+
328
+
329
+ if __name__ == "__main__":
330
+ main()
@@ -0,0 +1,150 @@
1
+ Metadata-Version: 2.4
2
+ Name: ragflow-cli-myfbee-test
3
+ Version: 0.27.2.dev0
4
+ Summary: Admin Service's client of [RAGFlow](https://github.com/infiniflow/ragflow). The Admin Service provides user management and system monitoring.
5
+ Author-email: Lynn <lynn_inf@hotmail.com>
6
+ License: Apache License, Version 2.0
7
+ Requires-Python: <3.14,>=3.13
8
+ Description-Content-Type: text/markdown
9
+ Requires-Dist: requests<3.0.0,>=2.30.0
10
+ Requires-Dist: beartype<1.0.0,>=0.22.9
11
+ Requires-Dist: pycryptodomex>=3.10.0
12
+ Requires-Dist: lark>=1.1.0
13
+ Requires-Dist: requests-toolbelt>=1.0.0
14
+
15
+ # RAGFlow Admin Service & CLI
16
+
17
+ ### Introduction
18
+
19
+ Admin Service is a dedicated management component designed to monitor, maintain, and administrate the RAGFlow system. It provides comprehensive tools for ensuring system stability, performing operational tasks, and managing users and permissions efficiently.
20
+
21
+ The service offers real-time monitoring of critical components, including the RAGFlow server, Task Executor processes, and dependent services such as MySQL, Infinity, Elasticsearch, Redis, and MinIO. It automatically checks their health status, resource usage, and uptime, and performs restarts in case of failures to minimize downtime.
22
+
23
+ For user and system management, it supports listing, creating, modifying, and deleting users and their associated resources like knowledge bases and Agents.
24
+
25
+ Built with scalability and reliability in mind, the Admin Service ensures smooth system operation and simplifies maintenance workflows.
26
+
27
+ It consists of a server-side Service and a command-line client (CLI), both implemented in Python. User commands are parsed using the Lark parsing toolkit.
28
+
29
+ - **Admin Service**: A backend service that interfaces with the RAGFlow system to execute administrative operations and monitor its status.
30
+ - **Admin CLI**: A command-line interface that allows users to connect to the Admin Service and issue commands for system management.
31
+
32
+
33
+
34
+ ### Starting the Admin Service
35
+
36
+ #### Launching from source code
37
+
38
+ 1. Before start Admin Service, please make sure RAGFlow system is already started.
39
+
40
+ 2. Launch from source code:
41
+
42
+ ```bash
43
+ python admin/server/admin_server.py
44
+ ```
45
+ The service will start and listen for incoming connections from the CLI on the configured port.
46
+
47
+ #### Using docker image
48
+
49
+ 1. Before startup, please configure the `docker_compose.yml` file to enable admin server:
50
+
51
+ ```bash
52
+ command:
53
+ - --enable-adminserver
54
+ ```
55
+
56
+ 2. Start the containers, the service will start and listen for incoming connections from the CLI on the configured port.
57
+
58
+
59
+
60
+ ### Using the Admin CLI
61
+
62
+ 1. Ensure the Admin Service is running.
63
+ 2. Install ragflow-cli.
64
+ ```bash
65
+ pip install ragflow-cli==0.27.2
66
+ ```
67
+ 3. Launch the CLI client:
68
+ ```bash
69
+ ragflow-cli -h 127.0.0.1 -p 9381
70
+ ```
71
+ You will be prompted to enter the superuser's password to log in.
72
+ The default password is admin.
73
+
74
+ **Parameters:**
75
+
76
+ - -h: RAGFlow admin server host address
77
+
78
+ - -p: RAGFlow admin server port
79
+
80
+
81
+
82
+ ## Supported Commands
83
+
84
+ Commands are case-insensitive and must be terminated with a semicolon (`;`).
85
+
86
+ ### Service Management Commands
87
+
88
+ - `LIST SERVICES;`
89
+ - Lists all available services within the RAGFlow system.
90
+ - `SHOW SERVICE <id>;`
91
+ - Shows detailed status information for the service identified by `<id>`.
92
+
93
+
94
+ ### User Management Commands
95
+
96
+ - `LIST USERS;`
97
+ - Lists all users known to the system.
98
+ - `SHOW USER '<username>';`
99
+ - Shows details and permissions for the specified user. The username must be enclosed in single or double quotes.
100
+
101
+ - `CREATE USER <username> <password>;`
102
+ - Create user by username and password. The username and password must be enclosed in single or double quotes.
103
+
104
+ - `DROP USER '<username>';`
105
+ - Removes the specified user from the system. Use with caution.
106
+ - `ALTER USER PASSWORD '<username>' '<new_password>';`
107
+ - Changes the password for the specified user.
108
+ - `ALTER USER ACTIVE <username> <on/off>;`
109
+ - Changes the user to active or inactive.
110
+
111
+
112
+ ### Data and Agent Commands
113
+
114
+ - `LIST DATASETS OF '<username>';`
115
+ - Lists the datasets associated with the specified user.
116
+ - `LIST AGENTS OF '<username>';`
117
+ - Lists the agents associated with the specified user.
118
+
119
+ ### Meta-Commands
120
+
121
+ Meta-commands are prefixed with a backslash (`\`).
122
+
123
+ - `\?` or `\help`
124
+ - Shows help information for the available commands.
125
+ - `\q` or `\quit`
126
+ - Exits the CLI application.
127
+
128
+ ## Examples
129
+
130
+ ```commandline
131
+ admin> list users;
132
+ +-------------------------------+------------------------+-----------+-------------+
133
+ | create_date | email | is_active | nickname |
134
+ +-------------------------------+------------------------+-----------+-------------+
135
+ | Fri, 22 Nov 2024 16:03:41 GMT | jeffery@infiniflow.org | 1 | Jeffery |
136
+ | Fri, 22 Nov 2024 16:10:55 GMT | aya@infiniflow.org | 1 | Waterdancer |
137
+ +-------------------------------+------------------------+-----------+-------------+
138
+
139
+ admin> list services;
140
+ +-------------------------------------------------------------------------------------------+-----------+----+---------------+-------+----------------+
141
+ | extra | host | id | name | port | service_type |
142
+ +-------------------------------------------------------------------------------------------+-----------+----+---------------+-------+----------------+
143
+ | {} | 0.0.0.0 | 0 | ragflow_0 | 9380 | ragflow_server |
144
+ | {'meta_type': 'mysql', 'password': 'infini_rag_flow', 'username': 'root'} | localhost | 1 | mysql | 5455 | meta_data |
145
+ | {'password': 'infini_rag_flow', 'store_type': 'minio', 'user': 'rag_flow'} | localhost | 2 | minio | 9000 | file_store |
146
+ | {'password': 'infini_rag_flow', 'retrieval_type': 'elasticsearch', 'username': 'elastic'} | localhost | 3 | elasticsearch | 1200 | retrieval |
147
+ | {'db_name': 'default_db', 'retrieval_type': 'infinity'} | localhost | 4 | infinity | 23817 | retrieval |
148
+ | {'database': 1, 'mq_type': 'redis', 'password': 'infini_rag_flow'} | localhost | 5 | redis | 6379 | message_queue |
149
+ +-------------------------------------------------------------------------------------------+-----------+----+---------------+-------+----------------+
150
+ ```
@@ -0,0 +1,10 @@
1
+ http_client.py,sha256=dmgha7IOu5Mh9zixsGT8nUeb9DqphtsXCfjwildj0c4,6486
2
+ parser.py,sha256=mOT1WXdF8WhWKbHfJI1FurR7LIUBur8jExi9qLUWSBc,34439
3
+ ragflow_cli.py,sha256=fjo8zKHiyrgu3KV1jZjRinx0z0vyZIhaYYBeUHEHuiA,12470
4
+ ragflow_client.py,sha256=BxJcjLStQaH9UZ5EKQeywYPl45d-r8OYCTaR39ccMhQ,108986
5
+ user.py,sha256=pxXzjYkQweUVpvRvC_qdV5OACd9SvG5Z4oiT2GAl7O8,3535
6
+ ragflow_cli_myfbee_test-0.27.2.dev0.dist-info/METADATA,sha256=C5Nn-jjVboXfucf5aE0Qed1UHZROnQaRGY7S_vnEAN4,6573
7
+ ragflow_cli_myfbee_test-0.27.2.dev0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
8
+ ragflow_cli_myfbee_test-0.27.2.dev0.dist-info/entry_points.txt,sha256=rR-6pSN9myKV0cJq0U0C_g2qsMHxviYJwdERj1mC1tY,49
9
+ ragflow_cli_myfbee_test-0.27.2.dev0.dist-info/top_level.txt,sha256=WFyNpng93LW1S-ZnHJ6cFbk0YNUQYJqOjqHk2F2IWAw,51
10
+ ragflow_cli_myfbee_test-0.27.2.dev0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ ragflow-cli = ragflow_cli:main
@@ -0,0 +1,5 @@
1
+ http_client
2
+ parser
3
+ ragflow_cli
4
+ ragflow_client
5
+ user