David commited on
Commit ·
3f771a9
1
Parent(s): edf3100
Still implementing and trying
Browse filesFiles changed (5)
- agent.py+125-21
- app.py+12-5
- gaia_system_prompt.py+18-1
- requirements.txt+6
- tools.py+127-9
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950from llama_index.llms.google_genai import GoogleGenAIfrom llama_index.tools.arxiv import ArxivToolSpecfrom llama_index.tools.wikipedia import WikipediaToolSpecfrom llama_index.tools.duckduckgo import DuckDuckGoSearchResultsToolSpecfrom llama_index.core.tools import FunctionToolfrom llama_index.core.agent.workflow import AgentWorkflowfrom tools import interpret_python_math_codefrom gaia_system_prompt import GAIA_SYSTEM_PROMPTimport osGEMINI_API_KEY = os.getenv("GEMINI_TOKEN")GEMINI_MODEL_NAME = "gemini-2.5-flash-preview-04-17"class FinalAgent:def __init__(self):# LLM Initializationself.llm = GoogleGenAI(model=GEMINI_MODEL_NAME, api_key=GEMINI_API_KEY)# Tool Initializationself.tools = [FunctionTool.from_defaults(func=interpret_python_math_code,name="InterpretPythonMathCode",description="Interprets Python code for mathematical expressions."),DuckDuckGoSearchResultsToolSpec(),WikipediaToolSpec(),ArxivToolSpec()]# Agent Workflow Initializationself.agent = AgentWorkflow(llm=self.llm,tools=self.tools,system_prompt=GAIA_SYSTEM_PROMPT)print("FinalAgent initialized.")def __call__(self, question: str) -> str:# Exampleprint(f"Agent received question (first 50 chars): {question[:50]}...")fixed_answer = "This is a default answer."print(f"Agent returning fixed answer: {fixed_answer}")# Implement agent logic hereresponse = self.agent.run(question)return response123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154from 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 DuckDuckGoSearchToolSpecfrom llama_index.core.tools import FunctionToolfrom llama_index.core.agent.workflow import AgentWorkflow, ReActAgentfrom llama_index.llms.lmstudio import LMStudiofrom llama_index.core.agent.workflow import (AgentStream,AgentOutput)from 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 URLclass FinalAgent:def __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 = [FunctionTool.from_defaults(fn=interpret_python_math_code,name="InterpretPythonMathCode",description="Interprets Python code for mathematical expressions.")]self.tools.extend(ArxivToolSpec().to_tool_list())self.tools.extend(WikipediaToolSpec().to_tool_list())self.tools.extend(DuckDuckGoSearchToolSpec().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:# # Example# print(f"Agent received question: {question}")# # fixed_answer = "This is a default answer."# # print(f"Agent returning fixed answer: {fixed_answer}")# # response = fixed_answer# # Implement agent logic here# response = ""# # Run the agent with the question# stream = await self.agent.run(question)# response = stream.response.content# # async for event in stream.stream_events():# # if isinstance(event, AgentStream):# # # Check if delta is empty# # if event.raw["choices"][0]["delta"] != {}:# # response += event.raw["choices"][0]["delta"]["content"]# print(f"Agent response: {response}")# return responseasync def __call__(self, question: str) -> str:print(f"Agent received question: {question}")response_str = ""try:# Use arun for an async method.agent_chat_response = await self.agent.run(question)potential_response_obj = agent_chat_response.responseif isinstance(potential_response_obj, ChatMessage):# If it's a ChatMessage, its .content attribute should hold the stringprint(f"DEBUG: Response object is ChatMessage. Role: {potential_response_obj.role}")response_str = potential_response_obj.contentif response_str is None: # Handle cases where content might be Noneprint("DEBUG: ChatMessage content is None, defaulting to empty string.")response_str = ""elif isinstance(potential_response_obj, str):# If it's already a stringprint("DEBUG: Response object is str.")response_str = potential_response_objelif isinstance(potential_response_obj, llama_index_chat_message):# If it's a llama_index ChatMessage, use its .content attributeprint(f"DEBUG: Response object is llama_index ChatMessage. Role: {potential_response_obj.role}")response_str = potential_response_obj.contentif response_str is None:print("DEBUG: llama_index ChatMessage content is None, defaulting to empty string.")response_str = ""else:# Fallback if it's some other typeprint(f"Warning: Agent response was of unexpected type: {type(potential_response_obj)}. Converting to string.")response_str = str(potential_response_obj)except Exception as e:print(f"Error during agent execution with LLM {self.llm.__class__.__name__}: {e}")# 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())
3 unmodified lines4567899 unmodified lines1920212223242514 unmodified lines4041424344454633 unmodified lines8081828384858684 unmodified lines17117217317417517617715 unmodified lines1931941951963 unmodified linesimport inspectimport pandas as pd# (Keep Constants as is)# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"9 unmodified linesprint(f"Agent returning fixed answer: {fixed_answer}")return fixed_answerdef run_and_submit_all( profile: gr.OAuthProfile | None):"""Fetches all questions, runs the BasicAgent on them, submits all answers,and displays the results.14 unmodified lines# 1. Instantiate Agent ( modify this part to create your agent)try:agent = BasicAgent()except Exception as e:print(f"Error instantiating agent: {e}")return f"Error initializing agent: {e}", None33 unmodified linesprint(f"Skipping item with missing task_id or question: {item}")continuetry:submitted_answer = 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:84 unmodified linesoutputs=[status_output, results_table])if __name__ == "__main__":print("\n" + "-"*30 + " App Starting " + "-"*30)# Check for SPACE_HOST and SPACE_ID at startup for informationspace_host_startup = os.getenv("SPACE_HOST")15 unmodified linesprint("-"*(60 + len(" App Starting ")) + "\n")print("Launching Gradio Interface for Basic Agent Evaluation...")demo.launch(debug=True, share=False)3 unmodified lines4567891011129 unmodified lines2223242526272814 unmodified lines43444546474849505133 unmodified lines8586878889909184 unmodified lines17617717817918018118215 unmodified lines1981992002012022033 unmodified linesimport inspectimport pandas as pdfrom agent import FinalAgentimport asyncio# (Keep Constants as is)# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"9 unmodified linesprint(f"Agent returning fixed answer: {fixed_answer}")return fixed_answerasync def run_and_submit_all( profile: gr.OAuthProfile | None):"""Fetches all questions, runs the BasicAgent on them, submits all answers,and displays the results.14 unmodified lines# 1. Instantiate Agent ( modify this part to create your agent)try:# agent = BasicAgent()agent = FinalAgent() # Use your custom agent class hereprint(f"Agent instantiated successfully: {agent}")except Exception as e:print(f"Error instantiating agent: {e}")return f"Error initializing agent: {e}", None33 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:84 unmodified linesoutputs=[status_output, results_table])async def main():print("\n" + "-"*30 + " App Starting " + "-"*30)# Check for SPACE_HOST and SPACE_ID at startup for informationspace_host_startup = os.getenv("SPACE_HOST")15 unmodified linesprint("-"*(60 + len(" App Starting ")) + "\n")print("Launching Gradio Interface for Basic Agent Evaluation...")demo.launch(debug=True, share=False)if __name__ == "__main__":asyncio.run(main())
2 unmodified lines34562 unmodified linesYOUR 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."""2 unmodified lines345678910111213141516171819202122232 unmodified linesYOUR 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."""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"""
2 unmodified lines34567892 unmodified linesnumpypandasscipyllama-indexllama-index-llms-geminillama-index-llms-google-genaillama-index-utils-workflow2 unmodified lines34567891011121314152 unmodified linesnumpypandasscipygroqllama-indexllama-index-llms-huggingfacellama-index-llms-huggingface-apillama-index-llms-groqllama-index-utils-workflowllama-index-llms-lmstudiollama-index-llms-geminillama-index-llms-google-genaillama-index-utils-workflow
4 unmodified lines5678910102 unmodified lines1131141151161171181191201211221231244 unmodified linesimport numpy as npimport pandas as pdimport scipyALLOWED_MODULES = {"numpy", "pandas", "scipy"}102 unmodified linessys.stdout = old_stdout# Example usage:if __name__ == "__main__":code = """import numpy as np# import os # This should trigger an error since 'os' is not allowedarr = np.array([1, 2, 3, 4, 5])_result = arr.mean()"""print(interpret_python_math_code(code))4 unmodified lines5678910111213141516102 unmodified lines1191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412424 unmodified linesimport numpy as npimport pandas as pdimport scipyfrom groq import Groqfrom pathlib import Pathimport pandas as pdimport mimetypesimport base64ALLOWED_MODULES = {"numpy", "pandas", "scipy"}102 unmodified linessys.stdout = old_stdout## STT tooldef convert_audio_to_text(path_to_audio: str) -> str:"""Converts speech from an audio file into text.Args:path_to_audio (str): The path to the audio file to be transcribed.Returns:str: 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.Args:path_to_image (str): The path to the image file to be analyzed.question (str): The question to be answered, based on the contents of the image.Returns:str: 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:"""Reads a CSV file from the specified path and returns its content as plain text.Args:path_to_csv (str): The file path to the CSV file.Returns:str: Content of the CSV file as plain text."""try:# Read the CSV file using pandasdf = pd.read_csv(path_to_csv)# Return df as plain tectreturn df.to_string(index=False)except Exception as e:return f"Error reading the CSV file: {e}"## Read .xlsx file tooldef read_xlsx_file(path_to_xlsx: str) -> str:"""Reads a XLSX file from the specified path and returns its content as plain text.Args:path_to_xlsx (str): The file path to the XLSX file.Returns:str: Content of the XLSX file as plain text."""try:# Read the XLSX file using pandasdf = pd.read_excel(path_to_xlsx)# Return df as plain tectreturn df.to_string(index=False)except Exception as e:return f"Error reading the XLSX file: {e}"
agent.py+125-21
app.py+12-5
gaia_system_prompt.py+18-1
requirements.txt+6
tools.py+127-9