Spaces:
Build error
Build error
Update app.py
Browse files2 unmodified lines34567812 unmodified lines212223242526272829303132333435363738394041424344454647484950515253545556575859607 unmodified lines686970717273743 unmodified lines787980818283843 unmodified lines8889909192939495969798991001011021031041055 unmodified lines1111121131141151161171181191201211221231241251261271281291301311321336 unmodified lines1401411421431441451461471481491501511521531541551561571581592 unmodified linesimport requestsimport pandas as pdimport jsonfrom langchain_core.messages import HumanMessagefrom langgraph_agent import build_graph12 unmodified linesmessages = [HumanMessage(content=question)]messages = self.graph.invoke({"messages": messages})# Check if messages or content is missingif 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 contentif isinstance(answer, list) and not answer:return "I am unable to determine the information using the available tools."# Convert non-string answers to stringif not isinstance(answer, str):answer = str(answer)# Normalize and strip common answer prefixesanswer = 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 explicitlyif not answer or answer.strip() in ['""', "''"]:answer = "I am unable to determine the information using the available tools."return answerdef 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 linesquestions_url = f"{api_url}/questions"submit_url = f"{api_url}/submit"# 1. Instantiate Agenttry:agent = BasicAgent()except Exception as e:3 unmodified linesagent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"print(agent_code)# 2. Fetch Questionsprint(f"Fetching questions from: {questions_url}")try:response = requests.get(questions_url, timeout=15)3 unmodified linesprint("Fetched questions list is empty.")return "Fetched questions list is empty or invalid format.", Noneprint(f"Fetched {len(questions_data)} questions.")except requests.exceptions.RequestException as e:print(f"Error fetching questions: {e}")return f"Error fetching questions: {e}", Noneexcept 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}", Noneexcept 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 Agentresults_log = []answers_payload = []5 unmodified linesprint(f"Skipping item with missing task_id or question: {item}")continuetry:submitted_answer = agent(question_text, task_id=task_id)print(f"Answer for task {task_id}: '{submitted_answer}'")answers_payload.append({"task_id": task_id,"submitted_answer": submitted_answer,# "reasoning_trace": None # optional, add if available})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}")answers_payload.append({"task_id": task_id,"submitted_answer": f"AGENT ERROR: {e}",# "reasoning_trace": None})results_log.append({6 unmodified linesprint("Agent did not produce any answers to submit.")return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)# 4. Prepare Submissionsubmission_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. Submitprint(f"Submitting {len(answers_payload)} answers to: {submit_url}")try:response = requests.post(submit_url, json=submission_data, timeout=60)response.raise_for_status()result_data = response.json()final_status = (2 unmodified lines34567891012 unmodified lines23242526272829303132333435363738394041424344454647484950515253545556575859607 unmodified lines6869707172733 unmodified lines7778798081823 unmodified lines868788899091929394955 unmodified lines1011021031041051061071081091101111121131141151161171181191201211221236 unmodified lines1301311321331341351361371381391401411421431441451461471481491501511521531541551562 unmodified linesimport requestsimport pandas as pdimport jsonimport ioimport refrom langchain_core.messages import HumanMessagefrom langgraph_agent import build_graph12 unmodified linesmessages = [HumanMessage(content=question)]messages = self.graph.invoke({"messages": messages})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].contentif isinstance(answer, list) and not answer:return "I am unable to determine the information using the available tools."if not isinstance(answer, str):answer = str(answer)answer = answer.strip()# 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 presentif (final_answer.startswith('"') and final_answer.endswith('"')) or \(final_answer.startswith("'") and final_answer.endswith("'")):final_answer = final_answer[1:-1].strip()answer = final_answerelse: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 answerdef run_and_submit_all(profile: gr.OAuthProfile | None):space_id = os.getenv("SPACE_ID")if profile:7 unmodified linesquestions_url = f"{api_url}/questions"submit_url = f"{api_url}/submit"try:agent = BasicAgent()except Exception as e:3 unmodified linesagent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"print(agent_code)print(f"Fetching questions from: {questions_url}")try:response = requests.get(questions_url, timeout=15)3 unmodified linesprint("Fetched questions list is empty.")return "Fetched questions list is empty or invalid format.", Noneprint(f"Fetched {len(questions_data)} questions.")except Exception as e:print(f"Error fetching questions: {e}")return f"Error fetching questions: {e}", Noneresults_log = []answers_payload = []5 unmodified linesprint(f"Skipping item with missing task_id or question: {item}")continuetry: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,"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": model_answer})except Exception as e:print(f"Error running agent on task {task_id}: {e}")answers_payload.append({"task_id": task_id,"model_answer": f"AGENT ERROR: {e}",# "reasoning_trace": None})results_log.append({6 unmodified linesprint("Agent did not produce any answers to submit.")return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)# Serialize answers to JSON Lines formatjson_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, data=data, files=files, timeout=60)response.raise_for_status()result_data = response.json()final_status = (
app.py+43-46