Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files20 unmodified lines212223242425262794 unmodified lines1221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801271811821291831841851861871881891901911341921931941951961971401981992002013 unmodified lines20520620715015115220820921021121221321421521621721815415515615721922022122222322422522622716316416516616716822822923023123223323423523623723823924024124224324424524624724824925025125225325425525673 unmodified lines3303313323332482492503343353363373383393 unmodified lines3433443452603463473483493503513523533543551 unmodified line35735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848920 unmodified lines import base64 import mimetypes import litellm from smolagents import CodeAgent, DuckDuckGoSearchTool, LiteLLMModel, tool from smolagents import CodeAgent, LiteLLMModel, tool
litellm.drop_params = True env_ci = {k.upper(): v for k, v in os.environ.items() if v}94 unmodified lines 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
results_out = [] try: try: from ddgs import DDGS except ImportError: from duckduckgo_search import DDGS
raw_results = DDGS().text(query, max_results=5) or [] for item in raw_results: title = item.get("title", "") href = item.get("href", "") body = item.get("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": query}, headers={"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36"}, timeout=15, ) 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() 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 '{query}'. Try search_wikipedia(query) or fetch_url_text(url)." return "\n\n".join(results_out) @tool def search_wikipedia(query: str) -> str: """Searches English Wikipedia and returns the plain text extract of the top matching article. """Searches English Wikipedia and returns clean plain text (including tables) of the best matching article. Args: query: Search query or Wikipedia article title. query: Search query or exact Wikipedia article title. """ import re from html import unescape
headers = {"User-Agent": "HF-Agents-Course-Bot/1.0"} api_endpoint = "https://en.wikipedia.org/w/api.php" try: search_resp = requests.get( "https://en.wikipedia.org/w/api.php", api_endpoint, params={ "action": "query", "list": "search", "srsearch": query, "format": "json", "srlimit": 3, "srlimit": 5, }, headers=headers, timeout=15,3 unmodified lines if not results: return f"No Wikipedia results for '{query}'."
title = results[0]["title"] page_resp = requests.get( "https://en.wikipedia.org/w/api.php", query_norm = query.strip().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]
parse_resp = requests.get( api_endpoint, params={ "action": "query", "prop": "extracts", "explaintext": True, "titles": title, "action": "parse", "page": title, "prop": "text", "redirects": 1, "format": "json", }, headers=headers, timeout=15, ) page_resp.raise_for_status() pages = page_resp.json().get("query", {}).get("pages", {}) extract = next(iter(pages.values())).get("extract", "") if len(extract) <= 6000: return f"Title: {title}\n\n{extract}" return f"Title: {title}\n\n{extract[:3000]}\n...\n{extract[-3000:]}" 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) > 16000: text = text[:8000] + "\n...\n" + text[-8000:]
header_info = f"Title: {resolved_title}" if other_titles: header_info += f"\nOther matching pages: {', '.join(other_titles)}" return f"{header_info}\n\n{text}" if text else f"{header_info}\n\nEmpty article text." except Exception as e: return f"Wikipedia error for '{query}': {str(e)}"
73 unmodified lines
exact_match_rule = ( "CRITICAL OUTPUT RULES FOR EXACT MATCH EVALUATION:\n" "- Always write valid Python code inside ```py and ``` fences. NEVER put 'Thought:' or HTML tags like <code> inside the Python block.\n" "- Never call built-in open(); use read_local_file(file_path) for text/spreadsheet files " "and inspect_image(image_path, question) for image attachments.\n" "- If web_search fails or returns no results, use search_wikipedia(query) or fetch_url_text(url).\n" "- Never call built-in open(); use read_local_file(file_path) for text/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"3 unmodified lines self.agent = CodeAgent( model=model, tools=[ DuckDuckGoSearchTool(), web_search, search_wikipedia, fetch_url_text, download_task_file, read_local_file, inspect_image, transcribe_audio, ], instructions=exact_match_rule, max_steps=10,1 unmodified line ) print("CodeAgent initialized with LiteLLMModel.")
@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 Gemini. 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") 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}" try: response = litellm.completion( model=self.model_id, api_key=gemini_key, messages=[ { "role": "user", "content": [ {"type": "text", "text": question}, {"type": "image_url", "image_url": {"url": data_uri}}, ], } ], max_tokens=2048, timeout=45, ) except Exception: response = litellm.completion( model=self.model_id, api_key=gemini_key, messages=[ { "role": "user", "content": [ {"type": "text", "text": question}, {"type": "file", "file": {"file_data": data_uri}}, ], } ], max_tokens=2048, timeout=45, ) return (response.choices[0].message.content or "").strip() except Exception as e: return f"Error transcribing audio '{audio_path}': {str(e)}"
candidate_models = [ "gemini/gemini-3.8-flash", "gemini/gemini-3-flash-preview", "gemini/gemini-2.5-flash-lite", "gemini/gemini-2.0-flash", ] selected_model = None last_probe_error = "" for candidate in candidate_models: try: litellm.completion( model=candidate, api_key=gemini_key, messages=[{"role": "user", "content": "Reply with OK"}], max_tokens=2048, timeout=15, ) selected_model = candidate print(f"Selected working Gemini model: {selected_model}") break except Exception as probe_exc: last_probe_error = f"{candidate}: {probe_exc}" print(f"Model probe failed for {last_probe_error}")
if not selected_model: raise RuntimeError(f"No working Gemini model found. Last error -> {last_probe_error}")
self.model_id = selected_model model = LiteLLMModel( model_id=self.model_id, api_key=gemini_key, max_tokens=4096, num_retries=5, timeout=45, )
exact_match_rule = ( "CRITICAL OUTPUT RULES FOR EXACT MATCH EVALUATION:\n" "- Always write valid Python code inside ```py and ``` fences. NEVER put 'Thought:' or HTML tags like <code> inside the Python block.\n" "- Never call built-in open(); use read_local_file(file_path) for text/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." )
self.agent = CodeAgent( model=model, tools=[ web_search, search_wikipedia, fetch_url_text, download_task_file, read_local_file, inspect_image, transcribe_audio, ], instructions=exact_match_rule, max_steps=10, verbosity_level=1, ) print("CodeAgent initialized with LiteLLMModel.") @staticmethod def _clean_exact_match_answer(raw_answer: str) -> str: import reapp.py+236-22