Shivang Vyas
Shivang Vyas

Reputation: 5

I want to use the SQLQueryChain method, but I am not being able to find it's import is deprecated

I am building a Chatbot in which I have to use Langchain's SQLQueryChain for which I am using from langchain.chains.sql_database import SQLQueryChain. But this is not recognised, so I don't have any idea. How can I fulfill my requirement?

Below is my code:

# Importing necessary libraries and modules

from langchain.sql_database import SQLDatabase
from langchain.chains.sql_database import SQLQueryChain
from langchain.llms.openai import OpenAI
import sqlalchemy  # For interacting with SQL databases

# Configuration for OpenAI and SQLDatabase
api_key = "your_openai_api_key" 
db_uri = "your_database_uri"  

# Creating instances of SQLDatabase and SQLQueryChain
sql_database = SQLDatabase.from_uri(db_uri)
sql_chain = SQLQueryChain(
    llm=OpenAI(api_key=api_key),
    database=sql_database,
)

# Function to execute SQL queries and return results
def execute_sql_query(sql_query):
    # Connect to the database
    engine = sqlalchemy.create_engine(db_uri)
    with engine.connect() as connection:
        # Execute the SQL query and fetch the results
        result = connection.execute(sql_query).fetchall()
    return result

I tried searching all the latest import statements to find the SQLQueryChain import but i couldn't find it.

Upvotes: 1

Views: 355

Answers (1)

furas
furas

Reputation: 142982

I can't find SQLQueryChain with Google (except example in js) so I checked source code.

I found

langchain.chains.sql_database.query.create_sql_query_chain()

which seems similar to example in js

Later I found it in documentation for Python: create_sql_query_chain


BTW:

You can find source code on local computer using __file__

import langchain.chains.sql_database

print( langchain.chains.sql_database.__file__ )

It gives /full/path/to/sql_database/__init__.py and you can use its part (in system shell) to see all files in folder sql_database

cd /full/path/to/sql_database/
ls   # or `dir` on Windows

And here source code for query.py on GitHub


EDIT:

Example from docstring in query.py

It seems you can use shorter langchain.chains.create_sql_query_chain

# pip install -U langchain langchain-community langchain-openai

from langchain_openai import ChatOpenAI
from langchain.chains import create_sql_query_chain
from langchain_community.utilities import SQLDatabase

db = SQLDatabase.from_uri("sqlite:///Chinook.db")
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
chain = create_sql_query_chain(llm, db)
response = chain.invoke({"question": "How many employees are there"})

Upvotes: 0

Related Questions