Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -5,8 +5,7 @@ import gradio as gr
|
|
5 |
import requests
|
6 |
import pandas as pd
|
7 |
from langchain_core.messages import HumanMessage
|
8 |
-
from agent import ninu
|
9 |
-
|
10 |
|
11 |
|
12 |
# (Keep Constants as is)
|
@@ -14,14 +13,13 @@ from agent import ninu
|
|
14 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
15 |
|
16 |
# --- Basic Agent Definition ---
|
17 |
-
# ----- THIS IS
|
18 |
-
|
19 |
|
20 |
class BasicAgent:
|
21 |
"""A langgraph agent."""
|
22 |
def __init__(self):
|
23 |
print("BasicAgent initialized.")
|
24 |
-
self.graph =
|
25 |
|
26 |
def __call__(self, question: str) -> str:
|
27 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
@@ -29,19 +27,20 @@ class BasicAgent:
|
|
29 |
messages = [HumanMessage(content=question)]
|
30 |
messages = self.graph.invoke({"messages": messages})
|
31 |
answer = messages['messages'][-1].content
|
|
|
32 |
return answer[14:]
|
33 |
|
34 |
|
35 |
-
def run_and_submit_all(
|
36 |
"""
|
37 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
38 |
and displays the results.
|
39 |
"""
|
40 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
41 |
-
space_id = os.getenv("SPACE_ID")
|
42 |
|
43 |
if profile:
|
44 |
-
username= f"{profile.username}"
|
45 |
print(f"User logged in: {username}")
|
46 |
else:
|
47 |
print("User not logged in.")
|
@@ -57,7 +56,8 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
57 |
except Exception as e:
|
58 |
print(f"Error instantiating agent: {e}")
|
59 |
return f"Error initializing agent: {e}", None
|
60 |
-
|
|
|
61 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
62 |
print(agent_code)
|
63 |
|
@@ -68,16 +68,16 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
68 |
response.raise_for_status()
|
69 |
questions_data = response.json()
|
70 |
if not questions_data:
|
71 |
-
|
72 |
-
|
73 |
print(f"Fetched {len(questions_data)} questions.")
|
74 |
except requests.exceptions.RequestException as e:
|
75 |
print(f"Error fetching questions: {e}")
|
76 |
return f"Error fetching questions: {e}", None
|
77 |
except requests.exceptions.JSONDecodeError as e:
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
except Exception as e:
|
82 |
print(f"An unexpected error occurred fetching questions: {e}")
|
83 |
return f"An unexpected error occurred fetching questions: {e}", None
|
@@ -97,14 +97,14 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
97 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
98 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
99 |
except Exception as e:
|
100 |
-
|
101 |
-
|
102 |
|
103 |
if not answers_payload:
|
104 |
print("Agent did not produce any answers to submit.")
|
105 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
106 |
|
107 |
-
# 4. Prepare Submission
|
108 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
109 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
110 |
print(status_update)
|
@@ -165,7 +165,7 @@ with gr.Blocks() as demo:
|
|
165 |
---
|
166 |
**Disclaimers:**
|
167 |
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).
|
168 |
-
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
|
169 |
"""
|
170 |
)
|
171 |
|
@@ -183,10 +183,10 @@ with gr.Blocks() as demo:
|
|
183 |
)
|
184 |
|
185 |
if __name__ == "__main__":
|
186 |
-
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
187 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
188 |
space_host_startup = os.getenv("SPACE_HOST")
|
189 |
-
space_id_startup = os.getenv("SPACE_ID")
|
190 |
|
191 |
if space_host_startup:
|
192 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
@@ -194,14 +194,14 @@ if __name__ == "__main__":
|
|
194 |
else:
|
195 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
196 |
|
197 |
-
if space_id_startup:
|
198 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
199 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
200 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
201 |
else:
|
202 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
203 |
|
204 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
205 |
|
206 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
207 |
-
demo.launch(debug=True, share=False)
|
|
|
5 |
import requests
|
6 |
import pandas as pd
|
7 |
from langchain_core.messages import HumanMessage
|
8 |
+
from agent import ninu # استيراد دالة بناء الـ agent من ملف agent.py
|
|
|
9 |
|
10 |
|
11 |
# (Keep Constants as is)
|
|
|
13 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
14 |
|
15 |
# --- Basic Agent Definition ---
|
16 |
+
# ----- THIS IS WHERE YOU CAN BUILD WHAT YOU WANT ------
|
|
|
17 |
|
18 |
class BasicAgent:
|
19 |
"""A langgraph agent."""
|
20 |
def __init__(self):
|
21 |
print("BasicAgent initialized.")
|
22 |
+
self.graph = ninu() # نستخدم دالة ninu لبناء الـ graph
|
23 |
|
24 |
def __call__(self, question: str) -> str:
|
25 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
|
|
27 |
messages = [HumanMessage(content=question)]
|
28 |
messages = self.graph.invoke({"messages": messages})
|
29 |
answer = messages['messages'][-1].content
|
30 |
+
# تفصيل هذه السطر حسب إجابة الـ agent لديك، أنا حافظتها كما كانت
|
31 |
return answer[14:]
|
32 |
|
33 |
|
34 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
35 |
"""
|
36 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
37 |
and displays the results.
|
38 |
"""
|
39 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
40 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
41 |
|
42 |
if profile:
|
43 |
+
username = f"{profile.username}"
|
44 |
print(f"User logged in: {username}")
|
45 |
else:
|
46 |
print("User not logged in.")
|
|
|
56 |
except Exception as e:
|
57 |
print(f"Error instantiating agent: {e}")
|
58 |
return f"Error initializing agent: {e}", None
|
59 |
+
|
60 |
+
# Link to your HF repo (if running as a HF space)
|
61 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
62 |
print(agent_code)
|
63 |
|
|
|
68 |
response.raise_for_status()
|
69 |
questions_data = response.json()
|
70 |
if not questions_data:
|
71 |
+
print("Fetched questions list is empty.")
|
72 |
+
return "Fetched questions list is empty or invalid format.", None
|
73 |
print(f"Fetched {len(questions_data)} questions.")
|
74 |
except requests.exceptions.RequestException as e:
|
75 |
print(f"Error fetching questions: {e}")
|
76 |
return f"Error fetching questions: {e}", None
|
77 |
except requests.exceptions.JSONDecodeError as e:
|
78 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
79 |
+
print(f"Response text: {response.text[:500]}")
|
80 |
+
return f"Error decoding server response for questions: {e}", None
|
81 |
except Exception as e:
|
82 |
print(f"An unexpected error occurred fetching questions: {e}")
|
83 |
return f"An unexpected error occurred fetching questions: {e}", None
|
|
|
97 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
98 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
99 |
except Exception as e:
|
100 |
+
print(f"Error running agent on task {task_id}: {e}")
|
101 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
102 |
|
103 |
if not answers_payload:
|
104 |
print("Agent did not produce any answers to submit.")
|
105 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
106 |
|
107 |
+
# 4. Prepare Submission
|
108 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
109 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
110 |
print(status_update)
|
|
|
165 |
---
|
166 |
**Disclaimers:**
|
167 |
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).
|
168 |
+
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 separate action or even to answer the questions asynchronously.
|
169 |
"""
|
170 |
)
|
171 |
|
|
|
183 |
)
|
184 |
|
185 |
if __name__ == "__main__":
|
186 |
+
print("\n" + "-" * 30 + " App Starting " + "-" * 30)
|
187 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
188 |
space_host_startup = os.getenv("SPACE_HOST")
|
189 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
190 |
|
191 |
if space_host_startup:
|
192 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
|
194 |
else:
|
195 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
196 |
|
197 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
198 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
199 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
200 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
201 |
else:
|
202 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
203 |
|
204 |
+
print("-" * (60 + len(" App Starting ")) + "\n")
|
205 |
|
206 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
207 |
+
demo.launch(debug=True, share=False)
|