DEV Community

Cover image for Query Database using Langchain 🦜🔗‍💥
Sanjay 🥷
Sanjay 🥷

Posted on • Edited on

Query Database using Langchain 🦜🔗‍💥

Introduction

💡 Transforming Database Queries into Intuitive Conversations 💬

Welcome to the fascinating world of LangChain, a groundbreaking framework for developing language model-powered applications. In this blog post, we'll embark on an exciting journey into the realm of querying databases using LangChain. Brace yourself for an exploration of how this framework combines the immense capabilities of language models with data-awareness and agentic interaction, enabling us to create truly intelligent and user-friendly applications.

Funny gif

  • What is Langchain ?

Langchain is a software development framework designed to simplify the creation of applications using large language models (LLMs).

Getting Started 🚀

When it comes to developing a user-friendly and interactive application, Streamlit emerges as a powerful tool in our arsenal. In this section, we'll explore how to integrate the LangChain framework with Streamlit, enabling us to create a seamless and immersive experience for querying databases using natural language.

Here's a quick guide to get you started 🛠️:

Requirements

Make sure you have the following requirements in place:

  • OpenAI API Key 🔑: Obtain an API key from OpenAI to access their language models. You can sign up for an account and generate an API key from the OpenAI website. Make sure to keep your API key secure and avoid sharing it publicly.

  • Python Installation 🐍: Ensure that you have Python installed on your system.

1. Install Langchain and Streamlit 💻🚀:

Begin by installing Streamlit and Langchain using pip or pip3, the package installer for Python. Open your terminal or command prompt and run the following command:

pip install streamlit
pip install langchain
pip install openai
Enter fullscreen mode Exit fullscreen mode

2. Create a Project Directory 📂🗂️:

Create a new directory for your project, and navigate to it in your terminal or command prompt:

mkdir langchain_app
cd langchain_app
Enter fullscreen mode Exit fullscreen mode

3. Create a Python Script 🐍📝:

Inside your project directory, create a new Python script, for example, app.py. This will serve as the main entry point for your Streamlit application.

4. Add .env and database files 🔑🗄️:

Your .env file should look like this:

OPENAI_API_KEY=YOUR API KEY
Enter fullscreen mode Exit fullscreen mode

You can add your own database file or link the database URL. Get the sample database chinook.db
Add these two files in the project root.
Note: Don't commit the .env file. ⚠️🔒

5. Import Streamlit and Create the App ⚙️📲:

Open app.py in your preferred text editor or integrated development environment (IDE), and start by importing Streamlit and langchain:

import streamlit as st
from langchain.chat_models import ChatOpenAI
from langchain import SQLDatabase, SQLDatabaseChain
Enter fullscreen mode Exit fullscreen mode

6. Build the Application 🏗️📱:

Now you can start building our application. Define the structure and layout of your app using Streamlit's intuitive API.

import streamlit as st
from dotenv import load_dotenv
from langchain.chat_models import ChatOpenAI
from langchain import SQLDatabase, SQLDatabaseChain

# Storing the response
if 'generated' not in st.session_state:
    st.session_state['generated'] = []

def generate_response(message):
    # Connect to the database
    dburi = "sqlite:///chinook.db"
    db = SQLDatabase.from_uri(dburi)

    # Create an instance of LLM
    llm = ChatOpenAI()

    # Create an SQLDatabaseChain using the ChatOpenAI model and the database
    db_chain = SQLDatabaseChain.from_llm(llm=llm, db=db)
    ai_response = db_chain.run(message)

    return ai_response

def get_text():
    # Get user input from text input field
    input_text = st.text_input("You: ", "", key="input")
    return input_text  

def main():
    # Load environment variables
    load_dotenv()

    # Display header
    st.header('Query Database Like you Chat')

    # Get user input
    user_input = get_text()

    if user_input:
        # Generate response for the user input
        st.session_state["generated"] = generate_response(user_input)

    if st.session_state['generated']:
        # Display the generated response
        st.write(st.session_state['generated'])

if __name__ == '__main__':
    main()
Enter fullscreen mode Exit fullscreen mode

7. Run the Application ▶️🔥:

To launch your Streamlit app, go back to your terminal or command prompt, navigate to your project directory, and execute the following command:

streamlit run app.py
Enter fullscreen mode Exit fullscreen mode

8. Here is the output 🎯🖼️:

Result demo

Congratulations! 🎉 You have successfully integrated LangChain with Streamlit, allowing you to build powerful applications that leverage the capabilities of language models to interact with databases in a conversational manner. Start exploring the possibilities and create your own intelligent and user-friendly applications today! 🚀💻💬

Top comments (0)