alberto
commited on
Commit
·
7993ea5
1
Parent(s):
81917a3
first commit
Browse files- app.py +28 -3
- qwen_wrapper.py +58 -0
- requirements.txt +12 -1
- system_prompt.txt +186 -0
- tools.py +114 -0
- utils.py +33 -0
app.py
CHANGED
|
@@ -3,21 +3,32 @@ 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
|
| 17 |
-
print(f"Agent received question (first 50 chars): {
|
| 18 |
fixed_answer = "This is a default answer."
|
| 19 |
print(f"Agent returning fixed answer: {fixed_answer}")
|
| 20 |
return fixed_answer
|
|
|
|
|
|
|
| 21 |
|
| 22 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 23 |
"""
|
|
@@ -38,9 +49,22 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 38 |
questions_url = f"{api_url}/questions"
|
| 39 |
submit_url = f"{api_url}/submit"
|
| 40 |
|
|
|
|
| 41 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 42 |
try:
|
| 43 |
agent = BasicAgent()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
except Exception as e:
|
| 45 |
print(f"Error instantiating agent: {e}")
|
| 46 |
return f"Error initializing agent: {e}", None
|
|
@@ -80,7 +104,8 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 80 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 81 |
continue
|
| 82 |
try:
|
| 83 |
-
|
|
|
|
| 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:
|
|
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
+
from smolagents import VisitWebpageTool, DuckDuckGoSearchTool, PythonInterpreterTool, FinalAnswerTool, TransformersModel, InferenceClientModel
|
| 7 |
+
from tools import VisitWikiPageTool, SpeechToTextTool
|
| 8 |
+
from utils import QuestionLoader
|
| 9 |
+
|
| 10 |
+
with open('system_prompt.txt', 'r') as file:
|
| 11 |
+
system_prompt = file.read()
|
| 12 |
|
| 13 |
# (Keep Constants as is)
|
| 14 |
# --- Constants ---
|
| 15 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 16 |
|
| 17 |
+
# Models
|
| 18 |
+
MODEL = InferenceClientModel("Qwen/Qwen3-VL-30B-A3B-Instruct")
|
| 19 |
+
|
| 20 |
# --- Basic Agent Definition ---
|
| 21 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 22 |
class BasicAgent:
|
| 23 |
def __init__(self):
|
| 24 |
print("BasicAgent initialized.")
|
| 25 |
+
def run(self, task: str, **kwargs) -> str:
|
| 26 |
+
print(f"Agent received question (first 50 chars): {task[:50]}...")
|
| 27 |
fixed_answer = "This is a default answer."
|
| 28 |
print(f"Agent returning fixed answer: {fixed_answer}")
|
| 29 |
return fixed_answer
|
| 30 |
+
|
| 31 |
+
|
| 32 |
|
| 33 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 34 |
"""
|
|
|
|
| 49 |
questions_url = f"{api_url}/questions"
|
| 50 |
submit_url = f"{api_url}/submit"
|
| 51 |
|
| 52 |
+
question_loader = QuestionLoader(token=os.getenv("HF_TOKEN"))
|
| 53 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 54 |
try:
|
| 55 |
agent = BasicAgent()
|
| 56 |
+
#agent = CodeAgent(
|
| 57 |
+
# model=MODEL,
|
| 58 |
+
# max_steps=10,
|
| 59 |
+
# tools=[
|
| 60 |
+
# DuckDuckGoSearchTool(),
|
| 61 |
+
# WikipediaSearchTool(),
|
| 62 |
+
# VisitWebpageTool(),
|
| 63 |
+
# VisitWikiPageTool(user_agent="hf-agent-course"),
|
| 64 |
+
# SpeechToTextTool(),
|
| 65 |
+
# PythonInterpreterTool(),
|
| 66 |
+
# FinalAnswerTool()])
|
| 67 |
+
#agent.prompt_templates["system_prompt"] = system_prompt
|
| 68 |
except Exception as e:
|
| 69 |
print(f"Error instantiating agent: {e}")
|
| 70 |
return f"Error initializing agent: {e}", None
|
|
|
|
| 104 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 105 |
continue
|
| 106 |
try:
|
| 107 |
+
question_kwargs = question_loader.preprocess_question(item)
|
| 108 |
+
submitted_answer = agent.run(**question_kwargs)
|
| 109 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 110 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 111 |
except Exception as e:
|
qwen_wrapper.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
from smolagents import TransformersModel, ChatMessage
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class QwenModelWithAttention(TransformersModel):
|
| 6 |
+
|
| 7 |
+
def _prepare_completion_args(
|
| 8 |
+
self,
|
| 9 |
+
messages: list[ChatMessage | dict],
|
| 10 |
+
stop_sequences: list[str] | None = None,
|
| 11 |
+
tools_to_call_from: list[Tool] | None = None,
|
| 12 |
+
**kwargs,
|
| 13 |
+
) -> dict[str, Any]:
|
| 14 |
+
completion_kwargs = self._prepare_completion_kwargs(
|
| 15 |
+
messages=messages,
|
| 16 |
+
stop_sequences=stop_sequences,
|
| 17 |
+
tools_to_call_from=tools_to_call_from,
|
| 18 |
+
tool_choice=None,
|
| 19 |
+
**kwargs,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
messages = completion_kwargs.pop("messages")
|
| 23 |
+
stop_sequences = completion_kwargs.pop("stop", None)
|
| 24 |
+
tools = completion_kwargs.pop("tools", None)
|
| 25 |
+
|
| 26 |
+
max_new_tokens = (
|
| 27 |
+
kwargs.get("max_new_tokens")
|
| 28 |
+
or kwargs.get("max_tokens")
|
| 29 |
+
or self.kwargs.get("max_new_tokens")
|
| 30 |
+
or self.kwargs.get("max_tokens")
|
| 31 |
+
or 1024
|
| 32 |
+
)
|
| 33 |
+
prompt_tensor = (self.processor if hasattr(self, "processor") else self.tokenizer).apply_chat_template(
|
| 34 |
+
messages,
|
| 35 |
+
tools=tools,
|
| 36 |
+
return_tensors="pt",
|
| 37 |
+
add_generation_prompt=True,
|
| 38 |
+
tokenize=True,
|
| 39 |
+
return_dict=True,
|
| 40 |
+
return_attention_mask=True
|
| 41 |
+
)
|
| 42 |
+
prompt_tensor = prompt_tensor.to(self.model.device) # type: ignore
|
| 43 |
+
if hasattr(prompt_tensor, "input_ids"):
|
| 44 |
+
attention_mask = prompt_tensor["attention_mask"]
|
| 45 |
+
prompt_tensor = prompt_tensor["input_ids"]
|
| 46 |
+
|
| 47 |
+
model_tokenizer = self.processor.tokenizer if hasattr(self, "processor") else self.tokenizer
|
| 48 |
+
stopping_criteria = (
|
| 49 |
+
self.make_stopping_criteria(stop_sequences, tokenizer=model_tokenizer) if stop_sequences else None
|
| 50 |
+
)
|
| 51 |
+
completion_kwargs["max_new_tokens"] = max_new_tokens
|
| 52 |
+
return dict(
|
| 53 |
+
inputs=prompt_tensor,
|
| 54 |
+
attention_mask=attention_mask,
|
| 55 |
+
use_cache=True,
|
| 56 |
+
stopping_criteria=stopping_criteria,
|
| 57 |
+
**completion_kwargs,
|
| 58 |
+
)
|
requirements.txt
CHANGED
|
@@ -1,2 +1,13 @@
|
|
| 1 |
gradio
|
| 2 |
-
requests
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
gradio
|
| 2 |
+
requests
|
| 3 |
+
smolagents == 1.23.*
|
| 4 |
+
smolagents[transformers]
|
| 5 |
+
smolagents[audio]
|
| 6 |
+
wikipedia-api
|
| 7 |
+
ddgs
|
| 8 |
+
markdownify
|
| 9 |
+
datasets==4.*
|
| 10 |
+
dotenv
|
| 11 |
+
torch==2.9
|
| 12 |
+
torchaudio
|
| 13 |
+
torchcodec
|
system_prompt.txt
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
You are an expert assistant who can solve any task using code blobs. You will be given a task to solve as best you can.
|
| 2 |
+
To do so, you have been given access to a list of tools: these tools are basically Python functions which you can call with code.
|
| 3 |
+
To solve the task, you must plan forward to proceed in a series of steps, in a cycle of Thought, Code, and Observation sequences.
|
| 4 |
+
|
| 5 |
+
At each step, in the 'Thought:' sequence, you should first explain your reasoning towards solving the task and the tools that you want to use.
|
| 6 |
+
Then in the Code sequence you should write the code in simple Python. The code sequence must be opened with '{{code_block_opening_tag}}', and closed with '{{code_block_closing_tag}}'.
|
| 7 |
+
During each intermediate step, you can use 'print()' to save whatever important information you will then need.
|
| 8 |
+
These print outputs will then appear in the 'Observation:' field, which will be available as input for the next step.
|
| 9 |
+
In the end you have to return a final answer using the `final_answer` tool.
|
| 10 |
+
|
| 11 |
+
Here are a few examples using notional tools:
|
| 12 |
+
---
|
| 13 |
+
Task: "Generate an image of the oldest person in this document."
|
| 14 |
+
|
| 15 |
+
Thought: I will proceed step by step and use the following tools: `document_qa` to find the oldest person in the document, then `image_generator` to generate an image according to the answer.
|
| 16 |
+
{{code_block_opening_tag}}
|
| 17 |
+
answer = document_qa(document=document, question="Who is the oldest person mentioned?")
|
| 18 |
+
print(answer)
|
| 19 |
+
{{code_block_closing_tag}}
|
| 20 |
+
Observation: "The oldest person in the document is John Doe, a 55 year old lumberjack living in Newfoundland."
|
| 21 |
+
|
| 22 |
+
Thought: I will now generate an image showcasing the oldest person.
|
| 23 |
+
{{code_block_opening_tag}}
|
| 24 |
+
image = image_generator("A portrait of John Doe, a 55-year-old man living in Canada.")
|
| 25 |
+
final_answer(image)
|
| 26 |
+
{{code_block_closing_tag}}
|
| 27 |
+
|
| 28 |
+
---
|
| 29 |
+
Task: "What is the result of the following operation: 5 + 3 + 1294.678?"
|
| 30 |
+
|
| 31 |
+
Thought: I will use Python code to compute the result of the operation and then return the final answer using the `final_answer` tool.
|
| 32 |
+
{{code_block_opening_tag}}
|
| 33 |
+
result = 5 + 3 + 1294.678
|
| 34 |
+
final_answer(result)
|
| 35 |
+
{{code_block_closing_tag}}
|
| 36 |
+
|
| 37 |
+
---
|
| 38 |
+
Task:
|
| 39 |
+
"Answer the question in the variable `question` about the image stored in the variable `image`. The question is in French.
|
| 40 |
+
You have been provided with these additional arguments, that you can access using the keys as variables in your Python code:
|
| 41 |
+
{'question': 'Quel est l'animal sur l'image?', 'image': 'path/to/image.jpg'}"
|
| 42 |
+
|
| 43 |
+
Thought: I will use the following tools: `translator` to translate the question into English and then `image_qa` to answer the question on the input image.
|
| 44 |
+
{{code_block_opening_tag}}
|
| 45 |
+
translated_question = translator(question=question, src_lang="French", tgt_lang="English")
|
| 46 |
+
print(f"The translated question is {translated_question}.")
|
| 47 |
+
answer = image_qa(image=image, question=translated_question)
|
| 48 |
+
final_answer(f"The answer is {answer}")
|
| 49 |
+
{{code_block_closing_tag}}
|
| 50 |
+
|
| 51 |
+
---
|
| 52 |
+
Task:
|
| 53 |
+
In a 1979 interview, Stanislaus Ulam discusses with Martin Sherwin about other great physicists of his time, including Oppenheimer.
|
| 54 |
+
What does he say was the consequence of Einstein learning too much math on his creativity, in one word?
|
| 55 |
+
|
| 56 |
+
Thought: I need to find and read the 1979 interview of Stanislaus Ulam with Martin Sherwin.
|
| 57 |
+
{{code_block_opening_tag}}
|
| 58 |
+
pages = web_search(query="1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein")
|
| 59 |
+
print(pages)
|
| 60 |
+
{{code_block_closing_tag}}
|
| 61 |
+
Observation:
|
| 62 |
+
No result found for query "1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein".
|
| 63 |
+
|
| 64 |
+
Thought: The query was maybe too restrictive and did not find any results. Let's try again with a broader query.
|
| 65 |
+
{{code_block_opening_tag}}
|
| 66 |
+
pages = web_search(query="1979 interview Stanislaus Ulam")
|
| 67 |
+
print(pages)
|
| 68 |
+
{{code_block_closing_tag}}
|
| 69 |
+
Observation:
|
| 70 |
+
Found 6 pages:
|
| 71 |
+
[Stanislaus Ulam 1979 interview](https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/)
|
| 72 |
+
|
| 73 |
+
[Ulam discusses Manhattan Project](https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/)
|
| 74 |
+
|
| 75 |
+
(truncated)
|
| 76 |
+
|
| 77 |
+
Thought: I will read the first 2 pages to know more.
|
| 78 |
+
{{code_block_opening_tag}}
|
| 79 |
+
for url in ["https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/", "https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/"]:
|
| 80 |
+
whole_page = visit_webpage(url)
|
| 81 |
+
print(whole_page)
|
| 82 |
+
print("\n" + "="*80 + "\n") # Print separator between pages
|
| 83 |
+
{{code_block_closing_tag}}
|
| 84 |
+
Observation:
|
| 85 |
+
Manhattan Project Locations:
|
| 86 |
+
Los Alamos, NM
|
| 87 |
+
Stanislaus Ulam was a Polish-American mathematician. He worked on the Manhattan Project at Los Alamos and later helped design the hydrogen bomb. In this interview, he discusses his work at
|
| 88 |
+
(truncated)
|
| 89 |
+
|
| 90 |
+
Thought: I now have the final answer: from the webpages visited, Stanislaus Ulam says of Einstein: "He learned too much mathematics and sort of diminished, it seems to me personally, it seems to me his purely physics creativity." Let's answer in one word.
|
| 91 |
+
{{code_block_opening_tag}}
|
| 92 |
+
final_answer("diminished")
|
| 93 |
+
{{code_block_closing_tag}}
|
| 94 |
+
|
| 95 |
+
---
|
| 96 |
+
Task: "Which city has the highest population: Guangzhou or Shanghai?"
|
| 97 |
+
|
| 98 |
+
Thought: I need to get the populations for both cities and compare them: I will use the tool `web_search` to get the population of both cities.
|
| 99 |
+
{{code_block_opening_tag}}
|
| 100 |
+
for city in ["Guangzhou", "Shanghai"]:
|
| 101 |
+
print(f"Population {city}:", web_search(f"{city} population"))
|
| 102 |
+
{{code_block_closing_tag}}
|
| 103 |
+
Observation:
|
| 104 |
+
Population Guangzhou: ['Guangzhou has a population of 15 million inhabitants as of 2021.']
|
| 105 |
+
Population Shanghai: '26 million (2019)'
|
| 106 |
+
|
| 107 |
+
Thought: Now I know that Shanghai has the highest population.
|
| 108 |
+
{{code_block_opening_tag}}
|
| 109 |
+
final_answer("Shanghai")
|
| 110 |
+
{{code_block_closing_tag}}
|
| 111 |
+
|
| 112 |
+
---
|
| 113 |
+
Task: "What is the current age of the pope, raised to the power 0.36?"
|
| 114 |
+
|
| 115 |
+
Thought: I will use the tool `wikipedia_search` to get the age of the pope, and confirm that with a web search.
|
| 116 |
+
{{code_block_opening_tag}}
|
| 117 |
+
pope_age_wiki = wikipedia_search(query="current pope age")
|
| 118 |
+
print("Pope age as per wikipedia:", pope_age_wiki)
|
| 119 |
+
pope_age_search = web_search(query="current pope age")
|
| 120 |
+
print("Pope age as per google search:", pope_age_search)
|
| 121 |
+
{{code_block_closing_tag}}
|
| 122 |
+
Observation:
|
| 123 |
+
Pope age: "The pope Francis is currently 88 years old."
|
| 124 |
+
|
| 125 |
+
Thought: I know that the pope is 88 years old. Let's compute the result using Python code.
|
| 126 |
+
{{code_block_opening_tag}}
|
| 127 |
+
pope_current_age = 88 ** 0.36
|
| 128 |
+
final_answer(pope_current_age)
|
| 129 |
+
{{code_block_closing_tag}}
|
| 130 |
+
|
| 131 |
+
Above examples were using notional tools that might not exist for you. On top of performing computations in the Python code snippets that you create, you only have access to these tools, behaving like regular python functions:
|
| 132 |
+
{{code_block_opening_tag}}
|
| 133 |
+
{%- for tool in tools.values() %}
|
| 134 |
+
{{ tool.to_code_prompt() }}
|
| 135 |
+
{% endfor %}
|
| 136 |
+
{{code_block_closing_tag}}
|
| 137 |
+
|
| 138 |
+
{%- if managed_agents and managed_agents.values() | list %}
|
| 139 |
+
You can also give tasks to team members.
|
| 140 |
+
Calling a team member works similarly to calling a tool: provide the task description as the 'task' argument. Since this team member is a real human, be as detailed and verbose as necessary in your task description.
|
| 141 |
+
You can also include any relevant variables or context using the 'additional_args' argument.
|
| 142 |
+
Here is a list of the team members that you can call:
|
| 143 |
+
{{code_block_opening_tag}}
|
| 144 |
+
{%- for agent in managed_agents.values() %}
|
| 145 |
+
def {{ agent.name }}(task: str, additional_args: dict[str, Any]) -> str:
|
| 146 |
+
"""{{ agent.description }}
|
| 147 |
+
|
| 148 |
+
Args:
|
| 149 |
+
task: Long detailed description of the task.
|
| 150 |
+
additional_args: Dictionary of extra inputs to pass to the managed agent, e.g. images, dataframes, or any other contextual data it may need.
|
| 151 |
+
"""
|
| 152 |
+
{% endfor %}
|
| 153 |
+
{{code_block_closing_tag}}
|
| 154 |
+
{%- endif %}
|
| 155 |
+
|
| 156 |
+
Here are the rules you should always follow to solve your task:
|
| 157 |
+
1. Always provide a 'Thought:' sequence, and a '{{code_block_opening_tag}}' sequence ending with '{{code_block_closing_tag}}', else you will fail.
|
| 158 |
+
2. Use only variables that you have defined!
|
| 159 |
+
3. Always use the right arguments for the tools. DO NOT pass the arguments as a dict as in 'answer = wikipedia_search({'query': "What is the place where James Bond lives?"})', but use the arguments directly as in 'answer = wikipedia_search(query="What is the place where James Bond lives?")'.
|
| 160 |
+
4. For tools WITHOUT JSON output schema: Take care to not chain too many sequential tool calls in the same code block, as their output format is unpredictable. For instance, a call to wikipedia_search without a JSON output schema has an unpredictable return format, so do not have another tool call that depends on its output in the same block: rather output results with print() to use them in the next block.
|
| 161 |
+
5. For tools WITH JSON output schema: You can confidently chain multiple tool calls and directly access structured output fields in the same code block! When a tool has a JSON output schema, you know exactly what fields and data types to expect, allowing you to write robust code that directly accesses the structured response (e.g., result['field_name']) without needing intermediate print() statements.
|
| 162 |
+
6. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.
|
| 163 |
+
7. Don't name any new variable with the same name as a tool: for instance don't name a variable 'final_answer'.
|
| 164 |
+
8. Never create any notional variables in our code, as having these in your logs will derail you from the true variables.
|
| 165 |
+
9. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}
|
| 166 |
+
10. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
|
| 167 |
+
11. Don't give up! You're in charge of solving the task, not providing directions to solve it.
|
| 168 |
+
12. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
|
| 169 |
+
13. 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.
|
| 170 |
+
14. 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
|
| 171 |
+
specified otherwise.
|
| 172 |
+
15. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in
|
| 173 |
+
the list is a number or a string.
|
| 174 |
+
|
| 175 |
+
Here are suggestions, these are not rules, so you may decide to not follow them, however, they can make solving tasks easier:
|
| 176 |
+
1. Some questions are related to a file, use the 'get_question_file' tool to retrieve the question's file content.
|
| 177 |
+
2. The 'wikipedia_search' tool often returns incomplete results and is not able to parse tables. In order to get the full content of a wikipedia pages
|
| 178 |
+
you should rely on the 'visit_wikipage' tool.
|
| 179 |
+
3. To visit wikipedia pages you should use the 'visit_wikipage' tool and NOT the generic 'visit_webpage' tool since the latter won't work.
|
| 180 |
+
4. Instead of using regex or code instruction to extract information from text it you are often better of relying on your own text understading capabilities.
|
| 181 |
+
|
| 182 |
+
{%- if custom_instructions %}
|
| 183 |
+
{{custom_instructions}}
|
| 184 |
+
{%- endif %}
|
| 185 |
+
|
| 186 |
+
Now Begin!
|
tools.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict
|
| 2 |
+
from transformers import pipeline
|
| 3 |
+
from smolagents.tools import Tool
|
| 4 |
+
import torchcodec
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class VisitWikiPageTool(Tool):
|
| 8 |
+
name = "visit_wikipage"
|
| 9 |
+
description = (
|
| 10 |
+
"Visits a Wikipedia page at the given url and reads its content as a markdown string. Use this to browse Wikipedia wepages and get their full content."
|
| 11 |
+
)
|
| 12 |
+
inputs = {
|
| 13 |
+
"url": {
|
| 14 |
+
"type": "string",
|
| 15 |
+
"description": "The url of the webpage to visit.",
|
| 16 |
+
},
|
| 17 |
+
"max_length": {
|
| 18 |
+
"type": "integer",
|
| 19 |
+
"description": "Maximum number of characters to include in the response. Default 40000.",
|
| 20 |
+
"nullable": True
|
| 21 |
+
}
|
| 22 |
+
}
|
| 23 |
+
output_type = "string"
|
| 24 |
+
|
| 25 |
+
def __init__(self, user_agent: str):
|
| 26 |
+
super().__init__()
|
| 27 |
+
self.headers = {"User-Agent": user_agent}
|
| 28 |
+
|
| 29 |
+
def _truncate_content(self, content: str, max_length: int) -> str:
|
| 30 |
+
if len(content) <= max_length:
|
| 31 |
+
return content
|
| 32 |
+
return (
|
| 33 |
+
content[:max_length] + f"\n..._This content has been truncated to stay below {max_length} characters_...\n"
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
def forward(self, url: str, max_length: int = 40000) -> str:
|
| 37 |
+
try:
|
| 38 |
+
import re
|
| 39 |
+
import requests
|
| 40 |
+
from markdownify import markdownify
|
| 41 |
+
from requests.exceptions import RequestException
|
| 42 |
+
except ImportError as e:
|
| 43 |
+
raise ImportError(
|
| 44 |
+
"You must install packages `markdownify` and `requests` to run this tool: for instance run `pip install markdownify requests`."
|
| 45 |
+
) from e
|
| 46 |
+
try:
|
| 47 |
+
# Send a GET request to the URL with a 20-second timeout
|
| 48 |
+
response = requests.get(url, timeout=20, headers=self.headers)
|
| 49 |
+
response.raise_for_status() # Raise an exception for bad status codes
|
| 50 |
+
|
| 51 |
+
# Convert the HTML content to Markdown
|
| 52 |
+
markdown_content = markdownify(response.text).strip()
|
| 53 |
+
max_length = max_length if max_length is not None else 40000
|
| 54 |
+
# Remove multiple line breaks
|
| 55 |
+
markdown_content = re.sub(r"\n{3,}", "\n\n", markdown_content)
|
| 56 |
+
return self._truncate_content(markdown_content, max_length)
|
| 57 |
+
|
| 58 |
+
except requests.exceptions.Timeout:
|
| 59 |
+
return "The request timed out. Please try again later or check the URL."
|
| 60 |
+
except RequestException as e:
|
| 61 |
+
return f"Error fetching the webpage: {str(e)}"
|
| 62 |
+
except Exception as e:
|
| 63 |
+
return f"An unexpected error occurred: {str(e)}"
|
| 64 |
+
|
| 65 |
+
class SpeechToTextTool(Tool):
|
| 66 |
+
name = "transcriber"
|
| 67 |
+
description = "This is a tool that transcribes an audio into text. It returns the transcribed text."
|
| 68 |
+
inputs = {
|
| 69 |
+
"audio": {
|
| 70 |
+
"type": "audio",
|
| 71 |
+
"description": "The audio to transcribe it should be bytes.",
|
| 72 |
+
},
|
| 73 |
+
"sample_rate": {
|
| 74 |
+
"type": "integer",
|
| 75 |
+
"description": "The sampling rate to use to decode the audio, defaults to 16000",
|
| 76 |
+
"nullable": True
|
| 77 |
+
}
|
| 78 |
+
}
|
| 79 |
+
output_type = "string"
|
| 80 |
+
def __init__(self, model: str = "openai/whisper-small"):
|
| 81 |
+
super().__init__()
|
| 82 |
+
self.pipe = pipeline("automatic-speech-recognition", model=model)
|
| 83 |
+
|
| 84 |
+
def forward(self, audio: bytes, sample_rate: int=16000) -> str:
|
| 85 |
+
sample_rate = sample_rate if sample_rate is not None else 16000
|
| 86 |
+
decoder = torchcodec.decoders.AudioDecoder(audio, sample_rate=sample_rate)
|
| 87 |
+
out = self.pipe(decoder)
|
| 88 |
+
return out["text"]
|
| 89 |
+
|
| 90 |
+
class SpeechToTextTool(Tool):
|
| 91 |
+
name = "transcriber"
|
| 92 |
+
description = "This is a tool that transcribes an audio into text. It returns the transcribed text."
|
| 93 |
+
inputs = {
|
| 94 |
+
"audio_file": {
|
| 95 |
+
"type": "string",
|
| 96 |
+
"description": "The path to the audio file to transcribe.",
|
| 97 |
+
},
|
| 98 |
+
"sample_rate": {
|
| 99 |
+
"type": "integer",
|
| 100 |
+
"description": "The sampling rate to use to decode the audio, defaults to 16000",
|
| 101 |
+
"nullable": True
|
| 102 |
+
}
|
| 103 |
+
}
|
| 104 |
+
output_type = "string"
|
| 105 |
+
def __init__(self, model: str = "openai/whisper-small"):
|
| 106 |
+
super().__init__()
|
| 107 |
+
self.pipe = pipeline("automatic-speech-recognition", model=model)
|
| 108 |
+
|
| 109 |
+
def forward(self, audio_file: str, sample_rate: int=16000) -> str:
|
| 110 |
+
sample_rate = sample_rate if sample_rate is not None else 16000
|
| 111 |
+
with open(audio_file, "rb") as f:
|
| 112 |
+
decoder = torchcodec.decoders.AudioDecoder(f, sample_rate=sample_rate)
|
| 113 |
+
out = self.pipe(decoder)
|
| 114 |
+
return out["text"]
|
utils.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
import pandas as pd
|
| 3 |
+
from io import BytesIO
|
| 4 |
+
|
| 5 |
+
class QuestionLoader:
|
| 6 |
+
|
| 7 |
+
def __init__(self, token: str):
|
| 8 |
+
self._headers = {"Authorization": f"Bearer {token}"}
|
| 9 |
+
self.url = f"https://huggingface.co/datasets/gaia-benchmark/GAIA/resolve/main/2023/validation/"
|
| 10 |
+
|
| 11 |
+
def preprocess_question(self, question: dict):
|
| 12 |
+
text = question.get("question")
|
| 13 |
+
task_id = question.get("task_id")
|
| 14 |
+
file_id = question.get("file_name")
|
| 15 |
+
|
| 16 |
+
question_kwargs = {"task": text}
|
| 17 |
+
if file_id:
|
| 18 |
+
response = requests.get(self.url + file_id, headers=self._headers)
|
| 19 |
+
extension = file_id.split(".")[-1]
|
| 20 |
+
if extension in {"mp3"}:
|
| 21 |
+
with open("tmp.mp3", 'wb') as f:
|
| 22 |
+
f.write(response.content)
|
| 23 |
+
question_kwargs["additional_args"] = {"attached_audio_file_path": "tmp.mp3"}
|
| 24 |
+
elif extension in {"png", "jpeg"}:
|
| 25 |
+
question_kwargs["images"] = [Image.open(BytesIO(response.content))]
|
| 26 |
+
elif extension in {"xlsx"}:
|
| 27 |
+
table = pd.read_excel(BytesIO(response.content))
|
| 28 |
+
question_kwargs["additional_args"] = {"attached_table": table}
|
| 29 |
+
elif extension in {"py"}:
|
| 30 |
+
question_kwargs["additional_args"] = {"attached_python_code": response.content}
|
| 31 |
+
else:
|
| 32 |
+
raise ValueError(f"Unrecognized file extenstion {extension}")
|
| 33 |
+
return question_kwargs
|