xarical commited on
Commit
32eac77
·
1 Parent(s): fa63e3d

modularize codebase

Browse files
Files changed (3) hide show
  1. BasicAgent.py +8 -0
  2. app.py +1 -134
  3. utils.py +129 -0
BasicAgent.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ class BasicAgent:
2
+ def __init__(self):
3
+ print("BasicAgent initialized.")
4
+ def __call__(self, question: str) -> str:
5
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
6
+ fixed_answer = "This is a default answer."
7
+ print(f"Agent returning fixed answer: {fixed_answer}")
8
+ return fixed_answer
app.py CHANGED
@@ -1,139 +1,6 @@
1
- import os
2
-
3
  import gradio as gr
4
- import requests
5
- import pandas as pd
6
-
7
-
8
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
-
10
-
11
- class BasicAgent:
12
- def __init__(self):
13
- print("BasicAgent initialized.")
14
- def __call__(self, question: str) -> str:
15
- print(f"Agent received question (first 50 chars): {question[:50]}...")
16
- fixed_answer = "This is a default answer."
17
- print(f"Agent returning fixed answer: {fixed_answer}")
18
- return fixed_answer
19
-
20
-
21
- def run_and_submit_all(profile: gr.OAuthProfile | None):
22
- """
23
- Fetches all questions, runs the BasicAgent on them, submits all answers,
24
- and displays the results.
25
- """
26
- if profile:
27
- username:str = profile.username
28
- print(f"User logged in: {username}")
29
- else:
30
- print("User not logged in.")
31
- return "Please Login to Hugging Face with the button.", None
32
-
33
- api_url = DEFAULT_API_URL
34
- questions_url = f"{api_url}/questions"
35
- submit_url = f"{api_url}/submit"
36
-
37
- # 1. Instantiate Agent ( modify this part to create your agent)
38
- try:
39
- agent = BasicAgent()
40
- except Exception as e:
41
- print(f"Error instantiating agent: {e}")
42
- return f"Error initializing agent: {e}", None
43
- # In the case of an app running as a HF Space, this link points toward your codebase
44
- agent_code = f"https://huggingface.co/spaces/{os.getenv("SPACE_ID")}/tree/main"
45
- print(agent_code)
46
-
47
- # 2. Fetch Questions
48
- print(f"Fetching questions from: {questions_url}")
49
- try:
50
- response = requests.get(questions_url, timeout=15)
51
- response.raise_for_status()
52
- questions_data: list[dict] = response.json()
53
- if not questions_data:
54
- print("Fetched questions list is empty.")
55
- return "Fetched questions list is empty or invalid format.", None
56
- print(f"Fetched {len(questions_data)} questions.")
57
- except requests.exceptions.RequestException as e:
58
- print(f"Error fetching questions: {e}")
59
- return f"Error fetching questions: {e}", None
60
- except requests.exceptions.JSONDecodeError as e:
61
- print(f"Error decoding JSON response from questions endpoint: {e}")
62
- print(f"Response text: {response.text[:500]}")
63
- return f"Error decoding server response for questions: {e}", None
64
- except Exception as e:
65
- print(f"An unexpected error occurred fetching questions: {e}")
66
- return f"An unexpected error occurred fetching questions: {e}", None
67
-
68
- # 3. Run your Agent
69
- results_log = []
70
- answers_payload = []
71
- print(f"Running agent on {len(questions_data)} questions...")
72
- for item in questions_data:
73
- task_id = item.get("task_id")
74
- question_text = item.get("question")
75
- if not task_id or question_text is None:
76
- print(f"Skipping item with missing task_id or question: {item}")
77
- continue
78
- try:
79
- submitted_answer = agent(question_text)
80
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
81
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
82
- except Exception as e:
83
- print(f"Error running agent on task {task_id}: {e}")
84
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
85
-
86
- if not answers_payload:
87
- print("Agent did not produce any answers to submit.")
88
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
89
-
90
- # 4. Prepare Submission
91
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
92
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
93
- print(status_update)
94
 
95
- # 5. Submit
96
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
97
- try:
98
- response = requests.post(submit_url, json=submission_data, timeout=60)
99
- response.raise_for_status()
100
- result_data = response.json()
101
- final_status = (
102
- f"Submission Successful!\n"
103
- f"User: {result_data.get('username')}\n"
104
- f"Overall Score: {result_data.get('score', 'N/A')}% "
105
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
106
- f"Message: {result_data.get('message', 'No message received.')}"
107
- )
108
- print("Submission successful.")
109
- results_df = pd.DataFrame(results_log)
110
- return final_status, results_df
111
- except requests.exceptions.HTTPError as e:
112
- error_detail = f"Server responded with status {e.response.status_code}."
113
- try:
114
- error_json = e.response.json()
115
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
116
- except requests.exceptions.JSONDecodeError:
117
- error_detail += f" Response: {e.response.text[:500]}"
118
- status_message = f"Submission Failed: {error_detail}"
119
- print(status_message)
120
- results_df = pd.DataFrame(results_log)
121
- return status_message, results_df
122
- except requests.exceptions.Timeout:
123
- status_message = "Submission Failed: The request timed out."
124
- print(status_message)
125
- results_df = pd.DataFrame(results_log)
126
- return status_message, results_df
127
- except requests.exceptions.RequestException as e:
128
- status_message = f"Submission Failed: Network error - {e}"
129
- print(status_message)
130
- results_df = pd.DataFrame(results_log)
131
- return status_message, results_df
132
- except Exception as e:
133
- status_message = f"An unexpected error occurred during submission: {e}"
134
- print(status_message)
135
- results_df = pd.DataFrame(results_log)
136
- return status_message, results_df
137
 
138
 
139
  # Demo app
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
+ from utils import run_and_submit_all
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
 
6
  # Demo app
utils.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Any, Tuple
3
+
4
+ import gradio as gr
5
+ import requests
6
+ import pandas as pd
7
+
8
+ from BasicAgent import BasicAgent
9
+
10
+
11
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
+
13
+
14
+ def run_and_submit_all(profile: gr.OAuthProfile | None, agent: BasicAgent) -> Tuple[str, Any]:
15
+ """
16
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
17
+ and displays the results.
18
+ """
19
+ if profile:
20
+ username: str = profile.username
21
+ print(f"User logged in: {username}")
22
+ else:
23
+ print("User not logged in.")
24
+ return "Please Login to Hugging Face with the button.", None
25
+
26
+ api_url = DEFAULT_API_URL
27
+ questions_url = f"{api_url}/questions"
28
+ submit_url = f"{api_url}/submit"
29
+
30
+ # 1. Instantiate Agent ( modify this part to create your agent)
31
+ try:
32
+ agent = BasicAgent()
33
+ except Exception as e:
34
+ print(f"Error instantiating agent: {e}")
35
+ return f"Error initializing agent: {e}", None
36
+ # In the case of an app running as a HF Space, this link points toward your codebase
37
+ agent_code = f"https://huggingface.co/spaces/{os.getenv("SPACE_ID")}/tree/main"
38
+ print(agent_code)
39
+
40
+ # 2. Fetch Questions
41
+ print(f"Fetching questions from: {questions_url}")
42
+ try:
43
+ response = requests.get(questions_url, timeout=15)
44
+ response.raise_for_status()
45
+ questions_data: list[dict] = response.json()
46
+ if not questions_data:
47
+ print("Fetched questions list is empty.")
48
+ return "Fetched questions list is empty or invalid format.", None
49
+ print(f"Fetched {len(questions_data)} questions.")
50
+ except requests.exceptions.RequestException as e:
51
+ print(f"Error fetching questions: {e}")
52
+ return f"Error fetching questions: {e}", None
53
+ except requests.exceptions.JSONDecodeError as e:
54
+ print(f"Error decoding JSON response from questions endpoint: {e}")
55
+ print(f"Response text: {response.text[:500]}")
56
+ return f"Error decoding server response for questions: {e}", None
57
+ except Exception as e:
58
+ print(f"An unexpected error occurred fetching questions: {e}")
59
+ return f"An unexpected error occurred fetching questions: {e}", None
60
+
61
+ # 3. Run your Agent
62
+ results_log = []
63
+ answers_payload = []
64
+ print(f"Running agent on {len(questions_data)} questions...")
65
+ for item in questions_data:
66
+ task_id = item.get("task_id")
67
+ question_text = item.get("question")
68
+ if not task_id or question_text is None:
69
+ print(f"Skipping item with missing task_id or question: {item}")
70
+ continue
71
+ try:
72
+ submitted_answer = agent(question_text)
73
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
74
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
75
+ except Exception as e:
76
+ print(f"Error running agent on task {task_id}: {e}")
77
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
78
+
79
+ if not answers_payload:
80
+ print("Agent did not produce any answers to submit.")
81
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
82
+
83
+ # 4. Prepare Submission
84
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
85
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
86
+ print(status_update)
87
+
88
+ # 5. Submit
89
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
90
+ try:
91
+ response = requests.post(submit_url, json=submission_data, timeout=60)
92
+ response.raise_for_status()
93
+ result_data: dict = response.json()
94
+ final_status = (
95
+ f"Submission Successful!\n"
96
+ f"User: {result_data.get('username')}\n"
97
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
98
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
99
+ f"Message: {result_data.get('message', 'No message received.')}"
100
+ )
101
+ print("Submission successful.")
102
+ results_df = pd.DataFrame(results_log)
103
+ return final_status, results_df
104
+ except requests.exceptions.HTTPError as e:
105
+ error_detail = f"Server responded with status {e.response.status_code}."
106
+ try:
107
+ error_json = e.response.json()
108
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
109
+ except requests.exceptions.JSONDecodeError:
110
+ error_detail += f" Response: {e.response.text[:500]}"
111
+ status_message = f"Submission Failed: {error_detail}"
112
+ print(status_message)
113
+ results_df = pd.DataFrame(results_log)
114
+ return status_message, results_df
115
+ except requests.exceptions.Timeout:
116
+ status_message = "Submission Failed: The request timed out."
117
+ print(status_message)
118
+ results_df = pd.DataFrame(results_log)
119
+ return status_message, results_df
120
+ except requests.exceptions.RequestException as e:
121
+ status_message = f"Submission Failed: Network error - {e}"
122
+ print(status_message)
123
+ results_df = pd.DataFrame(results_log)
124
+ return status_message, results_df
125
+ except Exception as e:
126
+ status_message = f"An unexpected error occurred during submission: {e}"
127
+ print(status_message)
128
+ results_df = pd.DataFrame(results_log)
129
+ return status_message, results_df