File size: 7,149 Bytes
d8ff681
 
 
b7c4fee
d8ff681
 
 
 
 
 
 
 
 
 
 
 
b7c4fee
 
 
 
d8ff681
b7c4fee
 
1029219
b7c4fee
 
944a160
b7c4fee
 
944a160
1029219
d8ff681
 
2f64b1f
d8ff681
 
 
b7c4fee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8ff681
 
 
944a160
 
 
 
 
 
d8ff681
 
944a160
 
 
d8ff681
b7c4fee
 
 
 
 
 
d8ff681
b7c4fee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8ff681
 
b7c4fee
 
d8ff681
944a160
b7c4fee
 
 
 
 
 
 
d8ff681
 
944a160
d8ff681
b7c4fee
 
 
 
d8ff681
b7c4fee
d8ff681
b7c4fee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8ff681
 
 
 
 
b7c4fee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8ff681
b7c4fee
 
1029219
b7c4fee
 
 
 
 
 
 
 
d8ff681
82fb5aa
b7c4fee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8ff681
 
b7c4fee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
from groq import Groq
from pydantic import BaseModel
import json
import gradio as gr

class ValidationStatus(BaseModel):
    is_valid: bool
    syntax_errors: list[str]

class SQLQueryGeneration(BaseModel):
    query: str
    query_type: str
    tables_used: list[str]
    estimated_complexity: str
    execution_notes: list[str]
    validation_status: ValidationStatus
    table_schema: str
    sample_data: str
    execution_results: str
    optimization_notes: list[str]

def generate_sql_query(api_key, user_query):
    """Generate SQL query from natural language using GROQ API"""
    try:
        if not api_key:
            return "Error: Please enter your GROQ API key", "", "", "", "", ""
        
        if not user_query:
            return "Error: Please enter a query description", "", "", "", "", ""
        
        client = Groq(api_key=api_key)
        
        response = client.chat.completions.create(
            model="moonshotai/kimi-k2-instruct-0905",
            messages=[
                {
                    "role": "system",
                    "content": """You are a SQL expert. Generate structured SQL queries from natural language descriptions with proper syntax validation and metadata.
After generating the SQL query, you must:
1. Create a sample SQL table schema based on the natural language description, including all necessary columns with appropriate data types
2. Populate the table with realistic sample data that demonstrates the query's functionality
3. Execute the generated SQL query against the sample table
4. Display the SQL table structure and data clearly
5. Show the query execution results
Always present your response in this order:
- Generated SQL query with syntax explanation
- Table schema (CREATE TABLE statement)
- Sample data (INSERT statements or table visualization)
- Query execution results
- Any relevant notes about assumptions made or query optimization suggestions""",
                },
                {
                    "role": "user", 
                    "content": user_query
                },
            ],
            response_format={
                "type": "json_schema",
                "json_schema": {
                    "name": "sql_query_generation",
                    "schema": SQLQueryGeneration.model_json_schema()
                }
            }
        )
        
        sql_query_generation = SQLQueryGeneration.model_validate(
            json.loads(response.choices[0].message.content)
        )
        
        # Format validation status
        validation_text = f"Valid: {sql_query_generation.validation_status.is_valid}\n"
        if sql_query_generation.validation_status.syntax_errors:
            validation_text += "Errors:\n" + "\n".join(
                f"- {error}" for error in sql_query_generation.validation_status.syntax_errors
            )
        else:
            validation_text += "No syntax errors found"
        
        # Format metadata
        metadata = f"""Query Type: {sql_query_generation.query_type}
Tables Used: {', '.join(sql_query_generation.tables_used)}
Complexity: {sql_query_generation.estimated_complexity}

Execution Notes:
{chr(10).join(f"- {note}" for note in sql_query_generation.execution_notes)}

Optimization Notes:
{chr(10).join(f"- {note}" for note in sql_query_generation.optimization_notes)}"""
        
        return (
            sql_query_generation.query,
            metadata,
            sql_query_generation.table_schema,
            sql_query_generation.sample_data,
            sql_query_generation.execution_results,
            validation_text
        )
        
    except Exception as e:
        error_msg = f"Error: {str(e)}"
        return error_msg, "", "", "", "", ""

# Create Gradio interface
with gr.Blocks(title="SQL Query Generator", theme=gr.themes.Soft()) as demo:
    gr.Markdown(
        """
        # 🗄️ Natural Language to SQL Query Generator
        Convert your natural language descriptions into structured SQL queries with validation and execution results.
        """
    )
    
    with gr.Row():
        with gr.Column():
            api_key_input = gr.Textbox(
                label="GROQ API Key",
                type="password",
                placeholder="Enter your GROQ API key here...",
                info="Your API key is not stored and only used for this session"
            )
            
            query_input = gr.Textbox(
                label="Natural Language Query",
                placeholder="e.g., Find all the students who scored more than 90 out of 100",
                lines=3,
                value="Find all the students who scored more than 90 out of 100"
            )
            
            generate_btn = gr.Button("Generate SQL Query", variant="primary", size="lg")
            
            gr.Examples(
                examples=[
                    ["Find all the students who scored more than 90 out of 100"],
                    ["Get the top 5 customers by total purchase amount"],
                    ["List all employees hired in the last 6 months"],
                    ["Find products with price between $50 and $100"],
                    ["Show average salary by department"]
                ],
                inputs=query_input,
                label="Example Queries"
            )
    
    with gr.Row():
        with gr.Column():
            sql_output = gr.Code(
                label="Generated SQL Query",
                language="sql",
                lines=5
            )
            
            metadata_output = gr.Textbox(
                label="Query Metadata",
                lines=8
            )
            
            validation_output = gr.Textbox(
                label="Validation Status",
                lines=3
            )
    
    with gr.Row():
        with gr.Column():
            schema_output = gr.Code(
                label="Table Schema",
                language="sql",
                lines=8
            )
        
        with gr.Column():
            sample_data_output = gr.Code(
                label="Sample Data",
                language="sql",
                lines=8
            )
    
    with gr.Row():
        execution_output = gr.Textbox(
            label="Execution Results",
            lines=10
        )
    
    generate_btn.click(
        fn=generate_sql_query,
        inputs=[api_key_input, query_input],
        outputs=[
            sql_output,
            metadata_output,
            schema_output,
            sample_data_output,
            execution_output,
            validation_output
        ]
    )
    
    gr.Markdown(
        """
        ---
        ### How to use:
        1. Enter your GROQ API key (get one from [console.groq.com](https://console.groq.com))
        2. Type your natural language query description
        3. Click "Generate SQL Query" to see the results
        
        The app will provide:
        - A validated SQL query
        - Table schema and sample data
        - Execution results
        - Optimization suggestions
        """
    )

if __name__ == "__main__":
    demo.launch(share=True)