Fixed 'str' object is not callable error.
Browse files
app.py
CHANGED
@@ -11,41 +11,42 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
11 |
|
12 |
# --- Basic Agent Definition ---
|
13 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
|
|
|
|
14 |
class BasicAgent:
|
15 |
def __init__(self):
|
16 |
print("BasicAgent initialized with smolagents.")
|
17 |
# Initialize CodeAgent with required 'tools' and 'model' parameters
|
18 |
# Using Qwen code model instead of gpt-3.5-turbo
|
19 |
tools = [] # Empty list of tools or define your specific tools here
|
20 |
-
model = "Qwen/
|
21 |
self.agent = CodeAgent(tools=tools, model=model)
|
22 |
-
|
23 |
def __call__(self, question: str) -> str:
|
24 |
print(f"Agent received question: {question[:50]}...")
|
25 |
-
|
26 |
try:
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
else:
|
32 |
-
answer = f"Search result for '{question[:50]}...': {search_result}"
|
33 |
except Exception as e:
|
34 |
answer = f"Error during search: {e}"
|
35 |
-
|
36 |
-
print(f"Agent returning answer: {answer}")
|
37 |
return answer
|
38 |
|
39 |
-
|
|
|
40 |
"""
|
41 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
42 |
and displays the results.
|
43 |
"""
|
44 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
45 |
-
space_id = os.getenv("SPACE_ID")
|
46 |
|
47 |
if profile:
|
48 |
-
username= f"{profile.username}"
|
49 |
print(f"User logged in: {username}")
|
50 |
else:
|
51 |
print("User not logged in.")
|
@@ -72,16 +73,16 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
72 |
response.raise_for_status()
|
73 |
questions_data = response.json()
|
74 |
if not questions_data:
|
75 |
-
|
76 |
-
|
77 |
print(f"Fetched {len(questions_data)} questions.")
|
78 |
except requests.exceptions.RequestException as e:
|
79 |
print(f"Error fetching questions: {e}")
|
80 |
return f"Error fetching questions: {e}", None
|
81 |
except requests.exceptions.JSONDecodeError as e:
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
except Exception as e:
|
86 |
print(f"An unexpected error occurred fetching questions: {e}")
|
87 |
return f"An unexpected error occurred fetching questions: {e}", None
|
@@ -101,14 +102,14 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
101 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
102 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
103 |
except Exception as e:
|
104 |
-
|
105 |
-
|
106 |
|
107 |
if not answers_payload:
|
108 |
print("Agent did not produce any answers to submit.")
|
109 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
110 |
|
111 |
-
# 4. Prepare Submission
|
112 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
113 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
114 |
print(status_update)
|
@@ -159,7 +160,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
159 |
|
160 |
# --- Build Gradio Interface using Blocks ---
|
161 |
with gr.Blocks() as demo:
|
162 |
-
gr.Markdown("# Basic Agent Evaluation Runner (Test #
|
163 |
gr.Markdown(
|
164 |
"""
|
165 |
**Instructions:**
|
@@ -189,10 +190,10 @@ with gr.Blocks() as demo:
|
|
189 |
)
|
190 |
|
191 |
if __name__ == "__main__":
|
192 |
-
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
193 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
194 |
space_host_startup = os.getenv("SPACE_HOST")
|
195 |
-
space_id_startup = os.getenv("SPACE_ID")
|
196 |
|
197 |
if space_host_startup:
|
198 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
@@ -200,14 +201,14 @@ if __name__ == "__main__":
|
|
200 |
else:
|
201 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
202 |
|
203 |
-
if space_id_startup:
|
204 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
205 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
206 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
207 |
else:
|
208 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
209 |
|
210 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
211 |
|
212 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
213 |
-
demo.launch(debug=True, share=False)
|
|
|
11 |
|
12 |
# --- Basic Agent Definition ---
|
13 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
14 |
+
|
15 |
+
|
16 |
class BasicAgent:
|
17 |
def __init__(self):
|
18 |
print("BasicAgent initialized with smolagents.")
|
19 |
# Initialize CodeAgent with required 'tools' and 'model' parameters
|
20 |
# Using Qwen code model instead of gpt-3.5-turbo
|
21 |
tools = [] # Empty list of tools or define your specific tools here
|
22 |
+
model = "Qwen/Qwen1.5-14B-Chat" # Using Qwen code model
|
23 |
self.agent = CodeAgent(tools=tools, model=model)
|
24 |
+
|
25 |
def __call__(self, question: str) -> str:
|
26 |
print(f"Agent received question: {question[:50]}...")
|
27 |
+
|
28 |
try:
|
29 |
+
# Format the question as a proper prompt for CodeAgent
|
30 |
+
prompt = f"Answer this question: {question}"
|
31 |
+
search_result = self.agent.run(prompt=prompt) # Pass the prompt with named parameter
|
32 |
+
answer = search_result # Return the direct result from the agent
|
|
|
|
|
33 |
except Exception as e:
|
34 |
answer = f"Error during search: {e}"
|
35 |
+
|
36 |
+
print(f"Agent returning answer: {answer[:100]}...") # Print just a preview
|
37 |
return answer
|
38 |
|
39 |
+
|
40 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
41 |
"""
|
42 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
43 |
and displays the results.
|
44 |
"""
|
45 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
46 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
47 |
|
48 |
if profile:
|
49 |
+
username = f"{profile.username}"
|
50 |
print(f"User logged in: {username}")
|
51 |
else:
|
52 |
print("User not logged in.")
|
|
|
73 |
response.raise_for_status()
|
74 |
questions_data = response.json()
|
75 |
if not questions_data:
|
76 |
+
print("Fetched questions list is empty.")
|
77 |
+
return "Fetched questions list is empty or invalid format.", None
|
78 |
print(f"Fetched {len(questions_data)} questions.")
|
79 |
except requests.exceptions.RequestException as e:
|
80 |
print(f"Error fetching questions: {e}")
|
81 |
return f"Error fetching questions: {e}", None
|
82 |
except requests.exceptions.JSONDecodeError as e:
|
83 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
84 |
+
print(f"Response text: {response.text[:500]}")
|
85 |
+
return f"Error decoding server response for questions: {e}", None
|
86 |
except Exception as e:
|
87 |
print(f"An unexpected error occurred fetching questions: {e}")
|
88 |
return f"An unexpected error occurred fetching questions: {e}", None
|
|
|
102 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
103 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
104 |
except Exception as e:
|
105 |
+
print(f"Error running agent on task {task_id}: {e}")
|
106 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
107 |
|
108 |
if not answers_payload:
|
109 |
print("Agent did not produce any answers to submit.")
|
110 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
111 |
|
112 |
+
# 4. Prepare Submission
|
113 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
114 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
115 |
print(status_update)
|
|
|
160 |
|
161 |
# --- Build Gradio Interface using Blocks ---
|
162 |
with gr.Blocks() as demo:
|
163 |
+
gr.Markdown("# Basic Agent Evaluation Runner (Test #4)")
|
164 |
gr.Markdown(
|
165 |
"""
|
166 |
**Instructions:**
|
|
|
190 |
)
|
191 |
|
192 |
if __name__ == "__main__":
|
193 |
+
print("\n" + "-" * 30 + " App Starting " + "-" * 30)
|
194 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
195 |
space_host_startup = os.getenv("SPACE_HOST")
|
196 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
197 |
|
198 |
if space_host_startup:
|
199 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
|
201 |
else:
|
202 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
203 |
|
204 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
205 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
206 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
207 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
208 |
else:
|
209 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
210 |
|
211 |
+
print("-" * (60 + len(" App Starting ")) + "\n")
|
212 |
|
213 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
214 |
+
demo.launch(debug=True, share=False)
|