Spaces:
Sleeping
Sleeping
Second commit, grant certificate, and various tests
Browse filesFiles changed (20)
- .gitattributes+1
- .gitignore+5-1
- README.md+14-1
- basic_agent.py+32-7
- data/cats.jpegAdded
- data/gaia_files/1f975693-876d-457b-a649-393859e79bf3.mp3Added+3
- data/gaia_files/7bd855d8-463d-4ed5-93ca-5fe35145f733.xlsxAdded
- data/gaia_files/99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3.mp3Added+3
- data/gaia_files/cca530fc-4052-43b2-b130-b30968d8aa44.pngAdded
- data/gaia_files/f918266a-b3e0-4914-865d-4faa564f1aef.pyAdded+35
- data/gaia_response_1747078562682.jsonAdded+138
- langgraph_agent.pyAdded+93
- openai_agent.pyAdded
- requirements.txt+11-3
- test_gemma3.ipynbAdded+320
- test_openai_based_agent.ipynbAdded
- test_opensource_agent.ipynbAdded
- test_qwen_25_omni.ipynbAdded+526
- tools.pyDeleted-19
- utils.pyAdded+89
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text*.mp3 filter=lfs diff=lfs merge=lfs -text
3 unmodified lines45673 unmodified lines*.pyc*.pyo*.pyd.env3 unmodified lines45678910113 unmodified lines*.pyc*.pyo*.pyd.env.DS_storemodels
11 unmodified lines1213141511 unmodified lineshf_oauth_expiration_minutes: 480---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference11 unmodified lines121314151617181920212223242526272811 unmodified lineshf_oauth_expiration_minutes: 480---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference### For Qwen 2.5 omni```pip uninstall transformerspip install git+https://github.com/huggingface/transformers@v4.51.3-Qwen2.5-Omni-previewpip install accelerate```To handle various types of audio and visual inputs (make sure your system has ffmpeg installed)```pip install qwen-omni-utils -U```
1 unmodified line234567825 unmodified lines3435363738395 unmodified lines454647484950515214 unmodified lines676869707172731 unmodified line7576777879808182838485861 unmodified linefrom langchain.prompts import PromptTemplatefrom langchain_ollama.chat_models import ChatOllamafrom langchain_ollama.llms import OllamaLLMfrom langchain.agents import AgentExecutor, create_react_agentfrom langchain_ollama import OllamaEmbeddingsfrom langchain_community.tools import DuckDuckGoSearchRun25 unmodified lines{tools}Use the following format:Question: the input question you must answer5 unmodified linesThought: I now know the final answerFinal Answer: the final answer to the original input questionBegin!Question: {input}Thought:{agent_scratchpad}"""14 unmodified linesprint("Agent initialized.")self.llm = llmself.embeddings = embeddingsself.tools = toolsself.prompt = promptself.graph = self.__initialize_graph()1 unmodified lineagent = create_react_agent(llm, self.tools, self.prompt)agent_executor = AgentExecutor(agent=agent, tools=self.tools, verbose=True)return agent_executordef __call__(self, question: str) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")fixed_answer = self.graph.invoke({"input": question})print(f"Agent returning fixed answer: {fixed_answer}")return fixed_answerbasic_agent = BasicAgent(tools=[DuckDuckGoSearchRun()])1 unmodified line234567825 unmodified lines34353637383940414243445 unmodified lines50515253545514 unmodified lines707172737475761 unmodified line787980818283848586878889909192939495969798991001011021031041051061071081091101111 unmodified linefrom langchain.prompts import PromptTemplatefrom langchain_ollama.chat_models import ChatOllamafrom langchain_ollama.llms import OllamaLLMfrom langchain.agents import AgentExecutor, create_react_agent, Toolfrom langchain_ollama import OllamaEmbeddingsfrom langchain_community.tools import DuckDuckGoSearchRun25 unmodified lines{tools}YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.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.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.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.Use the following format:Question: the input question you must answer5 unmodified linesThought: I now know the final answerFinal Answer: the final answer to the original input questionQuestion: {input}Thought:{agent_scratchpad}"""14 unmodified linesprint("Agent initialized.")self.llm = llmself.embeddings = embeddingsself.tools = tools + self.setup_base_tools()self.prompt = promptself.graph = self.__initialize_graph()1 unmodified lineagent = create_react_agent(llm, self.tools, self.prompt)agent_executor = AgentExecutor(agent=agent, tools=self.tools, verbose=True)return agent_executordef setup_base_tools(self):search = DuckDuckGoSearchRun()duckduckgo_tool = Tool(name = 'DuckDuckGo Search',func = search.run,description = '''A wrapper around DuckDuckGo Search.Useful for when you need to answer questions about current events, and search some information in the web.Input should be a search query.''')tools = [duckduckgo_tool]return toolsdef __call__(self, question: str) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")fixed_answer = self.graph.invoke({"input": question})print(f"Agent returning fixed answer: {fixed_answer['output']}")return fixed_answer["output"]# basic_agent = BasicAgent(tools=[DuckDuckGoSearchRun()])basic_agent = BasicAgent()if __name__ == "__main__":# answer = basic_agent("What is the capital of France?")# print(type(answer))# print(answer)pass
123version https://git-lfs.github.com/spec/v1oid sha256:200f767e732b49efef5c05d128903ee4d2c34e66fdce7f5593ac123b2e637673size 280868123version https://git-lfs.github.com/spec/v1oid sha256:b218c951c1f888f0bbe6f46c080f57afc7c9348fffc7ba4da35749ff1e2ac40fsize 1793041234567891011121314151617181920212223242526272829303132333435from random import randintimport time
class UhOh(Exception): pass
class Hmm: def __init__(self): self.value = randint(-100, 100)
def Yeah(self): if self.value == 0: return True else: raise UhOh()
def Okay(): while True: yield Hmm()
def keep_trying(go, first_try=True): maybe = next(go) try: if maybe.Yeah(): return maybe.value except UhOh: if first_try: print("Working...") print("Please wait patiently...") time.sleep(0.1) return keep_trying(go, first_try=False)
if __name__ == "__main__": go = Okay() print(f"{keep_trying(go)}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138[ { "task_id": "8e867cd7-cff9-4e6c-867a-ff5ddc2550be", "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.", "Level": "1", "file_name": "", "true_answer": "3" }, { "task_id": "a1e91b78-d3d8-4675-bb8d-62741b4b68a6", "question": "In the video https://www.youtube.com/watch?v=L1vXCYZAYYM, what is the highest number of bird species to be on camera simultaneously?", "Level": "1", "file_name": "", "true_answer": "3" }, { "task_id": "2d83110e-a098-4ebb-9987-066c06fa42d0", "question": ".rewsna eht sa \"tfel\" drow eht fo etisoppo eht etirw ,ecnetnes siht dnatsrednu uoy fI", "Level": "1", "file_name": "", "true_answer": "right" }, { "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", "file_name": "cca530fc-4052-43b2-b130-b30968d8aa44.png" }, { "task_id": "4fc2f1ae-8625-45b5-ab34-ad4433bc21f8", "question": "Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?", "Level": "1", "file_name": "", "true_answer": "FunkMonk" }, { "task_id": "6f37996b-2ac7-44b0-8e68-6d28256631b4", "question": "Given this table defining * on the set S = {a, b, c, d, e}\n\n|*|a|b|c|d|e|\n|---|---|---|---|---|---|\n|a|a|b|c|b|d|\n|b|b|c|a|e|c|\n|c|c|a|b|b|a|\n|d|b|e|b|e|d|\n|e|d|b|a|d|c|\n\nprovide the subset of S involved in any possible counter-examples that prove * is not commutative. Provide your answer as a comma separated list of the elements in the set in alphabetical order.", "Level": "1", "file_name": "", "true_answer": "b, e" }, { "task_id": "9d191bce-651d-4746-be2d-7ef8ecadb9c2", "question": "Examine the video at https://www.youtube.com/watch?v=1htKBjuUWec.\n\nWhat does Teal'c say in response to the question \"Isn't that hot?\"", "Level": "1", "file_name": "", "true_answer": "extremely" }, { "task_id": "cabe07ed-9eca-40ea-8ead-410ef5e83f91", "question": "What is the surname of the equine veterinarian mentioned in 1.E Exercises from the chemistry materials licensed by Marisa Alviar-Agnew & Henry Agnew under the CK-12 license in LibreText's Introductory Chemistry materials as compiled 08/21/2023?", "Level": "1", "file_name": "", "true_answer": "Louvrier" }, { "task_id": "3cef3a44-215e-4aed-8e3b-b1e3f08063b7", "question": "I'm making a grocery list for my mom, but she's a professor of botany and she's a real stickler when it comes to categorizing things. I need to add different foods to different categories on the grocery list, but if I make a mistake, she won't buy anything inserted in the wrong category. Here's the list I have so far:\n\nmilk, eggs, flour, whole bean coffee, Oreos, sweet potatoes, fresh basil, plums, green beans, rice, corn, bell pepper, whole allspice, acorns, broccoli, celery, zucchini, lettuce, peanuts\n\nI need to make headings for the fruits and vegetables. Could you please create a list of just the vegetables from my list? If you could do that, then I can figure out how to categorize the rest of the list into the appropriate categories. But remember that my mom is a real stickler, so make sure that no botanical fruits end up on the vegetable list, or she won't get them when she's at the store. Please alphabetize the list of vegetables, and place each item in a comma separated list.", "Level": "1", "file_name": "", "true_answer": "broccoli, celery, fresh basil, lettuce, sweet potatoes" }, { "task_id": "99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3", "question": "Hi, I'm making a pie but I could use some help with my shopping list. I have everything I need for the crust, but I'm not sure about the filling. I got the recipe from my friend Aditi, but she left it as a voice memo and the speaker on my phone is buzzing so I can't quite make out what she's saying. Could you please listen to the recipe and list all of the ingredients that my friend described? I only want the ingredients for the filling, as I have everything I need to make my favorite pie crust. I've attached the recipe as Strawberry pie.mp3.\n\nIn your response, please only list the ingredients, not any measurements. So if the recipe calls for \"a pinch of salt\" or \"two cups of ripe strawberries\" the ingredients on the list would be \"salt\" and \"ripe strawberries\".\n\nPlease format your response as a comma separated list of ingredients. Also, please alphabetize the ingredients.", "Level": "1", "file_name": "99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3.mp3" }, { "task_id": "305ac316-eef6-4446-960a-92d80d542f82", "question": "Who did the actor who played Ray in the Polish-language version of Everybody Loves Raymond play in Magda M.? Give only the first name.", "Level": "1", "file_name": "", "true_answer": "Wojciech" }, { "task_id": "f918266a-b3e0-4914-865d-4faa564f1aef", "question": "What is the final numeric output from the attached Python code?", "Level": "1", "file_name": "f918266a-b3e0-4914-865d-4faa564f1aef.py", "true_answer": "0" }, { "task_id": "3f57289b-8c60-48be-bd80-01f8099ca449", "question": "How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?", "Level": "1", "file_name": "", "true_answer": "519" }, { "task_id": "1f975693-876d-457b-a649-393859e79bf3", "question": "Hi, I was out sick from my classes on Friday, so I'm trying to figure out what I need to study for my Calculus mid-term next week. My friend from class sent me an audio recording of Professor Willowbrook giving out the recommended reading for the test, but my headphones are broken :(\n\nCould you please listen to the recording for me and tell me the page numbers I'm supposed to go over? I've attached a file called Homework.mp3 that has the recording. Please provide just the page numbers as a comma-delimited list. And please provide the list in ascending order.", "Level": "1", "file_name": "1f975693-876d-457b-a649-393859e79bf3.mp3", "true_answer": "132, 133, 134, 197, 245" }, { "task_id": "840bfca7-4f7b-481a-8794-c560c340185d", "question": "On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?", "Level": "1", "file_name": "" }, { "task_id": "bda648d7-d618-4883-88f4-3466eabd860e", "question": "Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations.", "Level": "1", "file_name": "", "true_answer": "Saint Petersburg" }, { "task_id": "cf106601-ab4f-4af9-b045-5295fe67b37d", "question": "What country had the least number of athletes at the 1928 Summer Olympics? If there's a tie for a number of athletes, return the first in alphabetical order. Give the IOC country code as your answer.", "Level": "1", "file_name": "", "true_answer": "CUB" }, { "task_id": "a0c07678-e491-4bbc-8f0b-07405144218f", "question": "Who are the pitchers with the number before and after Taishō Tamai's number as of July 2023? Give them to me in the form Pitcher Before, Pitcher After, use their last names only, in Roman characters.", "Level": "1", "file_name": "" }, { "task_id": "7bd855d8-463d-4ed5-93ca-5fe35145f733", "question": "The attached Excel file contains the sales of menu items for a local fast-food chain. What were the total sales that the chain made from food (not including drinks)? Express your answer in USD with two decimal places.", "Level": "1", "file_name": "7bd855d8-463d-4ed5-93ca-5fe35145f733.xlsx", "true_answer": "89706.00" }, { "task_id": "5a0c1adf-205e-4841-a666-7c3ef95def9d", "question": "What is the first name of the only Malko Competition recipient from the 20th Century (after 1977) whose nationality on record is a country that no longer exists?", "Level": "1", "file_name": "", "true_answer": "Claus" }]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293import osfrom typing import TypedDict, Annotated, Literalimport operatorimport jsonimport pandas as pdfrom IPython.display import Image, displayimport soundfile as sffrom tqdm.notebook import tqdmfrom pydantic import BaseModelfrom langchain_community.utilities import WikipediaAPIWrapperfrom langchain_community.tools import WikipediaQueryRun, DuckDuckGoSearchRunfrom langchain_core.tools import Toolfrom langchain_experimental.utilities import PythonREPLfrom langchain_ollama.chat_models import ChatOllamafrom langchain_ollama.llms import OllamaLLMfrom langchain_core.messages import AIMessage, HumanMessage, SystemMessage, AnyMessage, ToolMessagefrom langgraph.graph.message import add_messagesfrom langgraph.graph import MessagesState, StateGraph, END, START, StateGraphfrom transformers import Qwen2_5OmniForConditionalGeneration, Qwen2_5OmniProcessorfrom qwen_omni_utils import process_mm_infofrom utils import load_qa_data, GAIAQuestions, extract_json, submit
class QWEN2_5OmniModelRun: def __init__(self, model_path: str = "./models/Qwen2.5-Omni-3B", local_files_only: bool = True, use_audio_in_video = False, return_audio = False): self.model_path = model_path self.use_audio_in_video = use_audio_in_video self.return_audio = return_audio self.model = Qwen2_5OmniForConditionalGeneration.from_pretrained(model_path, torch_dtype="auto", device_map="auto", local_files_only=local_files_only) self.model.disable_talker() self.processor = Qwen2_5OmniProcessor.from_pretrained(model_path, local_files_only=local_files_only)
def __parse_messages(self, messages: list[AnyMessage], file_path: str | None = None, file_type: Literal["audio", "video", "image"] | None = None) -> list[dict]: parsed_messages = [] for message in messages: if isinstance(message, SystemMessage): parsed_messages.append({"role": "system", "content": [{"type": "text", "text": message.content}]}) elif isinstance(message, HumanMessage): parsed_messages.append({"role": "user", "content": [ {"type": file_type, file_type: file_path}, {"type": "text", "text": message.content}, ] if file_type else [{"type": "text", "text": message.content}]}) elif isinstance(message, AIMessage): parsed_messages.append({"role": "assistant", "content": [{"type": "text", "text": message.content}]}) elif isinstance(message, ToolMessage): parsed_messages.append({"role": "assistant", "content": message.content}) return parsed_messages
def inference(self, messages: list[dict]) -> str: # def inference(user_prompt: str, sys_prompt: str, file_path: str | None = None, file_type: Literal["audio", "video", "image"] | None = None) -> str: # messages = [ # {"role": "system", "content": [{"type": "text", "text": sys_prompt}]}, # {"role": "user", "content": [ # {"type": file_type, file_type: file_path}, # {"type": "text", "text": user_prompt}, # ] if file_type else [{"type": "text", "text": user_prompt}] # }, # ] text = self.processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) audios, images, videos = process_mm_info(messages, use_audio_in_video=self.use_audio_in_video) inputs = self.processor(text=text, audio=audios, images=images, videos=videos, return_tensors="pt", padding=True, use_audio_in_video=self.use_audio_in_video) inputs = inputs.to(self.model.device).to(self.model.dtype)
output = self.model.generate(**inputs, use_audio_in_video=self.use_audio_in_video, return_audio=self.return_audio)
text = self.processor.batch_decode(output, skip_special_tokens=True, clean_up_tokenization_spaces=False)
text = text[0].split("\nassistant\n")[-1]
return text
def invoke(self, messages = list[AnyMessage], file_path: str | None = None) -> AIMessage: file_type = None if file_path is not None: if file_path.endswith(".wav") or file_path.endswith(".mp3"): file_type = "audio" elif file_path.endswith(".mp4") or file_path.endswith(".avi"): file_type = "video" elif file_path.endswith(".jpg") or file_path.endswith(".png"): file_type = "image" else: raise ValueError("Unsupported file type. Supported types are: .wav, .mp3, .mp4, .avi, .jpg, .png") parsed_messages = self.__parse_messages(messages, file_path=file_path, file_type=file_type) response = self.inference(messages=parsed_messages, file_path=file_path, file_type=file_type) return AIMessage(content=response)
1234567duckduckgo-search==8.0.1gradio==5.29.0gradio[oauth]#langchain-community==0.3.23langchain-ollama==0.3.2langgraph==0.4.3requests==2.32.3123456789101112131415duckduckgo_search==8.0.2gradio==5.29.0gradio[oauth]huggingface-hub==0.31.1ipywidgets==8.1.7langchain==0.3.25langchain-community==0.3.23langchain-experimental==0.3.4langchain-ollama==0.3.2langchain-openai==0.3.18langchain-tavily==0.2.0langgraph==0.4.3protobuf==6.31.0requests==2.32.3wikipedia==1.4.0
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320{ "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", "<think>\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", "</think>\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}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "a8d5a653", "metadata": {}, "outputs": [], "source": [ "from typing import TypedDict, Annotated, Literal\n", "import pandas as pd\n", "import soundfile as sf\n", "#from transformers import AutoProcessor, AutoModel\n", "from langchain_core.messages import AIMessage, HumanMessage, SystemMessage\n", "from transformers import Qwen2_5OmniForConditionalGeneration, Qwen2_5OmniProcessor\n", "from qwen_omni_utils import process_mm_info\n", "from utils import load_qa_data, GAIAQuestions, extract_json, submit\n", "\n", "# set use audio in video\n", "USE_AUDIO_IN_VIDEO = False\n", "# set return audio\n", "RETURN_AUDIO = False" ] }, { "cell_type": "code", "execution_count": 2, "id": "8883d89b", "metadata": {}, "outputs": [], "source": [ "# model = Qwen2_5OmniForConditionalGeneration.from_pretrained(\"Qwen/Qwen2.5-Omni-3B\", torch_dtype=\"auto\", device_map=\"auto\")\n", "# model.disable_talker()\n", "# processor = Qwen2_5OmniProcessor.from_pretrained(\"Qwen/Qwen2.5-Omni-3B\")" ] }, { "cell_type": "code", "execution_count": 3, "id": "26b4b349", "metadata": {}, "outputs": [], "source": [ "# model.save_pretrained(\"models/Qwen2.5-Omni-3B\")\n", "# processor.save_pretrained(\"models/Qwen2.5-Omni-3B\")" ] }, { "cell_type": "code", "execution_count": 4, "id": "c103cf0d", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Unrecognized keys in `rope_scaling` for 'rope_type'='default': {'mrope_section'}\n", "Qwen2_5OmniToken2WavModel does not support eager attention implementation, fall back to sdpa\n", "Loading checkpoint shards: 100%|██████████| 3/3 [00:09<00:00, 3.12s/it]\n" ] } ], "source": [ "model = Qwen2_5OmniForConditionalGeneration.from_pretrained(\"models/Qwen2.5-Omni-3B\", torch_dtype=\"auto\", device_map=\"auto\", local_files_only=True)\n", "model.disable_talker()\n", "processor = Qwen2_5OmniProcessor.from_pretrained(\"models/Qwen2.5-Omni-3B\", local_files_only=True)" ] }, { "cell_type": "code", "execution_count": 42, "id": "84185fcc", "metadata": {}, "outputs": [], "source": [ "from typing import Literal\n", "\n", "def inference(prompt: str, sys_prompt: str, file_path: str | None = None, file_type: Literal[\"audio\", \"video\", \"image\"] | None = None):\n", " messages = [\n", " {\"role\": \"system\", \"content\": [{\"type\": \"text\", \"text\": sys_prompt}]},\n", " {\"role\": \"user\", \"content\": [\n", " {\"type\": file_type, file_type: file_path},\n", " {\"type\": \"text\", \"text\": prompt},\n", " ] if file_type else [{\"type\": \"text\", \"text\": prompt}]\n", " },\n", " ]\n", " text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)\n", " audios, images, videos = process_mm_info(messages, use_audio_in_video=USE_AUDIO_IN_VIDEO)\n", " inputs = processor(text=text, audio=audios, images=images, videos=videos, return_tensors=\"pt\", padding=True, use_audio_in_video=USE_AUDIO_IN_VIDEO)\n", " inputs = inputs.to(model.device).to(model.dtype)\n", "\n", " output = model.generate(**inputs, use_audio_in_video=USE_AUDIO_IN_VIDEO, return_audio=False)\n", "\n", " text = processor.batch_decode(output, skip_special_tokens=True, clean_up_tokenization_spaces=False)\n", " return text" ] }, { "cell_type": "code", "execution_count": 6, "id": "7cd6746a", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "WARNING:root:System prompt modified, audio output may not work as expected. Audio output mode only works when using default system prompt 'You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, capable of perceiving auditory and visual inputs, as well as generating text and speech.'\n" ] } ], "source": [ "file_path = 'data/cats.jpeg'\n", "prompt = \"Describe the image\"\n", "file_type = \"image\"\n", "response = inference(file_path=file_path, file_type=file_type, prompt=prompt, sys_prompt=\"You are a helpful assistant.\")" ] }, { "cell_type": "code", "execution_count": 7, "id": "e488db3c", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['system\\nYou are a helpful assistant.\\nuser\\nDescribe the image\\nassistant\\nThe image shows two cats sitting side by side. The cat on the left is a Siamese cat with a light-colored body and darker, pointed markings on its ears, face, paws, and tail. The cat on the right is a white cat with a red collar around its neck. Both cats have a calm and attentive expression. The background is plain and light-colored, which helps to highlight the cats.']" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "response" ] }, { "cell_type": "code", "execution_count": 8, "id": "a37fa018", "metadata": {}, "outputs": [], "source": [ "gaia_dataset = load_qa_data(\"data/gaia_response_1747078562682.json\")" ] }, { "cell_type": "code", "execution_count": 9, "id": "46098970", "metadata": {}, "outputs": [], "source": [ "class AgentState(TypedDict):\n", " file_path: str | None = None\n", " question: str | None = None\n" ] }, { "cell_type": "code", "execution_count": 34, "id": "363331fe", "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>Location</th>\n", " <th>Burgers</th>\n", " <th>Hot Dogs</th>\n", " <th>Salads</th>\n", " <th>Fries</th>\n", " <th>Ice Cream</th>\n", " <th>Soda</th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>0</th>\n", " <td>Pinebrook</td>\n", " <td>1594</td>\n", " <td>1999</td>\n", " <td>2002</td>\n", " <td>2005</td>\n", " <td>1977</td>\n", " <td>1980</td>\n", " </tr>\n", " <tr>\n", " <th>1</th>\n", " <td>Wharvton</td>\n", " <td>1983</td>\n", " <td>2008</td>\n", " <td>2014</td>\n", " <td>2015</td>\n", " <td>2017</td>\n", " <td>2018</td>\n", " </tr>\n", " <tr>\n", " <th>2</th>\n", " <td>Sagrada</td>\n", " <td>2019</td>\n", " <td>2022</td>\n", " <td>2022</td>\n", " <td>2023</td>\n", " <td>2021</td>\n", " <td>2019</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <td>Algrimand</td>\n", " <td>1958</td>\n", " <td>1971</td>\n", " <td>1982</td>\n", " <td>1989</td>\n", " <td>1998</td>\n", " <td>2009</td>\n", " </tr>\n", " <tr>\n", " <th>4</th>\n", " <td>Marztep</td>\n", " <td>2015</td>\n", " <td>2016</td>\n", " <td>2018</td>\n", " <td>2019</td>\n", " <td>2021</td>\n", " <td>2022</td>\n", " </tr>\n", " <tr>\n", " <th>5</th>\n", " <td>San Cecelia</td>\n", " <td>2011</td>\n", " <td>2010</td>\n", " <td>2012</td>\n", " <td>2013</td>\n", " <td>2015</td>\n", " <td>2016</td>\n", " </tr>\n", " <tr>\n", " <th>6</th>\n", " <td>Pimento</td>\n", " <td>2017</td>\n", " <td>1999</td>\n", " <td>2001</td>\n", " <td>2003</td>\n", " <td>1969</td>\n", " <td>2967</td>\n", " </tr>\n", " <tr>\n", " <th>7</th>\n", " <td>Tinseles</td>\n", " <td>1967</td>\n", " <td>1969</td>\n", " <td>1982</td>\n", " <td>1994</td>\n", " <td>2005</td>\n", " <td>2006</td>\n", " </tr>\n", " <tr>\n", " <th>8</th>\n", " <td>Rosdale</td>\n", " <td>2007</td>\n", " <td>2009</td>\n", " <td>2021</td>\n", " <td>1989</td>\n", " <td>2005</td>\n", " <td>2011</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " Location Burgers Hot Dogs Salads Fries Ice Cream Soda\n", "0 Pinebrook 1594 1999 2002 2005 1977 1980\n", "1 Wharvton 1983 2008 2014 2015 2017 2018\n", "2 Sagrada 2019 2022 2022 2023 2021 2019\n", "3 Algrimand 1958 1971 1982 1989 1998 2009\n", "4 Marztep 2015 2016 2018 2019 2021 2022\n", "5 San Cecelia 2011 2010 2012 2013 2015 2016\n", "6 Pimento 2017 1999 2001 2003 1969 2967\n", "7 Tinseles 1967 1969 1982 1994 2005 2006\n", "8 Rosdale 2007 2009 2021 1989 2005 2011" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df = pd.read_excel(\"data/gaia_files/7bd855d8-463d-4ed5-93ca-5fe35145f733.xlsx\")\n", "df" ] }, { "cell_type": "code", "execution_count": 40, "id": "c1dad680", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'[{\"Location\":\"Pinebrook\",\"Burgers\":1594,\"Hot Dogs\":1999,\"Salads\":2002,\"Fries\":2005,\"Ice Cream\":1977,\"Soda\":1980},{\"Location\":\"Wharvton\",\"Burgers\":1983,\"Hot Dogs\":2008,\"Salads\":2014,\"Fries\":2015,\"Ice Cream\":2017,\"Soda\":2018},{\"Location\":\"Sagrada\",\"Burgers\":2019,\"Hot Dogs\":2022,\"Salads\":2022,\"Fries\":2023,\"Ice Cream\":2021,\"Soda\":2019},{\"Location\":\"Algrimand\",\"Burgers\":1958,\"Hot Dogs\":1971,\"Salads\":1982,\"Fries\":1989,\"Ice Cream\":1998,\"Soda\":2009},{\"Location\":\"Marztep\",\"Burgers\":2015,\"Hot Dogs\":2016,\"Salads\":2018,\"Fries\":2019,\"Ice Cream\":2021,\"Soda\":2022},{\"Location\":\"San Cecelia\",\"Burgers\":2011,\"Hot Dogs\":2010,\"Salads\":2012,\"Fries\":2013,\"Ice Cream\":2015,\"Soda\":2016},{\"Location\":\"Pimento\",\"Burgers\":2017,\"Hot Dogs\":1999,\"Salads\":2001,\"Fries\":2003,\"Ice Cream\":1969,\"Soda\":2967},{\"Location\":\"Tinseles\",\"Burgers\":1967,\"Hot Dogs\":1969,\"Salads\":1982,\"Fries\":1994,\"Ice Cream\":2005,\"Soda\":2006},{\"Location\":\"Rosdale\",\"Burgers\":2007,\"Hot Dogs\":2009,\"Salads\":2021,\"Fries\":1989,\"Ice Cream\":2005,\"Soda\":2011}]'" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.to_json(orient=\"records\")" ] }, { "cell_type": "code", "execution_count": null, "id": "c4bb6e2a", "metadata": {}, "outputs": [], "source": [ "def extract_xlsx_data(file_path: str) -> str:\n", " df = pd.read_excel(\"your_file.xlsx\", sheet_name=\"Sheet1\")\n", " # text_data = df.to_string()\n", " text_data = df.to_json(orient=\"records\")\n", " return text_data" ] }, { "cell_type": "code", "execution_count": null, "id": "875e7fce", "metadata": {}, "outputs": [], "source": [ "SYSTEM_PROMPT = \"\"\"You are a general AI assistant. I will ask you a question, and sometimes I will append an external file to review and evaluate in order to answer the question. \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": null, "id": "f4c3740f", "metadata": {}, "outputs": [], "source": [ "def analyze_with_file(state: AgentState):\n", " question = state['question']\n", " file = None\n", " file_type = None\n", " if state['file_path'] is not None:\n", " file = f\"data/gaia_files/{state['file_path']}\"\n", " # context = \"\"\n", " if file.endswith(\".mp3\"):\n", " file_type = \"audio\"\n", " elif file.endswith(\".png\"):\n", " file_type = \"image\"\n", " # elif file.endswith(\".xlsx\"):\n", " # context = extract_xlsx_data(file)\n", " # elif file.endswith(\".py\"):\n", " # context = extract_code_data(file)\n", " response = inference(file_path=file, file_type=file_type, prompt=question, sys_prompt=SYSTEM_PROMPT)\n", " final_response = response[0].split(\"\\nassistant\\n\")[-1].split(\"FINAL ANSWER: \")[-1].strip()\n", " \n", " return final_response" ] }, { "cell_type": "code", "execution_count": 52, "id": "56e99100", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "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.\n" ] } ], "source": [ "index = 3 # image\n", "#index = 9 # audio\n", "gaia_example = gaia_dataset[index]\n", "print(gaia_example.question)" ] }, { "cell_type": "code", "execution_count": 53, "id": "ed8ec8e4", "metadata": {}, "outputs": [], "source": [ "agent_state = AgentState(file_path=gaia_example.file_name, question=gaia_example.question)" ] }, { "cell_type": "code", "execution_count": 54, "id": "f42e0236", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "WARNING:root:System prompt modified, audio output may not work as expected. Audio output mode only works when using default system prompt 'You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, capable of perceiving auditory and visual inputs, as well as generating text and speech.'\n" ] }, { "data": { "text/plain": [ "'e5'" ] }, "execution_count": 54, "metadata": {}, "output_type": "execute_result" } ], "source": [ "response = analyze_with_file(agent_state)\n", "response" ] }, { "cell_type": "code", "execution_count": 50, "id": "15005d40", "metadata": {}, "outputs": [], "source": [ "gaia_example.answer = response" ] }, { "cell_type": "code", "execution_count": 51, "id": "c3552e7f", "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": 51, "metadata": {}, "output_type": "execute_result" } ], "source": [ "submit([gaia_example], username=\"juancitro\", agent_code=f\"https://huggingface.co/spaces/juancitro/Final_Assignment_Template/tree/main\")" ] }, { "cell_type": "code", "execution_count": null, "id": "dcbc9fef", "metadata": {}, "outputs": [], "source": [] } ], "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}12345678910111213141516171819import requestsfrom langchain_community.tools import DuckDuckGoSearchRun, DuckDuckGoSearchResultsfrom langchain import hub
search = DuckDuckGoSearchRun()search = DuckDuckGoSearchResults(output_format="list")
def search_brave(query): url = f"https://api.brave.com/search?q={query}" response = requests.get(url) return response.json()
if __name__ == "__main__": # query = "What is the capital of France?" # results = search_brave(query) # print(results) prompt = hub.pull('hwchase17/react') print(type(prompt)) print(prompt)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889from pydantic import BaseModelimport requestsimport json
USERNAME = "juancitro"SPACE_ID = "juancitro/Final_Assignment_Template"AGENT_CODE = f"https://huggingface.co/spaces/{SPACE_ID}/tree/main"API_URL = "https://agents-course-unit4-scoring.hf.space" # Replace with actual API URL
def extract_json(response: str) -> dict | None: """ Extract the JSON part of the LLM response, and remove some invalid caracters. """ try: json_start = response.index("{") json_end = response.rfind("}") json_str_response = response[json_start:json_end + 1] json_str_response = json_str_response.replace('\n', ' ') json_response = json.loads(json_str_response) except (ValueError, json.JSONDecodeError) as e: print(f"JSON can't be parsed: {e}. Original response: {response}") return None return json_response
class GAIAQuestions(BaseModel): task_id: str question: str Level: str answer: str | None = None file_name: str | None = None
def load_qa_data(file_path: str) -> list[GAIAQuestions]: import json with open(file_path, 'r') as f: questions = json.load(f) return [GAIAQuestions(**question) for question in questions]
def submit(questions: list[GAIAQuestions], username=USERNAME, agent_code=AGENT_CODE, submit_url = f"{API_URL}/submit") -> str: answers_payload = [] results_log = [] for item in questions: answers_payload.append({"task_id": item.task_id, "submitted_answer": item.answer}) results_log.append({"Task ID": item.task_id, "Question": item.question, "Submitted Answer": item.answer}) submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload} status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..." print(status_update)
# 5. Submit print(f"Submitting {len(answers_payload)} answers to: {submit_url}") try: response = requests.post(submit_url, json=submission_data, timeout=60) response.raise_for_status() result_data = response.json() final_status = ( f"Submission Successful!\n" f"User: {result_data.get('username')}\n" f"Overall Score: {result_data.get('score', 'N/A')}% " f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n" f"Message: {result_data.get('message', 'No message received.')}" ) print("Submission successful.") return final_status except requests.exceptions.HTTPError as e: error_detail = f"Server responded with status {e.response.status_code}." try: error_json = e.response.json() error_detail += f" Detail: {error_json.get('detail', e.response.text)}" except requests.exceptions.JSONDecodeError: error_detail += f" Response: {e.response.text[:500]}" status_message = f"Submission Failed: {error_detail}" print(status_message) return status_message except requests.exceptions.Timeout: status_message = "Submission Failed: The request timed out." print(status_message) return status_message except requests.exceptions.RequestException as e: status_message = f"Submission Failed: Network error - {e}" print(status_message) return status_message except Exception as e: status_message = f"An unexpected error occurred during submission: {e}" print(status_message) return status_message.gitattributes+1
.gitignore+5-1
README.md+14-1
basic_agent.py+32-7
data/cats.jpegAdded

data/gaia_files/1f975693-876d-457b-a649-393859e79bf3.mp3Added+3
data/gaia_files/7bd855d8-463d-4ed5-93ca-5fe35145f733.xlsxAdded
data/gaia_files/99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3.mp3Added+3
data/gaia_files/cca530fc-4052-43b2-b130-b30968d8aa44.pngAdded

data/gaia_files/f918266a-b3e0-4914-865d-4faa564f1aef.pyAdded+35
data/gaia_response_1747078562682.jsonAdded+138
langgraph_agent.pyAdded+93
openai_agent.pyAdded
requirements.txt+11-3
test_gemma3.ipynbAdded+320
test_openai_based_agent.ipynbAdded
test_opensource_agent.ipynbAdded
test_qwen_25_omni.ipynbAdded+526
tools.pyDeleted-19
utils.pyAdded+89