Update app.py
Browse files
app.py
CHANGED
|
@@ -85,8 +85,30 @@ For example, if asked "What is the capital of France?", respond simply with "Par
|
|
| 85 |
print(f"Raw response type: {type(raw_response)}")
|
| 86 |
print(f"Raw response: {raw_response}")
|
| 87 |
|
| 88 |
-
# Handle ALL possible response formats
|
| 89 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
if self.verbose:
|
| 92 |
print(f"Extracted answer type: {type(answer)}")
|
|
@@ -112,71 +134,28 @@ For example, if asked "What is the capital of France?", respond simply with "Par
|
|
| 112 |
traceback.print_exc()
|
| 113 |
return error_msg
|
| 114 |
|
| 115 |
-
def
|
| 116 |
"""
|
| 117 |
-
|
| 118 |
-
This handles dict, list, and nested combinations.
|
| 119 |
"""
|
| 120 |
-
|
| 121 |
-
return ""
|
| 122 |
-
|
| 123 |
-
# If it's already a string, return it
|
| 124 |
-
if isinstance(response, str):
|
| 125 |
-
return response
|
| 126 |
-
|
| 127 |
-
# If it's a dict, try to get 'content' or 'message'
|
| 128 |
-
if isinstance(response, dict):
|
| 129 |
-
# Try common keys
|
| 130 |
-
for key in ['content', 'message', 'text', 'answer']:
|
| 131 |
-
if key in response:
|
| 132 |
-
return self._extract_answer(response[key])
|
| 133 |
-
# Try OpenAI-style format
|
| 134 |
-
if 'choices' in response:
|
| 135 |
-
choices = response['choices']
|
| 136 |
-
if choices and len(choices) > 0:
|
| 137 |
-
return self._extract_answer(choices[0])
|
| 138 |
-
# If nothing found, convert to string
|
| 139 |
-
return str(response)
|
| 140 |
-
|
| 141 |
-
# If it's a list, recursively process elements
|
| 142 |
-
if isinstance(response, list):
|
| 143 |
-
if len(response) == 0:
|
| 144 |
-
return ""
|
| 145 |
-
# Try to extract from first element
|
| 146 |
-
first_element = self._extract_answer(response[0])
|
| 147 |
-
# If first element is empty or None, try other elements
|
| 148 |
-
if not first_element and len(response) > 1:
|
| 149 |
-
for element in response[1:]:
|
| 150 |
-
extracted = self._extract_answer(element)
|
| 151 |
-
if extracted:
|
| 152 |
-
return extracted
|
| 153 |
-
return first_element
|
| 154 |
-
|
| 155 |
-
# For any other type, convert to string
|
| 156 |
-
return str(response)
|
| 157 |
-
|
| 158 |
-
def _clean_answer(self, answer) -> str:
|
| 159 |
-
"""
|
| 160 |
-
Ultra-safe answer extraction and cleaning.
|
| 161 |
-
Ensures the answer is always a string.
|
| 162 |
-
"""
|
| 163 |
-
# First, ensure we have a string
|
| 164 |
try:
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
if not isinstance(answer, str):
|
| 171 |
answer = str(answer)
|
| 172 |
-
|
| 173 |
except Exception as e:
|
| 174 |
print(f"Error in initial conversion: {e}")
|
| 175 |
-
|
| 176 |
-
try:
|
| 177 |
-
return str(answer) if answer else ""
|
| 178 |
-
except:
|
| 179 |
-
return ""
|
| 180 |
|
| 181 |
# Now answer should definitely be a string
|
| 182 |
try:
|
|
@@ -201,21 +180,23 @@ For example, if asked "What is the capital of France?", respond simply with "Par
|
|
| 201 |
|
| 202 |
return answer
|
| 203 |
except Exception as e:
|
| 204 |
-
print(f"Error in answer cleaning: {e}")
|
| 205 |
-
|
| 206 |
-
try:
|
| 207 |
-
return str(answer) if answer else ""
|
| 208 |
-
except:
|
| 209 |
-
return ""
|
| 210 |
|
| 211 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 212 |
"""
|
| 213 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 214 |
and displays the results.
|
| 215 |
"""
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
api_url = DEFAULT_API_URL
|
| 220 |
questions_url = f"{api_url}/questions"
|
| 221 |
submit_url = f"{api_url}/submit"
|
|
@@ -274,7 +255,6 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 274 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 275 |
except Exception as e:
|
| 276 |
print(f"Error running agent on task {task_id}: {e}")
|
| 277 |
-
traceback.print_exc()
|
| 278 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 279 |
|
| 280 |
if not answers_payload:
|
|
@@ -326,7 +306,6 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 326 |
except Exception as e:
|
| 327 |
status_message = f"An unexpected error occurred during submission: {e}"
|
| 328 |
print(status_message)
|
| 329 |
-
traceback.print_exc()
|
| 330 |
results_df = pd.DataFrame(results_log)
|
| 331 |
return status_message, results_df
|
| 332 |
|
|
@@ -382,7 +361,7 @@ class Tee:
|
|
| 382 |
|
| 383 |
if __name__ == "__main__":
|
| 384 |
# Redirect stdout and stderr
|
| 385 |
-
log_timestamp = datetime.now().strftime("%Y-%m-%
|
| 386 |
log_file = f"./logs/output_{log_timestamp}.log"
|
| 387 |
tee = Tee(log_file)
|
| 388 |
sys.stdout = tee
|
|
|
|
| 85 |
print(f"Raw response type: {type(raw_response)}")
|
| 86 |
print(f"Raw response: {raw_response}")
|
| 87 |
|
| 88 |
+
# Handle ALL possible response formats
|
| 89 |
+
if isinstance(raw_response, dict):
|
| 90 |
+
answer = raw_response.get('choices', [{}])[0].get('message', {}).get('content', str(raw_response))
|
| 91 |
+
elif isinstance(raw_response, list):
|
| 92 |
+
if len(raw_response) > 0:
|
| 93 |
+
if isinstance(raw_response[0], dict):
|
| 94 |
+
# Common format: [{"role": "assistant", "content": "..."}]
|
| 95 |
+
answer = raw_response[0].get('content', str(raw_response[0]))
|
| 96 |
+
elif isinstance(raw_response[0], list):
|
| 97 |
+
# Nested list - dig deeper
|
| 98 |
+
nested = raw_response[0]
|
| 99 |
+
if isinstance(nested, list) and len(nested) > 0:
|
| 100 |
+
if isinstance(nested[0], dict):
|
| 101 |
+
answer = nested[0].get('content', str(nested[0]))
|
| 102 |
+
else:
|
| 103 |
+
answer = str(nested[0])
|
| 104 |
+
else:
|
| 105 |
+
answer = str(raw_response[0])
|
| 106 |
+
else:
|
| 107 |
+
answer = str(raw_response[0])
|
| 108 |
+
else:
|
| 109 |
+
answer = "No response"
|
| 110 |
+
else:
|
| 111 |
+
answer = str(raw_response)
|
| 112 |
|
| 113 |
if self.verbose:
|
| 114 |
print(f"Extracted answer type: {type(answer)}")
|
|
|
|
| 134 |
traceback.print_exc()
|
| 135 |
return error_msg
|
| 136 |
|
| 137 |
+
def _clean_answer(self, answer: any) -> str:
|
| 138 |
"""
|
| 139 |
+
Ultra-safe answer extraction and cleaning
|
|
|
|
| 140 |
"""
|
| 141 |
+
# Force to string immediately with extra safety
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
try:
|
| 143 |
+
if answer is None:
|
| 144 |
+
return ""
|
| 145 |
+
if isinstance(answer, list):
|
| 146 |
+
# If it's a list, try to extract meaningful content
|
| 147 |
+
if len(answer) == 0:
|
| 148 |
+
return ""
|
| 149 |
+
# Try to get content from first element
|
| 150 |
+
answer = answer[0] if len(answer) > 0 else ""
|
| 151 |
+
if isinstance(answer, dict):
|
| 152 |
+
# If it's a dict, try to get 'content' or convert to string
|
| 153 |
+
answer = answer.get('content', str(answer))
|
| 154 |
if not isinstance(answer, str):
|
| 155 |
answer = str(answer)
|
|
|
|
| 156 |
except Exception as e:
|
| 157 |
print(f"Error in initial conversion: {e}")
|
| 158 |
+
return str(answer) if answer else ""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
|
| 160 |
# Now answer should definitely be a string
|
| 161 |
try:
|
|
|
|
| 180 |
|
| 181 |
return answer
|
| 182 |
except Exception as e:
|
| 183 |
+
print(f"Error in answer cleaning: {e}, returning raw string")
|
| 184 |
+
return str(answer) if answer else ""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
|
| 186 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 187 |
"""
|
| 188 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 189 |
and displays the results.
|
| 190 |
"""
|
| 191 |
+
space_id = os.getenv("SPACE_ID")
|
| 192 |
+
|
| 193 |
+
if profile:
|
| 194 |
+
username = f"{profile.username}"
|
| 195 |
+
print(f"User logged in: {username}")
|
| 196 |
+
else:
|
| 197 |
+
print("User not logged in.")
|
| 198 |
+
return "Please Login to Hugging Face with the button.", None
|
| 199 |
+
|
| 200 |
api_url = DEFAULT_API_URL
|
| 201 |
questions_url = f"{api_url}/questions"
|
| 202 |
submit_url = f"{api_url}/submit"
|
|
|
|
| 255 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 256 |
except Exception as e:
|
| 257 |
print(f"Error running agent on task {task_id}: {e}")
|
|
|
|
| 258 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 259 |
|
| 260 |
if not answers_payload:
|
|
|
|
| 306 |
except Exception as e:
|
| 307 |
status_message = f"An unexpected error occurred during submission: {e}"
|
| 308 |
print(status_message)
|
|
|
|
| 309 |
results_df = pd.DataFrame(results_log)
|
| 310 |
return status_message, results_df
|
| 311 |
|
|
|
|
| 361 |
|
| 362 |
if __name__ == "__main__":
|
| 363 |
# Redirect stdout and stderr
|
| 364 |
+
log_timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 365 |
log_file = f"./logs/output_{log_timestamp}.log"
|
| 366 |
tee = Tee(log_file)
|
| 367 |
sys.stdout = tee
|