Spaces:
Sleeping
Sleeping
added reverse_string tool
Browse files
app.py
CHANGED
|
@@ -6,7 +6,17 @@ import pandas as pd
|
|
| 6 |
|
| 7 |
|
| 8 |
from smolagents import LiteLLMModel
|
| 9 |
-
from smolagents import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
|
| 12 |
# (Keep Constants as is)
|
|
@@ -14,6 +24,71 @@ from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, WikipediaSea
|
|
| 14 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 15 |
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
# --- Basic Agent Definition ---
|
| 18 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 19 |
class BasicAgent:
|
|
@@ -30,17 +105,24 @@ class BasicAgent:
|
|
| 30 |
class MyAgent:
|
| 31 |
def __init__(self):
|
| 32 |
model = LiteLLMModel(
|
| 33 |
-
model_id="ollama_chat/gemma3:
|
| 34 |
api_base="http://127.0.0.1:11434", # Default Ollama local server
|
| 35 |
num_ctx=8192,
|
| 36 |
)
|
| 37 |
# model = HfApiModel()
|
| 38 |
|
| 39 |
self.agent = CodeAgent(
|
| 40 |
-
tools=[
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
model=model,
|
| 42 |
-
max_steps=
|
| 43 |
add_base_tools=True,
|
|
|
|
| 44 |
)
|
| 45 |
print("BasicAgent initialized.")
|
| 46 |
|
|
@@ -53,15 +135,32 @@ class MyAgent:
|
|
| 53 |
""
|
| 54 |
# "Ignore all previous instructions. "
|
| 55 |
"I will ask you a question. Report your thoughts step by step. "
|
|
|
|
| 56 |
# "Don't generate code, don't execute code, don't write explanations. "
|
| 57 |
# "Stop on the first step"
|
| 58 |
-
"Finish your answer only with the final answer. In the final answer don't write explanations
|
| 59 |
"The answer should be a number OR as few words as possible OR a comma separated list of numbers and/or strings."
|
| 60 |
" If you are asked for a number, don't use comma to write your number neither use units such as $ or "
|
| 61 |
"percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither "
|
| 62 |
"abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. "
|
| 63 |
"If you are asked for a comma separated list, apply the above rules depending of whether the element "
|
| 64 |
"to be put in the list is a number or a string."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
)
|
| 66 |
|
| 67 |
prompt = system_instruction + "\n" + question
|
|
@@ -126,7 +225,8 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 126 |
results_log = []
|
| 127 |
answers_payload = []
|
| 128 |
print(f"Running agent on {len(questions_data)} questions...")
|
| 129 |
-
|
|
|
|
| 130 |
task_id = item.get("task_id")
|
| 131 |
question_text = item.get("question")
|
| 132 |
if not task_id or question_text is None:
|
|
@@ -211,8 +311,16 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 211 |
return status_message, results_df
|
| 212 |
|
| 213 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
# --- Build Gradio Interface using Blocks ---
|
| 215 |
-
with gr.Blocks() as demo:
|
| 216 |
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 217 |
gr.Markdown(
|
| 218 |
"""
|
|
@@ -237,15 +345,19 @@ with gr.Blocks() as demo:
|
|
| 237 |
label="Run Status / Submission Result", lines=5, interactive=False
|
| 238 |
)
|
| 239 |
# Removed max_rows=10 from DataFrame constructor
|
| 240 |
-
results_table = gr.DataFrame(
|
|
|
|
|
|
|
| 241 |
|
| 242 |
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
| 243 |
|
|
|
|
| 244 |
if __name__ == "__main__":
|
| 245 |
print("\n" + "-" * 30 + " App Starting " + "-" * 30)
|
| 246 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 247 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 248 |
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
|
|
|
| 249 |
|
| 250 |
if space_host_startup:
|
| 251 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
|
|
| 6 |
|
| 7 |
|
| 8 |
from smolagents import LiteLLMModel
|
| 9 |
+
from smolagents import (
|
| 10 |
+
CodeAgent,
|
| 11 |
+
DuckDuckGoSearchTool,
|
| 12 |
+
HfApiModel,
|
| 13 |
+
WikipediaSearchTool,
|
| 14 |
+
PythonInterpreterTool,
|
| 15 |
+
CodeAgent,
|
| 16 |
+
FinalAnswerTool,
|
| 17 |
+
load_tool,
|
| 18 |
+
tool,
|
| 19 |
+
)
|
| 20 |
|
| 21 |
|
| 22 |
# (Keep Constants as is)
|
|
|
|
| 24 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 25 |
|
| 26 |
|
| 27 |
+
@tool
|
| 28 |
+
def reverse_string(input_string: str) -> str:
|
| 29 |
+
"""A tool that reverses the characters in a string.
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
input_string: The string to be reversed
|
| 33 |
+
"""
|
| 34 |
+
return input_string[::-1]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@tool
|
| 38 |
+
def optimized_web_search(
|
| 39 |
+
search_query: str, important_words: list, batch_size: int = 500
|
| 40 |
+
) -> str:
|
| 41 |
+
"""A tool that performs a web search and filters the results to only include content chunks that contain important keywords.
|
| 42 |
+
|
| 43 |
+
Args:
|
| 44 |
+
search_query: The search query to use (e.g., 'Beatles albums Wikipedia')
|
| 45 |
+
important_words: List of important keywords to filter by (e.g., ['Abbey Road', 'Let It Be', '1970'])
|
| 46 |
+
batch_size: The size of content chunks to process (default: 500 characters)
|
| 47 |
+
"""
|
| 48 |
+
try:
|
| 49 |
+
# Perform the search using DuckDuckGoSearchTool (assuming it's available in the environment)
|
| 50 |
+
search_tool = DuckDuckGoSearchTool()
|
| 51 |
+
search_results = search_tool.forward(search_query)
|
| 52 |
+
|
| 53 |
+
# If no results found, return early
|
| 54 |
+
if not search_results or len(search_results) == 0:
|
| 55 |
+
return "No search results found."
|
| 56 |
+
|
| 57 |
+
# Process the search results content
|
| 58 |
+
# Assuming search_results is a list of dictionaries with a 'content' field
|
| 59 |
+
# or a string with all content combined
|
| 60 |
+
if isinstance(search_results, list):
|
| 61 |
+
all_content = " ".join(
|
| 62 |
+
[result.get("content", "") for result in search_results]
|
| 63 |
+
)
|
| 64 |
+
else:
|
| 65 |
+
all_content = search_results
|
| 66 |
+
|
| 67 |
+
# Split the content into batches
|
| 68 |
+
batches = []
|
| 69 |
+
for i in range(0, len(all_content), batch_size):
|
| 70 |
+
batches.append(all_content[i : i + batch_size])
|
| 71 |
+
|
| 72 |
+
# Filter batches to only include those containing important words
|
| 73 |
+
filtered_batches = []
|
| 74 |
+
for batch in batches:
|
| 75 |
+
# Check if any important word is in the batch
|
| 76 |
+
if any(word.lower() in batch.lower() for word in important_words):
|
| 77 |
+
filtered_batches.append(batch)
|
| 78 |
+
|
| 79 |
+
# Join the filtered batches
|
| 80 |
+
filtered_content = "\n\n".join(filtered_batches)
|
| 81 |
+
|
| 82 |
+
# If no content remains after filtering, provide a helpful message
|
| 83 |
+
if not filtered_content:
|
| 84 |
+
return f"No content containing the important words {important_words} was found in the search results."
|
| 85 |
+
|
| 86 |
+
return filtered_content
|
| 87 |
+
|
| 88 |
+
except Exception as e:
|
| 89 |
+
return f"Error during optimized web search: {str(e)}"
|
| 90 |
+
|
| 91 |
+
|
| 92 |
# --- Basic Agent Definition ---
|
| 93 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 94 |
class BasicAgent:
|
|
|
|
| 105 |
class MyAgent:
|
| 106 |
def __init__(self):
|
| 107 |
model = LiteLLMModel(
|
| 108 |
+
model_id="ollama_chat/gemma3:12b", # Or try other Ollama-supported models
|
| 109 |
api_base="http://127.0.0.1:11434", # Default Ollama local server
|
| 110 |
num_ctx=8192,
|
| 111 |
)
|
| 112 |
# model = HfApiModel()
|
| 113 |
|
| 114 |
self.agent = CodeAgent(
|
| 115 |
+
tools=[
|
| 116 |
+
DuckDuckGoSearchTool(),
|
| 117 |
+
PythonInterpreterTool(),
|
| 118 |
+
# optimized_web_search,
|
| 119 |
+
reverse_string,
|
| 120 |
+
FinalAnswerTool(),
|
| 121 |
+
],
|
| 122 |
model=model,
|
| 123 |
+
max_steps=3,
|
| 124 |
add_base_tools=True,
|
| 125 |
+
additional_authorized_imports=["pandas", "*"],
|
| 126 |
)
|
| 127 |
print("BasicAgent initialized.")
|
| 128 |
|
|
|
|
| 135 |
""
|
| 136 |
# "Ignore all previous instructions. "
|
| 137 |
"I will ask you a question. Report your thoughts step by step. "
|
| 138 |
+
|
| 139 |
# "Don't generate code, don't execute code, don't write explanations. "
|
| 140 |
# "Stop on the first step"
|
| 141 |
+
"Finish your answer only with the final answer. In the final answer don't write explanations. "
|
| 142 |
"The answer should be a number OR as few words as possible OR a comma separated list of numbers and/or strings."
|
| 143 |
" If you are asked for a number, don't use comma to write your number neither use units such as $ or "
|
| 144 |
"percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither "
|
| 145 |
"abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. "
|
| 146 |
"If you are asked for a comma separated list, apply the above rules depending of whether the element "
|
| 147 |
"to be put in the list is a number or a string."
|
| 148 |
+
"Pay attention that the questions are specifically designed to be tricky. "
|
| 149 |
+
"Think about each sentence in the question and verify the answer against every sentence. "
|
| 150 |
+
"Follow the instructions in the question precisely. "
|
| 151 |
+
# "You have access to optimized_web_search, a powerful tool for efficient research:"
|
| 152 |
+
# "1. Use this tool whenever you need web information without context overload"
|
| 153 |
+
# "2. Required parameters:"
|
| 154 |
+
# "- search_query: Specific search terms (e.g., "
|
| 155 |
+
# "Beatles albums Wikipedia"
|
| 156 |
+
# ")"
|
| 157 |
+
# "- important_words: List of keywords ["
|
| 158 |
+
# "Abbey Road"
|
| 159 |
+
# ", "
|
| 160 |
+
# "Let It Be"
|
| 161 |
+
# "] to filter relevant content"
|
| 162 |
+
# "3. The tool will return only text chunks containing your keywords, saving context space"
|
| 163 |
+
# "Use this tool strategically when researching topics that need web information."
|
| 164 |
)
|
| 165 |
|
| 166 |
prompt = system_instruction + "\n" + question
|
|
|
|
| 225 |
results_log = []
|
| 226 |
answers_payload = []
|
| 227 |
print(f"Running agent on {len(questions_data)} questions...")
|
| 228 |
+
# array
|
| 229 |
+
for item in questions_data[2:3]:
|
| 230 |
task_id = item.get("task_id")
|
| 231 |
question_text = item.get("question")
|
| 232 |
if not task_id or question_text is None:
|
|
|
|
| 311 |
return status_message, results_df
|
| 312 |
|
| 313 |
|
| 314 |
+
# Custom CSS to make table content copyable
|
| 315 |
+
custom_css = """
|
| 316 |
+
.table-wrap table td {
|
| 317 |
+
user-select: text !important;
|
| 318 |
+
cursor: text !important;
|
| 319 |
+
}
|
| 320 |
+
"""
|
| 321 |
+
|
| 322 |
# --- Build Gradio Interface using Blocks ---
|
| 323 |
+
with gr.Blocks(css=custom_css) as demo:
|
| 324 |
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 325 |
gr.Markdown(
|
| 326 |
"""
|
|
|
|
| 345 |
label="Run Status / Submission Result", lines=5, interactive=False
|
| 346 |
)
|
| 347 |
# Removed max_rows=10 from DataFrame constructor
|
| 348 |
+
results_table = gr.DataFrame(
|
| 349 |
+
label="Questions and Agent Answers", wrap=True, interactive=True
|
| 350 |
+
)
|
| 351 |
|
| 352 |
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
| 353 |
|
| 354 |
+
|
| 355 |
if __name__ == "__main__":
|
| 356 |
print("\n" + "-" * 30 + " App Starting " + "-" * 30)
|
| 357 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 358 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 359 |
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 360 |
+
space_id_startup = "gmykola/Final_Assignment_Template"
|
| 361 |
|
| 362 |
if space_host_startup:
|
| 363 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|