Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import os
|
3 |
+
import openai
|
4 |
+
|
5 |
+
client = openai.OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
|
6 |
+
|
7 |
+
BASE_SYSTEM_PROMPT = "You are an SQL expert. Based on the selected dialect, return a correct SQL query for the user's request."
|
8 |
+
|
9 |
+
def query_openai(message, chat_history, dialect):
|
10 |
+
system_prompt = f"{BASE_SYSTEM_PROMPT} Use the {dialect} dialect."
|
11 |
+
|
12 |
+
messages = [{"role": "system", "content": system_prompt}]
|
13 |
+
for user, bot in chat_history:
|
14 |
+
messages.append({"role": "user", "content": user})
|
15 |
+
messages.append({"role": "assistant", "content": bot})
|
16 |
+
messages.append({"role": "user", "content": message})
|
17 |
+
|
18 |
+
response = client.chat.completions.create(
|
19 |
+
model="gpt-3.5-turbo",
|
20 |
+
messages=messages,
|
21 |
+
temperature=0.5
|
22 |
+
)
|
23 |
+
|
24 |
+
return response.choices[0].message.content
|
25 |
+
|
26 |
+
def respond(message, chat_history, dialect):
|
27 |
+
try:
|
28 |
+
bot_reply = query_openai(message, chat_history, dialect)
|
29 |
+
except Exception as e:
|
30 |
+
bot_reply = f"❌ Error: {str(e)}"
|
31 |
+
chat_history.append((message, bot_reply))
|
32 |
+
return "", chat_history
|
33 |
+
|
34 |
+
with gr.Blocks() as demo:
|
35 |
+
gr.Markdown("## 🧠 SQL Query Generator Bot (OpenAI GPT-Powered)")
|
36 |
+
|
37 |
+
dialect = gr.Dropdown(["MySQL", "PostgreSQL", "SQLite"], value="MySQL", label="Select SQL Dialect")
|
38 |
+
chatbot = gr.Chatbot()
|
39 |
+
msg = gr.Textbox(label="Describe your SQL query in plain English")
|
40 |
+
clear = gr.Button("Clear Chat")
|
41 |
+
state = gr.State([])
|
42 |
+
|
43 |
+
msg.submit(respond, [msg, state, dialect], [msg, chatbot])
|
44 |
+
clear.click(lambda: ([], []), None, [chatbot, state])
|
45 |
+
|
46 |
+
demo.launch()
|