Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -962,302 +962,41 @@ safe_workflow.add_edge("tool_executor", "safety")
|
|
| 962 |
# )
|
| 963 |
# safe_workflow.add_edge("tool_executor", END)
|
| 964 |
|
| 965 |
-
|
| 966 |
|
| 967 |
-
|
| 968 |
-
|
| 969 |
-
# ---
|
| 970 |
-
|
| 971 |
-
class BasicAgent:
|
| 972 |
-
def __init__(self):
|
| 973 |
-
self.safe_app = safe_workflow.compile()
|
| 974 |
-
|
| 975 |
-
print("BasicAgent initialized.")
|
| 976 |
-
def __call__(self, task_id: str, question: str, filename: str) -> str:
|
| 977 |
-
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 978 |
-
fixed_answer = "This is a default answer."
|
| 979 |
-
# print(f"Agent returning fixed answer: {fixed_answer}")
|
| 980 |
-
|
| 981 |
-
|
| 982 |
-
# if question == "Given this table defining * on the set S = {a, b, c, d, e}\n\n|*|a|b|c|d|e|\n|---|---|---|---|---|---|\n|a|a|b|c|b|d|\n|b|b|c|a|e|c|\n|c|c|a|b|b|a|\n|d|b|e|b|e|d|\n|e|d|b|a|d|c|\n\nprovide the subset of S involved in any possible counter-examples that prove * is not commutative. Provide your answer as a comma separated list of the elements in the set in alphabetical order.":
|
| 983 |
-
# if " image " not in question and " video " not in question:
|
| 984 |
-
# if question == "Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?" or question == "What is the first name of the only Malko Competition recipient from the 20th Century (after 1977) whose nationality on record is a country that no longer exists?":
|
| 985 |
-
# if question == "The attached Excel file contains the sales of menu items for a local fast-food chain. What were the total sales that the chain made from food (not including drinks)? Express your answer in USD with two decimal places.":
|
| 986 |
-
|
| 987 |
-
if question != "aalskdalsdh":
|
| 988 |
-
|
| 989 |
-
# if question == "Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations.":
|
| 990 |
-
|
| 991 |
-
state = {
|
| 992 |
-
"messages": question,
|
| 993 |
-
}
|
| 994 |
-
|
| 995 |
-
if len(tokenizer.encode(state["messages"][::-1])) < len(tokenizer.encode(state["messages"])):
|
| 996 |
-
state["messages"] = state["messages"][::-1]
|
| 997 |
-
|
| 998 |
-
|
| 999 |
-
# Replace with your actual API base URL
|
| 1000 |
-
BASE_URL = f"{DEFAULT_API_URL}/files"
|
| 1001 |
-
|
| 1002 |
-
# Construct the full URL
|
| 1003 |
-
url = f"{BASE_URL}/{task_id}"
|
| 1004 |
-
|
| 1005 |
-
# Send GET request
|
| 1006 |
-
response = requests.get(url)
|
| 1007 |
-
|
| 1008 |
-
# Check if the request was successful
|
| 1009 |
-
if response.status_code == 200:
|
| 1010 |
-
# Save the content to a local file
|
| 1011 |
-
with open(filename, "wb") as f:
|
| 1012 |
-
f.write(response.content)
|
| 1013 |
-
print("File downloaded successfully!")
|
| 1014 |
-
else:
|
| 1015 |
-
print(f"Failed to download file: {response.status_code}")
|
| 1016 |
-
|
| 1017 |
-
# df = pd.read_excel(filename)
|
| 1018 |
-
|
| 1019 |
-
try:
|
| 1020 |
-
response = self.safe_app.invoke(state)
|
| 1021 |
-
agent_answer = response["output"]
|
| 1022 |
-
|
| 1023 |
-
# agent_answer = str(df)
|
| 1024 |
-
# agent_answer = str(response.status_code) + " - " + task_id
|
| 1025 |
-
except Exception as e:
|
| 1026 |
-
agent_answer = str(e)
|
| 1027 |
-
|
| 1028 |
-
else:
|
| 1029 |
-
agent_answer = fixed_answer
|
| 1030 |
-
# agent_answer = self.agent.run(question)
|
| 1031 |
-
|
| 1032 |
-
|
| 1033 |
-
# print(f"Agent Answer: {agent_answer}")
|
| 1034 |
-
|
| 1035 |
-
return agent_answer
|
| 1036 |
-
|
| 1037 |
-
|
| 1038 |
-
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 1039 |
"""
|
| 1040 |
-
|
| 1041 |
-
and displays the results.
|
| 1042 |
"""
|
| 1043 |
-
|
| 1044 |
-
|
| 1045 |
-
|
| 1046 |
-
if profile:
|
| 1047 |
-
username= f"{profile.username}"
|
| 1048 |
-
print(f"User logged in: {username}")
|
| 1049 |
-
else:
|
| 1050 |
-
print("User not logged in.")
|
| 1051 |
-
return "Please Login to Hugging Face with the button.", None
|
| 1052 |
-
|
| 1053 |
-
api_url = DEFAULT_API_URL
|
| 1054 |
-
questions_url = f"{api_url}/questions"
|
| 1055 |
-
submit_url = f"{api_url}/submit"
|
| 1056 |
-
|
| 1057 |
-
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 1058 |
-
try:
|
| 1059 |
-
agent = BasicAgent()
|
| 1060 |
-
except Exception as e:
|
| 1061 |
-
print(f"Error instantiating agent: {e}")
|
| 1062 |
-
return f"Error initializing agent: {e}", None
|
| 1063 |
-
# 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)
|
| 1064 |
-
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 1065 |
-
print(agent_code)
|
| 1066 |
-
|
| 1067 |
-
# 2. Fetch Questions
|
| 1068 |
-
print(f"Fetching questions from: {questions_url}")
|
| 1069 |
-
try:
|
| 1070 |
-
# response = requests.get(questions_url, timeout=15)
|
| 1071 |
-
# response.raise_for_status()
|
| 1072 |
-
# questions_data = response.json()
|
| 1073 |
-
|
| 1074 |
|
| 1075 |
-
|
| 1076 |
-
|
| 1077 |
-
|
| 1078 |
-
if not questions_data:
|
| 1079 |
-
print("Fetched questions list is empty.")
|
| 1080 |
-
return "Fetched questions list is empty or invalid format.", None
|
| 1081 |
-
print(f"Fetched {len(questions_data)} questions.")
|
| 1082 |
-
except requests.exceptions.RequestException as e:
|
| 1083 |
-
print(f"Error fetching questions: {e}")
|
| 1084 |
-
return f"Error fetching questions: {e}", None
|
| 1085 |
-
except requests.exceptions.JSONDecodeError as e:
|
| 1086 |
-
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 1087 |
-
print(f"Response text: {response.text[:500]}")
|
| 1088 |
-
return f"Error decoding server response for questions: {e}", None
|
| 1089 |
-
except Exception as e:
|
| 1090 |
-
print(f"An unexpected error occurred fetching questions: {e}")
|
| 1091 |
-
return f"An unexpected error occurred fetching questions: {e}", None
|
| 1092 |
-
|
| 1093 |
-
|
| 1094 |
-
|
| 1095 |
-
|
| 1096 |
-
|
| 1097 |
-
# questions_data = [
|
| 1098 |
-
# {
|
| 1099 |
-
# "task_id": 1,
|
| 1100 |
-
# "question": "What is the outcome of 12 squared?"
|
| 1101 |
-
# },
|
| 1102 |
-
# ]
|
| 1103 |
-
|
| 1104 |
-
# # 3. Run your Agent
|
| 1105 |
-
# results_log = []
|
| 1106 |
-
# answers_payload = []
|
| 1107 |
-
# print(f"Running agent on {len(questions_data)} questions...")
|
| 1108 |
-
# for item in questions_data:
|
| 1109 |
-
# task_id = item.get("task_id")
|
| 1110 |
-
# question_text = item.get("question")
|
| 1111 |
-
# if not task_id or question_text is None:
|
| 1112 |
-
# print(f"Skipping item with missing task_id or question: {item}")
|
| 1113 |
-
# continue
|
| 1114 |
-
# try:
|
| 1115 |
-
# submitted_answer = agent(question_text)
|
| 1116 |
-
# answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 1117 |
-
# results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 1118 |
-
# except Exception as e:
|
| 1119 |
-
# print(f"Error running agent on task {task_id}: {e}")
|
| 1120 |
-
# results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 1121 |
-
|
| 1122 |
-
# if not answers_payload:
|
| 1123 |
-
# print("Agent did not produce any answers to submit.")
|
| 1124 |
-
# return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 1125 |
-
|
| 1126 |
-
# # 4. Prepare Submission
|
| 1127 |
-
# submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 1128 |
-
# status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 1129 |
-
# print(status_update)
|
| 1130 |
-
# results_df = pd.DataFrame(results_log)
|
| 1131 |
-
# print(results_df)
|
| 1132 |
-
|
| 1133 |
-
|
| 1134 |
-
|
| 1135 |
-
|
| 1136 |
-
|
| 1137 |
-
|
| 1138 |
-
# 3. Run your Agent
|
| 1139 |
-
results_log = []
|
| 1140 |
-
answers_payload = []
|
| 1141 |
-
print(f"Running agent on {len(questions_data)} questions...")
|
| 1142 |
-
for item in questions_data:
|
| 1143 |
-
task_id = item.get("task_id")
|
| 1144 |
-
question_text = item.get("question")
|
| 1145 |
-
filename = item.get("file_name")
|
| 1146 |
-
if not task_id or question_text is None:
|
| 1147 |
-
print(f"Skipping item with missing task_id or question: {item}")
|
| 1148 |
-
continue
|
| 1149 |
-
try:
|
| 1150 |
-
submitted_answer = agent(task_id, question_text, filename)
|
| 1151 |
-
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 1152 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 1153 |
-
except Exception as e:
|
| 1154 |
-
print(f"Error running agent on task {task_id}: {e}")
|
| 1155 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 1156 |
-
|
| 1157 |
-
if not answers_payload:
|
| 1158 |
-
print("Agent did not produce any answers to submit.")
|
| 1159 |
-
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 1160 |
-
|
| 1161 |
-
# 4. Prepare Submission
|
| 1162 |
-
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 1163 |
-
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 1164 |
-
print(status_update)
|
| 1165 |
-
|
| 1166 |
-
# 5. Submit
|
| 1167 |
-
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 1168 |
-
try:
|
| 1169 |
-
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 1170 |
-
response.raise_for_status()
|
| 1171 |
-
result_data = response.json()
|
| 1172 |
-
final_status = (
|
| 1173 |
-
f"Submission Successful!\n"
|
| 1174 |
-
f"User: {result_data.get('username')}\n"
|
| 1175 |
-
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 1176 |
-
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 1177 |
-
f"Message: {result_data.get('message', 'No message received.')}"
|
| 1178 |
-
)
|
| 1179 |
-
print("Submission successful.")
|
| 1180 |
-
results_df = pd.DataFrame(results_log)
|
| 1181 |
-
return final_status, results_df
|
| 1182 |
-
except requests.exceptions.HTTPError as e:
|
| 1183 |
-
error_detail = f"Server responded with status {e.response.status_code}."
|
| 1184 |
-
try:
|
| 1185 |
-
error_json = e.response.json()
|
| 1186 |
-
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 1187 |
-
except requests.exceptions.JSONDecodeError:
|
| 1188 |
-
error_detail += f" Response: {e.response.text[:500]}"
|
| 1189 |
-
status_message = f"Submission Failed: {error_detail}"
|
| 1190 |
-
print(status_message)
|
| 1191 |
-
results_df = pd.DataFrame(results_log)
|
| 1192 |
-
return status_message, results_df
|
| 1193 |
-
except requests.exceptions.Timeout:
|
| 1194 |
-
status_message = "Submission Failed: The request timed out."
|
| 1195 |
-
print(status_message)
|
| 1196 |
-
results_df = pd.DataFrame(results_log)
|
| 1197 |
-
return status_message, results_df
|
| 1198 |
-
except requests.exceptions.RequestException as e:
|
| 1199 |
-
status_message = f"Submission Failed: Network error - {e}"
|
| 1200 |
-
print(status_message)
|
| 1201 |
-
results_df = pd.DataFrame(results_log)
|
| 1202 |
-
return status_message, results_df
|
| 1203 |
-
except Exception as e:
|
| 1204 |
-
status_message = f"An unexpected error occurred during submission: {e}"
|
| 1205 |
-
print(status_message)
|
| 1206 |
-
results_df = pd.DataFrame(results_log)
|
| 1207 |
-
return status_message, results_df
|
| 1208 |
-
|
| 1209 |
-
|
| 1210 |
-
# --- Build Gradio Interface using Blocks ---
|
| 1211 |
with gr.Blocks() as demo:
|
| 1212 |
-
gr.Markdown("#
|
| 1213 |
-
|
| 1214 |
-
|
| 1215 |
-
|
| 1216 |
-
|
| 1217 |
-
|
| 1218 |
-
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 1219 |
-
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 1220 |
-
|
| 1221 |
-
---
|
| 1222 |
-
**Disclaimers:**
|
| 1223 |
-
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).
|
| 1224 |
-
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.
|
| 1225 |
-
"""
|
| 1226 |
)
|
| 1227 |
-
|
| 1228 |
-
gr.
|
| 1229 |
-
|
| 1230 |
-
|
| 1231 |
-
|
| 1232 |
-
|
| 1233 |
-
|
| 1234 |
-
|
| 1235 |
-
|
| 1236 |
-
|
| 1237 |
-
|
| 1238 |
-
outputs=[status_output, results_table]
|
| 1239 |
)
|
| 1240 |
|
| 1241 |
-
|
| 1242 |
-
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 1243 |
-
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 1244 |
-
space_host_startup = os.getenv("SPACE_HOST")
|
| 1245 |
-
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 1246 |
-
|
| 1247 |
-
if space_host_startup:
|
| 1248 |
-
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 1249 |
-
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 1250 |
-
else:
|
| 1251 |
-
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 1252 |
-
|
| 1253 |
-
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 1254 |
-
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 1255 |
-
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 1256 |
-
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 1257 |
-
else:
|
| 1258 |
-
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 1259 |
-
|
| 1260 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 1261 |
-
|
| 1262 |
-
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 1263 |
-
demo.launch(debug=True, share=False)
|
|
|
|
| 962 |
# )
|
| 963 |
# safe_workflow.add_edge("tool_executor", END)
|
| 964 |
|
| 965 |
+
safe_app = safe_workflow.compile()
|
| 966 |
|
| 967 |
+
# --------------------------
|
| 968 |
+
# Define user query function
|
| 969 |
+
# --------------------------
|
| 970 |
+
def answer_question(user_question):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 971 |
"""
|
| 972 |
+
Send the user input to your LangGraph agent and return the response.
|
|
|
|
| 973 |
"""
|
| 974 |
+
result = app.invoke({"messages": user_question})
|
| 975 |
+
agent_answer = result["output"]
|
| 976 |
+
return agent_answer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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= gr.Textbox(
|
| 985 |
+
label="Your Question",
|
| 986 |
+
placeholder="Type any question here...",
|
| 987 |
+
lines=2
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 988 |
)
|
| 989 |
+
|
| 990 |
+
answer_output = gr.Textbox(
|
| 991 |
+
label="Agent Response"
|
| 992 |
+
)
|
| 993 |
+
|
| 994 |
+
submit_btn = gr.Button("Ask")
|
| 995 |
+
|
| 996 |
+
submit_btn.click(
|
| 997 |
+
fn=answer_question,
|
| 998 |
+
inputs=user_input,
|
| 999 |
+
outputs=answer_output
|
|
|
|
| 1000 |
)
|
| 1001 |
|
| 1002 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|