Cookbook Examples Langchain Chat With SQL Using Langchain - Ipynb at Main Google-Gemini Cookbook
Cookbook Examples Langchain Chat With SQL Using Langchain - Ipynb at Main Google-Gemini Cookbook
google-gemini /
cookbook
https://github.com/google-gemini/cookbook/blob/main/examples/langchain/Chat_with_SQL_using_langchain.ipynb 1/9
27/7/24, 20:04 cookbook/examples/langchain/Chat_with_SQL_using_langchain.ipynb at main · google-gemini/cookbook
In [ ]: # @title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
Reading an SQL database can be challenging for humans. However, with accurate
prompts, Gemini models can generate answers based on the data. Through the use of
the Gemini API, you will be able retrieve necessary information by chatting with a SQL
database.
In [3]: import os
from google.colab import userdata
GOOGLE_API_KEY=userdata.get('GOOGLE_API_KEY')
os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY
1. Load the California Housing Dataset: Load the dataset from sklearn.datasets
and extract it into a DataFrame.
california_housing_bunch = fetch_california_housing(as_frame=True)
california_housing_df = california_housing_bunch.frame
2. Connect to the SQLite database: The database will be stored in the specified file.
Out[5]: 20640
Question to query
With the database connection established, the SQLDatabase object now contains
information about our database, which the model can access.
Out[7]: CREATE TABLE housing ( "MedInc" REAL, "HouseAge" REAL, "AveRooms" REAL,
"AveBedrms" REAL, "Population" REAL, "AveOccup" REAL, "Latitude" REAL, "Longitude"
REAL, "MedHouseVal" REAL )
In this case, default prompt is suitable for the task. However, feel free to experiment
with writing this part of our chain yourself to suit your preferences.
In [10]: Markdown(write_query_chain.get_prompts()[0].template)
Out[10]: You are a SQLite expert. Given an input question, first create a syntactically correct
SQLite query to run, then look at the results of the query and return the answer to the
input question. Unless the user specifies in the question a specific number of examples
to obtain, query for at most {top_k} results using the LIMIT clause as per SQLite. You can
order the results to return the most informative data in the database. Never query for
all columns from a table. You must query only the columns that are needed to answer
the question. Wrap each column name in double quotes (") to denote them as
delimited identifiers. Pay attention to use only the column names you can see in the
tables below. Be careful to not query for columns that do not exist. Also, pay attention
to which column is in which table. Pay attention to use date('now') function to get the
current date, if the question involves "today".
Question: Question here SQLQuery: SQL Query to run SQLResult: Result of the
SQLQuery Answer: Final answer here
Question: {input}
Out[12]: '[(29421840.0,)]'
Great! The SQL query is correct, but it needs proper formatting before it can be
executed directly by the database.
Automatic querying
Now, let's automate the process of querying the database using
QuerySQLDataBaseTool. This tool can receive text from previous parts of the chain,
execute the query, and return the answer.
Out[15]: '[(29421840.0,)]'
Generating answer
You are almost done!
To enhance our output, you'll use LLM not only to get the number but to get properly
formatted and natural language response.
answer_chain = (
RunnablePassthrough.assign(query=validate_chain).assign(
result=itemgetter("query") | execute_query
)
| answer_prompt | llm | StrOutputParser()
)
Next steps
Congratulations! You've successfully created a functional chain to interact with SQL.
Now, feel free to explore further by asking different questions.
https://github.com/google-gemini/cookbook/blob/main/examples/langchain/Chat_with_SQL_using_langchain.ipynb 6/9
27/7/24, 20:04 cookbook/examples/langchain/Chat_with_SQL_using_langchain.ipynb at main · google-gemini/cookbook
https://github.com/google-gemini/cookbook/blob/main/examples/langchain/Chat_with_SQL_using_langchain.ipynb 7/9
27/7/24, 20:04 cookbook/examples/langchain/Chat_with_SQL_using_langchain.ipynb at main · google-gemini/cookbook
https://github.com/google-gemini/cookbook/blob/main/examples/langchain/Chat_with_SQL_using_langchain.ipynb 8/9
27/7/24, 20:04 cookbook/examples/langchain/Chat_with_SQL_using_langchain.ipynb at main · google-gemini/cookbook
https://github.com/google-gemini/cookbook/blob/main/examples/langchain/Chat_with_SQL_using_langchain.ipynb 9/9