Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191 unmodified line121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206import osimport inspectimport gradio as grimport requestsimport pandas as pdfrom langchain_core.messages import HumanMessagefrom agent import build_graph# (Keep Constants as is)# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"# --- Basic Agent Definition ---# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------class BasicAgent:"""A langgraph agent."""def __init__(self):print("BasicAgent initialized.")self.graph = build_graph()def __call__(self, question: str) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")# Wrap the question in a HumanMessage from langchain_coremessages = [HumanMessage(content=question)]messages = self.graph.invoke({"messages": messages})answer = messages['messages'][-1].contentreturn answer[14:]def run_and_submit_all( profile: gr.OAuthProfile | None):"""Fetches all questions, runs the BasicAgent on them, submits all answers,and displays the results."""# --- Determine HF Space Runtime URL and Repo URL ---space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the codeif profile:username= f"{profile.username}"print(f"User logged in: {username}")else:print("User not logged in.")return "Please Login to Hugging Face with the button.", Noneapi_url = DEFAULT_API_URLquestions_url = f"{api_url}/questions"submit_url = f"{api_url}/submit"# 1. Instantiate Agent ( modify this part to create your agent)try:agent = BasicAgent()except Exception as e:print(f"Error instantiating agent: {e}")return f"Error initializing agent: {e}", None# In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)agent_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)response.raise_for_status()questions_data = response.json()if not questions_data:print("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 = []print(f"Running agent on {len(questions_data)} questions...")for item in questions_data:task_id = item.get("task_id")question_text = item.get("question")if not task_id or question_text is None:print(f"Skipping item with missing task_id or question: {item}")continuetry:submitted_answer = agent(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 Exception as e:print(f"Error running agent on task {task_id}: {e}")results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})if not answers_payload:print("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)# 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 = (f"Submission Successful!\n"f"User: {result_data.get('username')}\n"1 unmodified linef"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"f"Message: {result_data.get('message', 'No message received.')}")print("Submission successful.")results_df = pd.DataFrame(results_log)return final_status, results_dfexcept requests.exceptions.HTTPError as e:error_detail = f"Server responded with status {e.response.status_code}."try:error_json = e.response.json()error_detail += f" Detail: {error_json.get('detail', e.response.text)}"except requests.exceptions.JSONDecodeError:error_detail += f" Response: {e.response.text[:500]}"status_message = f"Submission Failed: {error_detail}"print(status_message)results_df = pd.DataFrame(results_log)return status_message, results_dfexcept requests.exceptions.Timeout:status_message = "Submission Failed: The request timed out."print(status_message)results_df = pd.DataFrame(results_log)return status_message, results_dfexcept requests.exceptions.RequestException as e:status_message = f"Submission Failed: Network error - {e}"print(status_message)results_df = pd.DataFrame(results_log)return status_message, results_dfexcept Exception as e:status_message = f"An unexpected error occurred during submission: {e}"print(status_message)results_df = pd.DataFrame(results_log)return status_message, results_df# --- Build Gradio Interface using Blocks ---with gr.Blocks() as demo:gr.Markdown("# Basic Agent Evaluation Runner")gr.Markdown("""**Instructions:**1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.---**Disclaimers:**Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.""")gr.LoginButton()run_button = gr.Button("Run Evaluation & Submit All Answers")status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)# Removed max_rows=10 from DataFrame constructorresults_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)run_button.click(fn=run_and_submit_all,outputs=[status_output, results_table])if __name__ == "__main__":print("\n" + "-"*30 + " App Starting " + "-"*30)# Check for SPACE_HOST and SPACE_ID at startup for informationspace_host_startup = os.getenv("SPACE_HOST")space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startupif space_host_startup:print(f"✅ SPACE_HOST found: {space_host_startup}")print(f" Runtime URL should be: https://{space_host_startup}.hf.space")else:print("ℹ️ SPACE_HOST environment variable not found (running locally?).")if space_id_startup: # Print repo URLs if SPACE_ID is foundprint(f"✅ SPACE_ID found: {space_id_startup}")print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")else:print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")print("-"*(60 + len(" App Starting ")) + "\n")print("Launching Gradio Interface for Basic Agent Evaluation...")demo.launch(debug=True, share=False)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462471 unmodified line249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367"""Agent Evaluation Runner======================This module implements a framework for evaluating LLM agents against a set of questionsand submitting the results to a scoring server.Main components:- BasicAgent: The agent implementation that processes questions- Evaluation functions: For running and submitting results- Gradio interface: For user interaction"""import osimport loggingfrom typing import Tuple, List, Dict, Any, Optionalimport gradio as grimport requestsimport pandas as pdfrom langchain_core.messages import HumanMessagefrom agent import build_graph# Configure logginglogging.basicConfig(level=logging.INFO,format="%(asctime)s - %(levelname)s - %(message)s",datefmt="%Y-%m-%d %H:%M:%S")logger = logging.getLogger(__name__)# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"REQUEST_TIMEOUT = 60 # secondsclass BasicAgent:"""A LangGraph-based agent that answers questions using a graph-based workflow.This agent takes natural language questions, processes them through apredefined graph workflow, and returns the answer.Attributes:graph: The LangGraph workflow that processes the questions"""def __init__(self):"""Initialize the agent with a graph-based workflow."""logger.info("Initializing BasicAgent")self.graph = build_graph()def __call__(self, question: str) -> str:"""Process a question and return an answer.Args:question: The natural language question to processReturns:The agent's answer to the question"""logger.info(f"Processing question (first 50 chars): {question[:50]}...")# Wrap the question in a HumanMessage from langchain_coremessages = [HumanMessage(content=question)]# Process through the graphmessages = self.graph.invoke({"messages": messages})# Extract and clean the answeranswer = messages['messages'][-1].content# Remove the "FINAL ANSWER:" prefix if presentreturn answer[14:] if answer.startswith("FINAL ANSWER:") else answerdef fetch_questions(api_url: str) -> List[Dict[str, Any]]:"""Fetch questions from the evaluation server.Args:api_url: Base URL of the evaluation APIReturns:List of question data dictionariesRaises:requests.exceptions.RequestException: If there's an error fetching questions"""questions_url = f"{api_url}/questions"logger.info(f"Fetching questions from: {questions_url}")response = requests.get(questions_url, timeout=REQUEST_TIMEOUT)response.raise_for_status()questions_data = response.json()if not questions_data:raise ValueError("Fetched questions list is empty or invalid format")logger.info(f"Successfully fetched {len(questions_data)} questions")return questions_datadef run_agent_on_questions(agent: BasicAgent,questions_data: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:"""Run the agent on a list of questions.Args:agent: The agent to runquestions_data: List of question data dictionariesReturns:Tuple of (answers_payload, results_log)"""results_log = []answers_payload = []logger.info(f"Running agent on {len(questions_data)} questions...")for item in questions_data:task_id = item.get("task_id")question_text = item.get("question")if not task_id or question_text is None:logger.warning(f"Skipping item with missing task_id or question: {item}")continuetry:submitted_answer = agent(question_text)# Prepare answer for submissionanswers_payload.append({"task_id": task_id,"submitted_answer": submitted_answer})# Log result for displayresults_log.append({"Task ID": task_id,"Question": question_text,"Submitted Answer": submitted_answer})except Exception as e:logger.error(f"Error running agent on task {task_id}: {e}", exc_info=True)# Log error in resultsresults_log.append({"Task ID": task_id,"Question": question_text,"Submitted Answer": f"AGENT ERROR: {e}"})return answers_payload, results_logdef submit_answers(api_url: str,username: str,agent_code: str,answers_payload: List[Dict[str, Any]]) -> Dict[str, Any]:"""Submit answers to the evaluation server.Args:api_url: Base URL of the evaluation APIusername: Hugging Face usernameagent_code: URL to the agent code repositoryanswers_payload: List of answer dictionariesReturns:Response data from the serverRaises:requests.exceptions.RequestException: If there's an error during submission"""submit_url = f"{api_url}/submit"# Prepare submission datasubmission_data = {"username": username.strip(),"agent_code": agent_code,"answers": answers_payload}logger.info(f"Submitting {len(answers_payload)} answers to: {submit_url}")# Submit answersresponse = requests.post(submit_url, json=submission_data, timeout=REQUEST_TIMEOUT)response.raise_for_status()result_data = response.json()logger.info("Submission successful")return result_datadef run_and_submit_all(profile: Optional[gr.OAuthProfile] = None) -> Tuple[str, pd.DataFrame]:"""Fetches all questions, runs the BasicAgent on them, submits all answers,and displays the results.Args:profile: Gradio OAuth profile containing user informationReturns:Tuple of (status_message, results_dataframe)"""# Check if user is logged inif not profile:logger.warning("User not logged in")return "Please Login to Hugging Face with the button.", Noneusername = profile.usernamelogger.info(f"User logged in: {username}")# Get the space ID for linking to codespace_id = os.getenv("SPACE_ID")api_url = DEFAULT_API_URLagent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"try:# 1. Instantiate Agentagent = BasicAgent()# 2. Fetch Questionsquestions_data = fetch_questions(api_url)# 3. Run Agent on Questionsanswers_payload, results_log = run_agent_on_questions(agent, questions_data)if not answers_payload:logger.warning("Agent did not produce any answers to submit")return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)# 4. Submit Answersresult_data = submit_answers(api_url, username, agent_code, answers_payload)# 5. Format and Return Resultsfinal_status = (f"Submission Successful!\n"f"User: {result_data.get('username')}\n"1 unmodified linef"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"f"Message: {result_data.get('message', 'No message received.')}")results_df = pd.DataFrame(results_log)return final_status, results_dfexcept requests.exceptions.HTTPError as e:# Handle HTTP errors with detailed error informationerror_detail = f"Server responded with status {e.response.status_code}."try:error_json = e.response.json()error_detail += f" Detail: {error_json.get('detail', e.response.text)}"except requests.exceptions.JSONDecodeError:error_detail += f" Response: {e.response.text[:500]}"status_message = f"Submission Failed: {error_detail}"logger.error(status_message)results_df = pd.DataFrame(results_log if 'results_log' in locals() else [])return status_message, results_dfexcept requests.exceptions.Timeout:status_message = f"Submission Failed: The request timed out after {REQUEST_TIMEOUT} seconds"logger.error(status_message)results_df = pd.DataFrame(results_log if 'results_log' in locals() else [])return status_message, results_dfexcept Exception as e:status_message = f"An unexpected error occurred: {str(e)}"logger.error(status_message, exc_info=True)results_df = pd.DataFrame(results_log if 'results_log' in locals() else [])return status_message, results_dfdef create_gradio_interface() -> gr.Blocks:"""Create and configure the Gradio interface.Returns:Configured Gradio Blocks interface"""with gr.Blocks() as demo:gr.Markdown("# Agent Evaluation Runner")gr.Markdown("""## Instructions1. **Clone this space** and modify the code to define your agent's logic, tools, and dependencies2. **Log in to your Hugging Face account** using the button below (required for submission)3. **Run Evaluation** to fetch questions, run your agent, and submit answers## Important Notes- The evaluation process may take several minutes to complete- This agent framework is intentionally minimal to allow for your own improvements- Consider implementing caching or async processing for better performance""")gr.LoginButton()run_button = gr.Button("Run Evaluation & Submit All Answers", variant="primary")status_output = gr.Textbox(label="Run Status / Submission Result",lines=5,interactive=False)results_table = gr.DataFrame(label="Questions and Agent Answers",wrap=True)run_button.click(fn=run_and_submit_all,outputs=[status_output, results_table])return demodef check_environment() -> None:"""Check and log environment variables at startup."""logger.info("-" * 30 + " App Starting " + "-" * 30)# Check for SPACE_HOSTspace_host = os.getenv("SPACE_HOST")if space_host:logger.info(f"✅ SPACE_HOST found: {space_host}")logger.info(f" Runtime URL should be: https://{space_host}.hf.space")else:logger.info("ℹ️ SPACE_HOST environment variable not found (running locally?).")# Check for SPACE_IDspace_id = os.getenv("SPACE_ID")if space_id:logger.info(f"✅ SPACE_ID found: {space_id}")logger.info(f" Repo URL: https://huggingface.co/spaces/{space_id}")logger.info(f" Repo Tree URL: https://huggingface.co/spaces/{space_id}/tree/main")else:logger.info("ℹ️ SPACE_ID environment variable not found (running locally?).")logger.info("-" * (60 + len(" App Starting ")) + "\n")if __name__ == "__main__":# Check environment at startupcheck_environment()# Create and launch Gradio interfacelogger.info("Launching Gradio Interface for Agent Evaluation...")demo = create_gradio_interface()demo.launch(debug=True, share=False)
app.py+292-131