Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files736 unmodified lines73773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525493 unmodified lines301930203021302230233024302513 unmodified lines3039304030413042304330443045736 unmodified lines except Exception as e: return f"Error inspecting image '{image_path}': {str(e)}"
@tool def inspect_youtube(url: str) -> str: """Fetches YouTube video title, author, description, and available captions/transcripts for a given YouTube URL or video ID. Args: url: YouTube video URL or 11-character video ID. """ import re from html import unescape
raw = (url or "").strip() vid_match = re.search( r"(?:v=|/shorts/|/embed/|youtu\.be/)([A-Za-z0-9_-]{11})", raw, ) video_id = vid_match.group(1) if vid_match else (raw if re.fullmatch(r"[A-Za-z0-9_-]{11}", raw) else "") if not video_id: return f"Invalid YouTube URL or video ID: '{url}'"
watch_url = f"https://www.youtube.com/watch?v={video_id}" headers = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36", "Accept-Language": "en-US,en;q=0.9", } sections = [f"Video ID: {video_id}", f"URL: {watch_url}"]
try: oembed_resp = requests.get( "https://www.youtube.com/oembed", params={"url": watch_url, "format": "json"}, headers=headers, timeout=20, ) if oembed_resp.status_code == 200: oembed = oembed_resp.json() if oembed.get("title"): sections.append(f"Title: {oembed['title']}") if oembed.get("author_name"): sections.append(f"Channel: {oembed['author_name']}") except Exception: pass
try: page_resp = requests.get(watch_url, headers=headers, timeout=25) if page_resp.status_code == 200: html_text = page_resp.text desc_match = re.search(r'"shortDescription"\s*:\s*"((?:\\.|[^"\\])*)"', html_text) if desc_match: try: desc_val = desc_match.group(1).encode("utf-8").decode("unicode_escape") except Exception: desc_val = unescape(desc_match.group(1)) sections.append(f"Description:\n{desc_val[:2000]}")
cap_match = re.search(r'"captionTracks"\s*:\s*(\[[^\]]*\])', html_text) if cap_match: import json
try: tracks = json.loads(cap_match.group(1)) for tr in tracks[:3]: base_url = tr.get("baseUrl") if not base_url: continue tr_resp = requests.get(unescape(base_url), headers=headers, timeout=20) if tr_resp.status_code == 200 and tr_resp.text: raw_cues = re.findall(r"(?is)<text[^>]*>(.*?)</text>", tr_resp.text) cues = [ re.sub(r"\s+", " ", unescape(re.sub(r"(?s)<[^>]+>", " ", c))).strip() for c in raw_cues ] transcript = " ".join(c for c in cues if c) if transcript: lang = tr.get("languageCode", "unknown") sections.append(f"Transcript ({lang}):\n{transcript[:8000]}") break except Exception: pass except Exception as e: sections.append(f"Page fetch note: {e}")
return "\n\n".join(sections) @tool def transcribe_audio( audio_path: str, question: str = "Transcribe all spoken words verbatim and answer any question about the audio.", ) -> str: """Transcribes or analyzes a local audio file (.mp3, .wav, .m4a, .ogg) using available audio/multimodal models. Args: audio_path: Local path to the downloaded audio file. question: Specific transcription or analysis instruction for the audio. """ try: if not os.path.isfile(audio_path): return f"Audio file not found: '{audio_path}'" ext = os.path.splitext(audio_path)[1].lower().lstrip(".") mime_map = { "mp3": "audio/mp3", "wav": "audio/wav", "m4a": "audio/mp4", "ogg": "audio/ogg", "flac": "audio/flac", } mime_type = mime_map.get(ext, "audio/mp3")
while True: groq_key = self._get_api_key("groq/whisper-large-v3-turbo") if not groq_key: break try: with open(audio_path, "rb") as audio_f: groq_resp = requests.post( "https://api.groq.com/openai/v1/audio/transcriptions", headers={"Authorization": f"Bearer {groq_key}"}, files={"file": (os.path.basename(audio_path), audio_f, mime_type)}, data={"model": "whisper-large-v3-turbo", "response_format": "text"}, timeout=45, ) if groq_resp.status_code == 200: transcript = groq_resp.text.strip() if transcript: return transcript break err_body = groq_resp.text.lower() if groq_resp.status_code in (401, 402, 403) or "quota" in err_body: if hasattr(self, "_rotate_api_key") and self._rotate_api_key("groq"): continue break if groq_resp.status_code == 429: groq_pool = self.provider_key_pools.get("groq") or [] if ( hasattr(self, "_rotate_api_key") and self._provider_key_idx.get("groq", 0) + 1 < len(groq_pool) and self._rotate_api_key("groq") ): continue break except Exception: break
with open(audio_path, "rb") as f: b64_data = base64.b64encode(f.read()).decode("utf-8") data_uri = f"data:{mime_type};base64,{b64_data}"
audio_models = [] if "gemini/" in getattr(self, "model_id", ""): audio_models.append(self.model_id) if self.provider_keys.get("gemini"): audio_models.extend( self.gemini_flash_models or [ "gemini/gemini-2.5-flash-lite", "gemini/gemini-2.5-flash", ] ) audio_models = list(dict.fromkeys(audio_models))
last_err = None while True: rate_limited_gemini = False for a_model in audio_models: while True: a_key = self._get_api_key(a_model) if not a_key: break key_failed_hard = False for part in ( {"type": "image_url", "image_url": {"url": data_uri}}, {"type": "file", "file": {"file_data": data_uri}}, ): try: response = litellm.completion( model=a_model, api_key=a_key, messages=[ { "role": "user", "content": [ {"type": "text", "text": question}, part, ], } ], max_tokens=2048, timeout=45, ) out = (response.choices[0].message.content or "").strip() if out: return out except Exception as exc: last_err = exc err_low = str(exc).lower() if any( marker in err_low for marker in ( "401", "402", "403", "authentication", "missing authentication header", "insufficient permissions", "does not have sufficient permissions", "quota", "resource_exhausted", ) ): key_failed_hard = True break if any(marker in err_low for marker in ("429", "rate limit exceeded")): rate_limited_gemini = True key_failed_hard = True break if key_failed_hard: if not rate_limited_gemini and hasattr(self, "_rotate_api_key") and self._rotate_api_key("gemini"): continue break break
gemini_pool = self.provider_key_pools.get("gemini") or [] if ( rate_limited_gemini and hasattr(self, "_rotate_api_key") and self._provider_key_idx.get("gemini", 0) + 1 < len(gemini_pool) and self._rotate_api_key("gemini") ): continue break
raise RuntimeError(str(last_err) if last_err else "No audio transcription model available.") except Exception as e: return f"Error transcribing audio '{audio_path}': {str(e)}"
candidate_models = [] priority_openrouter_models = [ "openrouter/openrouter/free", "openrouter/google/gemma-4-26b-a4b-it:free", "openrouter/google/gemma-4-31b-it:free", "openrouter/nvidia/nemotron-3-nano-30b-a3b:free", "openrouter/qwen/qwen3-next-80b-a3b-instruct:free", "openrouter/meta-llama/llama-3.3-70b-instruct:free", "openrouter/google/gemma-3-27b-it:free", "openrouter/liquid/lfm-2.5-2.6b:free", ]
if self.provider_keys.get("openrouter"): live_free_models = set() try: or_resp = requests.get( "https://openrouter.ai/api/v1/models", timeout=15, headers={"User-Agent": "HF-Agents-Course-Bot/1.0"}, ) if or_resp.status_code == 200: for item in or_resp.json().get("data", []): m_id = str(item.get("id", "")).strip() if m_id == "openrouter/free" or m_id.endswith(":free"): live_free_models.add(f"openrouter/{m_id}") except Exception as or_exc: print(f"Warning: could not list OpenRouter models: {or_exc}")
if live_free_models: curated_live = [m for m in priority_openrouter_models if m in live_free_models] extra_live = sorted( m for m in live_free_models if m not in curated_live and not any(bad in m.lower() for bad in ("embed", "whisper", "tts", "audio", "image")) )[:6] candidate_models.extend(curated_live or ["openrouter/openrouter/free"]) candidate_models.extend(extra_live) else: candidate_models.extend(priority_openrouter_models)
if self.provider_keys.get("gemini"): available_api_models = set() for g_key in self.provider_key_pools.get("gemini") or [gemini_key]: if not g_key: continue try: models_resp = requests.get( "https://generativelanguage.googleapis.com/v1beta/models", params={"key": g_key}, timeout=45, ) if models_resp.status_code == 200: for m in models_resp.json().get("models", []): if "generateContent" in m.get("supportedGenerationMethods", []): raw_name = m.get("name", "") if raw_name.startswith("models/"): available_api_models.add("gemini/" + raw_name[len("models/"):]) if available_api_models: break except Exception as list_exc: print(f"Warning: could not list Gemini models via REST: {list_exc}")
if available_api_models: fallback_gemini_flash = [ "gemini/gemini-2.5-flash-lite", "gemini/gemini-2.5-flash", ] discovered_flash = sorted( ( m for m in available_api_models if "flash" in m.lower() and not any( bad in m.lower() for bad in ("tts", "image", "embedding", "aqa", "audio", "exp", "thinking") ) ), key=lambda name: ( 0 if "lite" in name.lower() else 1, 1 if "preview" in name.lower() or "latest" in name.lower() else 0, name, ), ) self.gemini_flash_models = ( discovered_flash or [m for m in fallback_gemini_flash if m in available_api_models] or sorted(available_api_models)[:3] ) candidate_models.extend(self.gemini_flash_models) else: self.gemini_flash_models = [ "gemini/gemini-2.5-flash-lite", "gemini/gemini-2.5-flash", ] candidate_models.extend(self.gemini_flash_models)
if self.provider_keys.get("groq"): candidate_models.extend([ "groq/openai/gpt-oss-120b", "groq/openai/gpt-oss-20b", ])
if self.provider_keys.get("huggingface"): candidate_models.extend([ "huggingface/Qwen/Qwen2.5-72B-Instruct", "huggingface/meta-llama/Llama-3.1-8B-Instruct", ])
priority_rank = {name: idx for idx, name in enumerate(priority_openrouter_models)}
def _model_priority(model_name: str) -> tuple[int, int, int, str]: provider = model_name.split("/", 1)[0].lower() if "/" in model_name else "gemini" low = model_name.lower() if provider == "gemini": group = 0 sub_rank = 0 if "flash-lite" in low else 1 elif provider == "groq": group = 1 sub_rank = 0 if "20b" in low else 1 elif provider == "openrouter": group = 2 sub_rank = priority_rank.get(model_name, len(priority_rank)) else: group = 3 sub_rank = 0 if "8b" in low else 1 key_missing = 0 if self._get_api_key(model_name) else 1 return (key_missing, group, sub_rank, model_name)
self.working_models = sorted( dict.fromkeys(candidate_models), key=_model_priority, )
if not self.working_models: raise RuntimeError("No models available for the configured API keys.")
class SafeLiteLLMModel(LiteLLMModel): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._explicit_api_key = kwargs.get("api_key")
@staticmethod def _sanitize_code_tags(text: str) -> str: import ast import re
def _extract_valid_python(raw: str) -> str: lines = [] for line in raw.splitlines(): stripped = line.lstrip() if re.match(r"^(?:thoughts?|thinking)\s*:", stripped, flags=re.IGNORECASE): lines.append("# " + stripped) else: lines.append(line)
n = len(lines) for start in range(n): if not lines[start].strip(): continue for end in range(n, start, -1): candidate = "\n".join(lines[start:end]).strip() if not candidate: continue try: ast.parse(candidate) return candidate except SyntaxError: continue return "\n".join(lines).strip()
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 = html_match.group(1) inner = re.sub(r"```(?:py|python)?\s*\n?", "", inner, flags=re.IGNORECASE) inner = re.sub(r"\n?```", "", inner) inner = re.sub(r"</?code[^>]*>", "", inner, flags=re.IGNORECASE) return f"<code>\n{_extract_valid_python(inner)}\n</code>"
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"<code>\n{_extract_valid_python(inner)}\n</code>"
stripped_orphan_tags = re.sub(r"</?code[^>]*>", "", cleaned_text, flags=re.IGNORECASE).strip() if stripped_orphan_tags != cleaned_text.strip() and stripped_orphan_tags: return f"<code>\n{_extract_valid_python(stripped_orphan_tags)}\n</code>"
return cleaned_text
@classmethod def _validate_message(cls, msg): import json import re
if msg is None: raise RuntimeError( "Error in generating model output: empty model response (content=None)" )
raw_content = getattr(msg, "content", None) if isinstance(raw_content, list): text_parts = [] for part in raw_content: if isinstance(part, dict): if part.get("type") in ("text", "output_text", None) and part.get("text"): text_parts.append(str(part["text"])) else: p_type = getattr(part, "type", None) p_text = getattr(part, "text", None) if p_text and p_type in ("text", "output_text", None): text_parts.append(str(p_text)) content_str = "\n".join(text_parts).strip() elif raw_content is None: content_str = "" else: content_str = str(raw_content).strip()
reasoning = ( getattr(msg, "reasoning_content", None) or getattr(msg, "reasoning", None) or "" ) reasoning_str = str(reasoning).strip() if reasoning else "" tool_calls = getattr(msg, "tool_calls", None)
if not content_str and tool_calls: rendered_calls = [] for tc in tool_calls: fn_obj = getattr(tc, "function", None) if fn_obj is None and isinstance(tc, dict): fn_obj = tc.get("function") fn_name = getattr(fn_obj, "name", None) if fn_obj is not None else None if fn_name is None and isinstance(fn_obj, dict): fn_name = fn_obj.get("name") fn_args = getattr(fn_obj, "arguments", None) if fn_obj is not None else None if fn_args is None and isinstance(fn_obj, dict): fn_args = fn_obj.get("arguments") if not fn_name: continue if isinstance(fn_args, str): try: parsed_args = json.loads(fn_args) if fn_args.strip() else {} except Exception: parsed_args = {"query": fn_args} else: parsed_args = fn_args or {} if isinstance(parsed_args, dict): rendered_calls.append( f"print({fn_name}(**{json.dumps(parsed_args, ensure_ascii=False)}))" ) if rendered_calls: content_str = "<code>\n" + "\n".join(rendered_calls) + "\n</code>"
if not content_str and reasoning_str: code_match = re.search( r"(<code>.*?</code>|```(?:py|python)?\s*\n.*?```)", reasoning_str, flags=re.DOTALL | re.IGNORECASE, ) if code_match: content_str = code_match.group(1).strip() else: first_line = reasoning_str.splitlines()[0].replace('"', "'") content_str = f'<code>\nprint(ask_web("{first_line[:120]}")) # fallback from reasoning\n</code>'
if not content_str: raise RuntimeError( "Error in generating model output: empty model response (content=None)" )
cleaned = cls._sanitize_code_tags(content_str) if not cleaned.strip(): raise RuntimeError( "Error in generating model output: empty model response after sanitization" )
try: msg.content = cleaned except Exception: pass return msg
def _prepare_call_kwargs(self, kwargs: dict) -> dict: key = getattr(self, "_explicit_api_key", None) or kwargs.pop("api_key", None) model_name = str(getattr(self, "model_id", "") or "") if key: if model_name.startswith("openrouter/"): os.environ["OPENROUTER_API_KEY"] = key elif model_name.startswith("groq/"): os.environ["GROQ_API_KEY"] = key elif model_name.startswith("huggingface/"): os.environ["HF_TOKEN"] = key os.environ["HUGGINGFACE_API_KEY"] = key elif model_name.startswith("gemini/"): os.environ["GEMINI_API_KEY"] = key os.environ["GOOGLE_API_KEY"] = key kwargs.setdefault("timeout", 30) if model_name.startswith("openrouter/"): kwargs["max_tokens"] = 4096 return kwargs
if hasattr(LiteLLMModel, "generate"): def generate(self, *args, **kwargs): kwargs = self._prepare_call_kwargs(dict(kwargs)) return self._validate_message(super().generate(*args, **kwargs)) else: def __call__(self, *args, **kwargs): kwargs = self._prepare_call_kwargs(dict(kwargs)) return self._validate_message(super().__call__(*args, **kwargs))
self._model_cls = SafeLiteLLMModel self.model_id = self.working_models[0] print(f"Using primary LLM model: {self.model_id} (fallbacks: {self.working_models[1:]})")
def _build_model(model_name: str): is_openrouter = model_name.startswith("openrouter/") kwargs = { "model_id": model_name, "api_key": self._get_api_key(model_name), "max_tokens": 2048 if is_openrouter else 8192, "num_retries": 0, "timeout": 30, } if model_name.startswith("gemini/"): kwargs["reasoning_effort"] = "low" elif model_name.startswith("groq/"): kwargs["tool_choice"] = "auto" kwargs["parallel_tool_calls"] = False model_instance = self._model_cls(**kwargs) if model_name.startswith("groq/"): for attr_name in ("kwargs", "completion_kwargs", "model_kwargs"): target_dict = getattr(model_instance, attr_name, None) if isinstance(target_dict, dict): target_dict["tool_choice"] = "auto" return model_instance
self._build_model = _build_model model = self._build_model(self.model_id)
exact_match_rule = ( "CRITICAL OUTPUT RULES FOR EXACT MATCH EVALUATION:\n" "- Always write valid Python code inside <code> and </code> tags. NEVER put 'Thought:' or ``` fences inside the code block.\n" "- If the prompt includes a Task ID and mentions an image, board, diagram, or attached file, FIRST call path = download_task_file(task_id=...) and inspect it.\n" "- Never call built-in open(); use read_local_file(file_path) for text/PDF/ZIP/spreadsheet files, " "inspect_image(image_path, question) for images, and transcribe_audio(audio_path, question) for audio files (.mp3, .wav).\n" "- If web_search returns no results, use search_wikipedia(query) or fetch_url_text(url).\n" "- Return ONLY the concise exact answer value itself " "(e.g. a number, date, name, or short phrase) via final_answer().\n" "- NEVER include introductory text, explanations, markdown formatting, or the phrase 'FINAL ANSWER'.\n" "- Do not wrap the answer in a dictionary like {'answer': ...}; pass the plain answer string directly." )
agent_kwargs = { "model": model, "tools": [ web_search, search_wikipedia, ask_web, fetch_url_text, download_task_file, read_local_file, inspect_image, inspect_youtube, transcribe_audio, ], "additional_authorized_imports": [ "json", "csv", "pandas", "numpy", "urllib", "html", "decimal", "fractions", "string", "re", "time", ], "instructions": exact_match_rule, "code_block_tags": ("<code>", "</code>"), "max_steps": 10, "verbosity_level": 0, } sig = inspect.signature(CodeAgent.__init__) filtered_agent_kwargs = {k: v for k, v in agent_kwargs.items() if k in sig.parameters} self.agent = CodeAgent(**filtered_agent_kwargs) print("CodeAgent initialized with LiteLLMModel.")
@staticmethod def _clean_exact_match_answer(raw_answer) -> str: import re
if raw_answer is None: return "" if isinstance(raw_answer, (list, tuple)): text = ", ".join(str(item).strip() for item in raw_answer if str(item).strip()) else: text = str(raw_answer).strip()
if not text or text.startswith("AGENT ERROR:"): return text
text = re.sub(r"^```(?:[a-zA-Z0-9_-]+)?\s*\n?", "", text) text = re.sub(r"\n?```\s*$", "", text).strip()
text = re.sub(r"(?im)^\s*(final\s*answer|answer)\s*:\s*", "", text).strip() lines = [line.strip() for line in text.splitlines() if line.strip()] if lines: text = lines[-1]
if len(text) >= 2 and ((text[0] == '"' and text[-1] == '"') or (text[0] == "'" and text[-1] == "'")): text = text[1:-1].strip()
if len(text) > 1 and text.endswith(".") and not re.search(r"(?:\d|\b[A-Za-z]\.[A-Za-z])\.$", text): text = text[:-1].strip()
return text
def __call__(self, question: str, task_id: str = "") -> str: prompt = question.strip() if task_id: prompt += ( f"\n\nTask ID: {task_id}. If the question references an attached file " f"or image, use download_task_file(task_id='{task_id}') to inspect it." )
blocked_models = getattr(self, "_blocked_models", None) if blocked_models is None: blocked_models = set() self._blocked_models = blocked_models
blocked_providers = getattr(self, "_blocked_providers", None) if blocked_providers is None: blocked_providers = set() self._blocked_providers = blocked_providers
models_to_try = list(getattr(self, "working_models", []) or [self.model_id]) if self.model_id and self.model_id not in models_to_try: models_to_try.append(self.model_id)
while True: rate_limited_models = set() rate_limited_providers = set()
for model_name in models_to_try: if not hasattr(self, "_build_model") or not hasattr(self, "agent"): return "AGENT ERROR: Agent not initialized." provider = model_name.split("/", 1)[0].lower() if "/" in model_name else "gemini" while True: if ( model_name in blocked_models or model_name in rate_limited_models or provider in blocked_providers ): break if not self._get_api_key(model_name): blocked_providers.add(provider) break try: self.model_id = model_name self.agent.model = self._build_model(model_name) result = self.agent.run(prompt) cleaned = self._clean_exact_match_answer("" if result is None else str(result).strip()) if cleaned and not cleaned.startswith("AGENT ERROR:"): return cleaned blocked_models.add(model_name) break except Exception as exc: err_text = str(exc) err_lower = err_text.lower() print(f"[AGENT ERROR] task_id={task_id} model={model_name}: {err_text}") if any( marker in err_lower for marker in ( "401", "402", "403", "authentication", "missing authentication header", "insufficient permissions", "does not have sufficient permissions", "free-models-per-day", "quota", "resource_exhausted", ) ): if hasattr(self, "_rotate_api_key") and self._rotate_api_key(provider): continue blocked_providers.add(provider) blocked_models.add(model_name) break if any(marker in err_lower for marker in ("429", "rate limit exceeded")): rate_limited_models.add(model_name) rate_limited_providers.add(provider) break if any( marker in err_lower for marker in ( "400", "404", "not a valid model id", "no endpoints found", "provider returned error", "context length", "empty model response", "unavailable for free", ) ): blocked_models.add(model_name) break break
rotated_any = False if hasattr(self, "_rotate_api_key"): for prov in rate_limited_providers: if prov not in blocked_providers: pool = self.provider_key_pools.get(prov) or [] if self._provider_key_idx.get(prov, 0) + 1 < len(pool): if self._rotate_api_key(prov): rotated_any = True if not rotated_any: break
return "AGENT ERROR: All candidate models failed."
def run_and_submit_all(profile: gr.OAuthProfile | None): """ Fetches all questions, runs the BasicAgent on them, submits all answers, and displays the results. """ # --- Determine HF Space Runtime URL and Repo URL --- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
if profile: username = f"{profile.username}" print(f"User logged in: {username}") else: print("User not logged in.") return "Please Login to Hugging Face with the button.", None
api_url = DEFAULT_API_URL questions_url = f"{api_url}/questions" submit_url = f"{api_url}/submit"
# 1. Instantiate Agent ( modify this part to create your agent) try: agent = BasicAgent() except Exception as e: print(f"Error instantiating agent: {e}") return f"Error initializing agent: {e}", None # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public) agent_code = ( f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else ( os.getenv("AGENT_CODE_URL") or f"https://huggingface.co/spaces/{username.strip()}/Final_Assignment_Template/tree/main" ).strip() ) print(agent_code)
# 2. Fetch Questions print(f"Fetching questions from: {questions_url}") try: response = requests.get(questions_url, timeout=45) response.raise_for_status() questions_data = response.json() if not questions_data: print("Fetched questions list is empty.") return "Fetched questions list is empty or invalid format.", None print(f"Fetched {len(questions_data)} questions.") except requests.exceptions.RequestException as e: print(f"Error fetching questions: {e}") return f"Error fetching questions: {e}", None except requests.exceptions.JSONDecodeError as e: print(f"Error decoding JSON response from questions endpoint: {e}") print(f"Response text: {response.text[:500]}") return f"Error decoding server response for questions: {e}", None except Exception as e: print(f"An unexpected error occurred fetching questions: {e}") return f"An unexpected error occurred fetching questions: {e}", None
# 3. Run your Agent from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutError import json import time
results_log = [] answers_payload = [] partial_path = "/tmp/gaia_partial_results.json" cached_by_question = {} try: if os.path.isfile(partial_path): with open(partial_path, "r", encoding="utf-8") as f_cache: cached_items = json.load(f_cache) if isinstance(cached_items, list): for c_item in cached_items: if not isinstance(c_item, dict): continue c_q = c_item.get("Question") c_ans = c_item.get("Submitted Answer") if ( isinstance(c_q, str) and isinstance(c_ans, str) and c_ans.strip() and not c_ans.strip().startswith("AGENT ERROR:") ): cached_by_question[c_q] = c_ans.strip() except Exception: cached_by_question = {}
print(f"Running agent on {len(questions_data)} questions...") for idx, item in enumerate(questions_data): task_id = item.get("task_id") question_text = item.get("question") if not task_id or question_text is None: print(f"Skipping item with missing task_id or question: {item}") continue if question_text in cached_by_question: submitted_answer = cached_by_question[question_text] else: if len(results_log) > 0: time.sleep(3) try: with ThreadPoolExecutor(max_workers=1) as executor: future = executor.submit(agent, question_text, task_id=task_id) submitted_answer = future.result(timeout=120) except FutureTimeoutError: print(f"Timeout running agent on task {task_id} after 120s.") submitted_answer = "AGENT ERROR: Task timed out after 120s." except Exception as e: print(f"Error running agent on task {task_id}: {e}") submitted_answer = f"AGENT ERROR: {e}"
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer}) results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer}) try: with open(partial_path, "w", encoding="utf-8") as f_part: json.dump(results_log, f_part, ensure_ascii=False, indent=2) except Exception: pass
# 4. Prepare Submission submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload} status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..." print(status_update)
# 5. Submit print(f"Submitting {len(answers_payload)} answers to: {submit_url}") try: response = requests.post(submit_url, json=submission_data, timeout=45) response.raise_for_status() result_data = response.json() final_status = ( f"Submission Successful!\n" f"User: {result_data.get('username')}\n" f"Overall Score: {result_data.get('score', 'N/A')}% " f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n" f"Message: {result_data.get('message', 'No message received.')}" ) print("Submission successful.") results_df = pd.DataFrame(results_log) return final_status, results_df except requests.exceptions.HTTPError as e: error_detail = f"Server responded with status {e.response.status_code}." try: error_json = e.response.json() error_detail += f" Detail: {error_json.get('detail', e.response.text)}" except requests.exceptions.JSONDecodeError: error_detail += f" Response: {e.response.text[:500]}" status_message = f"Submission Failed: {error_detail}" print(status_message) results_df = pd.DataFrame(results_log) return status_message, results_df except requests.exceptions.Timeout: status_message = "Submission Failed: The request timed out." print(status_message) results_df = pd.DataFrame(results_log) return status_message, results_df except requests.exceptions.RequestException as e: status_message = f"Submission Failed: Network error - {e}" print(status_message) results_df = pd.DataFrame(results_log) return status_message, results_df except Exception as e: status_message = f"An unexpected error occurred during submission: {e}" print(status_message) results_df = pd.DataFrame(results_log) return status_message, results_df
# --- Build Gradio Interface using Blocks ---with gr.Blocks() as demo: gr.Markdown("# Basic Agent Evaluation Runner") gr.Markdown( """ **Instructions:**
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
--- **Disclaimers:** Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions). This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async. """ )
gr.LoginButton()
run_button = gr.Button("Run Evaluation & Submit All Answers")
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False) # Removed max_rows=10 from DataFrame constructor results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
run_button.click( fn=run_and_submit_all, outputs=[status_output, results_table] )
import osimport gradio as grimport requestsimport inspectimport pandas as pd
try: import spaces
@spaces.GPU def _register_zerogpu(): return Noneexcept ImportError: pass
# (Keep Constants as is)# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
# --- Basic Agent Definition ---# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------class BasicAgent: def __init__(self): import re import base64 import mimetypes import litellm from smolagents import CodeAgent, LiteLLMModel, tool
litellm.drop_params = True litellm.request_timeout = 25
provider_env_prefixes = { "openrouter": ("OPENROUTER_API_KEY", "OPENROUTER_TOKEN", "OPENROUTER_KEY"), "gemini": ("GEMINI_API_KEY", "GOOGLE_API_KEY", "GEMINI_TOKEN", "GOOGLE_GEMINI_API_KEY"), "groq": ("GROQ_API_KEY", "GROQ_TOKEN"), "huggingface": ("HF_TOKEN", "HUGGINGFACE_API_KEY", "HUGGINGFACEHUB_API_TOKEN", "HUGGINGFACE_TOKEN"), } raw_pools = {p: [] for p in provider_env_prefixes}
def _classify_token(token: str, default_provider: str) -> str: if token.startswith("sk-or-"): return "openrouter" if token.startswith("AIza"): return "gemini" if token.startswith("gsk_"): return "groq" if token.startswith("hf_"): return "huggingface" return default_provider
for raw_name, raw_val in os.environ.items(): if not raw_val: continue env_name = raw_name.upper().strip() matched_provider = next( ( prov for prov, prefixes in provider_env_prefixes.items() if any(env_name == pref or env_name.startswith(pref + "_") for pref in prefixes) ), None, ) if not matched_provider: continue for part in re.split(r"[\s,;]+", raw_val): tok = part.strip(" '\"\n\r\t[]") if tok: target_prov = _classify_token(tok, matched_provider) raw_pools[target_prov].append(tok)
self.provider_key_pools = { prov: list(dict.fromkeys(tokens)) for prov, tokens in raw_pools.items() } self._provider_key_idx = {prov: 0 for prov in self.provider_key_pools}
openrouter_key = self.provider_key_pools["openrouter"][0] if self.provider_key_pools["openrouter"] else "" groq_key = self.provider_key_pools["groq"][0] if self.provider_key_pools["groq"] else "" hf_key = self.provider_key_pools["huggingface"][0] if self.provider_key_pools["huggingface"] else "" gemini_key = self.provider_key_pools["gemini"][0] if self.provider_key_pools["gemini"] else ""
self.provider_keys = { "openrouter": openrouter_key, "groq": groq_key, "huggingface": hf_key, "gemini": gemini_key, } if not any(self.provider_keys.values()): raise ValueError( "Missing API key in Space secrets. Add at least one of: " "OPENROUTER_API_KEY, GROQ_API_KEY, HF_TOKEN, or GEMINI_API_KEY." )
self.gemini_key = gemini_key if gemini_key: os.environ["GEMINI_API_KEY"] = gemini_key os.environ["GOOGLE_API_KEY"] = gemini_key if openrouter_key: os.environ["OPENROUTER_API_KEY"] = openrouter_key if groq_key: os.environ["GROQ_API_KEY"] = groq_key if hf_key: os.environ["HF_TOKEN"] = hf_key os.environ["HUGGINGFACE_API_KEY"] = hf_key
def _get_api_key(model_name: str) -> str | None: provider = model_name.split("/", 1)[0].lower() if "/" in model_name else "gemini" pool = self.provider_key_pools.get(provider) or [] idx = self._provider_key_idx.get(provider, 0) if idx < len(pool): key = pool[idx] self.provider_keys[provider] = key return key self.provider_keys[provider] = "" return None
def _rotate_api_key(provider: str) -> bool: pool = self.provider_key_pools.get(provider) or [] next_idx = self._provider_key_idx.get(provider, 0) + 1 self._provider_key_idx[provider] = next_idx if next_idx < len(pool): new_key = pool[next_idx] self.provider_keys[provider] = new_key if provider == "openrouter": os.environ["OPENROUTER_API_KEY"] = new_key elif provider == "groq": os.environ["GROQ_API_KEY"] = new_key elif provider == "huggingface": os.environ["HF_TOKEN"] = new_key os.environ["HUGGINGFACE_API_KEY"] = new_key elif provider == "gemini": self.gemini_key = new_key os.environ["GEMINI_API_KEY"] = new_key os.environ["GOOGLE_API_KEY"] = new_key return True self.provider_keys[provider] = "" return False
self._get_api_key = _get_api_key self._rotate_api_key = _rotate_api_key self.gemini_flash_models = []
@tool def fetch_url_text(url: str) -> str: """Fetches clean plain text from a given URL. Args: url: The HTTP/HTTPS URL to fetch. """ import re from html import unescape
try: response = requests.get( url, timeout=45, headers={"User-Agent": "Mozilla/5.0"}, ) response.raise_for_status() raw_html = re.sub( r"(?is)<(script|style|noscript|svg|header|footer|nav).*?>.*?</\1>", " ", response.text, ) plain_text = re.sub(r"(?s)<[^>]+>", " ", raw_html) cleaned = re.sub(r"\s+", " ", unescape(plain_text)).strip() if not cleaned: return "Empty text response." if len(cleaned) <= 24000: return cleaned return cleaned[:12000] + "\n...\n" + cleaned[-12000:] except Exception as e: return f"Error fetching URL '{url}': {str(e)}"
@tool def download_task_file(task_id: str, output_dir: str = "/tmp/gaia_files") -> str: """Downloads a task attachment from the course API by task_id and returns the local file path. Args: task_id: The GAIA task identifier. output_dir: Target directory where the downloaded file is saved. """ import re from urllib.parse import unquote
url = f"{DEFAULT_API_URL.rstrip('/')}/files/{task_id}" try: os.makedirs(output_dir, exist_ok=True) response = requests.get( url, timeout=30, headers={"User-Agent": "Mozilla/5.0"}, ) response.raise_for_status()
content_disp = response.headers.get("Content-Disposition", "") filename = ""
star_match = re.search( r"filename\*\s*=\s*(?:[A-Za-z0-9_-]+''|\"[A-Za-z0-9_-]+'')?([^\";]+)", content_disp, flags=re.IGNORECASE, ) if star_match: raw_star = star_match.group(1).strip().strip('"') if "''" in raw_star: raw_star = raw_star.split("''", 1)[1] filename = os.path.basename(unquote(raw_star))
if not filename: std_match = re.search( r'filename\s*=\s*"?([^";]+)"?', content_disp, flags=re.IGNORECASE, ) if std_match: filename = os.path.basename(unquote(std_match.group(1).strip()))
if not filename: content_type = response.headers.get("Content-Type", "").split(";")[0].strip().lower() ext_map = { "text/plain": ".txt", "text/csv": ".csv", "application/json": ".json", "application/pdf": ".pdf", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx", "application/vnd.ms-excel": ".xls", "image/png": ".png", "image/jpeg": ".jpg", "audio/mpeg": ".mp3", "audio/wav": ".wav", "text/x-python": ".py", } ext = ext_map.get(content_type) or mimetypes.guess_extension(content_type) or ".bin" filename = f"{task_id}{ext}"
file_path = os.path.join(output_dir, filename) with open(file_path, "wb") as f: f.write(response.content)
return file_path except Exception as e: return f"Error downloading file for task '{task_id}': {str(e)}"
@tool def read_local_file(file_path: str) -> str: """Reads text, PDF, ZIP archive, or spreadsheet content from a local file downloaded by download_task_file. Args: file_path: Local path to the downloaded file. """ import zipfile
def _read_single(path: str, max_chars: int) -> str: f_ext = os.path.splitext(path)[1].lower() if f_ext in {".xlsx", ".xls"}: sheets = pd.read_excel(path, sheet_name=None) if not sheets: return "Empty Excel workbook." text = "\n\n".join( f"=== Sheet: {s_name} ===\n{df.to_csv(index=False)}" for s_name, df in sheets.items() ) elif f_ext == ".pdf": try: from pypdf import PdfReader
reader = PdfReader(path) pages = [ f"=== Page {i + 1} ===\n{(p.extract_text() or '').strip()}" for i, p in enumerate(reader.pages) ] text = "\n\n".join(p for p in pages if p.strip()) or "Empty PDF text." except Exception as pdf_exc: return f"Error reading PDF '{path}': {str(pdf_exc)}" elif f_ext in {".png", ".jpg", ".jpeg", ".webp", ".gif"}: return f"Binary image file '{path}'. Use inspect_image(image_path='{path}', question=...)." elif f_ext in {".mp3", ".wav", ".m4a", ".ogg", ".flac"}: return f"Binary audio file '{path}'. Use transcribe_audio(audio_path='{path}', question=...)." else: with open(path, "r", encoding="utf-8", errors="replace") as f: text = f.read()
if len(text) <= max_chars: return text half = max_chars // 2 return text[:half] + "\n...\n" + text[-half:]
try: if not os.path.isfile(file_path): return f"File not found: '{file_path}'" ext = os.path.splitext(file_path)[1].lower() if ext == ".zip" or zipfile.is_zipfile(file_path): extract_dir = os.path.join( os.path.dirname(file_path), f"extracted_{os.path.basename(file_path)}", ) os.makedirs(extract_dir, exist_ok=True) base_extract = os.path.realpath(extract_dir) sections = [] with zipfile.ZipFile(file_path, "r") as zf: members = [m for m in zf.namelist() if not m.endswith("/")] sections.append( f"=== ZIP Archive ({len(members)} files) ===\nFiles: {', '.join(members)}" ) for member in members: target_path = os.path.realpath(os.path.join(extract_dir, member)) if not (target_path == base_extract or target_path.startswith(base_extract + os.sep)): sections.append(f"=== {member} ===\nSkipped unsafe path.") continue os.makedirs(os.path.dirname(target_path), exist_ok=True) with zf.open(member, "r") as src, open(target_path, "wb") as dst: dst.write(src.read()) try: content_str = _read_single(target_path, max_chars=24000) sections.append(f"=== {member} (extracted to {target_path}) ===\n{content_str}") except Exception as m_exc: sections.append(f"=== {member} (extracted to {target_path}) ===\nRead error: {m_exc}") joined_zip = "\n\n".join(sections) if len(joined_zip) <= 48000: return joined_zip return joined_zip[:24000] + "\n...\n" + joined_zip[-24000:]
return _read_single(file_path, max_chars=48000) except Exception as e: return f"Error reading file '{file_path}': {str(e)}"
@tool def web_search(query: str) -> str: """Searches the web for a query and returns top results with titles, URLs, and snippets. Args: query: The search query string. """ import re from html import unescape
clean_q = (query or "").strip() if not clean_q: return "Empty search query."
results_out = [] try: try: from ddgs import DDGS except ImportError: from duckduckgo_search import DDGS
raw_results = DDGS().text(clean_q, max_results=5) or [] for item in raw_results: if not isinstance(item, dict): continue title = str(item.get("title", "")).strip() href = str(item.get("href", "")).strip() body = str(item.get("body", "")).strip() if title or href or body: results_out.append(f"- {title}\n URL: {href}\n Snippet: {body}") except Exception: pass
if not results_out: try: resp = requests.post( "https://html.duckduckgo.com/html/", data={"q": clean_q}, headers={"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36"}, timeout=25, ) resp.raise_for_status() links = re.findall( r'(?is)<a[^>]+class="result__a"[^>]+href="([^"]+)"[^>]*>(.*?)</a>', resp.text, ) snippets = re.findall( r'(?is)<a[^>]+class="result__snippet"[^>]*>(.*?)</a>', resp.text, ) for idx, (href, raw_title) in enumerate(links[:5]): title = re.sub(r"\s+", " ", unescape(re.sub(r"(?s)<[^>]+>", " ", raw_title))).strip() raw_snip = snippets[idx] if idx < len(snippets) else "" snip = re.sub(r"\s+", " ", unescape(re.sub(r"(?s)<[^>]+>", " ", raw_snip))).strip() if title or href or snip: results_out.append(f"- {title}\n URL: {href}\n Snippet: {snip}") except Exception: pass
if not results_out: return f"No web results found for '{clean_q}'. Try search_wikipedia(query) or fetch_url_text(url)." return "\n\n".join(results_out)
wiki_cache = {}
@tool def search_wikipedia(query: str) -> str: """Searches English Wikipedia and returns clean plain text (including tables) of the best matching article. Args: query: Search query or exact Wikipedia article title. """ import re import time from html import unescape
cache_key = query.strip().lower() if cache_key in wiki_cache: return wiki_cache[cache_key]
headers = {"User-Agent": "HF-Agents-Course-Bot/1.0"} api_endpoint = "https://en.wikipedia.org/w/api.php" use_2022 = "2022" in cache_key clean_query = re.sub(r"\b2022\b", "", query).strip() or query.strip() try: search_resp = None for attempt in range(3): search_resp = requests.get( api_endpoint, params={ "action": "query", "list": "search", "srsearch": clean_query, "format": "json", "srlimit": 5, }, headers=headers, timeout=45, ) if search_resp.status_code == 429 and attempt < 2: time.sleep(1.5 * (attempt + 1)) continue break search_resp.raise_for_status() results = search_resp.json().get("query", {}).get("search", []) if not results: out_empty = f"No Wikipedia results for '{query}'." wiki_cache[cache_key] = out_empty return out_empty
query_norm = clean_query.lower() selected = next( (r for r in results if r["title"].strip().lower() == query_norm), results[0], ) title = selected["title"] other_titles = [r["title"] for r in results if r["title"] != title]
rev_id = None if use_2022: rev_resp = requests.get( api_endpoint, params={ "action": "query", "titles": title, "prop": "revisions", "rvlimit": 1, "rvdir": "older", "rvstart": "2023-01-01T00:00:00Z", "format": "json", }, headers=headers, timeout=30, ) if rev_resp.status_code == 200: pages = rev_resp.json().get("query", {}).get("pages", {}) for p_data in pages.values(): revs = p_data.get("revisions") or [] if revs and revs[0].get("revid"): rev_id = revs[0]["revid"] break
parse_params = { "action": "parse", "prop": "text", "redirects": 1, "format": "json", } if rev_id: parse_params["oldid"] = rev_id else: parse_params["page"] = title
parse_resp = None for attempt in range(3): parse_resp = requests.get( api_endpoint, params=parse_params, headers=headers, timeout=45, ) if parse_resp.status_code == 429 and attempt < 2: time.sleep(1.5 * (attempt + 1)) continue break parse_resp.raise_for_status() parse_data = parse_resp.json().get("parse", {}) raw_html = parse_data.get("text", {}).get("*", "") resolved_title = parse_data.get("title", title)
if raw_html: cleaned_html = re.sub( r"(?is)<(script|style|noscript|svg).*?>.*?</\1>", " ", raw_html, ) cleaned_html = re.sub(r"(?i)</(tr|p|li|h[1-6]|div|br)>", "\n", cleaned_html) cleaned_html = re.sub(r"(?i)</(td|th)>", " | ", cleaned_html) plain_text = unescape(re.sub(r"(?s)<[^>]+>", " ", cleaned_html)) lines = [re.sub(r"[ \t]+", " ", ln).strip() for ln in plain_text.splitlines()] text = "\n".join(ln for ln in lines if ln) else: text = ""
if len(text) > 22000: disc_match = re.search(r"(?i)\bdiscography\b", text) if disc_match: start_pos = max(0, disc_match.start() - 500) text = text[:3000] + "\n...\n" + text[start_pos : start_pos + 19000] else: text = text[:11000] + "\n...\n" + text[-11000:]
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 except Exception as e: return f"Wikipedia error for '{query}': {str(e)}"
@tool def ask_web(query: str) -> str: """Searches Wikipedia first and falls back to DuckDuckGo web search if needed. Args: query: Search query string. """ import re from html import unescape
cleaned_query = (query or "").strip() if not cleaned_query: return "Brak wyników."
try: resp = requests.get( "https://en.wikipedia.org/w/api.php", params={"action": "opensearch", "search": cleaned_query, "limit": 3, "format": "json"}, headers={"User-Agent": "BasicAgent/1.0"}, timeout=15, ) resp.raise_for_status() data = resp.json() titles = data[1] if len(data) > 1 else [] descs = data[2] if len(data) > 2 else [] urls = data[3] if len(data) > 3 else [] wiki_lines = [f"{t}: {d} ({u})" for t, d, u in zip(titles, descs, urls) if t or d] if wiki_lines: return "\n".join(wiki_lines) except Exception: pass
try: ddg_resp = requests.post( "https://html.duckduckgo.com/html/", data={"q": cleaned_query}, headers={"User-Agent": "Mozilla/5.0"}, timeout=15, ) ddg_resp.raise_for_status() matches = re.findall( r'(?is)<a[^>]+class="result__a"[^>]+href="([^"]+)"[^>]*>(.*?)</a>', ddg_resp.text, ) out = [] for href, raw_title in matches[:3]: title = re.sub(r"\s+", " ", unescape(re.sub(r"(?s)<[^>]+>", " ", raw_title))).strip() if title: out.append(f"{title} ({href})") if out: return "\n".join(out) except Exception: pass
return "Brak wyników." @tool def inspect_image(image_path: str, question: str) -> str: """Analyzes a local image file using a multimodal vision model and answers a specific question about it. Args: image_path: Local path to the image file (.png, .jpg, .jpeg, .webp). question: Specific question or instruction about what to extract from the image. """ import io
try: if not os.path.isfile(image_path): return f"Image file not found: '{image_path}'"
mime_type, _ = mimetypes.guess_type(image_path) if not mime_type or not mime_type.startswith("image/"): mime_type = "image/png"
with open(image_path, "rb") as f: raw_bytes = f.read()
payload_bytes = raw_bytes if len(raw_bytes) > 3_500_000: try: from PIL import Image
img = Image.open(io.BytesIO(raw_bytes)) img.thumbnail((1600, 1600)) buf = io.BytesIO() save_fmt = "JPEG" if mime_type in ("image/jpeg", "image/jpg") else "PNG" if save_fmt == "JPEG" and img.mode in ("RGBA", "P"): img = img.convert("RGB") img.save(buf, format=save_fmt, optimize=True, quality=85) payload_bytes = buf.getvalue() mime_type = "image/jpeg" if save_fmt == "JPEG" else "image/png" except Exception: payload_bytes = raw_bytes
b64_data = base64.b64encode(payload_bytes).decode("utf-8")
vision_tags = ( "gemma-3", "gemma-4", "gemini", "vision", "-vl", "scout", "maverick", "pixtral", "qwen2.5-vl", "qwen3-vl", ) vision_candidates = [] current_model = getattr(self, "model_id", "") current_model_low = current_model.lower()
if current_model and any(tag in current_model_low for tag in vision_tags): vision_candidates.append(current_model)
if self.provider_keys.get("openrouter"): vision_candidates.extend([ "openrouter/google/gemma-4-26b-a4b-it:free", "openrouter/google/gemma-4-31b-it:free", "openrouter/google/gemma-3-27b-it:free", "openrouter/nvidia/nemotron-3.5-super-vl:free", ]) for m in getattr(self, "working_models", []): if m.startswith("openrouter/") and any(tag in m.lower() for tag in vision_tags): vision_candidates.append(m)
if self.provider_keys.get("gemini"): vision_candidates.extend( self.gemini_flash_models or [ "gemini/gemini-2.5-flash-lite", "gemini/gemini-2.5-flash", ] )
if self.provider_keys.get("groq"): vision_candidates.append("groq/meta-llama/llama-4-scout-17b-16e-instruct")
for m in getattr(self, "working_models", []): if m not in vision_candidates and any(tag in m.lower() for tag in vision_tags): vision_candidates.append(m)
unique_vision = list(dict.fromkeys(vision_candidates)) last_err = None
while True: rate_limited_providers = set() for v_model in unique_vision: v_provider = v_model.split("/", 1)[0].lower() if "/" in v_model else "gemini" while True: v_key = self._get_api_key(v_model) if not v_key: break try: response = litellm.completion( model=v_model, api_key=v_key, messages=[ { "role": "user", "content": [ {"type": "text", "text": question}, { "type": "image_url", "image_url": {"url": f"data:{mime_type};base64,{b64_data}"}, }, ], } ], max_tokens=2048, timeout=45, ) out = (response.choices[0].message.content or "").strip() if out: return out break except Exception as exc: last_err = exc err_low = str(exc).lower() if any( marker in err_low for marker in ( "401", "402", "403", "authentication", "missing authentication header", "insufficient permissions", "does not have sufficient permissions", "free-models-per-day", "quota", "resource_exhausted", ) ): if hasattr(self, "_rotate_api_key") and self._rotate_api_key(v_provider): continue break if any(marker in err_low for marker in ("429", "rate limit exceeded")): rate_limited_providers.add(v_provider) break break
rotated_any = False if hasattr(self, "_rotate_api_key"): for prov in rate_limited_providers: pool = self.provider_key_pools.get(prov) or [] if self._provider_key_idx.get(prov, 0) + 1 < len(pool): if self._rotate_api_key(prov): rotated_any = True if not rotated_any: break
raise RuntimeError(str(last_err) if last_err else "No vision model available.") except Exception as e: return f"Error inspecting image '{image_path}': {str(e)}"
@tool def inspect_youtube(url: str) -> str: """Fetches YouTube video title, author, description, and available captions/transcripts for a given YouTube URL or video ID. Args: url: YouTube video URL or 11-character video ID. """ import re from html import unescape
raw = (url or "").strip() vid_match = re.search( r"(?:v=|/shorts/|/embed/|youtu\.be/)([A-Za-z0-9_-]{11})", raw, ) video_id = vid_match.group(1) if vid_match else (raw if re.fullmatch(r"[A-Za-z0-9_-]{11}", raw) else "") if not video_id: return f"Invalid YouTube URL or video ID: '{url}'"
watch_url = f"https://www.youtube.com/watch?v={video_id}" headers = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36", "Accept-Language": "en-US,en;q=0.9", } sections = [f"Video ID: {video_id}", f"URL: {watch_url}"]
try: oembed_resp = requests.get( "https://www.youtube.com/oembed", params={"url": watch_url, "format": "json"}, headers=headers, timeout=20, ) if oembed_resp.status_code == 200: oembed = oembed_resp.json() if oembed.get("title"): sections.append(f"Title: {oembed['title']}") if oembed.get("author_name"): sections.append(f"Channel: {oembed['author_name']}") except Exception: pass
try: page_resp = requests.get(watch_url, headers=headers, timeout=25) if page_resp.status_code == 200: html_text = page_resp.text desc_match = re.search(r'"shortDescription"\s*:\s*"((?:\\.|[^"\\])*)"', html_text) if desc_match: try: desc_val = desc_match.group(1).encode("utf-8").decode("unicode_escape") except Exception: desc_val = unescape(desc_match.group(1)) sections.append(f"Description:\n{desc_val[:2000]}")
cap_match = re.search(r'"captionTracks"\s*:\s*(\[[^\]]*\])', html_text) if cap_match: import json
try: tracks = json.loads(cap_match.group(1)) for tr in tracks[:3]: base_url = tr.get("baseUrl") if not base_url: continue tr_resp = requests.get(unescape(base_url), headers=headers, timeout=20) if tr_resp.status_code == 200 and tr_resp.text: raw_cues = re.findall(r"(?is)<text[^>]*>(.*?)</text>", tr_resp.text) cues = [ re.sub(r"\s+", " ", unescape(re.sub(r"(?s)<[^>]+>", " ", c))).strip() for c in raw_cues ] transcript = " ".join(c for c in cues if c) if transcript: lang = tr.get("languageCode", "unknown") sections.append(f"Transcript ({lang}):\n{transcript[:8000]}") break except Exception: pass except Exception as e: sections.append(f"Page fetch note: {e}")
return "\n\n".join(sections) @tool def transcribe_audio( audio_path: str,493 unmodified lines exact_match_rule = ( "CRITICAL OUTPUT RULES FOR EXACT MATCH EVALUATION:\n" "- Always write valid Python code inside <code> and </code> tags. NEVER put 'Thought:' or ``` fences inside the code block.\n" "- If the prompt includes a Task ID and mentions an image, board, diagram, or attached file, FIRST call path = download_task_file(task_id=...) and inspect it.\n" "- Never call built-in open(); use read_local_file(file_path) for text/PDF/ZIP/spreadsheet files, " "inspect_image(image_path, question) for images, and transcribe_audio(audio_path, question) for audio files (.mp3, .wav).\n" "- If web_search returns no results, use search_wikipedia(query) or fetch_url_text(url).\n"13 unmodified lines download_task_file, read_local_file, inspect_image, inspect_youtube, transcribe_audio, ], "additional_authorized_imports": [app.py+1785