Freddolin commited on
Commit
3bad015
·
verified ·
1 Parent(s): 8bfc54d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +157 -52
app.py CHANGED
@@ -1,73 +1,178 @@
1
  import os
2
  import gradio as gr
3
  import requests
 
4
  import pandas as pd
5
- import subprocess # Needed for runtime pip install
6
- import sys # Needed for runtime pip install
7
 
8
- # --- START: Force ddgs installation workaround ---
9
- # This block ensures 'ddgs' (which provides 'duckduckgo_search') is installed
10
- # early, before smolagents tries to use its DuckDuckGoSearchTool.
11
- try:
12
- # Attempt to import duckduckgo_search to check if it's already available
13
- import duckduckgo_search
14
- print("duckduckgo_search (via ddgs) is already installed.")
15
- except ImportError:
16
- print("duckduckgo_search not found. Attempting to install ddgs...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  try:
18
- # Use 'ddgs' as it's the updated package name
19
- subprocess.check_call([sys.executable, "-m", "pip", "install", "ddgs>=4.0.0"])
20
- print("ddgs installed successfully.")
21
  except Exception as e:
22
- print(f"Failed to install ddgs: {e}")
23
- # Critical error: if ddgs can't be installed, the app can't function.
24
- raise RuntimeError(f"CRITICAL: Failed to install ddgs: {e}")
25
- # --- END: Force ddgs installation workaround ---
26
 
27
- # Now import the agent, as its dependencies (smolagents, duckduckgo_search) should be ready
28
- from agent import GaiaAgent
 
29
 
30
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
- def run_agent_and_score(task_description: str) -> str:
33
- # Initialize the agent within the function, so it's fresh for each run
34
- # This also helps if the agent initialization is heavy or stateful
35
- gaia_agent = GaiaAgent()
36
-
37
- # Process the task
38
- agent_output = gaia_agent.process_task(task_description)
39
-
40
- # Send output to the scoring API
41
  try:
42
- response = requests.post(
43
- f"{DEFAULT_API_URL}/score_agent",
44
- json={"task_description": task_description, "agent_response": agent_output}
 
 
 
 
 
 
45
  )
46
- response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
47
- scoring_result = response.json()
48
- 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.')}"
49
- return f"Agent Output:\n{agent_output}\n\n---\n\n{score_info}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  except requests.exceptions.RequestException as e:
51
- return f"Agent Output:\n{agent_output}\n\n---\n\nError connecting to scoring API: {e}"
 
 
 
52
  except Exception as e:
53
- return f"Agent Output:\n{agent_output}\n\n---\n\nAn unexpected error occurred during scoring: {e}"
 
 
 
54
 
55
- # Gradio Interface setup
56
  with gr.Blocks() as demo:
57
- gr.Markdown("# GAIA Basic Agent Evaluator (Freddolin)")
58
- 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.")
59
-
60
- task_input = gr.Textbox(label="Task Description", placeholder="e.g., 'What is the capital of France?'")
61
- output_text = gr.Textbox(label="Agent Output & Score", interactive=False)
62
-
63
- run_button = gr.Button("Run Agent & Score")
 
 
 
 
 
 
 
 
 
 
64
 
65
  run_button.click(
66
- fn=run_agent_and_score,
67
- inputs=task_input,
68
- outputs=output_text
69
  )
70
 
71
- # Launch the Gradio app
72
- demo.launch(debug=True) # debug=True can provide more info in logs during development
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
 
 
1
  import os
2
  import gradio as gr
3
  import requests
4
+ import inspect # Behåll denna, mallen använder den kanske internt
5
  import pandas as pd
 
 
6
 
7
+ # Importera din GaiaAgent från den separata agent.py filen
8
+ from agent import GaiaAgent
9
+
10
+ # --- Constants ---
11
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
+
13
+ # --- Main Evaluation Function ---
14
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
15
+ """
16
+ Fetches all questions, runs the GaiaAgent on them, submits all answers,
17
+ and displays the results.
18
+ """
19
+ # --- Determine HF Space Runtime URL and Repo URL ---
20
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
21
+ if profile:
22
+ username= f"{profile.username}"
23
+ print(f"User logged in: {username}")
24
+ else:
25
+ print("User not logged in.")
26
+ return "Please Login to Hugging Face with the button.", None
27
+ api_url = DEFAULT_API_URL
28
+ questions_url = f"{api_url}/questions"
29
+ submit_url = f"{api_url}/submit"
30
+
31
+ # 1. Instantiate Agent (MODIFY THIS PART to create your agent)
32
  try:
33
+ # Instantiera din GaiaAgent här istället för BasicAgent
34
+ agent = GaiaAgent()
 
35
  except Exception as e:
36
+ print(f"Error instantiating agent: {e}")
37
+ return f"Error initializing agent: {e}", None
 
 
38
 
39
+ # In the case of an app running as a hugging Face space, this link points toward your codebase ( useful for others so please keep it public)
40
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
41
+ print(agent_code)
42
 
43
+ # 2. Fetch Questions
44
+ print(f"Fetching questions from: {questions_url}")
45
+ try:
46
+ response = requests.get(questions_url, timeout=15)
47
+ response.raise_for_status()
48
+ questions_data = response.json()
49
+ if not questions_data:
50
+ print("Fetched questions list is empty.")
51
+ return "Fetched questions list is empty or invalid format.", None
52
+ print(f"Fetched {len(questions_data)} questions.")
53
+ except requests.exceptions.RequestException as e:
54
+ print(f"Error fetching questions: {e}")
55
+ return f"Error fetching questions: {e}", None
56
+ except requests.exceptions.JSONDecodeError as e:
57
+ print(f"Error decoding JSON response from questions endpoint: {e}")
58
+ print(f"Response text: {response.text[:500]}")
59
+ return f"Error decoding server response for questions: {e}", None
60
+ except Exception as e:
61
+ print(f"An unexpected error occurred fetching questions: {e}")
62
+ return f"An unexpected error occurred fetching questions: {e}", None
63
+
64
+ # 3. Run your Agent
65
+ results_log = []
66
+ answers_payload = []
67
+ print(f"Running agent on {len(questions_data)} questions...")
68
+ for item in questions_data:
69
+ task_id = item.get("task_id")
70
+ question_text = item.get("question")
71
+ if not task_id or question_text is None:
72
+ print(f"Skipping item with missing task_id or question: {item}")
73
+ continue
74
+ try:
75
+ # Anropa din GaiaAgent med frågan
76
+ submitted_answer = agent(question_text)
77
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
78
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
79
+ except Exception as e:
80
+ print(f"Error running agent on task {task_id}: {e}")
81
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
82
+
83
+ if not answers_payload:
84
+ print("Agent did not produce any answers to submit.")
85
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
86
 
87
+ # 4. Prepare Submission
88
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
89
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
90
+ print(status_update)
91
+
92
+ # 5. Submit
93
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
 
 
94
  try:
95
+ response = requests.post(submit_url, json=submission_data, timeout=60)
96
+ response.raise_for_status()
97
+ result_data = response.json()
98
+ final_status = (
99
+ f"Submission Successful!\n"
100
+ f"User: {result_data.get('username')}\n"
101
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
102
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
103
+ f"Message: {result_data.get('message', 'No message received.')}"
104
  )
105
+ print("Submission successful.")
106
+ results_df = pd.DataFrame(results_log)
107
+ return final_status, results_df
108
+ except requests.exceptions.HTTPError as e:
109
+ error_detail = f"Server responded with status {e.response.status_code}."
110
+ try:
111
+ error_json = e.response.json()
112
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
113
+ except requests.exceptions.JSONDecodeError:
114
+ error_detail += f" Response: {e.response.text[:500]}"
115
+ status_message = f"Submission Failed: {error_detail}"
116
+ print(status_message)
117
+ results_df = pd.DataFrame(results_log)
118
+ return status_message, results_df
119
+ except requests.exceptions.Timeout:
120
+ status_message = "Submission Failed: The request timed out."
121
+ print(status_message)
122
+ results_df = pd.DataFrame(results_log)
123
+ return status_message, results_df
124
  except requests.exceptions.RequestException as e:
125
+ status_message = f"Submission Failed: Network error - {e}"
126
+ print(status_message)
127
+ results_df = pd.DataFrame(results_log)
128
+ return status_message, results_df
129
  except Exception as e:
130
+ status_message = f"An unexpected error occurred during submission: {e}"
131
+ print(status_message)
132
+ results_df = pd.DataFrame(results_log)
133
+ return status_message, results_df
134
 
135
+ # --- Build Gradio Interface using Blocks ---
136
  with gr.Blocks() as demo:
137
+ gr.Markdown("# Basic Agent Evaluation Runner")
138
+ gr.Markdown(
139
+ """
140
+ **Instructions:**
141
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
142
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
143
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
144
+ ---
145
+ **Disclaimers:**
146
+ 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).
147
+ 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.
148
+ """
149
+ )
150
+ gr.LoginButton()
151
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
152
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
153
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True) # Ensure max_rows is not breaking it
154
 
155
  run_button.click(
156
+ fn=run_and_submit_all,
157
+ outputs=[status_output, results_table]
 
158
  )
159
 
160
+ if __name__ == "__main__":
161
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
162
+ space_host_startup = os.getenv("SPACE_HOST")
163
+ space_id_startup = os.getenv("SPACE_ID")
164
+ if space_host_startup:
165
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
166
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
167
+ else:
168
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
169
+ if space_id_startup:
170
+ print(f"✅ SPACE_ID found: {space_id_startup}")
171
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
172
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
173
+ else:
174
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
175
+ print("-"*(60 + len(" App Starting ")) + "\n")
176
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
177
+ demo.launch(debug=True, share=False)
178