Spaces:
Build error
Build error
Update app.py
Browse files2 unmodified lines34567891012 unmodified lines2324252426272829303031323334343536383740414243444546473839404142434445464748495051525354555657545556575859607 unmodified lines686970717172733 unmodified lines777879818081823 unmodified lines86878891899091949596979899100921029394955 unmodified lines1011021031141151041051061071181191081091101111121131241141151161171181191301201211221236 unmodified lines1301311321431441451461471481491501511521531541331341351361371381391401411421431441451461471481491501511521561531541551562 unmodified linesimport requestsimport pandas as pdimport jsonimport ioimport refrom langchain_core.messages import HumanMessagefrom langgraph_agent import build_graph
12 unmodified lines messages = [HumanMessage(content=question)] messages = self.graph.invoke({"messages": messages})
# Check if messages or content is missing if not messages or not messages.get('messages') or messages['messages'][-1].content is None: return "I am unable to determine the information using the available tools."
answer = messages['messages'][-1].content
# Handle empty list content if isinstance(answer, list) and not answer: return "I am unable to determine the information using the available tools."
# Convert non-string answers to string if not isinstance(answer, str): answer = str(answer)
# Normalize and strip common answer prefixes answer = answer.strip() prefixes = ["FINAL ANSWER:", "Final answer :", "Final answer:", "FINAL ANSWER :"] for prefix in prefixes: if answer.upper().startswith(prefix.upper()): answer = answer[len(prefix):].strip() break
# Handle empty or quote-only answers explicitly if not answer or answer.strip() in ['""', "''"]:
# Extract final answer after "FINAL ANSWER:" match = re.search(r'FINAL ANSWER:\s*(.*)', answer, re.IGNORECASE | re.DOTALL) if match: final_answer = match.group(1).strip() # Remove surrounding quotes if present if (final_answer.startswith('"') and final_answer.endswith('"')) or \ (final_answer.startswith("'") and final_answer.endswith("'")): final_answer = final_answer[1:-1].strip() answer = final_answer else: print("Warning: 'FINAL ANSWER:' not found in agent output; submitting full answer.")
if not answer: answer = "I am unable to determine the information using the available tools."
return answer
def run_and_submit_all(profile: gr.OAuthProfile | None): """ Fetches all questions, runs the BasicAgent on them, submits all answers, and displays the results. """ space_id = os.getenv("SPACE_ID")
if profile:7 unmodified lines questions_url = f"{api_url}/questions" submit_url = f"{api_url}/submit"
# 1. Instantiate Agent try: agent = BasicAgent() except Exception as e:3 unmodified lines agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" print(agent_code)
# 2. Fetch Questions print(f"Fetching questions from: {questions_url}") try: response = requests.get(questions_url, timeout=15)3 unmodified lines print("Fetched questions list is empty.") return "Fetched questions list is empty or invalid format.", None print(f"Fetched {len(questions_data)} questions.") except requests.exceptions.RequestException as e: except Exception as e: print(f"Error fetching questions: {e}") return f"Error fetching questions: {e}", None except requests.exceptions.JSONDecodeError as e: print(f"Error decoding JSON response from questions endpoint: {e}") print(f"Response text: {response.text[:500]}") return f"Error decoding server response for questions: {e}", None except Exception as e: print(f"An unexpected error occurred fetching questions: {e}") return f"An unexpected error occurred fetching questions: {e}", None
# 3. Run your Agent results_log = [] answers_payload = []
5 unmodified lines print(f"Skipping item with missing task_id or question: {item}") continue try: submitted_answer = agent(question_text, task_id=task_id) print(f"Answer for task {task_id}: '{submitted_answer}'") model_answer = agent(question_text, task_id=task_id) print(f"Answer for task {task_id}: '{model_answer}'") answers_payload.append({ "task_id": task_id, "submitted_answer": submitted_answer, # "reasoning_trace": None # optional, add if available "model_answer": model_answer, # "reasoning_trace": None # Add reasoning trace here if available }) results_log.append({ "Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer "Submitted Answer": model_answer }) except Exception as e: print(f"Error running agent on task {task_id}: {e}") answers_payload.append({ "task_id": task_id, "submitted_answer": f"AGENT ERROR: {e}", "model_answer": f"AGENT ERROR: {e}", # "reasoning_trace": None }) results_log.append({6 unmodified lines print("Agent did not produce any answers to submit.") return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
# 4. Prepare Submission submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload} status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..." print(status_update)
print(submission_data)
# 5. Submit print(f"Submitting {len(answers_payload)} answers to: {submit_url}") # Serialize answers to JSON Lines format json_lines_str = "\n".join(json.dumps(ans, ensure_ascii=False) for ans in answers_payload) file_like = io.BytesIO(json_lines_str.encode("utf-8")) file_like.name = "submission.jsonl"
data = { "username": username.strip(), "agent_code": agent_code } files = { "file": (file_like.name, file_like, "application/jsonl") }
print(f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'...") print("Submission payload preview (first 3 answers):") for ans in answers_payload[:3]: print(json.dumps(ans, ensure_ascii=False))
print(f"Submitting answers to: {submit_url}") try: response = requests.post(submit_url, json=submission_data, timeout=60) response = requests.post(submit_url, data=data, files=files, timeout=60) response.raise_for_status() result_data = response.json() final_status = (app.py+43-46