Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
@@ -4,6 +4,7 @@ import asyncio
|
|
4 |
import requests
|
5 |
from fastapi import FastAPI, HTTPException
|
6 |
import openai
|
|
|
7 |
|
8 |
|
9 |
# Initialize FastAPI app
|
@@ -19,6 +20,199 @@ AUTH_HEADERS = {
|
|
19 |
'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiYjczMDAxYzMyMTE1ZGIyNTY4ODUzMTg2OWVjMzUwNTdjZmE3YTJmN2I3ZWZjMjQzNjdmZTA2ZTk4ZjY4ZjMwMTE0ZTIzOGUwY2I0ZmQ0YjIiLCJpYXQiOjE3MzA3ODIxNjEuMjkyNDM0LCJuYmYiOjE3MzA3ODIxNjEuMjkyNDM3LCJleHAiOjQ4ODY0NTU3NjEuMDc2ODExLCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.I4wGFzoepmAC2RaADetE95BdbY4AYPUfUouFepVthZq_KewQLoYEiYMmxErgAOvYDL9IdhTg8pHm3KtCjtfF79Toigvzl-4RIYE9qwavVYabUaIMtxdkvLmzC2uSSxNkQ-Jx4ZsEVt34NpMMZ6ZsMsgszkreed_s7i5I6ek6T2-p9cZYPpFfGhlRIrgAhOL1yZe0t5HQMM7P1cULB7IMb3s0fvwLNBimPC4Iznick5o2lWO6KcubsKSAMyPwBaCQhjGTKd0eJCde1IvL8mEaMvhu8v853AIDSiBsC83hjK41hPAaiBHeev1JjdDhEd6_qO9dpucKaGCqYiVfBFH_pgnynErmhKlPEIz7sZlBWz8zxISDW5PRo9d-jXRP-A31W76Q3H-ZKfnam0D8yYFY0EIZHhvgvZUl3r0dR4PRh7PYlNZgnyfAcAYmK9Bektjbbx5RuzH6gtT9hLQrxYiQNg0irCNwgTYnuQ4AjPA3BpZuOfWtygeDZKgv1gnveTzMJG7T6s95k8yNSNT1_OfRQONPX8LBasRwZWCGkWj7fopO6K8gcrEU5FIpql0UviwGJOTZeFmqwWJ1AIcOM0MHWNp--Y8evHrvuNGk3SDcjBcvhF58I2Hd5F4MefN_ZB9N7oxUUDBYbxnTH6SN7Wx-VsluEOlf9ShfBNvHZaUi61E'
|
20 |
}
|
21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
# Helper function to get the order ID from the waybill number
|
23 |
def get_order_id(waybill_no):
|
24 |
url = f"https://dev3.api.curfox.parallaxtec.com/api/ml/order/{waybill_no}"
|
@@ -57,9 +251,15 @@ def ask_openai(messages):
|
|
57 |
response = openai.ChatCompletion.create(model="gpt-4o-mini", messages=messages)
|
58 |
return response.choices[0].message['content']
|
59 |
|
|
|
|
|
|
|
|
|
60 |
# Main endpoint to handle user queries
|
61 |
-
@app.post("/
|
62 |
-
async def process_query(query: str
|
|
|
|
|
63 |
# Initial message to check for waybill number in the query
|
64 |
messages = [
|
65 |
{"role": "system", "content": "You are a helpful assistant for Curfox delivery system."},
|
@@ -91,12 +291,26 @@ async def process_query(query: str):
|
|
91 |
{"role": "system", "content": "You are a helpful assistant for Curfox delivery system."},
|
92 |
{"role": "user", "content": f"Answer based on the provided data only. Data: {full_data}. User query: {query}"}
|
93 |
]
|
94 |
-
|
95 |
-
|
|
|
|
|
96 |
else:
|
97 |
-
|
98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
99 |
|
|
|
|
|
|
|
100 |
# Start the FastAPI app
|
101 |
# Run the app on Colab using Uvicorn
|
102 |
# import uvicorn
|
|
|
4 |
import requests
|
5 |
from fastapi import FastAPI, HTTPException
|
6 |
import openai
|
7 |
+
from typing import Optional
|
8 |
|
9 |
|
10 |
# Initialize FastAPI app
|
|
|
20 |
'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiYjczMDAxYzMyMTE1ZGIyNTY4ODUzMTg2OWVjMzUwNTdjZmE3YTJmN2I3ZWZjMjQzNjdmZTA2ZTk4ZjY4ZjMwMTE0ZTIzOGUwY2I0ZmQ0YjIiLCJpYXQiOjE3MzA3ODIxNjEuMjkyNDM0LCJuYmYiOjE3MzA3ODIxNjEuMjkyNDM3LCJleHAiOjQ4ODY0NTU3NjEuMDc2ODExLCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.I4wGFzoepmAC2RaADetE95BdbY4AYPUfUouFepVthZq_KewQLoYEiYMmxErgAOvYDL9IdhTg8pHm3KtCjtfF79Toigvzl-4RIYE9qwavVYabUaIMtxdkvLmzC2uSSxNkQ-Jx4ZsEVt34NpMMZ6ZsMsgszkreed_s7i5I6ek6T2-p9cZYPpFfGhlRIrgAhOL1yZe0t5HQMM7P1cULB7IMb3s0fvwLNBimPC4Iznick5o2lWO6KcubsKSAMyPwBaCQhjGTKd0eJCde1IvL8mEaMvhu8v853AIDSiBsC83hjK41hPAaiBHeev1JjdDhEd6_qO9dpucKaGCqYiVfBFH_pgnynErmhKlPEIz7sZlBWz8zxISDW5PRo9d-jXRP-A31W76Q3H-ZKfnam0D8yYFY0EIZHhvgvZUl3r0dR4PRh7PYlNZgnyfAcAYmK9Bektjbbx5RuzH6gtT9hLQrxYiQNg0irCNwgTYnuQ4AjPA3BpZuOfWtygeDZKgv1gnveTzMJG7T6s95k8yNSNT1_OfRQONPX8LBasRwZWCGkWj7fopO6K8gcrEU5FIpql0UviwGJOTZeFmqwWJ1AIcOM0MHWNp--Y8evHrvuNGk3SDcjBcvhF58I2Hd5F4MefN_ZB9N7oxUUDBYbxnTH6SN7Wx-VsluEOlf9ShfBNvHZaUi61E'
|
21 |
}
|
22 |
|
23 |
+
|
24 |
+
#db managments section
|
25 |
+
#get all data
|
26 |
+
import mysql.connector
|
27 |
+
from datetime import datetime
|
28 |
+
|
29 |
+
# Define the connection parameters
|
30 |
+
host = "68.183.225.237"
|
31 |
+
user = "sm_ml"
|
32 |
+
password = "Fz6/I733"
|
33 |
+
database = "sm_qa_1"
|
34 |
+
|
35 |
+
|
36 |
+
|
37 |
+
def delete_tread(tread_id_to_delete):
|
38 |
+
# Connect to the database
|
39 |
+
connection_load_chat = mysql.connector.connect(
|
40 |
+
host=host,
|
41 |
+
user=user,
|
42 |
+
password=password,
|
43 |
+
database=database
|
44 |
+
)
|
45 |
+
|
46 |
+
cursor = connection_load_chat.cursor()
|
47 |
+
|
48 |
+
# SQL query to delete a row from curfox_chat based on the tread ID
|
49 |
+
delete_query = "DELETE FROM curfox_chat WHERE tread = %s"
|
50 |
+
|
51 |
+
# Specify the thread ID to delete
|
52 |
+
#tread_id_to_delete = 1
|
53 |
+
|
54 |
+
# Execute the delete query
|
55 |
+
cursor.execute(delete_query, (tread_id_to_delete,))
|
56 |
+
|
57 |
+
# Commit the transaction
|
58 |
+
connection_load_chat.commit()
|
59 |
+
print(f"Thread ID {tread_id_to_delete} deleted successfully.")
|
60 |
+
|
61 |
+
# Close the cursor and connection
|
62 |
+
cursor.close()
|
63 |
+
connection_load_chat.close()
|
64 |
+
return {message":f"Thread ID {tread_id_to_delete} deleted successfully."}
|
65 |
+
|
66 |
+
|
67 |
+
|
68 |
+
def get_treadlist_of_user(user_name):
|
69 |
+
# Connect to the database
|
70 |
+
connection_load_chat = mysql.connector.connect(
|
71 |
+
host=host,
|
72 |
+
user=user,
|
73 |
+
password=password,
|
74 |
+
database=database
|
75 |
+
)
|
76 |
+
|
77 |
+
cursor = connection_load_chat.cursor()
|
78 |
+
user_name = 'John Doe'
|
79 |
+
# SQL query to select all columns from curfox_chat
|
80 |
+
select_query = f"SELECT * FROM curfox_chat WHERE user_name='{user_name}'"
|
81 |
+
|
82 |
+
# Execute the select query
|
83 |
+
cursor.execute(select_query)
|
84 |
+
|
85 |
+
# Fetching all rows from the result
|
86 |
+
rows = cursor.fetchall()
|
87 |
+
# Close the cursor and connection
|
88 |
+
cursor.close()
|
89 |
+
connection_load_chat.close()
|
90 |
+
import json
|
91 |
+
# Displaying the chat data
|
92 |
+
tread_list = []
|
93 |
+
for row in rows:
|
94 |
+
try:
|
95 |
+
js = json.loads(f'[{row[2]}]')
|
96 |
+
tread_list.append({"user_name":row[0],
|
97 |
+
"thread_id":row[1],
|
98 |
+
"chat_title":js[0]['user']['message']
|
99 |
+
})
|
100 |
+
except:
|
101 |
+
pass
|
102 |
+
|
103 |
+
return {"tread_list":tread_list,"message":"done"}
|
104 |
+
|
105 |
+
|
106 |
+
|
107 |
+
def get_thread_chats(thread_id):
|
108 |
+
# Connect to the database
|
109 |
+
connection_load_chat = mysql.connector.connect(
|
110 |
+
host=host,
|
111 |
+
user=user,
|
112 |
+
password=password,
|
113 |
+
database=database
|
114 |
+
)
|
115 |
+
|
116 |
+
cursor = connection_load_chat.cursor()
|
117 |
+
|
118 |
+
# SQL query to select all columns from curfox_chat
|
119 |
+
select_query = f"SELECT * FROM curfox_chat WHERE tread={thread_id}"
|
120 |
+
|
121 |
+
# Execute the select query
|
122 |
+
cursor.execute(select_query)
|
123 |
+
|
124 |
+
# Fetching all rows from the result
|
125 |
+
rows = cursor.fetchall()
|
126 |
+
# Close the cursor and connection
|
127 |
+
cursor.close()
|
128 |
+
connection_load_chat.close()
|
129 |
+
|
130 |
+
import json
|
131 |
+
# Displaying the chat data
|
132 |
+
for row in rows:
|
133 |
+
js = json.loads(f'[{row[2]}]')
|
134 |
+
return ({"user_name":row[0],
|
135 |
+
"thread_id":row[1],
|
136 |
+
"chat_title":js[0]['user']['message'],
|
137 |
+
"chat_list":js})
|
138 |
+
|
139 |
+
|
140 |
+
def insert_newchat(user_name,user_message,bot_message):
|
141 |
+
#insert data
|
142 |
+
# Connect to the database
|
143 |
+
connection_load_chat = mysql.connector.connect(
|
144 |
+
host=host,
|
145 |
+
user=user,
|
146 |
+
password=password,
|
147 |
+
database=database
|
148 |
+
)
|
149 |
+
|
150 |
+
cursor = connection_load_chat.cursor()
|
151 |
+
|
152 |
+
# SQL query to insert a row into curfox_chat table
|
153 |
+
insert_query = """
|
154 |
+
INSERT INTO curfox_chat (user_name, conversation)
|
155 |
+
VALUES (%s, %s)
|
156 |
+
"""
|
157 |
+
|
158 |
+
created_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S') # Current timestamp
|
159 |
+
conversation = f'{{"user": {{"message":"{user_message}","time":"{created_at}"}} , "bot": {{"message":"{bot_message}","time":"{created_at}"}}}}'
|
160 |
+
|
161 |
+
# Execute the insert query with data
|
162 |
+
cursor.execute(insert_query, (user_name, conversation))
|
163 |
+
|
164 |
+
# Commit the transaction
|
165 |
+
connection_load_chat.commit()
|
166 |
+
print("Data inserted successfully")
|
167 |
+
|
168 |
+
# Close the cursor and connection
|
169 |
+
cursor.close()
|
170 |
+
#connection_load_chat.close()
|
171 |
+
|
172 |
+
cursor = connection_load_chat.cursor()
|
173 |
+
sql_query = f"SELECT tread from curfox_chat WHERE user_name='"+user_name+"' ORDER BY tread DESC LIMIT 1"
|
174 |
+
|
175 |
+
cursor.execute(sql_query)
|
176 |
+
current_thread_id = cursor.fetchone()[0]
|
177 |
+
print(current_thread_id)
|
178 |
+
return {"current_thread_id":current_thread_id,"message":"chat stored successfully"}
|
179 |
+
|
180 |
+
def update_existingchat(tread_id,user_message,bot_message):
|
181 |
+
# Connect to the database
|
182 |
+
connection_load_chat = mysql.connector.connect(
|
183 |
+
host=host,
|
184 |
+
user=user,
|
185 |
+
password=password,
|
186 |
+
database=database
|
187 |
+
)
|
188 |
+
|
189 |
+
cursor = connection_load_chat.cursor()
|
190 |
+
|
191 |
+
# SQL query to update the conversation column
|
192 |
+
update_query = """
|
193 |
+
UPDATE curfox_chat
|
194 |
+
SET conversation = CONCAT(conversation, %s)
|
195 |
+
WHERE tread = %s
|
196 |
+
"""
|
197 |
+
|
198 |
+
created_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S') # Current timestamp
|
199 |
+
new_conversation = f', {{"user": {{"message":"{user_message}","time":"{created_at}"}} , "bot": {{"message":"{bot_message}","time":"{created_at}"}}}}'
|
200 |
+
|
201 |
+
# Execute the update query with data
|
202 |
+
|
203 |
+
cursor.execute(update_query, (new_conversation, tread_id))
|
204 |
+
|
205 |
+
# Commit the transaction
|
206 |
+
connection_load_chat.commit()
|
207 |
+
print(f"Conversation for thread ID {tread_id} updated successfully.")
|
208 |
+
|
209 |
+
# Close the cursor and connection
|
210 |
+
cursor.close()
|
211 |
+
connection_load_chat.close()
|
212 |
+
return {"current_thread_id":tread_id,"message":f"Conversation for thread ID {tread_id} updated successfully."}
|
213 |
+
|
214 |
+
|
215 |
+
|
216 |
# Helper function to get the order ID from the waybill number
|
217 |
def get_order_id(waybill_no):
|
218 |
url = f"https://dev3.api.curfox.parallaxtec.com/api/ml/order/{waybill_no}"
|
|
|
251 |
response = openai.ChatCompletion.create(model="gpt-4o-mini", messages=messages)
|
252 |
return response.choices[0].message['content']
|
253 |
|
254 |
+
|
255 |
+
|
256 |
+
|
257 |
+
|
258 |
# Main endpoint to handle user queries
|
259 |
+
@app.post("/get_response")
|
260 |
+
async def process_query(query: str,
|
261 |
+
user_name:str,
|
262 |
+
thread_id:Optional[str] = None):
|
263 |
# Initial message to check for waybill number in the query
|
264 |
messages = [
|
265 |
{"role": "system", "content": "You are a helpful assistant for Curfox delivery system."},
|
|
|
291 |
{"role": "system", "content": "You are a helpful assistant for Curfox delivery system."},
|
292 |
{"role": "user", "content": f"Answer based on the provided data only. Data: {full_data}. User query: {query}"}
|
293 |
]
|
294 |
+
result = ask_openai(response_message)
|
295 |
+
|
296 |
+
if thread_id==None:
|
297 |
+
return {"meta_data":insert_newchat(user_name,query,final_answer),"answer": result}
|
298 |
else:
|
299 |
+
return {"meta_data":update_existingchat(thread_id,query,final_answer),"answer": result}
|
300 |
+
|
301 |
+
|
302 |
+
@app.post("/get_thread_chats")
|
303 |
+
async def get_thread_chats(thread_id:str):
|
304 |
+
return get_thread_chats(thread_id)
|
305 |
+
|
306 |
+
|
307 |
+
@app.post("/get_thread_lists")
|
308 |
+
async def get_thread_lists(user_name:str):
|
309 |
+
return get_treadlist_of_user(user_name)
|
310 |
|
311 |
+
@app.post("/delete_thread")
|
312 |
+
async def get_thread_chats(tread_id_to_delete:str):
|
313 |
+
return delete_tread(tread_id_to_delete)
|
314 |
# Start the FastAPI app
|
315 |
# Run the app on Colab using Uvicorn
|
316 |
# import uvicorn
|