Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[UNIT] Final review of Unit 2.1 on smolagents - release 25/2/25 #216

Merged
merged 55 commits into from
Feb 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
55 commits
Select commit Hold shift + click to select a range
019dedf
Added Telemetry section to CodeAgents
sergiopaniego Feb 19, 2025
707b648
Updated vision agents example
sergiopaniego Feb 19, 2025
2b6453e
Improved vision+browser agent example
sergiopaniego Feb 20, 2025
bc01c88
Merge branch 'unit_2_1_smolagents' of https://github.com/huggingface/…
sergiopaniego Feb 21, 2025
64d235f
change a bold
burtenshaw Feb 21, 2025
7608d06
Merge branch 'main' into unit_2_1_smolagents
burtenshaw Feb 21, 2025
59ba0dc
restore table of contents
burtenshaw Feb 21, 2025
3b6e5fa
security suggestion
burtenshaw Feb 21, 2025
54a2613
improve introduction
burtenshaw Feb 21, 2025
74d6327
bolding in unit introduction
burtenshaw Feb 21, 2025
62927f4
bolding in multiagents
burtenshaw Feb 21, 2025
7e10c33
Added vision+browser agent video and final description
sergiopaniego Feb 21, 2025
f01b137
Merge branch 'unit_2_1_smolagents' of https://github.com/huggingface/…
sergiopaniego Feb 21, 2025
9e5aeff
Updated multiagent system notebook based on Aymeric ipynb
sergiopaniego Feb 21, 2025
713c804
Renamed notebooks and added Agent image
sergiopaniego Feb 21, 2025
a8e69eb
Added links to notebooks
sergiopaniego Feb 21, 2025
85c9360
Updated toctree
sergiopaniego Feb 21, 2025
b2c4fd4
Updated notebooks based on feedback
sergiopaniego Feb 21, 2025
b71072d
Update units/en/unit2/introduction.mdx
simoninithomas Feb 22, 2025
c0fb25c
Update units/en/_toctree.yml
simoninithomas Feb 22, 2025
2f2ef18
Update units/en/_toctree.yml
simoninithomas Feb 22, 2025
16d36df
Update units/en/unit2/smolagents/introduction.mdx
simoninithomas Feb 22, 2025
9d4eeab
Update units/en/unit2/smolagents/introduction.mdx
simoninithomas Feb 24, 2025
58af6f0
Update units/en/unit2/smolagents/code_agents.mdx
simoninithomas Feb 24, 2025
aaa9d88
Update units/en/unit2/smolagents/tools.mdx
simoninithomas Feb 24, 2025
f3ac071
use warning type tip instead of emoji
burtenshaw Feb 24, 2025
bea42fc
Merge pull request #217 from sergiopaniego/unit-2-1-final-additions
burtenshaw Feb 24, 2025
5cc6141
Updated video and image links to HF Org
sergiopaniego Feb 24, 2025
838df38
Updated links to notebooks
sergiopaniego Feb 24, 2025
cdbfd05
SmolAgents -> smolagents
sergiopaniego Feb 24, 2025
b6664e2
Updated tool and Tool using <code> instead of quotes
sergiopaniego Feb 24, 2025
104c6b5
Updated multiagent section adding outputs and updated notebook
sergiopaniego Feb 24, 2025
77b7fd8
Updated phrasingç
sergiopaniego Feb 24, 2025
65cfdd5
Merge pull request #231 from sergiopaniego/add-notebooks-media-smolag…
burtenshaw Feb 24, 2025
838f266
Apply suggestions from code review
burtenshaw Feb 25, 2025
2aa6a7a
make improvements in code_agents
burtenshaw Feb 25, 2025
772483b
Apply suggestions from code review
burtenshaw Feb 25, 2025
a3544a5
Added output map to notebook
sergiopaniego Feb 25, 2025
1b23d4b
Merge pull request #234 from sergiopaniego/add-output-map
burtenshaw Feb 25, 2025
c04ff37
Apply suggestions from code review
burtenshaw Feb 25, 2025
4fdd2d4
Update units/en/unit2/smolagents/code_agents.mdx
burtenshaw Feb 25, 2025
550aac6
Update units/en/unit2/smolagents/multi_agent_systems.mdx
burtenshaw Feb 25, 2025
d76d796
Update units/en/unit2/smolagents/multi_agent_systems.mdx
burtenshaw Feb 25, 2025
37c678f
Update units/en/unit2/smolagents/multi_agent_systems.mdx
burtenshaw Feb 25, 2025
8e93760
Update units/en/unit2/smolagents/multi_agent_systems.mdx
burtenshaw Feb 25, 2025
334f87e
Update units/en/unit2/smolagents/multi_agent_systems.mdx
burtenshaw Feb 25, 2025
0a74c9d
respond to suggestions
burtenshaw Feb 25, 2025
a1312ed
add like CTA
Jofthomas Feb 25, 2025
bae3ba0
remove capital letter
Jofthomas Feb 25, 2025
b1fb9a9
add link
Jofthomas Feb 25, 2025
24f5461
redundant with phrase on top
Jofthomas Feb 25, 2025
ca8d7dd
Merge pull request #235 from huggingface/unit2.1_smolagents_Joffrey-r…
burtenshaw Feb 25, 2025
273d4e7
fix casing on smolagents
burtenshaw Feb 25, 2025
0a072cb
final improvements in code agents
burtenshaw Feb 25, 2025
804ffd6
fixes in conclusion
burtenshaw Feb 25, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10,634 changes: 10,634 additions & 0 deletions notebooks/unit2/smolagents/code_agents.ipynb

Large diffs are not rendered by default.

8,639 changes: 8,639 additions & 0 deletions notebooks/unit2/smolagents/multiagent_notebook.ipynb

Large diffs are not rendered by default.

2,883 changes: 2,883 additions & 0 deletions notebooks/unit2/smolagents/retrieval_agents.ipynb

Large diffs are not rendered by default.

596 changes: 596 additions & 0 deletions notebooks/unit2/smolagents/tool_calling_agents.ipynb

Large diffs are not rendered by default.

1,590 changes: 1,590 additions & 0 deletions notebooks/unit2/smolagents/tools.ipynb

Large diffs are not rendered by default.

535 changes: 535 additions & 0 deletions notebooks/unit2/smolagents/vision_agents.ipynb

Large diffs are not rendered by default.

207 changes: 207 additions & 0 deletions notebooks/unit2/smolagents/vision_web_browser.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
import argparse
from io import BytesIO
from time import sleep

import helium
from dotenv import load_dotenv
from PIL import Image
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

from smolagents import CodeAgent, DuckDuckGoSearchTool, tool
from smolagents.agents import ActionStep
from smolagents.cli import load_model


alfred_guest_list_request = """
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.

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.
"""


def parse_arguments():
parser = argparse.ArgumentParser(description="Run a web browser automation script with a specified model.")
parser.add_argument(
"prompt",
type=str,
nargs="?", # Makes it optional
default=alfred_guest_list_request,
help="The prompt to run with the agent",
)
parser.add_argument(
"--model-type",
type=str,
default="LiteLLMModel",
help="The model type to use (e.g., OpenAIServerModel, LiteLLMModel, TransformersModel, HfApiModel)",
)
parser.add_argument(
"--model-id",
type=str,
default="gpt-4o",
help="The model ID to use for the specified model type",
)
return parser.parse_args()


def save_screenshot(memory_step: ActionStep, agent: CodeAgent) -> None:
sleep(1.0) # Let JavaScript animations happen before taking the screenshot
driver = helium.get_driver()
current_step = memory_step.step_number
if driver is not None:
for previous_memory_step in agent.memory.steps: # Remove previous screenshots from logs for lean processing
if isinstance(previous_memory_step, ActionStep) and previous_memory_step.step_number <= current_step - 2:
previous_memory_step.observations_images = None
png_bytes = driver.get_screenshot_as_png()
image = Image.open(BytesIO(png_bytes))
print(f"Captured a browser screenshot: {image.size} pixels")
memory_step.observations_images = [image.copy()] # Create a copy to ensure it persists, important!

# Update observations with current URL
url_info = f"Current url: {driver.current_url}"
memory_step.observations = (
url_info if memory_step.observations is None else memory_step.observations + "\n" + url_info
)
return


@tool
def search_item_ctrl_f(text: str, nth_result: int = 1) -> str:
"""
Searches for text on the current page via Ctrl + F and jumps to the nth occurrence.
Args:
text: The text to search for
nth_result: Which occurrence to jump to (default: 1)
"""
elements = driver.find_elements(By.XPATH, f"//*[contains(text(), '{text}')]")
if nth_result > len(elements):
raise Exception(f"Match n°{nth_result} not found (only {len(elements)} matches found)")
result = f"Found {len(elements)} matches for '{text}'."
elem = elements[nth_result - 1]
driver.execute_script("arguments[0].scrollIntoView(true);", elem)
result += f"Focused on element {nth_result} of {len(elements)}"
return result


@tool
def go_back() -> None:
"""Goes back to previous page."""
driver.back()


@tool
def close_popups() -> str:
"""
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.
"""
webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform()


def initialize_driver():
"""Initialize the Selenium WebDriver."""
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--force-device-scale-factor=1")
chrome_options.add_argument("--window-size=1000,1350")
chrome_options.add_argument("--disable-pdf-viewer")
chrome_options.add_argument("--window-position=0,0")
return helium.start_chrome(headless=False, options=chrome_options)


def initialize_agent(model):
"""Initialize the CodeAgent with the specified model."""
return CodeAgent(
tools=[DuckDuckGoSearchTool(), go_back, close_popups, search_item_ctrl_f],
model=model,
additional_authorized_imports=["helium"],
step_callbacks=[save_screenshot],
max_steps=20,
verbosity_level=2,
)


helium_instructions = """
Use your web_search tool when you want to get Google search results.
Then you can use helium to access websites. Don't use helium for Google search, only for navigating websites!
Don't bother about the helium driver, it's already managed.
We've already ran "from helium import *"
Then you can go to pages!
Code:
```py
go_to('github.com/trending')
```<end_code>

You can directly click clickable elements by inputting the text that appears on them.
Code:
```py
click("Top products")
```<end_code>

If it's a link:
Code:
```py
click(Link("Top products"))
```<end_code>

If you try to interact with an element and it's not found, you'll get a LookupError.
In general stop your action after each button click to see what happens on your screenshot.
Never try to login in a page.

To scroll up or down, use scroll_down or scroll_up with as an argument the number of pixels to scroll from.
Code:
```py
scroll_down(num_pixels=1200) # This will scroll one viewport down
```<end_code>

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).
Just use your built-in tool `close_popups` to close them:
Code:
```py
close_popups()
```<end_code>

You can use .exists() to check for the existence of an element. For example:
Code:
```py
if Text('Accept cookies?').exists():
click('I accept')
```<end_code>

Proceed in several steps rather than trying to solve the task in one shot.
And at the end, only when you have your answer, return your final answer.
Code:
```py
final_answer("YOUR_ANSWER_HERE")
```<end_code>

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!
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.
Of course, you can act on buttons like a user would do when navigating.
After each code blob you write, you will be automatically provided with an updated screenshot of the browser and the current browser url.
But beware that the screenshot will only be taken at the end of the whole action, it won't see intermediate states.
Don't kill the browser.
When you have modals or cookie banners on screen, you should get rid of them before you can click anything else.
"""


def main():
# Load environment variables
load_dotenv()

# Parse command line arguments
args = parse_arguments()

# Initialize the model based on the provided arguments
model = load_model(args.model_type, args.model_id)

global driver
driver = initialize_driver()
agent = initialize_agent(model)

# Run the agent with the provided prompt
agent.python_executor("from helium import *", agent.state)
agent.run(args.prompt + helium_instructions)


if __name__ == "__main__":
main()
32 changes: 31 additions & 1 deletion units/en/_toctree.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,41 @@
- local: unit1/dummy-agent-library
title: Dummy Agent Library
- local: unit1/tutorial
title: Let’s Create Our First Agent Using Smolagents
title: Let’s Create Our First Agent Using smolagents
- local: unit1/final-quiz
title: Unit 1 Final Quiz
- local: unit1/conclusion
title: Conclusion
- title: Unit 2. Frameworks for AI Agents
sections:
- local: unit2/introduction
title: Frameworks for AI Agents
- title: Unit 2.1 The smolagents framework
sections:
- local: unit2/smolagents/introduction
title: Introduction to smolagents
- local: unit2/smolagents/why_use_smolagents
title: Why use smolagents?
- local: unit2/smolagents/quiz1
title: Quick Quiz 1
- local: unit2/smolagents/code_agents
title: Building Agents That Use Code
- local: unit2/smolagents/tool_calling_agents
title: Integrating Agents With Tools
- local: unit2/smolagents/tools
title: Tools
- local: unit2/smolagents/retrieval_agents
title: Retrieval Agents
- local: unit2/smolagents/quiz2
title: Quick Quiz 2
- local: unit2/smolagents/multi_agent_systems
title: Multi-Agent Systems
- local: unit2/smolagents/vision_agents
title: Vision and Browser agents
- local: unit2/smolagents/final_quiz
title: Final Quiz
- local: unit2/smolagents/conclusion
title: Conclusion
- title: Bonus Unit 1. Fine-tuning an LLM for Function-calling
sections:
- local: bonus-unit1/introduction
Expand Down
Empty file removed units/en/unit2/README.md
Empty file.
37 changes: 37 additions & 0 deletions units/en/unit2/introduction.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Introduction to Agentic Frameworks

<img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/thumbnail.jpg" alt="Thumbnail"/>

Welcome to this second unit, where **we'll explore different agentic frameworks** that can be used to build powerful agentic applications.

We will study:

- In Unit 2.1: [smolagents](https://huggingface.co/docs/smolagents/en/index)
- In Unit 2.2: [LlamaIndex](https://www.llamaindex.ai/)
- In Unit 2.3: [LangGraph](https://www.langchain.com/langgraph)

Let's dive in! 🕵

## When to Use an Agentic Framework

An agentic framework is **not always needed when building an application around LLMs**. They provide flexibility in the workflow to efficiently solve a specific task, but they're not always necessary.

Sometimes, **predefined workflows are sufficient** to fulfill user requests, and there is no real need for an agentic framework. If the approach to build an agent is simple, like a chain of prompts, using plain code may be enough. The advantage is that the developer will have **full control and understanding of their system without abstractions**.

However, when the workflow becomes more complex, such as letting an LLM call functions or using multiple agents, these abstractions start to become helpful.

Considering these ideas, we can already identify the need for some features:

* An *LLM engine* that powers the system.
* A *list of tools* the agent can access.
* A *parser* for extracting tool calls from the LLM output.
* A *system prompt* synced with the parser.
* A *memory system*.
* *Error logging and retry mechanisms* to control LLM mistakes.
We'll explore how these topics are resolved in various frameworks, including `smolagents`, `LlamaIndex`, and `LangGraph`.

## Agentic Frameworks Units

| Framework | Description | Unit Author |
|------------|----------------|----------------|
| [smolagents](./smolagents/introduction) | Agents framework developed by Hugging Face. | Sergio Paniego - [HF](https://huggingface.co/sergiopaniego) - [X](https://x.com/sergiopaniego) - [Linkedin](https://www.linkedin.com/in/sergio-paniego-blanco) |
Loading