Spaces:
Runtime error
Runtime error
Refactor SmolAgent to integrate OpenAI's API, enhancing question answering capabilities with improved instructions and error handling. Update Gradio interface for GAIA evaluation submission and results display.
Browse files1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950511 unmodified line53545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352361 unmodified lineimport gradio as grimport requestsimport pandas as pdfrom smolagents import CodeAgent, InferenceClientModel, DuckDuckGoSearchToolfrom dotenv import load_dotenv# Load environment variablesload_dotenv()# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"HF_TOKEN = os.getenv("HF_TOKEN")INSTRUCTIONS = """Your task is to answer the user's question.Return a number OR as few words as possible OR a comma separated list of numbers and/or strings.- If you are asked for a number, don't use a comma to write your number, and don't use units like $ or % unless specified otherwise.- If you are asked for a string, don't use articles or abbreviations (e.g., for cities), and write digits in plain text unless specified otherwise.- If you are asked for a comma-separated list, apply the above rules to each element."""# --- Smol Agent Definition ---class SmolAgent:def __init__(self, hf_token: str):print("Initializing SmolAgent with smolagents...")if not hf_token:raise ValueError("Hugging Face token not found. Please set HF_TOKEN environment variable.")# Initialize the modelmodel = InferenceClientModel(model_id="meta-llama/Meta-Llama-3-8B-Instruct",token=hf_token,)# Initialize the agent with tools and instructionsself.agent = CodeAgent(tools=[DuckDuckGoSearchTool()],model=model,instructions=INSTRUCTIONS,)print("SmolAgent initialized with CodeAgent and DuckDuckGoSearchTool.")def __call__(self, question: str) -> str:print(f"\nπͺ Running on question:\n{question}\n")try:# The CodeAgent's run method returns the final answer directlyanswer = self.agent.run(question)print(f"β Agent's final answer: {answer}")return str(answer) # Ensure the output is a stringexcept Exception as e:import tracebacktraceback.print_exc()1 unmodified lineprint(f"β {error_message}")return error_messagedef run_and_submit_all(profile: gr.OAuthProfile | None):"""Fetches all questions, runs the SmolAgent on them, submits all answers,and displays the results."""# --- Determine HF Space Runtime URL and Repo URL ---space_id = os.getenv("SPACE_ID")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.", Noneapi_url = DEFAULT_API_URLquestions_url = f"{api_url}/questions"submit_url = f"{api_url}/submit"# 1. Instantiate Agenttry:agent = SmolAgent(hf_token=HF_TOKEN)except Exception as e:print(f"Error instantiating agent: {e}")return f"Error initializing agent: {e}", Noneagent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"print(f"Agent code link: {agent_code}")# 2. Fetch Questionsprint(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.", Noneprint(f"Fetched {len(questions_data)} questions.")except requests.exceptions.RequestException as e:print(f"Error fetching questions: {e}")return f"Error fetching questions: {e}", Noneexcept 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}", Noneexcept 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 Agentresults_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}")continuetry: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 Submissionsubmission_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. Submitprint(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_dfexcept 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_dfexcept requests.exceptions.Timeout:status_message = "Submission Failed: The request timed out."print(status_message)results_df = pd.DataFrame(results_log)return status_message, results_dfexcept 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_dfexcept 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("# SmolLM Agent Evaluation Runner")gr.Markdown("""**Instructions:**1. This space uses a `smolagents.CodeAgent` with the `meta-llama/Meta-Llama-3-8B-Instruct` model.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.---**Model Information:**- Agent: `smolagents.CodeAgent`- Model: `meta-llama/Meta-Llama-3-8B-Instruct`- Tools: `DuckDuckGoSearchTool`**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 constructorresults_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 informationspace_host_startup = os.getenv("SPACE_HOST")space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startupif 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 foundprint(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 Smol Agent Evaluation...")demo.launch(debug=True, share=False)1 unmodified line23456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960611 unmodified line636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062071 unmodified lineimport gradio as grimport requestsimport pandas as pdfrom dotenv import load_dotenvfrom smolagents import CodeAgent, OpenAIServerModel, DuckDuckGoSearchTool# Load environment variables (including OPENAI_API_KEY)load_dotenv()# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")INSTRUCTIONS = """You are a general AI assistant. I will ask you a question. Report your thoughts, and then provide your final answer.CRITICAL FORMATTING RULES:- Your final answer should be a number OR as few words as possible OR a comma separated list of numbers and/or strings- If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise- If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise- If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string- Be extremely precise with spelling and formatting - the evaluation uses exact matching- For strings: no extra spaces, no punctuation unless part of the answer, lowercase- For numbers: just the number, no units, no commas, no currency symbols- Provide ONLY the answer as your final response, nothing elseYou have access to a web search tool to help you find accurate information. Use it when you need to look up facts."""# --- Smol Agent Definition ---class SmolAgent:def __init__(self):print("Initializing SmolAgent with OpenAI model...")if not OPENAI_API_KEY:raise ValueError("OPENAI_API_KEY not found. Please set it in your environment.")# Initialize the OpenAI-backed modelself.model = OpenAIServerModel(model_id="gpt-4o-mini", # or "gpt-4", "gpt-3.5-turbo", etc.api_base="https://api.openai.com/v1",api_key=OPENAI_API_KEY,)# Initialize the agent with tools and instructionsself.agent = CodeAgent(tools=[DuckDuckGoSearchTool()],model=self.model,instructions=INSTRUCTIONS,max_steps=7,)print("SmolAgent initialized with CodeAgent and DuckDuckGoSearchTool.")def __call__(self, question: str) -> str:print(f"\nπͺ Running on question:\n{question}\n")try:answer = self.agent.run(question)print(f"β Agent's final answer: {answer}")return str(answer)except Exception as e:import tracebacktraceback.print_exc()1 unmodified lineprint(f"β {error_message}")return error_messagedef run_gaia_evaluation(username: str):"""Run the complete GAIA evaluation and submit results"""print("π GAIA Benchmark Evaluation with ChatGPT")print("=" * 60)if not username:return "β Please provide a username"print(f"π€ User: {username}")# Initialize the agenttry:agent = SmolAgent()except Exception as e:return f"β Failed to initialize agent: {e}"# Fetch questionstry:resp = requests.get(f"{DEFAULT_API_URL}/questions", timeout=30)resp.raise_for_status()data = resp.json()questions = data if isinstance(data, list) else data.get("questions", [])print(f"π Loaded {len(questions)} questions")except requests.RequestException as e:return f"β Error fetching questions: {e}"# Process questionsresults = []progress_log = []for i, q in enumerate(questions):task_id = q["task_id"]text = q["question"]progress_log.append(f"β Question {i+1}: {text}")print(f"\nβ Question {i+1}: {text}")try:result = agent(text)result_str = str(result).strip()# Take the last line as the answerout = result_str.splitlines()[-1] if result_str else "AGENT ERROR: No response."if out.startswith("{"):out = "AGENT ERROR: No final answer."out = out.strip().rstrip(".")results.append({"task_id": task_id, "submitted_answer": out})progress_log.append(f"β Answer: '{out}'")print(f"β Answer: '{out}'")except Exception as e:error_msg = f"AGENT ERROR: {e}"results.append({"task_id": task_id, "submitted_answer": error_msg})progress_log.append(f"β Error: {error_msg}")print(f"β Error: {error_msg}")# Submit resultspayload = {"username": username,"agent_code": "chatgpt-gpt4o-mini-with-tools","answers": results,}try:print("π€ Submitting to GAIA leaderboard...")post = requests.post(f"{DEFAULT_API_URL}/submit", json=payload, timeout=60)post.raise_for_status()res = post.json()# Format results for displayresult_summary = f"""π GAIA BENCHMARK RESULTS{'=' * 60}π€ User: {res.get('username', username)}π Overall Score: {res.get('score', res.get('overall_score', 'N/A'))}%β Correct: {res.get('correct_count', res.get('num_correct', 'N/A'))}/{len(results)}π¬ Message: {res.get('message', 'N/A')}{'=' * 60}"""# Combine progress log with final resultsfull_log = "\n".join(progress_log) + "\n" + result_summaryreturn full_logexcept requests.RequestException as e:error_msg = f"β Error submitting: {e}"done = sum(1 for r in results if not r["submitted_answer"].startswith("AGENT ERROR"))local_summary = f"π Completed locally: {done}/{len(results)}"return "\n".join(progress_log) + "\n" + error_msg + "\n" + local_summary# --- Gradio Interface ---def create_interface():with gr.Blocks(title="GAIA Benchmark with ChatGPT", theme=gr.themes.Soft()) as demo:gr.Markdown("# π GAIA Benchmark Evaluation with ChatGPT")gr.Markdown("This app runs the GAIA benchmark using ChatGPT (GPT-4o-mini) with web search capabilities.")with gr.Row():with gr.Column(scale=1):username_input = gr.Textbox(label="Hugging Face Username",placeholder="Enter your HF username",info="This will be used for the GAIA leaderboard submission")run_button = gr.Button("π Run GAIA Evaluation", variant="primary", size="lg")with gr.Column(scale=2):output_area = gr.Textbox(label="Results & Progress",lines=20,max_lines=50,interactive=False)# Event handlerrun_button.click(fn=run_gaia_evaluation,inputs=[username_input],outputs=[output_area])gr.Markdown("""### How it works:1. Enter your Hugging Face username2. Click "Run GAIA Evaluation"3. The agent will process all 20 GAIA questions using ChatGPT + web search4. Results will be automatically submitted to the GAIA leaderboard5. Your score will be displayed here### Requirements:- Set `OPENAI_API_KEY` in your environment variables- Valid Hugging Face username for leaderboard submission""")return demo# --- Main execution ---if __name__ == "__main__":demo = create_interface()demo.launch()
app.py+161-190