FortiShield commited on
Commit
c34e33c
1 Parent(s): 1cc709c

Add files via upload

Browse files
L2_Interacting_with_a_CSV_Data.ipynb ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "d792f35b",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Lesson 2: Interacting with a CSV Data"
9
+ ]
10
+ },
11
+ {
12
+ "cell_type": "markdown",
13
+ "id": "6be6d049",
14
+ "metadata": {},
15
+ "source": [
16
+ "## Setup and connect to the Azure OpenAI endpoint"
17
+ ]
18
+ },
19
+ {
20
+ "cell_type": "markdown",
21
+ "id": "399c89a2",
22
+ "metadata": {},
23
+ "source": [
24
+ "**Note**: The pre-configured cloud resource grants you access to the Azure OpenAI GPT model. The key and endpoint provided below are intended for teaching purposes only. Your notebook environment is already set up with the necessary keys, which may differ from those used by the instructor during the filming."
25
+ ]
26
+ },
27
+ {
28
+ "cell_type": "code",
29
+ "execution_count": null,
30
+ "id": "83ac3e59-d0d1-4110-a059-3a55d0d5e15e",
31
+ "metadata": {
32
+ "height": 217
33
+ },
34
+ "outputs": [],
35
+ "source": [
36
+ "import os \n",
37
+ "import pandas as pd\n",
38
+ "\n",
39
+ "from IPython.display import Markdown, HTML, display\n",
40
+ "from langchain.schema import HumanMessage\n",
41
+ "from langchain_openai import AzureChatOpenAI\n",
42
+ "\n",
43
+ "model = AzureChatOpenAI(\n",
44
+ " openai_api_version=\"2023-05-15\",\n",
45
+ " azure_deployment=\"gpt-4-1106\",\n",
46
+ " azure_endpoint=os.getenv(\"AZURE_OPENAI_ENDPOINT\"),\n",
47
+ ")"
48
+ ]
49
+ },
50
+ {
51
+ "cell_type": "markdown",
52
+ "id": "ba9075a3",
53
+ "metadata": {},
54
+ "source": [
55
+ "## Load the dataset"
56
+ ]
57
+ },
58
+ {
59
+ "cell_type": "markdown",
60
+ "id": "fb0dc855",
61
+ "metadata": {},
62
+ "source": [
63
+ "**Note**: To access the data locally, use the following code:\n",
64
+ "\n",
65
+ "```\n",
66
+ "os.makedirs(\"data\",exist_ok=True)\n",
67
+ "!wget https://covidtracking.com/data/download/all-states-history.csv -P ./data/\n",
68
+ "file_url = \"./data/all-states-history.csv\"\n",
69
+ "df = pd.read_csv(file_url).fillna(value = 0)\n",
70
+ "```"
71
+ ]
72
+ },
73
+ {
74
+ "cell_type": "code",
75
+ "execution_count": null,
76
+ "id": "b6c75799-55e2-4d39-a1ab-7b968b4f35a4",
77
+ "metadata": {
78
+ "height": 30
79
+ },
80
+ "outputs": [],
81
+ "source": [
82
+ "df = pd.read_csv(\"./data/all-states-history.csv\").fillna(value = 0)"
83
+ ]
84
+ },
85
+ {
86
+ "cell_type": "markdown",
87
+ "id": "a6a261ac",
88
+ "metadata": {},
89
+ "source": [
90
+ "## Prepare the Langchain dataframe agent"
91
+ ]
92
+ },
93
+ {
94
+ "cell_type": "code",
95
+ "execution_count": null,
96
+ "id": "60d0793b-90e7-4e8b-b2f1-66a8d1cf652d",
97
+ "metadata": {
98
+ "height": 115
99
+ },
100
+ "outputs": [],
101
+ "source": [
102
+ "from langchain.agents.agent_types import AgentType\n",
103
+ "from langchain_experimental.agents.agent_toolkits import create_pandas_dataframe_agent\n",
104
+ "\n",
105
+ "agent = create_pandas_dataframe_agent(llm=model,df=df,verbose=True)\n",
106
+ "\n",
107
+ "agent.invoke(\"how many rows are there?\")"
108
+ ]
109
+ },
110
+ {
111
+ "cell_type": "markdown",
112
+ "id": "7c6dedce",
113
+ "metadata": {},
114
+ "source": [
115
+ "## Design your prompt and ask your question"
116
+ ]
117
+ },
118
+ {
119
+ "cell_type": "code",
120
+ "execution_count": null,
121
+ "id": "0d005008-bad6-4458-90ec-6372d9ebe61c",
122
+ "metadata": {
123
+ "height": 523
124
+ },
125
+ "outputs": [],
126
+ "source": [
127
+ "CSV_PROMPT_PREFIX = \"\"\"\n",
128
+ "First set the pandas display options to show all the columns,\n",
129
+ "get the column names, then answer the question.\n",
130
+ "\"\"\"\n",
131
+ "\n",
132
+ "CSV_PROMPT_SUFFIX = \"\"\"\n",
133
+ "- **ALWAYS** before giving the Final Answer, try another method.\n",
134
+ "Then reflect on the answers of the two methods you did and ask yourself\n",
135
+ "if it answers correctly the original question.\n",
136
+ "If you are not sure, try another method.\n",
137
+ "- If the methods tried do not give the same result,reflect and\n",
138
+ "try again until you have two methods that have the same result.\n",
139
+ "- If you still cannot arrive to a consistent result, say that\n",
140
+ "you are not sure of the answer.\n",
141
+ "- If you are sure of the correct answer, create a beautiful\n",
142
+ "and thorough response using Markdown.\n",
143
+ "- **DO NOT MAKE UP AN ANSWER OR USE PRIOR KNOWLEDGE,\n",
144
+ "ONLY USE THE RESULTS OF THE CALCULATIONS YOU HAVE DONE**.\n",
145
+ "- **ALWAYS**, as part of your \"Final Answer\", explain how you got\n",
146
+ "to the answer on a section that starts with: \"\\n\\nExplanation:\\n\".\n",
147
+ "In the explanation, mention the column names that you used to get\n",
148
+ "to the final answer.\n",
149
+ "\"\"\"\n",
150
+ "\n",
151
+ "QUESTION = \"How may patients were hospitalized during July 2020\" \n",
152
+ "\"in Texas, and nationwide as the total of all states?\"\n",
153
+ "\"Use the hospitalizedIncrease column\" \n",
154
+ "\n",
155
+ "\n",
156
+ "agent.invoke(CSV_PROMPT_PREFIX + QUESTION + CSV_PROMPT_SUFFIX)"
157
+ ]
158
+ }
159
+ ],
160
+ "metadata": {
161
+ "kernelspec": {
162
+ "display_name": "Python 3 (ipykernel)",
163
+ "language": "python",
164
+ "name": "python3"
165
+ },
166
+ "language_info": {
167
+ "codemirror_mode": {
168
+ "name": "ipython",
169
+ "version": 3
170
+ },
171
+ "file_extension": ".py",
172
+ "mimetype": "text/x-python",
173
+ "name": "python",
174
+ "nbconvert_exporter": "python",
175
+ "pygments_lexer": "ipython3",
176
+ "version": "3.11.9"
177
+ }
178
+ },
179
+ "nbformat": 4,
180
+ "nbformat_minor": 5
181
+ }
L3_Connecting_to_a_SQL_Database.ipynb ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "834061f0",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Lesson 3: Connecting to a SQL Database"
9
+ ]
10
+ },
11
+ {
12
+ "cell_type": "markdown",
13
+ "id": "34cb8641",
14
+ "metadata": {},
15
+ "source": [
16
+ "## Setup"
17
+ ]
18
+ },
19
+ {
20
+ "cell_type": "code",
21
+ "execution_count": null,
22
+ "id": "f50bdee1-25c0-472e-a739-c8551b5c5349",
23
+ "metadata": {
24
+ "height": 132
25
+ },
26
+ "outputs": [],
27
+ "source": [
28
+ "import os\n",
29
+ "from IPython.display import Markdown, HTML, display\n",
30
+ "from langchain.chat_models import AzureChatOpenAI\n",
31
+ "from langchain.agents import create_sql_agent\n",
32
+ "from langchain.agents.agent_toolkits import SQLDatabaseToolkit\n",
33
+ "from langchain.sql_database import SQLDatabase\n",
34
+ "from langchain_openai import AzureChatOpenAI"
35
+ ]
36
+ },
37
+ {
38
+ "cell_type": "markdown",
39
+ "id": "730f966e",
40
+ "metadata": {},
41
+ "source": [
42
+ "## Recover the original dataset"
43
+ ]
44
+ },
45
+ {
46
+ "cell_type": "markdown",
47
+ "id": "95771d97",
48
+ "metadata": {},
49
+ "source": [
50
+ "**Note**: To access the data locally, use the following code:\n",
51
+ "\n",
52
+ "```\n",
53
+ "os.makedirs(\"data\",exist_ok=True)\n",
54
+ "!wget https://covidtracking.com/data/download/all-states-history.csv -P ./data/\n",
55
+ "file_url = \"./data/all-states-history.csv\"\n",
56
+ "df = pd.read_csv(file_url).fillna(value = 0)\n",
57
+ "```"
58
+ ]
59
+ },
60
+ {
61
+ "cell_type": "code",
62
+ "execution_count": null,
63
+ "id": "37246b14-8a2a-4396-b592-16c1b8b62973",
64
+ "metadata": {
65
+ "height": 98
66
+ },
67
+ "outputs": [],
68
+ "source": [
69
+ "from sqlalchemy import create_engine\n",
70
+ "import pandas as pd\n",
71
+ "\n",
72
+ "\n",
73
+ "df = pd.read_csv(\"./data/all-states-history.csv\").fillna(value = 0)"
74
+ ]
75
+ },
76
+ {
77
+ "cell_type": "markdown",
78
+ "id": "8df5c4c1",
79
+ "metadata": {},
80
+ "source": [
81
+ "## Move the data to the SQL database"
82
+ ]
83
+ },
84
+ {
85
+ "cell_type": "code",
86
+ "execution_count": null,
87
+ "id": "6bb39f31-4ab3-4c95-a55d-4140fd68711f",
88
+ "metadata": {
89
+ "height": 251
90
+ },
91
+ "outputs": [],
92
+ "source": [
93
+ "# Path to your SQLite database file\n",
94
+ "database_file_path = \"./db/test.db\"\n",
95
+ "\n",
96
+ "# Create an engine to connect to the SQLite database\n",
97
+ "# SQLite only requires the path to the database file\n",
98
+ "engine = create_engine(f'sqlite:///{database_file_path}')\n",
99
+ "file_url = \"./data/all-states-history.csv\"\n",
100
+ "df = pd.read_csv(file_url).fillna(value = 0)\n",
101
+ "df.to_sql(\n",
102
+ " 'all_states_history',\n",
103
+ " con=engine,\n",
104
+ " if_exists='replace',\n",
105
+ " index=False\n",
106
+ ")"
107
+ ]
108
+ },
109
+ {
110
+ "cell_type": "markdown",
111
+ "id": "8307ac30",
112
+ "metadata": {},
113
+ "source": [
114
+ "## Prepare the SQL prompt"
115
+ ]
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "execution_count": null,
120
+ "id": "a2e02e43-c499-4897-9981-78e7fbae3491",
121
+ "metadata": {
122
+ "height": 608
123
+ },
124
+ "outputs": [],
125
+ "source": [
126
+ "MSSQL_AGENT_PREFIX = \"\"\"\n",
127
+ "\n",
128
+ "You are an agent designed to interact with a SQL database.\n",
129
+ "## Instructions:\n",
130
+ "- Given an input question, create a syntactically correct {dialect} query\n",
131
+ "to run, then look at the results of the query and return the answer.\n",
132
+ "- Unless the user specifies a specific number of examples they wish to\n",
133
+ "obtain, **ALWAYS** limit your query to at most {top_k} results.\n",
134
+ "- You can order the results by a relevant column to return the most\n",
135
+ "interesting examples in the database.\n",
136
+ "- Never query for all the columns from a specific table, only ask for\n",
137
+ "the relevant columns given the question.\n",
138
+ "- You have access to tools for interacting with the database.\n",
139
+ "- You MUST double check your query before executing it.If you get an error\n",
140
+ "while executing a query,rewrite the query and try again.\n",
141
+ "- DO NOT make any DML statements (INSERT, UPDATE, DELETE, DROP etc.)\n",
142
+ "to the database.\n",
143
+ "- DO NOT MAKE UP AN ANSWER OR USE PRIOR KNOWLEDGE, ONLY USE THE RESULTS\n",
144
+ "OF THE CALCULATIONS YOU HAVE DONE.\n",
145
+ "- Your response should be in Markdown. However, **when running a SQL Query\n",
146
+ "in \"Action Input\", do not include the markdown backticks**.\n",
147
+ "Those are only for formatting the response, not for executing the command.\n",
148
+ "- ALWAYS, as part of your final answer, explain how you got to the answer\n",
149
+ "on a section that starts with: \"Explanation:\". Include the SQL query as\n",
150
+ "part of the explanation section.\n",
151
+ "- If the question does not seem related to the database, just return\n",
152
+ "\"I don\\'t know\" as the answer.\n",
153
+ "- Only use the below tools. Only use the information returned by the\n",
154
+ "below tools to construct your query and final answer.\n",
155
+ "- Do not make up table names, only use the tables returned by any of the\n",
156
+ "tools below.\n",
157
+ "\n",
158
+ "## Tools:\n",
159
+ "\n",
160
+ "\"\"\""
161
+ ]
162
+ },
163
+ {
164
+ "cell_type": "code",
165
+ "execution_count": null,
166
+ "id": "e70cd29a-c369-4419-ae27-e1f9912b5064",
167
+ "metadata": {
168
+ "height": 693
169
+ },
170
+ "outputs": [],
171
+ "source": [
172
+ "MSSQL_AGENT_FORMAT_INSTRUCTIONS = \"\"\"\n",
173
+ "\n",
174
+ "## Use the following format:\n",
175
+ "\n",
176
+ "Question: the input question you must answer.\n",
177
+ "Thought: you should always think about what to do.\n",
178
+ "Action: the action to take, should be one of [{tool_names}].\n",
179
+ "Action Input: the input to the action.\n",
180
+ "Observation: the result of the action.\n",
181
+ "... (this Thought/Action/Action Input/Observation can repeat N times)\n",
182
+ "Thought: I now know the final answer.\n",
183
+ "Final Answer: the final answer to the original input question.\n",
184
+ "\n",
185
+ "Example of Final Answer:\n",
186
+ "<=== Beginning of example\n",
187
+ "\n",
188
+ "Action: query_sql_db\n",
189
+ "Action Input: \n",
190
+ "SELECT TOP (10) [death]\n",
191
+ "FROM covidtracking \n",
192
+ "WHERE state = 'TX' AND date LIKE '2020%'\n",
193
+ "\n",
194
+ "Observation:\n",
195
+ "[(27437.0,), (27088.0,), (26762.0,), (26521.0,), (26472.0,), (26421.0,), (26408.0,)]\n",
196
+ "Thought:I now know the final answer\n",
197
+ "Final Answer: There were 27437 people who died of covid in Texas in 2020.\n",
198
+ "\n",
199
+ "Explanation:\n",
200
+ "I queried the `covidtracking` table for the `death` column where the state\n",
201
+ "is 'TX' and the date starts with '2020'. The query returned a list of tuples\n",
202
+ "with the number of deaths for each day in 2020. To answer the question,\n",
203
+ "I took the sum of all the deaths in the list, which is 27437.\n",
204
+ "I used the following query\n",
205
+ "\n",
206
+ "```sql\n",
207
+ "SELECT [death] FROM covidtracking WHERE state = 'TX' AND date LIKE '2020%'\"\n",
208
+ "```\n",
209
+ "===> End of Example\n",
210
+ "\n",
211
+ "\"\"\""
212
+ ]
213
+ },
214
+ {
215
+ "cell_type": "markdown",
216
+ "id": "a9350e98",
217
+ "metadata": {},
218
+ "source": [
219
+ "## Call the Azure Chat model and create the SQL agent"
220
+ ]
221
+ },
222
+ {
223
+ "cell_type": "markdown",
224
+ "id": "2816f00e",
225
+ "metadata": {},
226
+ "source": [
227
+ "**Note**: The pre-configured cloud resource grants you access to the Azure OpenAI GPT model. The key and endpoint provided below are intended for teaching purposes only. Your notebook environment is already set up with the necessary keys, which may differ from those used by the instructor during the filming."
228
+ ]
229
+ },
230
+ {
231
+ "cell_type": "code",
232
+ "execution_count": null,
233
+ "id": "a9d5ffc3-cea0-48f8-96ce-177bb9cecd92",
234
+ "metadata": {
235
+ "height": 183
236
+ },
237
+ "outputs": [],
238
+ "source": [
239
+ "llm = AzureChatOpenAI(\n",
240
+ " openai_api_version=\"2023-05-15\",\n",
241
+ " azure_deployment=\"gpt-4-1106\",\n",
242
+ " azure_endpoint=os.getenv(\"AZURE_OPENAI_ENDPOINT\"),\n",
243
+ " temperature=0, \n",
244
+ " max_tokens=500\n",
245
+ ")\n",
246
+ "\n",
247
+ "db = SQLDatabase.from_uri(f'sqlite:///{database_file_path}')\n",
248
+ "toolkit = SQLDatabaseToolkit(db=db, llm=llm)"
249
+ ]
250
+ },
251
+ {
252
+ "cell_type": "code",
253
+ "execution_count": null,
254
+ "id": "50e7259a-ee4b-4c8f-a0fa-f747237ad6a4",
255
+ "metadata": {
256
+ "height": 234
257
+ },
258
+ "outputs": [],
259
+ "source": [
260
+ "QUESTION = \"\"\"How may patients were hospitalized during October 2020\n",
261
+ "in New York, and nationwide as the total of all states?\n",
262
+ "Use the hospitalizedIncrease column\n",
263
+ "\"\"\"\n",
264
+ "\n",
265
+ "agent_executor_SQL = create_sql_agent(\n",
266
+ " prefix=MSSQL_AGENT_PREFIX,\n",
267
+ " format_instructions = MSSQL_AGENT_FORMAT_INSTRUCTIONS,\n",
268
+ " llm=llm,\n",
269
+ " toolkit=toolkit,\n",
270
+ " top_k=30,\n",
271
+ " verbose=True\n",
272
+ ")"
273
+ ]
274
+ },
275
+ {
276
+ "cell_type": "markdown",
277
+ "id": "9fea48e9",
278
+ "metadata": {},
279
+ "source": [
280
+ "## Invoke the SQL model"
281
+ ]
282
+ },
283
+ {
284
+ "cell_type": "code",
285
+ "execution_count": null,
286
+ "id": "953cee48-831b-4b87-98ef-359fafb7492d",
287
+ "metadata": {
288
+ "height": 30
289
+ },
290
+ "outputs": [],
291
+ "source": [
292
+ "agent_executor_SQL.invoke(QUESTION)"
293
+ ]
294
+ }
295
+ ],
296
+ "metadata": {
297
+ "kernelspec": {
298
+ "display_name": "Python 3 (ipykernel)",
299
+ "language": "python",
300
+ "name": "python3"
301
+ },
302
+ "language_info": {
303
+ "codemirror_mode": {
304
+ "name": "ipython",
305
+ "version": 3
306
+ },
307
+ "file_extension": ".py",
308
+ "mimetype": "text/x-python",
309
+ "name": "python",
310
+ "nbconvert_exporter": "python",
311
+ "pygments_lexer": "ipython3",
312
+ "version": "3.11.9"
313
+ }
314
+ },
315
+ "nbformat": 4,
316
+ "nbformat_minor": 5
317
+ }