jan01 commited on
Commit
5e8fa99
·
verified ·
1 Parent(s): 7520501

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -40
app.py CHANGED
@@ -1,41 +1,47 @@
1
  import os
 
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
5
- import openai # Added openai import
 
 
6
 
 
 
 
7
  # --- Constants ---
8
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
 
10
- # --- Basic Agent using OpenAI GPT ---
 
 
 
11
  class BasicAgent:
 
12
  def __init__(self):
13
- openai.api_key = os.getenv("OPENAI_API_KEY")
14
- if not openai.api_key:
15
- raise ValueError("OPENAI_API_KEY environment variable is not set!")
16
 
17
  def __call__(self, question: str) -> str:
18
- try:
19
- response = openai.ChatCompletion.create(
20
- model="gpt-4", # or "gpt-3.5-turbo"
21
- messages=[
22
- {"role": "system", "content": "You are a helpful assistant."},
23
- {"role": "user", "content": question}
24
- ],
25
- max_tokens=150,
26
- temperature=0.7
27
- )
28
- answer = response['choices'][0]['message']['content'].strip()
29
- return answer
30
- except Exception as e:
31
- print(f"OpenAI API error: {e}")
32
- return "Sorry, I couldn't answer that."
33
-
34
- def run_and_submit_all(profile: gr.OAuthProfile | None):
35
- space_id = os.getenv("SPACE_ID")
36
 
37
  if profile:
38
- username = f"{profile.username}"
39
  print(f"User logged in: {username}")
40
  else:
41
  print("User not logged in.")
@@ -45,27 +51,38 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
45
  questions_url = f"{api_url}/questions"
46
  submit_url = f"{api_url}/submit"
47
 
 
48
  try:
49
  agent = BasicAgent()
50
  except Exception as e:
51
  print(f"Error instantiating agent: {e}")
52
  return f"Error initializing agent: {e}", None
53
-
54
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Code repo link unavailable"
55
  print(agent_code)
56
 
 
 
57
  try:
58
  response = requests.get(questions_url, timeout=15)
59
  response.raise_for_status()
60
  questions_data = response.json()
61
  if not questions_data:
62
- print("Fetched questions list is empty.")
63
- return "Fetched questions list is empty or invalid format.", None
64
  print(f"Fetched {len(questions_data)} questions.")
65
- except Exception as e:
66
  print(f"Error fetching questions: {e}")
67
  return f"Error fetching questions: {e}", None
 
 
 
 
 
 
 
68
 
 
69
  results_log = []
70
  answers_payload = []
71
  print(f"Running agent on {len(questions_data)} questions...")
@@ -75,21 +92,28 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
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
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
91
- print(f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'...")
 
92
 
 
 
93
  try:
94
  response = requests.post(submit_url, json=submission_data, timeout=60)
95
  response.raise_for_status()
@@ -109,7 +133,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
109
  try:
110
  error_json = e.response.json()
111
  error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
112
- except Exception:
113
  error_detail += f" Response: {e.response.text[:500]}"
114
  status_message = f"Submission Failed: {error_detail}"
115
  print(status_message)
@@ -132,6 +156,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
132
  return status_message, results_df
133
 
134
 
 
135
  with gr.Blocks() as demo:
136
  gr.Markdown("# Basic Agent Evaluation Runner")
137
  gr.Markdown(
@@ -142,8 +167,8 @@ with gr.Blocks() as demo:
142
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
143
  ---
144
  **Disclaimers:**
145
- 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).
146
- 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 separate action or even to answer the questions asynchronously.
147
  """
148
  )
149
 
@@ -152,6 +177,7 @@ with gr.Blocks() as demo:
152
  run_button = gr.Button("Run Evaluation & Submit All Answers")
153
 
154
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
155
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
156
 
157
  run_button.click(
@@ -159,11 +185,11 @@ with gr.Blocks() as demo:
159
  outputs=[status_output, results_table]
160
  )
161
 
162
-
163
  if __name__ == "__main__":
164
- print("\n" + "-" * 30 + " App Starting " + "-" * 30)
 
165
  space_host_startup = os.getenv("SPACE_HOST")
166
- space_id_startup = os.getenv("SPACE_ID")
167
 
168
  if space_host_startup:
169
  print(f"✅ SPACE_HOST found: {space_host_startup}")
@@ -171,14 +197,14 @@ if __name__ == "__main__":
171
  else:
172
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
173
 
174
- if space_id_startup:
175
  print(f"✅ SPACE_ID found: {space_id_startup}")
176
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
177
  print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
178
  else:
179
  print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
180
 
181
- print("-" * (60 + len(" App Starting ")) + "\n")
182
 
183
  print("Launching Gradio Interface for Basic Agent Evaluation...")
184
  demo.launch(debug=True, share=False)
 
1
  import os
2
+ import inspect
3
  import gradio as gr
4
  import requests
5
  import pandas as pd
6
+ import time
7
+ from langchain_core.messages import HumanMessage
8
+ from agent import build_graph
9
 
10
+
11
+
12
+ # (Keep Constants as is)
13
  # --- Constants ---
14
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
15
 
16
+ # --- Basic Agent Definition ---
17
+ # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
18
+
19
+
20
  class BasicAgent:
21
+ """A langgraph agent."""
22
  def __init__(self):
23
+ print("BasicAgent initialized.")
24
+ self.graph = build_graph()
 
25
 
26
  def __call__(self, question: str) -> str:
27
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
28
+ # Wrap the question in a HumanMessage from langchain_core
29
+ messages = [HumanMessage(content=question)]
30
+ messages = self.graph.invoke({"messages": messages})
31
+ answer = messages['messages'][-1].content
32
+ return answer[14:]
33
+
34
+
35
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
36
+ """
37
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
38
+ and displays the results.
39
+ """
40
+ # --- Determine HF Space Runtime URL and Repo URL ---
41
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
 
 
 
42
 
43
  if profile:
44
+ username= f"{profile.username}"
45
  print(f"User logged in: {username}")
46
  else:
47
  print("User not logged in.")
 
51
  questions_url = f"{api_url}/questions"
52
  submit_url = f"{api_url}/submit"
53
 
54
+ # 1. Instantiate Agent ( modify this part to create your agent)
55
  try:
56
  agent = BasicAgent()
57
  except Exception as e:
58
  print(f"Error instantiating agent: {e}")
59
  return f"Error initializing agent: {e}", None
60
+ # 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)
61
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
62
  print(agent_code)
63
 
64
+ # 2. Fetch Questions
65
+ print(f"Fetching questions from: {questions_url}")
66
  try:
67
  response = requests.get(questions_url, timeout=15)
68
  response.raise_for_status()
69
  questions_data = response.json()
70
  if not questions_data:
71
+ print("Fetched questions list is empty.")
72
+ return "Fetched questions list is empty or invalid format.", None
73
  print(f"Fetched {len(questions_data)} questions.")
74
+ except requests.exceptions.RequestException as e:
75
  print(f"Error fetching questions: {e}")
76
  return f"Error fetching questions: {e}", None
77
+ except requests.exceptions.JSONDecodeError as e:
78
+ print(f"Error decoding JSON response from questions endpoint: {e}")
79
+ print(f"Response text: {response.text[:500]}")
80
+ return f"Error decoding server response for questions: {e}", None
81
+ except Exception as e:
82
+ print(f"An unexpected error occurred fetching questions: {e}")
83
+ return f"An unexpected error occurred fetching questions: {e}", None
84
 
85
+ # 3. Run your Agent
86
  results_log = []
87
  answers_payload = []
88
  print(f"Running agent on {len(questions_data)} questions...")
 
92
  if not task_id or question_text is None:
93
  print(f"Skipping item with missing task_id or question: {item}")
94
  continue
95
+
96
+ # time.sleep(10)
97
+
98
  try:
99
  submitted_answer = agent(question_text)
100
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
101
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
102
  except Exception as e:
103
+ print(f"Error running agent on task {task_id}: {e}")
104
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
105
 
106
  if not answers_payload:
107
  print("Agent did not produce any answers to submit.")
108
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
109
 
110
+ # 4. Prepare Submission
111
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
112
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
113
+ print(status_update)
114
 
115
+ # 5. Submit
116
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
117
  try:
118
  response = requests.post(submit_url, json=submission_data, timeout=60)
119
  response.raise_for_status()
 
133
  try:
134
  error_json = e.response.json()
135
  error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
136
+ except requests.exceptions.JSONDecodeError:
137
  error_detail += f" Response: {e.response.text[:500]}"
138
  status_message = f"Submission Failed: {error_detail}"
139
  print(status_message)
 
156
  return status_message, results_df
157
 
158
 
159
+ # --- Build Gradio Interface using Blocks ---
160
  with gr.Blocks() as demo:
161
  gr.Markdown("# Basic Agent Evaluation Runner")
162
  gr.Markdown(
 
167
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
168
  ---
169
  **Disclaimers:**
170
+ 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).
171
+ 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.
172
  """
173
  )
174
 
 
177
  run_button = gr.Button("Run Evaluation & Submit All Answers")
178
 
179
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
180
+ # Removed max_rows=10 from DataFrame constructor
181
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
182
 
183
  run_button.click(
 
185
  outputs=[status_output, results_table]
186
  )
187
 
 
188
  if __name__ == "__main__":
189
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
190
+ # Check for SPACE_HOST and SPACE_ID at startup for information
191
  space_host_startup = os.getenv("SPACE_HOST")
192
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
193
 
194
  if space_host_startup:
195
  print(f"✅ SPACE_HOST found: {space_host_startup}")
 
197
  else:
198
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
199
 
200
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
201
  print(f"✅ SPACE_ID found: {space_id_startup}")
202
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
203
  print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
204
  else:
205
  print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
206
 
207
+ print("-"*(60 + len(" App Starting ")) + "\n")
208
 
209
  print("Launching Gradio Interface for Basic Agent Evaluation...")
210
  demo.launch(debug=True, share=False)