arjunothayoth commited on
Commit
8549229
·
verified ·
1 Parent(s): 73d92b9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -38
app.py CHANGED
@@ -10,40 +10,55 @@ import os
10
  # --- Constants ---
11
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
 
 
13
  # --- Basic Agent Definition ---
14
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
15
  class BasicAgent:
16
  def __init__(self):
17
  print("BasicAgent initialized.")
18
- self.client = InferenceClient(
19
- token=os.getenv("HF_TOKEN")
20
- )
21
  def __call__(self, question: str) -> str:
22
- print(f"Agent received question (first 50 chars): {question[:50]}...")
23
- response = self.client.chat_completion(
24
  model="meta-llama/Llama-3.1-8B-Instruct",
25
  messages=[
26
- {"role": "user", "content": question}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  ],
28
- max_tokens=512
29
  )
30
 
31
- return response.choices[0].message.content
32
-
33
- # fixed_answer = "This is a default answer."
34
- # print(f"Agent returning fixed answer: {fixed_answer}")
35
- # return fixed_answer
 
36
 
37
- def run_and_submit_all( profile: gr.OAuthProfile | None):
38
  """
39
  Fetches all questions, runs the BasicAgent on them, submits all answers,
40
  and displays the results.
41
  """
42
  # --- Determine HF Space Runtime URL and Repo URL ---
43
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
44
 
45
  if profile:
46
- username= f"{profile.username}"
47
  print(f"User logged in: {username}")
48
  else:
49
  print("User not logged in.")
@@ -70,16 +85,16 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
70
  response.raise_for_status()
71
  questions_data = response.json()
72
  if not questions_data:
73
- print("Fetched questions list is empty.")
74
- return "Fetched questions list is empty or invalid format.", None
75
  print(f"Fetched {len(questions_data)} questions.")
76
  except requests.exceptions.RequestException as e:
77
  print(f"Error fetching questions: {e}")
78
  return f"Error fetching questions: {e}", None
79
  except requests.exceptions.JSONDecodeError as e:
80
- print(f"Error decoding JSON response from questions endpoint: {e}")
81
- print(f"Response text: {response.text[:500]}")
82
- return f"Error decoding server response for questions: {e}", None
83
  except Exception as e:
84
  print(f"An unexpected error occurred fetching questions: {e}")
85
  return f"An unexpected error occurred fetching questions: {e}", None
@@ -96,18 +111,36 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
96
  continue
97
  try:
98
  submitted_answer = agent(question_text)
99
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
100
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
 
 
 
 
 
 
 
101
  except Exception as e:
102
- print(f"Error running agent on task {task_id}: {e}")
103
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
 
 
 
 
104
 
105
  if not answers_payload:
106
  print("Agent did not produce any answers to submit.")
107
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
108
 
109
- # 4. Prepare Submission
110
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
 
 
 
 
111
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
112
  print(status_update)
113
 
@@ -175,20 +208,19 @@ with gr.Blocks() as demo:
175
 
176
  run_button = gr.Button("Run Evaluation & Submit All Answers")
177
 
178
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
 
179
  # Removed max_rows=10 from DataFrame constructor
180
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
181
 
182
- run_button.click(
183
- fn=run_and_submit_all,
184
- outputs=[status_output, results_table]
185
- )
186
 
187
  if __name__ == "__main__":
188
- print("\n" + "-"*30 + " App Starting " + "-"*30)
189
  # Check for SPACE_HOST and SPACE_ID at startup for information
190
  space_host_startup = os.getenv("SPACE_HOST")
191
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
192
 
193
  if space_host_startup:
194
  print(f"✅ SPACE_HOST found: {space_host_startup}")
@@ -196,14 +228,18 @@ if __name__ == "__main__":
196
  else:
197
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
198
 
199
- if space_id_startup: # Print repo URLs if SPACE_ID is found
200
  print(f"✅ SPACE_ID found: {space_id_startup}")
201
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
202
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
 
 
203
  else:
204
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
 
 
205
 
206
- print("-"*(60 + len(" App Starting ")) + "\n")
207
 
208
  print("Launching Gradio Interface for Basic Agent Evaluation...")
209
- demo.launch(debug=True, share=False)
 
10
  # --- Constants ---
11
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
 
13
+
14
  # --- Basic Agent Definition ---
15
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
16
  class BasicAgent:
17
  def __init__(self):
18
  print("BasicAgent initialized.")
19
+ self.client = InferenceClient(token=os.getenv("HF_TOKEN"))
20
+
 
21
  def __call__(self, question: str) -> str:
22
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
23
+ response = self.client.chat_completion(
24
  model="meta-llama/Llama-3.1-8B-Instruct",
25
  messages=[
26
+ {
27
+ "role": "system",
28
+ "content": """
29
+ You are an expert AI agent.
30
+
31
+ Instructions:
32
+ - Carefully analyze the question.
33
+ - Reason step by step internally.
34
+ - Perform calculations when needed.
35
+ - Be precise.
36
+ - Return only the final answer.
37
+ - Do not explain your reasoning.
38
+ """,
39
+ },
40
+ {"role": "user", "content": question},
41
  ],
42
+ max_tokens=512,
43
  )
44
 
45
+ return response.choices[0].message.content
46
+
47
+ # fixed_answer = "This is a default answer."
48
+ # print(f"Agent returning fixed answer: {fixed_answer}")
49
+ # return fixed_answer
50
+
51
 
52
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
53
  """
54
  Fetches all questions, runs the BasicAgent on them, submits all answers,
55
  and displays the results.
56
  """
57
  # --- Determine HF Space Runtime URL and Repo URL ---
58
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
59
 
60
  if profile:
61
+ username = f"{profile.username}"
62
  print(f"User logged in: {username}")
63
  else:
64
  print("User not logged in.")
 
85
  response.raise_for_status()
86
  questions_data = response.json()
87
  if not questions_data:
88
+ print("Fetched questions list is empty.")
89
+ return "Fetched questions list is empty or invalid format.", None
90
  print(f"Fetched {len(questions_data)} questions.")
91
  except requests.exceptions.RequestException as e:
92
  print(f"Error fetching questions: {e}")
93
  return f"Error fetching questions: {e}", None
94
  except requests.exceptions.JSONDecodeError as e:
95
+ print(f"Error decoding JSON response from questions endpoint: {e}")
96
+ print(f"Response text: {response.text[:500]}")
97
+ return f"Error decoding server response for questions: {e}", None
98
  except Exception as e:
99
  print(f"An unexpected error occurred fetching questions: {e}")
100
  return f"An unexpected error occurred fetching questions: {e}", None
 
111
  continue
112
  try:
113
  submitted_answer = agent(question_text)
114
+ answers_payload.append(
115
+ {"task_id": task_id, "submitted_answer": submitted_answer}
116
+ )
117
+ results_log.append(
118
+ {
119
+ "Task ID": task_id,
120
+ "Question": question_text,
121
+ "Submitted Answer": submitted_answer,
122
+ }
123
+ )
124
  except Exception as e:
125
+ print(f"Error running agent on task {task_id}: {e}")
126
+ results_log.append(
127
+ {
128
+ "Task ID": task_id,
129
+ "Question": question_text,
130
+ "Submitted Answer": f"AGENT ERROR: {e}",
131
+ }
132
+ )
133
 
134
  if not answers_payload:
135
  print("Agent did not produce any answers to submit.")
136
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
137
 
138
+ # 4. Prepare Submission
139
+ submission_data = {
140
+ "username": username.strip(),
141
+ "agent_code": agent_code,
142
+ "answers": answers_payload,
143
+ }
144
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
145
  print(status_update)
146
 
 
208
 
209
  run_button = gr.Button("Run Evaluation & Submit All Answers")
210
 
211
+ status_output = gr.Textbox(
212
+ label="Run Status / Submission Result", lines=5, interactive=False
213
+ )
214
  # Removed max_rows=10 from DataFrame constructor
215
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
216
 
217
+ run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
 
 
 
218
 
219
  if __name__ == "__main__":
220
+ print("\n" + "-" * 30 + " App Starting " + "-" * 30)
221
  # Check for SPACE_HOST and SPACE_ID at startup for information
222
  space_host_startup = os.getenv("SPACE_HOST")
223
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
224
 
225
  if space_host_startup:
226
  print(f"✅ SPACE_HOST found: {space_host_startup}")
 
228
  else:
229
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
230
 
231
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
232
  print(f"✅ SPACE_ID found: {space_id_startup}")
233
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
234
+ print(
235
+ f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main"
236
+ )
237
  else:
238
+ print(
239
+ "ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined."
240
+ )
241
 
242
+ print("-" * (60 + len(" App Starting ")) + "\n")
243
 
244
  print("Launching Gradio Interface for Basic Agent Evaluation...")
245
+ demo.launch(debug=True, share=False)