Skip to main content

Querying a SQL DB

We can replicate our SQLDatabaseChain with Runnables.

from langchain.prompts import ChatPromptTemplate

template = """Based on the table schema below, write a SQL query that would answer the user's question:
{schema}

Question: {question}
SQL Query:"""
prompt = ChatPromptTemplate.from_template(template)

API Reference:

from langchain.utilities import SQLDatabase

API Reference:

We'll need the Chinook sample DB for this example. There's many places to download it from, e.g. https://database.guide/2-sample-databases-sqlite/

db = SQLDatabase.from_uri("sqlite:///./Chinook.db")
def get_schema(_):
return db.get_table_info()
def run_query(query):
return db.run(query)
from operator import itemgetter

from langchain.chat_models import ChatOpenAI
from langchain.schema.output_parser import StrOutputParser
from langchain.schema.runnable import RunnableLambda, RunnableMap

model = ChatOpenAI()

inputs = {
"schema": RunnableLambda(get_schema),
"question": itemgetter("question")
}
sql_response = (
RunnableMap(inputs)
| prompt
| model.bind(stop=["\nSQLResult:"])
| StrOutputParser()
)
sql_response.invoke({"question": "How many employees are there?"})
    'SELECT COUNT(*) FROM Employee'
template = """Based on the table schema below, question, sql query, and sql response, write a natural language response:
{schema}

Question: {question}
SQL Query: {query}
SQL Response: {response}"""
prompt_response = ChatPromptTemplate.from_template(template)
full_chain = (
RunnableMap({
"question": itemgetter("question"),
"query": sql_response,
})
| {
"schema": RunnableLambda(get_schema),
"question": itemgetter("question"),
"query": itemgetter("query"),
"response": lambda x: db.run(x["query"])
}
| prompt_response
| model
)
full_chain.invoke({"question": "How many employees are there?"})
    AIMessage(content='There are 8 employees.', additional_kwargs={}, example=False)