Spaces:
Build error
Build error
Chris Ellerson commited on
Commit ·
68ed57f
1
Parent(s): c0edb03
initial commit of agent with score of 60
Browse filesFiles changed (11)
- .env.exampleAdded+1
- .gitignoreAdded+12
- README.md+156-6
- __pycache__/api_integration.cpython-311.pycAdded
- __pycache__/core_agent.cpython-311.pycAdded
- api_integration.pyAdded+39
- app.pyAdded+279
- core_agent.pyAdded+492
- local_test.pyAdded+249
- main.pyAdded+277
- requirements.txtAdded+6
1XAI_API_KEY=your-groq-api-key-here123456789101112.envenv.examplegaia-env/*/gaia-envproject_planning.mdprojectdescription.mdtest_agent.pytest_groq_api.pytest_groq_api_with_dotenv.pytest_results.jsontest_xai_api.pyupdate_groq_key.py12345678910111213---title: AgentCourseFinalProjectemoji: 🌍colorFrom: purplecolorTo: greensdk: gradiosdk_version: 5.26.0app_file: app.pypinned: falseshort_description: Agent Code for Final Project---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163---title: GAIA Agent for Hugging Face Agents Courseemoji: 🕵🏻♂️colorFrom: indigocolorTo: indigosdk: gradiosdk_version: 5.25.2app_file: app.pypinned: falsehf_oauth: true# optional, default duration is 8 hours/480 minutes. Max duration is 30 days/43200 minutes.hf_oauth_expiration_minutes: 480---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference# GAIA Agent for Hugging Face Agents CourseThis project implements a powerful intelligent agent using the SmolAgents framework to tackle the GAIA benchmark questions for the Hugging Face Agents course final assessment.## Project OverviewThe GAIA benchmark consists of challenging questions that require an agent to use various tools, including web search, file processing, and reasoning capabilities. This agent is designed to:1. Receive questions from the GAIA API2. Process and understand the questions3. Use appropriate tools to find answers4. Format and return precise answers## Features- **SmolAgents Integration**: Uses CodeAgent for flexible problem-solving with Python code execution- **Multi-Model Support**:- Compatible with Hugging Face models- OpenAI models (GPT-4o and others)- X.AI's Grok models- Anthropic, Cohere, and Mistral models via LiteLLM- **Enhanced Tool Suite**:- Web search via DuckDuckGo- Python interpreter for code execution- File handling (reading, saving, downloading)- Data analysis for CSV and Excel files- Image processing with OCR capabilities (when available)- **Flexible Environment Configuration**:- Easy setup via environment variables or .env file- Fallback mechanisms for missing dependencies- Support for both local and secure E2B code execution- **Answer Processing**:- Special handling for reversed text questions- Precise answer formatting for benchmark submission- Automatic cleanup of model responses for exact matching- **Interactive UI**: Gradio interface for running the agent and submitting answers## Setup### Prerequisites- Python 3.8+- Hugging Face account- API keys for your preferred models (HuggingFace, OpenAI, X.AI, etc.)### Installation1. Clone this repository2. Install the required dependencies:```bashpip install -r requirements.txt```3. Copy the example environment file and add your API keys:```bashcp env.example .env# Edit .env with your API keys and configuration```### ConfigurationConfigure the agent by setting these environment variables or editing the `.env` file:#### API Keys```HUGGINGFACEHUB_API_TOKEN=your_huggingface_token_hereOPENAI_API_KEY=your_openai_key_hereXAI_API_KEY=your_xai_api_key_here # For X.AI/Grok models```#### Agent Configuration```AGENT_MODEL_TYPE=OpenAIServerModel # HfApiModel, InferenceClientModel, LiteLLMModel, OpenAIServerModelAGENT_MODEL_ID=gpt-4o # Model ID depends on the model typeAGENT_TEMPERATURE=0.2AGENT_EXECUTOR_TYPE=local # local or e2b for secure executionAGENT_VERBOSE=true # Set to true for detailed logging```#### Advanced Configuration```AGENT_PROVIDER=hf-inference # Provider for InferenceClientModelAGENT_TIMEOUT=120 # Timeout in seconds for API callsAGENT_API_BASE=https://api.groq.com/openai/v1 # For X.AI when using OpenAIServerModel```## Usage### Running the AgentLaunch the Gradio interface with:```bashpython app.py```Then:1. Log in to your Hugging Face account using the button in the interface2. Click "Run Evaluation & Submit All Answers"### TestingTo test the agent with sample questions before running the full evaluation:```bashpython test_agent.py```For more focused testing with specific APIs:```bashpython test_groq_api.py # Test X.AI/Groq API integrationpython test_xai_api.py # Test X.AI API integration```## Project Structure- `app.py`: Main application with Gradio interface- `core_agent.py`: Agent implementation with SmolAgents framework- `api_integration.py`: Client for interacting with GAIA API- `test_agent.py`: Testing script with sample questions- `test_groq_api.py` & `test_xai_api.py`: API-specific test scripts- `update_groq_key.py`: Utility for updating API keys- `project_planning.md`: Development roadmap and progress tracking- `requirements.txt`: Project dependencies## Tools ImplementationThe agent includes several custom tools:1. **save_and_read_file**: Save content to a temporary file and return the path2. **download_file_from_url**: Download a file from a URL and save it locally3. **extract_text_from_image**: OCR for extracting text from images (requires pytesseract)4. **analyze_csv_file**: Load and analyze CSV files using pandas5. **analyze_excel_file**: Load and analyze Excel files using pandas## Resources- [GAIA Benchmark Information](https://huggingface.co/spaces/gaia-benchmark/leaderboard)- [SmolAgents Documentation](https://huggingface.co/docs/smolagents/en/index)- [Hugging Face Agents Course](https://huggingface.co/agents-course)## LicenseThis project is licensed under the MIT License.
123456789101112131415161718192021222324252627282930313233343536373839import requestsfrom typing import List, Dict, Anyfrom core_agent import GAIAAgent
class GAIAApiClient: def __init__(self, api_url="https://agents-course-unit4-scoring.hf.space"): self.api_url = api_url self.questions_url = f"{api_url}/questions" self.submit_url = f"{api_url}/submit" self.files_url = f"{api_url}/files" def get_questions(self) -> List[Dict[str, Any]]: """Fetch all evaluation questions""" response = requests.get(self.questions_url) response.raise_for_status() return response.json() def get_random_question(self) -> Dict[str, Any]: """Fetch a single random question""" response = requests.get(f"{self.api_url}/random-question") response.raise_for_status() return response.json() def get_file(self, task_id: str) -> bytes: """Download a file for a specific task""" response = requests.get(f"{self.files_url}/{task_id}") response.raise_for_status() return response.content def submit_answers(self, username: str, agent_code: str, answers: List[Dict[str, Any]]) -> Dict[str, Any]: """Submit agent answers and get score""" data = { "username": username, "agent_code": agent_code, "answers": answers } response = requests.post(self.submit_url, json=data) response.raise_for_status() return response.json()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279import osimport gradio as grimport requestsimport inspectimport pandas as pdfrom core_agent import GAIAAgent
# (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.") # Initialize the GAIAAgent with local execution try: # Load environment variables if dotenv is available try: import dotenv dotenv.load_dotenv() print("Loaded environment variables from .env file") except ImportError: print("python-dotenv not installed, continuing with environment as is") # Try to load API keys from environment api_key = os.getenv("XAI_API_KEY") or os.getenv("OPENAI_API_KEY") or os.getenv("HUGGINGFACEHUB_API_TOKEN") # If we have at least one API key, use a model-based approach if api_key: # Default model parameters model_type = os.getenv("AGENT_MODEL_TYPE", "OpenAIServerModel") model_id = os.getenv("AGENT_MODEL_ID", "gpt-4o") if os.getenv("XAI_API_KEY"): # Use X.AI API with OpenAIServerModel self.gaia_agent = GAIAAgent( model_type="OpenAIServerModel", model_id="grok-3-latest", # X.AI's model api_key=os.getenv("XAI_API_KEY"), api_base="https://api.x.ai/v1", # X.AI's endpoint, not Groq temperature=0.2, executor_type="local", verbose=False ) print("Using OpenAIServerModel with X.AI API") elif model_type == "HfApiModel" and os.getenv("HUGGINGFACEHUB_API_TOKEN"): # Use Hugging Face API self.gaia_agent = GAIAAgent( model_type="HfApiModel", model_id=model_id, api_key=os.getenv("HUGGINGFACEHUB_API_TOKEN"), temperature=0.2, executor_type="local", verbose=False ) print(f"Using HfApiModel with model_id: {model_id}") else: # Default to OpenAI API self.gaia_agent = GAIAAgent( model_type="OpenAIServerModel", model_id=model_id, api_key=os.getenv("OPENAI_API_KEY"), temperature=0.2, executor_type="local", verbose=False ) print(f"Using OpenAIServerModel with model_id: {model_id}") else: # No API keys available, use a local model setup with minimal dependencies self.gaia_agent = GAIAAgent( model_type="HfApiModel", model_id="gpt2", # Simple model for basic testing temperature=0.2, executor_type="local", verbose=False ) print("Warning: No API keys found. Using a basic local execution setup.") except Exception as e: print(f"Error initializing GAIAAgent: {e}") self.gaia_agent = None print("WARNING: Failed to initialize agent. Falling back to basic responses.") def __call__(self, question: str) -> str: print(f"Agent received question (first 50 chars): {question[:50]}...") # Check if we have a functioning GAIA agent if self.gaia_agent: try: # Process the question using the GAIA agent answer = self.gaia_agent.answer_question(question) print(f"Agent generated answer: {answer[:50]}..." if len(answer) > 50 else f"Agent generated answer: {answer}") return answer except Exception as e: print(f"Error processing question: {e}") # Fall back to a simple response on error return "An error occurred while processing your question. Please check the agent logs for details." else: # We don't have a valid agent, provide a basic response return "The agent is not properly initialized. Please check your API keys and configuration."
def run_and_submit_all( profile: gr.OAuthProfile | None): """ Fetches all questions, runs the BasicAgent on them, submits all answers, and displays the results. """ # --- Determine HF Space Runtime URL and Repo URL --- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
if profile: username= f"{profile.username}" print(f"User logged in: {username}") else: print("User not logged in.") return "Please Login to Hugging Face with the button.", None
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: agent = BasicAgent() except Exception as e: print(f"Error instantiating agent: {e}") return f"Error initializing agent: {e}", None # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public) agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" print(agent_code)
# 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") if not task_id or question_text is None: print(f"Skipping item with missing task_id or question: {item}") continue try: 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: 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 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)
# 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.") results_df = pd.DataFrame(results_log) return final_status, results_df 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) results_df = pd.DataFrame(results_log) return status_message, results_df except requests.exceptions.Timeout: status_message = "Submission Failed: The request timed out." print(status_message) results_df = pd.DataFrame(results_log) return status_message, results_df except requests.exceptions.RequestException as e: status_message = f"Submission Failed: Network error - {e}" print(status_message) results_df = pd.DataFrame(results_log) return status_message, results_df except Exception as e: status_message = f"An unexpected error occurred during submission: {e}" print(status_message) results_df = pd.DataFrame(results_log) return status_message, results_df
# --- Build Gradio Interface using Blocks ---with gr.Blocks() as demo: gr.Markdown("# Basic Agent Evaluation Runner") gr.Markdown( """ **Instructions:**
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ... 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission. 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
--- **Disclaimers:** Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions). This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async. """ )
gr.LoginButton()
run_button = gr.Button("Run Evaluation & Submit All Answers")
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False) # Removed max_rows=10 from DataFrame constructor results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
run_button.click( fn=run_and_submit_all, outputs=[status_output, results_table] )
if __name__ == "__main__": print("\n" + "-"*30 + " App Starting " + "-"*30) # Check for SPACE_HOST and SPACE_ID at startup for information space_host_startup = os.getenv("SPACE_HOST") space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
if space_host_startup: print(f"✅ SPACE_HOST found: {space_host_startup}") print(f" Runtime URL should be: https://{space_host_startup}.hf.space") else: print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
if space_id_startup: # Print repo URLs if SPACE_ID is found print(f"✅ SPACE_ID found: {space_id_startup}") print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}") print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main") else: print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
print("-"*(60 + len(" App Starting ")) + "\n")
print("Launching Gradio Interface for Basic Agent Evaluation...") demo.launch(debug=True, share=False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492from smolagents import ( CodeAgent, DuckDuckGoSearchTool, HfApiModel, LiteLLMModel, OpenAIServerModel, PythonInterpreterTool, tool, InferenceClientModel)from typing import List, Dict, Any, Optionalimport osimport tempfileimport reimport jsonimport requestsfrom urllib.parse import urlparse
@tooldef save_and_read_file(content: str, filename: Optional[str] = None) -> str: """ Save content to a temporary file and return the path. Useful for processing files from the GAIA API. Args: content: The content to save to the file filename: Optional filename, will generate a random name if not provided Returns: Path to the saved file """ temp_dir = tempfile.gettempdir() if filename is None: temp_file = tempfile.NamedTemporaryFile(delete=False) filepath = temp_file.name else: filepath = os.path.join(temp_dir, filename) # Write content to the file with open(filepath, 'w') as f: f.write(content) return f"File saved to {filepath}. You can read this file to process its contents."
@tooldef download_file_from_url(url: str, filename: Optional[str] = None) -> str: """ Download a file from a URL and save it to a temporary location. Args: url: The URL to download from filename: Optional filename, will generate one based on URL if not provided Returns: Path to the downloaded file """ try: # Parse URL to get filename if not provided if not filename: path = urlparse(url).path filename = os.path.basename(path) if not filename: # Generate a random name if we couldn't extract one import uuid filename = f"downloaded_{uuid.uuid4().hex[:8]}" # Create temporary file temp_dir = tempfile.gettempdir() filepath = os.path.join(temp_dir, filename) # Download the file response = requests.get(url, stream=True) response.raise_for_status() # Save the file with open(filepath, 'wb') as f: for chunk in response.iter_content(chunk_size=8192): f.write(chunk) return f"File downloaded to {filepath}. You can now process this file." except Exception as e: return f"Error downloading file: {str(e)}"
@tooldef extract_text_from_image(image_path: str) -> str: """ Extract text from an image using pytesseract (if available). Args: image_path: Path to the image file Returns: Extracted text or error message """ try: # Try to import pytesseract import pytesseract from PIL import Image # Open the image image = Image.open(image_path) # Extract text text = pytesseract.image_to_string(image) return f"Extracted text from image:\n\n{text}" except ImportError: return "Error: pytesseract is not installed. Please install it with 'pip install pytesseract' and ensure Tesseract OCR is installed on your system." except Exception as e: return f"Error extracting text from image: {str(e)}"
@tooldef analyze_csv_file(file_path: str, query: str) -> str: """ Analyze a CSV file using pandas and answer a question about it. Args: file_path: Path to the CSV file query: Question about the data Returns: Analysis result or error message """ try: import pandas as pd # Read the CSV file df = pd.read_csv(file_path) # Run various analyses based on the query result = f"CSV file loaded with {len(df)} rows and {len(df.columns)} columns.\n" result += f"Columns: {', '.join(df.columns)}\n\n" # Add summary statistics result += "Summary statistics:\n" result += str(df.describe()) return result except ImportError: return "Error: pandas is not installed. Please install it with 'pip install pandas'." except Exception as e: return f"Error analyzing CSV file: {str(e)}"
@tooldef analyze_excel_file(file_path: str, query: str) -> str: """ Analyze an Excel file using pandas and answer a question about it. Args: file_path: Path to the Excel file query: Question about the data Returns: Analysis result or error message """ try: import pandas as pd # Read the Excel file df = pd.read_excel(file_path) # Run various analyses based on the query result = f"Excel file loaded with {len(df)} rows and {len(df.columns)} columns.\n" result += f"Columns: {', '.join(df.columns)}\n\n" # Add summary statistics result += "Summary statistics:\n" result += str(df.describe()) return result except ImportError: return "Error: pandas and openpyxl are not installed. Please install them with 'pip install pandas openpyxl'." except Exception as e: return f"Error analyzing Excel file: {str(e)}"
class GAIAAgent: def __init__( self, model_type: str = "HfApiModel", model_id: Optional[str] = None, api_key: Optional[str] = None, api_base: Optional[str] = None, temperature: float = 0.2, executor_type: str = "local", # Changed from use_e2b to executor_type additional_imports: List[str] = None, additional_tools: List[Any] = None, system_prompt: Optional[str] = None, # We'll still accept this parameter but not use it directly verbose: bool = False, provider: Optional[str] = None, # Add provider for InferenceClientModel timeout: Optional[int] = None # Add timeout for InferenceClientModel ): """ Initialize a GAIAAgent with specified configuration Args: model_type: Type of model to use (HfApiModel, LiteLLMModel, OpenAIServerModel, InferenceClientModel) model_id: ID of the model to use api_key: API key for the model provider api_base: Base URL for API calls temperature: Temperature for text generation executor_type: Type of executor for code execution ('local' or 'e2b') additional_imports: Additional Python modules to allow importing additional_tools: Additional tools to provide to the agent system_prompt: Custom system prompt to use (not directly used, kept for backward compatibility) verbose: Enable verbose logging provider: Provider for InferenceClientModel (e.g., "hf-inference") timeout: Timeout in seconds for API calls """ # Set verbosity self.verbose = verbose self.system_prompt = system_prompt # Store for potential future use # Initialize model based on configuration if model_type == "HfApiModel": if api_key is None: api_key = os.getenv("HUGGINGFACEHUB_API_TOKEN") if not api_key: raise ValueError("No Hugging Face token provided. Please set HUGGINGFACEHUB_API_TOKEN environment variable or pass api_key parameter.") if self.verbose: print(f"Using Hugging Face token: {api_key[:5]}...") self.model = HfApiModel( model_id=model_id or "meta-llama/Llama-3-70B-Instruct", token=api_key, temperature=temperature ) elif model_type == "InferenceClientModel": if api_key is None: api_key = os.getenv("HUGGINGFACEHUB_API_TOKEN") if not api_key: raise ValueError("No Hugging Face token provided. Please set HUGGINGFACEHUB_API_TOKEN environment variable or pass api_key parameter.") if self.verbose: print(f"Using Hugging Face token: {api_key[:5]}...") self.model = InferenceClientModel( model_id=model_id or "meta-llama/Llama-3-70B-Instruct", provider=provider or "hf-inference", token=api_key, timeout=timeout or 120, temperature=temperature ) elif model_type == "LiteLLMModel": from smolagents import LiteLLMModel self.model = LiteLLMModel( model_id=model_id or "gpt-4o", api_key=api_key or os.getenv("OPENAI_API_KEY"), temperature=temperature ) elif model_type == "OpenAIServerModel": # Check for xAI API key and base URL first xai_api_key = os.getenv("XAI_API_KEY") xai_api_base = os.getenv("XAI_API_BASE") # If xAI credentials are available, use them if xai_api_key and api_key is None: api_key = xai_api_key if self.verbose: print(f"Using xAI API key: {api_key[:5]}...") # If no API key specified, fall back to OPENAI_API_KEY if api_key is None: api_key = os.getenv("OPENAI_API_KEY") if not api_key: raise ValueError("No OpenAI API key provided. Please set OPENAI_API_KEY or XAI_API_KEY environment variable or pass api_key parameter.") # If xAI API base is available and no api_base is provided, use it if xai_api_base and api_base is None: api_base = xai_api_base if self.verbose: print(f"Using xAI API base URL: {api_base}") # If no API base specified but environment variable available, use it if api_base is None: api_base = os.getenv("AGENT_API_BASE") if api_base and self.verbose: print(f"Using API base from AGENT_API_BASE: {api_base}") self.model = OpenAIServerModel( model_id=model_id or "gpt-4o", api_key=api_key, api_base=api_base, temperature=temperature ) else: raise ValueError(f"Unknown model type: {model_type}") if self.verbose: print(f"Initialized model: {model_type} - {model_id}") # Initialize default tools self.tools = [ DuckDuckGoSearchTool(), PythonInterpreterTool(), save_and_read_file, download_file_from_url, analyze_csv_file, analyze_excel_file ] # Add extract_text_from_image if PIL and pytesseract are available try: import pytesseract from PIL import Image self.tools.append(extract_text_from_image) if self.verbose: print("Added image processing tool") except ImportError: if self.verbose: print("Image processing libraries not available") # Add any additional tools if additional_tools: self.tools.extend(additional_tools) if self.verbose: print(f"Initialized with {len(self.tools)} tools") # Setup imports allowed self.imports = ["pandas", "numpy", "datetime", "json", "re", "math", "os", "requests", "csv", "urllib"] if additional_imports: self.imports.extend(additional_imports) # Initialize the CodeAgent executor_kwargs = {} if executor_type == "e2b": try: # Try to import e2b dependencies to check if they're available from e2b_code_interpreter import Sandbox if self.verbose: print("Using e2b executor") except ImportError: if self.verbose: print("e2b dependencies not found, falling back to local executor") executor_type = "local" # Fallback to local if e2b is not available self.agent = CodeAgent( tools=self.tools, model=self.model, additional_authorized_imports=self.imports, executor_type=executor_type, executor_kwargs=executor_kwargs, verbosity_level=2 if self.verbose else 0 ) if self.verbose: print("Agent initialized and ready") def answer_question(self, question: str, task_file_path: Optional[str] = None) -> str: """ Process a GAIA benchmark question and return the answer Args: question: The question to answer task_file_path: Optional path to a file associated with the question Returns: The answer to the question """ try: if self.verbose: print(f"Processing question: {question}") if task_file_path: print(f"With associated file: {task_file_path}") # Create a context with file information if available context = question file_content = None # If there's a file, read it and include its content in the context if task_file_path: try: with open(task_file_path, 'r') as f: file_content = f.read() # Determine file type from extension import os file_ext = os.path.splitext(task_file_path)[1].lower() context = f"""Question: {question}
This question has an associated file. Here is the file content:
```{file_ext}{file_content}```
Analyze the file content above to answer the question.""" except Exception as file_e: context = f"""Question: {question}
This question has an associated file at path: {task_file_path}However, there was an error reading the file: {file_e}You can still try to answer the question based on the information provided.""" # Check for special cases that need specific formatting # Reversed text questions if question.startswith(".") or ".rewsna eht sa" in question: context = f"""This question appears to be in reversed text. Here's the reversed version:{question[::-1]}
Now answer the question above. Remember to format your answer exactly as requested.""" # Add a prompt to ensure precise answers full_prompt = f"""{context}
When answering, provide ONLY the precise answer requested. Do not include explanations, steps, reasoning, or additional text.Be direct and specific. GAIA benchmark requires exact matching answers.For example, if asked "What is the capital of France?", respond simply with "Paris".""" # Run the agent with the question answer = self.agent.run(full_prompt) # Clean up the answer to ensure it's in the expected format # Remove common prefixes that models often add answer = self._clean_answer(answer) if self.verbose: print(f"Generated answer: {answer}") return answer except Exception as e: error_msg = f"Error answering question: {e}" if self.verbose: print(error_msg) return error_msg def _clean_answer(self, answer: any) -> str: """ Clean up the answer to remove common prefixes and formatting that models often add but that can cause exact match failures. Args: answer: The raw answer from the model Returns: The cleaned answer as a string """ # Convert non-string types to strings if not isinstance(answer, str): # Handle numeric types (float, int) if isinstance(answer, float): # Format floating point numbers properly # Check if it's an integer value in float form (e.g., 12.0) if answer.is_integer(): formatted_answer = str(int(answer)) else: # For currency values that might need formatting if abs(answer) >= 1000: formatted_answer = f"${answer:,.2f}" else: formatted_answer = str(answer) return formatted_answer elif isinstance(answer, int): return str(answer) else: # For any other type return str(answer) # Now we know answer is a string, so we can safely use string methods # Normalize whitespace answer = answer.strip() # Remove common prefixes and formatting that models add prefixes_to_remove = [ "The answer is ", "Answer: ", "Final answer: ", "The result is ", "To answer this question: ", "Based on the information provided, ", "According to the information: ", ] for prefix in prefixes_to_remove: if answer.startswith(prefix): answer = answer[len(prefix):].strip() # Remove quotes if they wrap the entire answer if (answer.startswith('"') and answer.endswith('"')) or (answer.startswith("'") and answer.endswith("'")): answer = answer[1:-1].strip() return answer123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249#!/usr/bin/env python3"""Test script for the GAIA agent using real API keys.This script simulates GAIA benchmark questions and helps debug/improve the agent."""
import osimport sysimport jsonimport tempfilefrom typing import List, Dict, Any, Optionalimport tracebackimport dotenv
# Load environment variables from .env filedotenv.load_dotenv()
# Import our agentfrom core_agent import GAIAAgent
# Simulation of GAIA benchmark questionsSAMPLE_QUESTIONS = [ { "task_id": "task_001", "question": "What is the capital of France?", "expected_answer": "Paris", "has_file": False, "file_content": None }, { "task_id": "task_002", "question": "What is the square root of 144?", "expected_answer": "12", "has_file": False, "file_content": None }, { "task_id": "task_003", "question": "If a train travels at 60 miles per hour, how far will it travel in 2.5 hours?", "expected_answer": "150 miles", "has_file": False, "file_content": None }, { "task_id": "task_004", "question": ".rewsna eht sa 'thgir' drow eht etirw ,tfel fo etisoppo eht si tahW", "expected_answer": "right", "has_file": False, "file_content": None }, { "task_id": "task_005", "question": "Analyze the data in the attached CSV file and tell me the total sales for the month of January.", "expected_answer": "$10,250.75", "has_file": True, "file_content": """Date,Product,Quantity,Price,Total2023-01-05,Widget A,10,25.99,259.902023-01-12,Widget B,5,45.50,227.502023-01-15,Widget C,20,50.25,1005.002023-01-20,Widget A,15,25.99,389.852023-01-25,Widget B,8,45.50,364.002023-01-28,Widget D,100,80.04,8004.50""" }, { "task_id": "task_006", "question": "I'm making a grocery list for my mom, but she's a picky eater. She only eats foods that don't contain the letter 'e'. List 5 common fruits and vegetables she can eat.", "expected_answer": "Banana, Kiwi, Corn, Fig, Taro", "has_file": False, "file_content": None }, { "task_id": "task_007", "question": "How many studio albums were published by Mercedes Sosa between 1972 and 1985?", "expected_answer": "12", "has_file": False, "file_content": None }, { "task_id": "task_008", "question": "In the video https://www.youtube.com/watch?v=L1vXC1KMRd0, what color is primarily associated with the main character?", "expected_answer": "Blue", "has_file": False, "file_content": None }]
def initialize_agent(): """Initialize the GAIAAgent with appropriate API keys.""" print("Initializing GAIAAgent with API keys...") # Try X.AI first (xAI) with the correct API endpoint if os.getenv("XAI_API_KEY"): print("Using X.AI API key") try: agent = GAIAAgent( model_type="OpenAIServerModel", model_id="grok-3-latest", # Use the X.AI model api_key=os.getenv("XAI_API_KEY"), api_base="https://api.x.ai/v1", # Correct X.AI endpoint temperature=0.2, executor_type="local", verbose=True, system_prompt_suffix=additional_system_prompt # Add our hints ) print("Using OpenAIServerModel with X.AI API") return agent except Exception as e: print(f"Error initializing with X.AI API: {e}") traceback.print_exc() # Then try OpenAI if os.getenv("OPENAI_API_KEY"): print("Using OpenAI API key") try: model_id = os.getenv("AGENT_MODEL_ID", "gpt-4o") agent = GAIAAgent( model_type="OpenAIServerModel", model_id=model_id, api_key=os.getenv("OPENAI_API_KEY"), temperature=0.2, executor_type="local", verbose=True ) print(f"Using OpenAIServerModel with model_id: {model_id}") return agent except Exception as e: print(f"Error initializing with OpenAI API: {e}") traceback.print_exc() # Last resort, try Hugging Face if os.getenv("HUGGINGFACEHUB_API_TOKEN"): print("Using Hugging Face API token") try: # Use a smaller model that might work within free tier model_id = "tiiuae/falcon-7b-instruct" # Try a smaller model that might be within free tier agent = GAIAAgent( model_type="HfApiModel", model_id=model_id, api_key=os.getenv("HUGGINGFACEHUB_API_TOKEN"), temperature=0.2, executor_type="local", verbose=True ) print(f"Using HfApiModel with model_id: {model_id}") return agent except Exception as e: print(f"Error initializing with Hugging Face API: {e}") traceback.print_exc() print("ERROR: No valid API keys found in environment. Please set one of the following:") print("- XAI_API_KEY (for X.AI)") print("- OPENAI_API_KEY") print("- HUGGINGFACEHUB_API_TOKEN") return None
def save_test_file(task_id: str, content: str) -> str: """Save a test file to a temporary location.""" temp_dir = tempfile.gettempdir() file_path = os.path.join(temp_dir, f"test_file_{task_id}.csv") with open(file_path, 'w') as f: f.write(content) return file_path
def run_tests(): """Run tests using the GAIAAgent with API keys.""" agent = initialize_agent() if not agent: print("Failed to initialize agent. Exiting.") return results = [] correct_count = 0 total_count = len(SAMPLE_QUESTIONS) for idx, question_data in enumerate(SAMPLE_QUESTIONS): task_id = question_data["task_id"] question = question_data["question"] expected = question_data["expected_answer"] print(f"\n{'='*80}") print(f"Question {idx+1}/{total_count}: {question}") print(f"Expected: {expected}") # Process any attached file file_path = None if question_data["has_file"] and question_data["file_content"]: file_path = save_test_file(task_id, question_data["file_content"]) print(f"Created test file: {file_path}") # Get answer from agent try: answer = agent.answer_question(question, file_path) print(f"Agent answer: {answer}") # Check if answer matches expected is_correct = answer.lower() == expected.lower() if is_correct: correct_count += 1 print(f"✅ CORRECT") else: print(f"❌ INCORRECT - Expected: {expected}") results.append({ "task_id": task_id, "question": question, "expected": expected, "answer": answer, "is_correct": is_correct }) except Exception as e: error_details = traceback.format_exc() print(f"Error processing question: {e}\n{error_details}") results.append({ "task_id": task_id, "question": question, "expected": expected, "answer": f"ERROR: {str(e)}", "is_correct": False }) # Print summary accuracy = (correct_count / total_count) * 100 print(f"\n{'='*80}") print(f"Test Results: {correct_count}/{total_count} correct ({accuracy:.1f}%)") return results
if __name__ == "__main__": print("Running tests for GAIA agent with API keys...") # Print environment information print("\nEnvironment information:") print(f"XAI_API_KEY set: {'Yes' if os.getenv('XAI_API_KEY') else 'No'}") print(f"OPENAI_API_KEY set: {'Yes' if os.getenv('OPENAI_API_KEY') else 'No'}") print(f"HUGGINGFACEHUB_API_TOKEN set: {'Yes' if os.getenv('HUGGINGFACEHUB_API_TOKEN') else 'No'}") print(f"AGENT_MODEL_TYPE: {os.getenv('AGENT_MODEL_TYPE', 'OpenAIServerModel')} (default: OpenAIServerModel)") print(f"AGENT_MODEL_ID: {os.getenv('AGENT_MODEL_ID', 'gpt-4o')} (default: gpt-4o)") results = run_tests() # Save results to a file with open("test_results.json", "w") as f: json.dump(results, f, indent=2) print("\nResults saved to test_results.json") 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277import osimport tempfileimport gradio as grimport pandas as pdimport tracebackfrom core_agent import GAIAAgentfrom api_integration import GAIAApiClient
# ConstantsDEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
def save_task_file(file_content, task_id): """ Save a task file to a temporary location """ if not file_content: return None # Create a temporary file temp_dir = tempfile.gettempdir() file_path = os.path.join(temp_dir, f"gaia_task_{task_id}.txt") # Write content to the file with open(file_path, 'wb') as f: f.write(file_content) print(f"File saved to {file_path}") return file_path
def get_agent_configuration(): """ Get the agent configuration based on environment variables """ # Default configuration config = { "model_type": "OpenAIServerModel", # Default to OpenAIServerModel "model_id": "gpt-4o", # Default model for OpenAI "temperature": 0.2, "executor_type": "local", "verbose": False, "provider": "hf-inference", # For InferenceClientModel "timeout": 120 # For InferenceClientModel } # Check for xAI API key and base URL xai_api_key = os.getenv("XAI_API_KEY") xai_api_base = os.getenv("XAI_API_BASE") # If we have xAI credentials, use them if xai_api_key: config["api_key"] = xai_api_key if xai_api_base: config["api_base"] = xai_api_base # Use a model that works well with xAI config["model_id"] = "mixtral-8x7b-32768" # Override with environment variables if present if os.getenv("AGENT_MODEL_TYPE"): config["model_type"] = os.getenv("AGENT_MODEL_TYPE") if os.getenv("AGENT_MODEL_ID"): config["model_id"] = os.getenv("AGENT_MODEL_ID") if os.getenv("AGENT_TEMPERATURE"): config["temperature"] = float(os.getenv("AGENT_TEMPERATURE")) if os.getenv("AGENT_EXECUTOR_TYPE"): config["executor_type"] = os.getenv("AGENT_EXECUTOR_TYPE") if os.getenv("AGENT_VERBOSE") is not None: config["verbose"] = os.getenv("AGENT_VERBOSE").lower() == "true" if os.getenv("AGENT_API_BASE"): config["api_base"] = os.getenv("AGENT_API_BASE") # InferenceClientModel specific settings if os.getenv("AGENT_PROVIDER"): config["provider"] = os.getenv("AGENT_PROVIDER") if os.getenv("AGENT_TIMEOUT"): config["timeout"] = int(os.getenv("AGENT_TIMEOUT")) return config
def run_and_submit_all(profile: gr.OAuthProfile | None): """ Fetches all questions, runs the GAIAAgent on them, submits all answers, and displays the results. """ # Check for user login if not profile: return "Please Login to Hugging Face with the button.", None username = profile.username print(f"User logged in: {username}") # Get SPACE_ID for code link space_id = os.getenv("SPACE_ID") agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" # Initialize API client api_client = GAIAApiClient(DEFAULT_API_URL) # Initialize Agent with configuration try: agent_config = get_agent_configuration() print(f"Using agent configuration: {agent_config}") agent = GAIAAgent(**agent_config) print("Agent initialized successfully") except Exception as e: error_details = traceback.format_exc() print(f"Error initializing agent: {e}\n{error_details}") return f"Error initializing agent: {e}", None # Fetch questions try: questions_data = api_client.get_questions() if not questions_data: return "Fetched questions list is empty or invalid format.", None print(f"Fetched {len(questions_data)} questions.") except Exception as e: error_details = traceback.format_exc() print(f"Error fetching questions: {e}\n{error_details}") return f"Error fetching questions: {e}", None # Run agent on questions results_log = [] answers_payload = [] print(f"Running agent on {len(questions_data)} questions...") # Progress tracking total_questions = len(questions_data) completed = 0 failed = 0 for item in questions_data: task_id = item.get("task_id") question_text = item.get("question") if not task_id or question_text is None: print(f"Skipping item with missing task_id or question: {item}") continue try: # Update progress completed += 1 print(f"Processing question {completed}/{total_questions}: Task ID {task_id}") # Check if the question has an associated file file_path = None try: file_content = api_client.get_file(task_id) print(f"Downloaded file for task {task_id}") file_path = save_task_file(file_content, task_id) except Exception as file_e: print(f"No file found for task {task_id} or error: {file_e}") # Run the agent to get the answer submitted_answer = agent.answer_question(question_text, file_path) # Add to results 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: # Update error count failed += 1 error_details = traceback.format_exc() print(f"Error running agent on task {task_id}: {e}\n{error_details}") # Add error to results error_msg = f"AGENT ERROR: {e}" answers_payload.append({"task_id": task_id, "submitted_answer": error_msg}) results_log.append({ "Task ID": task_id, "Question": question_text, "Submitted Answer": error_msg }) # Print summary print(f"\nProcessing complete: {completed} questions processed, {failed} failures") if not answers_payload: return "Agent did not produce any answers to submit.", pd.DataFrame(results_log) # Submit answers submission_data = { "username": username.strip(), "agent_code": agent_code, "answers": answers_payload } print(f"Submitting {len(answers_payload)} answers for username '{username}'...") try: result_data = api_client.submit_answers( username.strip(), agent_code, answers_payload ) # Calculate success rate correct_count = result_data.get('correct_count', 0) total_attempted = result_data.get('total_attempted', len(answers_payload)) success_rate = (correct_count / total_attempted) * 100 if total_attempted > 0 else 0 final_status = ( f"Submission Successful!\n" f"User: {result_data.get('username')}\n" f"Overall Score: {result_data.get('score', 'N/A')}% " f"({correct_count}/{total_attempted} correct, {success_rate:.1f}% success rate)\n" f"Message: {result_data.get('message', 'No message received.')}" ) print("Submission successful.") return final_status, pd.DataFrame(results_log) except Exception as e: error_details = traceback.format_exc() status_message = f"Submission Failed: {e}\n{error_details}" print(status_message) return status_message, pd.DataFrame(results_log)
# Build Gradio Interfacewith gr.Blocks() as demo: gr.Markdown("# GAIA Agent Evaluation Runner") gr.Markdown( """ **Instructions:** 1. Log in to your Hugging Face account using the button below. 2. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score. **Configuration:** You can configure the agent by setting these environment variables: - `AGENT_MODEL_TYPE`: Model type (HfApiModel, InferenceClientModel, LiteLLMModel, OpenAIServerModel) - `AGENT_MODEL_ID`: Model ID - `AGENT_TEMPERATURE`: Temperature for generation (0.0-1.0) - `AGENT_EXECUTOR_TYPE`: Type of executor ('local' or 'e2b') - `AGENT_VERBOSE`: Enable verbose logging (true/false) - `AGENT_API_BASE`: Base URL for API calls (for OpenAIServerModel) **xAI Support:** - `XAI_API_KEY`: Your xAI API key - `XAI_API_BASE`: Base URL for xAI API (default: https://api.groq.com/openai/v1) - When using xAI, set AGENT_MODEL_TYPE=OpenAIServerModel and AGENT_MODEL_ID=mixtral-8x7b-32768 **InferenceClientModel specific settings:** - `AGENT_PROVIDER`: Provider for InferenceClientModel (e.g., "hf-inference") - `AGENT_TIMEOUT`: Timeout in seconds for API calls """ ) gr.LoginButton() run_button = gr.Button("Run Evaluation & Submit All Answers") status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False) results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True) run_button.click( fn=run_and_submit_all, outputs=[status_output, results_table] )
if __name__ == "__main__": print("\n" + "-"*30 + " App Starting " + "-"*30) # Check for environment variables config = get_agent_configuration() print(f"Agent configuration: {config}") # Run the Gradio app demo.launch(debug=True, share=False)123456gradiorequestssmolagentspython-dotenvpandasnumpy.env.exampleAdded+1
.gitignoreAdded+12
README.md+156-6
__pycache__/api_integration.cpython-311.pycAdded
__pycache__/core_agent.cpython-311.pycAdded
api_integration.pyAdded+39
app.pyAdded+279
core_agent.pyAdded+492
local_test.pyAdded+249
main.pyAdded+277
requirements.txtAdded+6