File size: 1,485 Bytes
8fc9239
b5690cc
3bb06e0
8fc9239
 
 
 
 
 
 
 
 
 
 
 
 
3bb06e0
8fc9239
 
 
 
 
 
 
 
 
 
27a741e
 
8fc9239
 
a7f2b57
8fc9239
27a741e
 
8fc9239
 
 
 
 
 
 
 
 
 
 
 
27a741e
 
5fac831
27a741e
 
8fc9239
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
import openai
import streamlit as st

# Set up OpenAI API key
openai.api_key = "YOUR_API_KEY"  # Replace with your OpenAI API key

# Function to generate SQL query using GPT-3
def generate_sql_query(query, schema):
    prompt = f"""
    Given the following database schema:

    {schema}

    Translate the following question into an SQL query:

    Question: {query}

    SQL Query:
    """

    # Request GPT-3 to generate the SQL query
    response = openai.Completion.create(
        engine="text-davinci-003",  # Use gpt-3.5-turbo for faster and cheaper results
        prompt=prompt,
        max_tokens=150,
        temperature=0.0,  # Lower temperature for deterministic results
    )
    
    # Extract and return the SQL query
    sql_query = response.choices[0].text.strip()
    return sql_query

# Streamlit interface
def main():
    # Display title and instructions
    st.title("Text-to-SQL with GPT-3")
    st.write("Enter a database schema and a natural language query to generate the corresponding SQL query.")

    # Input boxes for schema and query
    schema_input = st.text_area("Enter the Database Schema:", height=200)
    query_input = st.text_input("Enter your Question:")

    if schema_input and query_input:
        # Generate the SQL query
        sql_query = generate_sql_query(query_input, schema_input)

        # Display the generated SQL query
        st.write("Generated SQL Query:")
        st.code(sql_query)

if __name__ == "__main__":
    main()