Skip to content

Commit 21d0345

Browse files
committed
feat: implement natural language to SQL query generation and execution API.
1 parent 34cd2a1 commit 21d0345

2 files changed

Lines changed: 10 additions & 15 deletions

File tree

backend/app/api/query.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,8 @@ def query_sql(payload: SQLQueryRequest):
2929

3030
except ValueError as exc:
3131
raise HTTPException(status_code=400, detail=str(exc))
32-
except Exception:
32+
except Exception as exc:
33+
print(exc)
3334
raise HTTPException(
3435
status_code=500,
3536
detail="Failed to process SQL query"

backend/app/services/sql_generator.py

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,9 @@ def generate_sql(question: str) -> Dict[str, Any]:
2121
schema = load_database_schema()
2222
formatted_schema = format_schema_for_prompt(schema)
2323

24-
system_prompt = f"""
24+
# We move the "Expert" rules to the system_instruction parameter
25+
system_instruction = f"""
2526
You are an expert SQL assistant.
26-
2727
You are given a PostgreSQL database schema.
2828
Your task is to generate a SINGLE, READ-ONLY SQL query
2929
that answers the user's question.
@@ -46,18 +46,12 @@ def generate_sql(question: str) -> Dict[str, Any]:
4646
}}
4747
"""
4848

49+
# Corrected method call for the google-genai SDK
4950
response = client.models.generate_content(
5051
model=settings.GEMINI_MODEL,
51-
contents=[
52-
types.Content(
53-
role="user",
54-
parts=[
55-
types.Part(text=system_prompt),
56-
types.Part(text=f"\nUSER QUESTION:\n{question}")
57-
]
58-
)
59-
],
60-
generation_config=types.GenerationConfig(
52+
contents=f"USER QUESTION: {question}",
53+
config=types.GenerateContentConfig(
54+
system_instruction=system_instruction,
6155
temperature=0.1,
6256
response_mime_type="application/json"
6357
)
@@ -68,9 +62,9 @@ def generate_sql(question: str) -> Dict[str, Any]:
6862
try:
6963
data = json.loads(raw_text)
7064
except json.JSONDecodeError as exc:
71-
raise ValueError("Gemini returned invalid JSON") from exc
65+
raise ValueError(f"Gemini returned invalid JSON: {raw_text}") from exc
7266

7367
if "sql" not in data or "explanation" not in data:
7468
raise ValueError("Gemini response missing required fields")
7569

76-
return data
70+
return data

0 commit comments

Comments
 (0)