Spaces:
Sleeping
Sleeping
fix
Browse files2 unmodified lines34567891011121314151617181920212223242512 unmodified lines3839404142434445464748495095 unmodified lines1461471481491501511521531541551561571581591602 unmodified lines1631641651661671681692 unmodified linesimport requestsimport inspectimport pandas as pd# (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.")def __call__(self, question: str) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")fixed_answer = "This is a default answer."print(f"Agent returning fixed answer: {fixed_answer}")return fixed_answerdef run_and_submit_all( profile: gr.OAuthProfile | None):"""Fetches all questions, runs the BasicAgent on them, submits all answers,and displays the results.12 unmodified linesquestions_url = f"{api_url}/questions"submit_url = f"{api_url}/submit"# 1. Instantiate Agent ( modify this part to create your agent)try:agent = BasicAgent()except Exception as e:print(f"Error instantiating agent: {e}")return f"Error initializing agent: {e}", None# In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"print(agent_code)95 unmodified linesgr.Markdown("""**Instructions:**1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.---**Disclaimers:**Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.""")2 unmodified linesrun_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(2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818212 unmodified lines959697989910010110210310410510610795 unmodified lines2032042052062072082092102112122132142152 unmodified lines2182192202212222232 unmodified linesimport requestsimport inspectimport pandas as pdfrom smolagents import CodeAgent, DuckDuckGoSearchTool, OpenAIServerModel# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"# --- Basic Agent Definition ---class BasicAgent:def __init__(self):print("BasicAgent initialized.")# Initialize the modelmodel = OpenAIServerModel(model_id="gpt-4o")# Initialize the search toolsearch_tool = DuckDuckGoSearchTool()# Initialize Agent without system promptself.agent = CodeAgent(model=model,tools=[search_tool])def __call__(self, question: str) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")# Enhance the question to reinforce code format requirementsenhanced_question = f"""You MUST solve this problem using Python code. Always start with 'Thoughts:' section followed by a 'Code:' section with a ```py codeblock:QUESTION: {question}REMEMBER:1. Your response MUST follow this format exactly:Thoughts: [your reasoning here]Code:```py# Your Python code solution here```2. Always include ```py at the beginning of your code block and close with ```3. Even if the answer seems simple, you MUST include code to derive it4. If you need to search, use web_search("query")5. If you need to provide a final answer, use final_answer(value)Now solve the problem:"""try:fixed_answer = self.agent.run(enhanced_question)print(f"Agent returning answer (first 100 chars): {fixed_answer[:100]}...")return fixed_answerexcept Exception as e:print(f"Error running agent: {e}")# If agent fails, provide a formatted response that matches expected patternfallback_answer = f"""Thoughts: I encountered an error while solving this problem.Code:```py# Fallback solutionfrom datetime import datetimedef solve_problem():# The original question was: {question[:100]}...print("Attempting to solve the problem")# Fallback approachreturn "Unable to automatically solve this problem"# Execute solutionresult = solve_problem()print(f"Result: {result}")```Due to technical difficulties, I couldn't fully process this question. Here's my best assessment: The question appears to be about {question[:50]}... Without being able to run a complete analysis, I would recommend approaching this by breaking down the problem and using appropriate Python libraries for the specific task."""return fallback_answerdef run_and_submit_all(profile: gr.OAuthProfile | None):"""Fetches all questions, runs the BasicAgent on them, submits all answers,and displays the results.12 unmodified linesquestions_url = f"{api_url}/questions"submit_url = f"{api_url}/submit"# 1. Instantiate Agenttry: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 codebaseagent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"print(agent_code)95 unmodified linesgr.Markdown("""**Instructions:**1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.---**Disclaimers:**Once clicking on the "submit button, it can take quite some time (this is the time for the agent to go through all the questions).This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution.""")2 unmodified linesrun_button = gr.Button("Run Evaluation & Submit All Answers")status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)run_button.click(
app.py+67-13