File size: 2,001 Bytes
c1a0d97
5a580f5
c1a0d97
 
 
5a580f5
 
 
a1eb97f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1a0d97
 
 
a1eb97f
 
 
 
c1a0d97
 
a1eb97f
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
from dotenv import load_dotenv
import os
import gradio as gr
from groq import Groq

load_dotenv()
api = os.getenv("groq_api_key")

def create_prompt(user_query, table_metadata):
    system_prompt = """
You are a SQL query generator specialized in generating SQL queries for a single table at a time.
Your task is to accurately convert natural language queries into SQL statements based on the user's intent and the provided table metadata.

Rules:
- Single Table Only: Use only the table in the metadata.
- Metadata-Based Validation: Use only columns in the metadata.
- User Intent: Support filters, grouping, sorting, etc.
- SQL Syntax: Use standard SQL (DuckDB compatible).
- Output only valid SQL. No extra commentary.

Input:
User Query: {user_query}
Table Metadata: {table_metadata}

Output:
SQL Query (on a single line, nothing else).
    """
    return system_prompt.strip(), f"User Query: {user_query}\nTable Metadata: {table_metadata}"

def generate_output(system_prompt, user_prompt):
    client = Groq(api_key=api)
    chat_completion = client.chat.completions.create(
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_prompt}
        ],
        model="llama3-70b-8192"
    )
    response = chat_completion.choices[0].message.content.strip()
    return response if response.lower().startswith("select") else "Can't perform the task at the moment."

# NEW: accepts user_query and dynamic table_metadata string
def response(payload):
    user_query = payload.get("question", "")
    table_metadata = payload.get("schema", "")
    system_prompt, user_prompt = create_prompt(user_query, table_metadata)
    return generate_output(system_prompt, user_prompt)

demo = gr.Interface(
    fn=response,
    inputs=gr.JSON(label="Input JSON (question, schema)"),
    outputs="text",
    title="SQL Generator (Groq + LLaMA3)",
    description="Input: question & table metadata. Output: SQL using dynamic schema."
)

demo.launch()