tomhflau commited on
Commit
36ca4f3
·
1 Parent(s): 2bbcb73

update app.py to use new agent with updated packages

Browse files
Files changed (2) hide show
  1. app.py +94 -27
  2. requirements.txt +0 -0
app.py CHANGED
@@ -3,32 +3,78 @@ import gradio as gr
3
  import requests
4
  import inspect
5
  import pandas as pd
 
 
 
 
 
6
 
7
- # (Keep Constants as is)
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
- # --- Basic Agent Definition ---
12
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
13
  class BasicAgent:
14
  def __init__(self):
15
- print("BasicAgent initialized.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  def __call__(self, question: str) -> str:
17
  print(f"Agent received question (first 50 chars): {question[:50]}...")
18
- fixed_answer = "This is a default answer."
19
- print(f"Agent returning fixed answer: {fixed_answer}")
20
- return fixed_answer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
- def run_and_submit_all( profile: gr.OAuthProfile | None):
23
  """
24
  Fetches all questions, runs the BasicAgent on them, submits all answers,
25
  and displays the results.
26
  """
27
  # --- Determine HF Space Runtime URL and Repo URL ---
28
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
29
 
30
  if profile:
31
- username= f"{profile.username}"
32
  print(f"User logged in: {username}")
33
  else:
34
  print("User not logged in.")
@@ -38,15 +84,20 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
38
  questions_url = f"{api_url}/questions"
39
  submit_url = f"{api_url}/submit"
40
 
41
- # 1. Instantiate Agent ( modify this part to create your agent)
 
 
 
 
 
 
 
 
42
  try:
43
  agent = BasicAgent()
44
  except Exception as e:
45
  print(f"Error instantiating agent: {e}")
46
  return f"Error initializing agent: {e}", None
47
- # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
48
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
49
- print(agent_code)
50
 
51
  # 2. Fetch Questions
52
  print(f"Fetching questions from: {questions_url}")
@@ -55,16 +106,16 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
55
  response.raise_for_status()
56
  questions_data = response.json()
57
  if not questions_data:
58
- print("Fetched questions list is empty.")
59
- return "Fetched questions list is empty or invalid format.", None
60
  print(f"Fetched {len(questions_data)} questions.")
61
  except requests.exceptions.RequestException as e:
62
  print(f"Error fetching questions: {e}")
63
  return f"Error fetching questions: {e}", None
64
  except requests.exceptions.JSONDecodeError as e:
65
- print(f"Error decoding JSON response from questions endpoint: {e}")
66
- print(f"Response text: {response.text[:500]}")
67
- return f"Error decoding server response for questions: {e}", None
68
  except Exception as e:
69
  print(f"An unexpected error occurred fetching questions: {e}")
70
  return f"An unexpected error occurred fetching questions: {e}", None
@@ -73,26 +124,43 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
73
  results_log = []
74
  answers_payload = []
75
  print(f"Running agent on {len(questions_data)} questions...")
76
- for item in questions_data:
 
77
  task_id = item.get("task_id")
78
  question_text = item.get("question")
79
  if not task_id or question_text is None:
80
  print(f"Skipping item with missing task_id or question: {item}")
81
  continue
 
 
82
  try:
83
  submitted_answer = agent(question_text)
84
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
85
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
 
 
 
86
  except Exception as e:
87
- print(f"Error running agent on task {task_id}: {e}")
88
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
 
 
 
 
89
 
90
  if not answers_payload:
91
  print("Agent did not produce any answers to submit.")
92
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
93
 
94
  # 4. Prepare Submission
95
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
 
 
 
 
96
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
97
  print(status_update)
98
 
@@ -163,7 +231,6 @@ with gr.Blocks() as demo:
163
  run_button = gr.Button("Run Evaluation & Submit All Answers")
164
 
165
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
166
- # Removed max_rows=10 from DataFrame constructor
167
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
168
 
169
  run_button.click(
@@ -175,7 +242,7 @@ if __name__ == "__main__":
175
  print("\n" + "-"*30 + " App Starting " + "-"*30)
176
  # Check for SPACE_HOST and SPACE_ID at startup for information
177
  space_host_startup = os.getenv("SPACE_HOST")
178
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
179
 
180
  if space_host_startup:
181
  print(f"✅ SPACE_HOST found: {space_host_startup}")
@@ -183,7 +250,7 @@ if __name__ == "__main__":
183
  else:
184
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
185
 
186
- if space_id_startup: # Print repo URLs if SPACE_ID is found
187
  print(f"✅ SPACE_ID found: {space_id_startup}")
188
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
189
  print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
 
3
  import requests
4
  import inspect
5
  import pandas as pd
6
+ from dotenv import load_dotenv
7
+ from huggingface_hub import InferenceClient
8
+
9
+ # Load environment variables
10
+ load_dotenv()
11
 
 
12
  # --- Constants ---
13
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
14
 
 
 
15
  class BasicAgent:
16
  def __init__(self):
17
+ print("BasicAgent initialized - using HF Inference API.")
18
+
19
+ # Get HF token from environment
20
+ hf_token = os.getenv("HUGGINGFACE_HUB_TOKEN") or os.getenv("HF_TOKEN")
21
+
22
+ if not hf_token:
23
+ raise ValueError("❌ No HF token found. Please set HF_TOKEN or HUGGINGFACE_HUB_TOKEN in your .env file\n"
24
+ "You can get a token from: https://huggingface.co/settings/tokens")
25
+
26
+ # Initialize the Inference Client
27
+ try:
28
+ self.client = InferenceClient(
29
+ provider="hf-inference",
30
+ api_key=hf_token,
31
+ )
32
+ print("✅ HF Inference Client initialized successfully")
33
+ except Exception as e:
34
+ print(f"❌ Error initializing HF Inference Client: {e}")
35
+ raise e
36
+
37
  def __call__(self, question: str) -> str:
38
  print(f"Agent received question (first 50 chars): {question[:50]}...")
39
+ try:
40
+ # Create a more detailed prompt for better responses
41
+ system_prompt = "You are a helpful AI assistant. Provide clear, accurate, and concise answers to questions."
42
+
43
+ completion = self.client.chat.completions.create(
44
+ model="HuggingFaceTB/SmolLM3-3B",
45
+ messages=[
46
+ {
47
+ "role": "system",
48
+ "content": system_prompt
49
+ },
50
+ {
51
+ "role": "user",
52
+ "content": question
53
+ }
54
+ ],
55
+ max_tokens=512,
56
+ temperature=0.7,
57
+ )
58
+
59
+ answer = completion.choices[0].message.content
60
+ print(f"Agent returning answer: {answer[:100]}...")
61
+ return answer
62
+
63
+ except Exception as e:
64
+ error_msg = f"Error processing question: {str(e)}"
65
+ print(f"❌ {error_msg}")
66
+ return error_msg
67
 
68
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
69
  """
70
  Fetches all questions, runs the BasicAgent on them, submits all answers,
71
  and displays the results.
72
  """
73
  # --- Determine HF Space Runtime URL and Repo URL ---
74
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
75
 
76
  if profile:
77
+ username = f"{profile.username}"
78
  print(f"User logged in: {username}")
79
  else:
80
  print("User not logged in.")
 
84
  questions_url = f"{api_url}/questions"
85
  submit_url = f"{api_url}/submit"
86
 
87
+ # Generate agent code URL
88
+ if space_id:
89
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
90
+ else:
91
+ agent_code = "https://huggingface.co/spaces/your-username/your-space/tree/main"
92
+
93
+ print(f"Agent code URL: {agent_code}")
94
+
95
+ # 1. Instantiate Agent
96
  try:
97
  agent = BasicAgent()
98
  except Exception as e:
99
  print(f"Error instantiating agent: {e}")
100
  return f"Error initializing agent: {e}", None
 
 
 
101
 
102
  # 2. Fetch Questions
103
  print(f"Fetching questions from: {questions_url}")
 
106
  response.raise_for_status()
107
  questions_data = response.json()
108
  if not questions_data:
109
+ print("Fetched questions list is empty.")
110
+ return "Fetched questions list is empty or invalid format.", None
111
  print(f"Fetched {len(questions_data)} questions.")
112
  except requests.exceptions.RequestException as e:
113
  print(f"Error fetching questions: {e}")
114
  return f"Error fetching questions: {e}", None
115
  except requests.exceptions.JSONDecodeError as e:
116
+ print(f"Error decoding JSON response from questions endpoint: {e}")
117
+ print(f"Response text: {response.text[:500]}")
118
+ return f"Error decoding server response for questions: {e}", None
119
  except Exception as e:
120
  print(f"An unexpected error occurred fetching questions: {e}")
121
  return f"An unexpected error occurred fetching questions: {e}", None
 
124
  results_log = []
125
  answers_payload = []
126
  print(f"Running agent on {len(questions_data)} questions...")
127
+
128
+ for i, item in enumerate(questions_data):
129
  task_id = item.get("task_id")
130
  question_text = item.get("question")
131
  if not task_id or question_text is None:
132
  print(f"Skipping item with missing task_id or question: {item}")
133
  continue
134
+
135
+ print(f"Processing question {i+1}/{len(questions_data)}: {task_id}")
136
  try:
137
  submitted_answer = agent(question_text)
138
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
139
+ results_log.append({
140
+ "Task ID": task_id,
141
+ "Question": question_text[:100] + "..." if len(question_text) > 100 else question_text,
142
+ "Submitted Answer": submitted_answer[:200] + "..." if len(submitted_answer) > 200 else submitted_answer
143
+ })
144
  except Exception as e:
145
+ error_msg = f"AGENT ERROR: {e}"
146
+ print(f"Error running agent on task {task_id}: {e}")
147
+ answers_payload.append({"task_id": task_id, "submitted_answer": error_msg})
148
+ results_log.append({
149
+ "Task ID": task_id,
150
+ "Question": question_text[:100] + "..." if len(question_text) > 100 else question_text,
151
+ "Submitted Answer": error_msg
152
+ })
153
 
154
  if not answers_payload:
155
  print("Agent did not produce any answers to submit.")
156
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
157
 
158
  # 4. Prepare Submission
159
+ submission_data = {
160
+ "username": username.strip(),
161
+ "agent_code": agent_code,
162
+ "answers": answers_payload
163
+ }
164
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
165
  print(status_update)
166
 
 
231
  run_button = gr.Button("Run Evaluation & Submit All Answers")
232
 
233
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
234
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
235
 
236
  run_button.click(
 
242
  print("\n" + "-"*30 + " App Starting " + "-"*30)
243
  # Check for SPACE_HOST and SPACE_ID at startup for information
244
  space_host_startup = os.getenv("SPACE_HOST")
245
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
246
 
247
  if space_host_startup:
248
  print(f"✅ SPACE_HOST found: {space_host_startup}")
 
250
  else:
251
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
252
 
253
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
254
  print(f"✅ SPACE_ID found: {space_id_startup}")
255
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
256
  print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
requirements.txt CHANGED
Binary files a/requirements.txt and b/requirements.txt differ