import gradio as gr import requests import os from dotenv import load_dotenv from PIL import Image import io import google.generativeai as genai from huggingface_hub import HfApi # Not strictly needed for functionality but good for HF context import json # For robust error logging of API responses # Load environment variables from .env file for local development load_dotenv() # --- Configuration --- # API URL for the GAIA course assignment (as per the template) COURSE_API_URL = os.getenv("API_URL", "https://agents-course-unit4-scoring.hf.space") # Global variables for API keys, can be updated by UI or .env HF_TOKEN = os.getenv("HF_TOKEN") GEMINI_API_KEY = os.getenv("GEMINI_API_KEY") SERPAPI_API_KEY = os.getenv("SERPAPI_API_KEY") # Configure Gemini once globally, can be reconfigured if key is input via UI if GEMINI_API_KEY: genai.configure(api_key=GEMINI_API_KEY) else: print("Warning: GEMINI_API_KEY not found in environment variables. Please provide it via UI or set it as an env var.") # --- Tools --- def search_web_serpapi(query: str, api_key: str) -> str: """Performs a web search using SerpApi and returns formatted snippets.""" if not api_key: return "Web search skipped: SERPAPI_API_KEY not configured." try: from serpapi import GoogleSearch params = { "q": query, "api_key": api_key, "num": 3 # Get top 3 results } search = GoogleSearch(params) results = search.get_dict() snippets = [] if "organic_results" in results: for result in results.get("organic_results", [])[:3]: # Max 3 snippets snippet = result.get("snippet", "") title = result.get("title", "") link = result.get("link", "") if snippet: # Only include if snippet is not empty snippets.append(f"Title: {title}\nSnippet: {snippet}\nSource: {link}") if snippets: return "Relevant information from web search:\n" + "\n\n".join(snippets) else: return "No relevant snippets found from web search." except ImportError: return "SerpApi library not installed. Web search skipped." except Exception as e: return f"Web search failed: {str(e)}" # --- LLM Interaction --- def ask_gemini_model(prompt_text: str, image_bytes: bytes = None, api_key: str = None) -> str: """ Asks the Gemini model a question, potentially with an image. Uses gemini-1.5-flash for a balance of capability and speed. """ current_gemini_key = api_key or GEMINI_API_KEY # Prioritize key passed directly (e.g. from UI) if not current_gemini_key: return "Error: GEMINI_API_KEY not configured." try: # Ensure genai is configured with the potentially updated key if genai. अभीष्ट.api_key != current_gemini_key: # Accessing the configured key, 'बिना' is a placeholder, use actual API if exists genai.configure(api_key=current_gemini_key) model_name = "gemini-1.5-flash-latest" generation_config = genai.types.GenerationConfig( candidate_count=1, temperature=0.2, # Lower temperature for more factual and deterministic answers max_output_tokens=2048, # GAIA answers are generally concise ) safety_settings = [ # Standard safety settings {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"}, {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_MEDIUM_AND_ABOVE"}, {"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"}, {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"}, ] model = genai.GenerativeModel( model_name=model_name, generation_config=generation_config, safety_settings=safety_settings ) content_parts = [prompt_text] if image_bytes: try: img_pil = Image.open(io.BytesIO(image_bytes)) # Gemini API supports various image formats directly with PIL Image object content_parts.append(img_pil) except Exception as e: return f"Error: Could not process image. {str(e)}" response = model.generate_content(content_parts) return response.text.strip() except Exception as e: print(f"Error calling Gemini API: {e}") return f"Error: Could not get response from Gemini. {str(e)}" # --- Agent Logic --- def solve_single_question(question_data: dict, current_hf_token: str, current_gemini_key: str, current_serpapi_key: str) -> dict: """Solves a single GAIA question.""" task_id = question_data["task_id"] question_text = question_data["question"] file_name = question_data.get("file_name") # Use .get() for optional field print(f"\nProcessing Task ID: {task_id}") print(f"Question: {question_text}") file_context_for_prompt = "" image_bytes_for_llm = None if file_name: print(f"File detected: {file_name}") # File download URL - no auth headers as per template for GET /files file_url = f"{COURSE_API_URL}/files/{task_id}" try: response = requests.get(file_url, timeout=30) # Added timeout response.raise_for_status() file_content = response.content if file_name.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.webp', '.heic', '.heif')): image_bytes_for_llm = file_content file_context_for_prompt = f"An image named '{file_name}' is associated with this question and has been provided for analysis." print(f"Image '{file_name}' downloaded ({len(file_content)} bytes) and will be sent to LLM.") elif file_name.lower().endswith(('.txt', '.csv', '.json', '.md', '.html', '.xml')): try: decoded_content = file_content.decode('utf-8') except UnicodeDecodeError: decoded_content = file_content.decode('latin-1', errors='replace') # Fallback encoding file_context_for_prompt = f"The content of the text-based file '{file_name}' is:\n{decoded_content}" print(f"Text file '{file_name}' downloaded and content extracted.") else: file_context_for_prompt = f"A file named '{file_name}' was provided. Its content type is not automatically processed for inclusion in this text prompt, but if it's an image, it will be sent to the LLM." print(f"File '{file_name}' downloaded, type handling is basic (passed as image if common image type).") # Attempt to treat as image if type is ambiguous but potentially an image try: Image.open(io.BytesIO(file_content)) image_bytes_for_llm = file_content file_context_for_prompt += " (Attempting to treat as image)." print("Treated unknown file as potential image.") except Exception: print("Unknown file type is not a processable image.") except requests.exceptions.RequestException as e: print(f"Error downloading file '{file_name}' for task {task_id}: {e}") file_context_for_prompt = f"Error: Could not download file '{file_name}'. This may impact the ability to answer the question." # Web Search print(f"Performing web search for: {question_text[:60]}...") search_results_context = search_web_serpapi(question_text, current_serpapi_key) print(f"Web search results snippet: {search_results_context[:100]}...") # Construct prompt for Gemini # This prompt is critical and needs to guide the LLM to produce EXACTLY the required output format. prompt = f"""You are an expert AI assistant. Your task is to answer the following question. Read the question carefully and provide only the direct answer. Do NOT include any introductory phrases (e.g., "The answer is...", "Based on the information..."), explanations, or any text other than the answer itself. Strictly adhere to any formatting requirements mentioned in the question (e.g., comma-separated list, specific order, capitalization, pluralization). If the question asks for a list, provide only the list. If it asks for a specific value, provide only that value. Question: "{question_text}" """ if file_context_for_prompt: prompt += f"\nContext from provided file ('{file_name}'):\n{file_context_for_prompt}\n" if search_results_context and "skipped" not in search_results_context.lower() and "failed" not in search_results_context.lower(): prompt += f"\n{search_results_context}\n" prompt += "\nAnswer:" # LLM should start its response right after this. print(f"Prompt for LLM (first 150 chars): {prompt[:150].replace(chr(10), ' ')}...") # Log a snippet llm_answer = ask_gemini_model(prompt, image_bytes_for_llm, current_gemini_key) # Minimal cleanup, relying on good prompting. final_answer = llm_answer.strip() # Ensure no "FINAL ANSWER" text as per instructions if "FINAL ANSWER:" in final_answer: final_answer = final_answer.split("FINAL ANSWER:", 1)[-1].strip() if "FINAL ANSWER" in final_answer: # A bit more general final_answer = final_answer.replace("FINAL ANSWER", "").strip() print(f"LLM Raw Answer for Task {task_id}: {llm_answer}") print(f"Final Processed Answer for Task {task_id}: {final_answer}") return {"task_id": task_id, "submitted_answer": final_answer} # --- Gradio App Main Function --- def run_assignment_flow(hf_username_or_spacename_ui: str, hf_token_ui: str, gemini_key_ui: str, serpapi_key_ui: str): global HF_TOKEN, GEMINI_API_KEY, SERPAPI_API_KEY # Allow updating global vars if UI provides new keys log_output = "Initializing assignment run...\n" if not hf_username_or_spacename_ui: return "Error: Hugging Face Username (or Space Name like 'user/RepoName') is required for submission.", "", "", "" # Update API keys from UI if provided, otherwise use existing (from env vars or previous runs) current_hf_token = hf_token_ui if hf_token_ui else HF_TOKEN current_gemini_key = gemini_key_ui if gemini_key_ui else GEMINI_API_KEY current_serpapi_key = serpapi_key_ui if serpapi_key_ui else SERPAPI_API_KEY if not current_hf_token: return "Error: Hugging Face Token is required for submission. Please provide it via UI or set HF_TOKEN environment variable.", "", "", "" if not current_gemini_key: return "Error: Gemini API Key is required. Please provide it via UI or set GEMINI_API_KEY environment variable.", "", "", "" # Update global vars for subsequent calls within this session if UI provided them HF_TOKEN, GEMINI_API_KEY, SERPAPI_API_KEY = current_hf_token, current_gemini_key, current_serpapi_key # Re-configure Gemini if a new key was provided via UI # This check is slightly complex because genai. अभीष्ट.api_key is not a public API. # Instead, just reconfigure if current_gemini_key is valid. if current_gemini_key: try: genai.configure(api_key=current_gemini_key) log_output += "Gemini API Key configured.\n" except Exception as e: log_output += f"Error configuring Gemini with provided key: {e}\n" return log_output, "", "", "" log_output += f"Using API URL: {COURSE_API_URL}\n" # 1. Get questions (No auth header for GET /questions as per template) questions_url = f"{COURSE_API_URL}/questions" try: log_output += f"Fetching questions from {questions_url}...\n" response = requests.get(questions_url, timeout=30) response.raise_for_status() questions = response.json() log_output += f"Successfully fetched {len(questions)} questions.\n" if not questions: log_output += "No questions received. Check API or token if applicable.\n" return log_output, "", "", "" except requests.exceptions.RequestException as e: log_output += f"Error fetching questions: {e}\nResponse text: {response.text if 'response' in locals() else 'N/A'}\n" return log_output, "", "", "" except json.JSONDecodeError as e: log_output += f"Error decoding JSON from questions response: {e}. Response content: {response.text if 'response' in locals() else 'N/A'}\n" return log_output, "", "", "" # 2. Solve each question all_answers = [] for q_data in questions: if not isinstance(q_data, dict) or "task_id" not in q_data or "question" not in q_data: log_output += f"Skipping invalid question data format: {q_data}\n" all_answers.append({"task_id": q_data.get("task_id", f"unknown_task_{len(all_answers)}"), "submitted_answer": "Error: Invalid question data format"}) continue try: ans = solve_single_question(q_data, current_hf_token, current_gemini_key, current_serpapi_key) all_answers.append(ans) log_output += f"Processed Task ID: {ans['task_id']}, Answer Snippet: '{str(ans['submitted_answer'])[:50]}...'\n" except Exception as e: task_id_err = q_data.get('task_id', 'N/A') log_output += f"Critical error solving question {task_id_err}: {e}\n" all_answers.append({"task_id": task_id_err, "submitted_answer": f"Error processing question: {e}"}) if not all_answers or len(all_answers) != len(questions): log_output += "Error: Number of answers does not match number of questions. Aborting submission.\n" return log_output, json.dumps(all_answers, indent=2), "", "" # 3. Prepare submission username_for_payload = hf_username_or_spacename_ui if "/" in hf_username_or_spacename_ui: # If "user/space" is given, extract "user" for payload username_for_payload = hf_username_or_spacename_ui.split("/")[0] space_id = os.getenv("SPACE_ID") # e.g. "YourUser/YourSpaceName" if space_id: agent_code_link = f"https://huggingface.co/spaces/{space_id}/tree/main" else: # Fallback if not running on an HF Space (e.g. local dev) log_output += "Warning: SPACE_ID env var not found. Constructing agent_code_link from input. Ensure this is correct for submission.\n" if "/" in hf_username_or_spacename_ui: # Use the full "user/space" if provided in the input field agent_code_link = f"https://huggingface.co/spaces/{hf_username_or_spacename_ui}/tree/main" else: # If only username provided, append a placeholder - user must ensure this is correct agent_code_link = f"https://huggingface.co/spaces/{hf_username_or_spacename_ui}/YOUR_SPACE_NAME_HERE/tree/main" log_output += f"Constructed a placeholder code link: {agent_code_link}. Update 'YOUR_SPACE_NAME_HERE' if needed.\n" log_output += f"Using Username for Payload: {username_for_payload}\n" log_output += f"Using Agent Code Link: {agent_code_link}\n" submission_data = { "username": username_for_payload, "agent_code": agent_code_link, "answers": all_answers } # 4. Submit (Requires HF_TOKEN in header) submit_url = f"{COURSE_API_URL}/submit" log_output += f"Submitting answers to {submit_url}...\n" headers_submit = {"Authorization": f"Bearer {current_hf_token}"} try: response = requests.post(submit_url, json=submission_data, headers=headers_submit, timeout=60) response.raise_for_status() submission_result = response.json() log_output += f"Submission successful! Result: {submission_result}\n" score = submission_result.get("score", "N/A") # leaderboard_html = submission_result.get("leaderboard", "") # If API returns HTML answers_str = json.dumps(all_answers, indent=2) # Nicely formatted JSON for display result_str = f"Score: {score}\nFull Submission Result:\n{json.dumps(submission_result, indent=2)}" return log_output, answers_str, result_str, agent_code_link except requests.exceptions.RequestException as e: err_msg = f"Error submitting answers: {e}." if 'response' in locals() and response is not None: err_msg += f" Status: {response.status_code}. Response: {response.text}" log_output += f"{err_msg}\n" return log_output, json.dumps(all_answers, indent=2), "Submission failed. Check logs.", agent_code_link except json.JSONDecodeError as e: # If server returns non-JSON error log_output += f"Error decoding JSON from submission response: {e}. Response content: {response.text if 'response' in locals() else 'N/A'}\n" return log_output, json.dumps(all_answers, indent=2), "Submission failed to decode server response.", agent_code_link # --- Gradio Interface Definition --- with gr.Blocks(theme=gr.themes.Soft()) as demo: gr.Markdown("# GAIA Agent - Hugging Face Agents Course Final Assignment 🚀") gr.Markdown( "This agent attempts to solve questions from a subset of the GAIA benchmark. " "It uses Gemini for reasoning, SerpApi for web search, and handles file inputs." ) with gr.Accordion("Setup (API Keys & User Info - use Space Secrets for deployment)", open=False): with gr.Row(): hf_username_input = gr.Textbox( label="HF Username or Space Name", placeholder="Enter your HF Username (e.g., 'MyUser') or Space Name (e.g. 'MyUser/MySpace')", info="Username is for the submission payload. If Space Name (user/repo) is entered, 'user' part is taken as username. Space Name also helps form code link if not on HF Space." ) with gr.Row(): hf_token_input = gr.Textbox( label="Hugging Face Token (hf_xxx)", type="password", placeholder="Uses HF_TOKEN secret if blank" ) gemini_api_key_input = gr.Textbox( label="Gemini API Key (AIza...)", type="password", placeholder="Uses GEMINI_API_KEY secret if blank" ) serpapi_api_key_input = gr.Textbox( label="SerpApi API Key (serp_...)", type="password", placeholder="Uses SERPAPI_API_KEY secret if blank" ) run_button = gr.Button("Run GAIA Assignment ✨", variant="primary") gr.Markdown("## 📊 Results & Logs") with gr.Tabs(): with gr.TabItem("📜 Run Log"): log_output_display = gr.Textbox(label="Full Log Output", lines=15, interactive=False, show_copy_button=True) with gr.TabItem("📝 Submitted Answers"): answers_display = gr.Code(label="Answers Sent to API (JSON)", language="json", lines=15, interactive=False) with gr.TabItem("🏆 Submission Score & Details"): submission_result_display = gr.Code(label="Score and Full API Response (JSON)", language="json", lines=15, interactive=False) agent_code_link_display = gr.Textbox(label="Agent Code Link Used in Submission", interactive=False, show_copy_button=True) run_button.click( run_assignment_flow, inputs=[hf_username_input, hf_token_input, gemini_api_key_input, serpapi_api_key_input], outputs=[log_output_display, answers_display, submission_result_display, agent_code_link_display] ) gr.Markdown("---") gr.Markdown("### About GAIA") gr.HTML("""

GAIA is a benchmark for evaluating AI assistants on real-world tasks requiring reasoning, multimodal understanding, web Browse, and tool use. Tasks are conceptually simple for humans but challenging for current AI systems.

Key GAIA Principles:

This agent aims for the 30% or higher score required for the course on a filtered subset of Level 1 questions.

""") if __name__ == "__main__": # This allows running the Gradio app locally for testing. # Hugging Face Spaces will use the demo.launch() from its own mechanisms or just run the file. # For local: HF_TOKEN, GEMINI_API_KEY, SERPAPI_API_KEY should be in a .env file or entered in UI. if not (HF_TOKEN and GEMINI_API_KEY and SERPAPI_API_KEY): print("Warning: One or more API keys (HF_TOKEN, GEMINI_API_KEY, SERPAPI_API_KEY) are not set in environment variables.") print("Please set them in a .env file or provide them via the UI for local execution.") demo.launch(debug=True) # debug=True for more detailed Gradio logs locally