EtienneB commited on
Commit
05454e1
·
1 Parent(s): a718e51

update with async issues

Browse files
Files changed (1) hide show
  1. app.py +69 -37
app.py CHANGED
@@ -44,7 +44,7 @@ class BasicAgent:
44
  get_current_time_in_timezone
45
  ]
46
 
47
- self.chat_with_tools = self.chat.with_tools(self.tools)
48
  print(f"Total tools available: {len(self.tools)}")
49
 
50
  async def answer(self, question: str) -> str:
@@ -53,33 +53,56 @@ class BasicAgent:
53
  response = await asyncio.to_thread(self.chat_with_tools.invoke, {"messages": messages})
54
  return response['messages'][-1].content[14:]
55
 
56
- async def run_agent_async(agent, questions_data):
57
- # results_log, answers_payload = [], []
58
- tasks = []
 
 
 
59
 
60
- print(f"Running agent on {len(questions_data)} questions...")
61
- results_log, answers_payload = asyncio.run(run_agent_async(agent, questions_data))
 
62
 
63
- async def process(task_id, question):
64
  try:
65
  answer = await agent.answer(question)
66
  return task_id, question, answer, None
67
  except Exception as e:
68
  return task_id, question, None, str(e)
69
 
70
- results = await asyncio.gather(*(process(tid, q) for tid, q in tasks))
71
- for tid, question, answer, error in results:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  if error:
73
- print(f"Error running agent on task {tid}: {error}")
74
- results_log.append({"Task ID": tid, "Question": question, "Submitted Answer": f"AGENT ERROR: {error}"})
75
  else:
76
- answers_payload.append({"task_id": tid, "submitted_answer": answer})
77
- results_log.append({"Task ID": tid, "Question": question, "Submitted Answer": answer})
78
 
79
  return results_log, answers_payload
80
 
81
 
82
- def run_and_submit_all( profile: gr.OAuthProfile | None):
83
  """
84
  Fetches all questions, runs the BasicAgent on them, submits all answers,
85
  and displays the results.
@@ -88,7 +111,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
88
  space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
89
 
90
  if profile:
91
- username= f"{profile.username}"
92
  print(f"User logged in: {username}")
93
  else:
94
  print("User not logged in.")
@@ -98,13 +121,14 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
98
  questions_url = f"{api_url}/questions"
99
  submit_url = f"{api_url}/submit"
100
 
101
- # 1. Instantiate Agent ( modify this part to create your agent)
102
  try:
103
  agent = BasicAgent()
104
  except Exception as e:
105
  print(f"Error instantiating agent: {e}")
106
  return f"Error initializing agent: {e}", None
107
- # 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)
 
108
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
109
  print(agent_code)
110
 
@@ -115,16 +139,16 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
115
  response.raise_for_status()
116
  questions_data = response.json()
117
  if not questions_data:
118
- print("Fetched questions list is empty.")
119
- return "Fetched questions list is empty or invalid format.", None
120
  print(f"Fetched {len(questions_data)} questions.")
121
  except requests.exceptions.RequestException as e:
122
  print(f"Error fetching questions: {e}")
123
  return f"Error fetching questions: {e}", None
124
  except requests.exceptions.JSONDecodeError as e:
125
- print(f"Error decoding JSON response from questions endpoint: {e}")
126
- print(f"Response text: {response.text[:500]}")
127
- return f"Error decoding server response for questions: {e}", None
128
  except Exception as e:
129
  print(f"An unexpected error occurred fetching questions: {e}")
130
  return f"An unexpected error occurred fetching questions: {e}", None
@@ -132,20 +156,27 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
132
  # 3. Run your Agent
133
  results_log = []
134
  answers_payload = []
135
- print(f"Running agent on {len(questions_data)} questions...")
136
- for item in questions_data:
137
- task_id = item.get("task_id")
138
- question_text = item.get("question")
139
- if not task_id or question_text is None:
140
- print(f"Skipping item with missing task_id or question: {item}")
141
- continue
142
- try:
143
- submitted_answer = agent(question_text)
144
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
145
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
146
- except Exception as e:
147
- print(f"Error running agent on task {task_id}: {e}")
148
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
 
 
 
 
 
149
 
150
  if not answers_payload:
151
  print("Agent did not produce any answers to submit.")
@@ -253,4 +284,5 @@ if __name__ == "__main__":
253
  print("-"*(60 + len(" App Starting ")) + "\n")
254
 
255
  print("Launching Gradio Interface for Basic Agent Evaluation...")
256
- demo.launch(debug=True, share=False)
 
 
44
  get_current_time_in_timezone
45
  ]
46
 
47
+ self.chat_with_tools = self.chat.bind_tools(self.tools)
48
  print(f"Total tools available: {len(self.tools)}")
49
 
50
  async def answer(self, question: str) -> str:
 
53
  response = await asyncio.to_thread(self.chat_with_tools.invoke, {"messages": messages})
54
  return response['messages'][-1].content[14:]
55
 
56
+ def answer_sync(self, question: str) -> str:
57
+ """Synchronous version of answer method"""
58
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
59
+ messages = [HumanMessage(content=question)]
60
+ response = self.chat_with_tools.invoke({"messages": messages})
61
+ return response.content
62
 
63
+ async def run_agent_async(agent, questions_data):
64
+ """Run agent asynchronously on all questions"""
65
+ results_log, answers_payload = [], []
66
 
67
+ async def process_question(task_id, question):
68
  try:
69
  answer = await agent.answer(question)
70
  return task_id, question, answer, None
71
  except Exception as e:
72
  return task_id, question, None, str(e)
73
 
74
+ # Create tasks for all questions
75
+ tasks = []
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
+ tasks.append(process_question(task_id, question_text))
83
+
84
+ print(f"Processing {len(tasks)} questions asynchronously...")
85
+
86
+ # Process all questions concurrently
87
+ results = await asyncio.gather(*tasks, return_exceptions=True)
88
+
89
+ for result in results:
90
+ if isinstance(result, Exception):
91
+ print(f"Unexpected error: {result}")
92
+ continue
93
+
94
+ task_id, question, answer, error = result
95
  if error:
96
+ print(f"Error running agent on task {task_id}: {error}")
97
+ results_log.append({"Task ID": task_id, "Question": question, "Submitted Answer": f"AGENT ERROR: {error}"})
98
  else:
99
+ answers_payload.append({"task_id": task_id, "submitted_answer": answer})
100
+ results_log.append({"Task ID": task_id, "Question": question, "Submitted Answer": answer})
101
 
102
  return results_log, answers_payload
103
 
104
 
105
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
106
  """
107
  Fetches all questions, runs the BasicAgent on them, submits all answers,
108
  and displays the results.
 
111
  space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
112
 
113
  if profile:
114
+ username = f"{profile.username}"
115
  print(f"User logged in: {username}")
116
  else:
117
  print("User not logged in.")
 
121
  questions_url = f"{api_url}/questions"
122
  submit_url = f"{api_url}/submit"
123
 
124
+ # 1. Instantiate Agent (modify this part to create your agent)
125
  try:
126
  agent = BasicAgent()
127
  except Exception as e:
128
  print(f"Error instantiating agent: {e}")
129
  return f"Error initializing agent: {e}", None
130
+
131
+ # In the case of an app running as a Hugging Face space, this link points toward your codebase (useful for others so please keep it public)
132
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
133
  print(agent_code)
134
 
 
139
  response.raise_for_status()
140
  questions_data = response.json()
141
  if not questions_data:
142
+ print("Fetched questions list is empty.")
143
+ return "Fetched questions list is empty or invalid format.", None
144
  print(f"Fetched {len(questions_data)} questions.")
145
  except requests.exceptions.RequestException as e:
146
  print(f"Error fetching questions: {e}")
147
  return f"Error fetching questions: {e}", None
148
  except requests.exceptions.JSONDecodeError as e:
149
+ print(f"Error decoding JSON response from questions endpoint: {e}")
150
+ print(f"Response text: {response.text[:500]}")
151
+ return f"Error decoding server response for questions: {e}", None
152
  except Exception as e:
153
  print(f"An unexpected error occurred fetching questions: {e}")
154
  return f"An unexpected error occurred fetching questions: {e}", None
 
156
  # 3. Run your Agent
157
  results_log = []
158
  answers_payload = []
159
+
160
+ # Try async approach first, fall back to sync if needed
161
+ try:
162
+ print(f"Running agent asynchronously on {len(questions_data)} questions...")
163
+ results_log, answers_payload = asyncio.run(run_agent_async(agent, questions_data))
164
+ except Exception as e:
165
+ print(f"Async processing failed: {e}, falling back to synchronous processing...")
166
+ # Fallback to synchronous processing
167
+ for item in questions_data:
168
+ task_id = item.get("task_id")
169
+ question_text = item.get("question")
170
+ if not task_id or question_text is None:
171
+ print(f"Skipping item with missing task_id or question: {item}")
172
+ continue
173
+ try:
174
+ submitted_answer = agent.answer_sync(question_text)
175
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
176
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
177
+ except Exception as e:
178
+ print(f"Error running agent on task {task_id}: {e}")
179
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
180
 
181
  if not answers_payload:
182
  print("Agent did not produce any answers to submit.")
 
284
  print("-"*(60 + len(" App Starting ")) + "\n")
285
 
286
  print("Launching Gradio Interface for Basic Agent Evaluation...")
287
+ demo.launch(debug=True, share=False)
288
+