Spaces:
Runtime error
Runtime error
Refactor SmolAgent to remove DuckDuckGoSearchTool, update SYSTEM_PROMPT for improved response format, and enhance answer parsing logic.
Browse files2 unmodified lines3456789101112131415161718192021222324252627284 unmodified lines3334353637383940416 unmodified lines4849505152535455565758596061626364124 unmodified lines1891901911921931941951961971981992002012022032 unmodified linesimport requestsimport inspectimport pandas as pdfrom smolagents import CodeAgent, InferenceClientModel, DuckDuckGoSearchTool# (Keep Constants as is)# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"HF_TOKEN = os.getenv("HF_TOKEN")SYSTEM_PROMPT = """You are a helpful assistant answering evaluation questions that will be scored using exact string match.Instructions:- Return ONLY the final answer on a single line.- Do NOT include explanations or reasoning.- Do NOT write "Answer:" or "FINAL ANSWER:" before your response.- If the answer is a number, return the plain number with no commas, currency symbols, or units unless explicitly required.- If the answer is a string, use lowercase, no articles, no abbreviations, and digits in plain text unless specified otherwise.- If the answer is a comma-separated list, follow the above rules for each element with no spaces after commas.- If unsure, guess concisely.Always strictly follow these instructions to maximize exact match accuracy."""# --- Smol Agent Definition ---4 unmodified linesif not hf_token:raise ValueError("Hugging Face token not found. Please set HF_TOKEN environment variable in HF Spaces settings.")# Initialize the toolsearch_tool = DuckDuckGoSearchTool()# 3. Initialize the SmolLM modelmodel = InferenceClientModel(model_id="HuggingFaceTB/SmolLM-1.7B-Instruct",6 unmodified linesmodel=model,instructions=SYSTEM_PROMPT,)print("SmolAgent initialized")def __call__(self, question: str) -> str:print(f"\n🪐 Running on question:\n{question}\n")try:answer = self._agent.run(prompt)print(f"Agent returning answer: {answer}")return str(answer)except Exception as e:print(f"Agent error: {e}")return f"Agent error: {e}"def run_and_submit_all( profile: gr.OAuthProfile | None):124 unmodified lines"""**Instructions:**1. This space uses SmolLM-360M-Instruct model with smolagents for question answering.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:**- Using: HuggingFaceTB/SmolLM-360M-Instruct- Framework: smolagents CodeAgent- Tools: DuckDuckGo Search (for web access)**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).2 unmodified lines34567891011121314154 unmodified lines2021222324256 unmodified lines323334353637383940414243444546474849505152535455565758596061626364124 unmodified lines1891901911921931941951961971981992002012022032 unmodified linesimport requestsimport inspectimport pandas as pdfrom smolagents import CodeAgent, InferenceClientModel# (Keep Constants as is)# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"HF_TOKEN = os.getenv("HF_TOKEN")SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]. 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."""# --- Smol Agent Definition ---4 unmodified linesif not hf_token:raise ValueError("Hugging Face token not found. Please set HF_TOKEN environment variable in HF Spaces settings.")# 3. Initialize the SmolLM modelmodel = InferenceClientModel(model_id="HuggingFaceTB/SmolLM-1.7B-Instruct",6 unmodified linesmodel=model,instructions=SYSTEM_PROMPT,)print("SmolAgent initialized.")def __call__(self, question: str) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")try:# The system prompt is already set, just pass the question.full_response = self._agent.run(question)print(f"Agent full response: {full_response}")# Parse the response to extract the final answerif "FINAL ANSWER:" in full_response:# Split and get the part after "FINAL ANSWER:"final_answer_part = full_response.split("FINAL ANSWER:")[1]# Remove brackets if they exist and strip whitespacefinal_answer = final_answer_part.strip()if final_answer.startswith('[') and final_answer.endswith(']'):final_answer = final_answer[1:-1]print(f"Agent returning parsed answer: {final_answer}")return final_answerelse:print("Warning: 'FINAL ANSWER:' not found in response. Returning full response.")return full_responseexcept Exception as e:print(f"Error running agent: {e}")return f"AGENT ERROR: {e}"def run_and_submit_all( profile: gr.OAuthProfile | None):124 unmodified lines"""**Instructions:**1. This space uses SmolLM-1.7B-Instruct model with smolagents for question answering.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:**- Using: HuggingFaceTB/SmolLM-1.7B-Instruct- Framework: smolagents CodeAgent- No additional tools (pure reasoning)**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).
app.py+28-28