Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files17 unmodified lines181920212223242535 unmodified lines61626364656667686970717217 unmodified lines909192939495969798991001011021031041051061071081091101111121131141151161171181 unmodified line1201211221231241251261271281291 unmodified line13113213313413513613713813914014114214314414514614714814915015115215315415515615717 unmodified lines# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------class BasicAgent:def __init__(self):import litellmfrom smolagents import CodeAgent, DuckDuckGoSearchTool, FinalAnswerTool, LiteLLMModel, tool@tooldef fetch_url_text(url: str) -> str:35 unmodified lines"""import rebase_url = (os.getenv("GAIA_API_URL")or DEFAULT_API_URL).rstrip("/")url = f"{base_url}/files/{task_id}"try:os.makedirs(output_dir, exist_ok=True)response = requests.get(17 unmodified linesexcept Exception as e:return f"Error downloading file for task '{task_id}': {str(e)}"litellm.drop_params = Trueraw_key = os.getenv("GEMINI_API_KEY")gemini_key = raw_key.strip(" '\"\n\r\t") if raw_key else ""if not gemini_key:raise ValueError("Missing GEMINI_API_KEY in environment/secrets. ""Add GEMINI_API_KEY in Space Settings -> Variables and secrets and restart the Space.")os.environ["GEMINI_API_KEY"] = gemini_keymodel = LiteLLMModel(model_id="gemini/gemini-2.5-flash",api_key=gemini_key,max_tokens=4096,num_retries=2,timeout=30,)exact_match_rule = ("CRITICAL OUTPUT RULES FOR EXACT MATCH EVALUATION:\n""- Return ONLY the concise exact answer value itself ""(e.g. a number, date, name, or short phrase).\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.")1 unmodified lineself.agent = CodeAgent(model=model,tools=[FinalAnswerTool(),DuckDuckGoSearchTool(),fetch_url_text,download_task_file,],instructions=exact_match_rule,max_steps=10,1 unmodified line)print("CodeAgent initialized with LiteLLMModel.")def _clean_exact_match_answer(raw_answer: str) -> str:import retext = (raw_answer or "").strip()if not text or text.startswith("AGENT ERROR:"):return texttext = 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 text.startswith("```") and text.endswith("```"):text = text.strip("`").strip()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\.$", text):text = text[:-1].strip()return text17 unmodified lines181920212223242526272829303132333435363735 unmodified lines7374757677787917 unmodified lines9798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192201 unmodified line2222232242252262272282292302312322331 unmodified line23523623723823924024124224324424524624724824925025125225325425525625725825926026126217 unmodified lines# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------class BasicAgent:def __init__(self):import base64import mimetypesimport litellmfrom smolagents import CodeAgent, DuckDuckGoSearchTool, LiteLLMModel, toollitellm.drop_params = Trueraw_key = os.getenv("GEMINI_API_KEY")gemini_key = raw_key.strip(" '\"\n\r\t") if raw_key else ""if not gemini_key:raise ValueError("Missing GEMINI_API_KEY in environment/secrets. ""Add GEMINI_API_KEY in Space Settings -> Variables and secrets and restart the Space.")os.environ["GEMINI_API_KEY"] = gemini_key@tooldef fetch_url_text(url: str) -> str:35 unmodified lines"""import reurl = f"{DEFAULT_API_URL.rstrip('/')}/files/{task_id}"try:os.makedirs(output_dir, exist_ok=True)response = requests.get(17 unmodified linesexcept Exception as e:return f"Error downloading file for task '{task_id}': {str(e)}"@tooldef read_local_file(file_path: str) -> str:"""Reads text or spreadsheet content from a local file downloaded by download_task_file.Args:file_path: Local path to the downloaded file."""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 in {".xlsx", ".xls"}:df = pd.read_excel(file_path)return df.to_csv(index=False)[:8000]with open(file_path, "r", encoding="utf-8", errors="replace") as f:return f.read()[:8000]except Exception as e:return f"Error reading file '{file_path}': {str(e)}"@tooldef search_wikipedia(query: str) -> str:"""Searches English Wikipedia and returns the plain text extract of the top matching article.Args:query: Search query or Wikipedia article title."""headers = {"User-Agent": "HF-Agents-Course-Bot/1.0"}try:search_resp = requests.get("https://en.wikipedia.org/w/api.php",params={"action": "query","list": "search","srsearch": query,"format": "json","srlimit": 3,},headers=headers,timeout=15,)search_resp.raise_for_status()results = search_resp.json().get("query", {}).get("search", [])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",params={"action": "query","prop": "extracts","explaintext": True,"titles": title,"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:]}"except Exception as e:return f"Wikipedia error for '{query}': {str(e)}"@tooldef 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."""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:b64_data = base64.b64encode(f.read()).decode("utf-8")response = litellm.completion(model="gemini/gemini-2.5-flash",api_key=gemini_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=30,)return (response.choices[0].message.content or "").strip()except Exception as e:return f"Error inspecting image '{image_path}': {str(e)}"model = LiteLLMModel(model_id="gemini/gemini-2.5-flash",api_key=gemini_key,max_tokens=4096,num_retries=5,timeout=45,)exact_match_rule = ("CRITICAL OUTPUT RULES FOR EXACT MATCH EVALUATION:\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""- 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.")1 unmodified lineself.agent = CodeAgent(model=model,tools=[DuckDuckGoSearchTool(),search_wikipedia,fetch_url_text,download_task_file,read_local_file,inspect_image,],instructions=exact_match_rule,max_steps=10,1 unmodified line)print("CodeAgent initialized with LiteLLMModel.")@staticmethoddef _clean_exact_match_answer(raw_answer: str) -> str:import retext = (raw_answer or "").strip()if not text or text.startswith("AGENT ERROR:"):return texttext = 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 text.startswith("```") and text.endswith("```"):text = text.strip("`").strip()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\.$", text):text = text[:-1].strip()return text
app.py+132-27