Spaces:
Sleeping
Sleeping
Update app.py
Browse files47 unmodified lines484950515253490 unmodified lines54454554654754854919 unmodified lines56957057157257357457550 unmodified lines6266276286296306319 unmodified lines64164264364464564664764864965047 unmodified lines# being fetched from the scoring server (avoids 429s from the shared Space IP).QUESTIONS_FILE = "questions.json"# Number of questions to skip from the start of the list (set to 0 to run all)SKIP_FIRST_N = 1490 unmodified linesprint(f"Using agent type: {AGENT_TYPE}")class ResearchAgentWrapper:"""Thin wrapper so the research agent can be called like19 unmodified linesraise RuntimeError(str(answer))print(f"Agent returning answer (first 50 chars): {str(answer)[:50]}...")return str(answer)# =========================================================50 unmodified linesresults_log = []answers_payload = []quota_exhausted = False# Skip the first N questionsquestions_data = questions_data[SKIP_FIRST_N:]9 unmodified linesprint(f"Skipping item with missing task_id or question: {item}")continuestart_time = time.monotonic()try:submitted_answer = _run_agent_with_backoff(agent_runner, 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 DailyQuotaExhaustedError as e:47 unmodified lines484950515253545556575859490 unmodified lines55055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460519 unmodified lines62562662762862963063150 unmodified lines6826836846856866876886896909 unmodified lines70070170270370470570670770870971071171271371471571671771847 unmodified lines# being fetched from the scoring server (avoids 429s from the shared Space IP).QUESTIONS_FILE = "questions.json"# Answers are saved here after each question, so a run that stops (e.g. daily# quota) can be resumed later without re-spending requests on finished questions.# Delete an entry (or the whole file) to force a question to be re-run.USE_ANSWER_CACHE = TrueANSWER_CACHE_FILE = "answers_cache.json"# Number of questions to skip from the start of the list (set to 0 to run all)SKIP_FIRST_N = 1490 unmodified linesprint(f"Using agent type: {AGENT_TYPE}")def _clean_answer(answer) -> str:"""Conservative cleanup so only the bare answer is submitted:strips whitespace, a leading "Final answer:" label, wrapping quotes/backticks/bold markers, and a trailing period. Does not rewrite content."""text = str(answer).strip()lowered = text.lower()for prefix in ("final answer:", "answer:"):if lowered.startswith(prefix):text = text[len(prefix):].strip()break# Remove wrapping quotes, backticks or bold markers (repeat for nesting)changed = Truewhile changed and len(text) >= 2:changed = Falsefor wrapper in ('"', "'", "`", "**"):if text.startswith(wrapper) and text.endswith(wrapper) and len(text) > 2 * len(wrapper):text = text[len(wrapper):-len(wrapper)].strip()changed = True# Trailing period ("3." -> "3"), but keep things like "St." or "U.S." intactif text.endswith(".") and not text.endswith("..") and text[:-1].replace(",", "").replace(".", "").isdigit():text = text[:-1]elif text.endswith(".") and " " not in text and text.count(".") == 1:text = text[:-1]return textdef _load_answer_cache() -> dict:if not USE_ANSWER_CACHE or not os.path.exists(ANSWER_CACHE_FILE):return {}try:with open(ANSWER_CACHE_FILE, "r", encoding="utf-8") as f:return json.load(f)except Exception as e:print(f"Could not read {ANSWER_CACHE_FILE}, starting fresh: {e}")return {}def _save_answer_cache(cache: dict) -> None:if not USE_ANSWER_CACHE:returnwith open(ANSWER_CACHE_FILE, "w", encoding="utf-8") as f:json.dump(cache, f, indent=2, ensure_ascii=False)class ResearchAgentWrapper:"""Thin wrapper so the research agent can be called like19 unmodified linesraise RuntimeError(str(answer))print(f"Agent returning answer (first 50 chars): {str(answer)[:50]}...")return _clean_answer(answer)# =========================================================50 unmodified linesresults_log = []answers_payload = []quota_exhausted = Falseanswer_cache = _load_answer_cache()if answer_cache:print(f"Loaded {len(answer_cache)} cached answer(s) from {ANSWER_CACHE_FILE}.")# Skip the first N questionsquestions_data = questions_data[SKIP_FIRST_N:]9 unmodified linesprint(f"Skipping item with missing task_id or question: {item}")continueif task_id in answer_cache:cached_answer = answer_cache[task_id]print(f"Using cached answer for task {task_id}: {cached_answer[:50]}")answers_payload.append({"task_id": task_id, "submitted_answer": cached_answer})results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": cached_answer})continuestart_time = time.monotonic()try:submitted_answer = _run_agent_with_backoff(agent_runner, question_text)answer_cache[task_id] = submitted_answer_save_answer_cache(answer_cache)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 DailyQuotaExhaustedError as e:
app.py+69-1