{ "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 }