mnosouhi96 commited on
Commit
0166bad
·
1 Parent(s): 2f74e6e

return tp openai

Browse files
Files changed (3) hide show
  1. agent.py +1 -1
  2. app.py +149 -60
  3. requirements.txt +26 -5
agent.py CHANGED
@@ -172,4 +172,4 @@ def build_graph(provider: str = "openai"):
172
  builder.add_conditional_edges("assistant", tools_condition)
173
  builder.add_edge("tools", "assistant")
174
 
175
- return builder.compile()
 
172
  builder.add_conditional_edges("assistant", tools_condition)
173
  builder.add_edge("tools", "assistant")
174
 
175
+ return builder.compile()
app.py CHANGED
@@ -1,115 +1,204 @@
1
  import os
2
  import gradio as gr
3
  import requests
 
4
  import pandas as pd
 
 
5
 
 
 
 
6
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
7
- SPACE_ID = "marjanns/Final_Assignment_Template"
 
 
 
 
8
 
9
  class BasicAgent:
10
  def __init__(self):
11
- print("BasicAgent initialized.")
 
 
12
  def __call__(self, question: str) -> str:
13
  print(f"Agent received question (first 50 chars): {question[:50]}...")
14
- return "This is a default answer."
15
-
16
- def _username_from_profile(p):
17
- if p is None:
18
- return None
19
- # object with attribute
20
- u = getattr(p, "username", None)
21
- if u:
22
- return str(u)
23
- # dict-style
24
- if isinstance(p, dict):
25
- return str(p.get("username") or "")
26
- return None
27
-
28
- def run_and_submit_all(profile, evt=None):
29
- space_id = SPACE_ID
30
- username = _username_from_profile(profile)
31
- if not username:
 
 
32
  return "Please Login to Hugging Face with the button.", None
33
 
34
  api_url = DEFAULT_API_URL
35
  questions_url = f"{api_url}/questions"
36
  submit_url = f"{api_url}/submit"
37
 
 
38
  try:
39
  agent = BasicAgent()
40
  except Exception as e:
 
41
  return f"Error initializing agent: {e}", None
42
-
43
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
 
44
 
 
 
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
- return "Fetched questions list is empty or invalid format.", None
51
- except Exception as e:
 
 
 
52
  return f"Error fetching questions: {e}", None
 
 
 
 
 
 
 
53
 
54
- results_log, answers_payload = [], []
 
 
 
55
  for item in questions_data:
56
- tid = item.get("task_id")
57
- q = item.get("question")
58
- if not tid or q is None:
 
59
  continue
60
  try:
61
- ans = agent(q)
 
 
62
  except Exception as e:
63
- ans = f"AGENT ERROR: {e}"
64
- answers_payload.append({"task_id": tid, "submitted_answer": ans})
65
- results_log.append({"Task ID": tid, "Question": q, "Submitted Answer": ans})
66
 
67
  if not answers_payload:
 
68
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
69
 
 
70
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
 
 
 
 
 
71
  try:
72
- resp = requests.post(submit_url, json=submission_data, timeout=60)
73
- resp.raise_for_status()
74
- data = resp.json()
75
- status = (
76
- "Submission Successful!\n"
77
- f"User: {data.get('username')}\n"
78
- f"Overall Score: {data.get('score','N/A')}% "
79
- f"({data.get('correct_count','?')}/{data.get('total_attempted','?')} correct)\n"
80
- f"Message: {data.get('message','No message received.')}"
81
  )
82
- return status, pd.DataFrame(results_log)
 
 
83
  except requests.exceptions.HTTPError as e:
 
84
  try:
85
- detail = e.response.json().get("detail", e.response.text)
86
- except Exception:
87
- detail = e.response.text
88
- return f"Submission Failed: HTTP {e.response.status_code}. Detail: {detail[:500]}", pd.DataFrame(results_log)
 
 
 
 
89
  except requests.exceptions.Timeout:
90
- return "Submission Failed: The request timed out.", pd.DataFrame(results_log)
 
 
 
 
 
 
 
 
91
  except Exception as e:
92
- return f"Submission Failed: {e}", pd.DataFrame(results_log)
 
 
 
93
 
 
 
94
  with gr.Blocks() as demo:
95
  gr.Markdown("# Basic Agent Evaluation Runner")
96
- gr.Markdown("Click **Log in with Hugging Face** first. After you see your username below, press **Run**.")
97
-
98
- login = gr.LoginButton()
99
- user_state = gr.State()
100
- whoami = gr.Markdown()
101
-
102
- def store_and_echo(p):
103
- u = _username_from_profile(p) or "(not logged in)"
104
- return p, f"✅ Logged in as **{u}**" if u and u != "(not logged in)" else "❌ Not logged in"
105
-
106
- login.click(store_and_echo, inputs=login, outputs=[user_state, whoami])
 
 
 
107
 
108
  run_button = gr.Button("Run Evaluation & Submit All Answers")
 
109
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
110
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
111
 
112
- run_button.click(fn=run_and_submit_all, inputs=[user_state], outputs=[status_output, results_table])
 
 
 
113
 
114
  if __name__ == "__main__":
115
- demo.launch(debug=True, share=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import gradio as gr
3
  import requests
4
+ import inspect
5
  import pandas as pd
6
+ from langchain_core.messages import HumanMessage
7
+ from agent import build_graph
8
 
9
+
10
+ # (Keep Constants as is)
11
+ # --- Constants ---
12
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
13
+
14
+ # --- Basic Agent Definition ---
15
+ # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
16
+ HF_TOKEN = os.getenv("HF_TOKEN")
17
+
18
 
19
  class BasicAgent:
20
  def __init__(self):
21
+ print("SmartAgent initialized.")
22
+ self.graph = build_graph()
23
+
24
  def __call__(self, question: str) -> str:
25
  print(f"Agent received question (first 50 chars): {question[:50]}...")
26
+ # Wrap the question in a HumanMessage from langchain_core
27
+ messages = [HumanMessage(content=question)]
28
+ messages = self.graph.invoke({"messages": messages})
29
+ answer = messages['messages'][-1].content
30
+ return answer[14:]
31
+
32
+
33
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
34
+ """
35
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
36
+ and displays the results.
37
+ """
38
+ # --- Determine HF Space Runtime URL and Repo URL ---
39
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
40
+
41
+ if profile:
42
+ username= f"{profile.username}"
43
+ print(f"User logged in: {username}")
44
+ else:
45
+ print("User not logged in.")
46
  return "Please Login to Hugging Face with the button.", None
47
 
48
  api_url = DEFAULT_API_URL
49
  questions_url = f"{api_url}/questions"
50
  submit_url = f"{api_url}/submit"
51
 
52
+ # 1. Instantiate Agent ( modify this part to create your agent)
53
  try:
54
  agent = BasicAgent()
55
  except Exception as e:
56
+ print(f"Error instantiating agent: {e}")
57
  return f"Error initializing agent: {e}", None
58
+ # 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)
59
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
60
+ print(agent_code)
61
 
62
+ # 2. Fetch Questions
63
+ print(f"Fetching questions from: {questions_url}")
64
  try:
65
  response = requests.get(questions_url, timeout=15)
66
  response.raise_for_status()
67
  questions_data = response.json()
68
  if not questions_data:
69
+ print("Fetched questions list is empty.")
70
+ return "Fetched questions list is empty or invalid format.", None
71
+ print(f"Fetched {len(questions_data)} questions.")
72
+ except requests.exceptions.RequestException as e:
73
+ print(f"Error fetching questions: {e}")
74
  return f"Error fetching questions: {e}", None
75
+ except requests.exceptions.JSONDecodeError as e:
76
+ print(f"Error decoding JSON response from questions endpoint: {e}")
77
+ print(f"Response text: {response.text[:500]}")
78
+ return f"Error decoding server response for questions: {e}", None
79
+ except Exception as e:
80
+ print(f"An unexpected error occurred fetching questions: {e}")
81
+ return f"An unexpected error occurred fetching questions: {e}", None
82
 
83
+ # 3. Run your Agent
84
+ results_log = []
85
+ answers_payload = []
86
+ print(f"Running agent on {len(questions_data)} questions...")
87
  for item in questions_data:
88
+ task_id = item.get("task_id")
89
+ question_text = item.get("question")
90
+ if not task_id or question_text is None:
91
+ print(f"Skipping item with missing task_id or question: {item}")
92
  continue
93
  try:
94
+ submitted_answer = agent(question_text)
95
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
96
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
97
  except Exception as e:
98
+ print(f"Error running agent on task {task_id}: {e}")
99
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
100
 
101
  if not answers_payload:
102
+ print("Agent did not produce any answers to submit.")
103
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
104
 
105
+ # 4. Prepare Submission
106
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
107
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
108
+ print(status_update)
109
+
110
+ # 5. Submit
111
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
112
  try:
113
+ response = requests.post(submit_url, json=submission_data, timeout=60)
114
+ response.raise_for_status()
115
+ result_data = response.json()
116
+ final_status = (
117
+ f"Submission Successful!\n"
118
+ f"User: {result_data.get('username')}\n"
119
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
120
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
121
+ f"Message: {result_data.get('message', 'No message received.')}"
122
  )
123
+ print("Submission successful.")
124
+ results_df = pd.DataFrame(results_log)
125
+ return final_status, results_df
126
  except requests.exceptions.HTTPError as e:
127
+ error_detail = f"Server responded with status {e.response.status_code}."
128
  try:
129
+ error_json = e.response.json()
130
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
131
+ except requests.exceptions.JSONDecodeError:
132
+ error_detail += f" Response: {e.response.text[:500]}"
133
+ status_message = f"Submission Failed: {error_detail}"
134
+ print(status_message)
135
+ results_df = pd.DataFrame(results_log)
136
+ return status_message, results_df
137
  except requests.exceptions.Timeout:
138
+ status_message = "Submission Failed: The request timed out."
139
+ print(status_message)
140
+ results_df = pd.DataFrame(results_log)
141
+ return status_message, results_df
142
+ except requests.exceptions.RequestException as e:
143
+ status_message = f"Submission Failed: Network error - {e}"
144
+ print(status_message)
145
+ results_df = pd.DataFrame(results_log)
146
+ return status_message, results_df
147
  except Exception as e:
148
+ status_message = f"An unexpected error occurred during submission: {e}"
149
+ print(status_message)
150
+ results_df = pd.DataFrame(results_log)
151
+ return status_message, results_df
152
 
153
+
154
+ # --- Build Gradio Interface using Blocks ---
155
  with gr.Blocks() as demo:
156
  gr.Markdown("# Basic Agent Evaluation Runner")
157
+ gr.Markdown(
158
+ """
159
+ **Instructions:**
160
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
161
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
162
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
163
+ ---
164
+ **Disclaimers:**
165
+ 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).
166
+ 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.
167
+ """
168
+ )
169
+
170
+ gr.LoginButton()
171
 
172
  run_button = gr.Button("Run Evaluation & Submit All Answers")
173
+
174
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
175
+ # Removed max_rows=10 from DataFrame constructor
176
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
177
 
178
+ run_button.click(
179
+ fn=run_and_submit_all,
180
+ outputs=[status_output, results_table]
181
+ )
182
 
183
  if __name__ == "__main__":
184
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
185
+ space_host_startup = os.getenv("SPACE_HOST")
186
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
187
+
188
+ if space_host_startup:
189
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
190
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
191
+ else:
192
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
193
+
194
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
195
+ print(f"✅ SPACE_ID found: {space_id_startup}")
196
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
197
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
198
+ else:
199
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
200
+
201
+ print("-"*(60 + len(" App Starting ")) + "\n")
202
+
203
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
204
+ demo.launch(debug=True, share=False)
requirements.txt CHANGED
@@ -50,8 +50,29 @@
50
  # requests
51
  # smolagents
52
  # smolagents[openai]
53
- gradio[oauth]>=4.44.0
54
- requests>=2.31.0
55
- pandas>=2.2.0
56
- itsdangerous>=2.1.2
57
- authlib>=1.3.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  # requests
51
  # smolagents
52
  # smolagents[openai]
53
+ # gradio[oauth]>=4.44.0
54
+ # requests>=2.31.0
55
+ # pandas>=2.2.0
56
+ # itsdangerous>=2.1.2
57
+ # authlib>=1.3.0
58
+ gradio
59
+ requests
60
+ langchain
61
+ langchain-community
62
+ langchain-core
63
+ langchain-google-genai
64
+ langchain-huggingface
65
+ langchain-groq
66
+ langchain_openai
67
+ langchain-tavily
68
+ langchain-chroma
69
+ langgraph
70
+ huggingface_hub
71
+ sentence-transformers
72
+ arxiv
73
+ pymupdf
74
+ wikipedia
75
+ pgvector
76
+ python-dotenv
77
+ protobuf==3.20.*
78
+ chromadb