Yatheshr commited on
Commit
8f8328b
Β·
verified Β·
1 Parent(s): 299f9f8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -0
app.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import openai
3
+ import pyodbc
4
+ import pandas as pd
5
+
6
+ # -----------------------------
7
+ # πŸ” 1. Configuration
8
+ # -----------------------------
9
+ openai.api_key = "YOUR_OPENAI_API_KEY"
10
+
11
+ # SQL Server connection string
12
+ server = 'dcdocstgdb01.dc68032.easn.morningstar.com'
13
+ database = 'DocumentAcquisition'
14
+ username = 'DocuUser'
15
+ password = 'StagTest@1'
16
+
17
+ conn_str = (
18
+ f"DRIVER={{ODBC Driver 17 for SQL Server}};"
19
+ f"SERVER={server};"
20
+ f"DATABASE={database};"
21
+ f"UID={username};"
22
+ f"PWD={password}"
23
+ )
24
+
25
+ # -----------------------------
26
+ # πŸ€– 2. Natural Language β†’ SQL
27
+ # -----------------------------
28
+ def generate_sql(nl_question):
29
+ prompt = f"""
30
+ You are a helpful assistant that converts user questions into SQL Server queries.
31
+
32
+ Question: "{nl_question}"
33
+
34
+ SQL Query:
35
+ """
36
+ response = openai.ChatCompletion.create(
37
+ model="gpt-4", # or gpt-3.5-turbo
38
+ messages=[{"role": "user", "content": prompt}],
39
+ temperature=0
40
+ )
41
+ sql_query = response.choices[0].message["content"].strip()
42
+ return sql_query
43
+
44
+ # -----------------------------
45
+ # 🧠 3. Run SQL and return results
46
+ # -----------------------------
47
+ def run_query(sql_query):
48
+ try:
49
+ conn = pyodbc.connect(conn_str)
50
+ df = pd.read_sql(sql_query, conn)
51
+ conn.close()
52
+ return df
53
+ except Exception as e:
54
+ return str(e)
55
+
56
+ # -----------------------------
57
+ # πŸŽ›οΈ 4. Streamlit UI
58
+ # -----------------------------
59
+ st.title("🧠 GenAI SQL Server Q&A")
60
+ st.markdown("Ask a question in natural language. I’ll generate SQL and return the results from your database.")
61
+
62
+ user_question = st.text_input("πŸ“Œ Ask your question:")
63
+
64
+ if st.button("Submit") and user_question:
65
+ with st.spinner("Thinking..."):
66
+ sql_query = generate_sql(user_question)
67
+ st.code(sql_query, language="sql")
68
+
69
+ result = run_query(sql_query)
70
+
71
+ if isinstance(result, pd.DataFrame):
72
+ st.success("βœ… Results:")
73
+ st.dataframe(result)
74
+ else:
75
+ st.error(f"❌ Error:\n{result}")