Spaces:
Build error
Build error
Update app.py
Browse files1234567891011121314154 unmodified lines202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394951 unmodified line97989910010110210350 unmodified lines154155156157158159120 unmodified lines280281282283""" Basic Agent Evaluation Runner"""import osimport inspectimport gradio as grimport requestsimport pandas as pdfrom langchain_core.messages import HumanMessagefrom langgraph_agent import build_graphfrom langchain_google_genai import ChatGoogleGenerativeAIimport jsonimport csvimport ast # Added this here to ensure it's at top level# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"4 unmodified linesdef __init__(self):print("BasicAgent initialized.")self.graph = build_graph()self.csv_taskid_to_answer = {}try:with open("questions.csv", "r", encoding="utf-8") as f:reader = csv.DictReader(f)for row in reader:# metadata is a string like: {'task_id': 'c61d22de-5f6c-4958-a7f6-5e9707bd3466', 'level': 2}meta = row.get("metadata", "")if "task_id" in meta:# Extract task_id from the metadata string# FIX: Moved import ast and try-except block here# import ast # Moved to top level for consistency, but if needed specifically here, keep it.try:meta_dict = ast.literal_eval(meta)task_id = meta_dict.get("task_id")except Exception:task_id = Noneif task_id:# Extract answer from content (after 'Final answer :')content = row.get("content", "")if "Final answer :" in content:answer = content.split("Final answer :",1)[1].strip().split("\n")[0].strip()self.csv_taskid_to_answer[task_id] = answerexcept Exception as e:print(f"Warning: Could not load test_questions.csv: {e}")# This is the correct __call__ method based on our previous discussions,# and it was indented correctly relative to the class.def __call__(self, question: str, task_id: str = None) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")messages = [HumanMessage(content=question)]messages = self.graph.invoke({"messages": messages})# Retrieve the content of the last message# If messages list is empty or the last message has no content,# default to an "unable to determine" string.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 # Keep the original variable name 'answer'# If the content is an empty list, explicitly return the "unable to determine" string.if isinstance(answer, list) and not answer:return "I am unable to determine the information using the available tools."# If the content is not a string, convert it to a string.if not isinstance(answer, str):answer = str(answer)# Process the answer to remove "FINAL ANSWER: " prefix if present.# This moves the slicing logic to before the return statement.if answer.startswith("FINAL ANSWER: "):# If the answer starts with the expected prefix, remove it.answer = answer[14:].strip()else:# If the prefix is not found, just strip whitespace from the answer.# This handles cases where the agent might not perfectly adhere to the format.answer = answer.strip()# Return the processed answer, without any slicing here.return answer# This `def __call__` method was a duplicate and had incorrect indentation relative to the class.# It has been removed in this corrected version.# def __call__(self, question: str, task_id: str = None) -> str:# print(f"Agent received question (first 50 chars): {question[:50]}...")# messages = [HumanMessage(content=question)]# messages = self.graph.invoke({"messages": messages})# answer = messages['messages'][-1].content# return answer[14:]def run_and_submit_all(profile: gr.OAuthProfile | None):1 unmodified lineFetches all questions, runs the BasicAgent on them, submits all answers,and displays the results."""# Determine HF Space Runtime URL and Repo URLspace_id = os.getenv("SPACE_ID")if profile:50 unmodified linescontinuetry:submitted_answer = agent(question_text, task_id=task_id)answers_payload.append({"task_id": task_id,"submitted_answer": submitted_answer120 unmodified linesprint("-" * (60 + len(" App Starting ")) + "\n")print("Launching Gradio Interface for Basic Agent Evaluation...")demo.launch(debug=True, share=False)1234567894 unmodified lines1415161718192021222324252627282930313233343536373839404142434445464748495051521 unmodified line54555657585950 unmodified lines110111112113114115116120 unmodified lines237238239240import osimport gradio as grimport requestsimport pandas as pdfrom langchain_core.messages import HumanMessagefrom langgraph_agent import build_graph# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"4 unmodified linesdef __init__(self):print("BasicAgent initialized.")self.graph = build_graph()def __call__(self, question: str, task_id: str = None) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")messages = [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):1 unmodified lineFetches all questions, runs the BasicAgent on them, submits all answers,and displays the results."""space_id = os.getenv("SPACE_ID")if profile:50 unmodified linescontinuetry:submitted_answer = agent(question_text, task_id=task_id)print(f"Submitting answer for task {task_id}: '{submitted_answer}'")answers_payload.append({"task_id": task_id,"submitted_answer": submitted_answer120 unmodified linesprint("-" * (60 + len(" App Starting ")) + "\n")print("Launching Gradio Interface for Basic Agent Evaluation...")demo.launch(debug=True, share=False)
app.py+20-63