Files
langchain/docs/modules/chains/examples/sqlite.ipynb
T

5.0 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.'
In [ ]: