-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapp.py
More file actions
288 lines (193 loc) · 7.1 KB
/
app.py
File metadata and controls
288 lines (193 loc) · 7.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import os
import time
import dotenv
import boto3
import ssl
import awswrangler as wr
from awswrangler import postgresql
from flask import Flask, request, Response, make_response, Blueprint
from flask_cors import CORS
from botocore.config import Config
from langchain import SQLDatabase
from utils.llm import get_llm_client
from utils.athena import get_athena_client, get_table_info, format_query_result
from utils.prompt import ATHENA_PROMPT, POSTGRES_PROMPT
# from utils.secretsmanager import generate_db_uri
import logging
logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO)
logging.info('Admin logged in')
app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "*"}})
dotenv.load_dotenv()
athena_client = get_athena_client()
# db_uri = generate_db_uri(os.getenv("RDS_SECRETS_MANAGER_ARN"))
# db = SQLDatabase.from_uri(db_uri)
# rds_table_info = db.table_info
api_bp = Blueprint("api", __name__, url_prefix="/api")
v1_bp = Blueprint("v1", __name__, url_prefix="/v1")
@app.before_request
def handle_preflight():
if request.method == "OPTIONS":
res = Response()
res.headers['X-Content-Type-Options'] = '*'
return res
@api_bp.route("/ping", methods=["GET"])
def ping():
return "pong"
@v1_bp.route("/athena/health", methods=["GET"])
def health():
try:
athena_client.list_data_catalogs()
except Exception as error:
return make_response({"error": error}, 400)
return make_response({"health": "ok"}, 200)
@v1_bp.route("/athena/catalog", methods=["GET"])
def get_data_catalog():
try:
data_catalogs = athena_client.list_data_catalogs()
# print("athena client region: ", athena_client.get_region())
except Exception as error:
return make_response({"error": error}, 400)
return make_response({
"catalogs": [catalog["CatalogName"] for catalog in data_catalogs["DataCatalogsSummary"]]
}, 200)
@v1_bp.route("/athena/database/<catalog_name>", methods=["GET"])
def get_databases(catalog_name):
try:
databases = athena_client.list_databases(CatalogName=catalog_name)
except Exception as error:
return make_response({"error": error}, 400)
return make_response({
"databases": [database["Name"] for database in databases["DatabaseList"]]
}, 200)
@v1_bp.route("/inference/explanation", methods=["POST"])
def explanation_inference():
req = request.get_json()
body = {
"catalog_name": req.get("CatalogName"),
"database_name": req.get("DatabaseName"),
"prompt": req.get("prompt"),
"qid": req.get("qid")
}
for key, value in body.items():
if value is None:
return make_response({
"error": f"{key} not provided!"
}, 400)
while True:
finish_state = athena_client.get_query_execution(QueryExecutionId=body["qid"])[
"QueryExecution"
]["Status"]["State"]
if finish_state == "RUNNING" or finish_state == "QUEUED":
time.sleep(2)
else:
break
try:
query_result = athena_client.get_query_results(
QueryExecutionId=body["qid"]
)
formatted_query_result = format_query_result(query_result)
# explainer_kwargs = {
# "input": body["prompt"],
# "result": formatted_query_result
# }
# explanation = llm.predict(EXPLAINER_PROMPT.format_prompt(**explainer_kwargs).to_string())
except BaseException as error:
return make_response({"error": error}, 400)
return make_response({
"explanation": None,
"data": [row.split(",") for row in formatted_query_result.strip().split("\n")]
})
# input: Human language ; output: SQL query.
@v1_bp.route("/inference/sql", methods=["POST"])
def sql_inference():
req = request.get_json()
prompt = req["prompt"]
if not prompt:
return make_response({
"error": "Prompt not provided!"
}, 400)
data_information = {
"catalog_name": req.get("CatalogName"),
"database_name": req.get("DatabaseName")
}
table_info = get_table_info(athena_client, data_information, logging)
sql_gen_kwargs = {
"input": prompt,
"table_info": table_info,
"top_k": 10,
}
prompt = ATHENA_PROMPT.format_prompt(**sql_gen_kwargs).to_string()
llm_client = get_llm_client()
try:
query = llm_client.generate_sql(prompt)
logging.info("------------------------------------------\nGenerated Athena SQL: \n" + query)
logging.info("------------------------------------------")
query_execution = athena_client.start_query_execution(
QueryString=query,
QueryExecutionContext={
'Database': data_information["database_name"],
'Catalog': data_information["catalog_name"]
},
ResultConfiguration={
'OutputLocation': 's3://a4l-query-result-98998/'
},
ResultReuseConfiguration={
"ResultReuseByAgeConfiguration": {
'Enabled': True,
'MaxAgeInMinutes': 5000
}
}
)
qid = query_execution["QueryExecutionId"]
except BaseException as error:
return make_response({"error": error}, 400)
return make_response({
"qid": qid,
"query": query,
}, 200)
# # input:human language ; output: SQL query
# @v1_bp.route("/postgres/inference", methods=["POST"])
# def postgres_sql_inference():
# req = request.get_json()
# prompt = req["prompt"]
# if not prompt:
# return make_response({
# "error": "Prompt not provided!"
# }, 400)
# prompt = POSTGRES_PROMPT.format_prompt(input=prompt, table_info=rds_table_info, top_k=10).to_string()
# try:
# llm_client = get_llm_client()
# query = llm_client.generate_sql(prompt)
# except BaseException as error:
# return make_response({"error": error}, 400)
# return make_response({
# "query": query,
# }, 200)
# # input: SQL query ; output: result after exec that SQL query via Database
# @v1_bp.route("/postgres/execute", methods=["POST"])
# def postgres_sql_execution():
# req = request.get_json()
# body = {
# "query": req["query"],
# }
# for k in body:
# if not body[k]:
# return make_response({
# "error": f"{k} not provided!"
# }, 400)
# session = boto3.Session(region_name="us-west-2")
# ssl_context = ssl.create_default_context()
# ssl_context.check_hostname = False
# ssl_context.verify_mode = ssl.CERT_NONE
# con_postgresql = postgresql.connect(
# secret_id=os.getenv("RDS_SECRETS_MANAGER_ARN"),
# boto3_session=session,
# ssl_context=ssl_context
# )
# result = wr.postgresql.read_sql_query(body["query"], con=con_postgresql)
# return make_response({
# "data": [row.split(',') for row in result.to_csv(index=False).splitlines()]
# }, 200)
api_bp.register_blueprint(v1_bp)
app.register_blueprint(api_bp)