Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files908 unmodified lines9099109119129139129139149151092 unmodified lines20082009201020112012201320142015201520162017201720182018201920202021202220232023202420252024202520262027202820292030203120322033203420352036179 unmodified lines221622172218221922202221222222232224221222132214221522162217221822192220222522262227222822292222222322242225222622302231223217 unmodified lines225022512252225022532254225522532256225722582259269 unmodified lines2529253025312529253025322533253425352536253725382539102 unmodified lines26422643264426452646264726482649265026512652265326542655265626572642265826592660266126622663266426652666266726682669264526462647267026712672267326742652267526762677267826792680268126822683268426852686268721 unmodified lines27092710271126802712271327142715271627172718271926852720272127222723272427252726272726902728272927302731109 unmodified lines28412842284328062844284528462847284836 unmodified lines288528862887288828892890289128922893289428952896289783 unmodified lines29812982298329842985298629872988193 unmodified lines31823183318431373138313931403141314231433144314531463147314831493150315131523153315431553156318531863159318731883189107 unmodified lines329732983299330033013302330332743275327632773278330433053306330733083309331033113280328132823283328433123313331433153316331733183319908 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", vision_candidates.extend([ "nvidia_nim/moonshotai/kimi-k2.5", ])
1092 unmodified lines continue try: tree = ast.parse(candidate) if not tree.body: continue if ( len(tree.body) == 1 and isinstance(tree.body[0], ast.Expr) and isinstance(tree.body[0].value, ast.Name) and isinstance(tree.body[0].value, (ast.Name, ast.Constant)) ): ident = tree.body[0].value.id return f"final_answer({json.dumps(ident, ensure_ascii=False)})" continue return _ensure_final_answer_call(_guard_unbound_lines(candidate)) except SyntaxError: continue
plain = "\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)) 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: 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'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}" ) 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 lines f"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(): else: cleaned = ( f"{cls.open_tag}\n" f"final_answer({json.dumps(cleaned.strip(), ensure_ascii=False)})\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 lines
exact_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. " "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 lines
cleaned = 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() cleaned = inner_fa 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*)?" r"(?:(['\"])(.*?)\1|([^()]*?))" r"\s*\)", r"final_answer\s*\(\s*(?:answer\s*=\s*)?(['\"])(.*?)\1\s*\)", cleaned, flags=re.DOTALL, ) if fa_call: cleaned = (fa_call.group(2) or fa_call.group(3) or "").strip() 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 lines r"^(?: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", 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)), "") 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): if junk_pattern.match(cleaned) or raw_code_pattern.match(cleaned) or tech_error_pattern.search(cleaned): return ""
if (109 unmodified lines prompt += ( "\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. " "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 lines cleaned = self._clean_exact_match_answer(raw_result) if cleaned and not cleaned.startswith("AGENT ERROR:"): return cleaned blocked_models.add(model_name) break last_step = getattr(getattr(run_agent, "memory", None), "steps", None) if last_step: for st in reversed(last_step):193 unmodified lines pass self._task_deadline = None
last_non_empty_steps = None last_agent = locals().get("run_agent") last_steps = getattr(getattr(last_agent, "memory", None), "steps", None) if last_steps: last_non_empty_steps = last_steps if last_non_empty_steps: for st in reversed(last_non_empty_steps): cand_val = getattr(st, "action_output", None) if cand_val is None: continue fallback_clean = self._clean_exact_match_answer(str(cand_val)) if ( fallback_clean and 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 lines c_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): continue raw_cached = c_ans.strip() 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() not raw_cached or raw_cached.startswith("AGENT ERROR:") or "</code>" in raw_cached.lower() or "without access to" in raw_cached.lower() ): continue clean_cached = agent._clean_exact_match_answer(raw_cached) if not clean_cached or clean_cached.startswith("AGENT ERROR:"): clean_cached = c_ans.strip() if isinstance(c_tid, str) and c_tid.strip(): cached_by_task_id[c_tid.strip()] = clean_cached if isinstance(c_q, str) and c_q.strip(): cached_by_question[c_q.strip()] = clean_cached continue if isinstance(c_tid, str) and c_tid.strip(): cached_by_task_id[c_tid.strip()] = clean_cached if isinstance(c_q, str) and c_q.strip(): cached_by_question[c_q.strip()] = clean_cached except Exception: cached_by_task_id = {} cached_by_question = {}app.py+98-66