Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -6,6 +6,7 @@ import matplotlib.pyplot as plt
|
|
6 |
import seaborn as sns
|
7 |
import os
|
8 |
from typing import Optional, Tuple
|
|
|
9 |
|
10 |
# OpenRouter API Key (Replace with yours)
|
11 |
OPENROUTER_API_KEY = "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"
|
@@ -38,6 +39,14 @@ def fetch_schema(db_path: str) -> str:
|
|
38 |
conn.close()
|
39 |
return schema
|
40 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
41 |
# Function: Convert text to SQL
|
42 |
def text_to_sql(query: str, schema: str) -> str:
|
43 |
prompt = (
|
@@ -52,11 +61,12 @@ def text_to_sql(query: str, schema: str) -> str:
|
|
52 |
model=OPENROUTER_MODEL,
|
53 |
messages=[{"role": "system", "content": "You are an SQL expert."}, {"role": "user", "content": prompt}]
|
54 |
)
|
55 |
-
|
56 |
-
return
|
57 |
except Exception as e:
|
58 |
return f"Error: {e}"
|
59 |
|
|
|
60 |
# Function: Execute SQL on SQLite database
|
61 |
def execute_sql(sql_query: str) -> Tuple[Optional[pd.DataFrame], Optional[str]]:
|
62 |
try:
|
|
|
6 |
import seaborn as sns
|
7 |
import os
|
8 |
from typing import Optional, Tuple
|
9 |
+
import re
|
10 |
|
11 |
# OpenRouter API Key (Replace with yours)
|
12 |
OPENROUTER_API_KEY = "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"
|
|
|
39 |
conn.close()
|
40 |
return schema
|
41 |
|
42 |
+
# Function: Extract SQL query from LLM response
|
43 |
+
def extract_sql_query(response: str) -> str:
|
44 |
+
# Use regex to find content between ```sql and ```
|
45 |
+
match = re.search(r"```sql(.*?)```", response, re.DOTALL)
|
46 |
+
if match:
|
47 |
+
return match.group(1).strip() # Extract and return the SQL query
|
48 |
+
return response # Fallback: return the entire response if no SQL block is found
|
49 |
+
|
50 |
# Function: Convert text to SQL
|
51 |
def text_to_sql(query: str, schema: str) -> str:
|
52 |
prompt = (
|
|
|
61 |
model=OPENROUTER_MODEL,
|
62 |
messages=[{"role": "system", "content": "You are an SQL expert."}, {"role": "user", "content": prompt}]
|
63 |
)
|
64 |
+
sql_response = response.choices[0].message.content.strip()
|
65 |
+
return extract_sql_query(sql_response) # Extract SQL query from the response
|
66 |
except Exception as e:
|
67 |
return f"Error: {e}"
|
68 |
|
69 |
+
|
70 |
# Function: Execute SQL on SQLite database
|
71 |
def execute_sql(sql_query: str) -> Tuple[Optional[pd.DataFrame], Optional[str]]:
|
72 |
try:
|