Spaces:
Build error
Build error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051523 unmodified lines56575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191205 unmodified lines1261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791803 unmodified lines184185186187188import osimport gradio as grimport requestsimport inspectimport pandas as pdfrom smolagent.agents import SimpleAgentfrom transformers import pipeline# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"# --- FLAN-T5 Agent Definition ---# Load the FLAN-T5 base model for question-answeringqa_pipeline = pipeline("text2text-generation", model="google/flan-t5-base")# Define a tool that wraps the FLAN-T5 modelclass FlanT5Tool:def __init__(self):self.name = "flan_t5_qa"self.description = "Answers questions using FLAN-T5 base."def __call__(self, question: str) -> str:print(f"FlanT5Tool received: {question}")response = qa_pipeline(question, max_new_tokens=100)return response[0]['generated_text']# Instantiate the toolflan_tool = FlanT5Tool()# Create a simple agent with the FLAN-T5 toolclass SmolAgentWrapper:def __init__(self):self.agent = SimpleAgent(tools=[flan_tool])def __call__(self, question: str) -> str:print(f"SmolAgentWrapper received: {question}")return self.agent.run(question)# --- Run and Submit Logic ---def run_and_submit_all(profile: gr.OAuthProfile | None):"""Fetches all questions, runs the agent 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.")3 unmodified linesquestions_url = f"{api_url}/questions"submit_url = f"{api_url}/submit"# 1. Instantiate Agent (with FLAN-T5)try:agent = SmolAgentWrapper()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(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()5 unmodified linesf"({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("# Smol 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.---**Disclaimers:**This space uses a small agent powered by FLAN-T5 base for answering questions.""")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)3 unmodified lines)if __name__ == "__main__":print("Launching Gradio Interface for Smol Agent Evaluation...")demo.launch(debug=True, share=False)12345678910111213141516171819202122232425262728293 unmodified lines3334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182835 unmodified lines89909192939495969798991001011021031041051061071081091101111121131141151163 unmodified lines120121122123124125126import osimport gradio as grimport requestsimport pandas as pdfrom smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"# --- Define Agent ---class SmolAgentWrapper:def __init__(self):self.model = InferenceClientModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct", provider="together") # Uses flan-t5-base via HF Inference APIself.tools = [DuckDuckGoSearchTool()] # You can add more tools hereself.agent = CodeAgent(model=self.model, tools=self.tools)def __call__(self, question: str) -> str:return self.agent.run(question)# --- Evaluation Logic ---def run_and_submit_all(profile: gr.OAuthProfile | None):space_id = os.getenv("SPACE_ID")if profile:username = f"{profile.username}"print(f"User logged in: {username}")else:print("User not logged in.")3 unmodified linesquestions_url = f"{api_url}/questions"submit_url = f"{api_url}/submit"# Create the agenttry:agent = SmolAgentWrapper()except Exception as e:return f"Error initializing agent: {e}", Noneagent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"# Fetch questionstry:response = requests.get(questions_url, timeout=15)response.raise_for_status()questions_data = response.json()if not questions_data:return "Fetched questions list is empty or invalid format.", Noneprint(f"Fetched {len(questions_data)} questions.")except Exception as e:return f"Error fetching questions: {e}", None# Run agentresults_log = []answers_payload = []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: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: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)# Submit answerssubmission_data = {"username": username.strip(),"agent_code": agent_code,"answers": answers_payload}try:response = requests.post(submit_url, json=submission_data, timeout=60)response.raise_for_status()5 unmodified linesf"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"f"Message: {result_data.get('message', 'No message received.')}")results_df = pd.DataFrame(results_log)return final_status, results_dfexcept Exception as e:return f"Submission Failed: {e}", pd.DataFrame(results_log)# --- Gradio Interface ---with gr.Blocks() as demo:gr.Markdown("# SmolAgent Evaluation Runner (Flan-T5 + DuckDuckGo Tool)")gr.Markdown("""**Instructions:**1. Log in to Hugging Face with the button below.2. Click the button to run all GAIA questions through the SmolAgent.3. Results will be submitted automatically and your score will be shown.**Note:** Model runs on Hugging Face Inference API using `flan-t5-base`, optimized for CPU.""")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)3 unmodified lines)if __name__ == "__main__":print("-" * 60)print("Launching SmolAgent Space...")print("-" * 60)demo.launch(debug=True, share=False)
app.py+32-94