Files
langchain/docs/modules/chains/examples/sqlite.ipynb
T
Harrison Chase 1c71fadfdc more complex sql chain (#619)
add a more complex sql chain that first subsets the necessary tables
2023-01-15 17:07:21 -08:00

6.7 KiB

SQLite example

This example showcases hooking up an LLM to answer questions over a database.

This uses the example Chinook database. To set it up follow the instructions on https://database.guide/2-sample-databases-sqlite/, placing the .db file in a notebooks folder at the root of this repository.

In [1]:
from langchain import OpenAI, SQLDatabase, SQLDatabaseChain
In [2]:
db = SQLDatabase.from_uri("sqlite:///../../../../notebooks/Chinook.db")
llm = OpenAI(temperature=0)
db_chain = SQLDatabaseChain(llm=llm, database=db, verbose=True)
In [3]:
db_chain.run("How many employees are there?")
Out [3]:

> Entering new SQLDatabaseChain chain...
How many employees are there? 
SQLQuery: SELECT COUNT(*) FROM Employee;
SQLResult: [(9,)]
Answer: There are 9 employees.
> Finished chain.
' There are 9 employees.'

Customize Prompt

You can also customize the prompt that is used. Here is an example prompting it to understand that foobar is the same as the Employee table

In [5]:
from langchain.prompts.prompt import PromptTemplate

_DEFAULT_TEMPLATE = """Given an input question, first create a syntactically correct {dialect} query to run, then look at the results of the query and return the answer.
Use the following format:

Question: "Question here"
SQLQuery: "SQL Query to run"
SQLResult: "Result of the SQLQuery"
Answer: "Final answer here"

Only use the following tables:

{table_info}

If someone asks for the table foobar, they really mean the employee table.

Question: {input}"""
PROMPT = PromptTemplate(
    input_variables=["input", "table_info", "dialect"], template=_DEFAULT_TEMPLATE
)
In [6]:
db_chain = SQLDatabaseChain(llm=llm, database=db, prompt=PROMPT, verbose=True)
In [7]:
db_chain.run("How many employees are there in the foobar table?")
Out [7]:

> Entering new SQLDatabaseChain chain...
How many employees are there in the foobar table? 
SQLQuery: SELECT COUNT(*) FROM Employee;
SQLResult: [(9,)]
Answer: There are 9 employees in the foobar table.
> Finished chain.
' There are 9 employees in the foobar table.'

SQLDatabaseSequentialChain

Chain for querying SQL database that is a sequential chain.

The chain is as follows:

1. Based on the query, determine which tables to use.
2. Based on those tables, call the normal SQL database chain.

This is useful in cases where the number of tables in the database is large.

In [3]:
from langchain.chains.sql_database.base import SQLDatabaseSequentialChain
In [4]:
chain = SQLDatabaseSequentialChain.from_llm(llm, db, verbose=True)
In [5]:
chain.run("How many employees are also customers?")
Out [5]:

> Entering new SQLDatabaseSequentialChain chain...
Table names to use:
['Employee', 'Customer']
> Finished chain.
' 0 employees are also customers.'
In [ ]: