File size: 24,090 Bytes
45b200f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "Preps",
   "id": "39fa029d099d9f52"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-10T20:50:31.142189Z",
     "start_time": "2025-06-10T20:50:31.139103Z"
    }
   },
   "cell_type": "code",
   "source": "from tools import describe_audio_tool",
   "id": "a8592566121f9a22",
   "outputs": [],
   "execution_count": 87
  },
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-06-10T20:50:31.155454Z",
     "start_time": "2025-06-10T20:50:31.152566Z"
    }
   },
   "source": [
    "from globals import *\n",
    "from global_functions import *\n",
    "from tools import *\n",
    "from IPython.display import Image, display\n",
    "import datasets\n",
    "import base64\n",
    "from langchain_core.messages import AnyMessage, HumanMessage, AIMessage, SystemMessage, ToolMessage\n",
    "# describe_image_tool\n",
    "import subprocess\n",
    "from langchain_community.document_loaders import UnstructuredExcelLoader\n",
    "import yt_dlp\n",
    "from langchain_community.tools import WikipediaQueryRun\n",
    "from langchain_community.utilities import WikipediaAPIWrapper"
   ],
   "outputs": [],
   "execution_count": 88
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-10T20:50:31.198378Z",
     "start_time": "2025-06-10T20:50:31.165368Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# ------------------------------------------------------ #\n",
    "# MODELS\n",
    "# ------------------------------------------------------ #\n",
    "# init_chat_llm = ChatOllama(model=model_name)\n",
    "init_chat_llm = ChatTogether(model=\"meta-llama/Llama-3.3-70B-Instruct-Turbo-Free\", api_key=os.getenv(\"TOGETHER_API_KEY\"))\n"
   ],
   "id": "de15a3991553b118",
   "outputs": [],
   "execution_count": 89
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-10T20:50:31.208604Z",
     "start_time": "2025-06-10T20:50:31.206116Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# ------------------------------------------------------ #\n",
    "# FUNCTIONS FOR TOOLS\n",
    "# ------------------------------------------------------ #\n",
    "def read_mp3(f, normalized=False):\n",
    "    \"\"\"Read MP3 file to numpy array.\"\"\"\n",
    "    a = pydub.AudioSegment.from_mp3(f)\n",
    "    y = np.array(a.get_array_of_samples())\n",
    "    if a.channels == 2:\n",
    "        y = y.reshape((-1, 2))\n",
    "        # y = y.mean(axis=1)\n",
    "        y = y[:,1]\n",
    "    if normalized:\n",
    "        return a.frame_rate, np.float32(y) / 2**15\n",
    "    else:\n",
    "        return a.frame_rate, y"
   ],
   "id": "6db4dcdc5746ff14",
   "outputs": [],
   "execution_count": 90
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-10T20:50:31.222129Z",
     "start_time": "2025-06-10T20:50:31.217718Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# ------------------------------------------------------ #\n",
    "# TOOLS\n",
    "# ------------------------------------------------------ #\n",
    "# mp3\n",
    "def describe_audio_tool(file_name: str) -> str:\n",
    "    \"\"\"\n",
    "    This tool receives a file name of an audio, uploads the audio and returns a detailed description of the audio.\n",
    "    Inputs: file_name as str\n",
    "    Outputs: audio detailed description as str\n",
    "    \"\"\"\n",
    "    # --------------------------------------------------------------------------- #\n",
    "    file_dir = f'files/{file_name}'\n",
    "    print(f\"{file_dir=}\")\n",
    "    audio_input_sr, audio_input_np = read_mp3(file_dir)\n",
    "    audio_input_t = torch.tensor(audio_input_np, dtype=torch.float32)\n",
    "    target_sr = 16000\n",
    "    resampler = T.Resample(audio_input_sr, target_sr, dtype=audio_input_t.dtype)\n",
    "    resampled_audio_input_t: torch.Tensor = resampler(audio_input_t)\n",
    "    resampled_audio_input_np = resampled_audio_input_t.numpy()\n",
    "    # --------------------------------------------------------------------------- #\n",
    "    inputs = processor(resampled_audio_input_np, sampling_rate=16000, return_tensors=\"pt\", padding=True)\n",
    "    # Inference\n",
    "    with torch.no_grad():\n",
    "        logits = model(**inputs).logits\n",
    "    # Decode\n",
    "    predicted_ids = torch.argmax(logits, dim=-1)\n",
    "    transcription = processor.decode(predicted_ids[0])\n",
    "    return transcription\n",
    "\n",
    "# py\n",
    "def python_repl_tool(file_name: str) -> str:\n",
    "    \"\"\"\n",
    "    This tool receives a file name of a python code and executes it. Then, it returns a an output of the code.\n",
    "    Inputs: file_name as str\n",
    "    Outputs: code's output as str\n",
    "    \"\"\"\n",
    "    file_dir = f'files/{file_name}'\n",
    "    print(f\"{file_dir=}\")\n",
    "    result = subprocess.run([\"python\", file_dir], capture_output=True, text=True)\n",
    "    return result.stdout\n",
    "\n",
    "# xlsx\n",
    "def excel_repl_tool(file_name: str) -> str:\n",
    "    \"\"\"\n",
    "    This tool receives a file name of an Excel file and reads it. Then, it returns a string of the content of the file.\n",
    "    Inputs: file_name as str\n",
    "    Outputs: file's content as str\n",
    "    \"\"\"\n",
    "    file_dir = f'files/{file_name}'\n",
    "    print(f\"{file_dir=}\")\n",
    "    loader = UnstructuredExcelLoader(file_dir, mode=\"elements\")\n",
    "    docs = loader.load()\n",
    "    return docs[0].metadata['text_as_html']\n",
    "\n",
    "\n",
    "# youtube\n",
    "def youtube_extractor_tool(url: str) -> str:\n",
    "    \"\"\"\n",
    "    This tool receives a url of the youtube video and reads it. Then, it returns a string of the content of the video.\n",
    "    Inputs: url as str\n",
    "    Outputs: video's content as str\n",
    "    \"\"\"\n",
    "    file_name = 'my_audio_file'\n",
    "    ydl_opts = {\n",
    "        'format': 'bestaudio/best',\n",
    "        'outtmpl': f'files/{file_name}.%(ext)s',  # <-- set your custom filename here\n",
    "        'postprocessors': [{\n",
    "            'key': 'FFmpegExtractAudio',\n",
    "            'preferredcodec': 'mp3',\n",
    "            'preferredquality': '192',\n",
    "        }],\n",
    "    }\n",
    "\n",
    "    with yt_dlp.YoutubeDL(ydl_opts) as ydl:\n",
    "        ydl.download([url])\n",
    "    return describe_audio_tool(file_name=f'{file_name}.mp3')\n",
    "\n",
    "\n",
    "# wiki\n",
    "def wikipedia_tool(query: str) -> str:\n",
    "    \"\"\"\n",
    "    This tool receives a query to search inside the Wikipedia website, reads the page and returns the relevant information as a string.\n",
    "    Inputs: query as str\n",
    "    Outputs: Wikipedia's relevant content as str\n",
    "    \"\"\"\n",
    "    print(f\"[wiki tool] {query=}\")\n",
    "    wikipedia = WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper())\n",
    "    respond = wikipedia.run(query)\n",
    "    return respond"
   ],
   "id": "259492d051c8ae57",
   "outputs": [],
   "execution_count": 91
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-10T20:50:31.239565Z",
     "start_time": "2025-06-10T20:50:31.230235Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# ------------------------------------------------------ #\n",
    "# BENDING TO TOOLS\n",
    "# ------------------------------------------------------ #\n",
    "tools = [search_tool, describe_image_tool, describe_audio_tool, python_repl_tool, excel_repl_tool, youtube_extractor_tool, wikipedia_tool]\n",
    "chat_llm = init_chat_llm.bind_tools(tools)"
   ],
   "id": "13d9344ff87bc5e6",
   "outputs": [],
   "execution_count": 92
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-10T20:50:31.247558Z",
     "start_time": "2025-06-10T20:50:31.246108Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# ------------------------------------------------------ #\n",
    "# STATE\n",
    "# ------------------------------------------------------ #\n",
    "class AgentState(TypedDict):\n",
    "    # messages: list[AnyMessage, add_messages]\n",
    "    messages: list[AnyMessage]\n",
    "    file_name: str\n",
    "    final_output_is_good: bool"
   ],
   "id": "6a38f29e827cab31",
   "outputs": [],
   "execution_count": 93
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-10T20:50:31.257049Z",
     "start_time": "2025-06-10T20:50:31.254965Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# ------------------------------------------------------ #\n",
    "# HELP FUNCTIONS\n",
    "# ------------------------------------------------------ #\n",
    "def step_print(state: AgentState | None, step_label: str):\n",
    "    if state:\n",
    "        print(f'<<--- [{len(state[\"messages\"])}] Entering ``{step_label}`` Node... --->>')\n",
    "    else:\n",
    "        print(f'<<--- [] Entering ``{step_label}`` Node... --->>')\n",
    "\n",
    "\n",
    "def messages_print(messages_to_print: List[AnyMessage]):\n",
    "    print('--- Message/s ---')\n",
    "    for m in messages_to_print:\n",
    "        print(f'{m.type} ({m.name}): \\n{m.content}')\n",
    "    print(f'<<--- *** --->>')"
   ],
   "id": "583f00a3c2e18e36",
   "outputs": [],
   "execution_count": 94
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-10T20:50:31.271958Z",
     "start_time": "2025-06-10T20:50:31.264390Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# ------------------------------------------------------ #\n",
    "# NODES\n",
    "# ------------------------------------------------------ #\n",
    "def preprocessing(state: AgentState):\n",
    "    # state['messages'] = [state['messages'][0]]\n",
    "    step_print(None, 'Preprocessing')\n",
    "    if state['file_name'] != '':\n",
    "        # state['messages'] += f\"\\nfile_name: {state['file_name']}\"\n",
    "        state['messages'][0].content += f\"\\nfile_name: {state['file_name']}\"\n",
    "    messages_print(state['messages'])\n",
    "    return {\n",
    "        \"messages\": [SystemMessage(content=DEFAULT_SYSTEM_PROMPT)] + state[\"messages\"]\n",
    "    }\n",
    "\n",
    "\n",
    "def assistant(state: AgentState):\n",
    "    # state[\"messages\"] = [SystemMessage(content=DEFAULT_SYSTEM_PROMPT)] + state[\"messages\"]\n",
    "    step_print(state, 'assistant')\n",
    "    ai_message = chat_llm.invoke(state[\"messages\"])\n",
    "    messages_print([ai_message])\n",
    "    return {\n",
    "        'messages': state[\"messages\"] + [ai_message]\n",
    "    }\n",
    "\n",
    "\n",
    "base_tool_node = ToolNode(tools)\n",
    "def wrapped_tool_node(state: AgentState):\n",
    "    step_print(state, 'Tools')\n",
    "    # Call the original ToolNode\n",
    "    result = base_tool_node.invoke(state)\n",
    "    messages_print(result[\"messages\"])\n",
    "    # Append to the messages list instead of replacing it\n",
    "    state[\"messages\"] += result[\"messages\"]\n",
    "    return {\"messages\": state[\"messages\"]}\n",
    "\n",
    "\n",
    "def checker_final_answer(state: AgentState):\n",
    "    step_print(state, 'Final Check')\n",
    "    s = state['messages'][-1].content\n",
    "    if \"FINAL ANSWER: \" not in s:\n",
    "        return {\n",
    "        'messages': state[\"messages\"],\n",
    "        'final_output_is_good': False\n",
    "    }\n",
    "    return {\n",
    "        'final_output_is_good': True\n",
    "    }\n"
   ],
   "id": "45ef5e1d3df698de",
   "outputs": [],
   "execution_count": 95
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-10T20:50:31.281228Z",
     "start_time": "2025-06-10T20:50:31.278542Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# ------------------------------------------------------ #\n",
    "# CONDITIONAL FUNCTIONS\n",
    "# ------------------------------------------------------ #\n",
    "def condition_output(state: AgentState) -> Literal[\"assistant\", \"__end__\"]:\n",
    "    if state['final_output_is_good']:\n",
    "        return END\n",
    "    return \"assistant\"\n",
    "\n",
    "\n",
    "def condition_tools_or_continue(\n",
    "    state: Union[list[AnyMessage], dict[str, Any], BaseModel],\n",
    "    messages_key: str = \"messages\",\n",
    ") -> Literal[\"tools\", \"checker_final_answer\"]:\n",
    "\n",
    "    if isinstance(state, list):\n",
    "        ai_message = state[-1]\n",
    "    elif isinstance(state, dict) and (messages := state.get(messages_key, [])):\n",
    "        ai_message = messages[-1]\n",
    "    elif messages := getattr(state, messages_key, []):\n",
    "        ai_message = messages[-1]\n",
    "    else:\n",
    "        # pass\n",
    "        raise ValueError(f\"No messages found in input state to tool_edge: {state}\")\n",
    "    if hasattr(ai_message, \"tool_calls\") and len(ai_message.tool_calls) > 0:\n",
    "        return \"tools\"\n",
    "    return \"checker_final_answer\"\n",
    "    # return \"__end__\"\n"
   ],
   "id": "8fd537b4436a3d4b",
   "outputs": [],
   "execution_count": 96
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-10T20:50:31.291047Z",
     "start_time": "2025-06-10T20:50:31.289017Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# ------------------------------------------------------ #\n",
    "# BUILDERS\n",
    "# ------------------------------------------------------ #\n",
    "def workflow_tools() -> Tuple[StateGraph, str]:\n",
    "    i_builder = StateGraph(AgentState)\n",
    "\n",
    "    # Nodes\n",
    "    i_builder.add_node('preprocessing', preprocessing)\n",
    "    i_builder.add_node('assistant', assistant)\n",
    "    i_builder.add_node('tools', wrapped_tool_node)\n",
    "    i_builder.add_node('checker_final_answer', checker_final_answer)\n",
    "\n",
    "    # Edges\n",
    "    i_builder.add_edge(START, 'preprocessing')\n",
    "    i_builder.add_edge('preprocessing', 'assistant')\n",
    "    i_builder.add_conditional_edges('assistant', condition_tools_or_continue)\n",
    "    i_builder.add_edge('tools', 'assistant')\n",
    "    i_builder.add_conditional_edges('checker_final_answer', condition_output)\n",
    "    return i_builder, 'workflow_tools'"
   ],
   "id": "ec58d7a039c99ca2",
   "outputs": [],
   "execution_count": 97
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "Graph",
   "id": "fda1229d71a9bba9"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-10T20:50:31.299610Z",
     "start_time": "2025-06-10T20:50:31.298066Z"
    }
   },
   "cell_type": "code",
   "source": "# print(alfred.get_graph().draw_mermaid())",
   "id": "66d69686b3d6c030",
   "outputs": [],
   "execution_count": 98
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-10T20:50:31.311304Z",
     "start_time": "2025-06-10T20:50:31.306768Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# ------------------------------------------------------ #\n",
    "# COMPILATION\n",
    "# ------------------------------------------------------ #\n",
    "# builder, builder_name = workflow_simple()\n",
    "builder, builder_name = workflow_tools()\n",
    "alfred = builder.compile()"
   ],
   "id": "42cebd005b0a53f4",
   "outputs": [],
   "execution_count": 99
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-10T20:50:31.319171Z",
     "start_time": "2025-06-10T20:50:31.317804Z"
    }
   },
   "cell_type": "code",
   "source": "# display(Image(alfred.get_graph().draw_mermaid_png()))",
   "id": "b611c5a2248d19af",
   "outputs": [],
   "execution_count": 100
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "Check",
   "id": "6247ddc363658c5e"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-10T20:50:32.029730Z",
     "start_time": "2025-06-10T20:50:31.326735Z"
    }
   },
   "cell_type": "code",
   "source": [
    "response = requests.get(questions_url, timeout=15)\n",
    "response.raise_for_status()\n",
    "questions_data = response.json()"
   ],
   "id": "713d8c986733ac2f",
   "outputs": [],
   "execution_count": 101
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-10T20:50:32.046633Z",
     "start_time": "2025-06-10T20:50:32.043386Z"
    }
   },
   "cell_type": "code",
   "source": [
    "for item_num, item in enumerate(questions_data):\n",
    "    # dict_keys(['task_id', 'question', 'Level', 'file_name'])\n",
    "    if item['file_name'] != '':\n",
    "        print(f\"Task {item_num} has file: {item['file_name']}\")\n",
    "    if 'wiki' in item['question']:\n",
    "        print(f\"Task {item_num} question: {item['question']}\")\n",
    "\n",
    "item_num = 0\n",
    "item = questions_data[item_num]\n",
    "# dict_keys(['task_id', 'question', 'Level', 'file_name'])\n",
    "print('---')\n",
    "print(f\"NUM: {item_num}\")\n",
    "print(f\"ID: {item['task_id']}\")\n",
    "print(f\"FILE NAME: {item['file_name']}\")\n",
    "print(f\"QUESTION: \\n{item['question']}\")\n",
    "print('---')"
   ],
   "id": "52247811540e5c73",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Task 0 question: How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.\n",
      "Task 3 has file: cca530fc-4052-43b2-b130-b30968d8aa44.png\n",
      "Task 9 has file: 99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3.mp3\n",
      "Task 11 has file: f918266a-b3e0-4914-865d-4faa564f1aef.py\n",
      "Task 13 has file: 1f975693-876d-457b-a649-393859e79bf3.mp3\n",
      "Task 18 has file: 7bd855d8-463d-4ed5-93ca-5fe35145f733.xlsx\n",
      "---\n",
      "NUM: 0\n",
      "ID: 8e867cd7-cff9-4e6c-867a-ff5ddc2550be\n",
      "FILE NAME: \n",
      "QUESTION: \n",
      "How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.\n",
      "---\n"
     ]
    }
   ],
   "execution_count": 102
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-10T20:50:46.752288Z",
     "start_time": "2025-06-10T20:50:36.572639Z"
    }
   },
   "cell_type": "code",
   "source": [
    "response = alfred.invoke({\n",
    "    'messages': [HumanMessage(content=item['question'])],\n",
    "    'file_name': item['file_name'],\n",
    "    'final_output_is_good': False,\n",
    "})"
   ],
   "id": "d1469f387207c914",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<<--- [] Entering ``Preprocessing`` Node... --->>\n",
      "--- Message/s ---\n",
      "human (None): \n",
      "How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.\n",
      "<<--- *** --->>\n",
      "<<--- [2] Entering ``assistant`` Node... --->>\n",
      "--- Message/s ---\n",
      "ai (None): \n",
      "\n",
      "<<--- *** --->>\n",
      "<<--- [3] Entering ``Tools`` Node... --->>\n",
      "[wiki tool] query='Mercedes Sosa discography'\n",
      "--- Message/s ---\n",
      "tool (wikipedia_tool): \n",
      "Page: Mercedes Sosa\n",
      "Summary: Haydée Mercedes \"La Negra\" Sosa (Latin American Spanish: [meɾˈseðes ˈsosa]; 9 July 1935 – 4 October 2009) was an Argentine singer who was popular throughout Latin America and many countries outside the region. With her roots in Argentine folk music, Sosa became one of the preeminent exponents of El nuevo cancionero. She gave voice to songs written by many Latin American songwriters. Her music made people hail her as the \"voice of the voiceless ones\". She was often called \"the conscience of Latin America\".\n",
      "Sosa performed in venues such as the Lincoln Center in New York City, the Théâtre Mogador in Paris, the Sistine Chapel in Vatican City, as well as sold-out shows in New York's Carnegie Hall and the Roman Colosseum during her final decade of life. Her career spanned four decades and she was the recipient of six Latin Grammy awards (2000, 2003, 2004, 2006, 2009, 2011), including a Latin Grammy Lifetime Achievement Award in 2004 and two posthumous Latin Grammy Award for Best Folk Album in 2009 and 2011. She won the Premio Gardel in 2000, the main musical award in Argentina. She served as an ambassador for UNICEF.\n",
      "\n",
      "Page: Cantora, un Viaje Íntimo\n",
      "Summary: Cantora, un Viaje Íntimo  (English: Cantora, An Intimate Journey) is a double album by Argentine singer Mercedes Sosa, released on 2009 through Sony Music Argentina. The album features Cantora 1 and Cantora 2, the project is Sosa's final album before her death on October 4, 2009.\n",
      "At the 10th Annual Latin Grammy Awards, Cantora 1 was nominated for Album of the Year and won Best Folk Album and Best Recording Package, the latter award went to Alejandro Ros, the art director of the album. Additionally, Sosa won two out of five nominations for the albums at the Gardel Awards 2010, the double album was nominated for Album of the Year and Production of the Year and won Best DVD while both Cantora 1 and Cantora 2 were nominated for Best Female Folk Album, with the former winning the category.\n",
      "The double album was a commercial success, being certified platinum by the CAPIF selling more than 200,000 copies in Argentina, Cantora 1 was also certified platinum selling 40,000 copies while Cantora 2 was certified gold selling 20,000 copies. The album also peaked at numbers 22 and 8 at the Top Latin Albums and Latin Pop Albums charts in United States, respectively, being Sosa's only appearances on both charts.\n",
      "At documentary film titled Mercedes Sosa, Cantora un viaje íntimo was released on 2009, it was directed by Rodrigo Vila and features the recording process of the album as well as testimonies from the different guest artists that appeared on the project.\n",
      "\n",
      "Page: Joan Baez discography\n",
      "Summary: This is a discography for American folk singer and songwriter Joan Baez.\n",
      "<<--- *** --->>\n",
      "<<--- [4] Entering ``assistant`` Node... --->>\n",
      "--- Message/s ---\n",
      "ai (None): \n",
      "According to the Wikipedia page, between 2000 and 2009, Mercedes Sosa published the following studio albums: Acústico (2002), Corazón Libre (2005), and Cantora 1 and Cantora 2 (2009). \n",
      "\n",
      "FINAL ANSWER: 4\n",
      "<<--- *** --->>\n",
      "<<--- [5] Entering ``Final Check`` Node... --->>\n"
     ]
    }
   ],
   "execution_count": 103
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-06-09T19:43:11.250731Z",
     "start_time": "2025-06-09T19:43:11.249022Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# pic_loc_str = 'files/cca530fc-4052-43b2-b130-b30968d8aa44.png'\n",
    "# # doc = [UnstructuredImageLoader(pic_loc_str).load()]\n",
    "# dataset = datasets.Dataset.from_dict({\"image\": [pic_loc_str]}).cast_column(\"image\", datasets.Image())\n",
    "# dataset[0][\"image\"]"
   ],
   "id": "c9ee8e0b9fbc5df7",
   "outputs": [],
   "execution_count": 93
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "\n",
   "id": "ab912d811bf50006"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}