Spaces:
Running
Running
import os | |
import gradio as gr | |
import requests | |
import inspect | |
import pandas as pd | |
import asyncio | |
from google import genai | |
from google.adk.agents import Agent | |
from google.adk.runners import Runner | |
from google.adk.sessions import InMemorySessionService | |
from google.genai import types | |
from google.adk.tools import agent_tool | |
from google.adk.agents import Agent | |
from google.adk.tools import google_search, built_in_code_execution | |
from google.adk.agents import LlmAgent | |
from huggingface_hub import snapshot_download | |
from openpyxl import load_workbook | |
import warnings | |
# Ignore all warnings | |
warnings.filterwarnings("ignore") | |
import logging | |
logging.basicConfig(level=logging.ERROR) | |
# Load API KEYs | |
from dotenv import load_dotenv | |
load_dotenv() | |
GOOGLE_API_KEY = os.environ['GOOGLE_API_KEY'] | |
# Agent Tools | |
coding_agent = LlmAgent( | |
model='gemini-2.0-flash', | |
name='CodeAgent', | |
instruction="""You are a calculator agent. | |
When given a mathematical expression, write and execute Python code to calculate the result. | |
Return only the final numerical result as plain text, without markdown or code blocks. | |
""", | |
description="Executes Python code to perform calculations.", | |
tools=[built_in_code_execution], | |
) | |
code_execution_agent = LlmAgent( | |
model='gemini-2.0-flash', | |
name='CodeAgent', | |
instruction=""" | |
You're a specialist in Code Execution. Execute Python code to get the result. | |
Return only the final numerical result as plain text, without markdown or code blocks. | |
If you given the python code, do not add, subtract any codes from original one. | |
""", | |
description="Executes Python code. It will not generate code.", | |
tools=[built_in_code_execution], | |
) | |
search_agent = Agent( | |
name="basic_search_agent", | |
model="gemini-2.5-flash-preview-04-17", | |
description="Agent to answer questions using Google Search.", | |
instruction="I can answer your questions by searching the internet. Just ask me anything!", | |
# google_search is a pre-built tool which allows the agent to perform Google searches. | |
tools=[google_search] | |
) | |
# YouTube Tools | |
def understand_youtube_video(video_url: str, question: str) -> str: | |
""" | |
Given a YouTube video URL and question, this will use the Gemini API to analyze the video content and provide an answer. | |
Args: | |
video_url (str): The URL of the YouTube video you want to analyze (e.g. "https://www.youtube.com/watch?v=..."). | |
If Gemini cannot handle this directly, you may need a different format, such as a GCS URI. | |
question (str): The specific question about the video content. | |
Returns: | |
str: The answer generated by the Gemini model based on the video and question. | |
Returns an error message if processing fails. | |
""" | |
print(f"--- Analyzing YouTube Video ---") | |
print(f"URL: {video_url}") | |
print(f"Question: {question}") | |
try: | |
client = genai.Client(api_key=GOOGLE_API_KEY) | |
model='models/gemini-2.0-flash', | |
response = client.models.generate_content( | |
model='models/gemini-2.0-flash', | |
contents=types.Content( | |
parts=[ | |
types.Part( | |
file_data=types.FileData(file_uri=video_url) | |
), | |
types.Part(text=question) | |
] | |
) | |
) | |
print("--- Gemini Response Received ---") | |
if hasattr(response, 'text'): | |
print("Video Description : ", response.text) | |
return response.text | |
elif response.parts: | |
return "".join(part.text for part in response.parts if hasattr(part, 'text')) | |
else: | |
block_reason = "" | |
if response.prompt_feedback and response.prompt_feedback.block_reason: | |
block_reason = f" Reason: {response.prompt_feedback.block_reason.name}" | |
return f"Model did not return text content.{block_reason}" | |
except Exception as e: | |
print(f"Error processing YouTube video '{video_url}' with Gemini: {e}") | |
return f"Sorry, an error occurred while analyzing the video. Please check the URL and ensure the video is accessible. Error details: {str(e)}" | |
# Image Tools | |
def understand_image(image_file_name: str) -> str: | |
""" | |
Given an image file , this will analyze the image in detail and describe its contents in as much detail as possible. | |
Args: | |
image_file_name (str): The file name of the image to analyze. | |
Returns: | |
str: The response text generated by the Gemini model. | |
""" | |
print("--- Analyzing Image ---") | |
print(f"Image URL/Path: {image_file_name}") | |
prompt = """ | |
Analyze the image in detail and describe its contents in as much detail as possible. | |
For example, give someone a chess board and describe where each piece is. | |
The description should include the following information: | |
- General overview of the image | |
- Details of important elements and features (e.g., location relationships, attributes, etc.) | |
- Identification of specific objects or characters (e.g., game piece names, positions, people, etc.) | |
# Steps | |
1. Examine the image as a whole and identify the main elements. | |
2. Examine each element in detail and identify what it is. | |
3. Develop a description of each element based on its characteristic relationships and positions. | |
4. Finally, summarize the overall scene or situation. | |
# Output Format | |
Provide detailed descriptions in paragraphs of text, using bullet points where necessary. | |
""" | |
try: | |
# Fetch the image data | |
if image_file_name.startswith("http"): | |
image_bytes = requests.get(image_file_name).content | |
else: | |
with open(image_file_name, "rb") as f: | |
image_bytes = f.read() | |
# Create image part | |
image_part = types.Part.from_bytes( | |
data=image_bytes, | |
mime_type="image/jpeg" | |
) | |
# Initialize the Gemini client | |
client = genai.Client(api_key=GOOGLE_API_KEY) | |
# Build contents with question text and image part | |
response = client.models.generate_content( | |
model="gemini-2.0-flash-exp", | |
contents=[ | |
prompt, | |
image_part | |
] | |
) | |
print("--- Gemini Response Received ---") | |
# Extract text from the response | |
if hasattr(response, 'text'): | |
print("Image Description : ", response.text) | |
return response.text | |
elif getattr(response, 'parts', None): | |
return "".join(part.text for part in response.parts if hasattr(part, 'text')) | |
else: | |
block_reason = "" | |
if response.prompt_feedback and response.prompt_feedback.block_reason: | |
block_reason = f" Reason: {response.prompt_feedback.block_reason.name}" | |
return f"Model did not return text content.{block_reason}" | |
except Exception as e: | |
print(f"Error processing image '{image_file_name}' with Gemini: {e}") | |
return f"Sorry, an error occurred while analyzing the image. Please check the image URL or path. Error details: {str(e)}" | |
# Audio Tool | |
def transcribe_audio(audio_path: str) -> str: | |
""" | |
Given an audio file path or URL, uploads the file to Gemini API and generates a speech transcript. | |
Args: | |
audio_path (str): The URL or local file path of the audio to transcribe. | |
Returns: | |
str: A Markdown-formatted transcript of the speech, or an error message. | |
""" | |
print("--- Transcribing Audio ---") | |
print(f"Audio Path: {audio_path}") | |
try: | |
# Initialize Gemini client | |
client = genai.Client(api_key=GOOGLE_API_KEY) | |
# Upload the audio file | |
uploaded = client.files.upload(file=audio_path) | |
prompt = "Generate a transcript of the speech." | |
# Generate transcript | |
response = client.models.generate_content( | |
model="gemini-2.0-flash", | |
contents=[prompt, uploaded] | |
) | |
print("--- Gemini Response Received ---") | |
# Extract transcript text | |
if hasattr(response, 'text'): | |
transcript = response.text | |
elif getattr(response, 'parts', None): | |
transcript = "".join(part.text for part in response.parts if hasattr(part, 'text')) | |
else: | |
transcript = "Model did not return text content." | |
print("Transcript : ", transcript) | |
# Format as Markdown | |
markdown_transcript = ( | |
"## Audio Transcription Result\n" | |
f"**Transcript:**\n{transcript}" | |
) | |
return markdown_transcript | |
except Exception as e: | |
error_msg = f"Error transcribing audio '{audio_path}': {str(e)}" | |
return f"**Error:** {error_msg}" | |
# Excel Tool | |
def excel_to_csv(excel_path: str) -> str: | |
""" | |
Given an Excel file path or URL and an optional sheet name, | |
reads the spreadsheet using openpyxl and returns its contents as CSV text. | |
Args: | |
excel_path (str): The URL or local file path of the Excel file to convert. | |
Returns: | |
str: The CSV-formatted content of the sheet. | |
""" | |
print("--- Converting Excel to CSV ---") | |
print(f"Excel Path: {excel_path}") | |
excel_path = os.path.join("./GAIA_resource/", excel_path) | |
try: | |
wb = load_workbook(filename=excel_path, data_only=True) | |
# Select worksheet | |
ws = wb.active | |
# Build CSV lines manually | |
lines = [] | |
for row in ws.iter_rows(values_only=True): | |
# Convert each cell to string, using empty string for None | |
str_cells = ["" if cell is None else str(cell) for cell in row] | |
# Join cells with commas | |
line = ",".join(str_cells) | |
lines.append(line) | |
# Combine all lines into one CSV string | |
print("Converted Excel to CSV result : ", lines) | |
return "\n".join(lines) | |
except Exception as e: | |
return f"Error converting Excel to CSV: {e}" | |
# Read text file | |
def LoadTextFileTool(file_path: str) -> str: | |
""" | |
This tool loads any text file | |
Args: | |
file_path (str): File Path | |
Returns: | |
str: Text file contents. | |
""" | |
print("---Load Text File Tool---") | |
print("File Path : ", file_path) | |
try: | |
# Decode bytes to ASCII string, replacing errors | |
with open(file_path, 'r', encoding='utf-8') as file: | |
return file.read() | |
except Exception as e: | |
return f"Error reading text file: {e}" | |
# Get task file | |
def GetTaskFileTool(file_name: str, task_id: str) -> str: | |
""" | |
This tool downloads the file content associated with the given task_id if exists. Returns absolute file path. | |
Args: | |
task_id (str): Task id | |
file_name (str) File name | |
Returns: | |
str: absolute file path | |
""" | |
print("---Get Task File Tool---") | |
print("File Name : ", file_name) | |
try: | |
response = requests.get(f"{DEFAULT_API_URL}/files/{task_id}", timeout=15) | |
response.raise_for_status() | |
with open(file_name, 'wb') as file: | |
file.write(response.content) | |
return os.path.abspath(file_name) | |
except TypeError as e: | |
return f"Error GetTaskFileTool '{file_name}' : {str(e)}" | |
except Exception as e: | |
return f"Error reading file: {e}" | |
# Call Agent Async | |
async def call_agent_async(query: str, runner, user_id, session_id): | |
"""Sends a query to the agent and prints the final response.""" | |
print(f"\n>>> User Query: {query}") | |
# Prepare the user's message in ADK format | |
content = types.Content(role='user', parts=[types.Part(text=query)]) | |
final_response_text = "Agent did not produce a final response." # Default | |
# Key Concept: run_async executes the agent logic and yields Events. | |
# We iterate through events to find the final answer. | |
async for event in runner.run_async(user_id=user_id, session_id=session_id, new_message=content): | |
# Key Concept: is_final_response() marks the concluding message for the turn. | |
if event.is_final_response(): | |
if event.content and event.content.parts: | |
# Assuming text response in the first part | |
final_response_text = event.content.parts[0].text | |
elif event.actions and event.actions.escalate: # Handle potential errors/escalations | |
final_response_text = f"Agent escalated: {event.error_message or 'No specific message.'}" | |
# Add more checks here if needed (e.g., specific error codes) | |
break # Stop processing events once the final response is found | |
print(f"<<< Agent Response: {final_response_text}") | |
return final_response_text # Return the final response text | |
# (Keep Constants as is) | |
# --- Constants --- | |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space" | |
# --- Basic Agent Definition --- | |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------ | |
#class BasicAgent: | |
# def __init__(self): | |
# print("BasicAgent initialized.") | |
# def __call__(self, question: str) -> str: | |
# print(f"Agent received question (first 50 chars): {question[:50]}...") | |
# #fixed_answer = "This is a default answer." | |
# #print(f"Agent returning fixed answer: {fixed_answer}") | |
# | |
# return fixed_answer | |
description_text = """ | |
You are GAIA Solver, a highly capable AI assistant designed to answer questions from the GAIA benchmark accurately and concisely using a suite of available tools. Your goal is to provide the precise answer in the requested format based *only* on the provided question text. | |
""" | |
instruction_text = """ | |
Thinking Process: | |
1. **Analyze Question & Identify Files:** Carefully read the question. Determine the core task and the **exact final answer format**. Check if the question explicitly mentions an attached file (image, Excel, audio, code). | |
2. **Identify Filename:** If a file is mentioned, identify its filename from the text (e.g., "Homework.mp3", "image.png"). If no specific filename is given for a required file type, state that you need the filename. **Do not guess filenames.** | |
3. **Plan:** Create a step-by-step plan using tools. If a file is needed, include the correct tool call with the identified filename. | |
4. **Execute & Refine:** Execute the plan. Pass correct arguments (especially filenames). Evaluate tool outputs. If errors occur (e.g., file not found, API errors) or info is insufficient, revise the plan (e.g., use different tool prompts). | |
5. **Synthesize Answer:** Combine information. Use `coding_agent` for final formatting/calculations. | |
6. **Final Output:** Generate **only the final answer** in the requested format. No extra text. If the answer cannot be found or a required filename was missing/invalid, output: "I could not find the answer." | |
Constraints: | |
- Base actions *only* on the provided question text. | |
- Adhere strictly to the requested output format. | |
""" | |
async def main(): | |
api_url = DEFAULT_API_URL | |
questions_url = f"{api_url}/questions" | |
submit_url = f"{api_url}/submit" | |
# 1. Instantiate Agent ( modify this part to create your agent) | |
try: | |
root_agent = Agent( | |
name = "root_agent", | |
model = "gemini-2.5-pro-preview-03-25", | |
description = description_text, | |
instruction = instruction_text, | |
tools = [ | |
agent_tool.AgentTool(agent=search_agent), | |
agent_tool.AgentTool(agent=coding_agent), | |
agent_tool.AgentTool(agent=code_execution_agent), | |
understand_youtube_video, | |
understand_image, | |
transcribe_audio, | |
excel_to_csv, | |
GetTaskFileTool, | |
LoadTextFileTool, | |
] | |
) | |
except Exception as e: | |
print(f"Error instantiating agent: {e}") | |
return f"Error initializing agent: {e}", None | |
# 2. Fetch Questions | |
print(f"Fetching questions from: {questions_url}") | |
try: | |
response = requests.get(questions_url, timeout=15) | |
response.raise_for_status() | |
questions_data = response.json() | |
if not questions_data: | |
print("Fetched questions list is empty.") | |
return "Fetched questions list is empty or invalid format.", None | |
print(f"Fetched {len(questions_data)} questions.") | |
except requests.exceptions.RequestException as e: | |
print(f"Error fetching questions: {e}") | |
return f"Error fetching questions: {e}", None | |
except requests.exceptions.JSONDecodeError as e: | |
print(f"Error decoding JSON response from questions endpoint: {e}") | |
print(f"Response text: {response.text[:500]}") | |
return f"Error decoding server response for questions: {e}", None | |
except Exception as e: | |
print(f"An unexpected error occurred fetching questions: {e}") | |
return f"An unexpected error occurred fetching questions: {e}", None | |
# 3. Run your Agent | |
results_log = [] | |
answers_payload = [] | |
print(f"Running agent on {len(questions_data)} questions...") | |
for item in questions_data: | |
task_id = item.get("task_id") | |
question_text = item.get("question") | |
file_name = item.get("file_name") | |
if task_id: | |
question_text += " task_id = " + task_id | |
if file_name: | |
question_text += " file_name = " + file_name | |
if not task_id or question_text is None: | |
print(f"Skipping item with missing task_id or question: {item}") | |
continue | |
try: | |
APP_NAME = "gaia_agent" | |
USER_ID = "user_1" | |
SESSION_ID = item.get("task_id") | |
session_service = InMemorySessionService() | |
session = session_service.create_session( | |
app_name=APP_NAME, | |
user_id=USER_ID, | |
session_id=SESSION_ID | |
) | |
runner = Runner( | |
agent=root_agent, # The agent we want to run | |
app_name=APP_NAME, # Associates runs with our app | |
session_service=session_service # Uses our session manager | |
) | |
submitted_answer = await call_agent_async(question_text, | |
runner=runner, | |
user_id=USER_ID, | |
session_id=SESSION_ID | |
) | |
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}"}) | |
if os.path.exists(file_name): | |
os.remove(file_name) | |
if not answers_payload: | |
print("Agent did not produce any answers to submit.") | |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log) | |
# 4. Prepare Submission | |
#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) | |
# ในใฏใชใใใ็ดๆฅๅฎ่กใใใๅ ดๅใซใใใใ้ๅงใใพใ | |
if __name__ == "__main__": | |
# asyncio.run() ใไฝฟใฃใฆ้ๅๆใฎ main ้ขๆฐใๅฎ่กใใพใ | |
# ใใใใชใใจ async def main() ใฏๅฎ่กใใใพใใ | |
try: | |
asyncio.run(main()) | |
except Exception as e: | |
print(f"An error occurred during the asyncio run: {e}") |