Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files26 unmodified lines27282930313233529 unmodified lines56356456556556656656756876 unmodified lines64564664764965064864965065165287 unmodified lines7407417427447437447457463 unmodified lines7507517527547557567537547557567577582 unmodified lines7617627637657647657667674 unmodified lines77277377477677777877977577677777877978078178278378178478578678724 unmodified lines8128138148128158168176 unmodified lines8248258268278288298308313 unmodified lines8358368378388398408419 unmodified lines85185285385485585685785814 unmodified lines87387487587687787887920 unmodified lines9009019028958969038979048999059069079083 unmodified lines91291391490991591691791891391491591691791992092192292192292392392492524 unmodified lines9509519529549539549559569579599589599619609619629632 unmodified lines96696796897096997097197211 unmodified lines9849859869889879889899909929919929939945 unmodified lines10001001100210041005100310041005100610071008100910111012101310101011101210131014101525 unmodified lines1041104210431045104410451046104749 unmodified lines10971098109911011102110311001101110211031104110529 unmodified lines113511361137113911401138113911401141114226 unmodified lines from smolagents import CodeAgent, LiteLLMModel, tool
litellm.drop_params = True litellm.request_timeout = 25 env_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 lines if 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 lines def _sanitize_code_tags(text: str) -> str: import re
cleaned_text = re.sub(r"</?code[^>]*>\s*```", "```", text, flags=re.IGNORECASE) cleaned_text = re.sub(r"```\s*</?code[^>]*>", "```", cleaned_text, flags=re.IGNORECASE) cleaned_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 lines
exact_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" "- 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." )
self.agent = CodeAgent( model=model, tools=[ agent_kwargs = { "model": model, "tools": [ web_search, search_wikipedia, fetch_url_text,2 unmodified lines inspect_image, transcribe_audio, ], additional_authorized_imports=[ "additional_authorized_imports": [ "json", "csv", "pandas",4 unmodified lines "fractions", "string", ], instructions=exact_match_rule, max_steps=14, verbosity_level=0, ) "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.")
@staticmethod def _clean_exact_match_answer(raw_answer) -> str: import re24 unmodified lines
return text
def __call__(self, question: str, task_id: str = "") -> str: import time from 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 lines is_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: 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: 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 = False
if models_to_try and (len(models_to_try) > 1 or models_to_try[0] != failed_model): if models_to_try: other_provider_models = [ m for m in models_to_try if m != failed_model and ( (m.split("/", 1)[0].lower() if "/" in m else "gemini") != current_provider ) if (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 lines if switched_provider or any(m in err_lower for m in fast_retry_markers): wait_sec = 2 else: wait_sec = 15 wait_sec = 10 print(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):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 lines space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
if profile: username= f"{profile.username}" username = f"{profile.username}" print(f"User logged in: {username}") else: print("User not logged in.")11 unmodified lines 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" f"[https://huggingface.co/spaces/](https://huggingface.co/spaces/){space_id}/tree/main" if space_id else ( os.getenv("AGENT_CODE_URL") or f"https://huggingface.co/spaces/{username.strip()}/Final_Assignment_Template/tree/main" or f"[https://huggingface.co/spaces/](https://huggingface.co/spaces/){username.strip()}/Final_Assignment_Template/tree/main" ).strip() ) print(agent_code)5 unmodified lines 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.", None print("Fetched questions list is empty.") return "Fetched questions list is empty or invalid format.", None print(f"Fetched {len(questions_data)} questions.") except requests.exceptions.RequestException as e: print(f"Error fetching questions: {e}") return f"Error fetching questions: {e}", None except 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}", None 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}", None except Exception as e: print(f"An unexpected error occurred fetching questions: {e}") return f"An unexpected error occurred fetching questions: {e}", None25 unmodified lines print("Agent did not produce any answers to submit.") return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
# 4. Prepare Submission # 4. Prepare Submission submission_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.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 lines
if space_id_startup: # Print repo URLs if SPACE_ID is found print(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") 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