Created
April 7, 2024 21:17
-
-
Save romiras/4e34c09f2ade33ea13f9664a79e0b9d0 to your computer and use it in GitHub Desktop.
Querying SQLite using LangChain
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
This demo program outputs raw SQL query by analyzing table, which is run by agent executer, via SQL adapter. | |
""" | |
import os | |
import sqlite3 | |
from langchain.agents import * | |
from langchain.sql_database import SQLDatabase | |
from langchain.chains import create_sql_query_chain | |
from langchain_community.llms import OpenAI | |
from langchain_openai import ChatOpenAI | |
# os.environ['OPENAI_API_KEY'] = "your_openai_api_key" | |
llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0) | |
db = SQLDatabase.from_uri(f"sqlite:///urls.db") | |
chain = create_sql_query_chain(llm, db) | |
response = chain.invoke({"question": "What are the top most popular 3 URLs in table `urls`?"}) | |
print(response) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
This demo program outputs result of a SQL query, which is run by agent executer, via SQL adapter. | |
""" | |
import os | |
import sqlite3 | |
from langchain.agents import * | |
from langchain.sql_database import SQLDatabase | |
from langchain_community.agent_toolkits.sql.toolkit import SQLDatabaseToolkit | |
from langchain_community.agent_toolkits import create_sql_agent | |
from langchain_openai import ChatOpenAI | |
db = SQLDatabase.from_uri(f"sqlite:///urls.db") | |
print(db.dialect) | |
print(db.get_usable_table_names()) | |
# os.environ['OPENAI_API_KEY'] = "your_openai_api_key" | |
llm = ChatOpenAI(model_name="gpt-3.5-turbo") | |
agent_executor = create_sql_agent(llm, db=db, agent_type="openai-tools", verbose=True) | |
# agent_executor.run("Describe the `urls` table") | |
agent_executor.run("What are the top most popular 3 URLs in table `urls`?") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pip install langchain-core | |
pip install -U langchain-community | |
pip install openai |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Additional references