diff --git a/docs/extras/use_cases/tabular/sql_query.ipynb b/docs/extras/use_cases/tabular/sql_query.ipynb new file mode 100644 index 00000000000..a2c1d9e9f3f --- /dev/null +++ b/docs/extras/use_cases/tabular/sql_query.ipynb @@ -0,0 +1,125 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "c04293ac", + "metadata": {}, + "source": [ + "# SQL Query\n", + "\n", + "This notebook walks through how to load and run a chain that constructs SQL queries that can be run against your database to answer a question. Note that this ONLY constructs the query and does not run it." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "e9063a93", + "metadata": {}, + "outputs": [], + "source": [ + "from langchain.chains import create_sql_query_chain\n", + "\n", + "from langchain.chat_models import ChatOpenAI\n", + "from langchain.utilities import SQLDatabase" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "a1ff5cee", + "metadata": {}, + "outputs": [], + "source": [ + "db = SQLDatabase.from_uri(\"sqlite:///../../../../notebooks/Chinook.db\")" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "cb04579f", + "metadata": {}, + "outputs": [], + "source": [ + "chain = create_sql_query_chain(ChatOpenAI(temperature=0), db)" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "744e6210", + "metadata": {}, + "outputs": [], + "source": [ + "response = chain.invoke({\"question\":\"How many employees are there\"})" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "28f984f1", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "SELECT COUNT(*) FROM Employee\n" + ] + } + ], + "source": [ + "print(response)" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "08de511c", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'[(8,)]'" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "db.run(response)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e3a006a7", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.1" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +}