Spaces:
Sleeping
Sleeping
Update app.py
Browse files1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481 unmodified lineimport gradio as grimport requestsimport pandas as pdimport subprocessimport sys # Import sys# --- START: Force DDGS installation workaround ---try:# Check if duckduckgo_search (provided by ddgs) can be importedimport duckduckgo_searchprint("duckduckgo_search (via ddgs) is already installed.")except ImportError:print("duckduckgo_search not found. Attempting to install ddgs...")try:# Use ddgs as it's the updated package namesubprocess.check_call([sys.executable, "-m", "pip", "install", "ddgs>=4.0.0"])print("ddgs installed successfully.")except Exception as e:print(f"Failed to install ddgs: {e}")# Critical error, re-raise to stop startup if essential dependency failsraise RuntimeError(f"CRITICAL: Failed to install ddgs: {e}")# --- END: Force DDGS installation workaround ---from agent import GaiaAgent # This line should now run after ddgs is confirmed installedDEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"def run_and_submit_all(profile: gr.OAuthProfile | None):space_id = os.getenv("SPACE_ID")if 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"try:agent = GaiaAgent()except Exception as e:return f"Error initializing agent: {e}", Noneagent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"try:response = requests.get(questions_url, timeout=15)response.raise_for_status()questions_data = response.json()except Exception as e:return f"Error fetching questions: {e}", Noneresults_log = []answers_payload = []print("\n--- STARTING AGENT RUN ---")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:continuetry:final_answer, trace = agent(question_text)print("\n--- QUESTION ---")print(f"Task ID: {task_id}")print(f"Question: {question_text}")print("\n--- REASONING TRACE ---")print(trace)print("\n--- FINAL ANSWER (SUBMITTED) ---")print(final_answer)answers_payload.append({"task_id": task_id,"submitted_answer": final_answer,"reasoning_trace": trace})results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": final_answer})except Exception as e:results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"ERROR: {e}"})if not answers_payload:return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)submission_data = {"username": username.strip(),"agent_code": agent_code,"answers": answers_payload}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"f"Overall Score: {result_data.get('score', 'N/A')}% "f"({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 Exception as e:return f"Submission Failed: {e}", pd.DataFrame(results_log)with gr.Blocks() as demo:gr.Markdown("# GAIA Agent Submission Interface")gr.Markdown("""Logga in och kör agenten.\nDu behöver INTE en OpenAI API-nyckel längre. Agenten kör en lokal modell.""")gr.LoginButton()run_button = gr.Button("Run Evaluation & Submit All Answers")status_output = gr.Textbox(label="Submission Result")results_table = gr.DataFrame(label="Answers")run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])if __name__ == "__main__":print("\n" + "-"*30 + " App Starting " + "-"*30)space_host_startup = os.getenv("SPACE_HOST")space_id_startup = os.getenv("SPACE_ID")if 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(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)1 unmodified line23456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172731 unmodified lineimport gradio as grimport requestsimport pandas as pdimport subprocess # Needed for runtime pip installimport sys # Needed for runtime pip install# --- START: Force ddgs installation workaround ---# This block ensures 'ddgs' (which provides 'duckduckgo_search') is installed# early, before smolagents tries to use its DuckDuckGoSearchTool.try:# Attempt to import duckduckgo_search to check if it's already availableimport duckduckgo_searchprint("duckduckgo_search (via ddgs) is already installed.")except ImportError:print("duckduckgo_search not found. Attempting to install ddgs...")try:# Use 'ddgs' as it's the updated package namesubprocess.check_call([sys.executable, "-m", "pip", "install", "ddgs>=4.0.0"])print("ddgs installed successfully.")except Exception as e:print(f"Failed to install ddgs: {e}")# Critical error: if ddgs can't be installed, the app can't function.raise RuntimeError(f"CRITICAL: Failed to install ddgs: {e}")# --- END: Force ddgs installation workaround ---# Now import the agent, as its dependencies (smolagents, duckduckgo_search) should be readyfrom agent import GaiaAgentDEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"def run_agent_and_score(task_description: str) -> str:# Initialize the agent within the function, so it's fresh for each run# This also helps if the agent initialization is heavy or statefulgaia_agent = GaiaAgent()# Process the taskagent_output = gaia_agent.process_task(task_description)# Send output to the scoring APItry:response = requests.post(f"{DEFAULT_API_URL}/score_agent",json={"task_description": task_description, "agent_response": agent_output})response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)scoring_result = response.json()score_info = f"Scoring Result:\nTotal Score: {scoring_result.get('total_score')}\nCorrectness Score: {scoring_result.get('correctness_score')}\nExplanation: {scoring_result.get('explanation', 'No explanation provided.')}"return f"Agent Output:\n{agent_output}\n\n---\n\n{score_info}"except requests.exceptions.RequestException as e:return f"Agent Output:\n{agent_output}\n\n---\n\nError connecting to scoring API: {e}"except Exception as e:return f"Agent Output:\n{agent_output}\n\n---\n\nAn unexpected error occurred during scoring: {e}"# Gradio Interface setupwith gr.Blocks() as demo:gr.Markdown("# GAIA Basic Agent Evaluator (Freddolin)")gr.Markdown("Enter a task description for the agent to process. The agent's output will be displayed, followed by its score from the GAIA scoring API.")task_input = gr.Textbox(label="Task Description", placeholder="e.g., 'What is the capital of France?'")output_text = gr.Textbox(label="Agent Output & Score", interactive=False)run_button = gr.Button("Run Agent & Score")run_button.click(fn=run_agent_and_score,inputs=task_input,outputs=output_text)# Launch the Gradio appdemo.launch(debug=True) # debug=True can provide more info in logs during development
app.py+43-118