mirror of
https://github.com/langchain-ai/langchain.git
synced 2026-10-06 01:45:27 +03:00
5.0 KiB
5.0 KiB
In [1]:
from langchain import OpenAI, SQLDatabase, SQLDatabaseChainIn [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]:
[1m> Entering new SQLDatabaseChain chain...[0m How many employees are there? SQLQuery:[32;1m[1;3m SELECT COUNT(*) FROM Employee;[0m SQLResult: [33;1m[1;3m[(9,)][0m Answer:[32;1m[1;3m There are 9 employees.[0m [1m> Finished chain.[0m
' There are 9 employees.'
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]:
[1m> Entering new SQLDatabaseChain chain...[0m How many employees are there in the foobar table? SQLQuery:[32;1m[1;3m SELECT COUNT(*) FROM Employee;[0m SQLResult: [33;1m[1;3m[(9,)][0m Answer:[32;1m[1;3m There are 9 employees in the foobar table.[0m [1m> Finished chain.[0m
' There are 9 employees in the foobar table.'
In [ ]: