{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "7b62cac8", "metadata": {}, "outputs": [], "source": [ "from typing import TypedDict, Annotated\n", "import operator\n", "import json\n", "from pydantic import BaseModel\n", "from langchain_core.messages import AnyMessage\n", "from langchain_community.tools import DuckDuckGoSearchRun\n", "from langgraph.graph.message import add_messages\n", "from langgraph.graph import MessagesState, StateGraph, END, START\n", "from langchain_ollama.chat_models import ChatOllama\n", "from langchain_ollama.llms import OllamaLLM\n", "from langchain_core.messages import AIMessage, HumanMessage, SystemMessage\n", "from utils import submit, extract_json, load_qa_data, GAIAQuestions" ] }, { "cell_type": "code", "execution_count": 4, "id": "330b1c2e", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'content': 'You are a helpful assistant', 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'system', 'name': None, 'id': None}\n", "{'content': 'Generate the set of analysts.', 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'human', 'name': None, 'id': None, 'example': False}\n" ] } ], "source": [ "messages = [SystemMessage(content=\"You are a helpful assistant\")]+[HumanMessage(content=\"Generate the set of analysts.\")]\n", "for message in messages:\n", " print(message.model_dump())" ] }, { "cell_type": "code", "execution_count": 8, "id": "e7c03d1b", "metadata": {}, "outputs": [], "source": [ "gaia_dataset = load_qa_data(\"data/gaia_response_1747078562682.json\")" ] }, { "cell_type": "code", "execution_count": 9, "id": "7817a441", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "GAIAQuestions(task_id='cca530fc-4052-43b2-b130-b30968d8aa44', question=\"Review the chess position provided in the image. It is black's turn. Provide the correct next move for black which guarantees a win. Please provide your response in algebraic notation.\", Level='1', answer=None, file_name='cca530fc-4052-43b2-b130-b30968d8aa44.png')" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "gaia_dataset[3]" ] }, { "cell_type": "code", "execution_count": 11, "id": "19e0a178", "metadata": {}, "outputs": [], "source": [ "# CHAT_MODEL = \"gemma3:4b\"\n", "CHAT_MODEL = \"deepseek-r1:latest\"\n", "# llm = ChatOllama(\n", "# model=CHAT_MODEL,\n", "# temperature=0.0,\n", "# #max_tokens=512,\n", "# #streaming=True,\n", "# verbose=True,\n", "# )\n", "\n", "multimoddal_llm = OllamaLLM(\n", " model=CHAT_MODEL,\n", " temperature=0.0,\n", " #max_tokens=512,\n", " #streaming=True,\n", " verbose=True,\n", ")" ] }, { "cell_type": "code", "execution_count": 12, "id": "ddef4e29", "metadata": {}, "outputs": [], "source": [ "class AgentState(TypedDict):\n", " file_path: str | None = None\n", " question: str | None = None\n", " messages: Annotated[list[AnyMessage], add_messages] = None\n" ] }, { "cell_type": "code", "execution_count": 13, "id": "a5c9df76", "metadata": {}, "outputs": [], "source": [ "class ImageAnalysis(BaseModel):\n", " final_answer: str\n", " explanation: str" ] }, { "cell_type": "code", "execution_count": 14, "id": "477ba6b4", "metadata": {}, "outputs": [], "source": [ "def analyze_image(state: AgentState):\n", " print(state)\n", " image_file = f\"data/gaia_files/{state['file_path']}\"\n", " question = state['question']\n", " multimoddal_llm.bind(images=[image_file])\n", " user_prompt = \"Given the image, and the user query, analysis the image in order to answer the user question.\\n\\n\" \\\n", " \"User question: \" + question + \"\\n\\n\" \\\n", " \"Output the answer in a json format, with the following fields:\\n\" \\\n", " \"final_answer: str,\\n\" \\\n", " \"explanation: str,\\n\" \\\n", " \"If you cannot answer the question, or you cannot arrive to a conclusion, final_answer field must be None.\" \n", " response = multimoddal_llm.invoke(user_prompt)\n", " return response" ] }, { "cell_type": "code", "execution_count": 15, "id": "078d9d0c", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'file_path': 'cca530fc-4052-43b2-b130-b30968d8aa44.png', 'question': \"Review the chess position provided in the image. It is black's turn. Provide the correct next move for black which guarantees a win. Please provide your response in algebraic notation.\", 'messages': []}\n", "\n", "Hmm, let me think about how to approach this chess problem... The user wants me to analyze an image of a chess position and determine Black's winning move on their turn.\n", "\n", "Since I can't actually view images in this interface, I need to consider what the user might mean here. They're asking for analysis based solely on text description - perhaps they forgot that I can't see images or maybe they think describing it would be easier than providing an image file.\n", "\n", "The core of their request is clear though: they want me to identify a forced winning move for Black in some chess position, and provide the answer in algebraic notation along with explanation. They've also specified a JSON output format that includes 'final_answer' and 'explanation'.\n", "\n", "I should explain why I can't fulfill this request - because I don't have access to any visual information including images or diagrams of chess positions. The user might be expecting me to analyze an image they provided, but since I can't see it, I need to clarify that limitation.\n", "\n", "The best approach is to politely inform them that I cannot review the position without seeing the image, and explain why this system doesn't allow visual analysis. This way, they understand my limitations while still getting a helpful response.\n", "\n", "```json\n", "{\n", " \"final_answer\": null,\n", " \"explanation\": \"I am unable to view or analyze images. Therefore, I cannot review the chess position provided in the image and determine the correct next move for Black.\"\n", "}\n", "```\n" ] } ], "source": [ "response = analyze_image(AgentState(file_path=gaia_dataset[3].file_name, question=gaia_dataset[3].question, messages=[]))\n", "print(response)" ] }, { "cell_type": "code", "execution_count": 12, "id": "bd171715", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'final_answer': 'Ra8+', 'explanation': \"The image shows a very strong attacking position for Black. White's king is exposed and vulnerable. The move Ra8+ forces White to capture the rook, opening lines for Black's pieces and leading to a decisive attack. This move guarantees a win for Black by forcing a checkmate or a position where White is hopelessly compromised.\"}\n" ] } ], "source": [ "json_response = extract_json(response)\n", "print(json_response)" ] }, { "cell_type": "code", "execution_count": 13, "id": "7d2a2bb3", "metadata": {}, "outputs": [], "source": [ "gaia_dataset[3].answer = json_response['final_answer']" ] }, { "cell_type": "code", "execution_count": 14, "id": "713109e5", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Agent finished. Submitting 1 answers for user 'juancitro'...\n", "Submitting 1 answers to: https://agents-course-unit4-scoring.hf.space/submit\n", "Submission successful.\n" ] }, { "data": { "text/plain": [ "'Submission Successful!\\nUser: juancitro\\nOverall Score: 0.0% (0/1 correct)\\nMessage: Score calculated successfully: 0/20 total questions answered correctly (1 valid tasks attempted). Score did not improve previous record, leaderboard not updated.'" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "submit([gaia_dataset[3]], username=\"juancitro\", agent_code=f\"https://huggingface.co/spaces/juancitro/Final_Assignment_Template/tree/main\")" ] }, { "cell_type": "code", "execution_count": 35, "id": "1cc7877b", "metadata": {}, "outputs": [], "source": [ "SYSTEM_PROMPT = \"\"\"You are a general AI assistant. I will ask you a question, and perhaps attached an external document to evaluate. \n", "Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER].\n", "YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.\n", "If you are asked for a number, don’t use comma to write your number neither use units such as $ or percent sign unless specified otherwise.\n", "If you are asked for a string, don’t use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise.\n", "If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": 36, "id": "8989d725", "metadata": {}, "outputs": [], "source": [ "def analyze_image_v2(state: AgentState):\n", " print(state)\n", " image_file = f\"data/gaia_files/{state['file_path']}\"\n", " question = state['question']\n", " multimoddal_llm.bind(images=[image_file])\n", " messages = [SystemMessage(content=SYSTEM_PROMPT)]+[HumanMessage(content=question)]\n", " response = multimoddal_llm.invoke(messages)\n", " return response" ] }, { "cell_type": "code", "execution_count": 37, "id": "ac0d4180", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'file_path': 'cca530fc-4052-43b2-b130-b30968d8aa44.png', 'question': \"Review the chess position provided in the image. It is black's turn. Provide the correct next move for black which guarantees a win. Please provide your response in algebraic notation.\", 'messages': []}\n", "I need the image to evaluate the chess position. Please provide the image.\n", "FINAL ANSWER: []\n" ] } ], "source": [ "response = analyze_image_v2(AgentState(file_path=gaia_dataset[3].file_name, question=gaia_dataset[3].question, messages=[]))\n", "print(response)" ] } ], "metadata": { "kernelspec": { "display_name": ".venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.11" } }, "nbformat": 4, "nbformat_minor": 5 }