File size: 33,510 Bytes
b38c914
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Adding a Spotify Tool - Musically You!\n",
    "\n",
    "This version of the notebook introduces a Spotify tool that can query your listening history from Spotify to extend the domain of questions the chatbot can answer to include your musical tastes.\n",
    "\n",
    "Unfortunately, it's a bit of PITA to get acess and refresh tokens for Spotify.  The process requires connecting to an authentication end point while logged in to Spotify and then processing a callback.  To make this easier, instructions along with a small app that can be deployed to HuggingFace Spaces using Gradio are included at the end of this notebook. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The first big project - Professionally You!\n",
    "\n",
    "### And, Tool use.\n",
    "\n",
    "### But first: introducing Pushover\n",
    "\n",
    "Pushover is a nifty tool for sending Push Notifications to your phone.\n",
    "\n",
    "It's super easy to set up and install!\n",
    "\n",
    "Simply visit https://pushover.net/ and click 'Login or Signup' on the top right to sign up for a free account, and create your API keys.\n",
    "\n",
    "Once you've signed up, on the home screen, click \"Create an Application/API Token\", and give it any name (like Agents) and click Create Application.\n",
    "\n",
    "Then add 2 lines to your `.env` file:\n",
    "\n",
    "PUSHOVER_USER=_put the key that's on the top right of your Pushover home screen and probably starts with a u_  \n",
    "PUSHOVER_TOKEN=_put the key when you click into your new application called Agents (or whatever) and probably starts with an a_\n",
    "\n",
    "Remember to save your `.env` file, and run `load_dotenv(override=True)` after saving, to set your environment variables.\n",
    "\n",
    "Finally, click \"Add Phone, Tablet or Desktop\" to install on your phone."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "# imports\n",
    "\n",
    "from dotenv import load_dotenv\n",
    "from openai import OpenAI\n",
    "import json\n",
    "import os\n",
    "import requests\n",
    "from pypdf import PdfReader\n",
    "import gradio as gr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "# The usual start\n",
    "\n",
    "load_dotenv(override=True)\n",
    "openai = OpenAI()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# For pushover\n",
    "\n",
    "pushover_user = os.getenv(\"PUSHOVER_USER\")\n",
    "pushover_token = os.getenv(\"PUSHOVER_TOKEN\")\n",
    "pushover_url = \"https://api.pushover.net/1/messages.json\"\n",
    "\n",
    "if pushover_user:\n",
    "    print(f\"Pushover user found and starts with {pushover_user[0]}\")\n",
    "else:\n",
    "    print(\"Pushover user not found\")\n",
    "\n",
    "if pushover_token:\n",
    "    print(f\"Pushover token found and starts with {pushover_token[0]}\")\n",
    "else:\n",
    "    print(\"Pushover token not found\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "def push(message):\n",
    "    print(f\"Push: {message}\")\n",
    "    payload = {\"user\": pushover_user, \"token\": pushover_token, \"message\": message}\n",
    "    requests.post(pushover_url, data=payload)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [],
   "source": [
    "def record_user_details(email, name=\"Name not provided\", notes=\"not provided\"):\n",
    "    push(f\"Recording interest from {name} with email {email} and notes {notes}\")\n",
    "    return {\"recorded\": \"ok\"}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "def record_unknown_question(question):\n",
    "    push(f\"Recording {question} asked that I couldn't answer\")\n",

    "    return {\"recorded\": \"ok\"}"

   ]

  },

  {

   "cell_type": "code",

   "execution_count": null,

   "metadata": {},

   "outputs": [],

   "source": [

    "# For Spotify access token and refresh token\n",

    "import base64\n",

    "import time\n",

    "import hashlib\n",

    "import secrets\n",

    "import urllib.parse\n",

    "\n",

    "spotify_client_id = os.getenv(\"SPOTIFY_CLIENT_ID\")\n",

    "spotify_client_secret = os.getenv(\"SPOTIFY_CLIENT_SECRET\")\n",

    "\n",

    "if spotify_client_id:\n",

    "    print(f\"Spotify client ID found and starts with {spotify_client_id[:4]}\")\n",

    "else:\n",

    "    print(\"Spotify client ID not found\")\n",

    "\n",

    "if spotify_client_secret:\n",

    "    print(f\"Spotify client secret found and starts with {spotify_client_secret[:4]}\")\n",

    "else:\n",

    "    print(\"Spotify client secret not found\")\n",

    "\n",

    "spotify_access_token = os.getenv(\"SPOTIFY_ACCESS_TOKEN\")\n",

    "spotify_refresh_token = os.getenv(\"SPOTIFY_REFRESH_TOKEN\")\n",

    "\n",

    "if spotify_access_token and spotify_refresh_token:\n",

    "    # Set expiry to past to force refresh on first use\n",

    "    spotify_token_expiry = time.time() - 60\n",

    "    print(\"Spotify tokens loaded from environment!\")\n",

    "    print(f\"Access token preview: {spotify_access_token[:20]}...\")\n",

    "    print(f\"Refresh token preview: {spotify_refresh_token[:20]}...\")\n",

    "else:\n",

    "    print(\"No Spotify tokens found in environment. Run spotify_flask_auth.py to get them.\")"

   ]

  },

  {

   "cell_type": "code",

   "execution_count": 30,

   "metadata": {},

   "outputs": [],

   "source": [

    "def get_spotify_access_token():\n",

    "    global spotify_access_token, spotify_refresh_token, spotify_token_expiry\n",

    "    \n",

    "    # Check if we have a valid cached token\n",

    "    if spotify_access_token and time.time() < spotify_token_expiry:\n",

    "        return spotify_access_token\n",

    "    \n",

    "\n",

    "    auth_url = \"https://accounts.spotify.com/api/token\"\n",

    "    \n",

    "    credentials = f\"{spotify_client_id}:{spotify_client_secret}\"\n",

    "    encoded_credentials = base64.b64encode(credentials.encode()).decode()\n",

    "    \n",

    "    headers = {\n",

    "        \"Authorization\": f\"Basic {encoded_credentials}\",\n",

    "        \"Content-Type\": \"application/x-www-form-urlencoded\"\n",

    "    }\n",

    "    \n",

    "    data = {\n",

    "        \"grant_type\": \"refresh_token\",\n",

    "        \"refresh_token\": spotify_refresh_token\n",

    "    }\n",

    "    \n",

    "    response = requests.post(auth_url, headers=headers, data=data)\n",

    "    \n",

    "    if response.status_code == 200:\n",

    "        token_data = response.json()\n",

    "        spotify_access_token = token_data[\"access_token\"]\n",

    "        # Update refresh token if a new one is provided\n",

    "        if \"refresh_token\" in token_data:\n",

    "            spotify_refresh_token = token_data[\"refresh_token\"]\n",

    "        # Set expiry time with a buffer\n",

    "        spotify_token_expiry = time.time() + token_data[\"expires_in\"] - 300\n",

    "        return spotify_access_token\n",

    "    else:\n",

    "        print(f\"Failed to refresh Spotify access token: {response.status_code}\")\n",

    "        print(f\"Response: {response.text}\")\n",

    "        return None\n"

   ]

  },

  {

   "cell_type": "code",

   "execution_count": 31,

   "metadata": {},

   "outputs": [],

   "source": [

    "def get_user_top_items(item_type=\"artists\", time_range=\"medium_term\", limit=10):\n",

    "    \"\"\"\n",

    "    Get the user's top artists or tracks from Spotify.\n",

    "    \n",

    "    Args:\n",

    "        item_type: 'artists' or 'tracks'\n",

    "        time_range: 'short_term' (4 weeks), 'medium_term' (6 months), 'long_term' (several years)\n",

    "        limit: Number of items to return (1-50)\n",

    "    \n",

    "    Returns:\n",

    "        Dictionary with top items data\n",

    "    \"\"\"\n",
    "    token = get_spotify_access_token()\n",
    "    if not token:\n",
    "        return {\"error\": \"Failed to get Spotify access token\"}\n",
    "    \n",
    "    # Make API request\n",
    "    url = f\"https://api.spotify.com/v1/me/top/{item_type}\"\n",
    "    headers = {\n",
    "        \"Authorization\": f\"Bearer {token}\"\n",
    "    }\n",
    "    params = {\n",
    "        \"time_range\": time_range,\n",
    "        \"limit\": limit\n",
    "    }\n",
    "    \n",
    "    response = requests.get(url, headers=headers, params=params)\n",
    "    \n",
    "    if response.status_code == 200:\n",
    "        data = response.json()\n",
    "        \n",
    "        formatted_items = []\n",
    "        for idx, item in enumerate(data.get(\"items\", []), 1):\n",
    "            if item_type == \"artists\":\n",
    "                formatted_items.append({\n",
    "                    \"rank\": idx,\n",
    "                    \"name\": item[\"name\"],\n",
    "                    \"genres\": item.get(\"genres\", []),\n",
    "                    \"popularity\": item.get(\"popularity\", 0),\n",
    "                    \"spotify_url\": item[\"external_urls\"][\"spotify\"]\n",
    "                })\n",
    "            else:  # tracks\n",
    "                formatted_items.append({\n",
    "                    \"rank\": idx,\n",
    "                    \"name\": item[\"name\"],\n",
    "                    \"artist\": item[\"artists\"][0][\"name\"] if item.get(\"artists\") else \"Unknown\",\n",
    "                    \"album\": item[\"album\"][\"name\"] if item.get(\"album\") else \"Unknown\",\n",
    "                    \"popularity\": item.get(\"popularity\", 0),\n",
    "                    \"spotify_url\": item[\"external_urls\"][\"spotify\"]\n",
    "                })\n",
    "        \n",
    "        return {\n",
    "            \"item_type\": item_type,\n",
    "            \"time_range\": time_range,\n",
    "            \"count\": len(formatted_items),\n",
    "            \"items\": formatted_items\n",
    "        }\n",
    "    else:\n",
    "        return {\"error\": f\"Failed to get top items: {response.status_code} - {response.text}\"}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# lets test the tool\n",
    "get_user_top_items(item_type=\"artists\", time_range=\"medium_term\", limit=3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [],
   "source": [
    "record_user_details_json = {\n",
    "    \"name\": \"record_user_details\",\n",
    "    \"description\": \"Use this tool to record that a user is interested in being in touch and provided an email address\",\n",
    "    \"parameters\": {\n",
    "        \"type\": \"object\",\n",
    "        \"properties\": {\n",
    "            \"email\": {\n",
    "                \"type\": \"string\",\n",
    "                \"description\": \"The email address of this user\"\n",
    "            },\n",
    "            \"name\": {\n",
    "                \"type\": \"string\",\n",
    "                \"description\": \"The user's name, if they provided it\"\n",

    "            }\n",

    "            ,\n",

    "            \"notes\": {\n",

    "                \"type\": \"string\",\n",

    "                \"description\": \"Any additional information about the conversation that's worth recording to give context\"\n",
    "            }\n",
    "        },\n",
    "        \"required\": [\"email\"],\n",
    "        \"additionalProperties\": False\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [],
   "source": [
    "get_user_top_items_json = {\n",
    "    \"name\": \"get_user_top_items\",\n",
    "    \"description\": \"Get the user's top artists or tracks from Spotify based on their listening history\",\n",

    "    \"parameters\": {\n",

    "        \"type\": \"object\",\n",

    "        \"properties\": {\n",

    "            \"item_type\": {\n",

    "                \"type\": \"string\",\n",

    "                \"description\": \"Type of items to retrieve: 'artists' or 'tracks'\",\n",

    "                \"enum\": [\"artists\", \"tracks\"]\n",

    "            },\n",

    "            \"time_range\": {\n",

    "                \"type\": \"string\", \n",

    "                \"description\": \"Time range for the data: 'short_term' (4 weeks), 'medium_term' (6 months), or 'long_term' (several years)\",\n",

    "                \"enum\": [\"short_term\", \"medium_term\", \"long_term\"]\n",

    "            },\n",

    "            \"limit\": {\n",

    "                \"type\": \"integer\",\n",

    "                \"description\": \"Number of items to return (1-50)\",\n",

    "                \"minimum\": 1,\n",

    "                \"maximum\": 50\n",

    "            }\n",

    "        },\n",

    "        \"required\": [\"item_type\", \"time_range\", \"limit\"],\n",

    "        \"additionalProperties\": False\n",

    "    }\n",

    "}"

   ]

  },

  {

   "cell_type": "code",

   "execution_count": 35,

   "metadata": {},

   "outputs": [],

   "source": [

    "record_unknown_question_json = {\n",

    "    \"name\": \"record_unknown_question\",\n",

    "    \"description\": \"Always use this tool to record any question that couldn't be answered as you didn't know the answer\",\n",

    "    \"parameters\": {\n",

    "        \"type\": \"object\",\n",

    "        \"properties\": {\n",

    "            \"question\": {\n",

    "                \"type\": \"string\",\n",

    "                \"description\": \"The question that couldn't be answered\"\n",
    "            },\n",
    "        },\n",
    "        \"required\": [\"question\"],\n",
    "        \"additionalProperties\": False\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [],
   "source": [
    "tools = [{\"type\": \"function\", \"function\": record_user_details_json},\n",
    "        {\"type\": \"function\", \"function\": record_unknown_question_json},\n",
    "        {\"type\": \"function\", \"function\": get_user_top_items_json}]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [],
   "source": [
    "# This function can take a list of tool calls, and run them. This is the IF statement!!\n",
    "\n",
    "def handle_tool_calls(tool_calls):\n",
    "    results = []\n",
    "    for tool_call in tool_calls:\n",
    "        tool_name = tool_call.function.name\n",
    "        arguments = json.loads(tool_call.function.arguments)\n",
    "        print(f\"Tool called: {tool_name}\", flush=True)\n",
    "\n",
    "        # THE BIG IF STATEMENT!!!\n",
    "\n",
    "        if tool_name == \"record_user_details\":\n",
    "            result = record_user_details(**arguments)\n",
    "        elif tool_name == \"record_unknown_question\":\n",
    "            result = record_unknown_question(**arguments)\n",
    "        elif tool_name == \"get_user_top_items\":\n",
    "            result = get_user_top_items(**arguments)\n",
    "\n",
    "        results.append({\"role\": \"tool\",\"content\": json.dumps(result),\"tool_call_id\": tool_call.id})\n",
    "    return results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "globals()[\"record_unknown_question\"](\"this is a really hard question\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [],
   "source": [
    "# This is a more elegant way that avoids the IF statement.\n",
    "\n",
    "def handle_tool_calls(tool_calls):\n",
    "    results = []\n",
    "    for tool_call in tool_calls:\n",
    "        tool_name = tool_call.function.name\n",
    "        arguments = json.loads(tool_call.function.arguments)\n",
    "        print(f\"Tool called: {tool_name}\", flush=True)\n",
    "        tool = globals().get(tool_name)\n",
    "        result = tool(**arguments) if tool else {}\n",
    "        results.append({\"role\": \"tool\",\"content\": json.dumps(result),\"tool_call_id\": tool_call.id})\n",
    "    return results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [],
   "source": [
    "reader = PdfReader(\"me/linkedin.pdf\")\n",
    "linkedin = \"\"\n",
    "for page in reader.pages:\n",
    "    text = page.extract_text()\n",
    "    if text:\n",
    "        linkedin += text\n",
    "\n",
    "with open(\"me/summary.txt\", \"r\", encoding=\"utf-8\") as f:\n",
    "    summary = f.read()\n",
    "\n",
    "name = \"Ed Donner\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [],
   "source": [
    "# We've added a \"If they ask you about your tastes in music you can use your get_user_top_items tool...\" \n",
    "\n",
    "system_prompt = f\"You are acting as {name}. You are answering questions on {name}'s website, \\\n",

    "particularly questions related to {name}'s career, background, skills and experience. \\\n",

    "Your responsibility is to represent {name} for interactions on the website as faithfully as possible. \\\n",

    "You are given a summary of {name}'s background and LinkedIn profile which you can use to answer questions. \\\n",

    "Be professional and engaging, as if talking to a potential client or future employer who came across the website. \\\n",

    "If they ask you about your tastes in music you can use your get_user_top_items tool to get information about your top artists and tracks. \\\n",

    "If you don't know the answer to any question, use your record_unknown_question tool to record the question that you couldn't answer, even if it's about something trivial or unrelated to career. \\\n",

    "If the user is engaging in discussion, try to steer them towards getting in touch via email; ask for their email and record it using your record_user_details tool. \"\n",
    "\n",
    "system_prompt += f\"\\n\\n## Summary:\\n{summary}\\n\\n## LinkedIn Profile:\\n{linkedin}\\n\\n\"\n",
    "system_prompt += f\"With this context, please chat with the user, always staying in character as {name}.\"\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [],
   "source": [
    "def chat(message, history):\n",
    "    messages = [{\"role\": \"system\", \"content\": system_prompt}] + history + [{\"role\": \"user\", \"content\": message}]\n",
    "    done = False\n",
    "    while not done:\n",
    "\n",
    "        # This is the call to the LLM - see that we pass in the tools json\n",
    "\n",
    "        response = openai.chat.completions.create(model=\"gpt-4o-mini\", messages=messages, tools=tools)\n",
    "\n",
    "        finish_reason = response.choices[0].finish_reason\n",
    "        \n",
    "        # If the LLM wants to call a tool, we do that!\n",
    "         \n",
    "        if finish_reason==\"tool_calls\":\n",
    "            message = response.choices[0].message\n",
    "            tool_calls = message.tool_calls\n",
    "            results = handle_tool_calls(tool_calls)\n",
    "            messages.append(message)\n",
    "            messages.extend(results)\n",
    "        else:\n",
    "            done = True\n",
    "    return response.choices[0].message.content"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gr.ChatInterface(chat, type=\"messages\").launch()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## And now for deployment\n",
    "\n",
    "This code is in `app.py`\n",
    "\n",
    "We will deploy to HuggingFace Spaces.\n",
    "\n",
    "Before you start: remember to update the files in the \"me\" directory - your LinkedIn profile and summary.txt - so that it talks about you! Also change `self.name = \"Ed Donner\"` in `app.py`..  \n",
    "\n",
    "Also check that there's no README file within the 1_foundations directory. If there is one, please delete it. The deploy process creates a new README file in this directory for you.\n",
    "\n",
    "1. Visit https://huggingface.co and set up an account  \n",
    "2. From the Avatar menu on the top right, choose Access Tokens. Choose \"Create New Token\". Give it WRITE permissions - it needs to have WRITE permissions! Keep a record of your new key.  \n",
    "3. In the Terminal, run: `uv tool install 'huggingface_hub[cli]'` to install the HuggingFace tool, then `hf auth login` to login at the command line with your key. Afterwards, run `hf auth whoami` to check you're logged in  \n",
    "4. Take your new token and add it to your .env file: `HF_TOKEN=hf_xxx` for the future\n",
    "5. From the 1_foundations folder, enter: `uv run gradio deploy` \n",
    "6. Follow its instructions: name it \"career_conversation\", specify app.py, choose cpu-basic as the hardware, say Yes to needing to supply secrets, provide your openai api key, your pushover user and token, and say \"no\" to github actions.  \n",
    "\n",
    "Thank you Robert, James, Martins, Andras and Priya for these tips.  \n",
    "Please read the next 2 sections - how to change your Secrets, and how to redeploy your Space (you may need to delete the README.md that gets created in this 1_foundations directory).\n",
    "\n",
    "#### More about these secrets:\n",
    "\n",
    "If you're confused by what's going on with these secrets: it just wants you to enter the key name and value for each of your secrets -- so you would enter:  \n",
    "`OPENAI_API_KEY`  \n",
    "Followed by:  \n",
    "`sk-proj-...`  \n",
    "\n",
    "And if you don't want to set secrets this way, or something goes wrong with it, it's no problem - you can change your secrets later:  \n",
    "1. Log in to HuggingFace website  \n",
    "2. Go to your profile screen via the Avatar menu on the top right  \n",
    "3. Select the Space you deployed  \n",
    "4. Click on the Settings wheel on the top right  \n",
    "5. You can scroll down to change your secrets (Variables and Secrets section), delete the space, etc.\n",
    "\n",
    "#### And now you should be deployed!\n",
    "\n",
    "If you want to completely replace everything and start again with your keys, you may need to delete the README.md that got created in this 1_foundations folder.\n",
    "\n",
    "Here is mine: https://huggingface.co/spaces/ed-donner/Career_Conversation\n",
    "\n",
    "I just got a push notification that a student asked me how they can become President of their country πŸ˜‚πŸ˜‚\n",
    "\n",
    "For more information on deployment:\n",
    "\n",
    "https://www.gradio.app/guides/sharing-your-app#hosting-on-hf-spaces\n",
    "\n",
    "To delete your Space in the future:  \n",
    "1. Log in to HuggingFace\n",
    "2. From the Avatar menu, select your profile\n",
    "3. Click on the Space itself and select the settings wheel on the top right\n",
    "4. Scroll to the Delete section at the bottom\n",
    "5. ALSO: delete the README file that Gradio may have created inside this 1_foundations folder (otherwise it won't ask you the questions the next time you do a gradio deploy)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Spotify API Setup Instructions\n",
    "\n",
    "To use the Spotify tool in this notebook, you need will need to undergo a one-time setup process to obtain access and refresh tokens from Spotify.  This involve the following steps:\n",
    "\n",
    "1. **Create a Spotify App**:\n",
    "   - Go to https://developer.spotify.com/dashboard\n",
    "   - Click \"Create app\"\n",
    "   - Fill in the app details\n",
    "   - Set Redirect URI to: `https://your-username-your-space-name.hf.space/callback` (replace with your actual HuggingFace Space URL)\n",
    "   - Save your Client ID and Client Secret\n",
    "\n",
    "2. **Add to your `.env` file**:\n",
    "   ```\n",
    "   SPOTIFY_CLIENT_ID=your_client_id_here\n",
    "   SPOTIFY_CLIENT_SECRET=your_client_secret_here\n",
    "   ```\n",
    "\n",
    "3. **Deploy and authenticate**:\n",
    "   - Deploy the authentication app from the **Flask Authentication App for Spotify** cell below to HuggingFace Spaces\n",
    "   - Visit your deployed app and click \"Authorize with Spotify\"\n",
    "   - After authorizing, copy the tokens displayed\n",
    "   - ONCE YOU HAVE HAVE OBTAINED YOUR ACCESS AND REFRESH TOKESNS YOU CAN DELETE THIS DEPLOYMENT\n",
    "\n",
    "4. **Add tokens to .env and reload**:\n",
    "   ```\n",
    "   SPOTIFY_ACCESS_TOKEN=your_access_token\n",
    "   SPOTIFY_REFRESH_TOKEN=your_refresh_token\n",
    "   ```\n",
    "   Then run `load_dotenv(override=True)`\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Flask Authentication App for Spotify\n",
    "\n",
    "Deploy this code as `spotify_flask_auth.py` to HuggingFace Spaces using Gradio following the steps as above fro\n",
    "app.py.  You need the following:\n",
    "1. SPOTIFY_CLIENT_ID and SPOTIFY_CLIENT_SECRET defined in your environment\n",
    "2. Need a requirements.txt with Flask listed as a dependency (no other dependencies are needed)\n",
    "\n",
    "```python\n",
    "from flask import Flask, request, redirect, render_template_string\n",
    "import requests\n",
    "import base64\n",
    "import os\n",
    "from dotenv import load_dotenv\n",
    "import urllib.parse\n",
    "import secrets\n",
    "import string\n",
    "\n",
    "load_dotenv(override=True)\n",
    "\n",
    "app = Flask(__name__)\n",
    "app.secret_key = ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(32))\n",
    "\n",
    "CLIENT_ID = os.getenv(\"SPOTIFY_CLIENT_ID\")\n",
    "CLIENT_SECRET = os.getenv(\"SPOTIFY_CLIENT_SECRET\")\n",
    "\n",
    "REDIRECT_URI = f\"https://{os.getenv('SPACE_HOST')}/callback\"\n",
    "SCOPE = \"user-top-read\"\n",
    "tokens = {}\n",
    "\n",
    "# HTML template for the home page\n",
    "HOME_TEMPLATE = \"\"\"\n",

    "<!DOCTYPE html>\n",

    "<html>\n",

    "<head>\n",

    "    <title>Spotify OAuth Helper</title>\n",

    "</head>\n",

    "<body>\n",

    "    {% if has_credentials %}\n",

    "        <div style=\"margin-bottom: 20px;\">\n",

    "            <p>Make sure to add this redirect URI to your Spotify app settings:</p>\n",

    "            <code>{{ redirect_uri }}</code>\n",

    "        </div>\n",

    "        <button onclick=\"window.open('https://accounts.spotify.com/authorize?client_id={{ client_id }}&response_type=code&redirect_uri={{ redirect_uri | urlencode }}&scope={{ scope | urlencode }}&show_dialog=true', '_blank')\">Authorize with Spotify</button>\n",

    "    {% else %}\n",

    "        <div>Missing Spotify credentials in .env file</div>\n",

    "    {% endif %}\n",

    "</body>\n",

    "</html>\n",

    "\"\"\"\n",
    "\n",
    "SUCCESS_TEMPLATE = \"\"\"\n",

    "<!DOCTYPE html>\n",

    "<html>\n",

    "<head>\n",

    "    <title>Spotify OAuth - Success!</title>\n",

    "</head>\n",

    "<body>\n",

    "    <p>Authorization Complete</p>\n",

    "    <h3>Add to your .env file:</h3>\n",

    "    <pre>SPOTIFY_ACCESS_TOKEN={{ access_token }}\n",

    "SPOTIFY_REFRESH_TOKEN={{ refresh_token }}</pre>\n",

    "</body>\n",

    "</html>\n",

    "\"\"\"\n",
    "\n",
    "@app.route('/')\n",
    "def home():\n",
    "    error = request.args.get('error')\n",
    "    has_credentials = CLIENT_ID and CLIENT_SECRET\n",
    "    return render_template_string(HOME_TEMPLATE, error=error, has_credentials=has_credentials, redirect_uri=REDIRECT_URI, client_id=CLIENT_ID, scope=SCOPE)\n",
    "\n",
    "@app.route('/authorize')\n",
    "def authorize():\n",
    "    \"\"\"Redirect to Spotify authorization\"\"\"\n",
    "    if not CLIENT_ID:\n",
    "        return redirect('/?error=Missing SPOTIFY_CLIENT_ID')\n",
    "    \n",
    "    auth_url = \"https://accounts.spotify.com/authorize\"\n",
    "    params = {\n",
    "        \"client_id\": CLIENT_ID,\n",
    "        \"response_type\": \"code\",\n",
    "        \"redirect_uri\": REDIRECT_URI,\n",
    "        \"scope\": SCOPE,\n",
    "        \"show_dialog\": \"true\"\n",
    "    }\n",
    "    \n",
    "    url = f\"{auth_url}?{urllib.parse.urlencode(params)}\"\n",
    "    return redirect(url)\n",
    "\n",
    "@app.route('/callback')\n",
    "def callback():\n",
    "    \"\"\"Handle the OAuth callback\"\"\"\n",
    "    error = request.args.get('error')\n",
    "    if error:\n",
    "        return redirect(f'/?error=Authorization failed: {error}')\n",
    "    \n",
    "    code = request.args.get('code')\n",
    "    if not code:\n",
    "        return redirect('/?error=No authorization code received')\n",
    "    \n",
    "    # Exchange code for tokens\n",
    "    token_url = \"https://accounts.spotify.com/api/token\"\n",
    "    \n",
    "    credentials = f\"{CLIENT_ID}:{CLIENT_SECRET}\"\n",
    "    encoded_credentials = base64.b64encode(credentials.encode()).decode()\n",
    "    \n",
    "    headers = {\n",
    "        \"Authorization\": f\"Basic {encoded_credentials}\",\n",
    "        \"Content-Type\": \"application/x-www-form-urlencoded\"\n",
    "    }\n",
    "    \n",
    "    data = {\n",
    "        \"grant_type\": \"authorization_code\",\n",
    "        \"code\": code,\n",
    "        \"redirect_uri\": REDIRECT_URI\n",
    "    }\n",
    "    \n",
    "    response = requests.post(token_url, headers=headers, data=data)\n",
    "    \n",
    "    if response.status_code == 200:\n",
    "        token_data = response.json()\n",
    "        tokens['access_token'] = token_data['access_token']\n",
    "        tokens['refresh_token'] = token_data['refresh_token']\n",
    "        \n",
    "        return render_template_string(\n",
    "            SUCCESS_TEMPLATE,\n",
    "            access_token=token_data['access_token'],\n",
    "            refresh_token=token_data['refresh_token']\n",
    "        )\n",
    "    else:\n",
    "        error_msg = response.json().get('error_description', 'Unknown error')\n",
    "        return redirect(f'/?error=Token exchange failed: {error_msg}')\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    app.run(host='0.0.0.0', port=7860)\n",
    "```\n",
    "\n",
    "**Deployment Instructions:**\n",
    "1. You will need to provide `SPOTIFY_CLIENT_ID` and `SPOTIFY_CLIENT_SECRET` as secrets in HuggingFace Spaces\n",
    "2. Create a `requirements.txt` file with a single entry: `Flask`\n",
    "3. Deploy to HuggingFace Spaces using the instructions in the deployment section below"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<table style=\"margin: 0; text-align: left; width:100%\">\n",
    "    <tr>\n",
    "        <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n",
    "            <img src=\"../assets/business.png\" width=\"150\" height=\"150\" style=\"display: block;\" />\n",
    "        </td>\n",
    "        <td>\n",
    "            <h2 style=\"color:#00bfff;\">Commercial implications</h2>\n",
    "            <span style=\"color:#00bfff;\">Aside from the obvious (your career alter-ego) this has business applications in any situation where you need an AI assistant with domain expertise and an ability to interact with the real world.\n",
    "            </span>\n",
    "        </td>\n",
    "    </tr>\n",
    "</table>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "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.12.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}