Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files26 unmodified lines272829303132529 unmodified lines56256356456556656756856976 unmodified lines64664764864965065165265387 unmodified lines7417427437447457467473 unmodified lines7517527537547557567577587592 unmodified lines7627637647657667677684 unmodified lines77377477577677777877978078178278378424 unmodified lines8098108118128138148156 unmodified lines8228238248258268273 unmodified lines8318328338348358369 unmodified lines84684784884985085114 unmodified lines86686786886987087120 unmodified lines8928938948958968978988999009019023 unmodified lines90690790890991091191291391491591691791891992092192292392492592624 unmodified lines9519529539549559569579589599609619629639642 unmodified lines96796896997097197297311 unmodified lines9859869879889899909919929939949955 unmodified lines100110021003100410051006100710081009101010111012101310141015101625 unmodified lines104210431044104510461047104849 unmodified lines10981099110011011102110311041105110629 unmodified lines1136113711381139114011411142114326 unmodified linesfrom smolagents import CodeAgent, LiteLLMModel, toollitellm.drop_params = Trueenv_ci = {k.upper(): v.strip(" '\"\n\r\t") for k, v in os.environ.items() if v}gemini_key = env_ci.get("GEMINI_API_KEY") or env_ci.get("GOOGLE_API_KEY") or ""529 unmodified linesif self.provider_keys.get("groq"):candidate_models.extend(["groq/openai/gpt-oss-120b","groq/qwen/qwen3-32b","groq/llama-3.3-70b-versatile","groq/openai/gpt-oss-20b","groq/llama-3.1-8b-instant",])76 unmodified linesdef _sanitize_code_tags(text: str) -> str:import recleaned_text = re.sub(r"</?code[^>]*>\s*```", "```", text, flags=re.IGNORECASE)cleaned_text = re.sub(r"```\s*</?code[^>]*>", "```", cleaned_text, flags=re.IGNORECASE)if re.search(r"<code>.*?</code>", cleaned_text, flags=re.DOTALL | re.IGNORECASE):def _clean_html_block(match):87 unmodified linesexact_match_rule = ("CRITICAL OUTPUT RULES FOR EXACT MATCH EVALUATION:\n""- Always write valid Python code inside ```py and ``` fences. NEVER put 'Thought:' or HTML tags like <code> inside the Python block.\n""- Never call built-in open(); use read_local_file(file_path) for text/PDF/ZIP/spreadsheet files, ""inspect_image(image_path, question) for images, and transcribe_audio(audio_path, question) for audio files (.mp3, .wav).\n""- If web_search returns no results, use search_wikipedia(query) or fetch_url_text(url).\n"3 unmodified lines"- Do not wrap the answer in a dictionary like {'answer': ...}; pass the plain answer string directly.")self.agent = CodeAgent(model=model,tools=[web_search,search_wikipedia,fetch_url_text,2 unmodified linesinspect_image,transcribe_audio,],additional_authorized_imports=["json","csv","pandas",4 unmodified lines"fractions","string",],instructions=exact_match_rule,max_steps=14,verbosity_level=0,)print("CodeAgent initialized with LiteLLMModel.")@staticmethoddef _clean_exact_match_answer(raw_answer) -> str:import re24 unmodified linesreturn textdef __call__(self, question: str, task_id: str = "") -> str:import timefrom smolagents import LiteLLMModel6 unmodified lines)models_to_try = list(getattr(self, "working_models", []) or [self.model_id])max_attempts = min(max(3, len(models_to_try)), 6)model_cls = getattr(self, "_model_cls", LiteLLMModel)3 unmodified lines"error in code parsing","expected string or bytes-like object","reached max steps",)exception_error_markers = output_error_markers + ("authenticationerror",9 unmodified lines"503","overloaded","temporarily unavailable",)permanent_model_markers = ("401",14 unmodified lines"error in code parsing","expected string or bytes-like object","reached max steps",)for attempt in range(max_attempts):20 unmodified linesis_permanent = any(m in err_lower for m in permanent_model_markers)is_rate_limited = any(m in err_lower for m in provider_limit_markers)if is_permanent:if len(models_to_try) <= 1:return f"AGENT ERROR: {exc}"models_to_try = [m for m in models_to_try if m != failed_model]if hasattr(self, "working_models") and len(self.working_models) > 1:self.working_models = [m for m in self.working_models if m != failed_model]current_provider = (3 unmodified lines)switched_provider = Falseif models_to_try and (len(models_to_try) > 1 or models_to_try[0] != failed_model):other_provider_models = [mfor m in models_to_tryif m != failed_modeland ((m.split("/", 1)[0].lower() if "/" in m else "gemini")!= current_provider)]if other_provider_models and (is_permanent or is_rate_limited):next_model = other_provider_models[0]elif failed_model in models_to_try:idx = models_to_try.index(failed_model)next_model = models_to_try[(idx + 1) % len(models_to_try)]else:next_model = models_to_try[0]24 unmodified linesif switched_provider or any(m in err_lower for m in fast_retry_markers):wait_sec = 2else:wait_sec = 15print(f"Sleeping {wait_sec}s before next attempt...")time.sleep(wait_sec)return "AGENT ERROR: Max retries exceeded."def run_and_submit_all( profile: gr.OAuthProfile | None):"""Fetches all questions, runs the BasicAgent on them, submits all answers,and displays the results.2 unmodified linesspace_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the codeif profile:username= f"{profile.username}"print(f"User logged in: {username}")else:print("User not logged in.")11 unmodified linesreturn 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"if space_idelse (os.getenv("AGENT_CODE_URL")or f"https://huggingface.co/spaces/{username.strip()}/Final_Assignment_Template/tree/main").strip())print(agent_code)5 unmodified linesresponse.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}", None25 unmodified linesprint("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)49 unmodified lines"""**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:**29 unmodified linesif 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.")26 unmodified lines27282930313233529 unmodified lines56356456556656756876 unmodified lines64564664764864965065165287 unmodified lines7407417427437447457463 unmodified lines7507517527537547557567577582 unmodified lines7617627637647657667674 unmodified lines77277377477577677777877978078178278378478578678724 unmodified lines8128138148158168176 unmodified lines8248258268278288298308313 unmodified lines8358368378388398408419 unmodified lines85185285385485585685785814 unmodified lines87387487587687787887920 unmodified lines9009019029039049059069079083 unmodified lines91291391491591691791891992092192292392492524 unmodified lines9509519529539549559569579589599609619629632 unmodified lines96696796896997097197211 unmodified lines9849859869879889899909919929939945 unmodified lines100010011002100310041005100610071008100910101011101210131014101525 unmodified lines104110421043104410451046104749 unmodified lines10971098109911001101110211031104110529 unmodified lines1135113611371138113911401141114226 unmodified linesfrom smolagents import CodeAgent, LiteLLMModel, toollitellm.drop_params = Truelitellm.request_timeout = 25env_ci = {k.upper(): v.strip(" '\"\n\r\t") for k, v in os.environ.items() if v}gemini_key = env_ci.get("GEMINI_API_KEY") or env_ci.get("GOOGLE_API_KEY") or ""529 unmodified linesif self.provider_keys.get("groq"):candidate_models.extend(["groq/openai/gpt-oss-120b","groq/openai/gpt-oss-20b","groq/llama-3.1-8b-instant",])76 unmodified linesdef _sanitize_code_tags(text: str) -> str:import recleaned_text = re.sub(r"</?code[^>]*>\s*```", "<code>\n", text, flags=re.IGNORECASE)cleaned_text = re.sub(r"```\s*</?code[^>]*>", "\n</code>", cleaned_text, flags=re.IGNORECASE)if re.search(r"<code>.*?</code>", cleaned_text, flags=re.DOTALL | re.IGNORECASE):def _clean_html_block(match):87 unmodified linesexact_match_rule = ("CRITICAL OUTPUT RULES FOR EXACT MATCH EVALUATION:\n""- Always write valid Python code inside <code> and </code> tags. NEVER put 'Thought:' or ``` fences inside the code block.\n""- Never call built-in open(); use read_local_file(file_path) for text/PDF/ZIP/spreadsheet files, ""inspect_image(image_path, question) for images, and transcribe_audio(audio_path, question) for audio files (.mp3, .wav).\n""- If web_search returns no results, use search_wikipedia(query) or fetch_url_text(url).\n"3 unmodified lines"- Do not wrap the answer in a dictionary like {'answer': ...}; pass the plain answer string directly.")agent_kwargs = {"model": model,"tools": [web_search,search_wikipedia,fetch_url_text,2 unmodified linesinspect_image,transcribe_audio,],"additional_authorized_imports": ["json","csv","pandas",4 unmodified lines"fractions","string",],"instructions": exact_match_rule,"code_block_tags": ("<code>", "</code>"),"max_steps": 10,"verbosity_level": 0,}sig = inspect.signature(CodeAgent.__init__)filtered_agent_kwargs = {k: v for k, v in agent_kwargs.items() if k in sig.parameters}self.agent = CodeAgent(**filtered_agent_kwargs)print("CodeAgent initialized with LiteLLMModel.")@staticmethoddef _clean_exact_match_answer(raw_answer) -> str:import re24 unmodified linesreturn textdef __call__(self, question: str, task_id: str = "") -> str:import timefrom smolagents import LiteLLMModel6 unmodified lines)models_to_try = list(getattr(self, "working_models", []) or [self.model_id])if self.model_id not in models_to_try:models_to_try.insert(0, self.model_id)max_attempts = min(max(3, len(models_to_try)), 6)model_cls = getattr(self, "_model_cls", LiteLLMModel)3 unmodified lines"error in code parsing","expected string or bytes-like object","reached max steps","tool_use_failed",)exception_error_markers = output_error_markers + ("authenticationerror",9 unmodified lines"503","overloaded","temporarily unavailable","timeout","timed out",)permanent_model_markers = ("401",14 unmodified lines"error in code parsing","expected string or bytes-like object","reached max steps","tool_use_failed",)for attempt in range(max_attempts):20 unmodified linesis_permanent = any(m in err_lower for m in permanent_model_markers)is_rate_limited = any(m in err_lower for m in provider_limit_markers)if len(models_to_try) > 1:models_to_try = [m for m in models_to_try if m != failed_model]if is_permanent and hasattr(self, "working_models") and len(self.working_models) > 1:self.working_models = [m for m in self.working_models if m != failed_model]current_provider = (3 unmodified lines)switched_provider = Falseif models_to_try:other_provider_models = [mfor m in models_to_tryif (m.split("/", 1)[0].lower() if "/" in m else "gemini") != current_provider]if other_provider_models and (is_permanent or is_rate_limited):next_model = other_provider_models[0]else:next_model = models_to_try[0]24 unmodified linesif switched_provider or any(m in err_lower for m in fast_retry_markers):wait_sec = 2else:wait_sec = 10print(f"Sleeping {wait_sec}s before next attempt...")time.sleep(wait_sec)return "AGENT ERROR: Max retries exceeded."def run_and_submit_all(profile: gr.OAuthProfile | None):"""Fetches all questions, runs the BasicAgent on them, submits all answers,and displays the results.2 unmodified linesspace_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the codeif profile:username = f"{profile.username}"print(f"User logged in: {username}")else:print("User not logged in.")11 unmodified linesreturn 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/](https://huggingface.co/spaces/){space_id}/tree/main"if space_idelse (os.getenv("AGENT_CODE_URL")or f"[https://huggingface.co/spaces/](https://huggingface.co/spaces/){username.strip()}/Final_Assignment_Template/tree/main").strip())print(agent_code)5 unmodified linesresponse.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}", None25 unmodified linesprint("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)49 unmodified lines"""**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:**29 unmodified linesif 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/](https://huggingface.co/spaces/){space_id_startup}")print(f" Repo Tree URL: [https://huggingface.co/spaces/](https://huggingface.co/spaces/){space_id_startup}/tree/main")else:print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
app.py+44-45