Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445461 unmodified line48495051525354555657585960616263646566676869707172737475767778798081828384851 unmodified line87888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306import osimport reimport gradio as grimport requestsimport pandas as pdfrom smolagents import CodeAgent, DuckDuckGoSearchToolfrom smolagents.models import OpenAIServerModel# ---------------------------------------------------# Constants# ---------------------------------------------------DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"# ---------------------------------------------------# Agent# ---------------------------------------------------class BasicAgent:def __init__(self):print("Initializing Groq Agent...")self.model = OpenAIServerModel(model_id="llama-3.3-70b-versatile",api_base="https://api.groq.com/openai/v1",api_key=os.getenv("GROQ_API_KEY"))self.agent = CodeAgent(tools=[DuckDuckGoSearchTool()],model=self.model,max_steps=3,verbosity_level=0)print("Groq Agent initialized.")# ---------------------------------------------------# Clean outputs for exact-match grading# ---------------------------------------------------def clean_answer(self, text):if text is None:1 unmodified linetext = str(text)# remove markdown/codetext = text.replace("```", "")text = text.replace("FINAL ANSWER:", "")text = text.replace("Answer:", "")# remove excessive whitespacetext = re.sub(r"\s+", " ", text)# first line onlytext = text.split("\n")[0]# concisetext = text.strip()return text[:300]# ---------------------------------------------------# Run agent# ---------------------------------------------------def __call__(self, question: str) -> str:prompt = f"""You are solving a GAIA benchmark question.IMPORTANT:- Return ONLY the final answer.- No reasoning.- No explanations.- No markdown.- No bullet points.- Be concise and accurate.- Use web search if needed.Question:{question}1 unmodified linetry:result = self.agent.run(prompt)cleaned = self.clean_answer(result)print(f"\nQUESTION:\n{question}")print(f"\nANSWER:\n{cleaned}")return cleanedexcept Exception as e:print(f"Agent error: {e}")return ""# ---------------------------------------------------# Evaluation + Submission# ---------------------------------------------------def run_and_submit_all(profile: gr.OAuthProfile | None):space_id = os.getenv("SPACE_ID")# Login checkif profile:username = profile.usernameprint(f"Logged in as: {username}")else:return "Please login with Hugging Face.", Noneapi_url = DEFAULT_API_URLquestions_url = f"{api_url}/questions"submit_url = f"{api_url}/submit"# ---------------------------------------------------# Initialize Agent# ---------------------------------------------------try:agent = BasicAgent()except Exception as e:print(f"Initialization error: {e}")return f"Error initializing agent: {e}", None# Space repo linkagent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"# ---------------------------------------------------# Fetch Questions# ---------------------------------------------------try:print("Fetching questions...")response = requests.get(questions_url,timeout=30)response.raise_for_status()questions_data = response.json()print(f"Fetched {len(questions_data)} questions.")except Exception as e:print(f"Question fetch error: {e}")return f"Error fetching questions: {e}", None# ---------------------------------------------------# Run Agent# ---------------------------------------------------answers_payload = []results_log = []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:continueprint(f"\nRunning task {task_id}")try: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"Task error: {e}")results_log.append({"Task ID": task_id,"Question": question_text,"Submitted Answer": f"ERROR: {e}"})# ---------------------------------------------------# Submit# ---------------------------------------------------submission_data = {"username": username.strip(),"agent_code": agent_code,"answers": answers_payload}try:print("Submitting answers...")response = requests.post(submit_url,json=submission_data,timeout=120)response.raise_for_status()result_data = response.json()final_status = (f"Submission Successful!\n\n"f"User: {result_data.get('username')}\n"f"Score: {result_data.get('score', 'N/A')}%\n"f"Correct: "f"{result_data.get('correct_count', '?')}/"f"{result_data.get('total_attempted', '?')}\n\n"f"Message: {result_data.get('message', '')}")print(final_status)return final_status, pd.DataFrame(results_log)except Exception as e:error_message = f"Submission failed: {e}"print(error_message)return error_message, pd.DataFrame(results_log)# ---------------------------------------------------# UI# ---------------------------------------------------with gr.Blocks() as demo:gr.Markdown("# Hugging Face Agents Course - Final Assignment")gr.Markdown("""This agent uses:- Groq API- Llama 3.3 70B- smolagents- DuckDuckGo Search""")gr.LoginButton()run_button = gr.Button("Run Evaluation & Submit")status_output = gr.Textbox(label="Submission Result",lines=8,interactive=False)results_table = gr.DataFrame(label="Agent Answers",wrap=True)run_button.click(fn=run_and_submit_all,outputs=[status_output,results_table])# ---------------------------------------------------# Launch# ---------------------------------------------------if __name__ == "__main__":print("\n==============================")print("Starting Groq Agent...")print("==============================\n")demo.launch(debug=True,share=False)12345678910111213141516171 unmodified line1920212223242526272829303132333435363738394041421 unmodified line44454647484950515253545556575859606162class BasicAgent:def __init__(self):print("Initializing Fast Groq Agent...")self.model = OpenAIServerModel(model_id="llama-3.1-8b-instant",api_base="https://api.groq.com/openai/v1",api_key=os.getenv("GROQ_API_KEY"))print("Fast agent ready.")def clean_answer(self, text):if text is None:1 unmodified linetext = str(text)text = text.replace("```", "")text = text.replace("FINAL ANSWER:", "")text = text.replace("Answer:", "")text = text.strip().split("\n")[0]return text[:200]def __call__(self, question: str) -> str:prompt = f"""Answer the question.IMPORTANT:- Return ONLY the final answer.- No reasoning.- No explanation.- Keep answers concise.Question:{question}1 unmodified linetry:response = self.model(prompt,max_tokens=80)cleaned = self.clean_answer(response)print(cleaned)return cleanedexcept Exception as e:print(e)return ""
app.py+16-260