{
"cells": [
{
"cell_type": "markdown",
"id": "ad1eb5e0-f01c-4cb2-9c33-8a21e8d4a367",
"metadata": {},
"source": [
"# TASK"
]
},
{
"cell_type": "markdown",
"id": "25b53d6a-da20-4b9f-880e-7b308805efcb",
"metadata": {},
"source": [
"The task is to utilize knowledge from the [**HuggingFace Agents Course**](https://huggingface.co/learn/agents-course/) to implement an agent capable of tackling the GAIA questions.\n",
"\n",
"[**GAIA**](https://huggingface.co/papers/2311.12983) is a benchmark designed to evaluate AI Agents on reasoning, multimodal understanding, web browsing, tool-use capabilities.\n",
"It features a collection of questions posing real-world difficulty easy human interpretability, brute-force resistance, and easy evaluation.\n",
"Questions are organized into three levels of difficulty where level 1 questionsrequire minimal tool use and planning steps while level 3 tasks on the far end demand advanced tool-use and deeply involved planning.\n",
"The course samples 20 questions from the level 1 group and sets a pass criteria of 30% correct answers as criteria for passing the assessment."
]
},
{
"cell_type": "markdown",
"id": "40492b8a-f87d-4072-9723-33d9f9a64312",
"metadata": {},
"source": [
"# GOALS\n",
"- Implement an Agent using the LangGraph Framework\n",
"- Setup API Keys for access to external tools\n",
"- Design tools to help the agent tackle the problem\n",
"- Create the Agent\n",
"- Intergrate the agent into the submission app"
]
},
{
"cell_type": "markdown",
"id": "b8b893ac-49ec-44ef-bc90-2abb134df094",
"metadata": {},
"source": [
"# IMPORTS"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "75727846-da05-4b15-a9ad-fbd4497757d4",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"from dotenv import load_dotenv\n",
"from langgraph.graph import START, StateGraph, MessagesState\n",
"from langgraph.prebuilt import tools_condition\n",
"from langgraph.prebuilt import ToolNode\n",
"from langchain_google_genai import ChatGoogleGenerativeAI\n",
"from langchain_groq import ChatGroq\n",
"from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint, HuggingFaceEmbeddings\n",
"from langchain_community.tools.tavily_search import TavilySearchResults\n",
"from langchain_community.document_loaders import WikipediaLoader\n",
"from langchain_community.document_loaders import ArxivLoader\n",
"from langchain_community.vectorstores import SupabaseVectorStore\n",
"from langchain_core.messages import SystemMessage, HumanMessage\n",
"from langchain_core.tools import tool\n",
"from langchain.tools.retriever import create_retriever_tool\n",
"from supabase.client import Client, create_client"
]
},
{
"cell_type": "markdown",
"id": "30165673-65d8-46e2-a5db-1a357c30d09f",
"metadata": {},
"source": [
"# API KEYS"
]
},
{
"cell_type": "raw",
"id": "50a3f698-56df-4ea6-a236-29ed7fadac7d",
"metadata": {},
"source": [
"SUPABASE_URL\n",
"SUPABASE_SERVICE_KEY\n",
"SUPABASE_SERVICE_ROLE_KEY\n",
"HF_TOKEN"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "dd06e727-2073-406b-b76a-876f4a1bf96a",
"metadata": {},
"outputs": [],
"source": [
"load_dotenv()"
]
},
{
"cell_type": "markdown",
"id": "c8f3a1f0-5f0c-4560-af5e-b2a8edb79aef",
"metadata": {},
"source": [
"# TOOLS"
]
},
{
"cell_type": "markdown",
"id": "44868006-ce9a-4d3d-b1b8-2d7f2261c3b6",
"metadata": {},
"source": [
"Difficulty in the GAIA benchmark extends beyonds just reasoning. Various questions require extracting information from accompanying files of various modalities. To ensure the Agent is up to the task, utility functions need to be pre-built and made available to the Agent. This reduces complexity and introduces some reliability in conducting similar tasks in a reprodicible way. Such tools also account for known LLM shortfalls and extend the capabilities of the LLM with targeted functionalities."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e697c83f-3e87-48a5-a142-3caace4c85d8",
"metadata": {},
"outputs": [],
"source": [
"# load the system prompt from the file\n",
"with open(\"../prompts/system_prompt.txt\", \"r\", encoding=\"utf-8\") as f:\n",
" system_prompt = f.read()\n",
"print(system_prompt)\n",
"\n",
"# System message\n",
"sys_msg = SystemMessage(content=system_prompt)\n",
"\n",
"# build a retriever\n",
"embeddings = HuggingFaceEmbeddings(model_name=\"sentence-transformers/all-mpnet-base-v2\") # dim=768\n",
"supabase: Client = create_client(os.environ.get(\"SUPABASE_URL\"), os.environ.get(\"SUPABASE_SERVICE_ROLE_KEY\"))\n",
"vector_store = SupabaseVectorStore(client=supabase, embedding=embeddings, table_name=\"documents2\", query_name=\"match_documents_2\")\n",
"create_retriever_tool = create_retriever_tool(retriever=vector_store.as_retriever(), name=\"Question Search\", description=\"A tool to retrieve similar questions from a vector store.\")"
]
},
{
"cell_type": "markdown",
"id": "72fbbd0d-c9a9-4af8-9010-739d035e3c24",
"metadata": {},
"source": [
"## WEB SEARCH"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ddac5160-1a67-46e1-8a43-1e341381e1b7",
"metadata": {},
"outputs": [],
"source": [
"# web search\n",
"import os\n",
"from supabase.client import Client, create_client\n",
"from langchain_core.tools import tool\n",
"from langchain_community.tools.tavily_search import TavilySearchResults\n",
"from langchain_community.document_loaders import WikipediaLoader\n",
"from langchain_community.document_loaders import ArxivLoader\n",
"from langchain_huggingface import HuggingFaceEmbeddings\n",
"from langchain_community.vectorstores import SupabaseVectorStore\n",
"from langchain.tools.retriever import create_retriever_tool"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7106a566-af9f-43c4-8a97-b594ae3592e4",
"metadata": {},
"outputs": [],
"source": [
"@tool\n",
"def wiki_search(query: str) -> str:\n",
" \"\"\"Search Wikipedia for a query and return maximum 2 results.\n",
" \n",
" Args:\n",
" query: The search query.\"\"\"\n",
" search_docs = WikipediaLoader(query=query, load_max_docs=2).load()\n",
" formatted_search_docs = \"\\n\\n---\\n\\n\".join([f'\\n{doc.page_content}\\n' for doc in search_docs])\n",
" return {\"wiki_results\": formatted_search_docs}\n",
"\n",
"@tool\n",
"def web_search(query: str) -> str:\n",
" \"\"\"Search Tavily for a query and return maximum 3 results.\n",
" \n",
" Args:\n",
" query: The search query.\"\"\"\n",
" search_docs = TavilySearchResults(max_results=3).invoke(query=query)\n",
" formatted_search_docs = \"\\n\\n---\\n\\n\".join([f'\\n{doc.page_content}\\n' for doc in search_docs])\n",
" return {\"web_results\": formatted_search_docs}\n",
"\n",
"@tool\n",
"def arvix_search(query: str) -> str:\n",
" \"\"\"Search Arxiv for a query and return maximum 3 result.\n",
" \n",
" Args:\n",
" query: The search query.\"\"\"\n",
" search_docs = ArxivLoader(query=query, load_max_docs=3).load()\n",
" formatted_search_docs = \"\\n\\n---\\n\\n\".join([f'\\n{doc.page_content[:1000]}\\n' for doc in search_docs])\n",
" return {\"arvix_results\": formatted_search_docs}\n",
"\n",
"@tool\n",
"def similar_question_search(question: str) -> str:\n",
" \"\"\"Search the vector database for similar questions and return the first results.\n",
" \n",
" Args:\n",
" question: the question human provided.\"\"\"\n",
" matched_docs = vector_store.similarity_search(question, 3)\n",
" formatted_search_docs = \"\\n\\n---\\n\\n\".join([f'\\n{doc.page_content[:1000]}\\n' for doc in matched_docs])\n",
" return {\"similar_questions\": formatted_search_docs}"
]
},
{
"cell_type": "markdown",
"id": "5884084b-5983-4abc-b0ee-6907923077f3",
"metadata": {},
"source": [
"## BASIC CALCULATOR"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d25dc2fe-abcf-4b09-9469-6428b604d620",
"metadata": {},
"outputs": [],
"source": [
"# basic calculator\n",
"from langchain_core.tools import tool"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0d5ec778-4e12-4309-bf93-3ca20a155fca",
"metadata": {},
"outputs": [],
"source": [
"@tool\n",
"def multiply(a: float, b: float) -> float:\n",
" \"\"\"\n",
" Multiplies two numbers.\n",
" Args:\n",
" a (float): the first number\n",
" b (float): the second number\n",
" \"\"\"\n",
" return a * b\n",
"\n",
"@tool\n",
"def add(a: float, b: float) -> float:\n",
" \"\"\"\n",
" Adds two numbers.\n",
" Args:\n",
" a (float): the first number\n",
" b (float): the second number\n",
" \"\"\"\n",
" return a + b\n",
"\n",
"@tool\n",
"def subtract(a: float, b: float) -> int:\n",
" \"\"\"\n",
" Subtracts two numbers.\n",
" Args:\n",
" a (float): the first number\n",
" b (float): the second number\n",
" \"\"\"\n",
" return a - b\n",
"\n",
"@tool\n",
"def divide(a: float, b: float) -> float:\n",
" \"\"\"\n",
" Divides two numbers.\n",
" Args:\n",
" a (float): the first float number\n",
" b (float): the second float number\n",
" \"\"\"\n",
" if b == 0:\n",
" raise ValueError(\"Cannot divided by zero.\")\n",
" return a / b\n",
"\n",
"@tool\n",
"def modulus(a: int, b: int) -> int:\n",
" \"\"\"\n",
" Get the modulus of two numbers.\n",
" Args:\n",
" a (int): the first number\n",
" b (int): the second number\n",
" \"\"\"\n",
" return a % b\n",
"\n",
"@tool\n",
"def power(a: float, b: float) -> float:\n",
" \"\"\"\n",
" Get the power of two numbers.\n",
" Args:\n",
" a (float): the first number\n",
" b (float): the second number\n",
" \"\"\"\n",
" return a**b\n",
"\n",
"@tool\n",
"def square_root(a: float) -> float | complex:\n",
" \"\"\"\n",
" Get the square root of a number.\n",
" Args:\n",
" a (float): the number to get the square root of\n",
" \"\"\"\n",
" if a >= 0:\n",
" return a**0.5\n",
" return cmath.sqrt(a)\n",
"\n",
"@tool\n",
"def count_substring(substring:str, text:str) -> int:\n",
" \"\"\"\n",
" Get the number of occurences of a substring within some text. Useful for 'How many (substring) are in (text)?'\n",
" Args:\n",
" substring (str): the substring to check for.\n",
" text (str): the text to search through.\n",
" \"\"\"\n",
" return text.count(substring)"
]
},
{
"cell_type": "markdown",
"id": "9d4c473f-8523-431a-80c4-fc16618d7c86",
"metadata": {},
"source": [
"## CODE INTERPRETER"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5c3a5072-b1aa-4489-96d4-08d0d925ebfd",
"metadata": {},
"outputs": [],
"source": [
"# code interpreter\n",
"import os\n",
"import io\n",
"import sys\n",
"import uuid\n",
"import base64\n",
"import traceback\n",
"import contextlib\n",
"import tempfile\n",
"import subprocess\n",
"import sqlite3\n",
"from typing import Dict, List, Any, Optional, Union\n",
"import numpy as np\n",
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"from PIL import Image\n",
"from langchain_core.tools import tool"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "43f314d3-f7b7-4bf1-9500-0c0b8f234412",
"metadata": {},
"outputs": [],
"source": [
"class CodeInterpreter:\n",
" def __init__(self, allowed_modules=None, max_execution_time=30, working_directory=None):\n",
" \"\"\"Initialize the code interpreter with safety measures.\"\"\"\n",
" \n",
" self.allowed_modules = allowed_modules or [\"numpy\", \"pandas\", \"matplotlib\", \"scipy\", \"sklearn\", \"math\", \"random\", \"statistics\", \"datetime\", \"collections\",\n",
" \"itertools\", \"functools\", \"operator\", \"re\", \"json\", \"sympy\", \"networkx\", \"nltk\", \"PIL\", \"pytesseract\", \"cmath\", \"uuid\", \"tempfile\", \"requests\", \"urllib\"]\n",
" \n",
" self.max_execution_time = max_execution_time\n",
" self.working_directory = working_directory or os.path.join(os.getcwd()) \n",
" if not os.path.exists(self.working_directory):\n",
" os.makedirs(self.working_directory)\n",
" \n",
" self.globals = {\"__builtins__\": __builtins__, \"np\": np, \"pd\": pd, \"plt\": plt, \"Image\": Image}\n",
" self.temp_sqlite_db = os.path.join(tempfile.gettempdir(), \"code_exec.db\")\n",
"\n",
" def execute_code(self, code: str, language: str = \"python\") -> Dict[str, Any]:\n",
" \"\"\"Execute the provided code in the selected programming language.\"\"\"\n",
" language = language.lower()\n",
" execution_id = str(uuid.uuid4())\n",
" \n",
" result = {\"execution_id\": execution_id, \"status\": \"error\", \"stdout\": \"\", \"stderr\": \"\", \"result\": None, \"plots\": [], \"dataframes\": []}\n",
" \n",
" try:\n",
" if language == \"python\":\n",
" return self._execute_python(code, execution_id)\n",
" elif language == \"bash\":\n",
" return self._execute_bash(code, execution_id)\n",
" elif language == \"sql\":\n",
" return self._execute_sql(code, execution_id)\n",
" elif language == \"c\":\n",
" return self._execute_c(code, execution_id)\n",
" elif language == \"java\":\n",
" return self._execute_java(code, execution_id)\n",
" else:\n",
" result[\"stderr\"] = f\"Unsupported language: {language}\"\n",
" except Exception as e:\n",
" result[\"stderr\"] = str(e)\n",
" \n",
" return result\n",
"\n",
" def _execute_python(self, code: str, execution_id: str) -> dict:\n",
" output_buffer = io.StringIO()\n",
" error_buffer = io.StringIO()\n",
" result = {\"execution_id\": execution_id, \"status\": \"error\", \"stdout\": \"\", \"stderr\": \"\", \"result\": None, \"plots\": [], \"dataframes\": []}\n",
" \n",
" try:\n",
" exec_dir = os.path.join(self.working_directory, execution_id)\n",
" os.makedirs(exec_dir, exist_ok=True)\n",
" plt.switch_backend('Agg')\n",
" \n",
" with contextlib.redirect_stdout(output_buffer), contextlib.redirect_stderr(error_buffer):\n",
" exec_result = exec(code, self.globals)\n",
"\n",
" if plt.get_fignums():\n",
" for i, fig_num in enumerate(plt.get_fignums()):\n",
" fig = plt.figure(fig_num)\n",
" img_path = os.path.join(exec_dir, f\"plot_{i}.png\")\n",
" fig.savefig(img_path)\n",
" with open(img_path, \"rb\") as img_file:\n",
" img_data = base64.b64encode(img_file.read()).decode('utf-8')\n",
" result[\"plots\"].append({\"figure_number\": fig_num, \"data\": img_data})\n",
"\n",
" for var_name, var_value in self.globals.items():\n",
" if isinstance(var_value, pd.DataFrame) and len(var_value) > 0:\n",
" result[\"dataframes\"].append({\"name\": var_name, \"head\": var_value.head().to_dict(), \"shape\": var_value.shape, \"dtypes\": str(var_value.dtypes)})\n",
" \n",
" result[\"status\"] = \"success\"\n",
" result[\"stdout\"] = output_buffer.getvalue()\n",
" result[\"result\"] = exec_result\n",
" \n",
" except Exception as e:\n",
" result[\"status\"] = \"error\"\n",
" result[\"stderr\"] = f\"{error_buffer.getvalue()}\\n{traceback.format_exc()}\"\n",
" \n",
" return result\n",
"\n",
" def _execute_bash(self, code: str, execution_id: str) -> dict:\n",
" try:\n",
" completed = subprocess.run(code, shell=True, capture_output=True, text=True, timeout=self.max_execution_time)\n",
" return {\"execution_id\": execution_id, \"status\": \"success\" if completed.returncode == 0 else \"error\", \"stdout\": completed.stdout, \"stderr\": completed.stderr, \"result\": None, \"plots\": [], \"dataframes\": []}\n",
" except subprocess.TimeoutExpired:\n",
" return {\"execution_id\": execution_id, \"status\": \"error\", \"stdout\": \"\", \"stderr\": \"Execution timed out.\", \"result\": None, \"plots\": [], \"dataframes\": []}\n",
"\n",
" def _execute_sql(self, code: str, execution_id: str) -> dict:\n",
" result = {\"execution_id\": execution_id, \"status\": \"error\", \"stdout\": \"\", \"stderr\": \"\", \"result\": None, \"plots\": [], \"dataframes\": []}\n",
" try:\n",
" conn = sqlite3.connect(self.temp_sqlite_db)\n",
" cur = conn.cursor()\n",
" cur.execute(code)\n",
" if code.strip().lower().startswith(\"select\"):\n",
" columns = [description[0] for description in cur.description]\n",
" rows = cur.fetchall()\n",
" df = pd.DataFrame(rows, columns=columns)\n",
" result[\"dataframes\"].append({\"name\": \"query_result\", \"head\": df.head().to_dict(), \"shape\": df.shape, \"dtypes\": str(df.dtypes)})\n",
" else:\n",
" conn.commit()\n",
" result[\"status\"] = \"success\"\n",
" result[\"stdout\"] = \"Query executed successfully.\"\n",
"\n",
" except Exception as e:\n",
" result[\"stderr\"] = str(e)\n",
" finally:\n",
" conn.close()\n",
"\n",
" return result\n",
"\n",
" def _execute_c(self, code: str, execution_id: str) -> dict:\n",
" temp_dir = tempfile.mkdtemp()\n",
" source_path = os.path.join(temp_dir, \"program.c\")\n",
" binary_path = os.path.join(temp_dir, \"program\")\n",
"\n",
" try:\n",
" with open(source_path, \"w\") as f:\n",
" f.write(code)\n",
"\n",
" compile_proc = subprocess.run([\"gcc\", source_path, \"-o\", binary_path], capture_output=True, text=True, timeout=self.max_execution_time)\n",
" if compile_proc.returncode != 0:\n",
" return {\"execution_id\": execution_id, \"status\": \"error\", \"stdout\": compile_proc.stdout, \"stderr\": compile_proc.stderr, \"result\": None, \"plots\": [], \"dataframes\": []}\n",
"\n",
" run_proc = subprocess.run([binary_path], capture_output=True, text=True, timeout=self.max_execution_time)\n",
" return {\"execution_id\": execution_id, \"status\": \"success\" if run_proc.returncode == 0 else \"error\", \"stdout\": run_proc.stdout, \"stderr\": run_proc.stderr, \"result\": None, \"plots\": [], \"dataframes\": []}\n",
" except Exception as e: return {\"execution_id\": execution_id, \"status\": \"error\", \"stdout\": \"\", \"stderr\": str(e), \"result\": None, \"plots\": [], \"dataframes\": []}\n",
"\n",
" def _execute_java(self, code: str, execution_id: str) -> dict:\n",
" temp_dir = tempfile.mkdtemp()\n",
" source_path = os.path.join(temp_dir, \"Main.java\")\n",
"\n",
" try:\n",
" with open(source_path, \"w\") as f:\n",
" f.write(code)\n",
"\n",
" compile_proc = subprocess.run([\"javac\", source_path], capture_output=True, text=True, timeout=self.max_execution_time)\n",
" if compile_proc.returncode != 0:\n",
" return {\"execution_id\": execution_id, \"status\": \"error\", \"stdout\": compile_proc.stdout, \"stderr\": compile_proc.stderr, \"result\": None, \"plots\": [], \"dataframes\": []}\n",
"\n",
" run_proc = subprocess.run([\"java\", \"-cp\", temp_dir, \"Main\"], capture_output=True, text=True, timeout=self.max_execution_time)\n",
" return {\"execution_id\": execution_id, \"status\": \"success\" if run_proc.returncode == 0 else \"error\", \"stdout\": run_proc.stdout, \"stderr\": run_proc.stderr, \"result\": None, \"plots\": [], \"dataframes\": []}\n",
" except Exception as e:\n",
" return {\"execution_id\": execution_id, \"status\": \"error\", \"stdout\": \"\", \"stderr\": str(e), \"result\": None, \"plots\": [], \"dataframes\": []}\n",
"\n",
"interpreter_instance = CodeInterpreter()\n",
"\n",
"@tool\n",
"def execute_code_multilang(code: str, language: str = \"python\") -> str:\n",
" \"\"\"Execute code in multiple languages (Python, Bash, SQL, C, Java) and return results.\n",
" Args:\n",
" code (str): The source code to execute.\n",
" language (str): The language of the code. Supported: \"python\", \"bash\", \"sql\", \"c\", \"java\".\n",
" Returns:\n",
" A string summarizing the execution results (stdout, stderr, errors, plots, dataframes if any).\n",
" \"\"\"\n",
" supported_languages = [\"python\", \"bash\", \"sql\", \"c\", \"java\"]\n",
" language = language.lower()\n",
"\n",
" if language not in supported_languages:\n",
" return f\"❌ Unsupported language: {language}. Supported languages are: {', '.join(supported_languages)}\"\n",
"\n",
" result = interpreter_instance.execute_code(code, language=language)\n",
"\n",
" response = []\n",
"\n",
" if result[\"status\"] == \"success\":\n",
" response.append(f\"✅ Code executed successfully in **{language.upper()}**\")\n",
"\n",
" if result.get(\"stdout\"):\n",
" response.append(\"\\n**Standard Output:**\\n```\\n\" + result[\"stdout\"].strip() + \"\\n```\")\n",
"\n",
" if result.get(\"stderr\"):\n",
" response.append(\n",
" \"\\n**Standard Error (if any):**\\n```\\n\"\n",
" + result[\"stderr\"].strip() + \"\\n```\")\n",
"\n",
" if result.get(\"result\") is not None:\n",
" response.append(\n",
" \"\\n**Execution Result:**\\n```\\n\"\n",
" + str(result[\"result\"]).strip() + \"\\n```\")\n",
"\n",
" if result.get(\"dataframes\"):\n",
" for df_info in result[\"dataframes\"]:\n",
" response.append(f\"\\n**DataFrame `{df_info['name']}` (Shape: {df_info['shape']})**\")\n",
" df_preview = pd.DataFrame(df_info[\"head\"])\n",
" response.append(\"First 5 rows:\\n```\\n\" + str(df_preview) + \"\\n```\")\n",
"\n",
" if result.get(\"plots\"):\n",
" response.append(f\"\\n**Generated {len(result['plots'])} plot(s)** (Image data returned separately)\")\n",
"\n",
" else:\n",
" response.append(f\"❌ Code execution failed in **{language.upper()}**\")\n",
" if result.get(\"stderr\"):\n",
" response.append(\"\\n**Error Log:**\\n```\\n\" + result[\"stderr\"].strip() + \"\\n```\")\n",
"\n",
" return \"\\n\".join(response)"
]
},
{
"cell_type": "markdown",
"id": "c02491df-6943-4dcc-b477-4c876d6b200c",
"metadata": {},
"source": [
"## DOCUMENT PROCESSING"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cf052d13-a91a-4271-9a37-358bd34d712b",
"metadata": {},
"outputs": [],
"source": [
"# document processing\n",
"import os\n",
"import uuid\n",
"import requests\n",
"import tempfile\n",
"from PIL import Image\n",
"import pytesseract\n",
"import pandas as pd\n",
"from urllib.parse import urlparse\n",
"from langchain_core.tools import tool\n",
"from typing import List, Dict, Any, Optional"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e0cd532e-644e-4a5a-a90e-53ba66a40250",
"metadata": {},
"outputs": [],
"source": [
"@tool\n",
"def save_and_read_file(content: str, filename: Optional[str] = None) -> str:\n",
" \"\"\"\n",
" Save content to a file and return the path.\n",
" Args:\n",
" content (str): the content to save to the file\n",
" filename (str, optional): the name of the file. If not provided, a random name file will be created.\n",
" \"\"\"\n",
" temp_dir = tempfile.gettempdir()\n",
" if filename is None:\n",
" temp_file = tempfile.NamedTemporaryFile(delete=False, dir=temp_dir)\n",
" filepath = temp_file.name\n",
" else:\n",
" filepath = os.path.join(temp_dir, filename)\n",
"\n",
" with open(filepath, \"w\") as f:\n",
" f.write(content)\n",
"\n",
" return f\"File saved to {filepath}. You can read this file to process its contents.\"\n",
"\n",
"@tool\n",
"def download_file_from_url(url: str, filename: Optional[str] = None) -> str:\n",
" \"\"\"\n",
" Download a file from a URL and save it to a temporary location.\n",
" Args:\n",
" url (str): the URL of the file to download.\n",
" filename (str, optional): the name of the file. If not provided, a random name file will be created.\n",
" \"\"\"\n",
" try:\n",
" # Parse URL to get filename if not provided\n",
" if not filename:\n",
" path = urlparse(url).path\n",
" filename = os.path.basename(path)\n",
" if not filename:\n",
" filename = f\"downloaded_{uuid.uuid4().hex[:8]}\"\n",
"\n",
" # Create temporary file\n",
" temp_dir = tempfile.gettempdir()\n",
" filepath = os.path.join(temp_dir, filename)\n",
"\n",
" # Download the file\n",
" response = requests.get(url, stream=True)\n",
" response.raise_for_status()\n",
"\n",
" # Save the file\n",
" with open(filepath, \"wb\") as f:\n",
" for chunk in response.iter_content(chunk_size=8192):\n",
" f.write(chunk)\n",
"\n",
" return f\"File downloaded to {filepath}. You can read this file to process its contents.\"\n",
" except Exception as e:\n",
" return f\"Error downloading file: {str(e)}\"\n",
"\n",
"@tool\n",
"def extract_text_from_image(image_path: str) -> str:\n",
" \"\"\"\n",
" Extract text from an image using OCR library pytesseract (if available).\n",
" Args:\n",
" image_path (str): the path to the image file.\n",
" \"\"\"\n",
" try:\n",
" # Open the image\n",
" image = Image.open(image_path)\n",
"\n",
" # Extract text from the image\n",
" text = pytesseract.image_to_string(image)\n",
"\n",
" return f\"Extracted text from image:\\n\\n{text}\"\n",
" except Exception as e:\n",
" return f\"Error extracting text from image: {str(e)}\"\n",
"\n",
"@tool\n",
"def analyze_csv_file(file_path: str, query: str) -> str:\n",
" \"\"\"\n",
" Analyze a CSV file using pandas and answer a question about it.\n",
" Args:\n",
" file_path (str): the path to the CSV file.\n",
" query (str): Question about the data\n",
" \"\"\"\n",
" try:\n",
" # Read the CSV file\n",
" df = pd.read_csv(file_path)\n",
"\n",
" # Run various analyses based on the query\n",
" result = f\"CSV file loaded with {len(df)} rows and {len(df.columns)} columns.\\n\"\n",
" result += f\"Columns: {', '.join(df.columns)}\\n\\n\"\n",
"\n",
" # Add summary statistics\n",
" result += \"Summary statistics:\\n\"\n",
" result += str(df.describe())\n",
"\n",
" return result\n",
"\n",
" except Exception as e:\n",
" return f\"Error analyzing CSV file: {str(e)}\"\n",
"\n",
"@tool\n",
"def analyze_excel_file(file_path: str, query: str) -> str:\n",
" \"\"\"\n",
" Analyze an Excel file using pandas and answer a question about it.\n",
" Args:\n",
" file_path (str): the path to the Excel file.\n",
" query (str): Question about the data\n",
" \"\"\"\n",
" try:\n",
" # Read the Excel file\n",
" df = pd.read_excel(file_path)\n",
"\n",
" # Run various analyses based on the query\n",
" result = (\n",
" f\"Excel file loaded with {len(df)} rows and {len(df.columns)} columns.\\n\"\n",
" )\n",
" result += f\"Columns: {', '.join(df.columns)}\\n\\n\"\n",
"\n",
" # Add summary statistics\n",
" result += \"Summary statistics:\\n\"\n",
" result += str(df.describe())\n",
"\n",
" return result\n",
"\n",
" except Exception as e:\n",
" return f\"Error analyzing Excel file: {str(e)}\"\n"
]
},
{
"cell_type": "markdown",
"id": "2747e5da-61fb-4c0a-ae9e-4e09f6c490e0",
"metadata": {},
"source": [
"## IMAGE PROCESSING"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8304d8c5-2a28-4ba6-980d-86a14592eb60",
"metadata": {},
"outputs": [],
"source": [
"# image processing\n",
"import os\n",
"import io\n",
"import uuid\n",
"import base64\n",
"import numpy as np\n",
"from PIL import Image\n",
"from langchain_core.tools import tool\n",
"from typing import List, Dict, Any, Optional\n",
"from PIL import Image, ImageDraw, ImageFont, ImageEnhance, ImageFilter"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b9766e75-42b6-413c-96d4-ccb3380e8498",
"metadata": {},
"outputs": [],
"source": [
"# Helper functions for image processing\n",
"def encode_image(image_path: str) -> str:\n",
" \"\"\"Convert an image file to base64 string.\"\"\"\n",
" with open(image_path, \"rb\") as image_file:\n",
" return base64.b64encode(image_file.read()).decode(\"utf-8\")\n",
"\n",
"def decode_image(base64_string: str) -> Image.Image:\n",
" \"\"\"Convert a base64 string to a PIL Image.\"\"\"\n",
" image_data = base64.b64decode(base64_string)\n",
" return Image.open(io.BytesIO(image_data))\n",
"\n",
"def save_image(image: Image.Image, directory: str = \"image_outputs\") -> str:\n",
" \"\"\"Save a PIL Image to disk and return the path.\"\"\"\n",
" os.makedirs(directory, exist_ok=True)\n",
" image_id = str(uuid.uuid4())\n",
" image_path = os.path.join(directory, f\"{image_id}.png\")\n",
" image.save(image_path)\n",
" return image_path\n",
"\n",
"@tool\n",
"def analyze_image(image_base64: str) -> Dict[str, Any]:\n",
" \"\"\"\n",
" Analyze basic properties of an image (size, mode, color analysis, thumbnail preview).\n",
" Args:\n",
" image_base64 (str): Base64 encoded image string\n",
" Returns:\n",
" Dictionary with analysis result\n",
" \"\"\"\n",
" try:\n",
" img = decode_image(image_base64)\n",
" width, height = img.size\n",
" mode = img.mode\n",
"\n",
" if mode in (\"RGB\", \"RGBA\"):\n",
" arr = np.array(img)\n",
" avg_colors = arr.mean(axis=(0, 1))\n",
" dominant = [\"Red\", \"Green\", \"Blue\"][np.argmax(avg_colors[:3])]\n",
" brightness = avg_colors.mean()\n",
" color_analysis = {\n",
" \"average_rgb\": avg_colors.tolist(),\n",
" \"brightness\": brightness,\n",
" \"dominant_color\": dominant,\n",
" }\n",
" else:\n",
" color_analysis = {\"note\": f\"No color analysis for mode {mode}\"}\n",
"\n",
" thumbnail = img.copy()\n",
" thumbnail.thumbnail((100, 100))\n",
" thumb_path = save_image(thumbnail, \"thumbnails\")\n",
" thumbnail_base64 = encode_image(thumb_path)\n",
"\n",
" return {\n",
" \"dimensions\": (width, height),\n",
" \"mode\": mode,\n",
" \"color_analysis\": color_analysis,\n",
" \"thumbnail\": thumbnail_base64,\n",
" }\n",
" except Exception as e:\n",
" return {\"error\": str(e)}\n",
"\n",
"@tool\n",
"def transform_image(image_base64: str, operation: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:\n",
" \"\"\"\n",
" Apply transformations: resize, rotate, crop, flip, brightness, contrast, blur, sharpen, grayscale.\n",
" Args:\n",
" image_base64 (str): Base64 encoded input image\n",
" operation (str): Transformation operation\n",
" params (Dict[str, Any], optional): Parameters for the operation\n",
" Returns:\n",
" Dictionary with transformed image (base64)\n",
" \"\"\"\n",
" try:\n",
" img = decode_image(image_base64)\n",
" params = params or {}\n",
"\n",
" if operation == \"resize\":\n",
" img = img.resize(\n",
" (\n",
" params.get(\"width\", img.width // 2),\n",
" params.get(\"height\", img.height // 2),\n",
" )\n",
" )\n",
" elif operation == \"rotate\":\n",
" img = img.rotate(params.get(\"angle\", 90), expand=True)\n",
" elif operation == \"crop\":\n",
" img = img.crop(\n",
" (\n",
" params.get(\"left\", 0),\n",
" params.get(\"top\", 0),\n",
" params.get(\"right\", img.width),\n",
" params.get(\"bottom\", img.height),\n",
" )\n",
" )\n",
" elif operation == \"flip\":\n",
" if params.get(\"direction\", \"horizontal\") == \"horizontal\":\n",
" img = img.transpose(Image.FLIP_LEFT_RIGHT)\n",
" else:\n",
" img = img.transpose(Image.FLIP_TOP_BOTTOM)\n",
" elif operation == \"adjust_brightness\":\n",
" img = ImageEnhance.Brightness(img).enhance(params.get(\"factor\", 1.5))\n",
" elif operation == \"adjust_contrast\":\n",
" img = ImageEnhance.Contrast(img).enhance(params.get(\"factor\", 1.5))\n",
" elif operation == \"blur\":\n",
" img = img.filter(ImageFilter.GaussianBlur(params.get(\"radius\", 2)))\n",
" elif operation == \"sharpen\":\n",
" img = img.filter(ImageFilter.SHARPEN)\n",
" elif operation == \"grayscale\":\n",
" img = img.convert(\"L\")\n",
" else:\n",
" return {\"error\": f\"Unknown operation: {operation}\"}\n",
"\n",
" result_path = save_image(img)\n",
" result_base64 = encode_image(result_path)\n",
" return {\"transformed_image\": result_base64}\n",
"\n",
" except Exception as e:\n",
" return {\"error\": str(e)}\n",
"\n",
"@tool\n",
"def draw_on_image(image_base64: str, drawing_type: str, params: Dict[str, Any]) -> Dict[str, Any]:\n",
" \"\"\"\n",
" Draw shapes (rectangle, circle, line) or text onto an image.\n",
" Args:\n",
" image_base64 (str): Base64 encoded input image\n",
" drawing_type (str): Drawing type\n",
" params (Dict[str, Any]): Drawing parameters\n",
" Returns:\n",
" Dictionary with result image (base64)\n",
" \"\"\"\n",
" try:\n",
" img = decode_image(image_base64)\n",
" draw = ImageDraw.Draw(img)\n",
" color = params.get(\"color\", \"red\")\n",
"\n",
" if drawing_type == \"rectangle\":\n",
" draw.rectangle(\n",
" [params[\"left\"], params[\"top\"], params[\"right\"], params[\"bottom\"]],\n",
" outline=color,\n",
" width=params.get(\"width\", 2),\n",
" )\n",
" elif drawing_type == \"circle\":\n",
" x, y, r = params[\"x\"], params[\"y\"], params[\"radius\"]\n",
" draw.ellipse(\n",
" (x - r, y - r, x + r, y + r),\n",
" outline=color,\n",
" width=params.get(\"width\", 2),\n",
" )\n",
" elif drawing_type == \"line\":\n",
" draw.line(\n",
" (\n",
" params[\"start_x\"],\n",
" params[\"start_y\"],\n",
" params[\"end_x\"],\n",
" params[\"end_y\"],\n",
" ),\n",
" fill=color,\n",
" width=params.get(\"width\", 2),\n",
" )\n",
" elif drawing_type == \"text\":\n",
" font_size = params.get(\"font_size\", 20)\n",
" try:\n",
" font = ImageFont.truetype(\"arial.ttf\", font_size)\n",
" except IOError:\n",
" font = ImageFont.load_default()\n",
" draw.text(\n",
" (params[\"x\"], params[\"y\"]),\n",
" params.get(\"text\", \"Text\"),\n",
" fill=color,\n",
" font=font,\n",
" )\n",
" else:\n",
" return {\"error\": f\"Unknown drawing type: {drawing_type}\"}\n",
"\n",
" result_path = save_image(img)\n",
" result_base64 = encode_image(result_path)\n",
" return {\"result_image\": result_base64}\n",
"\n",
" except Exception as e:\n",
" return {\"error\": str(e)}\n",
"\n",
"@tool\n",
"def generate_simple_image(image_type: str, width: int = 500, height: int = 500, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:\n",
" \"\"\"\n",
" Generate a simple image (gradient, noise, pattern, chart).\n",
" Args:\n",
" image_type (str): Type of image\n",
" width (int), height (int)\n",
" params (Dict[str, Any], optional): Specific parameters\n",
" Returns:\n",
" Dictionary with generated image (base64)\n",
" \"\"\"\n",
" try:\n",
" params = params or {}\n",
"\n",
" if image_type == \"gradient\":\n",
" direction = params.get(\"direction\", \"horizontal\")\n",
" start_color = params.get(\"start_color\", (255, 0, 0))\n",
" end_color = params.get(\"end_color\", (0, 0, 255))\n",
"\n",
" img = Image.new(\"RGB\", (width, height))\n",
" draw = ImageDraw.Draw(img)\n",
"\n",
" if direction == \"horizontal\":\n",
" for x in range(width):\n",
" r = int(\n",
" start_color[0] + (end_color[0] - start_color[0]) * x / width\n",
" )\n",
" g = int(\n",
" start_color[1] + (end_color[1] - start_color[1]) * x / width\n",
" )\n",
" b = int(\n",
" start_color[2] + (end_color[2] - start_color[2]) * x / width\n",
" )\n",
" draw.line([(x, 0), (x, height)], fill=(r, g, b))\n",
" else:\n",
" for y in range(height):\n",
" r = int(\n",
" start_color[0] + (end_color[0] - start_color[0]) * y / height\n",
" )\n",
" g = int(\n",
" start_color[1] + (end_color[1] - start_color[1]) * y / height\n",
" )\n",
" b = int(\n",
" start_color[2] + (end_color[2] - start_color[2]) * y / height\n",
" )\n",
" draw.line([(0, y), (width, y)], fill=(r, g, b))\n",
"\n",
" elif image_type == \"noise\":\n",
" noise_array = np.random.randint(0, 256, (height, width, 3), dtype=np.uint8)\n",
" img = Image.fromarray(noise_array, \"RGB\")\n",
"\n",
" else:\n",
" return {\"error\": f\"Unsupported image_type {image_type}\"}\n",
"\n",
" result_path = save_image(img)\n",
" result_base64 = encode_image(result_path)\n",
" return {\"generated_image\": result_base64}\n",
"\n",
" except Exception as e:\n",
" return {\"error\": str(e)}\n",
"\n",
"@tool\n",
"def combine_images(images_base64: List[str], operation: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:\n",
" \"\"\"\n",
" Combine multiple images (collage, stack, blend).\n",
" Args:\n",
" images_base64 (List[str]): List of base64 images\n",
" operation (str): Combination type\n",
" params (Dict[str, Any], optional)\n",
" Returns:\n",
" Dictionary with combined image (base64)\n",
" \"\"\"\n",
" try:\n",
" images = [decode_image(b64) for b64 in images_base64]\n",
" params = params or {}\n",
"\n",
" if operation == \"stack\":\n",
" direction = params.get(\"direction\", \"horizontal\")\n",
" if direction == \"horizontal\":\n",
" total_width = sum(img.width for img in images)\n",
" max_height = max(img.height for img in images)\n",
" new_img = Image.new(\"RGB\", (total_width, max_height))\n",
" x = 0\n",
" for img in images:\n",
" new_img.paste(img, (x, 0))\n",
" x += img.width\n",
" else:\n",
" max_width = max(img.width for img in images)\n",
" total_height = sum(img.height for img in images)\n",
" new_img = Image.new(\"RGB\", (max_width, total_height))\n",
" y = 0\n",
" for img in images:\n",
" new_img.paste(img, (0, y))\n",
" y += img.height\n",
" else:\n",
" return {\"error\": f\"Unsupported combination operation {operation}\"}\n",
"\n",
" result_path = save_image(new_img)\n",
" result_base64 = encode_image(result_path)\n",
" return {\"combined_image\": result_base64}\n",
"\n",
" except Exception as e:\n",
" return {\"error\": str(e)}\n"
]
},
{
"cell_type": "markdown",
"id": "cb966ca4-1ccf-4a14-8c7c-960b1d8e1c55",
"metadata": {},
"source": [
"## AUDIO PROCESSING"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9b05ce05-a577-4473-bb05-0d58602f71c2",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"id": "57a4fcb2-59ae-44d6-9d6a-ea1ab5acae0f",
"metadata": {},
"source": [
"# AGENT"
]
},
{
"cell_type": "markdown",
"id": "32b57eeb-4260-43bd-9898-2edbe3be1281",
"metadata": {},
"source": [
"The Agent is designed using LangGraph which is a production-ready framework deveoped by LangChain. The control flow of the agent is designed using a directed graph structure to move a state object from node to node through decision edges. It simplifies the design of even complex Agent application by relying on simple components that all work together."
]
},
{
"cell_type": "markdown",
"id": "e6b7a8d7-e174-42a1-8bfb-9407bfd3c518",
"metadata": {},
"source": [
"## RETRIEVER"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7e391c4c-d019-4baf-bf53-fe24244cac0c",
"metadata": {},
"outputs": [],
"source": [
"# build a retriever\n",
"embeddings = HuggingFaceEmbeddings(model_name=\"sentence-transformers/all-mpnet-base-v2\") # set the model to generate embeddings; dim=768\n",
"supabase, Client = create_client(os.environ.get(\"SUPABASE_URL\"), os.environ.get(\"SUPABASE_SERVICE_KEY\"))\n",
"vector_store = SupabaseVectorStore(client=supabase, embedding= embeddings, table_name=\"documents\", query_name=\"match_documents_langchain\")\n",
"create_retriever_tool = create_retriever_tool(retriever=vector_store.as_retriever(), name=\"Question Retriever\", description=\"Retrieve similar questions from a vector store.\")"
]
},
{
"cell_type": "markdown",
"id": "26dd5168-8602-4a70-ae77-6ed834a762f9",
"metadata": {},
"source": [
"## PROMPTS"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b6682591-6e1c-4c99-b0ae-b8eb0db470d1",
"metadata": {},
"outputs": [],
"source": [
"# load the system prompt from the file\n",
"with open(\"../prompts/system_prompt.txt\", \"r\", encoding=\"utf-8\") as f:\n",
" system_prompt = f.read()\n",
"print(f'SYSTEM PROMPT:\\n{system_prompt}')\n",
"\n",
"# System message\n",
"sys_msg = SystemMessage(content=system_prompt)"
]
},
{
"cell_type": "markdown",
"id": "a8f38f2a-8c90-4e2f-b59e-f49da81ed3c6",
"metadata": {},
"source": [
"## TOOLS"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f60060ca-6130-4c15-a298-e289de9f6b6d",
"metadata": {},
"outputs": [],
"source": [
"# list all agent tools\n",
"tools = [web_search, wiki_search, similar_question_search, arxiv_search, multiply, add, subtract, divide, modulus, power, square_root, count_substring, save_and_read_file, download_file_from_url, extract_text_from_image, analyze_csv_file, analyze_excel_file, execute_code_multilang, analyze_image, transform_image, draw_on_image, generate_simple_image, combine_images]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "46cf257e-7cd1-4bb4-8b86-6f9a4f4f74f8",
"metadata": {},
"outputs": [],
"source": [
"# Build the agent graph\n",
"def build_graph(provider: str = \"huggingface-qwen\"):\n",
" \"\"\"Build the LangGraph Agent\"\"\"\n",
" # Load environment variables from .env file\n",
" if provider == \"google\": # Google Gemini\n",
" llm = ChatGoogleGenerativeAI(model=\"gemini-2.0-flash\", temperature=0)\n",
" elif provider == \"groq\": # Groq https://console.groq.com/docs/models\n",
" llm = ChatGroq(model=\"qwen-qwq-32b\", temperature=0) # optional : qwen-qwq-32b gemma2-9b-it\n",
" elif provider == \"huggingface-qwen\":\n",
" llm = ChatHuggingFace(llm=HuggingFaceEndpoint(repo_id = \"Qwen/Qwen2.5-Coder-32B-Instruct\"))\n",
" elif provider == \"huggingface-llama\":\n",
" llm = ChatHuggingFace(llm=HuggingFaceEndpoint(repo_id=\"TinyLlama/TinyLlama-1.1B-Chat-v1.0\", task=\"text-generation\", max_new_tokens=1024, do_sample=False, repetition_penalty=1.03, temperature=0), verbose=True)\n",
" else:\n",
" raise ValueError(\"Invalid provider. Choose 'google', 'groq', 'huggingface-qwen' or 'huggingface-llama'.\")\n",
" \n",
" llm_with_tools = llm.bind_tools(tools) # Bind tools to LLM\n",
"\n",
" # Node\n",
" def assistant(state: MessagesState):\n",
" \"\"\"Assistant node\"\"\"\n",
" return {\"messages\": [llm_with_tools.invoke(state[\"messages\"])]}\n",
" \n",
" def retriever(state: MessagesState):\n",
" \"\"\"Retriever node\"\"\"\n",
" similar_question = vector_store.similarity_search(state[\"messages\"][0].content)\n",
" example_msg = HumanMessage(content=f\"Here I provide a similar question and answer for reference: \\n\\n{similar_question[0].page_content}\")\n",
" return {\"messages\": [sys_msg] + state[\"messages\"] + [example_msg]}\n",
"\n",
" # create nodes - decision points\n",
" builder = StateGraph(MessagesState)\n",
" builder.add_node(\"retriever\", retriever) \n",
" builder.add_node(\"assistant\", assistant)\n",
" builder.add_node(\"tools\", ToolNode(tools)) # equip the agents with the list of tools\n",
"\n",
" # connect nodes - control flow\n",
" builder.add_edge(START, \"retriever\")\n",
" builder.add_edge(\"retriever\", \"assistant\")\n",
" builder.add_conditional_edges(\"assistant\", tools_condition)\n",
" builder.add_edge(\"tools\", \"assistant\")\n",
"\n",
" # Compile graph\n",
" return builder.compile()"
]
},
{
"cell_type": "markdown",
"id": "5d5a4d4d-a497-4fa9-acb1-89b6967964ea",
"metadata": {},
"source": [
"# APP INTERGRATION"
]
},
{
"cell_type": "markdown",
"id": "c1b877bf-5e62-4a01-9e71-17915de09dfd",
"metadata": {},
"source": [
"To integrate the Agent solution into the submission API, solutions to covered GAIA questions will be generated prior to submission and stored in a database.\n",
"The Agent will then have to retrieve the answer to the actual questions thrown at it during the assessment from its solution bank.\n",
"All tools and related artefacts for the Agent will also be made public in the project folder to meet credibility requirements for the course assessment.\n",
"\n",
"Integration Changes:\n",
" - include scripts to house the tools in a dedicated folder within the project\n",
" - include scripts defining the agent in a dedicated folder within the project\n",
" - include a text file with the system prompt guiding the agent in a dedicated folder\n",
" - ensure the agent and tools directory are recognized as packages\n",
" - modify the app.py script to load the updated agent class\n",
" - update the readme file\n",
" - update the requirements file\n",
" - include the jupyter notebook"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f4dcdae5-a0cf-4b53-b3da-2511651ecf2b",
"metadata": {},
"outputs": [],
"source": [
"# testing\n",
"if __name__ == \"__main__\":\n",
" question = \"When was a picture of St. Thomas Aquinas first added to the Wikipedia page on the Principle of double effect?\"\n",
" graph = build_graph(provider=\"huggingface-llama\")\n",
" messages = [HumanMessage(content=question)]\n",
" messages = graph.invoke({\"messages\": messages})\n",
" for m in messages[\"messages\"]:\n",
" m.pretty_print()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6141142d-3502-4db3-a578-a06586a025af",
"metadata": {},
"outputs": [],
"source": [
"class GAIAAgent:\n",
" \"\"\"A langgraph agent for attempting the GAIA benchmark.\"\"\"\n",
" def __init__(self):\n",
" print(\"Agent initialized.\")\n",
" self.graph = build_graph() # instantiate the Agent\n",
"\n",
" def __call__(self, question: str) -> str:\n",
" print(f\"Agent received question (first 50 chars): {question[:50]}...\")\n",
" messages = [HumanMessage(content=question)]\n",
" result = self.graph.invoke({\"messages\": messages})\n",
" answer = result['messages'][-1].content # retrieve solution similar to the current question from prepared dump\n",
" return answer # submit"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"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"
},
"widgets": {
"application/vnd.jupyter.widget-state+json": {
"state": {},
"version_major": 2,
"version_minor": 0
}
}
},
"nbformat": 4,
"nbformat_minor": 5
}