Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files401 unmodified lines4024034044054064072 unmodified lines41041141241341441541611 unmodified lines4284294304314324334341 unmodified line43643743843944044144244344444544644744844945045145245319 unmodified lines473474475476477478479480481482955 unmodified lines1438143914401441144214435 unmodified lines1449145014511452145314541455145614571458145914601461146214631464146514661467401 unmodified linesheaders = {"User-Agent": "HF-Agents-Course-Bot/1.0"}api_endpoint = "https://en.wikipedia.org/w/api.php"try:search_resp = Nonefor attempt in range(3):2 unmodified linesparams={"action": "query","list": "search","srsearch": query,"format": "json","srlimit": 5,},11 unmodified lineswiki_cache[cache_key] = out_emptyreturn out_emptyquery_norm = query.strip().lower()selected = next((r for r in results if r["title"].strip().lower() == query_norm),results[0],1 unmodified linetitle = selected["title"]other_titles = [r["title"] for r in results if r["title"] != title]parse_resp = Nonefor attempt in range(3):parse_resp = requests.get(api_endpoint,params={"action": "parse","page": title,"prop": "text","redirects": 1,"format": "json",},headers=headers,timeout=45,)if parse_resp.status_code == 429 and attempt < 2:19 unmodified lineselse: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)}"output = f"{header_info}\n\n{text}" if text else f"{header_info}\n\nEmpty article text."955 unmodified linesreturn f"An unexpected error occurred fetching questions: {e}", None# 3. Run your Agentresults_log = []answers_payload = []partial_path = "/tmp/gaia_partial_results.json"5 unmodified linesprint(f"Skipping item with missing task_id or question: {item}")continueif idx > 0:import timetime.sleep(3)try: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})try:import jsonwith open(partial_path, "w", encoding="utf-8") as f_part:json.dump(results_log, f_part, ensure_ascii=False, indent=2)except Exception:401 unmodified lines4024034044054064074084092 unmodified lines41241341441541641741811 unmodified lines4304314324334344354361 unmodified line43843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348419 unmodified lines504505506507508509510511512513514515516517518519520955 unmodified lines14761477147814791480148114821483148414855 unmodified lines149114921493149414951496149714981499150015011502150315041505150615071508150915101511401 unmodified linesheaders = {"User-Agent": "HF-Agents-Course-Bot/1.0"}api_endpoint = "https://en.wikipedia.org/w/api.php"use_2022 = "2022" in cache_keyclean_query = re.sub(r"\b2022\b", "", query).strip() or query.strip()try:search_resp = Nonefor attempt in range(3):2 unmodified linesparams={"action": "query","list": "search","srsearch": clean_query,"format": "json","srlimit": 5,},11 unmodified lineswiki_cache[cache_key] = out_emptyreturn out_emptyquery_norm = clean_query.lower()selected = next((r for r in results if r["title"].strip().lower() == query_norm),results[0],1 unmodified linetitle = selected["title"]other_titles = [r["title"] for r in results if r["title"] != title]rev_id = Noneif 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"]breakparse_params = {"action": "parse","prop": "text","redirects": 1,"format": "json",}if rev_id:parse_params["oldid"] = rev_idelse:parse_params["page"] = titleparse_resp = Nonefor 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:19 unmodified lineselse: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."955 unmodified linesreturn f"An unexpected error occurred fetching questions: {e}", None# 3. Run your Agentfrom concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutErrorimport jsonimport timeresults_log = []answers_payload = []partial_path = "/tmp/gaia_partial_results.json"5 unmodified linesprint(f"Skipping item with missing task_id or question: {item}")continueif idx > 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:
app.py+63-19