Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files1755 unmodified lines1756175717581759176017611762604 unmodified lines23672368236923702371237223732374237523762377237835 unmodified lines241424152416241724182419242020 unmodified lines2441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825391755 unmodified linesdef _trim_messages(raw_msgs):if not isinstance(raw_msgs, list):return raw_msgsselected = ([raw_msgs[0]] + raw_msgs[-3:]) if len(raw_msgs) > 4 else list(raw_msgs)out = []for m in selected:m_copy = copy.copy(m)604 unmodified linesmodel = self._build_model(self.model_id)exact_match_rule = (f"Write Python inside {code_open_tag} and {code_close_tag} only. No 'Thought:' or markdown fences. ""Use only provided tools and allowed Python modules; never use subprocess/os.system/open() or import tools. ""Never name variables 'log' or 'print'. Keep code fast (<15s), no nested network loops. ""If inspect_youtube returns 'Transcript/Video Analysis Status: unavailable', switch immediately to web_search or search_wikipedia. ""If Task ID has an attachment, use download_task_file, read_local_file, inspect_image, or transcribe_audio. ""Call final_answer(value) with ONLY the plain answer value (number, date, name, short phrase, or comma-separated list) — no units, no sentences, no dict, no 'FINAL ANSWER'.")accepted_params = set(sig.parameters) | set(inspect.signature(MultiStepAgent.__init__).parameters)35 unmodified lines],"instructions": exact_match_rule,"code_block_tags": (code_open_tag, code_close_tag),"max_steps": 6,"verbosity_level": 0,}20 unmodified linesprint("CodeAgent initialized with LiteLLMModel.")def _clean_exact_match_answer(self, text: str) -> str:import reif text is None:return ""cleaned = str(text).strip()if not cleaned or cleaned.startswith("AGENT ERROR:"):return cleanedcleaned = re.sub(r"</?code[^>]*>", "", cleaned, flags=re.IGNORECASE).strip()fa_call = re.fullmatch(r"final_answer\(\s*(?:answer\s*=\s*)?(.*?)\s*\)",cleaned,flags=re.DOTALL,)if fa_call:cleaned = fa_call.group(1).strip()if cleaned.startswith("```") and cleaned.endswith("```"):lines = cleaned.splitlines()if len(lines) >= 3:cleaned = "\n".join(lines[1:-1]).strip()else:cleaned = cleaned.strip("`").strip()lines = [ln.strip() for ln in cleaned.splitlines() if ln.strip()]if len(lines) > 1:for ln in reversed(lines):m_final = re.match(r"^(?:\*\*)?(?:final\s+answer|answer|result|output)(?:\*\*)?\s*:\s*(.+)$",ln,flags=re.IGNORECASE,)if m_final:cleaned = m_final.group(1).strip()breakelse:cleaned = lines[-1]prefix_match = re.match(r"^(?:\*\*)?(?:final\s+answer|the\s+final\s+answer\s+is|the\s+answer\s+is|answer|result|output)(?:\*\*)?\s*:?\s+(.+)$",cleaned,flags=re.IGNORECASE,)had_prefix = Falseif prefix_match:cleaned = prefix_match.group(1).strip()had_prefix = Truetrailing_bold = re.search(r"\*\*([^*]+?)\*\*[.!?]?\s*$", cleaned)if trailing_bold:candidate = trailing_bold.group(1).strip()prefix_part = cleaned[: trailing_bold.start()].strip().lower()if (candidateand len(candidate) <= 120and (not prefix_partor prefix_part.startswith(("according to", "based on", "under ", "in ", "from ", "the ", "this ", "it is", "it was")))):cleaned = candidatehad_prefix = Trueif len(cleaned) >= 2 and ((cleaned.startswith("**") and cleaned.endswith("**"))or (cleaned.startswith("__") and cleaned.endswith("__"))or (cleaned.startswith("`") and cleaned.endswith("`"))or (cleaned.startswith('"') and cleaned.endswith('"'))or (cleaned.startswith("'") and cleaned.endswith("'"))):cleaned = cleaned[2:-2].strip() if cleaned.startswith(("**", "__")) else cleaned[1:-1].strip()num_only = re.fullmatch(r"(?:there\s+(?:are|is)\s+|a\s+total\s+of\s+|total\s*:\s*)?(\d+)(?:\s+(?:studio\s+albums?|albums?|bird\s+species|species|items?))?[.!]?",cleaned.strip(),flags=re.IGNORECASE,)if num_only:return num_only.group(1)if had_prefix and cleaned.endswith(".") and not re.search(r"\b(?:Mr|Mrs|Ms|Dr|St|Jr|Sr|Inc|Ltd|vs|etc)\.$", cleaned):cleaned = cleaned[:-1].strip()if re.match(r"^(?:title|channel|transcript|description|duration|views|url|source|file\s*path|status|error|no\s+transcript)\s*:",cleaned,flags=re.IGNORECASE,):return ""return cleaneddef __call__(self, question: str, task_id: str = "", file_name: str = "") -> str:import time1755 unmodified lines1756175717581759176017611762176317641765604 unmodified lines23702371237223732374237523762377237835 unmodified lines241424152416241724182419242020 unmodified lines244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125021755 unmodified linesdef _trim_messages(raw_msgs):if not isinstance(raw_msgs, list):return raw_msgsif len(raw_msgs) > 4:selected = [raw_msgs[0]] + raw_msgs[-2:]else:selected = raw_msgsout = []for m in selected:m_copy = copy.copy(m)604 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, no 'final answer' prefix. ""For numbers, omit commas (1500 not 1,500).")accepted_params = set(sig.parameters) | set(inspect.signature(MultiStepAgent.__init__).parameters)35 unmodified lines],"instructions": exact_match_rule,"code_block_tags": (code_open_tag, code_close_tag),"max_steps": 4,"verbosity_level": 0,}20 unmodified linesprint("CodeAgent initialized with LiteLLMModel.")def _clean_exact_match_answer(self, text: str) -> str:import re, jsonif text is None:return ""cleaned = str(text).strip()if not cleaned or cleaned.startswith("AGENT ERROR:"):return cleaned# 1. usuń tagi code i markdowncleaned = re.sub(r"</?code[^>]*>", "", cleaned, flags=re.IGNORECASE)cleaned = re.sub(r"^```(?:\w+)?\s*|\s*```$", "", cleaned.strip(), flags=re.MULTILINE).strip()# 2. final_answer(...) → wartośćfa = re.fullmatch(r"final_answer\s*\(\s*(?:answer\s*=\s*)?(.*?)\s*\)", cleaned, flags=re.DOTALL)if fa:inner = fa.group(1).strip()if (inner.startswith('"') and inner.endswith('"')) or (inner.startswith("'") and inner.endswith("'")):try:cleaned = json.loads(inner) if inner.startswith('"') else inner[1:-1]except Exception:cleaned = inner.strip("\"'")else:cleaned = inner# 3. jedna linia = odpowiedź; wiele linii = ostatnia niepustalines = [ln.strip() for ln in cleaned.splitlines() if ln.strip()]if len(lines) > 1:for ln in reversed(lines):m = re.match(r"^(?:\*\*)?(?:final\s+answer|answer|result)\s*:?\s*(.+)$", ln, re.IGNORECASE)if m:cleaned = m.group(1).strip()breakelse:cleaned = lines[-1]elif lines:cleaned = lines[0]else:return ""# 4. zdejmij otaczające cudzysłowy / bold / backtickif len(cleaned) >= 2 and ((cleaned[0] == cleaned[-1] and cleaned[0] in "\"'`")or (cleaned.startswith("**") and cleaned.endswith("**"))or (cleaned.startswith("__") and cleaned.endswith("__"))):cleaned = cleaned.strip("\"'`").strip("*_").strip()# 5. liczby: usuń separatory tysięcy, zostaw kropkę dziesiętnąif re.fullmatch(r"-?\d{1,3}(?:,\d{3})+(?:\.\d+)?", cleaned):cleaned = cleaned.replace(",", "")# 6. usuń końcową kropkę (poza skrótami)if cleaned.endswith(".") and not re.search(r"\b(?:Mr|Mrs|Ms|Dr|St|Jr|Sr|Inc|Ltd|vs|etc)\.$", cleaned):cleaned = cleaned[:-1].strip()return cleaneddef __call__(self, question: str, task_id: str = "", file_name: str = "") -> str:import time
app.py+58-95