Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files2 unmodified lines3456783 unmodified lines12131415161718192021222356 unmodified lines8081828384858687888990912 unmodified linesimport requestsimport inspectimport pandas as pd# (Keep Constants as is)# --- Constants ---3 unmodified lines# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------class BasicAgent:def __init__(self):print("BasicAgent initialized.")def __call__(self, question: str) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")fixed_answer = "This is a default answer."print(f"Agent returning fixed answer: {fixed_answer}")return fixed_answerdef run_and_submit_all( profile: gr.OAuthProfile | None):"""56 unmodified linesprint(f"Skipping item with missing task_id or question: {item}")continuetry:submitted_answer = agent(question_text)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})except Exception as e:print(f"Error running agent on task {task_id}: {e}")results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})if not answers_payload:print("Agent did not produce any answers to submit.")2 unmodified lines345678910111213143 unmodified lines1819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214356 unmodified lines2002012022032042052062072082092102112122132 unmodified linesimport requestsimport inspectimport pandas as pdimport spaces@spaces.GPUdef _register_zerogpu():return None# (Keep Constants as is)# --- Constants ---3 unmodified lines# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------class BasicAgent:def __init__(self):import litellmfrom smolagents import CodeAgent, DuckDuckGoSearchTool, LiteLLMModel, toolfrom tools.final_answer import FinalAnswerTool@tooldef fetch_url_text(url: str) -> str:"""Fetches clean plain text from a given URL.Args:url: The HTTP/HTTPS URL to fetch."""import refrom html import unescapetry:response = requests.get(url,timeout=15,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) <= 6000:return cleanedreturn cleaned[:3000] + "\n...\n" + cleaned[-3000:]except Exception as e:return f"Error fetching URL '{url}': {str(e)}"@tooldef 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 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(url,timeout=30,headers={"User-Agent": "Mozilla/5.0"},)response.raise_for_status()content_disp = response.headers.get("Content-Disposition", "")match = re.search(r'filename="?([^";]+)"?', content_disp)filename = os.path.basename(match.group(1)) if match else f"{task_id}.bin"if not filename:filename = f"{task_id}.bin"file_path = os.path.join(output_dir, filename)with open(file_path, "wb") as f:f.write(response.content)return file_pathexcept Exception as e:return f"Error downloading file for task '{task_id}': {str(e)}"litellm.drop_params = Trueopenrouter_key = (os.getenv("OPENROUTER_API_KEY") or "").strip(" '\"\n\r\t") or Noneif openrouter_key:os.environ["OPENROUTER_API_KEY"] = openrouter_keymodel = LiteLLMModel(model_id="openrouter/nvidia/nemotron-3.5-lightning:free",api_key=openrouter_key,max_tokens=8192,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.")self.agent = CodeAgent(model=model,tools=[FinalAnswerTool(),DuckDuckGoSearchTool(),fetch_url_text,download_task_file,],instructions=exact_match_rule,max_steps=10,verbosity_level=1,)print("CodeAgent initialized with LiteLLMModel.")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.")try:result = self.agent.run(prompt)return "" if result is None else str(result).strip()except Exception as exc:return f"AGENT ERROR: {exc}"def run_and_submit_all( profile: gr.OAuthProfile | None):"""56 unmodified linesprint(f"Skipping item with missing task_id or question: {item}")continuetry:submitted_answer = agent(question_text, task_id=task_id)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})except Exception as e:print(f"Error running agent on task {task_id}: {e}")error_answer = f"AGENT ERROR: {e}"answers_payload.append({"task_id": task_id, "submitted_answer": error_answer})results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": error_answer})if not answers_payload:print("Agent did not produce any answers to submit.")
app.py+131-9