Spaces:
Running
Running
223111524
commited on
Commit
·
1312d23
1
Parent(s):
81917a3
Added tools to BasicAgent
Browse files- app.py +109 -6
- requirements.txt +8 -1
app.py
CHANGED
@@ -3,23 +3,127 @@ 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 =
|
19 |
-
print(f"Agent returning
|
20 |
return fixed_answer
|
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.
|
@@ -91,7 +195,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
91 |
print("Agent did not produce any answers to submit.")
|
92 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
93 |
|
94 |
-
# 4. Prepare Submission
|
95 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
96 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
97 |
print(status_update)
|
@@ -139,7 +243,6 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
139 |
results_df = pd.DataFrame(results_log)
|
140 |
return status_message, results_df
|
141 |
|
142 |
-
|
143 |
# --- Build Gradio Interface using Blocks ---
|
144 |
with gr.Blocks() as demo:
|
145 |
gr.Markdown("# Basic Agent Evaluation Runner")
|
@@ -193,4 +296,4 @@ if __name__ == "__main__":
|
|
193 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
194 |
|
195 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
196 |
-
demo.launch(debug=True, share=False)
|
|
|
3 |
import requests
|
4 |
import inspect
|
5 |
import pandas as pd
|
6 |
+
from smolagents import OpenAIServerModel, DuckDuckGoSearchTool, CodeAgent, WikipediaSearchTool
|
7 |
+
from smolagents.tools import Tool
|
8 |
|
9 |
# (Keep Constants as is)
|
10 |
# --- Constants ---
|
11 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
12 |
|
13 |
+
class TextSummarizationTool(Tool):
|
14 |
+
"""Summarize long texts using a simple algorithm."""
|
15 |
+
|
16 |
+
name = "text_summarization"
|
17 |
+
description = "Summarize a long text into a shorter version."
|
18 |
+
|
19 |
+
inputs = {
|
20 |
+
"text": {
|
21 |
+
"type": "string",
|
22 |
+
"description": "The text to summarize.",
|
23 |
+
}
|
24 |
+
}
|
25 |
+
output_type = "string"
|
26 |
+
|
27 |
+
def forward(self, text: str) -> str:
|
28 |
+
"""Summarize the text using a simple algorithm."""
|
29 |
+
try:
|
30 |
+
# Simple summarization by taking the first few sentences
|
31 |
+
sentences = text.split('. ')
|
32 |
+
summary = '. '.join(sentences[:3]) + '.'
|
33 |
+
return summary
|
34 |
+
except Exception as exc:
|
35 |
+
return f"Error summarizing text: {exc}"
|
36 |
+
|
37 |
+
class KeywordExtractorTool(Tool):
|
38 |
+
"""Extract keywords from a text."""
|
39 |
+
|
40 |
+
name = "keyword_extractor"
|
41 |
+
description = "Extract keywords from a given text."
|
42 |
+
|
43 |
+
inputs = {
|
44 |
+
"text": {
|
45 |
+
"type": "string",
|
46 |
+
"description": "The text from which to extract keywords.",
|
47 |
+
}
|
48 |
+
}
|
49 |
+
output_type = "string"
|
50 |
+
|
51 |
+
def forward(self, text: str) -> str:
|
52 |
+
"""Extract keywords from the text."""
|
53 |
+
try:
|
54 |
+
# Simple keyword extraction based on word frequency
|
55 |
+
words = re.findall(r'\b\w+\b', text.lower())
|
56 |
+
common_words = ['the', 'and', 'is', 'in', 'it', 'of', 'to', 'a']
|
57 |
+
filtered_words = [word for word in words if word not in common_words]
|
58 |
+
word_counts = Counter(filtered_words)
|
59 |
+
keywords = ', '.join([word for word, count in word_counts.most_common(5)])
|
60 |
+
return keywords
|
61 |
+
except Exception as exc:
|
62 |
+
return f"Error extracting keywords: {exc}"
|
63 |
+
|
64 |
+
class TextTranslationTool(Tool):
|
65 |
+
"""Translate text using a simple dictionary-based approach."""
|
66 |
+
|
67 |
+
name = "text_translation"
|
68 |
+
description = "Translate a given text from one language to another using a simple dictionary."
|
69 |
+
|
70 |
+
inputs = {
|
71 |
+
"text": {
|
72 |
+
"type": "string",
|
73 |
+
"description": "The text to translate.",
|
74 |
+
},
|
75 |
+
"source_lang": {
|
76 |
+
"type": "string",
|
77 |
+
"description": "The source language (e.g., 'en' for English).",
|
78 |
+
},
|
79 |
+
"target_lang": {
|
80 |
+
"type": "string",
|
81 |
+
"description": "The target language (e.g., 'es' for Spanish).",
|
82 |
+
}
|
83 |
+
}
|
84 |
+
output_type = "string"
|
85 |
+
|
86 |
+
def __init__(self):
|
87 |
+
self.translation_dict = {
|
88 |
+
'hello': 'hola',
|
89 |
+
'world': 'mundo',
|
90 |
+
'goodbye': 'adiós',
|
91 |
+
# Add more translations as needed
|
92 |
+
}
|
93 |
+
|
94 |
+
def forward(self, text: str, source_lang: str, target_lang: str) -> str:
|
95 |
+
"""Translate the text using a simple dictionary-based approach."""
|
96 |
+
try:
|
97 |
+
words = text.split()
|
98 |
+
translated_words = [self.translation_dict.get(word, word) for word in words]
|
99 |
+
return ' '.join(translated_words)
|
100 |
+
except Exception as exc:
|
101 |
+
return f"Error translating text: {exc}"
|
102 |
+
|
103 |
# --- Basic Agent Definition ---
|
104 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
105 |
class BasicAgent:
|
106 |
def __init__(self):
|
107 |
+
self.agent = CodeAgent(
|
108 |
+
model=OpenAIServerModel(model_id="gpt-4o-mini"),
|
109 |
+
tools=[
|
110 |
+
DuckDuckGoSearchTool(),
|
111 |
+
WikipediaSearchTool(),
|
112 |
+
TextSummarizationTool(),
|
113 |
+
KeywordExtractorTool(),
|
114 |
+
TextTranslationTool()
|
115 |
+
],
|
116 |
+
add_base_tools=True,
|
117 |
+
)
|
118 |
print("BasicAgent initialized.")
|
119 |
+
|
120 |
def __call__(self, question: str) -> str:
|
121 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
122 |
+
fixed_answer = self.agent.run(question)
|
123 |
+
print(f"Agent returning answer: {fixed_answer}")
|
124 |
return fixed_answer
|
125 |
|
126 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
127 |
"""
|
128 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
129 |
and displays the results.
|
|
|
195 |
print("Agent did not produce any answers to submit.")
|
196 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
197 |
|
198 |
+
# 4. Prepare Submission
|
199 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
200 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
201 |
print(status_update)
|
|
|
243 |
results_df = pd.DataFrame(results_log)
|
244 |
return status_message, results_df
|
245 |
|
|
|
246 |
# --- Build Gradio Interface using Blocks ---
|
247 |
with gr.Blocks() as demo:
|
248 |
gr.Markdown("# Basic Agent Evaluation Runner")
|
|
|
296 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
297 |
|
298 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
299 |
+
demo.launch(debug=True, share=False)
|
requirements.txt
CHANGED
@@ -1,2 +1,9 @@
|
|
|
|
1 |
gradio
|
2 |
-
requests
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Core dependencies
|
2 |
gradio
|
3 |
+
requests
|
4 |
+
smolagents
|
5 |
+
python-dotenv
|
6 |
+
pandas
|
7 |
+
|
8 |
+
# Additional dependencies for new tools
|
9 |
+
tabulate
|