Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files17 unmodified lines18192021222322242526272829303132333435363735 unmodified lines7374756465666768697677787917 unmodified lines979899939495969798991001011021001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052061081092072082092102112122132142152161152172182192201 unmodified line2222232241232252262272282292302312322331 unmodified line23523623723823924013624124224324414024524624724824914525025125214825325425515125625725815425926026126217 unmodified lines# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------class BasicAgent: def __init__(self): import base64 import mimetypes import litellm from smolagents import CodeAgent, DuckDuckGoSearchTool, FinalAnswerTool, LiteLLMModel, tool from smolagents import CodeAgent, DuckDuckGoSearchTool, LiteLLMModel, tool
litellm.drop_params = True raw_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
@tool def fetch_url_text(url: str) -> str:35 unmodified lines """ import re
base_url = ( os.getenv("GAIA_API_URL") or DEFAULT_API_URL ).rstrip("/") url = f"{base_url}/files/{task_id}"
url = f"{DEFAULT_API_URL.rstrip('/')}/files/{task_id}" try: os.makedirs(output_dir, exist_ok=True) response = requests.get(17 unmodified lines except Exception as e: return f"Error downloading file for task '{task_id}': {str(e)}"
litellm.drop_params = True raw_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 @tool def 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)}"
@tool def 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)}"
@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. """ 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=2, timeout=30, 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).\n" "(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 line self.agent = CodeAgent( model=model, tools=[ FinalAnswerTool(), 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.")
@staticmethod def _clean_exact_match_answer(raw_answer: str) -> str: import re
text = (raw_answer or "").strip() if not text or text.startswith("AGENT ERROR:"): return text
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 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