Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files908 unmodified lines9099109119129139149159161092 unmodified lines20092010201120122013201420152016201720182019202020212022202320242025202620272028179 unmodified lines220822092210221122122213221422152216221722182219222022212222222322242225222622272228222917 unmodified lines2247224822492250225122522253225422552256269 unmodified lines25262527252825292530253125322533102 unmodified lines2636263726382639264026412642264326442645264626472648264926502651265226532654265521 unmodified lines26772678267926802681268226832684268526862687268826892690269126922693109 unmodified lines280328042805280628072808280936 unmodified lines28462847284828492850285183 unmodified lines293529362937293829392940193 unmodified lines31343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162107 unmodified lines327032713272327332743275327632773278327932803281328232833284328532863287908 unmodified lines"openrouter/google/gemma-3-27b-it:free",])if self.provider_keys.get("nvidia_nim"):candidate_models.extend(["nvidia_nim/nvidia/nemotron-3-ultra-550b-a55b","nvidia_nim/moonshotai/kimi-k2.5",])1092 unmodified linescontinuetry:tree = ast.parse(candidate)if (len(tree.body) == 1and isinstance(tree.body[0], ast.Expr)and isinstance(tree.body[0].value, ast.Name)):ident = tree.body[0].value.idreturn f"final_answer({json.dumps(ident, ensure_ascii=False)})"return _ensure_final_answer_call(_guard_unbound_lines(candidate))except SyntaxError:continueplain = "\n".join(src_lines).strip()if plain and len(plain) <= 250 and "\n" not in plain:return f"final_answer({json.dumps(plain, ensure_ascii=False)})"return _ensure_final_answer_call(_guard_unbound_lines(plain))converted_top = _convert_xml_tool_calls(text)if converted_top is not None:179 unmodified lines)if fa_matches and fa_matches[-1].strip():ans_val = fa_matches[-1].strip()else:non_empty_lines = [ln.strip().strip("*`\"'")for ln in reasoning_str.splitlines()if ln.strip()]ans_val = non_empty_lines[-1] if non_empty_lines else ""if not ans_val:raise RuntimeError("Error in generating model output: reasoning-only response without code block or final_answer()")content_str = (f"{cls.open_tag}\n"f"final_answer({json.dumps(ans_val, ensure_ascii=False)})\n"f"{cls.close_tag}")if not content_str:print(17 unmodified linesf"final_answer({json.dumps(ans_val, ensure_ascii=False)})\n"f"{cls.close_tag}")elif len(cleaned.strip()) <= 250 and "\n" not in cleaned.strip():cleaned = (f"{cls.open_tag}\n"f"final_answer({json.dumps(cleaned.strip(), ensure_ascii=False)})\n"f"{cls.close_tag}")269 unmodified linesexact_match_rule = (f"Answer ONLY with the exact value (number, short phrase, or comma-separated list) inside {code_open_tag}...{code_close_tag}. ""No explanations, no units, no sentences, no 'final answer' prefix, and never output only one numbered item. ""Evaluate every single item in the provided list and include ALL matching items in the exact requested order and separator. ""For numbers, omit commas (1500 not 1,500). ""In Python code, always define every variable before using it (never reference undefined variables like `lines`), ""do not import `requests` or `posixpath`, use `read_local_file(file_path=...)` instead of `open(...)` for local files, "102 unmodified linescleaned = re.sub(r"(?im)^\s*(?:#\s*)?(?:thought|reasoning|plan)\s*:.*$", "", cleaned).strip()if cleaned.startswith("final_answer(") and cleaned.endswith(")"):inner_fa = cleaned[len("final_answer("):-1].strip()inner_fa = re.sub(r"^answer\s*=\s*", "", inner_fa).strip()cleaned = inner_faelse:fa_call = re.search(r"final_answer\s*\(\s*(?:answer\s*=\s*)?"r"(?:(['\"])(.*?)\1|([^()]*?))"r"\s*\)",cleaned,flags=re.DOTALL,)if fa_call:cleaned = (fa_call.group(2) or fa_call.group(3) or "").strip()arrow_match = re.search(r"\b(?:answer|result|output|final\s+answer)\s*->\s*(.+)$",21 unmodified linesr"^(?:the wikipedia article|the youtube video|the search results show|this scene is from|"r"the page is quite long|the task doesn't have|the download failed|let me try|let me search|"r"let me check|now i need to find|i found the|the operation is not commutative|"r"the scene occurs|i need to|i should|i will|i can)\b",re.IGNORECASE,)lines = [ln.strip() for ln in cleaned.splitlines() if ln.strip()]answer_line = next((ln for ln in reversed(lines) if not junk_pattern.match(ln)), "")if not answer_line:return ""cleaned = answer_line.strip("`").strip()if junk_pattern.match(cleaned):return ""if (109 unmodified linesprompt += ("\n\nIMPORTANT for image tasks: Extract ALL visible numbers, labels, and text first. ""For tables/charts, read row/column headers and data cells before answering. ""For chess positions, identify piece placement and whose turn it is. ""Do not describe the image generally—answer the specific question asked.")else:36 unmodified lines)prompt_lower = prompt.lower()if "table" in prompt_lower or "|*|" in prompt or "commutative" in prompt_lower:prompt += ("\n\nIMPORTANT: For table/operation tasks, write Python that builds a dict of dicts, "83 unmodified linescleaned = self._clean_exact_match_answer(raw_result)if cleaned and not cleaned.startswith("AGENT ERROR:"):return cleanedlast_step = getattr(getattr(run_agent, "memory", None), "steps", None)if last_step:for st in reversed(last_step):193 unmodified linespassself._task_deadline = Nonelast_non_empty_steps = Nonelast_agent = locals().get("run_agent")last_steps = getattr(getattr(last_agent, "memory", None), "steps", None)if last_steps:last_non_empty_steps = last_stepsif last_non_empty_steps:for st in reversed(last_non_empty_steps):cand_val = getattr(st, "action_output", None)if cand_val is None:continuefallback_clean = self._clean_exact_match_answer(str(cand_val))if (fallback_cleanand not fallback_clean.startswith(("AGENT ERROR:", "Error ", "No attachment", "No web results", "No Wikipedia"))and len(fallback_clean) <= 600):return " ".join(fallback_clean.splitlines()).strip()return ""def _trim_tool_output(text: str, max_chars: int = 4000) -> str:if not isinstance(text, str):return str(text)107 unmodified linesc_tid = c_item.get("Task ID")c_q = c_item.get("Question")c_ans = c_item.get("Submitted Answer")if (isinstance(c_ans, str)and c_ans.strip()and not c_ans.strip().startswith("AGENT ERROR:")and "</code>" not in c_ans.lower()and "without access to" not in c_ans.lower()):clean_cached = c_ans.strip()if isinstance(c_tid, str) and c_tid.strip():cached_by_task_id[c_tid.strip()] = clean_cachedif isinstance(c_q, str) and c_q.strip():cached_by_question[c_q.strip()] = clean_cachedexcept Exception:cached_by_task_id = {}cached_by_question = {}908 unmodified lines9099109119129139149151092 unmodified lines20082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036179 unmodified lines2216221722182219222022212222222322242225222622272228222922302231223217 unmodified lines2250225122522253225422552256225722582259269 unmodified lines25292530253125322533253425352536253725382539102 unmodified lines264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268721 unmodified lines27092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731109 unmodified lines2841284228432844284528462847284836 unmodified lines288528862887288828892890289128922893289428952896289783 unmodified lines29812982298329842985298629872988193 unmodified lines31823183318431853186318731883189107 unmodified lines32973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319908 unmodified lines"openrouter/google/gemma-3-27b-it:free",])if self.provider_keys.get("nvidia_nim"):vision_candidates.extend(["nvidia_nim/moonshotai/kimi-k2.5",])1092 unmodified linescontinuetry:tree = ast.parse(candidate)if not tree.body:continueif (len(tree.body) == 1and isinstance(tree.body[0], ast.Expr)and isinstance(tree.body[0].value, (ast.Name, ast.Constant))):continuereturn _ensure_final_answer_call(_guard_unbound_lines(candidate))except SyntaxError:continueplain = "\n".join(src_lines).strip()fa_match = re.findall(r"(?im)^\s*(?:final\s*answer|answer)\s*:\s*(.+)$",plain,)if fa_match and fa_match[-1].strip():return f"final_answer({json.dumps(fa_match[-1].strip(), ensure_ascii=False)})"return (f'print("Invalid non-code output. Write valid Python code inside 'f'{open_t}...{close_t} calling a tool or final_answer(...).")')converted_top = _convert_xml_tool_calls(text)if converted_top is not None:179 unmodified lines)if fa_matches and fa_matches[-1].strip():ans_val = fa_matches[-1].strip()content_str = (f"{cls.open_tag}\n"f"final_answer({json.dumps(ans_val, ensure_ascii=False)})\n"f"{cls.close_tag}")else:content_str = (f"{cls.open_tag}\n"f'print("No Python code block produced. Write valid Python code inside {cls.open_tag}...{cls.close_tag} to call a tool or final_answer(...).")\n'f"{cls.close_tag}")if not content_str:print(17 unmodified linesf"final_answer({json.dumps(ans_val, ensure_ascii=False)})\n"f"{cls.close_tag}")else:cleaned = (f"{cls.open_tag}\n"f'print("Invalid non-code output. Write valid Python code inside {cls.open_tag}...{cls.close_tag} to call a tool or final_answer(...).")\n'f"{cls.close_tag}")269 unmodified linesexact_match_rule = (f"Answer ONLY with the exact value (number, short phrase, or comma-separated list) inside {code_open_tag}...{code_close_tag}. ""No explanations, no units, no sentences, and no 'final answer' prefix. ""Match the exact requested granularity: if the question asks for a single item, person, first name, or surname, ""output ONLY that single field (e.g., only the first name if asked for 'first name', never both first and last name or multiple people). ""Output a comma-separated list ONLY when multiple items are requested, evaluating every item in the provided list in the requested order. ""For chess moves, output ONLY Standard Algebraic Notation (SAN, e.g., Rd5, Nf6+, O-O) without move numbers or commentary. ""For numbers, omit commas (1500 not 1,500). ""In Python code, always define every variable before using it (never reference undefined variables like `lines`), ""do not import `requests` or `posixpath`, use `read_local_file(file_path=...)` instead of `open(...)` for local files, "102 unmodified linescleaned = re.sub(r"(?im)^\s*(?:#\s*)?(?:thought|reasoning|plan)\s*:.*$", "", cleaned).strip()tech_error_pattern = re.compile(r"(?:invalid non-code output|no python code block produced|"r"reached max steps|max steps reached|error in generating|error in execution|"r"task time budget exhausted|traceback \(most recent call last\)|"r"transcript/video analysis status:\s*unavailable)",re.IGNORECASE,)if tech_error_pattern.search(cleaned):return ""if cleaned.startswith("final_answer(") and cleaned.endswith(")"):inner_fa = cleaned[len("final_answer("):-1].strip()inner_fa = re.sub(r"^answer\s*=\s*", "", inner_fa).strip()try:lit_val = ast.literal_eval(inner_fa)if isinstance(lit_val, (list, tuple)):cleaned = ", ".join(str(item).strip() for item in lit_val if str(item).strip())elif isinstance(lit_val, (str, int, float, bool)):cleaned = str(lit_val).strip()else:return ""except Exception:return ""else:fa_call = re.search(r"final_answer\s*\(\s*(?:answer\s*=\s*)?(['\"])(.*?)\1\s*\)",cleaned,flags=re.DOTALL,)if fa_call:cleaned = fa_call.group(2).strip()raw_code_pattern = re.compile(r"^(?:print|final_answer|web_search|search_wikipedia|fetch_url_text|"r"download_task_file|read_local_file|inspect_image|inspect_youtube|"r"transcribe_audio|ask_web)\s*\(|^(?:import|from|def|class|for|while|try)\b",re.IGNORECASE,)if raw_code_pattern.match(cleaned):return ""arrow_match = re.search(r"\b(?:answer|result|output|final\s+answer)\s*->\s*(.+)$",21 unmodified linesr"^(?:the wikipedia article|the youtube video|the search results show|this scene is from|"r"the page is quite long|the task doesn't have|the download failed|let me try|let me search|"r"let me check|now i need to find|i found the|the operation is not commutative|"r"the scene occurs|i need to|i should|i will|i can|"r"no attachment|no web results|no wikipedia|file not found|image file not found|"r"audio file not found|error fetching|error downloading|error reading|"r"error inspecting|error transcribing)\b",re.IGNORECASE,)lines = [ln.strip() for ln in cleaned.splitlines() if ln.strip()]answer_line = next((ln for ln in reversed(lines) if not junk_pattern.match(ln) and not raw_code_pattern.match(ln)),"",)if not answer_line:return ""cleaned = answer_line.strip("`").strip()if junk_pattern.match(cleaned) or raw_code_pattern.match(cleaned) or tech_error_pattern.search(cleaned):return ""if (109 unmodified linesprompt += ("\n\nIMPORTANT for image tasks: Extract ALL visible numbers, labels, and text first. ""For tables/charts, read row/column headers and data cells before answering. ""For chess positions, verify board orientation (a1-h8 coordinates, White vs Black at bottom), ""list exact piece squares and side to move, and answer ONLY with the move in Standard Algebraic Notation (SAN). ""Do not describe the image generally—answer the specific question asked.")else:36 unmodified lines)prompt_lower = prompt.lower()if "chess" in prompt_lower or "algebraic notation" in prompt_lower:prompt += ("\n\nIMPORTANT for chess tasks: First call inspect_image (if an image is attached) to read the exact ""board orientation (files a-h, ranks 1-8) and every piece square. Verify legality and tactical outcome, ""then output ONLY the single move in Standard Algebraic Notation (SAN, e.g. Rd5, Nf6+, O-O) ""without move numbers (no '1.' or '1...') or commentary.")if "table" in prompt_lower or "|*|" in prompt or "commutative" in prompt_lower:prompt += ("\n\nIMPORTANT: For table/operation tasks, write Python that builds a dict of dicts, "83 unmodified linescleaned = self._clean_exact_match_answer(raw_result)if cleaned and not cleaned.startswith("AGENT ERROR:"):return cleanedblocked_models.add(model_name)breaklast_step = getattr(getattr(run_agent, "memory", None), "steps", None)if last_step:for st in reversed(last_step):193 unmodified linespassself._task_deadline = Nonereturn ""def _trim_tool_output(text: str, max_chars: int = 4000) -> str:if not isinstance(text, str):return str(text)107 unmodified linesc_tid = c_item.get("Task ID")c_q = c_item.get("Question")c_ans = c_item.get("Submitted Answer")if not isinstance(c_ans, str):continueraw_cached = c_ans.strip()if (not raw_cachedor raw_cached.startswith("AGENT ERROR:")or "</code>" in raw_cached.lower()or "without access to" in raw_cached.lower()):continueclean_cached = agent._clean_exact_match_answer(raw_cached)if not clean_cached or clean_cached.startswith("AGENT ERROR:"):continueif isinstance(c_tid, str) and c_tid.strip():cached_by_task_id[c_tid.strip()] = clean_cachedif isinstance(c_q, str) and c_q.strip():cached_by_question[c_q.strip()] = clean_cachedexcept Exception:cached_by_task_id = {}cached_by_question = {}
app.py+98-66