Skip to content

Commit 7e729de

Browse files
Add component ExeSQL (infiniflow#1966)
### What problem does this PR solve? infiniflow#1965 ### Type of change - [x] New Feature (non-breaking change which adds functionality) --------- Co-authored-by: Kevin Hu <[email protected]>
1 parent 4673f1d commit 7e729de

File tree

6 files changed

+153
-0
lines changed

6 files changed

+153
-0
lines changed

agent/component/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
from .github import GitHub, GitHubParam
2222
from .baidufanyi import BaiduFanyi, BaiduFanyiParam
2323
from .qweather import QWeather, QWeatherParam
24+
from .exesql import ExeSQL, ExeSQLParam
2425

2526
def component_class(class_name):
2627
m = importlib.import_module("agent.component")

agent/component/exesql.py

+85
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
#
2+
# Copyright 2024 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+
from abc import ABC
17+
18+
import pandas as pd
19+
from peewee import MySQLDatabase, PostgresqlDatabase
20+
from agent.component.base import ComponentBase, ComponentParamBase
21+
22+
23+
class ExeSQLParam(ComponentParamBase):
24+
"""
25+
Define the ExeSQL component parameters.
26+
"""
27+
28+
def __init__(self):
29+
super().__init__()
30+
self.db_type = "mysql"
31+
self.database = ""
32+
self.username = ""
33+
self.host = ""
34+
self.port = 3306
35+
self.password = ""
36+
self.loop = 3
37+
self.top_n = 30
38+
39+
def check(self):
40+
self.check_valid_value(self.db_type, "Choose DB type", ['mysql', 'postgresql', 'mariadb'])
41+
self.check_empty(self.database, "Database name")
42+
self.check_empty(self.username, "database username")
43+
self.check_empty(self.host, "IP Address")
44+
self.check_positive_integer(self.port, "IP Port")
45+
self.check_empty(self.password, "Database password")
46+
self.check_positive_integer(self.top_n, "Number of records")
47+
48+
49+
class ExeSQL(ComponentBase, ABC):
50+
component_name = "ExeSQL"
51+
52+
def _run(self, history, **kwargs):
53+
if not hasattr(self, "_loop"):
54+
setattr(self, "_loop", 0)
55+
if self._loop >= self._param.loop:
56+
self._loop = 0
57+
raise Exception("Maximum loop time exceeds. Can't query the correct data via sql statement.")
58+
self._loop += 1
59+
60+
ans = self.get_input()
61+
ans = "".join(ans["content"]) if "content" in ans else ""
62+
if not ans:
63+
return ExeSQL.be_output("SQL statement not found!")
64+
65+
if self._param.db_type in ["mysql", "mariadb"]:
66+
db = MySQLDatabase(self._param.database, user=self._param.username, host=self._param.host,
67+
port=self._param.port, password=self._param.password)
68+
elif self._param.db_type == 'postgresql':
69+
db = PostgresqlDatabase(self._param.database, user=self._param.username, host=self._param.host,
70+
port=self._param.port, password=self._param.password)
71+
72+
try:
73+
db.connect()
74+
query = db.execute_sql(ans)
75+
sql_res = [{"content": rec + "\n"} for rec in [str(i) for i in query.fetchall()]]
76+
db.close()
77+
except Exception as e:
78+
return ExeSQL.be_output("**Error**:" + str(e))
79+
80+
if not sql_res:
81+
return ExeSQL.be_output("No record in the database!")
82+
83+
sql_res.insert(0, {"content": "Number of records retrieved from the database is " + str(len(sql_res)) + "\n"})
84+
df = pd.DataFrame(sql_res[0:self._param.top_n + 1])
85+
return ExeSQL.be_output(df.to_markdown())

agent/test/dsl_examples/exesql.json

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
{
2+
"components": {
3+
"begin": {
4+
"obj":{
5+
"component_name": "Begin",
6+
"params": {
7+
"prologue": "Hi there!"
8+
}
9+
},
10+
"downstream": ["answer:0"],
11+
"upstream": []
12+
},
13+
"answer:0": {
14+
"obj": {
15+
"component_name": "Answer",
16+
"params": {}
17+
},
18+
"downstream": ["exesql:0"],
19+
"upstream": ["begin", "exesql:0"]
20+
},
21+
"exesql:0": {
22+
"obj": {
23+
"component_name": "ExeSQL",
24+
"params": {
25+
"database": "rag_flow",
26+
"username": "root",
27+
"host": "mysql",
28+
"port": 3306,
29+
"password": "infini_rag_flow",
30+
"top_n": 3
31+
}
32+
},
33+
"downstream": ["answer:0"],
34+
"upstream": ["answer:0"]
35+
}
36+
},
37+
"history": [],
38+
"messages": [],
39+
"reference": {},
40+
"path": [],
41+
"answer": []
42+
}
43+

api/apps/canvas_app.py

+20
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
from api.utils import get_uuid
2222
from api.utils.api_utils import get_json_result, server_error_response, validate_request
2323
from agent.canvas import Canvas
24+
from peewee import MySQLDatabase, PostgresqlDatabase
2425

2526

2627
@manager.route('/templates', methods=['GET'])
@@ -158,3 +159,22 @@ def reset():
158159
return get_json_result(data=req["dsl"])
159160
except Exception as e:
160161
return server_error_response(e)
162+
163+
164+
@manager.route('/test_db_connect', methods=['POST'])
165+
@validate_request("db_type", "database", "username", "host", "port", "password")
166+
@login_required
167+
def test_db_connect():
168+
req = request.json
169+
try:
170+
if req["db_type"] in ["mysql", "mariadb"]:
171+
db = MySQLDatabase(req["database"], user=req["username"], host=req["host"], port=req["port"],
172+
password=req["password"])
173+
elif req["db_type"] == 'postgresql':
174+
db = PostgresqlDatabase(req["database"], user=req["username"], host=req["host"], port=req["port"],
175+
password=req["password"])
176+
db.connect()
177+
db.close()
178+
return get_json_result(retmsg="Database Connection Successful!")
179+
except Exception as e:
180+
return server_error_response(str(e))

requirements.txt

+2
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ peewee==3.17.1
5353
Pillow==10.3.0
5454
pipreqs==0.5.0
5555
protobuf==5.27.2
56+
psycopg2-binary==2.9.9
5657
pyclipper==1.3.0.post5
5758
pycryptodomex==3.20.0
5859
pypdf==4.3.0
@@ -73,6 +74,7 @@ setuptools==70.0.0
7374
Shapely==2.0.5
7475
six==1.16.0
7576
StrEnum==0.4.15
77+
tabulate==0.9.0
7678
tika==2.6.0
7779
tiktoken==0.6.0
7880
torch==2.3.0

requirements_arm.txt

+2
Original file line numberDiff line numberDiff line change
@@ -160,3 +160,5 @@ editdistance==0.8.1
160160
markdown_to_json==2.1.1
161161
scholarly==1.7.11
162162
deepl==1.18.0
163+
psycopg2-binary==2.9.9
164+
tabulate-0.9.0

0 commit comments

Comments
 (0)