Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files732 unmodified lines7337347357367377387397407417427437447457467477487497507517527537547557561006 unmodified lines17631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791193 unmodified lines19851986198719881989199025 unmodified lines201620172018201920202021202215 unmodified lines2038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089456 unmodified lines254625472548254925502551255225532554255525562557255825592560256154 unmodified lines2616261726182619262026212622262369 unmodified lines26932694269526962697269826992700270127022703270494 unmodified lines27992800280128022803280428058 unmodified lines281428152816281728182819282044 unmodified lines28652866286728682869287027 unmodified lines289828992900290129022903290426 unmodified lines29312932293329342935293610 unmodified lines294729482949295029512952732 unmodified lineselse:text = ""if len(text) > 4800:# Najpierw spróbuj znaleźć sekcję Discography i zwróć ją priorytetowodisc_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_sectionelse: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] = outputreturn outputexcept Exception as e:return f"Wikipedia error for '{query}': {str(e)}"1006 unmodified lineslitellm.num_retries = 0t0 = time.monotonic()def _trim_messages(raw_msgs):if not isinstance(raw_msgs, list):return raw_msgsif len(raw_msgs) > 6:selected = [raw_msgs[0]] + raw_msgs[-4:]else:selected = raw_msgsout = []for m in selected: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:]else:content = getattr(m_copy, "content", None)if isinstance(content, str) and len(content) > 3200:try:setattr(m_copy,"content",content[:1500] + "\n...[trimmed]...\n" + content[-1500:],)except Exception:passout.append(m_copy)193 unmodified linesreturn f"{prefix}\n{final_snippet}".strip() if prefix else final_snippetreturn clean_codedef _extract_valid_python(raw: str) -> str:converted = _convert_xml_tool_calls(raw)if converted is not None:25 unmodified linesand isinstance(tree.body[0].value, (ast.Name, ast.Constant))):continuereturn _ensure_final_answer_call(_guard_unbound_lines(candidate))except SyntaxError:continue15 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@classmethoddef _validate_message(cls, msg):import json456 unmodified linesmodel = 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. ""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, ""and call `final_answer(...)` as soon as you have the exact value.")allowed_funcs = {54 unmodified linesif llm_err is not None:raise llm_errobs = getattr(step_log, "observations", None)if isinstance(obs, str) and len(obs) > 4500:step_log.observations = obs[:2200] + "\n...[trimmed]...\n" + obs[-2200:]local_kwargs = dict(agent_kwargs)local_kwargs["model"] = model_instance69 unmodified linescleaned = 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(94 unmodified linesif task_id:prefetched_path = ""if hasattr(self, "_download_task_file"):for _attempt in range(2):try:res_path = self._download_task_file(task_id=task_id,8 unmodified linesbreakexcept Exception as dl_exc:print(f"[DOWNLOAD WARN] task_id={task_id} attempt={_attempt + 1}: {dl_exc}", flush=True)if not clean_file_name:breaktime.sleep(1.0)44 unmodified lines)else:tool_hint = f"Call read_local_file(file_path='{prefetched_path}') immediately."read_fn = getattr(self, "_read_local_file", None) or tools_map.get("read_local_file")if read_fn is not None:try:27 unmodified linesif 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, "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.")blocked_models = set(self._dead_models)blocked_providers = set()10 unmodified linesmodels_to_try = [m for m in all_candidates if m not in self._dead_models] or all_candidatesbackoff_rounds = 0while time.monotonic() < deadline:rate_limited_models = set()rate_limited_providers = set()732 unmodified lines7337347357367377387397407417427437447457467477487497507517527537547557567577581006 unmodified lines1765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810193 unmodified lines2004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202925 unmodified lines205520562057205820592060206115 unmodified lines207720782079208020812082456 unmodified lines253925402541254225432544254525462547254825492550255125522553255425552556255754 unmodified lines2612261326142615261626172618261969 unmodified lines26892690269126922693269426952696269726982699270027012702270394 unmodified lines27982799280028012802280328048 unmodified lines281328142815281628172818281944 unmodified lines28642865286628672868286928702871287228732874287527 unmodified lines2903290429052906290729082909291026 unmodified lines2937293829392940294129422943294429452946294729482949295029512952295310 unmodified lines2964296529662967296829692970732 unmodified lineselse:text = ""body_text = re.split(r"(?im)^(?:references|external links|further reading|notes)\s*$",text,maxsplit=1,)[0].strip() or textif 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_sectionelse:text = body_text[:4200] + "\n...\n" + body_text[-4200:]else:text = body_textexcept Exception as e:return f"Wikipedia error for '{query}': {str(e)}"1006 unmodified lineslitellm.num_retries = 0t0 = time.monotonic()def _trim_text_val(val: str, max_len: int) -> str:if len(val) <= max_len:return valhalf_len = max_len // 2return val[:half_len] + "\n...[trimmed]...\n" + val[-half_len:]def _trim_messages(raw_msgs):if not isinstance(raw_msgs, list):return raw_msgsif len(raw_msgs) > 8:selected = raw_msgs[:2] + raw_msgs[-6:]else:selected = raw_msgsout = []for idx, m in enumerate(selected):max_len = 14000 if idx < 2 else 8500m_copy = copy.copy(m)if isinstance(m_copy, dict):content = m_copy.get("content")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_partselse:content = getattr(m_copy, "content", None)if isinstance(content, str) and len(content) > max_len:try:setattr(m_copy, "content", _trim_text_val(content, max_len))except Exception:passout.append(m_copy)193 unmodified linesreturn f"{prefix}\n{final_snippet}".strip() if prefix else final_snippetreturn clean_codedef _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_codetry:tree = ast.parse(clean_code)except SyntaxError:return clean_codeif not tree.body:return clean_codelast_node = tree.body[-1]if (isinstance(last_node, ast.Assign)and len(last_node.targets) == 1and isinstance(last_node.targets[0], ast.Name)):var_name = last_node.targets[0].idreturn f"{clean_code}\nprint({var_name})"return clean_codedef _extract_valid_python(raw: str) -> str:converted = _convert_xml_tool_calls(raw)if converted is not None:25 unmodified linesand isinstance(tree.body[0].value, (ast.Name, ast.Constant))):continuereturn _ensure_observable_output(_guard_unbound_lines(candidate))except SyntaxError:continue15 unmodified lines'the code block calling a tool or final_answer(...).")')@classmethoddef _validate_message(cls, msg):import json456 unmodified linesmodel = self._build_model(self.model_id)exact_match_rule = (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, ""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, 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 linesif llm_err is not None:raise llm_errobs = getattr(step_log, "observations", None)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 linescleaned = fa_call.group(2).strip()raw_code_pattern = re.compile(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|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.search(cleaned):return ""arrow_match = re.search(94 unmodified linesif task_id:prefetched_path = ""if hasattr(self, "_download_task_file"):for _attempt in range(3):try:res_path = self._download_task_file(task_id=task_id,8 unmodified linesbreakexcept Exception as dl_exc:print(f"[DOWNLOAD WARN] task_id={task_id} attempt={_attempt + 1}: {dl_exc}", flush=True)if not clean_file_name and _attempt >= 1:breaktime.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 linesif clean_file_name:prompt += f" (expected attachment filename: '{clean_file_name}')"prompt += (". 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_lowerfor 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 linesmodels_to_try = [m for m in all_candidates if m not in self._dead_models] or all_candidatesbackoff_rounds = 0while time.monotonic() < deadline:rate_limited_models = set()rate_limited_providers = set()
app.py+110-92