Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,7 +5,10 @@ import duckdb
|
|
| 5 |
import openai
|
| 6 |
|
| 7 |
# 1) Load your OpenAI key from the Space’s Secrets
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
# 2) Load your synthetic data into DuckDB
|
| 11 |
df = pd.read_csv('synthetic_profit.csv')
|
|
@@ -22,18 +25,22 @@ def generate_sql(question: str) -> str:
|
|
| 22 |
f"with columns: {schema}. "
|
| 23 |
"Translate the user's question into a valid SQL query and return ONLY the SQL."
|
| 24 |
)
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
sql = resp.choices[0].message.content.strip()
|
| 36 |
-
# strip
|
| 37 |
if sql.startswith("```") and sql.endswith("```"):
|
| 38 |
sql = "\n".join(sql.splitlines()[1:-1])
|
| 39 |
return sql
|
|
@@ -41,25 +48,32 @@ def generate_sql(question: str) -> str:
|
|
| 41 |
# 5) Core Q&A function: NL → SQL → execute → format
|
| 42 |
def answer_profitability(question: str) -> str:
|
| 43 |
# a) turn the question into SQL
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
# b) try to run it
|
| 46 |
try:
|
| 47 |
result_df = conn.execute(sql).df()
|
| 48 |
except Exception as e:
|
| 49 |
return (
|
| 50 |
-
f"❌
|
| 51 |
-
f"Generated SQL
|
| 52 |
)
|
|
|
|
| 53 |
# c) format the result
|
| 54 |
if result_df.empty:
|
| 55 |
return f"No rows returned.\n\n```sql\n{sql}\n```"
|
|
|
|
| 56 |
# single-cell → scalar
|
| 57 |
if result_df.shape == (1,1):
|
| 58 |
return str(result_df.iat[0,0])
|
| 59 |
-
|
|
|
|
| 60 |
return result_df.to_markdown(index=False)
|
| 61 |
|
| 62 |
-
# 6) Gradio interface with explicit outputs
|
| 63 |
iface = gr.Interface(
|
| 64 |
fn=answer_profitability,
|
| 65 |
inputs=gr.Textbox(lines=2, placeholder="Ask a question about profitability…", label="Question"),
|
|
|
|
| 5 |
import openai
|
| 6 |
|
| 7 |
# 1) Load your OpenAI key from the Space’s Secrets
|
| 8 |
+
OPENAI_KEY = os.getenv("OPENAI_API_KEY")
|
| 9 |
+
if not OPENAI_KEY:
|
| 10 |
+
raise RuntimeError("Missing OPENAI_API_KEY secret in your Space settings")
|
| 11 |
+
openai.api_key = OPENAI_KEY
|
| 12 |
|
| 13 |
# 2) Load your synthetic data into DuckDB
|
| 14 |
df = pd.read_csv('synthetic_profit.csv')
|
|
|
|
| 25 |
f"with columns: {schema}. "
|
| 26 |
"Translate the user's question into a valid SQL query and return ONLY the SQL."
|
| 27 |
)
|
| 28 |
+
try:
|
| 29 |
+
resp = openai.ChatCompletion.create(
|
| 30 |
+
model="gpt-3.5-turbo",
|
| 31 |
+
messages=[
|
| 32 |
+
{"role": "system", "content": system_prompt},
|
| 33 |
+
{"role": "user", "content": question},
|
| 34 |
+
],
|
| 35 |
+
temperature=0.0,
|
| 36 |
+
max_tokens=150,
|
| 37 |
+
)
|
| 38 |
+
except Exception as e:
|
| 39 |
+
# Catch network/auth errors
|
| 40 |
+
raise RuntimeError(f"OpenAI API error: {e}")
|
| 41 |
+
|
| 42 |
sql = resp.choices[0].message.content.strip()
|
| 43 |
+
# strip triple-backticks if present
|
| 44 |
if sql.startswith("```") and sql.endswith("```"):
|
| 45 |
sql = "\n".join(sql.splitlines()[1:-1])
|
| 46 |
return sql
|
|
|
|
| 48 |
# 5) Core Q&A function: NL → SQL → execute → format
|
| 49 |
def answer_profitability(question: str) -> str:
|
| 50 |
# a) turn the question into SQL
|
| 51 |
+
try:
|
| 52 |
+
sql = generate_sql(question)
|
| 53 |
+
except Exception as e:
|
| 54 |
+
return f"❌ **OpenAI Error**\n{e}"
|
| 55 |
+
|
| 56 |
# b) try to run it
|
| 57 |
try:
|
| 58 |
result_df = conn.execute(sql).df()
|
| 59 |
except Exception as e:
|
| 60 |
return (
|
| 61 |
+
f"❌ **SQL Execution Error**\n{e}\n\n"
|
| 62 |
+
f"**Generated SQL**\n```sql\n{sql}\n```"
|
| 63 |
)
|
| 64 |
+
|
| 65 |
# c) format the result
|
| 66 |
if result_df.empty:
|
| 67 |
return f"No rows returned.\n\n```sql\n{sql}\n```"
|
| 68 |
+
|
| 69 |
# single-cell → scalar
|
| 70 |
if result_df.shape == (1,1):
|
| 71 |
return str(result_df.iat[0,0])
|
| 72 |
+
|
| 73 |
+
# multi-cell → markdown table
|
| 74 |
return result_df.to_markdown(index=False)
|
| 75 |
|
| 76 |
+
# 6) Gradio interface with explicit inputs & outputs
|
| 77 |
iface = gr.Interface(
|
| 78 |
fn=answer_profitability,
|
| 79 |
inputs=gr.Textbox(lines=2, placeholder="Ask a question about profitability…", label="Question"),
|