refactor: replace requests with httpx for asynchronous HTTP calls and update error handling in app.py
Browse files- app.py +25 -92
- workflow.py +0 -3
app.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
-
import
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
from agent import BasicAgent
|
|
@@ -10,74 +10,7 @@ from workflow import MultiStepWorkflow
|
|
| 10 |
# --- Constants ---
|
| 11 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 12 |
|
| 13 |
-
def
|
| 14 |
-
api_url = DEFAULT_API_URL
|
| 15 |
-
random_question_url = f"{api_url}/random-question"
|
| 16 |
-
submit_url = f"{api_url}/submit"
|
| 17 |
-
|
| 18 |
-
try:
|
| 19 |
-
agent = BasicAgent(verbose=True)
|
| 20 |
-
except Exception as e:
|
| 21 |
-
print(f"Error instantiating agent: {e}")
|
| 22 |
-
return f"Error initializing agent: {e}", None
|
| 23 |
-
|
| 24 |
-
try:
|
| 25 |
-
response = requests.get(random_question_url, timeout=15)
|
| 26 |
-
response.raise_for_status()
|
| 27 |
-
question_data = response.json()
|
| 28 |
-
if not question_data:
|
| 29 |
-
return "Fetched questions list is empty or invalid format.", None
|
| 30 |
-
print(f"Fetched {len(question_data)} questions.")
|
| 31 |
-
except requests.exceptions.JSONDecodeError as e:
|
| 32 |
-
return f"Error decoding server response for questions: {e}", None
|
| 33 |
-
except requests.exceptions.RequestException as e:
|
| 34 |
-
return f"Error fetching questions: {e}", None
|
| 35 |
-
except Exception as e:
|
| 36 |
-
return f"An unexpected error occurred fetching questions: {e}", None
|
| 37 |
-
|
| 38 |
-
results_log = []
|
| 39 |
-
answers_payload = []
|
| 40 |
-
|
| 41 |
-
task_id = question_data.get("task_id")
|
| 42 |
-
question_text = question_data.get("question")
|
| 43 |
-
if not task_id or question_text is None:
|
| 44 |
-
print(f"Skipping item with missing task_id or question: {question_data}")
|
| 45 |
-
try:
|
| 46 |
-
submitted_answer = agent.call_sync(question_text)
|
| 47 |
-
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 48 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 49 |
-
except Exception as e:
|
| 50 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 51 |
-
|
| 52 |
-
if not answers_payload:
|
| 53 |
-
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 54 |
-
|
| 55 |
-
# 4. Prepare Submission
|
| 56 |
-
submission_data = {"username": 'agsagds', "agent_code": 'https://huggingface.co/spaces/agsagds/Unit_3_Agentic_RAG/tree/main', "answers": answers_payload}
|
| 57 |
-
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user agsagds..."
|
| 58 |
-
print(status_update)
|
| 59 |
-
|
| 60 |
-
# 5. Submit
|
| 61 |
-
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 62 |
-
try:
|
| 63 |
-
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 64 |
-
response.raise_for_status()
|
| 65 |
-
result_data = response.json()
|
| 66 |
-
final_status = (
|
| 67 |
-
f"Submission Successful!\n"
|
| 68 |
-
f"User: {result_data.get('username')}\n"
|
| 69 |
-
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 70 |
-
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 71 |
-
f"Message: {result_data.get('message', 'No message received.')}"
|
| 72 |
-
)
|
| 73 |
-
print("Submission successful.")
|
| 74 |
-
results_log.append(final_status)
|
| 75 |
-
results_df = pd.DataFrame(results_log)
|
| 76 |
-
return results_df
|
| 77 |
-
except Exception as e:
|
| 78 |
-
return f"Error submitting answers: {e}", None
|
| 79 |
-
|
| 80 |
-
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 81 |
"""
|
| 82 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 83 |
and displays the results.
|
|
@@ -109,18 +42,18 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 109 |
# 2. Fetch Questions
|
| 110 |
print(f"Fetching questions from: {questions_url}")
|
| 111 |
try:
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
|
|
|
| 115 |
if not questions_data:
|
| 116 |
print("Fetched questions list is empty.")
|
| 117 |
return "Fetched questions list is empty or invalid format.", None
|
| 118 |
print(f"Fetched {len(questions_data)} questions.")
|
| 119 |
-
except
|
| 120 |
-
print(f"Error
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
except requests.exceptions.RequestException as e:
|
| 124 |
print(f"Error fetching questions: {e}")
|
| 125 |
return f"Error fetching questions: {e}", None
|
| 126 |
except Exception as e:
|
|
@@ -148,7 +81,13 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 148 |
continue
|
| 149 |
try:
|
| 150 |
print(f"Running agent workflow on question: {task_id} {question_text}")
|
| 151 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
print(f"Submitted answer: {submitted_answer}")
|
| 153 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 154 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
|
@@ -168,9 +107,10 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 168 |
# 5. Submit
|
| 169 |
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 170 |
try:
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
|
|
|
| 174 |
final_status = (
|
| 175 |
f"Submission Successful!\n"
|
| 176 |
f"User: {result_data.get('username')}\n"
|
|
@@ -181,23 +121,23 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 181 |
print("Submission successful.")
|
| 182 |
results_df = pd.DataFrame(results_log)
|
| 183 |
return final_status, results_df
|
| 184 |
-
except
|
| 185 |
error_detail = f"Server responded with status {e.response.status_code}."
|
| 186 |
try:
|
| 187 |
error_json = e.response.json()
|
| 188 |
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 189 |
-
except
|
| 190 |
error_detail += f" Response: {e.response.text[:500]}"
|
| 191 |
status_message = f"Submission Failed: {error_detail}"
|
| 192 |
print(status_message)
|
| 193 |
results_df = pd.DataFrame(results_log)
|
| 194 |
return status_message, results_df
|
| 195 |
-
except
|
| 196 |
status_message = "Submission Failed: The request timed out."
|
| 197 |
print(status_message)
|
| 198 |
results_df = pd.DataFrame(results_log)
|
| 199 |
return status_message, results_df
|
| 200 |
-
except
|
| 201 |
status_message = f"Submission Failed: Network error - {e}"
|
| 202 |
print(status_message)
|
| 203 |
results_df = pd.DataFrame(results_log)
|
|
@@ -207,8 +147,6 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 207 |
print(status_message)
|
| 208 |
results_df = pd.DataFrame(results_log)
|
| 209 |
return status_message, results_df
|
| 210 |
-
|
| 211 |
-
|
| 212 |
# Load evns from .env file
|
| 213 |
from dotenv import load_dotenv
|
| 214 |
load_dotenv()
|
|
@@ -234,7 +172,6 @@ with gr.Blocks() as demo:
|
|
| 234 |
gr.LoginButton()
|
| 235 |
|
| 236 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 237 |
-
run_once_button = gr.Button("Run Evaluation for random question")
|
| 238 |
|
| 239 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 240 |
# Removed max_rows=10 from DataFrame constructor
|
|
@@ -244,10 +181,6 @@ with gr.Blocks() as demo:
|
|
| 244 |
fn=run_and_submit_all,
|
| 245 |
outputs=[status_output, results_table]
|
| 246 |
)
|
| 247 |
-
run_once_button.click(
|
| 248 |
-
fn=run_and_print_random,
|
| 249 |
-
outputs=[results_table]
|
| 250 |
-
)
|
| 251 |
|
| 252 |
if __name__ == "__main__":
|
| 253 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
|
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
+
import httpx
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
from agent import BasicAgent
|
|
|
|
| 10 |
# --- Constants ---
|
| 11 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 12 |
|
| 13 |
+
async def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
"""
|
| 15 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 16 |
and displays the results.
|
|
|
|
| 42 |
# 2. Fetch Questions
|
| 43 |
print(f"Fetching questions from: {questions_url}")
|
| 44 |
try:
|
| 45 |
+
async with httpx.AsyncClient(timeout=15.0) as client:
|
| 46 |
+
response = await client.get(questions_url)
|
| 47 |
+
response.raise_for_status()
|
| 48 |
+
questions_data = response.json()
|
| 49 |
if not questions_data:
|
| 50 |
print("Fetched questions list is empty.")
|
| 51 |
return "Fetched questions list is empty or invalid format.", None
|
| 52 |
print(f"Fetched {len(questions_data)} questions.")
|
| 53 |
+
except httpx.HTTPStatusError as e:
|
| 54 |
+
print(f"Error fetching questions: HTTP {e.response.status_code}")
|
| 55 |
+
return f"Error fetching questions: HTTP {e.response.status_code}", None
|
| 56 |
+
except httpx.RequestError as e:
|
|
|
|
| 57 |
print(f"Error fetching questions: {e}")
|
| 58 |
return f"Error fetching questions: {e}", None
|
| 59 |
except Exception as e:
|
|
|
|
| 81 |
continue
|
| 82 |
try:
|
| 83 |
print(f"Running agent workflow on question: {task_id} {question_text}")
|
| 84 |
+
# Use async run method directly instead of callSync
|
| 85 |
+
result = await agent_workflow.run(question=question_text)
|
| 86 |
+
# Extract result if it's a StopEvent, otherwise use directly
|
| 87 |
+
if hasattr(result, 'result'):
|
| 88 |
+
submitted_answer = str(result.result)
|
| 89 |
+
else:
|
| 90 |
+
submitted_answer = str(result)
|
| 91 |
print(f"Submitted answer: {submitted_answer}")
|
| 92 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 93 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
|
|
|
| 107 |
# 5. Submit
|
| 108 |
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 109 |
try:
|
| 110 |
+
async with httpx.AsyncClient(timeout=60.0) as client:
|
| 111 |
+
response = await client.post(submit_url, json=submission_data)
|
| 112 |
+
response.raise_for_status()
|
| 113 |
+
result_data = response.json()
|
| 114 |
final_status = (
|
| 115 |
f"Submission Successful!\n"
|
| 116 |
f"User: {result_data.get('username')}\n"
|
|
|
|
| 121 |
print("Submission successful.")
|
| 122 |
results_df = pd.DataFrame(results_log)
|
| 123 |
return final_status, results_df
|
| 124 |
+
except httpx.HTTPStatusError as e:
|
| 125 |
error_detail = f"Server responded with status {e.response.status_code}."
|
| 126 |
try:
|
| 127 |
error_json = e.response.json()
|
| 128 |
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 129 |
+
except Exception:
|
| 130 |
error_detail += f" Response: {e.response.text[:500]}"
|
| 131 |
status_message = f"Submission Failed: {error_detail}"
|
| 132 |
print(status_message)
|
| 133 |
results_df = pd.DataFrame(results_log)
|
| 134 |
return status_message, results_df
|
| 135 |
+
except httpx.TimeoutException:
|
| 136 |
status_message = "Submission Failed: The request timed out."
|
| 137 |
print(status_message)
|
| 138 |
results_df = pd.DataFrame(results_log)
|
| 139 |
return status_message, results_df
|
| 140 |
+
except httpx.RequestError as e:
|
| 141 |
status_message = f"Submission Failed: Network error - {e}"
|
| 142 |
print(status_message)
|
| 143 |
results_df = pd.DataFrame(results_log)
|
|
|
|
| 147 |
print(status_message)
|
| 148 |
results_df = pd.DataFrame(results_log)
|
| 149 |
return status_message, results_df
|
|
|
|
|
|
|
| 150 |
# Load evns from .env file
|
| 151 |
from dotenv import load_dotenv
|
| 152 |
load_dotenv()
|
|
|
|
| 172 |
gr.LoginButton()
|
| 173 |
|
| 174 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
|
|
|
| 175 |
|
| 176 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 177 |
# Removed max_rows=10 from DataFrame constructor
|
|
|
|
| 181 |
fn=run_and_submit_all,
|
| 182 |
outputs=[status_output, results_table]
|
| 183 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
|
| 185 |
if __name__ == "__main__":
|
| 186 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
workflow.py
CHANGED
|
@@ -113,9 +113,6 @@ class MultiStepWorkflow(Workflow):
|
|
| 113 |
|
| 114 |
return StopEvent(result=str(formattedAnswer))
|
| 115 |
|
| 116 |
-
def callSync(self, question: str) -> str:
|
| 117 |
-
return asyncio.run(self.run(question=question))
|
| 118 |
-
|
| 119 |
if __name__ == "__main__":
|
| 120 |
async def main():
|
| 121 |
questionAlbums = "How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia."
|
|
|
|
| 113 |
|
| 114 |
return StopEvent(result=str(formattedAnswer))
|
| 115 |
|
|
|
|
|
|
|
|
|
|
| 116 |
if __name__ == "__main__":
|
| 117 |
async def main():
|
| 118 |
questionAlbums = "How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia."
|