Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files732 unmodified lines7337347357367377387397407417427367377387397407417427437447457467477487497507517527447457467477487497507517527537537547557567577581006 unmodified lines176517661767176817691770177117721773177417751776176917701777177817791780178117741782178317841785178617781779178717881789179017911792179317941795179617971798179918001801180218031804178218051806178417851786178717881807180818091810193 unmodified lines2004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202925 unmodified lines2055205620572019205820592060206115 unmodified lines2077207820792041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208020812082456 unmodified lines25392540254125492550254225432544254525462547254825522549255025542555255625572558255125522553255425552556255754 unmodified lines261226132614261926202615261626172618261969 unmodified lines268926902691269626922693269826992694269526962697269826992701270027012702270394 unmodified lines279827992800280228012802280328048 unmodified lines2813281428152817281628172818281944 unmodified lines28642865286628672868286928702871287228732874287527 unmodified lines29032904290529012906290729082909291026 unmodified lines2937293829392940294129422943294429452946294729482949295029512952295310 unmodified lines2964296529662967296829692970732 unmodified lines else: text = ""
if len(text) > 4800: # Najpierw spróbuj znaleźć sekcję Discography i zwróć ją priorytetowo disc_match = re.search(r"(?i)\bdiscography\b", text) if disc_match: start = max(0, disc_match.start() - 200) disc_section = text[start:start + 4000] text = text[:800] + "\n...\n" + disc_section body_text = re.split( r"(?im)^(?:references|external links|further reading|notes)\s*$", text, maxsplit=1, )[0].strip() or text
if len(body_text) > 8500: section_match = re.search( r"(?i)\b(?:discography|studio albums|participating national olympic committees|" r"participating nations|recipients|laureates|winners|medal table)\b", body_text, ) if section_match: start = max(0, section_match.start() - 250) focus_section = body_text[start:start + 6800] text = body_text[:1400] + "\n...\n" + focus_section else: text = text[:2400] + "\n...\n" + text[-2400:]
header_info = f"Title: {resolved_title}" if rev_id: header_info += f" (revid: {rev_id}, pre-2023)" if other_titles: header_info += f"\nOther matching pages: {', '.join(other_titles)}" output = f"{header_info}\n\n{text}" if text else f"{header_info}\n\nEmpty article text." wiki_cache[cache_key] = output return output text = body_text[:4200] + "\n...\n" + body_text[-4200:] else: text = body_text except Exception as e: return f"Wikipedia error for '{query}': {str(e)}"
1006 unmodified lines litellm.num_retries = 0 t0 = time.monotonic()
def _trim_text_val(val: str, max_len: int) -> str: if len(val) <= max_len: return val half_len = max_len // 2 return val[:half_len] + "\n...[trimmed]...\n" + val[-half_len:]
def _trim_messages(raw_msgs): if not isinstance(raw_msgs, list): return raw_msgs if len(raw_msgs) > 6: selected = [raw_msgs[0]] + raw_msgs[-4:] if len(raw_msgs) > 8: selected = raw_msgs[:2] + raw_msgs[-6:] else: selected = raw_msgs out = [] for m in selected: for idx, m in enumerate(selected): max_len = 14000 if idx < 2 else 8500 m_copy = copy.copy(m) if isinstance(m_copy, dict): content = m_copy.get("content") if isinstance(content, str) and len(content) > 3200: m_copy["content"] = content[:1500] + "\n...[trimmed]...\n" + content[-1500:] if isinstance(content, str) and len(content) > max_len: m_copy["content"] = _trim_text_val(content, max_len) elif isinstance(content, list): new_parts = [] for part in content: if ( isinstance(part, dict) and isinstance(part.get("text"), str) and len(part["text"]) > max_len ): part_copy = dict(part) part_copy["text"] = _trim_text_val(part["text"], max_len) new_parts.append(part_copy) else: new_parts.append(part) m_copy["content"] = new_parts else: content = getattr(m_copy, "content", None) if isinstance(content, str) and len(content) > 3200: if isinstance(content, str) and len(content) > max_len: try: setattr( m_copy, "content", content[:1500] + "\n...[trimmed]...\n" + content[-1500:], ) setattr(m_copy, "content", _trim_text_val(content, max_len)) except Exception: pass out.append(m_copy)193 unmodified lines return f"{prefix}\n{final_snippet}".strip() if prefix else final_snippet return clean_code def _ensure_observable_output(code_str: str) -> str: clean_code = (code_str or "").strip() if not clean_code or "final_answer(" in clean_code: return clean_code try: tree = ast.parse(clean_code) except SyntaxError: return clean_code if not tree.body: return clean_code last_node = tree.body[-1] if ( isinstance(last_node, ast.Assign) and len(last_node.targets) == 1 and isinstance(last_node.targets[0], ast.Name) ): var_name = last_node.targets[0].id return f"{clean_code}\nprint({var_name})" return clean_code
def _extract_valid_python(raw: str) -> str: converted = _convert_xml_tool_calls(raw) if converted is not None:25 unmodified lines and isinstance(tree.body[0].value, (ast.Name, ast.Constant)) ): continue return _ensure_final_answer_call(_guard_unbound_lines(candidate)) return _ensure_observable_output(_guard_unbound_lines(candidate)) except SyntaxError: continue
15 unmodified lines 'the code block calling a tool or final_answer(...).")' )
converted_top = _convert_xml_tool_calls(text) if converted_top is not None: return f"{open_t}\n{_extract_valid_python(converted_top)}\n{close_t}"
cleaned_text = re.sub(r"<\|[^|]+\|>", "", text) cleaned_text = re.sub(r"</?code[^>]*>\s*```", "<code>\n", cleaned_text, flags=re.IGNORECASE) cleaned_text = re.sub(r"```\s*</?code[^>]*>", "\n</code>", cleaned_text, flags=re.IGNORECASE)
html_match = re.search(r"<code>(.*?)</code>", cleaned_text, flags=re.DOTALL | re.IGNORECASE) if html_match: inner = re.sub(r"```(?:py|python)?\s*\n?|\n?```|</?code[^>]*>", "", html_match.group(1), flags=re.IGNORECASE) return f"{open_t}\n{_extract_valid_python(inner)}\n{close_t}"
md_match = re.search( r"```(?:py|python)?\s*\n(.*?)```", cleaned_text, flags=re.DOTALL | re.IGNORECASE, ) if md_match: inner = re.sub(r"</?code[^>]*>", "", md_match.group(1), flags=re.IGNORECASE) return f"{open_t}\n{_extract_valid_python(inner)}\n{close_t}"
stripped_orphan_tags = re.sub(r"</?code[^>]*>", "", cleaned_text, flags=re.IGNORECASE).strip() if stripped_orphan_tags != cleaned_text.strip() and stripped_orphan_tags: extracted_orphan = _extract_valid_python(stripped_orphan_tags) try: ast.parse(extracted_orphan) return f"{open_t}\n{extracted_orphan}\n{close_t}" except SyntaxError: if len(stripped_orphan_tags) <= 300 and "\n" not in stripped_orphan_tags: return ( f"{open_t}\n" f"final_answer({json.dumps(stripped_orphan_tags, ensure_ascii=False)})\n" f"{close_t}" )
if "final_answer(" in cleaned_text: extracted = _extract_valid_python(cleaned_text) if "final_answer(" in extracted: return f"{open_t}\n{extracted}\n{close_t}"
extracted_main = _extract_valid_python(cleaned_text) if extracted_main: return f"{open_t}\n{extracted_main}\n{close_t}" return cleaned_text
@classmethod def _validate_message(cls, msg): import json456 unmodified lines model = self._build_model(self.model_id)
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, and no 'final answer' prefix. " f"Write ONLY valid, executable Python code inside {code_open_tag}...{code_close_tag} at every step. " "In intermediate steps, always call print(...) on tool outputs (e.g., `res = search_wikipedia(...); print(res)`) " "so you can read the result in the next step—never end a step with a bare assignment without print(...). " "When you have the final result, call `final_answer(exact_value)` inside the code block, where `exact_value` is ONLY " "the exact requested value (number, short phrase, or comma-separated list) with 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). " "pass 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, " "and call `final_answer(...)` as soon as you have the exact value." "For chess moves, pass ONLY Standard Algebraic Notation (SAN, e.g., 'Rd5', 'Nf6+', 'O-O') without move numbers or commentary. " "For numbers, omit commas ('1500' not '1,500'). " "Always define every variable before using it (never reference undefined variables like `lines`), " "do not import `requests` or `posixpath`, and use `read_local_file(file_path=...)` instead of `open(...)` for local files." )
allowed_funcs = {54 unmodified lines if llm_err is not None: raise llm_err obs = getattr(step_log, "observations", None) if isinstance(obs, str) and len(obs) > 4500: step_log.observations = obs[:2200] + "\n...[trimmed]...\n" + obs[-2200:] if isinstance(obs, str) and len(obs) > 9000: step_log.observations = obs[:4400] + "\n...[trimmed]...\n" + obs[-4400:]
local_kwargs = dict(agent_kwargs) local_kwargs["model"] = model_instance69 unmodified lines cleaned = fa_call.group(2).strip()
raw_code_pattern = re.compile( r"^(?:print|final_answer|web_search|search_wikipedia|fetch_url_text|" r"(?:^|\b)(?: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, r"transcribe_audio|ask_web|final_answer)\s*\(|" r"^\s*print\s*\(|" r"^\s*[A-Za-z_][A-Za-z0-9_]*\s*=\s*[A-Za-z_][A-Za-z0-9_.]*\s*\(|" r"^\s*(?:import|from|def|class|for|while|try|if|elif|else|with|return|raise)\b", re.IGNORECASE | re.MULTILINE, ) if raw_code_pattern.match(cleaned): if raw_code_pattern.search(cleaned): return ""
arrow_match = re.search(94 unmodified lines if task_id: prefetched_path = "" if hasattr(self, "_download_task_file"): for _attempt in range(2): for _attempt in range(3): try: res_path = self._download_task_file( task_id=task_id,8 unmodified lines break except Exception as dl_exc: print(f"[DOWNLOAD WARN] task_id={task_id} attempt={_attempt + 1}: {dl_exc}", flush=True) if not clean_file_name: if not clean_file_name and _attempt >= 1: break time.sleep(1.0)
44 unmodified lines ) else: tool_hint = f"Call read_local_file(file_path='{prefetched_path}') immediately." if ext in {".xlsx", ".xlsm", ".xls", ".csv"}: prompt += ( f"\n\nTask ID: {task_id}. The tabular attachment is saved at '{prefetched_path}'. " f"Use pandas (`pd.read_excel('{prefetched_path}', sheet_name=None)` or `pd.read_csv('{prefetched_path}')`) " "to inspect exact sheet names, columns, and compute exact totals/filters." ) read_fn = getattr(self, "_read_local_file", None) or tools_map.get("read_local_file") if read_fn is not None: try:27 unmodified lines if clean_file_name: prompt += f" (expected attachment filename: '{clean_file_name}')" prompt += ( ". If this task refers to an attached file, image, spreadsheet, audio, or document, " ". NEVER list or inspect the current working directory ('.' or repo files like app.py/README.md). " "If this task refers to an attached file, spreadsheet, image, audio, or document, " f"call download_task_file(task_id='{task_id}', preferred_filename='{clean_file_name}') first." )
26 unmodified lines "If the table is not visible in the provided text, call search_wikipedia again with " "the exact article title + ' discography' to get the full section." ) if any( k in prompt_lower for k in ("first name", "last name", "surname", "ioc", "country code", "recipient", "only ") ): prompt += ( "\n\nIMPORTANT for multi-condition & single-field questions: " "Do NOT return a list of candidates before verifying all constraints. " "Check each candidate's attributes via search_wikipedia/web_search, filter down to the single matching entity, " "and extract ONLY the exact requested sub-field (e.g., if 'first name' is asked, output only the given/first name, " "never the full name or a list of names; if 'IOC country code' is asked, verify the exact table numbers first and output only the 3-letter code)." )
blocked_models = set(self._dead_models) blocked_providers = set()10 unmodified lines models_to_try = [m for m in all_candidates if m not in self._dead_models] or all_candidates
backoff_rounds = 0
while time.monotonic() < deadline: rate_limited_models = set() rate_limited_providers = set()app.py+110-92