SQL AI Assistant Chatbot with Python – No SQL Knowledge Required

SQL AI Assistant Chatbot with Python – No SQL Knowledge Required

SQL AI assistant no SQL knowledge required Python OpenAI chatbot tutorial

In this tutorial, you’ll learn how to build a SQL AI Assistant no SQL knowledge required, using Python and the OpenAI API. This beginner-friendly chatbot generates SQL queries from natural language questions, allowing anyone to interact with SQL Server or other databases without writing a single SQL statement. We’ll cover step-by-step instructions, code examples, and best practices to help you get started quickly. See also our Python tutorials for more beginner-friendly AI projects.

Generate SQL queries with AI for SQL Server

A SQL AI Assistant Chatbot is a Python-based tool that generates SQL queries from natural language questions using OpenAI. This allows anyone to interact with databases without needing prior SQL knowledge. It’s perfect for beginners and developers who want to automate database queries quickly. Watch the full tutorial on SQL AI Assistant No SQL Knowledge Required Tutorial on YouTube .

Build SQL AI Assistant Chatbot No SQL Knowledge Required

I created a SQL AI Assistant Chatbot which helps you work without writing a single line of SQL syntax. You can just use simple, normal English words. For example, if a user wants to display a table called ‘student’ from a database, they usually need to write a query like SELECT * FROM student. But with this AI SQL tool, you can use a natural English prompt to fetch records, like “list the student table” or “get data from student.” It populates the data table from the database using these easy prompts. I developed this tool using Python to connect a SQL Server database with an OpenAI API key.

How SQL AI Assistant Tool Works Between Python and SQL Server with OpenAI Python SQL Server chatbot guide

This Build AI chatbot Python OpenAI without SQL. To communicate between the frontend (Python) and backend (SQL Server), you need an AI API key. In the market, there are plenty of free and paid API options like Google AI Studio or OpenAI. In this tutorial, we’ll use the OpenAI paid version.

Follow these steps to create an OpenAI API key:

  1. Login to OpenAI: Log in with any valid Gmail account. On the left panel, select API Keys. This redirects you to the API keys page. Click the + Create new secret key button.
  2. Save Your Secret Key: A dialog box will appear: “Save your key. Please save your secret key in a safe place since you won’t be able to view it again. Keep it secure, as anyone with your API key can make requests on your behalf. If you lose it, you’ll need to generate a new one.” Copy the key and save it in a secure file or notepad. Once you click Done, you won’t be able to see it again.
  3. Prepare Your IDE: Download and install a coding environment like Visual Studio Code (VS Code) or PyCharm if you don’t have one. Once ready, we can start coding.

How to create SQL chatbot with Python and OpenAI

  
# Import required libraries
import pyodbc                 # Used to connect Python with SQL Server
from openai import OpenAI     # OpenAI client to communicate with AI models
from dotenv import load_dotenv # Loads environment variables from .env file
import os                     # Used to access environment variables

# Load environment variables from .env file
load_dotenv(override=True)

# Create OpenAI client using API key stored in .env file
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

# Print API key to verify it loaded correctly (for testing purposes)
print("API Key:", os.getenv("OPENAI_API_KEY"))

# Try connecting to SQL Server database
try:
    conn = pyodbc.connect(
        r"DRIVER={ODBC Driver 17 for SQL Server};"  # SQL Server driver
        r"SERVER=localhost;"                        # SQL Server location
        r"DATABASE=abc;"                            # Database name
        r"Trusted_Connection=yes;"                  # Windows authentication
    )

    # Create a cursor object to execute SQL queries
    cursor = conn.cursor()

    # Print success message
    print("Connected Successfully To SQL Server\n")

# If connection fails, show error
except Exception as e:
    print(f"Error Connecting To SQL Server Database : {e}")
    exit()


# Function that asks OpenAI to convert a question into a SQL query
def ask_ai_sql(question):

    # Prompt sent to OpenAI model
    prompt = f"""
You are an expert SQL Server Developer.
Convert the following question into a valid SQL Server Query.

Rules:
- Return ONLY the SQL query
- No explanations
- No backticks
- SQL Server syntax only

Question: {question}
"""

    try:
        # Send request to OpenAI model
        response = client.chat.completions.create(
            model="gpt-4o-mini",  # AI model used to generate SQL
            messages=[{"role": "user", "content": prompt}]
        )

        # Extract SQL query from response
        sql_query = response.choices[0].message.content.strip()

        # Remove unwanted backticks if AI adds them
        return sql_query.replace("`", "")

    # Handle OpenAI errors
    except Exception as e:
        print(f"Error Generating SQL FROM GPT: {e}")
        return None


# Inform user how to exit the program
print("Type 'exit' to quit.\n")

# Continuous loop to ask questions
while True:

    # Take user input question
    q = input("Enter The Question: ")

    # Exit program if user types 'exit'
    if q.lower() == "exit":
        break

    try:
        # Send question to AI to generate SQL query
        sql_query = ask_ai_sql(q)

        # If SQL generation fails
        if not sql_query:
            print("SQL generation failed.")
            continue

        # Display generated SQL query
        print(f"\nGenerated SQL Query:\n{sql_query}\n")

        # Execute the generated SQL query in SQL Server
        cursor.execute(sql_query)

        # Fetch all results returned by the query
        rows = cursor.fetchall()

        # Print rows if results exist
        if rows:
            for row in rows:
                print(row)
        else:
            print("No Results Found.")

    # Handle SQL execution errors
    except Exception as e:
        print(f"Error executing the Query: {e}")

# Close database cursor
cursor.close()

# Close SQL Server connection
conn.close()

# Print closing message
print("SQL Connection Closed.")