pythonpy-langchain

ImportError: cannot import name 'SQLDatabaseChain' from 'langchain'


After installing pip install langchain-experimental I have tried:

from langchain_experimental.sql_database import SQLDatabase

But it does not work. The code is as follows:

# 1. Load db with  langchain
from langchain.sql_database import SQLDatabase
db = SQLDatabase.from_uri("sqlite:////python/chatopenai/ecommerce.db")

# 2. Import APIs
import a_env_vars
import os
os.environ["OPENAI_API_KEY"] = a_env_vars.OPENAI_API_KEY

# 3. Create LLM
from langchain.chat_models import ChatOpenAI
llm = ChatOpenAI(temperature=0,model_name='gpt-3.5-turbo')

# 4. Create chain
from langchain import SQLDatabaseChain
cadena = SQLDatabaseChain(llm = llm, database = db, verbose=False)

And the error is:

ImportError: cannot import name 'SQLDatabaseChain' from 'langchain' (C:\Users\jcarr\AppData\Local\Programs\Python\Python311\Lib\site-packages\langchain\__init__.py) Traceback: File "C:\Users\jcarr\AppData\Local\Programs\Python\Python311\Lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 534, in _run_script
    exec(code, module.__dict__) File "C:\python\chatOpenAI\c_front_end.py", line 3, in <module>
    import b_backend File "C:\python\chatOpenAI\b_backend.py", line 15, in <module>
    from langchain import SQLDatabaseChain

This is after doing the same with "langchain.sql_database".


Solution

  • Can use this code:

    from langchain.llms import OpenAI
    from langchain.sql_database import SQLDatabase
    from langchain_experimental.sql import SQLDatabaseChain
    
    db = SQLDatabase.from_uri("sqlite:///Chinook.db")
    db_chain = SQLDatabaseChain.from_llm(OpenAI(), db)