Spaces:
Sleeping
Sleeping
clean
Browse filesFiles changed (4)
- README.md+34-285
- app.py+2-2
- config.py+37-1
- evaluation.pyDeleted-416
10 unmodified lines111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031110 unmodified lineshf_oauth_expiration_minutes: 480---# OpenAI GPT-4.1-nano Agent Evaluation## IntroductionThis is an advanced AI-powered agent that answers questions using OpenAI's GPT-4.1-nano model with access to multiple tools including web search, code interpreter, and retrieval capabilities. The agent uses the latest **Responses API** for improved performance and efficiency. It intelligently selects the appropriate tools based on the question type and provides comprehensive answers for the GAIA evaluation.## Features- **GPT-4.1-nano Integration**: Uses OpenAI's latest GPT-4.1-nano model for high-quality responses- **Responses API**: Implements the newer, more efficient Responses API instead of Chat Completions- **Configurable System**: Centralized configuration management with presets and customization options- **Web Search**: Automatically searches the web for current events, recent information, and real-time data- **Code Interpreter**: Handles mathematical calculations, data analysis, and computational tasks- **Retrieval Tools**: Accesses knowledge base for factual information- **Intelligent Tool Selection**: Automatically chooses the best tool based on question content- **Fallback Mechanisms**: Gracefully handles tool failures with direct model responses- **Comprehensive Error Handling**: Robust error handling for network and API issues## Requirements- Python 3.8+- OpenAI API key (set as the `OPENAI_API_KEY` environment variable)- Internet connection for web search and API access## Project Structure```final/├── evaluation.py # Main evaluation application with OpenAI agent├── config.py # Configuration management and settings├── config_example.py # Example configurations and customization├── test_openai_agent.py # Test script for the OpenAI agent├── requirements.txt # Python dependencies└── README.md # This file```## Setup Instructions1. **Install dependencies:**```bashpip install -r requirements.txt```2. **Set your OpenAI API key:**```bashexport OPENAI_API_KEY=your_openai_api_key_here```3. **Test the agent:**```bashpython test_openai_agent.py```4. **Run the evaluation application:**```bashpython evaluation.py```## Configuration SystemThe agent uses a centralized configuration system that allows easy customization of all parameters.### Default ConfigurationThe default configuration is defined in `config.py`:```pythonMODEL_CONFIG = {"model": "gpt-4.1-nano","temperature": 0.7,"top_p": 1.0,"frequency_penalty": 0.0,"presence_penalty": 0.0,"stream": False}```### Available PresetsThe system includes several pre-configured presets:- **evaluation**: Optimized for GAIA evaluation (default)- **conservative**: Lower temperature, shorter responses- **creative**: Higher temperature, longer responses### Customizing ConfigurationYou can customize the agent in several ways:#### 1. Using Presets```pythonfrom evaluation import OpenAIAgent# Use conservative presetagent = OpenAIAgent(use_tools=True, preset="conservative")# Use creative presetagent = OpenAIAgent(use_tools=True, preset="creative")```#### 2. Custom Model Configuration```pythonfrom config import get_model_config# Get custom configurationcustom_config = get_model_config({"temperature": 0.5,"top_p": 0.9})```#### 3. Custom System Prompts```pythonfrom config import get_system_prompt# Get domain-specific prompttechnical_prompt = get_system_prompt("code_interpreter")```#### 4. Environment-Specific Configuration```python# Development environmentexport DEBUG_MODE=true# Production environmentexport DEBUG_MODE=false```### Configuration ExamplesSee `config_example.py` for comprehensive examples of:- Custom model configurations- Domain-specific system prompts- Environment-specific settings- Custom question type detection- Advanced customization patterns## How the Agent Works### Responses API ImplementationThe agent uses OpenAI's **Responses API** which provides:- **Simplified Interface**: Direct prompt-based interactions- **Better Performance**: More efficient than Chat Completions API- **Tool Integration**: Native support for web search, code interpreter, and retrieval- **Streamlined Responses**: Cleaner response format with `response.choices[0].text`### Tool Selection LogicThe agent intelligently selects tools based on question keywords:**Web Search** (for current/recent information):- Keywords: "latest", "recent", "current", "today", "news", "weather", "price", "stock", etc.**Code Interpreter** (for calculations and data analysis):- Keywords: "calculate", "compute", "solve", "equation", "percentage", "statistics", "data", etc.**Direct Response** (fallback):- For general knowledge questions and when tools are unavailable### Example Tool Usage- **Q:** "What are the latest AI developments?"- **Tool:** Web search for current AI news- **Response:** Recent AI announcements and developments- **Q:** "Calculate 25% of 400"- **Tool:** Code interpreter- **Response:** Mathematical calculation with step-by-step explanation- **Q:** "What is machine learning?"- **Tool:** Direct GPT-4.1-nano response- **Response:** Comprehensive explanation of machine learning concepts## API UsageThe agent uses OpenAI's latest **Responses API** with the following features:- **Model:** `gpt-4.1-nano` (cost-effective, high-performance)- **API:** `client.responses.create()` (newer, more efficient)- **Tools:** `web_search`, `code_interpreter`, `retrieval`- **Temperature:** 0.7 (balanced creativity and accuracy)- **Response Length:** Automatically determined by the model based on content### Responses API vs Chat Completions| Feature | Responses API | Chat Completions ||---------|---------------|------------------|| Interface | `prompt` parameter | `messages` array || Response | `response.choices[0].text` | `response.choices[0].message.content` || Tools | Native tool support | Function calling || Parameters | No `max_tokens` | Supports `max_tokens` || Performance | More efficient | Standard || Complexity | Simpler | More complex |## Configuration Management### Key Configuration Files1. **`config.py`**: Main configuration with all settings and presets2. **`config_example.py`**: Examples of custom configurations3. **Environment Variables**: For API keys and debug settings### Configuration ValidationThe system includes automatic configuration validation:```pythonfrom config import validate_configif validate_config():print("✅ Configuration is valid")else:print("❌ Configuration has issues")```### Performance Settings```pythonPERFORMANCE_CONFIG = {"cache_responses": True,"cache_ttl": 3600, # 1 hour"max_concurrent_requests": 5,"request_timeout": 30}```## Error HandlingThe implementation includes comprehensive error handling:1. **Connectivity Checks**: Verifies internet and OpenAI API access2. **Configuration Validation**: Validates all settings before use3. **Tool Fallbacks**: Falls back to simpler methods if tools fail4. **API Error Recovery**: Handles rate limits, timeouts, and API errors5. **Graceful Degradation**: Continues operation even with partial failures## TestingUse the test script to verify your setup:```bashpython test_openai_agent.py```This will test:- Configuration validation- Model configuration presets- Internet connectivity- OpenAI API access- Responses API functionality- Agent initialization- Various question types- Tool functionalityThe test script includes both direct API testing and full agent testing to ensure everything works correctly.## Advanced Customization### Creating Custom Presets```pythonfrom config import get_preset# Create custom presetcustom_preset = {"temperature": 0.4,"system_prompt": "Your custom system prompt here"}# Use in agentagent = OpenAIAgent(use_tools=True, preset="evaluation")agent.preset_config.update(custom_preset)```### Domain-Specific Configuration```python# Technical domaintechnical_config = {"temperature": 0.3,"system_prompt": "You are a technical expert..."}# Creative domaincreative_config = {"temperature": 1.0,"system_prompt": "You are a creative assistant..."}```## LicenseThis project is licensed under the [MIT License](https://mit-license.org/).10 unmodified lines111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596010 unmodified lineshf_oauth_expiration_minutes: 480---# 🤗 Hugging Face GAIA Evaluation AgentA robust, agentic AI assistant for the GAIA evaluation, running **entirely on free Hugging Face models**. No OpenAI or paid APIs required. Handles all question types and file attachments (PDF, CSV, TXT, DOCX, images) with a beautiful Gradio UI.## Features- **Free models only** (no OpenAI)- Handles all question types: factual, reasoning, math/code, retrieval- Supports file uploads: PDF, CSV, TXT, DOCX, XLSX, PNG, JPG- Modern, beautiful Gradio Blocks UI- Robust agentic flows for GAIA evaluation- Easy to deploy on Hugging Face Spaces## Setup (for Hugging Face Spaces)1. **Clone or upload all files** to your Space:- `app.py`- `hf_agent.py`- `config.py`- `requirements.txt`2. **Install requirements** (automatically handled by Spaces):- `transformers`, `sentence-transformers`, `gradio`, `pandas`, `pdfplumber`, `python-docx`, `Pillow`, `requests`3. **Launch the Space**. The UI will guide you through login, asking questions, uploading files, and running the GAIA evaluation.## Usage- **Ask a Question:**- Enter your question and (optionally) upload files for context.- The agent will select the best tool (LLM, code, retrieval) and answer robustly.- **GAIA Evaluation:**- Log in with your Hugging Face account.- Click "Run Evaluation & Submit All Answers" to fetch, answer, and submit all GAIA questions.## File Support- `.txt`, `.pdf`, `.csv`, `.docx`, `.xlsx`, `.png`, `.jpg`, `.jpeg`## Model Choices- General LLM: `HuggingFaceH4/zephyr-7b-beta`- Math/Code: `google/flan-t5-large`- Retrieval: `sentence-transformers/all-MiniLM-L6-v2`## No OpenAI RequiredThis project is 100% free and open, using only Hugging Face models and infrastructure.---**For advanced features (async, caching, more file types, RAG, etc.), open an issue or PR!**
24 unmodified lines2526272829303177 unmodified lines10911011111211311411524 unmodified linesexcept Exception as e:return {"error": str(e)}def run_evaluation(profile):api_url = DEFAULT_API_URLspace_id = "tjrtm"agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"77 unmodified linesstatus_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)eval_btn = gr.Button("Run Evaluation & Submit All Answers", variant="primary")eval_btn.click(run_evaluation, inputs=[gr.OAuthProfile()], outputs=[status_output, results_table])gr.Markdown("---")gr.Markdown("<center><small>Powered by Hugging Face free models. No OpenAI or paid APIs used.</small></center>")24 unmodified lines2526272829303177 unmodified lines10911011111211311411524 unmodified linesexcept Exception as e:return {"error": str(e)}def run_evaluation(profile=None):api_url = DEFAULT_API_URLspace_id = "tjrtm"agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"77 unmodified linesstatus_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)eval_btn = gr.Button("Run Evaluation & Submit All Answers", variant="primary")eval_btn.click(run_evaluation, outputs=[status_output, results_table])gr.Markdown("---")gr.Markdown("<center><small>Powered by Hugging Face free models. No OpenAI or paid APIs used.</small></center>")
2 unmodified lines34567850 unmodified lines596061622 unmodified linesContains all model parameters, system prompts, and settings"""# --- Model Configuration ---# Use only free Hugging Face modelsMODEL_CONFIG = {50 unmodified linesreturn DEFAULT_PROMPTS.get(prompt_type, DEFAULT_PROMPTS["direct_question"])def get_supported_file_types():return SUPPORTED_FILE_TYPES.copy()2 unmodified lines34567891050 unmodified lines61626364656667686970717273747576777879808182838485868788899091929394959697982 unmodified linesContains all model parameters, system prompts, and settings"""import os# --- Model Configuration ---# Use only free Hugging Face modelsMODEL_CONFIG = {50 unmodified linesreturn DEFAULT_PROMPTS.get(prompt_type, DEFAULT_PROMPTS["direct_question"])def get_supported_file_types():return SUPPORTED_FILE_TYPES.copy()def get_question_keywords():"""Returns a dictionary of keywords for determining when to use web search or code interpreter tools."""return {"web_search": ["current", "latest", "news", "today", "recent", "update", "event", "happening", "trending", "who won", "who is president", "weather", "stock", "price", "score", "live", "breaking"],"code_interpreter": ["calculate", "compute", "sum", "average", "mean", "median", "plot", "graph", "chart", "data", "analyze", "analysis", "number", "math", "equation", "solve", "python", "code", "script"]}def get_tools_config(use_tools=True):"""Returns a list or dict of tool configurations depending on whether tools are enabled.This is a placeholder; customize as needed for your agent/tools."""if use_tools:# Example: return a list of enabled tool types (matching what evaluation.py expects)return [{"type": "web_search_preview"},{"type": "code_interpreter"},{"type": "retrieval"}]else:return []def get_api_key():"""Returns the OpenAI API key from the environment variable OPENAI_API_KEY, or None if not set."""return os.getenv("OPENAI_API_KEY")
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416import osimport gradio as grimport requestsimport inspectimport pandas as pdfrom transformers import pipelineimport wikipediaimport socketfrom openai import OpenAIimport jsonimport timefrom config import ( get_model_config, get_system_prompt, get_tools_config, get_question_keywords, get_api_key, validate_config, get_preset, ERROR_MESSAGES, DEFAULT_PROMPTS)
# (Keep Constants as is)# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
def check_internet_connection(): """Check if internet connection is available""" try: # Try to connect to a reliable host socket.create_connection(("8.8.8.8", 53), timeout=3) return True except OSError: return False
def check_openai_api(): """Check if OpenAI API is accessible""" try: api_key = get_api_key() if not api_key: return False, ERROR_MESSAGES["no_api_key"] client = OpenAI(api_key=api_key) # Test with a simple request using Responses API model_config = get_model_config() response = client.responses.create( model=model_config["model"], input="Hello" ) return True, "OpenAI API accessible" except Exception as e: return False, f"OpenAI API error: {str(e)}"
# --- OpenAI Agent Definition ---# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------class OpenAIAgent: def __init__(self, use_tools=True, preset="evaluation"): print("OpenAI Agent initialized.") self.use_tools = use_tools self.preset = preset # Validate configuration if not validate_config(): raise Exception("Configuration validation failed") # Check connectivity and API access internet_available = check_internet_connection() openai_available, openai_status = check_openai_api() print(f"Internet connection: {'✅ Available' if internet_available else '❌ Not available'}") print(f"OpenAI API: {'✅ Available' if openai_available else '❌ Not available'} - {openai_status}") if not internet_available or not openai_available: raise Exception(f"Cannot initialize OpenAI agent: {openai_status}") # Initialize OpenAI client self.client = OpenAI(api_key=get_api_key()) # Get configuration from preset self.preset_config = get_preset(preset) self.model_config = get_model_config(self.preset_config) self.system_prompt = self.preset_config.get("system_prompt", get_system_prompt("evaluation")) # Get tools configuration self.tools = get_tools_config(use_tools) # Get question keywords self.question_keywords = get_question_keywords() print(f"✅ OpenAI Agent initialized with preset '{preset}' and {'tools enabled' if use_tools else 'tools disabled'}")
def search_web(self, query: str) -> str: """Perform web search using OpenAI's web_search tool""" try: response = self.client.responses.create( model=self.model_config["model"], input=DEFAULT_PROMPTS["web_search_query"].format(query=query), tools=[{"type": "web_search_preview"}], temperature=self.model_config["temperature"] ) return response.output_text except Exception as e: print(f"Web search failed: {e}") return ""
def get_web_answer(self, question: str) -> str: """Get answer using web search""" try: response = self.client.responses.create( model=self.model_config["model"], input=DEFAULT_PROMPTS["web_search_question"].format(question=question), tools=[{"type": "web_search_preview"}], temperature=self.model_config["temperature"] ) return response.output_text except Exception as e: print(f"Web answer generation failed: {e}") return ""
def get_code_answer(self, question: str) -> str: """Get answer using code interpreter if the question involves calculations or data analysis""" try: response = self.client.responses.create( model=self.model_config["model"], input=DEFAULT_PROMPTS["code_interpreter_question"].format(question=question), tools=[{"type": "code_interpreter"}], temperature=self.model_config["temperature"] ) return response.output_text except Exception as e: print(f"Code interpreter failed: {e}") return ""
def get_direct_answer(self, question: str) -> str: """Get direct answer without tools""" try: response = self.client.responses.create( model=self.model_config["model"], input=DEFAULT_PROMPTS["direct_question"].format(question=question), temperature=self.model_config["temperature"] ) return response.output_text except Exception as e: print(f"Direct answer generation failed: {e}") return ""
def __call__(self, question: str) -> str: print(f"OpenAI Agent received question (first 50 chars): {question[:50]}...") # Determine the best approach based on question type question_lower = question.lower() # Check if question needs web search (current events, specific facts, etc.) needs_web_search = any(keyword in question_lower for keyword in self.question_keywords["web_search"]) # Check if question needs code interpretation (math, calculations, data analysis) needs_code = any(keyword in question_lower for keyword in self.question_keywords["code_interpreter"]) if self.use_tools: if needs_web_search: print("Using web search for current/recent information...") answer = self.get_web_answer(question) if answer: print(f"Web search answer: {answer[:100]}...") return answer if needs_code: print("Using code interpreter for calculations...") answer = self.get_code_answer(question) if answer: print(f"Code interpreter answer: {answer[:100]}...") return answer # Fallback to direct answer print(f"Using direct {self.model_config['model']} response...") answer = self.get_direct_answer(question) print(f"Direct answer: {answer[:100]}...") return answer
def test_agent_initialization(): """Test function to check if the agent can be initialized properly""" try: print("Testing agent initialization...") # Check connectivity first internet_available = check_internet_connection() openai_available, openai_status = check_openai_api() status_msg = f"Connectivity Status:\n" status_msg += f"Internet: {'✅ Available' if internet_available else '❌ Not available'}\n" status_msg += f"OpenAI API: {'✅ Available' if openai_available else '❌ Not available'} - {openai_status}\n\n" # Try online mode first if possible if internet_available and openai_available: try: agent = OpenAIAgent(use_tools=True, preset="evaluation") status_msg += "✅ OpenAI Agent with tools and evaluation preset initialized successfully\n" except Exception as e: status_msg += f"❌ OpenAI Agent with tools failed: {e}\n" status_msg += "Trying without tools...\n" agent = OpenAIAgent(use_tools=False, preset="evaluation") status_msg += "✅ OpenAI Agent without tools initialized successfully\n" else: status_msg += "❌ Cannot initialize OpenAI Agent - missing connectivity or API key\n" status_msg += "Please check your internet connection and OPENAI_API_KEY environment variable\n" return status_msg # Test with a simple question test_question = "What is artificial intelligence?" answer = agent(test_question) status_msg += f"✅ Test question answered: {answer[:100]}...\n" status_msg += "\n🎉 OpenAI Agent is ready to use!" return status_msg except Exception as e: error_msg = f"❌ Agent test failed: {e}" print(error_msg) return error_msg
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 = "tjrtm"
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: # First try with tools enabled and evaluation preset agent = OpenAIAgent(use_tools=True, preset="evaluation") print("OpenAI Agent initialized with tools and evaluation preset") except Exception as e: print(f"Error instantiating agent with tools: {e}") print("Trying without tools...") try: agent = OpenAIAgent(use_tools=False, preset="evaluation") print("OpenAI Agent initialized without tools") except Exception as e2: print(f"Error instantiating agent without tools: {e2}") return f"Error initializing OpenAI agent: {e2}. Please check your OPENAI_API_KEY environment variable.", 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("# OpenAI GPT-4.1-nano Agent Evaluation Runner") gr.Markdown( """ **Instructions:**
1. This agent uses OpenAI's GPT-4.1-nano model with web search, code interpreter, and retrieval tools. 2. Set your OpenAI API key as an environment variable: `export OPENAI_API_KEY=your_key_here` 3. Log in to your Hugging Face account using the button below. This uses your HF username for submission. 4. Click 'Test Agent Initialization' to verify your setup, then 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
--- **Features:** - Web search for current events and recent information - Code interpreter for calculations and data analysis - Retrieval tools for accessing knowledge - Intelligent tool selection based on question type - Fallback to direct GPT-4.1-nano responses
--- **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()
with gr.Row(): test_button = gr.Button("Test Agent Initialization", variant="secondary") run_button = gr.Button("Run Evaluation & Submit All Answers", variant="primary")
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)
test_button.click( fn=test_agent_initialization, outputs=[status_output] ) 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 OpenAI GPT-4.1-nano Agent Evaluation...") demo.launch(debug=True, share=False)README.md+34-285
app.py+2-2
config.py+37-1
evaluation.pyDeleted-416