File size: 50,369 Bytes
eb87615
 
f7a1a4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb87615
 
f7a1a4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb87615
 
 
f7a1a4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb87615
 
 
f7a1a4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb87615
 
 
 
f7a1a4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb87615
 
 
 
f7a1a4f
 
eb87615
 
 
f7a1a4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb87615
 
 
f7a1a4f
 
 
 
 
 
 
 
 
 
 
eb87615
f7a1a4f
 
 
 
 
eb87615
 
 
 
f7a1a4f
 
eb87615
f7a1a4f
 
 
 
 
 
 
 
 
 
 
 
 
eb87615
f7a1a4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb87615
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d312255a",
   "metadata": {},
   "source": [
    " Project Structure\n",
    "\n",
    "    tools.py – Provides auxiliary tools for the agent.\n",
    "    retriever.py – Implements retrieval functions to support knowledge access.\n",
    "    app.py – Integrates all components into a fully functional agent, which we’ll finalize in the last part of this unit."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fbbeaeb4",
   "metadata": {},
   "source": [
    "### Building the Guestbook Tool"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5cd54389",
   "metadata": {},
   "source": [
    "Step 1: Load and Prepare the Dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "a36bf5b5",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core.schema import Document\n",
    "import pandas as pd\n",
    "#from huggingface_hub import hf_hub_download"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "62d4fbf9",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load the dataset\n",
    "#guest_dataset = datasets.load_dataset(\"agents-course/unit3-invitees\", split=\"train\")\n",
    "guest_dataset = pd.read_parquet(\"/home/cairo/code/alfred-agent-rag/data/train-00000-of-00001.parquet\")\n",
    "\n",
    "# Convert dataset entries into Document objects\n",
    "docs = [\n",
    "    Document(\n",
    "        text=\"\\n\".join([\n",
    "            f\"Name: {guest_dataset['name'][i]}\",\n",
    "            f\"Relation: {guest_dataset['relation'][i]}\",\n",
    "            f\"Description: {guest_dataset['description'][i]}\",\n",
    "            f\"Email: {guest_dataset['email'][i]}\"\n",
    "        ]),\n",
    "        metadata={\"name\": guest_dataset['name'][i]}\n",
    "    )\n",
    "    for i in range(len(guest_dataset))\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "5e94a1f5",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.microsoft.datawrangler.viewer.v0+json": {
       "columns": [
        {
         "name": "index",
         "rawType": "int64",
         "type": "integer"
        },
        {
         "name": "name",
         "rawType": "object",
         "type": "string"
        },
        {
         "name": "relation",
         "rawType": "object",
         "type": "string"
        },
        {
         "name": "description",
         "rawType": "object",
         "type": "string"
        },
        {
         "name": "email",
         "rawType": "object",
         "type": "string"
        }
       ],
       "conversionMethod": "pd.DataFrame",
       "ref": "5b022186-8682-4d89-87c4-204710defe6d",
       "rows": [
        [
         "0",
         "Ada Lovelace",
         "best friend",
         "Lady Ada Lovelace is my best friend. She is an esteemed mathematician and friend. She is renowned for her pioneering work in mathematics and computing, often celebrated as the first computer programmer due to her work on Charles Babbage's Analytical Engine.",
         "ada.lovelace@example.com"
        ],
        [
         "1",
         "Dr. Nikola Tesla",
         "old friend from university days",
         "Dr. Nikola Tesla is an old friend from your university days. He's recently patented a new wireless energy transmission system and would be delighted to discuss it with you. Just remember he's passionate about pigeons, so that might make for good small talk.",
         "nikola.tesla@gmail.com"
        ],
        [
         "2",
         "Marie Curie",
         "no relation",
         "Marie Curie was a groundbreaking physicist and chemist, famous for her research on radioactivity.",
         "marie.curie@example.com"
        ]
       ],
       "shape": {
        "columns": 4,
        "rows": 3
       }
      },
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>name</th>\n",
       "      <th>relation</th>\n",
       "      <th>description</th>\n",
       "      <th>email</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Ada Lovelace</td>\n",
       "      <td>best friend</td>\n",
       "      <td>Lady Ada Lovelace is my best friend. She is an...</td>\n",
       "      <td>ada.lovelace@example.com</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Dr. Nikola Tesla</td>\n",
       "      <td>old friend from university days</td>\n",
       "      <td>Dr. Nikola Tesla is an old friend from your un...</td>\n",
       "      <td>nikola.tesla@gmail.com</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Marie Curie</td>\n",
       "      <td>no relation</td>\n",
       "      <td>Marie Curie was a groundbreaking physicist and...</td>\n",
       "      <td>marie.curie@example.com</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "               name                         relation  \\\n",
       "0      Ada Lovelace                      best friend   \n",
       "1  Dr. Nikola Tesla  old friend from university days   \n",
       "2       Marie Curie                      no relation   \n",
       "\n",
       "                                         description                     email  \n",
       "0  Lady Ada Lovelace is my best friend. She is an...  ada.lovelace@example.com  \n",
       "1  Dr. Nikola Tesla is an old friend from your un...    nikola.tesla@gmail.com  \n",
       "2  Marie Curie was a groundbreaking physicist and...   marie.curie@example.com  "
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "guest_dataset"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3354008a",
   "metadata": {},
   "source": [
    "Step 2: Create the Retriever Tool\n",
    "\n",
    "Now, let’s create a custom tool that Alfred can use to search through our guest information."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "25f03ac1",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core.tools import FunctionTool\n",
    "from llama_index.retrievers.bm25 import BM25Retriever\n",
    "\n",
    "bm25_retriever = BM25Retriever.from_defaults(nodes=docs)\n",
    "\n",
    "def get_guest_info_retriever(query: str) -> str:\n",
    "    \"\"\"Retrieves detailed information about gala guests based on their name or relation.\"\"\"\n",
    "    results = bm25_retriever.retrieve(query)\n",
    "    if results:\n",
    "        return \"\\n\\n\".join([doc.text for doc in results[:3]])\n",
    "    else:\n",
    "        return \"No matching guest information found.\"\n",
    "\n",
    "# Initialize the tool\n",
    "guest_info_tool = FunctionTool.from_defaults(get_guest_info_retriever)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5df9b39b",
   "metadata": {},
   "source": [
    "Let’s understand this tool step-by-step.\n",
    "\n",
    "- The docstring helps the agent understand when and how to use this tool\n",
    "- The type decorators define what parameters the tool expects (in this case, a search query)\n",
    "- We’re using a BM25Retriever, which is a powerful text retrieval algorithm that doesn’t require embeddings\n",
    "- The method processes the query and returns the most relevant guest information"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "37217aaf",
   "metadata": {},
   "source": [
    "Step 3: Integrate the Tool with Alfred"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "4a52e554",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "97f624e7ef9b4b0fb132bf0bce536477",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "VBox(children=(HTML(value='<center> <img\\nsrc=https://huggingface.co/front/assets/huggingface_logo-noborder.sv…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from huggingface_hub import login\n",
    "\n",
    "login()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "d1258afc",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Exception in callback Dispatcher.span.<locals>.wrapper.<locals>.handle_future_result(span_id='Workflow.run...-e3cd19dfc9c6', bound_args=<BoundArgumen...mory': None})>, instance=<llama_index....x76ae1634edb0>, context=<_contextvars...x76ae168519c0>)(<WorkflowHand...ompletions'\")>) at /home/cairo/anaconda3/lib/python3.12/site-packages/llama_index/core/instrumentation/dispatcher.py:274\n",
      "handle: <Handle Dispatcher.span.<locals>.wrapper.<locals>.handle_future_result(span_id='Workflow.run...-e3cd19dfc9c6', bound_args=<BoundArgumen...mory': None})>, instance=<llama_index....x76ae1634edb0>, context=<_contextvars...x76ae168519c0>)(<WorkflowHand...ompletions'\")>) at /home/cairo/anaconda3/lib/python3.12/site-packages/llama_index/core/instrumentation/dispatcher.py:274>\n",
      "Traceback (most recent call last):\n",
      "  File \"/home/cairo/anaconda3/lib/python3.12/site-packages/llama_index/core/workflow/context.py\", line 583, in _step_worker\n",
      "    new_ev = await instrumented_step(**kwargs)\n",
      "             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
      "  File \"/home/cairo/anaconda3/lib/python3.12/site-packages/llama_index/core/instrumentation/dispatcher.py\", line 368, in async_wrapper\n",
      "    result = await func(*args, **kwargs)\n",
      "             ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
      "  File \"/home/cairo/anaconda3/lib/python3.12/site-packages/llama_index/core/agent/workflow/multi_agent_workflow.py\", line 382, in run_agent_step\n",
      "    agent_output = await agent.take_step(\n",
      "                   ^^^^^^^^^^^^^^^^^^^^^^\n",
      "  File \"/home/cairo/anaconda3/lib/python3.12/site-packages/llama_index/core/agent/workflow/react_agent.py\", line 101, in take_step\n",
      "    async for last_chat_response in response:\n",
      "  File \"/home/cairo/anaconda3/lib/python3.12/site-packages/llama_index/llms/huggingface_api/base.py\", line 429, in gen\n",
      "    async for chunk in await self._async_client.chat_completion(\n",
      "                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
      "  File \"/home/cairo/anaconda3/lib/python3.12/site-packages/huggingface_hub/inference/_generated/_async_client.py\", line 1032, in chat_completion\n",
      "    data = await self._inner_post(request_parameters, stream=stream)\n",
      "           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
      "  File \"/home/cairo/anaconda3/lib/python3.12/site-packages/huggingface_hub/inference/_generated/_async_client.py\", line 367, in _inner_post\n",
      "    raise error\n",
      "  File \"/home/cairo/anaconda3/lib/python3.12/site-packages/huggingface_hub/inference/_generated/_async_client.py\", line 353, in _inner_post\n",
      "    response.raise_for_status()\n",
      "  File \"/home/cairo/anaconda3/lib/python3.12/site-packages/aiohttp/client_reqrep.py\", line 1093, in raise_for_status\n",
      "    raise ClientResponseError(\n",
      "aiohttp.client_exceptions.ClientResponseError: 402, message='Payment Required', url='https://router.huggingface.co/hf-inference/models/Qwen/Qwen2.5-Coder-32B-Instruct/v1/chat/completions'\n",
      "\n",
      "The above exception was the direct cause of the following exception:\n",
      "\n",
      "Traceback (most recent call last):\n",
      "  File \"/home/cairo/anaconda3/lib/python3.12/asyncio/events.py\", line 88, in _run\n",
      "    self._context.run(self._callback, *self._args)\n",
      "  File \"/home/cairo/anaconda3/lib/python3.12/site-packages/llama_index/core/instrumentation/dispatcher.py\", line 286, in handle_future_result\n",
      "    raise exception\n",
      "  File \"/home/cairo/anaconda3/lib/python3.12/site-packages/llama_index/core/workflow/workflow.py\", line 394, in _run_workflow\n",
      "    raise exception_raised\n",
      "  File \"/home/cairo/anaconda3/lib/python3.12/site-packages/llama_index/core/workflow/context.py\", line 592, in _step_worker\n",
      "    raise WorkflowRuntimeError(\n",
      "llama_index.core.workflow.errors.WorkflowRuntimeError: Error in step 'run_agent_step': 402, message='Payment Required', url='https://router.huggingface.co/hf-inference/models/Qwen/Qwen2.5-Coder-32B-Instruct/v1/chat/completions'\n"
     ]
    },
    {
     "ename": "WorkflowRuntimeError",
     "evalue": "Error in step 'run_agent_step': 402, message='Payment Required', url='https://router.huggingface.co/hf-inference/models/Qwen/Qwen2.5-Coder-32B-Instruct/v1/chat/completions'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mClientResponseError\u001b[0m                       Traceback (most recent call last)",
      "File \u001b[0;32m~/anaconda3/lib/python3.12/site-packages/llama_index/core/workflow/context.py:583\u001b[0m, in \u001b[0;36mContext._step_worker\u001b[0;34m(self, name, step, config, stepwise, verbose, checkpoint_callback, run_id, service_manager, dispatcher)\u001b[0m\n\u001b[1;32m    582\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[0;32m--> 583\u001b[0m     new_ev \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mawait\u001b[39;00m instrumented_step(\u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs)\n\u001b[1;32m    584\u001b[0m     kwargs\u001b[38;5;241m.\u001b[39mclear()\n",
      "File \u001b[0;32m~/anaconda3/lib/python3.12/site-packages/llama_index/core/instrumentation/dispatcher.py:368\u001b[0m, in \u001b[0;36mDispatcher.span.<locals>.async_wrapper\u001b[0;34m(func, instance, args, kwargs)\u001b[0m\n\u001b[1;32m    367\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[0;32m--> 368\u001b[0m     result \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mawait\u001b[39;00m func(\u001b[38;5;241m*\u001b[39margs, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs)\n\u001b[1;32m    369\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mBaseException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n",
      "File \u001b[0;32m~/anaconda3/lib/python3.12/site-packages/llama_index/core/agent/workflow/multi_agent_workflow.py:382\u001b[0m, in \u001b[0;36mAgentWorkflow.run_agent_step\u001b[0;34m(self, ctx, ev)\u001b[0m\n\u001b[1;32m    380\u001b[0m tools \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mawait\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mget_tools(ev\u001b[38;5;241m.\u001b[39mcurrent_agent_name, user_msg_str \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m--> 382\u001b[0m agent_output \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mawait\u001b[39;00m agent\u001b[38;5;241m.\u001b[39mtake_step(\n\u001b[1;32m    383\u001b[0m     ctx,\n\u001b[1;32m    384\u001b[0m     ev\u001b[38;5;241m.\u001b[39minput,\n\u001b[1;32m    385\u001b[0m     tools,\n\u001b[1;32m    386\u001b[0m     memory,\n\u001b[1;32m    387\u001b[0m )\n\u001b[1;32m    389\u001b[0m ctx\u001b[38;5;241m.\u001b[39mwrite_event_to_stream(agent_output)\n",
      "File \u001b[0;32m~/anaconda3/lib/python3.12/site-packages/llama_index/core/agent/workflow/react_agent.py:101\u001b[0m, in \u001b[0;36mReActAgent.take_step\u001b[0;34m(self, ctx, llm_input, tools, memory)\u001b[0m\n\u001b[1;32m    100\u001b[0m last_chat_response \u001b[38;5;241m=\u001b[39m ChatResponse(message\u001b[38;5;241m=\u001b[39mChatMessage())\n\u001b[0;32m--> 101\u001b[0m \u001b[38;5;28;01masync\u001b[39;00m \u001b[38;5;28;01mfor\u001b[39;00m last_chat_response \u001b[38;5;129;01min\u001b[39;00m response:\n\u001b[1;32m    102\u001b[0m     raw \u001b[38;5;241m=\u001b[39m (\n\u001b[1;32m    103\u001b[0m         last_chat_response\u001b[38;5;241m.\u001b[39mraw\u001b[38;5;241m.\u001b[39mmodel_dump()\n\u001b[1;32m    104\u001b[0m         \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(last_chat_response\u001b[38;5;241m.\u001b[39mraw, BaseModel)\n\u001b[1;32m    105\u001b[0m         \u001b[38;5;28;01melse\u001b[39;00m last_chat_response\u001b[38;5;241m.\u001b[39mraw\n\u001b[1;32m    106\u001b[0m     )\n",
      "File \u001b[0;32m~/anaconda3/lib/python3.12/site-packages/llama_index/llms/huggingface_api/base.py:429\u001b[0m, in \u001b[0;36mHuggingFaceInferenceAPI.astream_chat.<locals>.gen\u001b[0;34m()\u001b[0m\n\u001b[1;32m    428\u001b[0m cur_index \u001b[38;5;241m=\u001b[39m \u001b[38;5;241m-\u001b[39m\u001b[38;5;241m1\u001b[39m\n\u001b[0;32m--> 429\u001b[0m \u001b[38;5;28;01masync\u001b[39;00m \u001b[38;5;28;01mfor\u001b[39;00m chunk \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28;01mawait\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_async_client\u001b[38;5;241m.\u001b[39mchat_completion(\n\u001b[1;32m    430\u001b[0m     messages\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_to_huggingface_messages(messages),\n\u001b[1;32m    431\u001b[0m     stream\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mTrue\u001b[39;00m,\n\u001b[1;32m    432\u001b[0m     \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mmodel_kwargs,\n\u001b[1;32m    433\u001b[0m ):\n\u001b[1;32m    434\u001b[0m     \u001b[38;5;28;01mif\u001b[39;00m chunk\u001b[38;5;241m.\u001b[39mchoices[\u001b[38;5;241m0\u001b[39m]\u001b[38;5;241m.\u001b[39mfinish_reason \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n",
      "File \u001b[0;32m~/anaconda3/lib/python3.12/site-packages/huggingface_hub/inference/_generated/_async_client.py:1032\u001b[0m, in \u001b[0;36mAsyncInferenceClient.chat_completion\u001b[0;34m(self, messages, model, stream, frequency_penalty, logit_bias, logprobs, max_tokens, n, presence_penalty, response_format, seed, stop, stream_options, temperature, tool_choice, tool_prompt, tools, top_logprobs, top_p, extra_body)\u001b[0m\n\u001b[1;32m   1025\u001b[0m request_parameters \u001b[38;5;241m=\u001b[39m provider_helper\u001b[38;5;241m.\u001b[39mprepare_request(\n\u001b[1;32m   1026\u001b[0m     inputs\u001b[38;5;241m=\u001b[39mmessages,\n\u001b[1;32m   1027\u001b[0m     parameters\u001b[38;5;241m=\u001b[39mparameters,\n\u001b[0;32m   (...)\u001b[0m\n\u001b[1;32m   1030\u001b[0m     api_key\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mtoken,\n\u001b[1;32m   1031\u001b[0m )\n\u001b[0;32m-> 1032\u001b[0m data \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mawait\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_inner_post(request_parameters, stream\u001b[38;5;241m=\u001b[39mstream)\n\u001b[1;32m   1034\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m stream:\n",
      "File \u001b[0;32m~/anaconda3/lib/python3.12/site-packages/huggingface_hub/inference/_generated/_async_client.py:367\u001b[0m, in \u001b[0;36mAsyncInferenceClient._inner_post\u001b[0;34m(self, request_parameters, stream)\u001b[0m\n\u001b[1;32m    366\u001b[0m     \u001b[38;5;28;01mawait\u001b[39;00m session\u001b[38;5;241m.\u001b[39mclose()\n\u001b[0;32m--> 367\u001b[0m     \u001b[38;5;28;01mraise\u001b[39;00m error\n\u001b[1;32m    368\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mException\u001b[39;00m:\n",
      "File \u001b[0;32m~/anaconda3/lib/python3.12/site-packages/huggingface_hub/inference/_generated/_async_client.py:353\u001b[0m, in \u001b[0;36mAsyncInferenceClient._inner_post\u001b[0;34m(self, request_parameters, stream)\u001b[0m\n\u001b[1;32m    352\u001b[0m         \u001b[38;5;28;01mpass\u001b[39;00m\n\u001b[0;32m--> 353\u001b[0m response\u001b[38;5;241m.\u001b[39mraise_for_status()\n\u001b[1;32m    354\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m stream:\n",
      "File \u001b[0;32m~/anaconda3/lib/python3.12/site-packages/aiohttp/client_reqrep.py:1093\u001b[0m, in \u001b[0;36mClientResponse.raise_for_status\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m   1092\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mrelease()\n\u001b[0;32m-> 1093\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m ClientResponseError(\n\u001b[1;32m   1094\u001b[0m     \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mrequest_info,\n\u001b[1;32m   1095\u001b[0m     \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mhistory,\n\u001b[1;32m   1096\u001b[0m     status\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mstatus,\n\u001b[1;32m   1097\u001b[0m     message\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mreason,\n\u001b[1;32m   1098\u001b[0m     headers\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mheaders,\n\u001b[1;32m   1099\u001b[0m )\n",
      "\u001b[0;31mClientResponseError\u001b[0m: 402, message='Payment Required', url='https://router.huggingface.co/hf-inference/models/Qwen/Qwen2.5-Coder-32B-Instruct/v1/chat/completions'",
      "\nThe above exception was the direct cause of the following exception:\n",
      "\u001b[0;31mWorkflowRuntimeError\u001b[0m                      Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[15], line 14\u001b[0m\n\u001b[1;32m      8\u001b[0m alfred \u001b[38;5;241m=\u001b[39m AgentWorkflow\u001b[38;5;241m.\u001b[39mfrom_tools_or_functions(\n\u001b[1;32m      9\u001b[0m     [guest_info_tool],\n\u001b[1;32m     10\u001b[0m     llm\u001b[38;5;241m=\u001b[39mllm,\n\u001b[1;32m     11\u001b[0m )\n\u001b[1;32m     13\u001b[0m \u001b[38;5;66;03m# Example query Alfred might receive during the gala\u001b[39;00m\n\u001b[0;32m---> 14\u001b[0m response \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mawait\u001b[39;00m alfred\u001b[38;5;241m.\u001b[39mrun(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mTell me about our guest named \u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mLady Ada Lovelace\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m.\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m     16\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m🎩 Alfred\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124ms Response:\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m     17\u001b[0m \u001b[38;5;28mprint\u001b[39m(response)\n",
      "File \u001b[0;32m~/anaconda3/lib/python3.12/site-packages/llama_index/core/workflow/workflow.py:394\u001b[0m, in \u001b[0;36mWorkflow.run.<locals>._run_workflow\u001b[0;34m()\u001b[0m\n\u001b[1;32m    390\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m exception_raised:\n\u001b[1;32m    391\u001b[0m     \u001b[38;5;66;03m# cancel the stream\u001b[39;00m\n\u001b[1;32m    392\u001b[0m     ctx\u001b[38;5;241m.\u001b[39mwrite_event_to_stream(StopEvent())\n\u001b[0;32m--> 394\u001b[0m     \u001b[38;5;28;01mraise\u001b[39;00m exception_raised\n\u001b[1;32m    396\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m we_done:\n\u001b[1;32m    397\u001b[0m     \u001b[38;5;66;03m# cancel the stream\u001b[39;00m\n\u001b[1;32m    398\u001b[0m     ctx\u001b[38;5;241m.\u001b[39mwrite_event_to_stream(StopEvent())\n",
      "File \u001b[0;32m~/anaconda3/lib/python3.12/site-packages/llama_index/core/workflow/context.py:592\u001b[0m, in \u001b[0;36mContext._step_worker\u001b[0;34m(self, name, step, config, stepwise, verbose, checkpoint_callback, run_id, service_manager, dispatcher)\u001b[0m\n\u001b[1;32m    590\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[1;32m    591\u001b[0m     \u001b[38;5;28;01mif\u001b[39;00m config\u001b[38;5;241m.\u001b[39mretry_policy \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[0;32m--> 592\u001b[0m         \u001b[38;5;28;01mraise\u001b[39;00m WorkflowRuntimeError(\n\u001b[1;32m    593\u001b[0m             \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mError in step \u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mname\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00me\u001b[38;5;132;01m!s}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m    594\u001b[0m         ) \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01me\u001b[39;00m\n\u001b[1;32m    596\u001b[0m     delay \u001b[38;5;241m=\u001b[39m config\u001b[38;5;241m.\u001b[39mretry_policy\u001b[38;5;241m.\u001b[39mnext(\n\u001b[1;32m    597\u001b[0m         retry_start_at \u001b[38;5;241m+\u001b[39m time\u001b[38;5;241m.\u001b[39mtime(), attempts, e\n\u001b[1;32m    598\u001b[0m     )\n\u001b[1;32m    599\u001b[0m     \u001b[38;5;28;01mif\u001b[39;00m delay \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[1;32m    600\u001b[0m         \u001b[38;5;66;03m# We're done retrying\u001b[39;00m\n",
      "\u001b[0;31mWorkflowRuntimeError\u001b[0m: Error in step 'run_agent_step': 402, message='Payment Required', url='https://router.huggingface.co/hf-inference/models/Qwen/Qwen2.5-Coder-32B-Instruct/v1/chat/completions'"
     ]
    }
   ],
   "source": [
    "from llama_index.core.agent.workflow import AgentWorkflow\n",
    "from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI\n",
    "\n",
    "# Initialize the Hugging Face model\n",
    "llm = HuggingFaceInferenceAPI(model_name=\"Qwen/Qwen2.5-Coder-32B-Instruct\")\n",
    "\n",
    "# Create Alfred, our gala agent, with the guest info tool\n",
    "alfred = AgentWorkflow.from_tools_or_functions(\n",
    "    [guest_info_tool],\n",
    "    llm=llm,\n",
    ")\n",
    "\n",
    "# Example query Alfred might receive during the gala\n",
    "response = await alfred.run(\"Tell me about our guest named 'Lady Ada Lovelace'.\")\n",
    "\n",
    "print(\"🎩 Alfred's Response:\")\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8ce1210b",
   "metadata": {},
   "source": [
    "What’s happening in this final step:\n",
    "\n",
    "- We initialize a Hugging Face model using the HuggingFaceInferenceAPI class\n",
    "- We create our agent (Alfred) as a AgentWorkflow, including the tool we just created\n",
    "- We ask Alfred to retrieve information about a guest named “Lady Ada Lovelace”"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a83f4bc6",
   "metadata": {},
   "source": [
    "### Building and Integrating Tools for Your Agent"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6dee00aa",
   "metadata": {},
   "source": [
    "Give Your Agent Access to the Web"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "adaac02f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "He served two terms as the president of Brazil from 2003 to 2010 and left office with an approval rating of 80%. Brazilian president-elect for the leftist Workers Party (PT) Luiz Inacio Lula da ...\n"
     ]
    }
   ],
   "source": [
    "from llama_index.tools.duckduckgo import DuckDuckGoSearchToolSpec\n",
    "from llama_index.core.tools import FunctionTool\n",
    "\n",
    "# Initialize the DuckDuckGo search tool\n",
    "tool_spec = DuckDuckGoSearchToolSpec()\n",
    "\n",
    "search_tool = FunctionTool.from_defaults(tool_spec.duckduckgo_full_search)\n",
    "# Example usage\n",
    "response = search_tool(\"Who's the current President of Brazil?\")\n",
    "print(response.raw_output[-1]['body'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d43f238a",
   "metadata": {},
   "source": [
    "Creating a Custom Tool for Weather Information to Schedule the Fireworks"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "1c59be40",
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "from llama_index.core.tools import FunctionTool\n",
    "\n",
    "def get_weather_info(location: str) -> str:\n",
    "    \"\"\"Fetches dummy weather information for a given location.\"\"\"\n",
    "    # Dummy weather data\n",
    "    weather_conditions = [\n",
    "        {\"condition\": \"Rainy\", \"temp_c\": 15},\n",
    "        {\"condition\": \"Clear\", \"temp_c\": 25},\n",
    "        {\"condition\": \"Windy\", \"temp_c\": 20}\n",
    "    ]\n",
    "    # Randomly select a weather condition\n",
    "    data = random.choice(weather_conditions)\n",
    "    return f\"Weather in {location}: {data['condition']}, {data['temp_c']}°C\"\n",
    "\n",
    "# Initialize the tool\n",
    "weather_info_tool = FunctionTool.from_defaults(get_weather_info)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "98b670b7",
   "metadata": {},
   "source": [
    "Creating a Hub Stats Tool for Influential AI Builders"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "82ce0fa8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The most downloaded model by facebook is facebook/esmfold_v1 with 24,213,202 downloads.\n"
     ]
    }
   ],
   "source": [
    "import random\n",
    "from llama_index.core.tools import FunctionTool\n",
    "from huggingface_hub import list_models\n",
    "\n",
    "def get_hub_stats(author: str) -> str:\n",
    "    \"\"\"Fetches the most downloaded model from a specific author on the Hugging Face Hub.\"\"\"\n",
    "    try:\n",
    "        # List models from the specified author, sorted by downloads\n",
    "        models = list(list_models(author=author, sort=\"downloads\", direction=-1, limit=1))\n",
    "\n",
    "        if models:\n",
    "            model = models[0]\n",
    "            return f\"The most downloaded model by {author} is {model.id} with {model.downloads:,} downloads.\"\n",
    "        else:\n",
    "            return f\"No models found for author {author}.\"\n",
    "    except Exception as e:\n",
    "        return f\"Error fetching models for {author}: {str(e)}\"\n",
    "\n",
    "# Initialize the tool\n",
    "hub_stats_tool = FunctionTool.from_defaults(get_hub_stats)\n",
    "\n",
    "# Example usage\n",
    "print(hub_stats_tool(\"facebook\")) # Example: Get the most downloaded model by Facebook"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6722948c",
   "metadata": {},
   "source": [
    "Integrating Tools with Alfred"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "cea842d2",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Exception in callback Dispatcher.span.<locals>.wrapper.<locals>.handle_future_result(span_id='Workflow.run...-55bd0ee16e6f', bound_args=<BoundArgumen...mory': None})>, instance=<llama_index....x76ae0f7cddf0>, context=<_contextvars...x76ae50734e40>)(<WorkflowHand...ompletions'\")>) at /home/cairo/anaconda3/lib/python3.12/site-packages/llama_index/core/instrumentation/dispatcher.py:274\n",
      "handle: <Handle Dispatcher.span.<locals>.wrapper.<locals>.handle_future_result(span_id='Workflow.run...-55bd0ee16e6f', bound_args=<BoundArgumen...mory': None})>, instance=<llama_index....x76ae0f7cddf0>, context=<_contextvars...x76ae50734e40>)(<WorkflowHand...ompletions'\")>) at /home/cairo/anaconda3/lib/python3.12/site-packages/llama_index/core/instrumentation/dispatcher.py:274>\n",
      "Traceback (most recent call last):\n",
      "  File \"/home/cairo/anaconda3/lib/python3.12/site-packages/llama_index/core/workflow/context.py\", line 583, in _step_worker\n",
      "    new_ev = await instrumented_step(**kwargs)\n",
      "             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
      "  File \"/home/cairo/anaconda3/lib/python3.12/site-packages/llama_index/core/instrumentation/dispatcher.py\", line 368, in async_wrapper\n",
      "    result = await func(*args, **kwargs)\n",
      "             ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
      "  File \"/home/cairo/anaconda3/lib/python3.12/site-packages/llama_index/core/agent/workflow/multi_agent_workflow.py\", line 382, in run_agent_step\n",
      "    agent_output = await agent.take_step(\n",
      "                   ^^^^^^^^^^^^^^^^^^^^^^\n",
      "  File \"/home/cairo/anaconda3/lib/python3.12/site-packages/llama_index/core/agent/workflow/react_agent.py\", line 101, in take_step\n",
      "    async for last_chat_response in response:\n",
      "  File \"/home/cairo/anaconda3/lib/python3.12/site-packages/llama_index/llms/huggingface_api/base.py\", line 429, in gen\n",
      "    async for chunk in await self._async_client.chat_completion(\n",
      "                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
      "  File \"/home/cairo/anaconda3/lib/python3.12/site-packages/huggingface_hub/inference/_generated/_async_client.py\", line 1032, in chat_completion\n",
      "    data = await self._inner_post(request_parameters, stream=stream)\n",
      "           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
      "  File \"/home/cairo/anaconda3/lib/python3.12/site-packages/huggingface_hub/inference/_generated/_async_client.py\", line 367, in _inner_post\n",
      "    raise error\n",
      "  File \"/home/cairo/anaconda3/lib/python3.12/site-packages/huggingface_hub/inference/_generated/_async_client.py\", line 353, in _inner_post\n",
      "    response.raise_for_status()\n",
      "  File \"/home/cairo/anaconda3/lib/python3.12/site-packages/aiohttp/client_reqrep.py\", line 1093, in raise_for_status\n",
      "    raise ClientResponseError(\n",
      "aiohttp.client_exceptions.ClientResponseError: 402, message='Payment Required', url='https://router.huggingface.co/hf-inference/models/Qwen/Qwen2.5-Coder-32B-Instruct/v1/chat/completions'\n",
      "\n",
      "The above exception was the direct cause of the following exception:\n",
      "\n",
      "Traceback (most recent call last):\n",
      "  File \"/home/cairo/anaconda3/lib/python3.12/asyncio/events.py\", line 88, in _run\n",
      "    self._context.run(self._callback, *self._args)\n",
      "  File \"/home/cairo/anaconda3/lib/python3.12/site-packages/llama_index/core/instrumentation/dispatcher.py\", line 286, in handle_future_result\n",
      "    raise exception\n",
      "  File \"/home/cairo/anaconda3/lib/python3.12/site-packages/llama_index/core/workflow/workflow.py\", line 394, in _run_workflow\n",
      "    raise exception_raised\n",
      "  File \"/home/cairo/anaconda3/lib/python3.12/site-packages/llama_index/core/workflow/context.py\", line 592, in _step_worker\n",
      "    raise WorkflowRuntimeError(\n",
      "llama_index.core.workflow.errors.WorkflowRuntimeError: Error in step 'run_agent_step': 402, message='Payment Required', url='https://router.huggingface.co/hf-inference/models/Qwen/Qwen2.5-Coder-32B-Instruct/v1/chat/completions'\n"
     ]
    },
    {
     "ename": "WorkflowRuntimeError",
     "evalue": "Error in step 'run_agent_step': 402, message='Payment Required', url='https://router.huggingface.co/hf-inference/models/Qwen/Qwen2.5-Coder-32B-Instruct/v1/chat/completions'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mClientResponseError\u001b[0m                       Traceback (most recent call last)",
      "File \u001b[0;32m~/anaconda3/lib/python3.12/site-packages/llama_index/core/workflow/context.py:583\u001b[0m, in \u001b[0;36mContext._step_worker\u001b[0;34m(self, name, step, config, stepwise, verbose, checkpoint_callback, run_id, service_manager, dispatcher)\u001b[0m\n\u001b[1;32m    582\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[0;32m--> 583\u001b[0m     new_ev \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mawait\u001b[39;00m instrumented_step(\u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs)\n\u001b[1;32m    584\u001b[0m     kwargs\u001b[38;5;241m.\u001b[39mclear()\n",
      "File \u001b[0;32m~/anaconda3/lib/python3.12/site-packages/llama_index/core/instrumentation/dispatcher.py:368\u001b[0m, in \u001b[0;36mDispatcher.span.<locals>.async_wrapper\u001b[0;34m(func, instance, args, kwargs)\u001b[0m\n\u001b[1;32m    367\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[0;32m--> 368\u001b[0m     result \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mawait\u001b[39;00m func(\u001b[38;5;241m*\u001b[39margs, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs)\n\u001b[1;32m    369\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mBaseException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n",
      "File \u001b[0;32m~/anaconda3/lib/python3.12/site-packages/llama_index/core/agent/workflow/multi_agent_workflow.py:382\u001b[0m, in \u001b[0;36mAgentWorkflow.run_agent_step\u001b[0;34m(self, ctx, ev)\u001b[0m\n\u001b[1;32m    380\u001b[0m tools \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mawait\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mget_tools(ev\u001b[38;5;241m.\u001b[39mcurrent_agent_name, user_msg_str \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m--> 382\u001b[0m agent_output \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mawait\u001b[39;00m agent\u001b[38;5;241m.\u001b[39mtake_step(\n\u001b[1;32m    383\u001b[0m     ctx,\n\u001b[1;32m    384\u001b[0m     ev\u001b[38;5;241m.\u001b[39minput,\n\u001b[1;32m    385\u001b[0m     tools,\n\u001b[1;32m    386\u001b[0m     memory,\n\u001b[1;32m    387\u001b[0m )\n\u001b[1;32m    389\u001b[0m ctx\u001b[38;5;241m.\u001b[39mwrite_event_to_stream(agent_output)\n",
      "File \u001b[0;32m~/anaconda3/lib/python3.12/site-packages/llama_index/core/agent/workflow/react_agent.py:101\u001b[0m, in \u001b[0;36mReActAgent.take_step\u001b[0;34m(self, ctx, llm_input, tools, memory)\u001b[0m\n\u001b[1;32m    100\u001b[0m last_chat_response \u001b[38;5;241m=\u001b[39m ChatResponse(message\u001b[38;5;241m=\u001b[39mChatMessage())\n\u001b[0;32m--> 101\u001b[0m \u001b[38;5;28;01masync\u001b[39;00m \u001b[38;5;28;01mfor\u001b[39;00m last_chat_response \u001b[38;5;129;01min\u001b[39;00m response:\n\u001b[1;32m    102\u001b[0m     raw \u001b[38;5;241m=\u001b[39m (\n\u001b[1;32m    103\u001b[0m         last_chat_response\u001b[38;5;241m.\u001b[39mraw\u001b[38;5;241m.\u001b[39mmodel_dump()\n\u001b[1;32m    104\u001b[0m         \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(last_chat_response\u001b[38;5;241m.\u001b[39mraw, BaseModel)\n\u001b[1;32m    105\u001b[0m         \u001b[38;5;28;01melse\u001b[39;00m last_chat_response\u001b[38;5;241m.\u001b[39mraw\n\u001b[1;32m    106\u001b[0m     )\n",
      "File \u001b[0;32m~/anaconda3/lib/python3.12/site-packages/llama_index/llms/huggingface_api/base.py:429\u001b[0m, in \u001b[0;36mHuggingFaceInferenceAPI.astream_chat.<locals>.gen\u001b[0;34m()\u001b[0m\n\u001b[1;32m    428\u001b[0m cur_index \u001b[38;5;241m=\u001b[39m \u001b[38;5;241m-\u001b[39m\u001b[38;5;241m1\u001b[39m\n\u001b[0;32m--> 429\u001b[0m \u001b[38;5;28;01masync\u001b[39;00m \u001b[38;5;28;01mfor\u001b[39;00m chunk \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28;01mawait\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_async_client\u001b[38;5;241m.\u001b[39mchat_completion(\n\u001b[1;32m    430\u001b[0m     messages\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_to_huggingface_messages(messages),\n\u001b[1;32m    431\u001b[0m     stream\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mTrue\u001b[39;00m,\n\u001b[1;32m    432\u001b[0m     \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mmodel_kwargs,\n\u001b[1;32m    433\u001b[0m ):\n\u001b[1;32m    434\u001b[0m     \u001b[38;5;28;01mif\u001b[39;00m chunk\u001b[38;5;241m.\u001b[39mchoices[\u001b[38;5;241m0\u001b[39m]\u001b[38;5;241m.\u001b[39mfinish_reason \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n",
      "File \u001b[0;32m~/anaconda3/lib/python3.12/site-packages/huggingface_hub/inference/_generated/_async_client.py:1032\u001b[0m, in \u001b[0;36mAsyncInferenceClient.chat_completion\u001b[0;34m(self, messages, model, stream, frequency_penalty, logit_bias, logprobs, max_tokens, n, presence_penalty, response_format, seed, stop, stream_options, temperature, tool_choice, tool_prompt, tools, top_logprobs, top_p, extra_body)\u001b[0m\n\u001b[1;32m   1025\u001b[0m request_parameters \u001b[38;5;241m=\u001b[39m provider_helper\u001b[38;5;241m.\u001b[39mprepare_request(\n\u001b[1;32m   1026\u001b[0m     inputs\u001b[38;5;241m=\u001b[39mmessages,\n\u001b[1;32m   1027\u001b[0m     parameters\u001b[38;5;241m=\u001b[39mparameters,\n\u001b[0;32m   (...)\u001b[0m\n\u001b[1;32m   1030\u001b[0m     api_key\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mtoken,\n\u001b[1;32m   1031\u001b[0m )\n\u001b[0;32m-> 1032\u001b[0m data \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mawait\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_inner_post(request_parameters, stream\u001b[38;5;241m=\u001b[39mstream)\n\u001b[1;32m   1034\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m stream:\n",
      "File \u001b[0;32m~/anaconda3/lib/python3.12/site-packages/huggingface_hub/inference/_generated/_async_client.py:367\u001b[0m, in \u001b[0;36mAsyncInferenceClient._inner_post\u001b[0;34m(self, request_parameters, stream)\u001b[0m\n\u001b[1;32m    366\u001b[0m     \u001b[38;5;28;01mawait\u001b[39;00m session\u001b[38;5;241m.\u001b[39mclose()\n\u001b[0;32m--> 367\u001b[0m     \u001b[38;5;28;01mraise\u001b[39;00m error\n\u001b[1;32m    368\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mException\u001b[39;00m:\n",
      "File \u001b[0;32m~/anaconda3/lib/python3.12/site-packages/huggingface_hub/inference/_generated/_async_client.py:353\u001b[0m, in \u001b[0;36mAsyncInferenceClient._inner_post\u001b[0;34m(self, request_parameters, stream)\u001b[0m\n\u001b[1;32m    352\u001b[0m         \u001b[38;5;28;01mpass\u001b[39;00m\n\u001b[0;32m--> 353\u001b[0m response\u001b[38;5;241m.\u001b[39mraise_for_status()\n\u001b[1;32m    354\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m stream:\n",
      "File \u001b[0;32m~/anaconda3/lib/python3.12/site-packages/aiohttp/client_reqrep.py:1093\u001b[0m, in \u001b[0;36mClientResponse.raise_for_status\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m   1092\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mrelease()\n\u001b[0;32m-> 1093\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m ClientResponseError(\n\u001b[1;32m   1094\u001b[0m     \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mrequest_info,\n\u001b[1;32m   1095\u001b[0m     \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mhistory,\n\u001b[1;32m   1096\u001b[0m     status\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mstatus,\n\u001b[1;32m   1097\u001b[0m     message\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mreason,\n\u001b[1;32m   1098\u001b[0m     headers\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mheaders,\n\u001b[1;32m   1099\u001b[0m )\n",
      "\u001b[0;31mClientResponseError\u001b[0m: 402, message='Payment Required', url='https://router.huggingface.co/hf-inference/models/Qwen/Qwen2.5-Coder-32B-Instruct/v1/chat/completions'",
      "\nThe above exception was the direct cause of the following exception:\n",
      "\u001b[0;31mWorkflowRuntimeError\u001b[0m                      Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[21], line 13\u001b[0m\n\u001b[1;32m      7\u001b[0m alfred \u001b[38;5;241m=\u001b[39m AgentWorkflow\u001b[38;5;241m.\u001b[39mfrom_tools_or_functions(\n\u001b[1;32m      8\u001b[0m     [search_tool, weather_info_tool, hub_stats_tool],\n\u001b[1;32m      9\u001b[0m     llm\u001b[38;5;241m=\u001b[39mllm\n\u001b[1;32m     10\u001b[0m )\n\u001b[1;32m     12\u001b[0m \u001b[38;5;66;03m# Example query Alfred might receive during the gala\u001b[39;00m\n\u001b[0;32m---> 13\u001b[0m response \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mawait\u001b[39;00m alfred\u001b[38;5;241m.\u001b[39mrun(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mWhat is Facebook and what\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124ms their most popular model?\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m     15\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m🎩 Alfred\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124ms Response:\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m     16\u001b[0m \u001b[38;5;28mprint\u001b[39m(response)\n",
      "File \u001b[0;32m~/anaconda3/lib/python3.12/site-packages/llama_index/core/workflow/workflow.py:394\u001b[0m, in \u001b[0;36mWorkflow.run.<locals>._run_workflow\u001b[0;34m()\u001b[0m\n\u001b[1;32m    390\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m exception_raised:\n\u001b[1;32m    391\u001b[0m     \u001b[38;5;66;03m# cancel the stream\u001b[39;00m\n\u001b[1;32m    392\u001b[0m     ctx\u001b[38;5;241m.\u001b[39mwrite_event_to_stream(StopEvent())\n\u001b[0;32m--> 394\u001b[0m     \u001b[38;5;28;01mraise\u001b[39;00m exception_raised\n\u001b[1;32m    396\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m we_done:\n\u001b[1;32m    397\u001b[0m     \u001b[38;5;66;03m# cancel the stream\u001b[39;00m\n\u001b[1;32m    398\u001b[0m     ctx\u001b[38;5;241m.\u001b[39mwrite_event_to_stream(StopEvent())\n",
      "File \u001b[0;32m~/anaconda3/lib/python3.12/site-packages/llama_index/core/workflow/context.py:592\u001b[0m, in \u001b[0;36mContext._step_worker\u001b[0;34m(self, name, step, config, stepwise, verbose, checkpoint_callback, run_id, service_manager, dispatcher)\u001b[0m\n\u001b[1;32m    590\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[1;32m    591\u001b[0m     \u001b[38;5;28;01mif\u001b[39;00m config\u001b[38;5;241m.\u001b[39mretry_policy \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[0;32m--> 592\u001b[0m         \u001b[38;5;28;01mraise\u001b[39;00m WorkflowRuntimeError(\n\u001b[1;32m    593\u001b[0m             \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mError in step \u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mname\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00me\u001b[38;5;132;01m!s}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m    594\u001b[0m         ) \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01me\u001b[39;00m\n\u001b[1;32m    596\u001b[0m     delay \u001b[38;5;241m=\u001b[39m config\u001b[38;5;241m.\u001b[39mretry_policy\u001b[38;5;241m.\u001b[39mnext(\n\u001b[1;32m    597\u001b[0m         retry_start_at \u001b[38;5;241m+\u001b[39m time\u001b[38;5;241m.\u001b[39mtime(), attempts, e\n\u001b[1;32m    598\u001b[0m     )\n\u001b[1;32m    599\u001b[0m     \u001b[38;5;28;01mif\u001b[39;00m delay \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[1;32m    600\u001b[0m         \u001b[38;5;66;03m# We're done retrying\u001b[39;00m\n",
      "\u001b[0;31mWorkflowRuntimeError\u001b[0m: Error in step 'run_agent_step': 402, message='Payment Required', url='https://router.huggingface.co/hf-inference/models/Qwen/Qwen2.5-Coder-32B-Instruct/v1/chat/completions'"
     ]
    }
   ],
   "source": [
    "from llama_index.core.agent.workflow import AgentWorkflow\n",
    "from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI\n",
    "\n",
    "# Initialize the Hugging Face model\n",
    "llm = HuggingFaceInferenceAPI(model_name=\"Qwen/Qwen2.5-Coder-32B-Instruct\")\n",
    "# Create Alfred with all the tools\n",
    "alfred = AgentWorkflow.from_tools_or_functions(\n",
    "    [search_tool, weather_info_tool, hub_stats_tool],\n",
    "    llm=llm\n",
    ")\n",
    "\n",
    "# Example query Alfred might receive during the gala\n",
    "response = await alfred.run(\"What is Facebook and what's their most popular model?\")\n",
    "\n",
    "print(\"🎩 Alfred's Response:\")\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9d85b055",
   "metadata": {},
   "source": [
    "Conclusion\n",
    "\n",
    "By integrating these tools, Alfred is now equipped to handle a variety of tasks, from web searches to weather updates and model statistics. This ensures he remains the most informed and engaging host at the gala."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eac6666b",
   "metadata": {},
   "source": [
    "### Creating Your Gala Agent"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "33897d2c",
   "metadata": {},
   "source": [
    "https://huggingface.co/learn/agents-course/unit3/agentic-rag/agent?agents-frameworks=llama-index"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a9ba3df0",
   "metadata": {},
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "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.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}