grevy commited on
Commit
73526a5
·
1 Parent(s): 81917a3

Wire agent to langgraph.

Browse files
Files changed (4) hide show
  1. .python-version +1 -0
  2. app.py +87 -34
  3. pyproject.toml +7 -0
  4. tools.py +0 -0
.python-version ADDED
@@ -0,0 +1 @@
 
 
1
+ 3.13
app.py CHANGED
@@ -3,32 +3,66 @@ 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.")
@@ -55,16 +89,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
@@ -81,18 +115,36 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
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
 
@@ -143,8 +195,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
143
  # --- Build Gradio Interface using Blocks ---
144
  with gr.Blocks() as demo:
145
  gr.Markdown("# Basic Agent Evaluation Runner")
146
- gr.Markdown(
147
- """
148
  **Instructions:**
149
 
150
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
@@ -155,27 +206,25 @@ with gr.Blocks() as demo:
155
  **Disclaimers:**
156
  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).
157
  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.
158
- """
159
- )
160
 
161
  gr.LoginButton()
162
 
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(
170
- fn=run_and_submit_all,
171
- outputs=[status_output, results_table]
172
- )
173
 
174
  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,14 +232,18 @@ 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")
 
 
190
  else:
191
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
 
 
192
 
193
- print("-"*(60 + len(" App Starting ")) + "\n")
194
 
195
  print("Launching Gradio Interface for Basic Agent Evaluation...")
196
- demo.launch(debug=True, share=False)
 
3
  import requests
4
  import inspect
5
  import pandas as pd
6
+ from langchain_ollama import ChatOllama
7
+ from typing import TypedDict, Annotated
8
+ from langgraph.graph.message import add_messages
9
+ from langgraph.graph import START, StateGraph, END
10
+ from langchain_core.messages import AnyMessage, HumanMessage
11
 
12
  # (Keep Constants as is)
13
  # --- Constants ---
14
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
15
 
16
+
17
  # --- Basic Agent Definition ---
18
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
19
+
20
+
21
+ class AgentState(TypedDict):
22
+ messages: Annotated[list[AnyMessage], add_messages]
23
+
24
+
25
  class BasicAgent:
26
  def __init__(self):
27
  print("BasicAgent initialized.")
28
+
29
+ self.chat = ChatOllama(
30
+ model="qwen2.5:14b-instruct-q4_K_M",
31
+ base_url="http://localhost:11434",
32
+ )
33
+ self.agent = self.__init__agent()
34
+
35
  def __call__(self, question: str) -> str:
36
+ return self.answer(question)
37
+
38
+ def __init__agent(self):
39
+ builder = StateGraph(AgentState)
40
+ builder.add_node("assistant", self.assitant)
41
+ builder.add_edge(START, "assistant")
42
+ builder.add_edge("assistant", END)
43
+ return builder.compile()
44
 
45
+ def assitant(self, state: AgentState):
46
+ return {
47
+ "messages": [self.chat.invoke(state["messages"])],
48
+ }
49
+
50
+ def answer(self, question):
51
+ messages = [HumanMessage(content=question)]
52
+ response = self.agent.invoke({"messages": messages})
53
+ return response["messages"][-1].content
54
+
55
+
56
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
57
  """
58
  Fetches all questions, runs the BasicAgent on them, submits all answers,
59
  and displays the results.
60
  """
61
  # --- Determine HF Space Runtime URL and Repo URL ---
62
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
63
 
64
  if profile:
65
+ username = f"{profile.username}"
66
  print(f"User logged in: {username}")
67
  else:
68
  print("User not logged in.")
 
89
  response.raise_for_status()
90
  questions_data = response.json()
91
  if not questions_data:
92
+ print("Fetched questions list is empty.")
93
+ return "Fetched questions list is empty or invalid format.", None
94
  print(f"Fetched {len(questions_data)} questions.")
95
  except requests.exceptions.RequestException as e:
96
  print(f"Error fetching questions: {e}")
97
  return f"Error fetching questions: {e}", None
98
  except requests.exceptions.JSONDecodeError as e:
99
+ print(f"Error decoding JSON response from questions endpoint: {e}")
100
+ print(f"Response text: {response.text[:500]}")
101
+ return f"Error decoding server response for questions: {e}", None
102
  except Exception as e:
103
  print(f"An unexpected error occurred fetching questions: {e}")
104
  return f"An unexpected error occurred fetching questions: {e}", None
 
115
  continue
116
  try:
117
  submitted_answer = agent(question_text)
118
+ answers_payload.append(
119
+ {"task_id": task_id, "submitted_answer": submitted_answer}
120
+ )
121
+ results_log.append(
122
+ {
123
+ "Task ID": task_id,
124
+ "Question": question_text,
125
+ "Submitted Answer": submitted_answer,
126
+ }
127
+ )
128
  except Exception as e:
129
+ print(f"Error running agent on task {task_id}: {e}")
130
+ results_log.append(
131
+ {
132
+ "Task ID": task_id,
133
+ "Question": question_text,
134
+ "Submitted Answer": f"AGENT ERROR: {e}",
135
+ }
136
+ )
137
 
138
  if not answers_payload:
139
  print("Agent did not produce any answers to submit.")
140
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
141
 
142
+ # 4. Prepare Submission
143
+ submission_data = {
144
+ "username": username.strip(),
145
+ "agent_code": agent_code,
146
+ "answers": answers_payload,
147
+ }
148
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
149
  print(status_update)
150
 
 
195
  # --- Build Gradio Interface using Blocks ---
196
  with gr.Blocks() as demo:
197
  gr.Markdown("# Basic Agent Evaluation Runner")
198
+ gr.Markdown("""
 
199
  **Instructions:**
200
 
201
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
 
206
  **Disclaimers:**
207
  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).
208
  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.
209
+ """)
 
210
 
211
  gr.LoginButton()
212
 
213
  run_button = gr.Button("Run Evaluation & Submit All Answers")
214
 
215
+ status_output = gr.Textbox(
216
+ label="Run Status / Submission Result", lines=5, interactive=False
217
+ )
218
  # Removed max_rows=10 from DataFrame constructor
219
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
220
 
221
+ run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
 
 
 
222
 
223
  if __name__ == "__main__":
224
+ print("\n" + "-" * 30 + " App Starting " + "-" * 30)
225
  # Check for SPACE_HOST and SPACE_ID at startup for information
226
  space_host_startup = os.getenv("SPACE_HOST")
227
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
228
 
229
  if space_host_startup:
230
  print(f"✅ SPACE_HOST found: {space_host_startup}")
 
232
  else:
233
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
234
 
235
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
236
  print(f"✅ SPACE_ID found: {space_id_startup}")
237
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
238
+ print(
239
+ f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main"
240
+ )
241
  else:
242
+ print(
243
+ "ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined."
244
+ )
245
 
246
+ print("-" * (60 + len(" App Starting ")) + "\n")
247
 
248
  print("Launching Gradio Interface for Basic Agent Evaluation...")
249
+ demo.launch(debug=True, share=False)
pyproject.toml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "final-assignment-template"
3
+ version = "0.1.0"
4
+ description = "Add your description here"
5
+ readme = "README.md"
6
+ requires-python = ">=3.13"
7
+ dependencies = []
tools.py ADDED
File without changes