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 rasa_sdk import Action
from rasa_sdk.executor import CollectingDispatcher
from rasa_sdk import Tracker
from rasa_sdk.events import SlotSet
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" # Replace with your OpenAI API key
db_uri = "your_database_uri" # Replace with your SQL 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
# Custom action to query HRMS database based on context
class ActionQueryHRMS(Action):
def name(self):
return "action_query_hrms"
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: dict):
# Get the intent and any relevant entities from the tracker
intent = tracker.latest_message.get("intent", {}).get("name", "")
entities = {slot: tracker.get_slot(slot) for slot in ["employee_name", "department_name"]}
# Generate SQL query based on the intent and context (entities)
sql_query = sql_chain.generate(intent=intent, context=entities)
# Execute the SQL query and fetch the results
result = execute_sql_query(sql_query)
if result:
# Format the response based on the query result
response = f"Query result: {result}"
else:
response = "No relevant information found."
dispatcher.utter_message(text=response) # Send response back to the user
return []
I tried searching all the latest import statements to find SQLQueryChain import but i couldn’t find it.