David commited on
Commit ·
7da5655
1
Parent(s): 3f771a9
Included tools to understand audio, image and video. Sleep is included to avoid free tier RPM
Browse filesFiles changed (5)
- agent.py+61-34
- app.py+6
- gaia_system_prompt.py+11-14
- requirements.txt+1-4
- tools.py+47-57
12345677 unmodified lines15161718192021222324252627282930311 unmodified line333435363738394041421 unmodified line4445464748496 unmodified lines5657585960616263646566676869707172737475767724 unmodified lines10210310410510610725 unmodified lines133134135136137138139140141142143144145146147148149150151152153154from llama_index.llms.google_genai import GoogleGenAIfrom llama_index.llms.gemini import Geminifrom llama_index.llms.groq import Groqfrom llama_index.llms.huggingface_api import HuggingFaceInferenceAPIfrom llama_index.tools.arxiv import ArxivToolSpecfrom llama_index.tools.wikipedia import WikipediaToolSpecfrom llama_index.tools.duckduckgo import DuckDuckGoSearchToolSpec7 unmodified linesfrom gradio import ChatMessagefrom llama_index.core.base.llms.types import ChatMessage as llama_index_chat_messagefrom tools import interpret_python_math_codefrom gaia_system_prompt import SYSTEM_PROMPT as GAIA_SYSTEM_PROMPTimport osimport asyncioTIMEOUT=180 # Timeout for agent execution in secondsGEMINI_API_KEY = os.getenv("GEMINI_TOKEN")GROQ_API_KEY = os.getenv("GROQ_TOKEN")GEMINI_OPENAI_API_DIR = "https://generativelanguage.googleapis.com/v1beta/openai/"GEMINI_MODEL_NAME = "gemini-2.5-flash-preview-04-17"LMSTUDIO_MODEL_NAME = "gemma-3-12B-it-qat-GGUF"API_DIR = "http://host.docker.internal:1234/v1" # LM Studio API URL1 unmodified linedef __init__(self):# LLM Initialization# self.llm = GoogleGenAI(model=GEMINI_MODEL_NAME, api_key=GEMINI_API_KEY)# self.llm = Gemini(model=GEMINI_MODEL_NAME, api_key=GEMINI_API_KEY)# self.llm = Groq(model="meta-llama/llama-4-maverick-17b-128e-instruct", api_key=GROQ_API_KEY)# self.llm = LMStudio(model_name=LMSTUDIO_MODEL_NAME, base_url=API_DIR, request_timeout=180, temperature=0.1)self.llm = HuggingFaceInferenceAPI(model_name="meta-llama/Llama-3.3-70B-Instruct", timeout=TIMEOUT)# Tool Initializationself.tools = [1 unmodified linefn=interpret_python_math_code,name="InterpretPythonMathCode",description="Interprets Python code for mathematical expressions.")]self.tools.extend(6 unmodified linesDuckDuckGoSearchToolSpec().to_tool_list())# Agent Workflow Initialization# self.agent = AgentWorkflow.from_tools_or_functions(# tools_or_functions=self.tools,# llm=self.llm,# system_prompt=GAIA_SYSTEM_PROMPT,# timeout=TIMEOUT# )self.agent = ReActAgent(llm=self.llm,verbose=True,max_iterations=5,system_prompt=GAIA_SYSTEM_PROMPT,tools=self.tools)print("FinalAgent initialized.")# async def __call__(self, question: str) -> str:# # Example24 unmodified linestry:# Use arun for an async method.agent_chat_response = await self.agent.run(question)potential_response_obj = agent_chat_response.response25 unmodified lines# Depending on requirements, you might want to return an error message or re-raiseresponse_str = f"Agent error: {e}"# Get the agent's final response string from FINAL ANSWER:if "FINAL ANSWER: " in response_str:response_str = response_str.split("FINAL ANSWER: ")[-1].strip()else:print("Warning: 'FINAL ANSWER:' not found in response string. Returning full response.")print(f"Agent final response: {response_str}")return response_strasync def main():# Example usageagent = FinalAgent()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."answer = await agent(question)print(f"Final answer: {answer}")if __name__ == "__main__":asyncio.run(main())123457 unmodified lines131415161718192021222324252627281 unmodified line30313233343536371 unmodified line394041424344454647484950515253545556575859606162636465666768696 unmodified lines76777879808182838485868788899091929394959697989910010110224 unmodified lines12712812913013113213325 unmodified lines159160161162163164165166167168169170171172173174175176177178179180181from llama_index.llms.google_genai import GoogleGenAIfrom llama_index.llms.gemini import Geminifrom llama_index.tools.arxiv import ArxivToolSpecfrom llama_index.tools.wikipedia import WikipediaToolSpecfrom llama_index.tools.duckduckgo import DuckDuckGoSearchToolSpec7 unmodified linesfrom gradio import ChatMessagefrom llama_index.core.base.llms.types import ChatMessage as llama_index_chat_messagefrom tools import interpret_python_math_code, image_understanding, convert_audio_to_text, video_understanding, read_csv_file, read_xlsx_filefrom gaia_system_prompt import GAIA_SYSTEM_PROMPT, CUSTOM_SYSTEM_PROMPTimport osimport asyncioTIMEOUT=180 # Timeout for agent execution in secondsGEMINI_API_KEY = os.getenv("GEMINI_TOKEN")GEMINI_OPENAI_API_DIR = "https://generativelanguage.googleapis.com/v1beta/openai/"GEMINI_MODEL_NAME = "gemini-2.0-flash"LMSTUDIO_MODEL_NAME = "gemma-3-12B-it-qat-GGUF"API_DIR = "http://host.docker.internal:1234/v1" # LM Studio API URL1 unmodified linedef __init__(self):# LLM Initialization# self.llm = GoogleGenAI(model=GEMINI_MODEL_NAME, api_key=GEMINI_API_KEY)self.llm = Gemini(model=GEMINI_MODEL_NAME, api_key=GEMINI_API_KEY)# self.llm = LMStudio(model_name=LMSTUDIO_MODEL_NAME, base_url=API_DIR, request_timeout=180, temperature=0.1)# Tool Initializationself.tools = [1 unmodified linefn=interpret_python_math_code,name="InterpretPythonMathCode",description="Interprets Python code for mathematical expressions."),FunctionTool.from_defaults(fn=image_understanding,name="ImageUnderstanding",description="Analyzes an image and generates a response to a given question based on the image's content."),FunctionTool.from_defaults(fn=convert_audio_to_text,name="ConvertAudioToText",description="Converts audio files to text using a speech-to-text model."),FunctionTool.from_defaults(fn=video_understanding,name="VideoUnderstanding",description="Analyzes a video and generates a response to a given question based on the video's content."),FunctionTool.from_defaults(fn=read_csv_file,name="ReadCSVFile",description="Reads a CSV file and returns its content as a string."),FunctionTool.from_defaults(fn=read_xlsx_file,name="ReadXLSXFile",description="Reads an XLSX file and returns its content as a string.")]self.tools.extend(6 unmodified linesDuckDuckGoSearchToolSpec().to_tool_list())# Print the tools for debuggingprint("Tools initialized:")for tool in self.tools:print(f"- {tool._metadata}")# Agent Workflow Initializationself.agent = AgentWorkflow.from_tools_or_functions(tools_or_functions=self.tools,llm=self.llm,system_prompt=CUSTOM_SYSTEM_PROMPT,timeout=TIMEOUT)# self.agent = ReActAgent(# llm=self.llm,# verbose=True,# max_iterations=5,# system_prompt=CUSTOM_SYSTEM_PROMPT,# tools=self.tools# )print("FinalAgent initialized.")# async def __call__(self, question: str) -> str:# # Example24 unmodified linestry:# Use arun for an async method.agent_chat_response = await self.agent.run(question)print(agent_chat_response)potential_response_obj = agent_chat_response.response25 unmodified lines# Depending on requirements, you might want to return an error message or re-raiseresponse_str = f"Agent error: {e}"# Get the agent's final response between <final_answer> and </final_answer> tagsif "<final_answer>" in response_str and "</final_answer>" in response_str:start_index = response_str.index("<final_answer>") + len("<final_answer>")end_index = response_str.index("</final_answer>")response_str = response_str[start_index:end_index].strip()else:print("Warning: No <final_answer> tags found in the response.")return response_str# async def main():# # Example usage# agent = FinalAgent()# 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."# answer = await agent(question)# print(f"Final answer: {answer}")# if __name__ == "__main__":# asyncio.run(main())
5 unmodified lines6789101173 unmodified lines8586878889909192935 unmodified linesfrom agent import FinalAgentimport asyncio# (Keep Constants as is)# --- Constants ---73 unmodified linesprint(f"Skipping item with missing task_id or question: {item}")continuetry:submitted_answer = await agent(question_text)answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})except Exception as e:print(f"Error running agent on task {task_id}: {e}")results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})5 unmodified lines6789101112131473 unmodified lines8889909192939495969798995 unmodified linesfrom agent import FinalAgentimport asyncioimport timeSLEEP_TIME_BETWEEN_QUESTIONS = 30 # Sleep time between questions to avoid rate limiting# (Keep Constants as is)# --- Constants ---73 unmodified linesprint(f"Skipping item with missing task_id or question: {item}")continuetry:# Run the agent on the questionsubmitted_answer = await agent(question_text)answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})time.sleep(SLEEP_TIME_BETWEEN_QUESTIONS) # Sleep for 60 seconds to avoid Gemini free RPD rate limiting issuesexcept Exception as e:print(f"Error running agent on task {task_id}: {e}")results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
4 unmodified lines5678910111213141516171819202122234 unmodified linesIf 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."""SYSTEM_PROMPT = """You are a general AI assistant. Answer my question directly, following these strict rules. Your entire output must be *only* the template below.**Rules:*** No thoughts, explanations, or extra text.* The *only* output is: FINAL ANSWER: [YOUR SHORT ANSWER]* [YOUR SHORT ANSWER] is a number, string, or comma-separated list.* Numbers: No commas, no units (unless specified).* Strings: No articles, no abbreviations, digits as words (unless specified).* Lists: Apply number/string rules to items.**Example:**User: What is the capital of France?Assistant:FINAL ANSWER: Paris"""4 unmodified lines5678910111213141516171819204 unmodified linesIf 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."""CUSTOM_SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question and you should use your tools to answer as better as you can. You must be concise and precise in your answers.I provide you some guidelines to follow:1. Your final answer should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.2. 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.3. 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.4. 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.The final answer should be written in the following format:<final_answer>YOUR FINAL ANSWER</final_answer>"""
2 unmodified lines3456789101112132 unmodified linesnumpypandasscipygroqllama-indexllama-index-llms-huggingfacellama-index-llms-huggingface-apillama-index-llms-groqllama-index-utils-workflowllama-index-llms-lmstudiollama-index-llms-gemini2 unmodified lines3456789102 unmodified linesnumpypandasscipygoogle-genaillama-indexllama-index-utils-workflowllama-index-llms-lmstudiollama-index-llms-gemini
4 unmodified lines56789101112131415161718100 unmodified lines1191201211221231241253 unmodified lines1291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601615 unmodified lines1671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042054 unmodified linesimport numpy as npimport pandas as pdimport scipyfrom groq import Groqfrom pathlib import Pathimport pandas as pdimport mimetypesimport base64ALLOWED_MODULES = {"numpy", "pandas", "scipy"}def interpret_python_math_code(python_code: str) -> str:"""100 unmodified linessys.stdout = old_stdout## STT tooldef convert_audio_to_text(path_to_audio: str) -> str:"""Converts speech from an audio file into text.3 unmodified linesstr: The transcribed text content of the audio file."""# Validate audio fileif not isinstance(path_to_audio, str):raise TypeError("Parameter 'path_to_audio' must be a string containing the file path.")path = Path(path_to_audio).expanduser().resolve()if not path.is_file():raise FileNotFoundError(f"No such audio file: {path}")# Initialize the Groq clientclient = Groq()# Open the audio filewith open(path_to_audio, "rb") as audio_file:# Create a transcription of the audio filetranscription = client.audio.transcriptions.create(file=audio_file,model="whisper-large-v3-turbo",response_format="text", # Returns plain text instead of JSONlanguage="en",temperature=0.1)return transcription## Analyze image tooldef analyze_image(path_to_image: str, question: str) -> str:"""Analyzes an image and generates a response to a given question based on the image's content.5 unmodified linesstr: The response from a VLM, typically a textual analysis or description based on the image."""def encode_image(image_path):with open(image_path, "rb") as image_file:return base64.b64encode(image_file.read()).decode('utf-8')# Get the MIME type (e.g., image/png, image/jpeg)mime_type, _ = mimetypes.guess_type(path_to_image)if mime_type is None:raise ValueError("Unsupported file type. Please provide a valid image.")base64_image = encode_image(path_to_image)# Initialize the Groq clientclient = GroqClient()chat_completion = client.chat.completions.create(messages=[{"role": "user","content": [{"type": "text", "text": question},{"type": "image_url","image_url": {"url": f"data:{mime_type};base64,{base64_image}",},},],}],model="meta-llama/llama-4-scout-17b-16e-instruct",)return chat_completion.choices[0].message.content## Read .csv file tooldef read_csv_file(path_to_csv: str) -> str:4 unmodified lines567891011121314151617181920100 unmodified lines1211221231241251261273 unmodified lines1311321331341351361371381391401411421431441451461471481495 unmodified lines1551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941954 unmodified linesimport numpy as npimport pandas as pdimport scipyfrom pathlib import Pathimport mimetypesimport base64from google import genaiALLOWED_MODULES = {"numpy", "pandas", "scipy"}GEMINI_API_KEY = os.getenv("GEMINI_TOKEN")GEMINI_MODEL_NAME = "gemini-2.0-flash"def interpret_python_math_code(python_code: str) -> str:"""100 unmodified linessys.stdout = old_stdout# STT tooldef convert_audio_to_text(path_to_audio: str) -> str:"""Converts speech from an audio file into text.3 unmodified linesstr: The transcribed text content of the audio file."""client = genai.Client(api_key="GOOGLE_API_KEY")myfile = client.files.upload(file=path_to_audio)transcription = client.models.generate_content(model=GEMINI_MODEL_NAME, contents=["Provide a transcription of this audio file.", myfile])return transcription.text# Analyze image tooldef image_understanding(path_to_image: str, question: str) -> str:"""Analyzes an image and generates a response to a given question based on the image's content.5 unmodified linesstr: The response from a VLM, typically a textual analysis or description based on the image."""client = genai.Client(api_key=GEMINI_API_KEY)my_file = client.files.upload(file=path_to_image)response = client.models.generate_content(model=GEMINI_MODEL_NAME,contents=[my_file, question],)return response.text# Analyze video tooldef video_understanding(path_to_video: str, question: str) -> str:"""Analyzes a video and generates a response to a given question based on the video's content.Args:path_to_video (str): The path to the video file to be analyzed.question (str): The question to be answered, based on the contents of the video.Returns:str: The response from a VLM, typically a textual analysis or description based on the video."""client = genai.Client(api_key=GEMINI_API_KEY)my_file = client.files.upload(file=path_to_video)response = client.models.generate_content(model=GEMINI_MODEL_NAME,contents=[my_file, question],)return response.text## Read .csv file tooldef read_csv_file(path_to_csv: str) -> str:
agent.py+61-34
app.py+6
gaia_system_prompt.py+11-14
requirements.txt+1-4
tools.py+47-57