Spaces:
Runtime error
Runtime error
franckberneron commited on
Commit ·
a9987d3
1
Parent(s): ff1701c
Ajoute les exercices de fin du module Smolagents
Browse files- smolagent_multiagent.py +30 -0
- smolagent_test.py +16 -0
- smolagents-vision_web_browser.py +225 -0
- smolagents.ipynb +1 -18
smolagent_multiagent.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from smolagents import CodeAgent, GoogleSearchTool, VisitWebPageTool, HfApiModel, ToolCallingAgent
|
| 2 |
+
# Create web agent and manager agent structure
|
| 3 |
+
|
| 4 |
+
model = HfApiModel(
|
| 5 |
+
"Qwen/Qwen2.5-Coder-32B-Instruct", provider="together", max_tokens=8096
|
| 6 |
+
)
|
| 7 |
+
|
| 8 |
+
web_agent = ToolCallingAgent(
|
| 9 |
+
tools=[GoogleSearchTool(), VisitWebPageTool()], # Add required tools
|
| 10 |
+
model=model, # Add model
|
| 11 |
+
max_steps=5, # Adjust steps
|
| 12 |
+
name="web_agent", # Add name
|
| 13 |
+
description="Runs web searches and visits web pages for you." # Add description
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
manager_agent = CodeAgent(
|
| 17 |
+
model=model,
|
| 18 |
+
manager_agent=[web_agent],
|
| 19 |
+
additional_authorized_imports=[
|
| 20 |
+
"geopandas",
|
| 21 |
+
"plotly",
|
| 22 |
+
"shapely",
|
| 23 |
+
"json",
|
| 24 |
+
"pandas",
|
| 25 |
+
"numpy",
|
| 26 |
+
],
|
| 27 |
+
planning_intervals = 5,
|
| 28 |
+
verbosity_level = 2,
|
| 29 |
+
max_steps= 10
|
| 30 |
+
)
|
smolagent_test.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Create a CodeAgent with DuckDuckGo search capability
|
| 2 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel
|
| 3 |
+
|
| 4 |
+
web_search = DuckDuckGoSearchTool()
|
| 5 |
+
|
| 6 |
+
model = HfApiModel(
|
| 7 |
+
max_tokens=2096,
|
| 8 |
+
temperature=0.5,
|
| 9 |
+
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
|
| 10 |
+
custom_role_conversions=None,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
agent = CodeAgent(
|
| 14 |
+
tools=[web_search], # Add search tool here
|
| 15 |
+
model=model # Add model here
|
| 16 |
+
)
|
smolagents-vision_web_browser.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
from io import BytesIO
|
| 3 |
+
from time import sleep
|
| 4 |
+
|
| 5 |
+
import helium
|
| 6 |
+
from dotenv import load_dotenv
|
| 7 |
+
from PIL import Image
|
| 8 |
+
from selenium import webdriver
|
| 9 |
+
from selenium.webdriver.common.by import By
|
| 10 |
+
from selenium.webdriver.common.keys import Keys
|
| 11 |
+
|
| 12 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, tool, LiteLLMModel
|
| 13 |
+
from smolagents.agents import ActionStep
|
| 14 |
+
from smolagents.cli import load_model
|
| 15 |
+
import configparser
|
| 16 |
+
|
| 17 |
+
config = configparser.ConfigParser()
|
| 18 |
+
config.read('config.cfg')
|
| 19 |
+
api_key = config.get('huggingface','OPENAI_API_KEY')
|
| 20 |
+
|
| 21 |
+
alfred_guest_list_request = """
|
| 22 |
+
I am Alfred, the butler of Wayne Manor, responsible for verifying the identity of guests at party. A superhero has arrived at the entrance claiming to be Wonder Woman, but I need to confirm if she is who she says she is.
|
| 23 |
+
|
| 24 |
+
Please search for images of Wonder Woman and generate a detailed visual description based on those images. Additionally, navigate to Wikipedia to gather key details about her appearance. With this information, I can determine whether to grant her access to the event.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def parse_arguments():
|
| 29 |
+
parser = argparse.ArgumentParser(description="Run a web browser automation script with a specified model.")
|
| 30 |
+
parser.add_argument(
|
| 31 |
+
"prompt",
|
| 32 |
+
type=str,
|
| 33 |
+
nargs="?", # Makes it optional
|
| 34 |
+
default=alfred_guest_list_request,
|
| 35 |
+
help="The prompt to run with the agent",
|
| 36 |
+
)
|
| 37 |
+
parser.add_argument(
|
| 38 |
+
"--model-type",
|
| 39 |
+
type=str,
|
| 40 |
+
default="LiteLLMModel",
|
| 41 |
+
help="The model type to use (e.g., OpenAIServerModel, LiteLLMModel, TransformersModel, HfApiModel)",
|
| 42 |
+
)
|
| 43 |
+
parser.add_argument(
|
| 44 |
+
"--model-id",
|
| 45 |
+
type=str,
|
| 46 |
+
default="gpt-4o",
|
| 47 |
+
help="The model ID to use for the specified model type",
|
| 48 |
+
)
|
| 49 |
+
parser.add_argument(
|
| 50 |
+
"--api-key",
|
| 51 |
+
type=str,
|
| 52 |
+
default=api_key,
|
| 53 |
+
help="The API Key to use to load the OpenAI API key",
|
| 54 |
+
)
|
| 55 |
+
return parser.parse_args()
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def save_screenshot(memory_step: ActionStep, agent: CodeAgent) -> None:
|
| 59 |
+
sleep(1.0) # Let JavaScript animations happen before taking the screenshot
|
| 60 |
+
driver = helium.get_driver()
|
| 61 |
+
current_step = memory_step.step_number
|
| 62 |
+
if driver is not None:
|
| 63 |
+
for previous_memory_step in agent.memory.steps: # Remove previous screenshots from logs for lean processing
|
| 64 |
+
if isinstance(previous_memory_step, ActionStep) and previous_memory_step.step_number <= current_step - 2:
|
| 65 |
+
previous_memory_step.observations_images = None
|
| 66 |
+
png_bytes = driver.get_screenshot_as_png()
|
| 67 |
+
image = Image.open(BytesIO(png_bytes))
|
| 68 |
+
print(f"Captured a browser screenshot: {image.size} pixels")
|
| 69 |
+
memory_step.observations_images = [image.copy()] # Create a copy to ensure it persists, important!
|
| 70 |
+
|
| 71 |
+
# Update observations with current URL
|
| 72 |
+
url_info = f"Current url: {driver.current_url}"
|
| 73 |
+
memory_step.observations = (
|
| 74 |
+
url_info if memory_step.observations is None else memory_step.observations + "\n" + url_info
|
| 75 |
+
)
|
| 76 |
+
return
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
@tool
|
| 80 |
+
def search_item_ctrl_f(text: str, nth_result: int = 1) -> str:
|
| 81 |
+
"""
|
| 82 |
+
Searches for text on the current page via Ctrl + F and jumps to the nth occurrence.
|
| 83 |
+
Args:
|
| 84 |
+
text: The text to search for
|
| 85 |
+
nth_result: Which occurrence to jump to (default: 1)
|
| 86 |
+
"""
|
| 87 |
+
elements = driver.find_elements(By.XPATH, f"//*[contains(text(), '{text}')]")
|
| 88 |
+
if nth_result > len(elements):
|
| 89 |
+
raise Exception(f"Match n°{nth_result} not found (only {len(elements)} matches found)")
|
| 90 |
+
result = f"Found {len(elements)} matches for '{text}'."
|
| 91 |
+
elem = elements[nth_result - 1]
|
| 92 |
+
driver.execute_script("arguments[0].scrollIntoView(true);", elem)
|
| 93 |
+
result += f"Focused on element {nth_result} of {len(elements)}"
|
| 94 |
+
return result
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
@tool
|
| 98 |
+
def go_back() -> None:
|
| 99 |
+
"""Goes back to previous page."""
|
| 100 |
+
driver.back()
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@tool
|
| 104 |
+
def close_popups() -> str:
|
| 105 |
+
"""
|
| 106 |
+
Closes any visible modal or pop-up on the page. Use this to dismiss pop-up windows! This does not work on cookie consent banners.
|
| 107 |
+
"""
|
| 108 |
+
webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform()
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def initialize_driver():
|
| 112 |
+
"""Initialize the Selenium WebDriver."""
|
| 113 |
+
chrome_options = webdriver.ChromeOptions()
|
| 114 |
+
chrome_options.add_argument("--force-device-scale-factor=1")
|
| 115 |
+
chrome_options.add_argument("--window-size=1000,1350")
|
| 116 |
+
chrome_options.add_argument("--disable-pdf-viewer")
|
| 117 |
+
chrome_options.add_argument("--window-position=0,0")
|
| 118 |
+
return helium.start_chrome(headless=False, options=chrome_options)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def initialize_agent(model, api_key):
|
| 122 |
+
"""Initialize the CodeAgent with the specified model."""
|
| 123 |
+
return CodeAgent(
|
| 124 |
+
tools=[DuckDuckGoSearchTool(), go_back, close_popups, search_item_ctrl_f],
|
| 125 |
+
model=model,
|
| 126 |
+
additional_authorized_imports=["helium"],
|
| 127 |
+
step_callbacks=[save_screenshot],
|
| 128 |
+
max_steps=20,
|
| 129 |
+
verbosity_level=2,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
helium_instructions = """
|
| 134 |
+
Use your web_search tool when you want to get Google search results.
|
| 135 |
+
Then you can use helium to access websites. Don't use helium for Google search, only for navigating websites!
|
| 136 |
+
Don't bother about the helium driver, it's already managed.
|
| 137 |
+
We've already ran "from helium import *"
|
| 138 |
+
Then you can go to pages!
|
| 139 |
+
Code:
|
| 140 |
+
```py
|
| 141 |
+
go_to('github.com/trending')
|
| 142 |
+
```<end_code>
|
| 143 |
+
|
| 144 |
+
You can directly click clickable elements by inputting the text that appears on them.
|
| 145 |
+
Code:
|
| 146 |
+
```py
|
| 147 |
+
click("Top products")
|
| 148 |
+
```<end_code>
|
| 149 |
+
|
| 150 |
+
If it's a link:
|
| 151 |
+
Code:
|
| 152 |
+
```py
|
| 153 |
+
click(Link("Top products"))
|
| 154 |
+
```<end_code>
|
| 155 |
+
|
| 156 |
+
If you try to interact with an element and it's not found, you'll get a LookupError.
|
| 157 |
+
In general stop your action after each button click to see what happens on your screenshot.
|
| 158 |
+
Never try to login in a page.
|
| 159 |
+
|
| 160 |
+
To scroll up or down, use scroll_down or scroll_up with as an argument the number of pixels to scroll from.
|
| 161 |
+
Code:
|
| 162 |
+
```py
|
| 163 |
+
scroll_down(num_pixels=1200) # This will scroll one viewport down
|
| 164 |
+
```<end_code>
|
| 165 |
+
|
| 166 |
+
When you have pop-ups with a cross icon to close, don't try to click the close icon by finding its element or targeting an 'X' element (this most often fails).
|
| 167 |
+
Just use your built-in tool `close_popups` to close them:
|
| 168 |
+
Code:
|
| 169 |
+
```py
|
| 170 |
+
close_popups()
|
| 171 |
+
```<end_code>
|
| 172 |
+
|
| 173 |
+
You can use .exists() to check for the existence of an element. For example:
|
| 174 |
+
Code:
|
| 175 |
+
```py
|
| 176 |
+
if Text('Accept cookies?').exists():
|
| 177 |
+
click('I accept')
|
| 178 |
+
```<end_code>
|
| 179 |
+
|
| 180 |
+
Proceed in several steps rather than trying to solve the task in one shot.
|
| 181 |
+
And at the end, only when you have your answer, return your final answer.
|
| 182 |
+
Code:
|
| 183 |
+
```py
|
| 184 |
+
final_answer("YOUR_ANSWER_HERE")
|
| 185 |
+
```<end_code>
|
| 186 |
+
|
| 187 |
+
If pages seem stuck on loading, you might have to wait, for instance `import time` and run `time.sleep(5.0)`. But don't overuse this!
|
| 188 |
+
To list elements on page, DO NOT try code-based element searches like 'contributors = find_all(S("ol > li"))': just look at the latest screenshot you have and read it visually, or use your tool search_item_ctrl_f.
|
| 189 |
+
Of course, you can act on buttons like a user would do when navigating.
|
| 190 |
+
After each code blob you write, you will be automatically provided with an updated screenshot of the browser and the current browser url.
|
| 191 |
+
But beware that the screenshot will only be taken at the end of the whole action, it won't see intermediate states.
|
| 192 |
+
Don't kill the browser.
|
| 193 |
+
When you have modals or cookie banners on screen, you should get rid of them before you can click anything else.
|
| 194 |
+
"""
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def main():
|
| 198 |
+
# Load environment variables
|
| 199 |
+
load_dotenv()
|
| 200 |
+
|
| 201 |
+
# Parse command line arguments
|
| 202 |
+
args = parse_arguments()
|
| 203 |
+
|
| 204 |
+
# Initialize the model based on the provided arguments
|
| 205 |
+
# model = load_model(args.model_type, args.model_id, args.api_key)
|
| 206 |
+
|
| 207 |
+
model = LiteLLMModel(
|
| 208 |
+
model_id="gpt-4o",
|
| 209 |
+
temperature=0.2,
|
| 210 |
+
api_key=api_key
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
global driver
|
| 215 |
+
driver = initialize_driver()
|
| 216 |
+
agent = initialize_agent(model, api_key)
|
| 217 |
+
|
| 218 |
+
# Run the agent with the provided prompt
|
| 219 |
+
|
| 220 |
+
agent.python_executor("from helium import *")
|
| 221 |
+
agent.run(args.prompt + helium_instructions)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
if __name__ == "__main__":
|
| 225 |
+
main()
|
smolagents.ipynb
CHANGED
|
@@ -18,7 +18,7 @@
|
|
| 18 |
},
|
| 19 |
{
|
| 20 |
"cell_type": "code",
|
| 21 |
-
"execution_count":
|
| 22 |
"id": "7710d928",
|
| 23 |
"metadata": {},
|
| 24 |
"outputs": [],
|
|
@@ -43,23 +43,6 @@
|
|
| 43 |
"## Test de Smolagent\n"
|
| 44 |
]
|
| 45 |
},
|
| 46 |
-
{
|
| 47 |
-
"cell_type": "code",
|
| 48 |
-
"execution_count": null,
|
| 49 |
-
"id": "8de17394",
|
| 50 |
-
"metadata": {},
|
| 51 |
-
"outputs": [],
|
| 52 |
-
"source": [
|
| 53 |
-
"from smolagents import CodeAgent, DuckDuckGoSearchTool\n",
|
| 54 |
-
"\n",
|
| 55 |
-
"# model = InferenceClientModel()\n",
|
| 56 |
-
"\n",
|
| 57 |
-
"model =\n",
|
| 58 |
-
"agent = CodeAgent(tools=[DuckDuckGoSearchTool()], model=model)\n",
|
| 59 |
-
"\n",
|
| 60 |
-
"agent.run(\"How many seconds would it take for a leopard at full speed to run through Pont des Arts?\")"
|
| 61 |
-
]
|
| 62 |
-
},
|
| 63 |
{
|
| 64 |
"cell_type": "markdown",
|
| 65 |
"id": "d68bb015",
|
|
|
|
| 18 |
},
|
| 19 |
{
|
| 20 |
"cell_type": "code",
|
| 21 |
+
"execution_count": 11,
|
| 22 |
"id": "7710d928",
|
| 23 |
"metadata": {},
|
| 24 |
"outputs": [],
|
|
|
|
| 43 |
"## Test de Smolagent\n"
|
| 44 |
]
|
| 45 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
{
|
| 47 |
"cell_type": "markdown",
|
| 48 |
"id": "d68bb015",
|