Spaces:
Runtime error
Runtime error
Update app.py
Browse files2 unmodified lines3456789101112131415161718192021222316 unmodified lines4041424344454647484992 unmodified lines1421431441451461471481491501511521531541551561571581591601611621631641651661671681691701 unmodified line17217317417517617717811 unmodified lines1901911921931941951962 unmodified linesimport requestsimport inspectimport pandas as pd# (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:def __init__(self):print("BasicAgent initialized.")def __call__(self, question: str) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")fixed_answer = "This is a default answer."print(f"Agent returning fixed answer: {fixed_answer}")return fixed_answerdef run_and_submit_all( profile: gr.OAuthProfile | None):"""16 unmodified lines# 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)92 unmodified lines# --- 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,1 unmodified line)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 startup11 unmodified lineselse: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)2 unmodified lines345678910111213141516171819202122232425262728293031323334353637383940414243444546474816 unmodified lines6566676869707172737492 unmodified lines1671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981991 unmodified line20120220320420520620711 unmodified lines2192202212222232242252 unmodified linesimport requestsimport inspectimport pandas as pdfrom crewai_agent import CrewAIAgent# (Keep Constants as is)# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"# --- CrewAI Agent Definition ---# ----- THIS IS WHERE YOU CAN BUILD WHAT YOU WANT ------class CrewAIBasicAgent:"""Wrapper class for CrewAI agent to match the expected interface."""def __init__(self, provider: str = "google"):print(f"CrewAI Agent initialized with provider: {provider}")try:self.agent = CrewAIAgent(provider=provider)print("CrewAI Agent successfully initialized.")except Exception as e:print(f"Error initializing CrewAI Agent: {e}")# Fallback to simple agentself.agent = Nonedef __call__(self, question: str) -> str:"""Process question using CrewAI agent."""print(f"CrewAI Agent received question (first 50 chars): {question[:50]}...")if self.agent is None:# Fallback response if agent failed to initializefallback_answer = "CrewAI agent initialization failed. Using fallback response."print(f"Using fallback answer: {fallback_answer}")return fallback_answertry:# Use the CrewAI agent to process the questionanswer = self.agent(question)print(f"CrewAI Agent generated answer (first 100 chars): {answer[:100]}...")return answerexcept Exception as e:error_msg = f"Error in CrewAI agent processing: {str(e)}"print(error_msg)return error_msgdef run_and_submit_all( profile: gr.OAuthProfile | None):"""16 unmodified lines# 1. Instantiate Agent ( modify this part to create your agent)try:agent = CrewAIBasicAgent(provider="google") # Using CrewAI agent instead of BasicAgentexcept Exception as e:print(f"Error instantiating CrewAI agent: {e}")return f"Error initializing CrewAI 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)92 unmodified lines# --- Build Gradio Interface using Blocks ---with gr.Blocks() as demo:gr.Markdown("# CrewAI Multi-Purpose Agent Evaluation Runner")gr.Markdown("""**CrewAI Agent Features:**- **Multi-Agent Architecture**: Specialized agents for different types of tasks- **Research Capabilities**: Search Wikipedia, ArXiv papers, and web sources- **Mathematical Operations**: Perform calculations and solve mathematical problems- **Intelligent Task Routing**: Automatically selects the best agent for each question**Instructions:**1. Please clone this space, then modify the code to define your CrewAI agent's logic, tools, and packages2. Add your API keys to the `.env` file (Google, Tavily, etc.)3. Log in to your Hugging Face account using the button below4. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your CrewAI agent, and see the score---**Note:** The CrewAI agent uses multiple specialized agents working together to provide comprehensive answers.This may take longer than a basic agent but provides much more intelligent responses.""")gr.LoginButton()run_button = gr.Button("Run CrewAI 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 CrewAI Agent Answers", wrap=True)run_button.click(fn=run_and_submit_all,1 unmodified line)if __name__ == "__main__":print("\n" + "-"*30 + " CrewAI 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 startup11 unmodified lineselse:print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")print("-"*(60 + len(" CrewAI App Starting ")) + "\n")print("Launching Gradio Interface for CrewAI Multi-Purpose Agent...")demo.launch(debug=True, share=False)
app.py+55-26