Generative AI with SQL database: A personal SQL Developer Chatbot ππ€
Writing tons of SQL queries to retrieve information from the database is obviously time consuming and take so much mental effort.
Now AI has the capability to increase the productivity level exponentially of SQL developers.
In this article, I will show you how you can build your own AI chatbot that takes the prompt (what you want). then it will write and execute SQL query and bring the results in front of you from the database.
I will try to make things as simple as possible.
Import Dependencies
from langchain.sql_database import SQLDatabase
from langchain_experimental.sql import SQLDatabaseChain
from langchain.llms import OpenAI
from langchain.agents import Tool
from sqlalchemy import create_engine, MetaData, Table, select
Connect with My SQL Database
If you have a database on live, thatβs great. If not, you need to install XAMPP and start MYSQL.
Configure My SQL credentials and integrate it with python. create a connection string and pass it in create_engine
function. It will establish a connection with database.
username = 'user_name'
password = 'your_password'
host = 'localhost'
port = 'port_name'
database_name = 'your_db'
connection_string = f"mysql+mysqlconnector://{username}:{password}@{host}:{port}/{database_name}β
engine = create_engine(connection_string)metadata = MetaData()
metadata.reflect(bind=engine)
Integrate SQL with LLM through LangChain
Set up the LLM model. Pass the engine
object to Langchain SQLDatabase
class. Use SQLDatabaseChain
to gather up all things.
llm = OpenAI(model_name='gpt-3.5-turbo', openai_api_key='your_api_key', temperature = 0.7)
db = SQLDatabase(engine)
sql_chain = SQLDatabaseChain(llm=llm, database=db, verbose=True)
Ask
You can ask query it will return the retrieve information and SQL query as well.
sql_chain.run("Can you please tell me the phone number of Anas")
Isnβt it awesome? Let me know in the comment section below.
This thing unlocks so many possibilities that is not possible before. Follow me here, You will be notified every time I published.
You can get alot of more useful article from this website. aqdasansari.com
π Thanks for reading π. see you soonπ.