Spaces:
Sleeping
Sleeping
Upload engine.py
Browse files
engine.py
CHANGED
|
@@ -143,21 +143,24 @@ def build_join_sql(base_table, steps):
|
|
| 143 |
# =========================
|
| 144 |
|
| 145 |
def parse_intent(question):
|
| 146 |
-
# 1️⃣ Load metadata
|
| 147 |
meta = load_metadata()
|
| 148 |
|
| 149 |
-
#
|
| 150 |
schema_description = "\n".join([
|
| 151 |
-
f"{module}: {', '.join(
|
| 152 |
for module in meta["modules"]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
])
|
| 154 |
|
| 155 |
-
# 3️⃣ Prompt with schema awareness
|
| 156 |
prompt = f"""
|
| 157 |
You are a SQL query planner.
|
| 158 |
|
| 159 |
You MUST only use fields listed below.
|
| 160 |
-
If a field does not exist, choose the closest valid
|
|
|
|
| 161 |
|
| 162 |
Available schema:
|
| 163 |
{schema_description}
|
|
@@ -165,17 +168,9 @@ Available schema:
|
|
| 165 |
Extract:
|
| 166 |
- module
|
| 167 |
- filters (field, operator, value)
|
| 168 |
-
- selected fields
|
| 169 |
|
| 170 |
-
Return JSON
|
| 171 |
-
|
| 172 |
-
Example:
|
| 173 |
-
{{
|
| 174 |
-
"module": "employees",
|
| 175 |
-
"filters": [
|
| 176 |
-
{{ "field": "start_date", "operator": "greater_or_equal", "value": "2024-01-01" }}
|
| 177 |
-
]
|
| 178 |
-
}}
|
| 179 |
|
| 180 |
User question:
|
| 181 |
{question}
|
|
@@ -187,7 +182,11 @@ User question:
|
|
| 187 |
temperature=0
|
| 188 |
)
|
| 189 |
|
| 190 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
|
| 192 |
|
| 193 |
# =========================
|
|
|
|
| 143 |
# =========================
|
| 144 |
|
| 145 |
def parse_intent(question):
|
|
|
|
| 146 |
meta = load_metadata()
|
| 147 |
|
| 148 |
+
# ✅ Build schema safely (skip empty modules)
|
| 149 |
schema_description = "\n".join([
|
| 150 |
+
f"{module}: {', '.join(fields)}"
|
| 151 |
for module in meta["modules"]
|
| 152 |
+
if (fields := [
|
| 153 |
+
f for f in meta["fields"]
|
| 154 |
+
if meta["fields"][f]["module"] == module
|
| 155 |
+
])
|
| 156 |
])
|
| 157 |
|
|
|
|
| 158 |
prompt = f"""
|
| 159 |
You are a SQL query planner.
|
| 160 |
|
| 161 |
You MUST only use fields listed below.
|
| 162 |
+
If a field does not exist, choose the closest valid field.
|
| 163 |
+
Do NOT invent column names.
|
| 164 |
|
| 165 |
Available schema:
|
| 166 |
{schema_description}
|
|
|
|
| 168 |
Extract:
|
| 169 |
- module
|
| 170 |
- filters (field, operator, value)
|
| 171 |
+
- selected fields
|
| 172 |
|
| 173 |
+
Return ONLY valid JSON.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
User question:
|
| 176 |
{question}
|
|
|
|
| 182 |
temperature=0
|
| 183 |
)
|
| 184 |
|
| 185 |
+
# ✅ Safe JSON parsing
|
| 186 |
+
try:
|
| 187 |
+
return json.loads(res.choices[0].message.content)
|
| 188 |
+
except json.JSONDecodeError:
|
| 189 |
+
raise ValueError("LLM returned invalid JSON")
|
| 190 |
|
| 191 |
|
| 192 |
# =========================
|