Spaces:
Sleeping
Sleeping
go with HF
Browse filesFiles changed (8)
- README.md+260-28
- app.py+117
- config.pyAdded+62
- config_example.pyAdded+137
- evaluation.py+229-39
- hf_agent.pyAdded+64
- requirements.txt+8-7
- test_openai_agent.pyAdded+171
123456789101112131415161718192021222324252627282930313233343536373839404142434445465 unmodified lines525354555657585960616263646566676869707172737475767778---title: GAIA Agent - Q&A ChatbotcolorFrom: greencolorTo: bluesdk: 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---# Reasoning Q&A Chatbot## IntroductionThis is a simple AI-powered chatbot that answers user questions using only reasoning and conversation. It uses the OpenAI API (with the `gpt-4.1-nano` model) to generate responses. The chatbot can also analyze images uploaded by the user, providing detailed reasoning about their content. No external tools, code execution, web search, or file processing is used. The chatbot is designed for natural language Q&A, image analysis, and general conversation.## Features- Natural language Q&A- Image analysis: upload an image and receive a detailed, reasoned description- Reasoning-based answers powered by OpenAI's GPT-4.1-nano- All answers include reasoning in <think> tags- No code execution, web search, or file processing- Simple, user-friendly chat interface (Gradio)## Requirements- Python 3.8+- OpenAI API key (set as the `OPENAI_API_KEY` environment variable)## Project Structure```final/βββ app.py # Main Q&A chatbot interfaceβββ requirements.txtβββ README.md # This file```## How to Use1. **Install dependencies:**```bash5 unmodified linesexport OPENAI_API_KEY=your_openai_api_key_here```3. **Run the chatbot:**```bashpython app.py```4. **Access the interface:**- Open `http://localhost:7860` in your browser- Ask any question in natural language- Optionally, upload an image for analysis- Get answers and image analyses with detailed reasoning in <think> tags## Example Interactions- **Q:** What is the capital of France?- **A:** Paris. <think>France's capital is Paris, which is a well-known fact.</think>- **Q:** Can you help me with a math problem?- **A:** Sure! Please describe your math problem. <think>I can help with math reasoning step by step.</think>- **Q:** (with an uploaded image of a cat) What do you see in this image?- **A:** This image shows a cat sitting on a windowsill. <think>I analyzed the image and identified the animal as a cat based on its shape, fur, and facial features.</think>## License12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535 unmodified lines5960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310---title: OpenAI GPT-4.1-nano Agent - Q&A EvaluationcolorFrom: greencolorTo: bluesdk: gradiosdk_version: 5.25.2app_file: evaluation.pypinned: falsehf_oauth: true# optional, default duration is 8 hours/480 minutes. Max duration is 30 days/43200 minutes.hf_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:**```bash5 unmodified linesexport 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..."}```## License
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117import gradio as grfrom hf_agent import HuggingFaceAgentimport requestsimport pandas as pd# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"def fetch_questions(api_url):questions_url = f"{api_url}/questions"try:response = requests.get(questions_url, timeout=15)response.raise_for_status()return response.json()except Exception as e:return []def submit_answers(api_url, username, agent_code, answers):submit_url = f"{api_url}/submit"submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers}try:response = requests.post(submit_url, json=submission_data, timeout=60)response.raise_for_status()return response.json()except 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"if not profile:return "Please login to Hugging Face.", Noneusername = profile.usernameagent = HuggingFaceAgent()questions = fetch_questions(api_url)if not questions:return "No questions fetched from server.", Noneanswers_payload = []results_log = []for item in questions:task_id = item.get("task_id")question_text = item.get("question")if not task_id or question_text is None:continuetry:answer = agent(question_text)answers_payload.append({"task_id": task_id, "submitted_answer": answer})results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": answer})except Exception as e:results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})if not answers_payload:return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)result_data = submit_answers(api_url, username, agent_code, answers_payload)if "error" in result_data:return f"Submission Failed: {result_data['error']}", pd.DataFrame(results_log)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.')}")return final_status, pd.DataFrame(results_log)def agent_qa(question, files):agent = HuggingFaceAgent()answer = agent(question, files)return answerdef file_preview(files):previews = []for file in files or []:name = file.nameext = name.split('.')[-1].lower()if ext in ["png", "jpg", "jpeg"]:previews.append(gr.Image(value=file, label=name))else:previews.append(gr.Textbox(value=f"Uploaded: {name}", label=name))return previewswith gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {max-width: 900px !important;}") as demo:gr.Markdown("""# π€ Hugging Face GAIA Evaluation Agent<span style='color:#555'>- **Free models only** (no OpenAI)- Handles all question types and file attachments- Beautiful, modern UI- Robust agentic flows for GAIA evaluation</span>""")gr.Markdown("""**Instructions:**1. Login with your Hugging Face account.2. Ask any question, optionally upload files (PDF, CSV, TXT, DOCX, images).3. Or run the full GAIA evaluation and submit your answers.""")gr.LoginButton()with gr.Tab("Ask a Question"):with gr.Row():question = gr.Textbox(label="Your Question", lines=2, scale=3)files = gr.File(label="Attach Files", file_types=[".txt", ".pdf", ".csv", ".docx", ".xlsx", ".png", ".jpg", ".jpeg"], file_count="multiple", scale=2)file_previews = gr.Group()answer = gr.Textbox(label="Agent Answer", lines=5)ask_btn = gr.Button("Get Answer", variant="primary")ask_btn.click(agent_qa, inputs=[question, files], outputs=answer)with gr.Tab("GAIA Evaluation"):status_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>")if __name__ == "__main__":demo.launch()
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162"""Configuration file for Hugging Face Agent (GAIA Evaluation)Contains all model parameters, system prompts, and settings"""
# --- Model Configuration ---# Use only free Hugging Face modelsMODEL_CONFIG = { "llm_model": "HuggingFaceH4/zephyr-7b-beta", # General LLM "code_model": "google/flan-t5-large", # For math/code "retrieval_model": "sentence-transformers/all-MiniLM-L6-v2", # For retrieval "temperature": 0.7, "max_new_tokens": 512, "top_p": 1.0,}
# --- System Prompts ---SYSTEM_PROMPTS = { "default": ( "You are a helpful, concise, and robust AI assistant. " "You can use tools, analyze files, and answer any question. " "Always provide short, accurate, and well-structured answers. " "If a file is provided, use its content as context." ), "math_code": ( "You are an expert code interpreter and mathematician. " "Solve the user's question step by step. " "Show your reasoning and keep answers concise." ), "retrieval": ( "You are a retrieval-augmented AI assistant. " "Use the provided context to answer the question accurately." ), "evaluation": ( "You are participating in the GAIA evaluation. " "Provide accurate, comprehensive, and concise answers using all available tools and context." )}
# --- Default Prompts ---DEFAULT_PROMPTS = { "file_context": "The following file(s) were provided as context:\n{context}\n---\n", "direct_question": "{question}", "math_code_question": "Solve or explain: {question}", "retrieval_question": "Answer using the following context: {context}\nQuestion: {question}",}
# --- File Types Supported ---SUPPORTED_FILE_TYPES = [".txt", ".pdf", ".csv", ".docx", ".xlsx", ".png", ".jpg", ".jpeg"]
# --- Utility Functions ---def get_model_config(): return MODEL_CONFIG.copy()
def get_system_prompt(prompt_type: str = "default") -> str: return SYSTEM_PROMPTS.get(prompt_type, SYSTEM_PROMPTS["default"])
def get_default_prompt(prompt_type: str = "direct_question") -> str: return DEFAULT_PROMPTS.get(prompt_type, DEFAULT_PROMPTS["direct_question"])
def get_supported_file_types(): return SUPPORTED_FILE_TYPES.copy() 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137"""Example configuration file showing how to customize the OpenAI AgentCopy this file and modify the settings as needed"""
from config import get_model_config, get_preset, get_system_prompt
# --- Example 1: Custom Model Configuration ---def get_custom_model_config(): """Example of custom model configuration""" return { "model": "gpt-4.1-nano", "temperature": 0.5, # More conservative than default "top_p": 0.9, "frequency_penalty": 0.1, # Slight penalty for repetition "presence_penalty": 0.0, "stream": False }
# --- Example 2: Custom System Prompt ---def get_custom_system_prompt(): """Example of custom system prompt""" return """You are an expert AI assistant specializing in technical and scientific questions.Your responses should be:- Accurate and well-researched- Technical but accessible- Include relevant examples when helpful- Cite sources when using web search- Show step-by-step reasoning for calculations
Always prioritize accuracy over brevity."""
# --- Example 3: Custom Preset ---def get_custom_preset(): """Example of custom preset configuration""" return { "temperature": 0.4, # More conservative "system_prompt": get_custom_system_prompt(), "use_web_search": True, "use_code_interpreter": True, "use_retrieval": False # Disable retrieval for this preset }
# --- Example 4: Custom Question Keywords ---def get_custom_question_keywords(): """Example of custom question type detection""" return { "web_search": [ "latest", "recent", "current", "today", "yesterday", "this year", "2024", "2025", "news", "update", "announcement", "price", "stock", "weather", "location", "website", "url", "online", "internet", "search", "now", "live", "breaking", "trending", "popular", "viral" # Added custom keywords ], "code_interpreter": [ "calculate", "compute", "solve", "equation", "formula", "percentage", "statistics", "data", "analysis", "graph", "chart", "plot", "sum", "average", "mean", "median", "math", "mathematical", "arithmetic", "algebra", "geometry", "calculus", "algorithm", "program", "code", "script" # Added programming keywords ] }
# --- Example 5: Using Custom Configuration in Agent ---def create_custom_agent(): """Example of how to create an agent with custom configuration""" from evaluation import OpenAIAgent # Method 1: Use custom preset custom_preset = get_custom_preset() agent = OpenAIAgent(use_tools=True, preset="evaluation") # Method 2: Override configuration after creation agent.model_config.update(get_custom_model_config()) agent.system_prompt = get_custom_system_prompt() agent.question_keywords = get_custom_question_keywords() return agent
# --- Example 6: Environment-Specific Configurations ---def get_environment_config(env="production"): """Example of environment-specific configurations""" configs = { "development": { "temperature": 0.8, # More creative for development "debug_mode": True }, "testing": { "temperature": 0.3, # Very conservative for testing "debug_mode": True }, "production": { "temperature": 0.7, # Balanced for production "debug_mode": False } } return configs.get(env, configs["production"])
# --- Example 7: Domain-Specific Configurations ---def get_domain_config(domain="general"): """Example of domain-specific configurations""" domain_configs = { "technical": { "system_prompt": "You are a technical expert. Provide detailed, accurate technical explanations.", "temperature": 0.3 }, "creative": { "system_prompt": "You are a creative assistant. Provide imaginative and engaging responses.", "temperature": 1.0 }, "educational": { "system_prompt": "You are an educational assistant. Explain concepts clearly with examples.", "temperature": 0.6 }, "general": { "system_prompt": "You are a helpful AI assistant. Provide accurate and useful information.", "temperature": 0.7 } } return domain_configs.get(domain, domain_configs["general"])
if __name__ == "__main__": # Example usage print("=== Configuration Examples ===") print("\n1. Custom Model Config:") print(get_custom_model_config()) print("\n2. Custom System Prompt:") print(get_custom_system_prompt()) print("\n3. Custom Preset:") print(get_custom_preset()) print("\n4. Environment Config (production):") print(get_environment_config("production")) print("\n5. Domain Config (technical):") print(get_domain_config("technical")) 4 unmodified lines56789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525316 unmodified lines7071727374757677787992 unmodified lines1721731741751761771781791801811821831841854 unmodified lines19019119219319419519619719819920020120 unmodified lines2222232242252264 unmodified linesimport pandas as pdfrom transformers import pipelineimport wikipedia# (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.")# Use a strong open-domain model (can be changed to another if needed)self.generator = pipeline("text-generation", model="google/gemma-7b-it", max_new_tokens=64)self.qa = pipeline("question-answering", model="deepset/roberta-base-squad2")def search_wikipedia(self, question: str) -> str:try:page = wikipedia.page(question, auto_suggest=True)return page.content[:2000] # Limit context length for QAexcept Exception as e:print(f"Wikipedia search failed: {e}")return ""def __call__(self, question: str) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")# Try Wikipedia search for factual questionscontext = self.search_wikipedia(question)if context:try:result = self.qa(question=question, context=context)answer = result["answer"]if answer and answer.lower() not in ["", "n/a", "no answer"]:print(f"QA pipeline answer: {answer}")return answerexcept Exception as e:print(f"QA pipeline failed: {e}")# Fallback to generative modeltry:gen = self.generator(question)[0]["generated_text"]print(f"Generative model answer: {gen}")return gen.strip()except Exception as e:print(f"Generator failed: {e}")return "Sorry, I couldn't generate an answer."def run_and_submit_all( profile: gr.OAuthProfile | None):"""16 unmodified lines# 1. Instantiate Agent ( modify this part to create your agent)try:agent = BasicAgent()except Exception as e:print(f"Error instantiating agent: {e}")return f"Error initializing agent: {e}", 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)92 unmodified lines# --- 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:**4 unmodified linesgr.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 constructorresults_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)run_button.click(fn=run_and_submit_all,outputs=[status_output, results_table]20 unmodified linesprint("-"*(60 + len(" App Starting ")) + "\n")print("Launching Gradio Interface for Basic Agent Evaluation...")demo.launch(debug=True, share=False)4 unmodified lines5678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821916 unmodified lines23623723823924024124224324424524624724824925025125225392 unmodified lines3463473483493503513523533543553563573583593603613623633643653663673684 unmodified lines37337437537637737837938038138238338438538638738838939039120 unmodified lines4124134144154164 unmodified linesimport 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 hostsocket.create_connection(("8.8.8.8", 53), timeout=3)return Trueexcept OSError:return Falsedef 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 APImodel_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_toolsself.preset = preset# Validate configurationif not validate_config():raise Exception("Configuration validation failed")# Check connectivity and API accessinternet_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 clientself.client = OpenAI(api_key=get_api_key())# Get configuration from presetself.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 configurationself.tools = get_tools_config(use_tools)# Get question keywordsself.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_textexcept 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_textexcept 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_textexcept 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_textexcept 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 typequestion_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 answerif 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 answerprint(f"Using direct {self.model_config['model']} response...")answer = self.get_direct_answer(question)print(f"Direct answer: {answer[:100]}...")return answerdef test_agent_initialization():"""Test function to check if the agent can be initialized properly"""try:print("Testing agent initialization...")# Check connectivity firstinternet_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 possibleif 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 questiontest_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_msgexcept Exception as e:error_msg = f"β Agent test failed: {e}"print(error_msg)return error_msgdef run_and_submit_all( profile: gr.OAuthProfile | None):"""16 unmodified lines# 1. Instantiate Agent ( modify this part to create your agent)try:# First try with tools enabled and evaluation presetagent = 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)92 unmodified lines# --- 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:**4 unmodified linesgr.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 constructorresults_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]20 unmodified linesprint("-"*(60 + len(" App Starting ")) + "\n")print("Launching Gradio Interface for OpenAI GPT-4.1-nano Agent Evaluation...")demo.launch(debug=True, share=False)
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364import osfrom transformers import pipelinefrom config import get_model_config, get_system_prompt, get_default_prompt, get_supported_file_typesimport pandas as pdimport pdfplumberfrom docx import Documentfrom PIL import Imageimport io
class HuggingFaceAgent: def __init__(self): self.config = get_model_config() self.llm = pipeline("text-generation", model=self.config["llm_model"], max_new_tokens=self.config["max_new_tokens"]) self.code = pipeline("text2text-generation", model=self.config["code_model"], max_new_tokens=self.config["max_new_tokens"]) # Retrieval pipeline can be added here if needed self.supported_file_types = get_supported_file_types()
def extract_file_context(self, files): context = [] for file in files: ext = os.path.splitext(file.name)[1].lower() if ext == ".txt": context.append(file.read().decode("utf-8")[:2000]) elif ext == ".pdf": with pdfplumber.open(file) as pdf: text = " ".join(page.extract_text() or '' for page in pdf.pages) context.append(text[:2000]) elif ext == ".csv": df = pd.read_csv(file) context.append(df.head(10).to_string()) elif ext == ".docx": doc = Document(file) text = "\n".join([p.text for p in doc.paragraphs]) context.append(text[:2000]) elif ext in [".png", ".jpg", ".jpeg"]: img = Image.open(file) context.append(f"[Image file: {file.name}, size: {img.size}]") else: context.append(f"[Unsupported file type: {file.name}]") return "\n".join(context)
def is_math_or_code(self, question): keywords = ["calculate", "compute", "solve", "equation", "math", "code", "python", "step by step", "formula", "percentage", "sum", "average", "mean", "median", "algebra", "geometry", "calculus"] return any(k in question.lower() for k in keywords)
def __call__(self, question, files=None): context = "" if files: context = self.extract_file_context(files) if context: prompt = get_default_prompt("retrieval_question").format(context=context, question=question) system_prompt = get_system_prompt("retrieval") input_text = f"{system_prompt}\n{prompt}" return self.llm(input_text)[0]["generated_text"].strip() elif self.is_math_or_code(question): system_prompt = get_system_prompt("math_code") prompt = get_default_prompt("math_code_question").format(question=question) input_text = f"{system_prompt}\n{prompt}" return self.code(input_text)[0]["generated_text"].strip() else: system_prompt = get_system_prompt("default") prompt = get_default_prompt("direct_question").format(question=question) input_text = f"{system_prompt}\n{prompt}" return self.llm(input_text)[0]["generated_text"].strip() 1234567gradiorequestsopenaitransformerswikipediagradio[oauth]torch12345678transformers>=4.36.0sentence-transformers>=2.2.2gradio>=4.0.0pandas>=1.5.0pdfplumber>=0.10.0python-docx>=0.8.11Pillow>=9.0.0requests>=2.28.0
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171#!/usr/bin/env python3"""Test script for OpenAI GPT-4.1-nano Agent with Responses API and Configuration"""
import osfrom evaluation import OpenAIAgent, check_internet_connection, check_openai_apifrom config import validate_config, get_preset, get_model_config
def test_configuration(): """Test configuration validation and presets""" print("Testing Configuration...") print("=" * 60) # Test configuration validation print("1. Testing configuration validation...") if validate_config(): print("β
Configuration validation passed") else: print("β Configuration validation failed") return False # Test presets print("\n2. Testing configuration presets...") presets = ["evaluation", "conservative", "creative"] for preset in presets: preset_config = get_preset(preset) print(f"β
Preset '{preset}': temperature={preset_config.get('temperature', 'N/A')}, max_tokens={preset_config.get('max_tokens', 'N/A')}") return True
def test_openai_agent(): """Test the OpenAI agent with various question types using Responses API""" print("\nTesting OpenAI GPT-4.1-nano Agent with Responses API...") print("=" * 60) # Check prerequisites internet_available = check_internet_connection() openai_available, openai_status = check_openai_api() print(f"Internet: {'β
' if internet_available else 'β'}") print(f"OpenAI API: {'β
' if openai_available else 'β'} - {openai_status}") if not internet_available or not openai_available: print("β Cannot test agent - missing prerequisites") return # Test questions covering different tool types test_questions = [ "What is artificial intelligence?", # Direct response "What is the current weather in New York?", # Web search "Calculate 15% of 250", # Code interpreter "What are the latest news about AI?", # Web search "What is the capital of France?", # Direct response "Solve the equation: 2x + 5 = 15", # Code interpreter "What's the current price of Bitcoin?", # Web search ] # Test different presets presets_to_test = ["evaluation", "conservative"] for preset in presets_to_test: print(f"\n--- Testing with preset: {preset} ---") try: # Initialize agent with tools and preset agent = OpenAIAgent(use_tools=True, preset=preset) # Test each question for i, question in enumerate(test_questions[:3], 1): # Test first 3 questions per preset print(f"\n--- Test {i}: {question} ---") try: answer = agent(question) if answer: print(f"β
Answer: {answer[:200]}...") else: print("β No answer received") except Exception as e: print(f"β Error: {e}") print(f"β
Preset '{preset}' tests completed!") except Exception as e: print(f"β Agent initialization with preset '{preset}' failed: {e}") # Test without tools print(f"\n--- Testing without tools ---") try: agent = OpenAIAgent(use_tools=False, preset="evaluation") print("β
Agent initialized without tools") # Test with one simple question question = "What is artificial intelligence?" answer = agent(question) if answer: print(f"β
Answer: {answer[:200]}...") else: print("β No answer received") except Exception as e: print(f"β Agent initialization without tools failed: {e}")
def test_responses_api_directly(): """Test the Responses API directly to verify it's working""" print("\n" + "=" * 60) print("Testing Responses API directly...") print("=" * 60) try: from openai import OpenAI from config import get_api_key, get_model_config client = OpenAI(api_key=get_api_key()) model_config = get_model_config() # Test basic response response = client.responses.create( model=model_config["model"], input="What is 2+2?", temperature=model_config["temperature"] ) print(f"β
Direct API test successful") print(f"Response: {response.output_text}") # Test with tools response_with_tools = client.responses.create( model=model_config["model"], input="What is the weather like today?", tools=[{"type": "web_search_preview"}], temperature=model_config["temperature"] ) print(f"β
Tools API test successful") print(f"Response: {response_with_tools.output_text}") except Exception as e: print(f"β Direct API test failed: {e}")
def test_model_configuration(): """Test different model configurations""" print("\n" + "=" * 60) print("Testing Model Configuration...") print("=" * 60) # Test default configuration default_config = get_model_config() print(f"β
Default config: {default_config}") # Test custom configuration custom_config = get_model_config({ "temperature": 0.5, "max_tokens": 500 }) print(f"β
Custom config: {custom_config}") # Test preset configurations for preset_name in ["evaluation", "conservative", "creative"]: preset_config = get_preset(preset_name) print(f"β
Preset '{preset_name}': {preset_config}")
if __name__ == "__main__": print("π§ͺ Starting comprehensive OpenAI Agent tests...") # Run all tests test_configuration() test_model_configuration() test_responses_api_directly() test_openai_agent() print("\nπ All tests completed!") README.md+260-28
app.py+117
config.pyAdded+62
config_example.pyAdded+137
evaluation.py+229-39
hf_agent.pyAdded+64
requirements.txt+8-7
test_openai_agent.pyAdded+171