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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "97086e6f",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Lesson 4: Azure OpenAI Function Calling Feature"
9
+ ]
10
+ },
11
+ {
12
+ "cell_type": "markdown",
13
+ "id": "fe2677c5",
14
+ "metadata": {},
15
+ "source": [
16
+ "## Setup"
17
+ ]
18
+ },
19
+ {
20
+ "cell_type": "markdown",
21
+ "id": "6b9a66f8",
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": "f871d539-bb14-4f6b-9212-1222a1227a35",
31
+ "metadata": {
32
+ "height": 166
33
+ },
34
+ "outputs": [],
35
+ "source": [
36
+ "import os\n",
37
+ "from openai import AzureOpenAI\n",
38
+ "import json\n",
39
+ "\n",
40
+ "client = AzureOpenAI(\n",
41
+ " azure_endpoint = os.getenv(\"AZURE_OPENAI_ENDPOINT\"),\n",
42
+ " api_key=os.getenv(\"AZURE_OPENAI_API_KEY\"),\n",
43
+ " api_version=\"2023-05-15\"\n",
44
+ ")"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "markdown",
49
+ "id": "4673778b",
50
+ "metadata": {},
51
+ "source": [
52
+ "## 1. Using an illustrative example"
53
+ ]
54
+ },
55
+ {
56
+ "cell_type": "code",
57
+ "execution_count": null,
58
+ "id": "c7f93802-cb53-42cd-b79b-a8b144f73efb",
59
+ "metadata": {
60
+ "height": 370
61
+ },
62
+ "outputs": [],
63
+ "source": [
64
+ "def get_current_weather(location, unit=\"fahrenheit\"):\n",
65
+ " \"\"\"Get the current weather in a given location. \n",
66
+ " The default unit when not specified is fahrenheit\"\"\"\n",
67
+ " if \"new york\" in location.lower():\n",
68
+ " return json.dumps(\n",
69
+ " {\"location\": \"New York\", \"temperature\": \"40\", \"unit\": unit}\n",
70
+ " )\n",
71
+ " elif \"san francisco\" in location.lower():\n",
72
+ " return json.dumps(\n",
73
+ " {\"location\": \"San Francisco\", \"temperature\": \"50\", \"unit\": unit}\n",
74
+ " )\n",
75
+ " elif \"las vegas\" in location.lower():\n",
76
+ " return json.dumps(\n",
77
+ " {\"location\": \"Las Vegas\", \"temperature\": \"70\", \"unit\": unit}\n",
78
+ " )\n",
79
+ " else:\n",
80
+ " return json.dumps(\n",
81
+ " {\"location\": location, \"temperature\": \"unknown\"}\n",
82
+ " )\n",
83
+ "\n",
84
+ "get_current_weather(\"New York\")"
85
+ ]
86
+ },
87
+ {
88
+ "cell_type": "markdown",
89
+ "id": "4aa6f455",
90
+ "metadata": {},
91
+ "source": [
92
+ "### Define the tools"
93
+ ]
94
+ },
95
+ {
96
+ "cell_type": "code",
97
+ "execution_count": null,
98
+ "id": "f37fd6aa-ce79-4f01-bb96-ccb1b5425743",
99
+ "metadata": {
100
+ "height": 676
101
+ },
102
+ "outputs": [],
103
+ "source": [
104
+ "messages = [\n",
105
+ " {\"role\": \"user\",\n",
106
+ " \"content\": \"\"\"What's the weather like in San Francisco,\n",
107
+ " New York, and Las Vegass?\"\"\"\n",
108
+ " }\n",
109
+ "]\n",
110
+ "\n",
111
+ "tools = [\n",
112
+ " {\n",
113
+ " \"type\": \"function\",\n",
114
+ " \"function\": {\n",
115
+ " \"name\": \"get_current_weather\",\n",
116
+ " \"description\": \"\"\"Get the current weather in a given\n",
117
+ " location.The default unit when not\n",
118
+ " specified is fahrenheit\"\"\",\n",
119
+ " \"parameters\": {\n",
120
+ " \"type\": \"object\",\n",
121
+ " \"properties\": {\n",
122
+ " \"location\": {\n",
123
+ " \"type\": \"string\",\n",
124
+ " \"description\": \"\"\"The city and state,\n",
125
+ " e.g. San Francisco, CA\"\"\",\n",
126
+ " },\n",
127
+ " \"unit\": {\n",
128
+ " \"type\": \"string\",\n",
129
+ " \"default\":\"fahrenheit\",\n",
130
+ " \"enum\": [ \"fahrenheit\", \"celsius\"],\n",
131
+ " \"description\": \"\"\"The messuring unit for\n",
132
+ " the temperature.\n",
133
+ " If not explicitly specified\n",
134
+ " the default unit is \n",
135
+ " fahrenheit\"\"\"\n",
136
+ " },\n",
137
+ " },\n",
138
+ " \"required\": [\"location\"],\n",
139
+ " },\n",
140
+ " },\n",
141
+ " }\n",
142
+ "]"
143
+ ]
144
+ },
145
+ {
146
+ "cell_type": "markdown",
147
+ "id": "04d25317",
148
+ "metadata": {},
149
+ "source": [
150
+ "### Use the function calling"
151
+ ]
152
+ },
153
+ {
154
+ "cell_type": "code",
155
+ "execution_count": null,
156
+ "id": "0c4b13fc-aec6-4753-9cb7-d93243ba4a4d",
157
+ "metadata": {
158
+ "height": 608
159
+ },
160
+ "outputs": [],
161
+ "source": [
162
+ "response = client.chat.completions.create(\n",
163
+ " model=\"gpt-4-1106\",\n",
164
+ " messages=messages,\n",
165
+ " tools=tools,\n",
166
+ " tool_choice=\"auto\", \n",
167
+ ")\n",
168
+ "\n",
169
+ "response_message = response.choices[0].message\n",
170
+ "tool_calls = response_message.tool_calls\n",
171
+ "\n",
172
+ "if tool_calls:\n",
173
+ " print (tool_calls)\n",
174
+ " \n",
175
+ " available_functions = {\n",
176
+ " \"get_current_weather\": get_current_weather,\n",
177
+ " } \n",
178
+ " messages.append(response_message) \n",
179
+ " \n",
180
+ " for tool_call in tool_calls:\n",
181
+ " function_name = tool_call.function.name\n",
182
+ " function_to_call = available_functions[function_name]\n",
183
+ " function_args = json.loads(tool_call.function.arguments)\n",
184
+ " function_response = function_to_call(\n",
185
+ " location=function_args.get(\"location\"),\n",
186
+ " unit=function_args.get(\"unit\"),\n",
187
+ " )\n",
188
+ " messages.append(\n",
189
+ " {\n",
190
+ " \"tool_call_id\": tool_call.id,\n",
191
+ " \"role\": \"tool\",\n",
192
+ " \"name\": function_name,\n",
193
+ " \"content\": function_response,\n",
194
+ " }\n",
195
+ " ) \n",
196
+ " print (messages)"
197
+ ]
198
+ },
199
+ {
200
+ "cell_type": "code",
201
+ "execution_count": null,
202
+ "id": "73d48df7-7eeb-4d5e-ab95-4ae5c1071ded",
203
+ "metadata": {
204
+ "height": 98
205
+ },
206
+ "outputs": [],
207
+ "source": [
208
+ "second_response = client.chat.completions.create(\n",
209
+ " model=\"gpt-4-1106\",\n",
210
+ " messages=messages,\n",
211
+ " )\n",
212
+ "print (second_response)"
213
+ ]
214
+ },
215
+ {
216
+ "cell_type": "markdown",
217
+ "id": "cdcafa56",
218
+ "metadata": {},
219
+ "source": [
220
+ "## 2. Using our SQL database "
221
+ ]
222
+ },
223
+ {
224
+ "cell_type": "markdown",
225
+ "id": "3fffee20",
226
+ "metadata": {},
227
+ "source": [
228
+ "**Note**: To access the data locally, use the following code:\n",
229
+ "\n",
230
+ "```\n",
231
+ "os.makedirs(\"data\",exist_ok=True)\n",
232
+ "!wget https://covidtracking.com/data/download/all-states-history.csv -P ./data/\n",
233
+ "file_url = \"./data/all-states-history.csv\"\n",
234
+ "df = pd.read_csv(file_url).fillna(value = 0)\n",
235
+ "```"
236
+ ]
237
+ },
238
+ {
239
+ "cell_type": "code",
240
+ "execution_count": null,
241
+ "id": "28b73aa0-5eb6-419c-9637-d66a916979d9",
242
+ "metadata": {
243
+ "height": 81
244
+ },
245
+ "outputs": [],
246
+ "source": [
247
+ "from sqlalchemy import create_engine\n",
248
+ "import pandas as pd\n",
249
+ "\n",
250
+ "df = pd.read_csv(\"./data/all-states-history.csv\").fillna(value = 0)"
251
+ ]
252
+ },
253
+ {
254
+ "cell_type": "code",
255
+ "execution_count": null,
256
+ "id": "a4f045df-8811-4af5-9874-fc3f63b813c3",
257
+ "metadata": {
258
+ "height": 166
259
+ },
260
+ "outputs": [],
261
+ "source": [
262
+ "database_file_path = \"./db/test.db\"\n",
263
+ "\n",
264
+ "engine = create_engine(f'sqlite:///{database_file_path}')\n",
265
+ "\n",
266
+ "df.to_sql(\n",
267
+ " 'all_states_history',\n",
268
+ " con=engine,\n",
269
+ " if_exists='replace',\n",
270
+ " index=False)"
271
+ ]
272
+ },
273
+ {
274
+ "cell_type": "markdown",
275
+ "id": "dd8c6c50",
276
+ "metadata": {},
277
+ "source": [
278
+ "### Create two functions"
279
+ ]
280
+ },
281
+ {
282
+ "cell_type": "code",
283
+ "execution_count": null,
284
+ "id": "d89d871e-0d85-40f1-9851-91aa953f7339",
285
+ "metadata": {
286
+ "height": 370
287
+ },
288
+ "outputs": [],
289
+ "source": [
290
+ "import numpy as np\n",
291
+ "from sqlalchemy import text\n",
292
+ "\n",
293
+ "def get_hospitalized_increase_for_state_on_date(state_abbr, specific_date):\n",
294
+ " try:\n",
295
+ " query = f\"\"\"\n",
296
+ " SELECT date, hospitalizedIncrease\n",
297
+ " FROM all_states_history\n",
298
+ " WHERE state = '{state_abbr}' AND date = '{specific_date}';\n",
299
+ " \"\"\"\n",
300
+ " query = text(query)\n",
301
+ "\n",
302
+ " with engine.connect() as connection:\n",
303
+ " result = pd.read_sql_query(query, connection)\n",
304
+ " if not result.empty:\n",
305
+ " return result.to_dict('records')[0]\n",
306
+ " else:\n",
307
+ " return np.nan\n",
308
+ " except Exception as e:\n",
309
+ " print(e)\n",
310
+ " return np.nan"
311
+ ]
312
+ },
313
+ {
314
+ "cell_type": "code",
315
+ "execution_count": null,
316
+ "id": "9b6106ea-799d-4cbe-b75a-26a79627cfd4",
317
+ "metadata": {
318
+ "height": 319
319
+ },
320
+ "outputs": [],
321
+ "source": [
322
+ "def get_positive_cases_for_state_on_date(state_abbr, specific_date):\n",
323
+ " try:\n",
324
+ " query = f\"\"\"\n",
325
+ " SELECT date, state, positiveIncrease AS positive_cases\n",
326
+ " FROM all_states_history\n",
327
+ " WHERE state = '{state_abbr}' AND date = '{specific_date}';\n",
328
+ " \"\"\"\n",
329
+ " query = text(query)\n",
330
+ "\n",
331
+ " with engine.connect() as connection:\n",
332
+ " result = pd.read_sql_query(query, connection)\n",
333
+ " if not result.empty:\n",
334
+ " return result.to_dict('records')[0]\n",
335
+ " else:\n",
336
+ " return np.nan\n",
337
+ " except Exception as e:\n",
338
+ " print(e)\n",
339
+ " return np.nan"
340
+ ]
341
+ },
342
+ {
343
+ "cell_type": "code",
344
+ "execution_count": null,
345
+ "id": "d235c9f0-9377-46d1-880c-c2a5da3f2bc9",
346
+ "metadata": {
347
+ "height": 30
348
+ },
349
+ "outputs": [],
350
+ "source": [
351
+ "get_hospitalized_increase_for_state_on_date(\"AK\",\"2021-03-05\")"
352
+ ]
353
+ },
354
+ {
355
+ "cell_type": "markdown",
356
+ "id": "58a111f7",
357
+ "metadata": {},
358
+ "source": [
359
+ "### Execute the function calling against the SQL database"
360
+ ]
361
+ },
362
+ {
363
+ "cell_type": "code",
364
+ "execution_count": null,
365
+ "id": "97c99de7-2e22-467f-a5b8-771986692fc2",
366
+ "metadata": {
367
+ "height": 115
368
+ },
369
+ "outputs": [],
370
+ "source": [
371
+ "messages = [\n",
372
+ " {\"role\": \"user\",\n",
373
+ " \"content\": \"\"\" how many hospitalized people we had in Alaska\n",
374
+ " the 2021-03-05?\"\"\"\n",
375
+ " }\n",
376
+ "]"
377
+ ]
378
+ },
379
+ {
380
+ "cell_type": "code",
381
+ "execution_count": null,
382
+ "id": "8e22ddeb-911b-4169-810d-33a2cdbc55da",
383
+ "metadata": {
384
+ "height": 931
385
+ },
386
+ "outputs": [],
387
+ "source": [
388
+ "tools_sql = [\n",
389
+ " {\n",
390
+ " \"type\": \"function\",\n",
391
+ " \"function\": {\n",
392
+ " \"name\": \"get_hospitalized_increase_for_state_on_date\",\n",
393
+ " \"description\": \"\"\"Retrieves the daily increase in\n",
394
+ " hospitalizations for a specific state\n",
395
+ " on a specific date.\"\"\",\n",
396
+ " \"parameters\": {\n",
397
+ " \"type\": \"object\",\n",
398
+ " \"properties\": {\n",
399
+ " \"state_abbr\": {\n",
400
+ " \"type\": \"string\",\n",
401
+ " \"description\": \"\"\"The abbreviation of the state\n",
402
+ " (e.g., 'NY', 'CA').\"\"\"\n",
403
+ " },\n",
404
+ " \"specific_date\": {\n",
405
+ " \"type\": \"string\",\n",
406
+ " \"description\": \"\"\"The specific date for\n",
407
+ " the query in 'YYYY-MM-DD'\n",
408
+ " format.\"\"\"\n",
409
+ " }\n",
410
+ " },\n",
411
+ " \"required\": [\"state_abbr\", \"specific_date\"]\n",
412
+ " }\n",
413
+ " }\n",
414
+ " },\n",
415
+ " {\n",
416
+ " \"type\": \"function\",\n",
417
+ " \"function\": {\n",
418
+ " \"name\": \"get_positive_cases_for_state_on_date\",\n",
419
+ " \"description\": \"\"\"Retrieves the daily increase in \n",
420
+ " positive cases for a specific state\n",
421
+ " on a specific date.\"\"\",\n",
422
+ " \"parameters\": {\n",
423
+ " \"type\": \"object\",\n",
424
+ " \"properties\": {\n",
425
+ " \"state_abbr\": {\n",
426
+ " \"type\": \"string\",\n",
427
+ " \"description\": \"\"\"The abbreviation of the \n",
428
+ " state (e.g., 'NY', 'CA').\"\"\"\n",
429
+ " },\n",
430
+ " \"specific_date\": {\n",
431
+ " \"type\": \"string\",\n",
432
+ " \"description\": \"\"\"The specific date for the\n",
433
+ " query in 'YYYY-MM-DD'\n",
434
+ " format.\"\"\"\n",
435
+ " }\n",
436
+ " },\n",
437
+ " \"required\": [\"state_abbr\", \"specific_date\"]\n",
438
+ " }\n",
439
+ " }\n",
440
+ " }\n",
441
+ "]"
442
+ ]
443
+ },
444
+ {
445
+ "cell_type": "code",
446
+ "execution_count": null,
447
+ "id": "4e1c0ba8-7b79-4548-9d8a-32d905b24fb9",
448
+ "metadata": {
449
+ "height": 625
450
+ },
451
+ "outputs": [],
452
+ "source": [
453
+ "response = client.chat.completions.create(\n",
454
+ " model=\"gpt-4-1106\",\n",
455
+ " messages=messages,\n",
456
+ " tools=tools_sql,\n",
457
+ " tool_choice=\"auto\",\n",
458
+ ")\n",
459
+ "\n",
460
+ "response_message = response.choices[0].message\n",
461
+ "tool_calls = response_message.tool_calls\n",
462
+ "\n",
463
+ "if tool_calls:\n",
464
+ " print (tool_calls)\n",
465
+ " \n",
466
+ " available_functions = {\n",
467
+ " \"get_positive_cases_for_state_on_date\": get_positive_cases_for_state_on_date,\n",
468
+ " \"get_hospitalized_increase_for_state_on_date\":get_hospitalized_increase_for_state_on_date\n",
469
+ " } \n",
470
+ " messages.append(response_message) \n",
471
+ " \n",
472
+ " for tool_call in tool_calls:\n",
473
+ " function_name = tool_call.function.name\n",
474
+ " function_to_call = available_functions[function_name]\n",
475
+ " function_args = json.loads(tool_call.function.arguments)\n",
476
+ " function_response = function_to_call(\n",
477
+ " state_abbr=function_args.get(\"state_abbr\"),\n",
478
+ " specific_date=function_args.get(\"specific_date\"),\n",
479
+ " )\n",
480
+ " messages.append(\n",
481
+ " {\n",
482
+ " \"tool_call_id\": tool_call.id,\n",
483
+ " \"role\": \"tool\",\n",
484
+ " \"name\": function_name,\n",
485
+ " \"content\": str(function_response),\n",
486
+ " }\n",
487
+ " ) \n",
488
+ " print(messages)"
489
+ ]
490
+ },
491
+ {
492
+ "cell_type": "code",
493
+ "execution_count": null,
494
+ "id": "1958ad27-0656-4208-98b9-bd813a5af0ee",
495
+ "metadata": {
496
+ "height": 98
497
+ },
498
+ "outputs": [],
499
+ "source": [
500
+ "second_response = client.chat.completions.create(\n",
501
+ " model=\"gpt-4-1106\",\n",
502
+ " messages=messages,\n",
503
+ " )\n",
504
+ "print (second_response)"
505
+ ]
506
+ }
507
+ ],
508
+ "metadata": {
509
+ "kernelspec": {
510
+ "display_name": "Python 3 (ipykernel)",
511
+ "language": "python",
512
+ "name": "python3"
513
+ },
514
+ "language_info": {
515
+ "codemirror_mode": {
516
+ "name": "ipython",
517
+ "version": 3
518
+ },
519
+ "file_extension": ".py",
520
+ "mimetype": "text/x-python",
521
+ "name": "python",
522
+ "nbconvert_exporter": "python",
523
+ "pygments_lexer": "ipython3",
524
+ "version": "3.11.9"
525
+ }
526
+ },
527
+ "nbformat": 4,
528
+ "nbformat_minor": 5
529
+ }