Spaces:
Sleeping
Sleeping
Renzo
commited on
Commit
·
d68986e
1
Parent(s):
745d7fa
Refactor agent and app modules to enhance functionality and improve response handling
Browse files- agent.py +17 -4
- app.py +29 -17
- requirements.txt +3 -1
agent.py
CHANGED
@@ -1,18 +1,31 @@
|
|
1 |
-
from agno.agent import Agent
|
2 |
from agno.models.openai import OpenAIChat
|
3 |
-
from agno.playground import Playground, serve_playground_app
|
4 |
from agno.tools.reasoning import ReasoningTools
|
|
|
|
|
5 |
|
6 |
test_question = "On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?"
|
7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
agent = Agent(
|
9 |
model=OpenAIChat(id="gpt-4.1-nano"),
|
10 |
-
markdown=
|
11 |
debug_mode=True,
|
12 |
-
instructions="
|
13 |
tools=[
|
14 |
ReasoningTools(think=True, add_few_shot=True),
|
|
|
|
|
15 |
],
|
|
|
|
|
|
|
16 |
)
|
17 |
|
18 |
# Print the response in the terminal
|
|
|
1 |
+
from agno.agent import Agent
|
2 |
from agno.models.openai import OpenAIChat
|
|
|
3 |
from agno.tools.reasoning import ReasoningTools
|
4 |
+
from agno.tools.duckduckgo import DuckDuckGoTools
|
5 |
+
from agno.tools.wikipedia import WikipediaTools
|
6 |
|
7 |
test_question = "On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?"
|
8 |
|
9 |
+
|
10 |
+
def get_current_date() -> str:
|
11 |
+
import datetime
|
12 |
+
date = datetime.datetime.now().strftime("%Y-%m-%d")
|
13 |
+
return "The current date is " + date
|
14 |
+
|
15 |
+
|
16 |
agent = Agent(
|
17 |
model=OpenAIChat(id="gpt-4.1-nano"),
|
18 |
+
markdown=False,
|
19 |
debug_mode=True,
|
20 |
+
instructions="You are a general AI assistant. I will ask you a question. Report your thoughts, but your final answer must be only the answer itself, with nothing else. The answer should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.",
|
21 |
tools=[
|
22 |
ReasoningTools(think=True, add_few_shot=True),
|
23 |
+
DuckDuckGoTools(fixed_max_results=5),
|
24 |
+
WikipediaTools()
|
25 |
],
|
26 |
+
context={"current_time": get_current_date},
|
27 |
+
add_context=True,
|
28 |
+
show_tool_calls=True
|
29 |
)
|
30 |
|
31 |
# Print the response in the terminal
|
app.py
CHANGED
@@ -1,34 +1,46 @@
|
|
1 |
import os
|
|
|
2 |
import gradio as gr
|
3 |
import requests
|
4 |
import inspect
|
5 |
import pandas as pd
|
|
|
|
|
6 |
|
7 |
# (Keep Constants as is)
|
8 |
# --- Constants ---
|
9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
10 |
|
|
|
11 |
# --- Basic Agent Definition ---
|
12 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
|
|
|
|
|
|
|
|
|
|
13 |
class BasicAgent:
|
14 |
def __init__(self):
|
15 |
print("BasicAgent initialized.")
|
|
|
16 |
def __call__(self, question: str) -> str:
|
17 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
18 |
fixed_answer = "This is a default answer."
|
19 |
-
|
20 |
-
|
|
|
|
|
21 |
|
22 |
-
def run_and_submit_all(
|
23 |
"""
|
24 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
25 |
and displays the results.
|
26 |
"""
|
27 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
28 |
-
space_id = os.getenv("SPACE_ID")
|
29 |
|
30 |
if profile:
|
31 |
-
username= f"{profile.username}"
|
32 |
print(f"User logged in: {username}")
|
33 |
else:
|
34 |
print("User not logged in.")
|
@@ -55,16 +67,16 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
55 |
response.raise_for_status()
|
56 |
questions_data = response.json()
|
57 |
if not questions_data:
|
58 |
-
|
59 |
-
|
60 |
print(f"Fetched {len(questions_data)} questions.")
|
61 |
except requests.exceptions.RequestException as e:
|
62 |
print(f"Error fetching questions: {e}")
|
63 |
return f"Error fetching questions: {e}", None
|
64 |
except requests.exceptions.JSONDecodeError as e:
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
except Exception as e:
|
69 |
print(f"An unexpected error occurred fetching questions: {e}")
|
70 |
return f"An unexpected error occurred fetching questions: {e}", None
|
@@ -84,8 +96,8 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
84 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
85 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
86 |
except Exception as e:
|
87 |
-
|
88 |
-
|
89 |
|
90 |
if not answers_payload:
|
91 |
print("Agent did not produce any answers to submit.")
|
@@ -172,10 +184,10 @@ with gr.Blocks() as demo:
|
|
172 |
)
|
173 |
|
174 |
if __name__ == "__main__":
|
175 |
-
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
176 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
177 |
space_host_startup = os.getenv("SPACE_HOST")
|
178 |
-
space_id_startup = os.getenv("SPACE_ID")
|
179 |
|
180 |
if space_host_startup:
|
181 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
@@ -183,14 +195,14 @@ if __name__ == "__main__":
|
|
183 |
else:
|
184 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
185 |
|
186 |
-
if space_id_startup:
|
187 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
188 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
189 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
190 |
else:
|
191 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
192 |
|
193 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
194 |
|
195 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
196 |
-
demo.launch(debug=True, share=False)
|
|
|
1 |
import os
|
2 |
+
import asyncio
|
3 |
import gradio as gr
|
4 |
import requests
|
5 |
import inspect
|
6 |
import pandas as pd
|
7 |
+
from agent import agent
|
8 |
+
from agno.agent import RunResponse
|
9 |
|
10 |
# (Keep Constants as is)
|
11 |
# --- Constants ---
|
12 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
13 |
|
14 |
+
|
15 |
# --- Basic Agent Definition ---
|
16 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
17 |
+
async def _async_answer(answer_text: str) -> str:
|
18 |
+
response: RunResponse = await agent.arun(answer_text)
|
19 |
+
return response.content
|
20 |
+
|
21 |
+
|
22 |
class BasicAgent:
|
23 |
def __init__(self):
|
24 |
print("BasicAgent initialized.")
|
25 |
+
|
26 |
def __call__(self, question: str) -> str:
|
27 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
28 |
fixed_answer = "This is a default answer."
|
29 |
+
answer = asyncio.run(_async_answer(question))
|
30 |
+
print(f"Agent returning fixed answer: {answer}")
|
31 |
+
return answer
|
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.")
|
|
|
67 |
response.raise_for_status()
|
68 |
questions_data = response.json()
|
69 |
if not questions_data:
|
70 |
+
print("Fetched questions list is empty.")
|
71 |
+
return "Fetched questions list is empty or invalid format.", None
|
72 |
print(f"Fetched {len(questions_data)} questions.")
|
73 |
except requests.exceptions.RequestException as e:
|
74 |
print(f"Error fetching questions: {e}")
|
75 |
return f"Error fetching questions: {e}", None
|
76 |
except requests.exceptions.JSONDecodeError as e:
|
77 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
78 |
+
print(f"Response text: {response.text[:500]}")
|
79 |
+
return f"Error decoding server response for questions: {e}", None
|
80 |
except Exception as e:
|
81 |
print(f"An unexpected error occurred fetching questions: {e}")
|
82 |
return f"An unexpected error occurred fetching questions: {e}", None
|
|
|
96 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
97 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
98 |
except Exception as e:
|
99 |
+
print(f"Error running agent on task {task_id}: {e}")
|
100 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
101 |
|
102 |
if not answers_payload:
|
103 |
print("Agent did not produce any answers to submit.")
|
|
|
184 |
)
|
185 |
|
186 |
if __name__ == "__main__":
|
187 |
+
print("\n" + "-" * 30 + " App Starting " + "-" * 30)
|
188 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
189 |
space_host_startup = os.getenv("SPACE_HOST")
|
190 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
191 |
|
192 |
if space_host_startup:
|
193 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
|
195 |
else:
|
196 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
197 |
|
198 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
199 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
200 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
201 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
202 |
else:
|
203 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
204 |
|
205 |
+
print("-" * (60 + len(" App Starting ")) + "\n")
|
206 |
|
207 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
208 |
+
demo.launch(debug=True, share=False)
|
requirements.txt
CHANGED
@@ -1,4 +1,6 @@
|
|
1 |
gradio
|
2 |
requests
|
3 |
agno
|
4 |
-
openai
|
|
|
|
|
|
1 |
gradio
|
2 |
requests
|
3 |
agno
|
4 |
+
openai
|
5 |
+
duckduckgo-search
|
6 |
+
wikipedia
|