[!警告] 本节中的示例需要访问一个强大的VLM模型。我们使用GPT-4o API进行了测试。
然而, 为何使用 smolagents 讨论了 smolagents 和 Hugging Face 支持的替代解决方案。如果您想探索其他选项,请务必查看该部分内容。
为智能体提供视觉能力对于解决超出文本处理的任务至关重要。许多现实世界中的挑战,如网页浏览或文档理解,都需要分析丰富的视觉内容。幸运的是, smolagents 为视觉语言模型提供内置支持,使智能体能够有效处理和解译图像。
在这个示例中,假设韦恩庄园的管家阿尔弗雷德负责核实参加派对的客人的身份。可想而知,阿尔弗雷德可能对每一位到访的客人都不熟悉。为了帮助他,我们可以使用一个智能体,该智能体通过利用虚拟语言模型来搜索关于客人外貌的视觉信息,从而验证他们的身份。这将使阿尔弗雷德能够做出关于谁可以进入的明智决策。让我们来构建这个示例吧!
在智能体执行开始时提供图像
[!TIP] 您可以按照代码进行操作。 这个笔记本 您可以使用 Google Colab来运行它。
在这种方法中,图像在开始时被传递给智能体,并存储为 task_images 与任务提示并行。智能体在运行过程中处理这些图像。
假设阿尔弗雷德想要验证参加派对的超级英雄们的身份。他已经有一组来自之前派对的图片数据,其中包含客人的名字。当看到一位新访客的照片时,智能体可以将照片与现有的数据集进行比较,并决定是否允许他们进入。
在这种情况下,有客人试图进入,阿尔弗雷德怀疑这位访客可能是扮演神奇女侠的小丑。阿尔弗雷德需要验证他们的身份,以防止任何不希望的人进入。
让我们来构建这个示例。首先,加载图像。在这种情况下,我们使用来自维基百科的图像,以保持示例的简洁性,但想象一下可能的应用场景!
from PIL import Image
import requests
from io import BytesIO
image_urls = [
"https://upload.wikimedia.org/wikipedia/commons/e/e8/The_Joker_at_Wax_Museum_Plus.jpg", # Joker image
"https://upload.wikimedia.org/wikipedia/en/9/98/Joker_%28DC_Comics_character%29.jpg" # Joker image
]
images = []
for url in image_urls:
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
}
response = requests.get(url,headers=headers)
image = Image.open(BytesIO(response.content)).convert("RGB")
images.append(image)
现在我们已经有了这些图片,智能体会告诉我们某个客人究竟是超级英雄(神奇女侠)还是反派角色(小丑)。
from smolagents import CodeAgent, OpenAIServerModel
model = OpenAIServerModel(model_id="gpt-4o")
# Instantiate the agent
agent = CodeAgent(
tools=[],
model=model,
max_steps=20,
verbosity_level=2
)
response = agent.run(
"""
Describe the costume and makeup that the comic character in these photos is wearing and return the description.
Tell me if the guest is The Joker or Wonder Woman.
""",
images=images
)
在我的实验中,输出结果如下,不过在您的情况下可能会有所不同,正如我们已经讨论过的那样:
{
'Costume and Makeup - First Image': (
'Purple coat and a purple silk-like cravat or tie over a mustard-yellow shirt.',
'White face paint with exaggerated features, dark eyebrows, blue eye makeup, red lips forming a wide smile.'
),
'Costume and Makeup - Second Image': (
'Dark suit with a flower on the lapel, holding a playing card.',
'Pale skin, green hair, very red lips with an exaggerated grin.'
),
'Character Identity': 'This character resembles known depictions of The Joker from comic book media.'
}
在这种情况下,输出结果显示该人正在冒充他人,因此我们可以阻止“小丑”加入该群体!
提供带有动态检索的图像
[!TIP] 您可以按照代码进行操作。 这个 Python 文件
之前的方法很有价值,并且有许多潜在的应用场景。然而,在智能体不在数据库中的情况下,我们需要探索其他识别它们的方法。一种可能的解决方案是从外部来源动态获取图像和信息,例如通过浏览网络来获取详细信息。
在这种方法中,在执行过程中,图像会被动态添加到智能体的内存中。众所周知,智能体在 smolagents 基于 MultiStepAgent 这是一个对 ReAct 框架的抽象。这个类在一个结构化的循环中运行,其中各种变量和知识在不同的阶段被记录下来:
- 系统提示步骤: 存储系统提示信息。
- 任务步骤: 记录用户查询以及任何提供的输入。
- ActionStep: 动作步骤 捕获智能体行为和结果的日志。
这种结构化方法使智能体能够动态整合视觉信息,并针对不断变化的任务做出适应性响应。下面是我们已经看到的图表,它展示了动态工作流程过程以及不同步骤如何在智能体生命周期中相互整合。在浏览过程中,智能体可以截取屏幕截图并将其保存为 observation_images 在 ActionStep.

既然我们已经了解了需求,那么让我们来构建完整的示例。在这种情况下,Alfred希望完全控制客人验证过程,因此搜索相关信息成为一个可行的解决方案。为了完成这个示例,我们需要为智能体配备一套新的工具。此外,我们还将使用Selenium和Helium这两个浏览器自动化工具。这将使我们能够构建一个能够探索网络、搜索潜在客人相关信息并获取验证信息的智能体。现在,让我们安装所需的工具吧:
pip install "smolagents[all]" helium selenium python-dotenv
我们需要一套专门为浏览设计的智能体工具,例如 search_item_ctrl_f, go_back,以及 close_popups这些工具使智能体能够像在网页上导航的人一样行事。
@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()
我们还需要保存截图的功能,因为这将是我们的VLM智能体完成任务时不可或缺的一部分。该功能会捕获截图并将其保存下来。 step_log.observations_images = [image.copy()],使得智能体能够在导航过程中动态存储和处理图像。
def save_screenshot(step_log: ActionStep, agent: CodeAgent) -> None:
sleep(1.0) # Let JavaScript animations happen before taking the screenshot
driver = helium.get_driver()
current_step = step_log.step_number
if driver is not None:
for step_logs in agent.logs: # Remove previous screenshots from logs for lean processing
if isinstance(step_log, ActionStep) and step_log.step_number <= current_step - 2:
step_logs.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")
step_log.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}"
step_log.observations = url_info if step_logs.observations is None else step_log.observations + "\n" + url_info
return
此函数被传递给智能体作为 step_callback因为在智能体执行过程中,每个步骤的末尾都会触发此操作。这使得智能体能够动态地捕获并存储屏幕截图,以记录其整个过程。
现在,我们可以为浏览网页的视觉智能体生成工具,为它提供我们创建的工具,以及 DuckDuckGoSearchTool 以探索网络为目的。该工具将帮助智能体根据视觉线索获取验证客人身份所需的信息。
from smolagents import CodeAgent, OpenAIServerModel, DuckDuckGoSearchTool
model = OpenAIServerModel(model_id="gpt-4o")
agent = 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,
)
至此,阿尔弗雷德已经准备好检查智能体的身份,并据此做出是否允许他们加入派对的决策了:
agent.run("""
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.
""" + helium_instructions)
你可以看到,我们包含了 helium_instructions 作为任务的一部分。这个特殊提示旨在控制智能体的导航,确保它在浏览网页时遵循正确的步骤。
让我们在下面的视频中看看这是如何工作的:
这就是最终输出结果:
Final answer: Wonder Woman is typically depicted wearing a red and gold bustier, blue shorts or skirt with white stars, a golden tiara, silver bracelets, and a golden Lasso of Truth. She is Princess Diana of Themyscira, known as Diana Prince in the world of men.
有了这一切,我们已经成功地为这个活动创建了身份验证工具!阿尔弗雷德现在拥有了必要的工具,可以确保只有合适的客人能够进入大门。现在,一切都已经准备就绪,让韦恩庄园的时光变得愉快起来吧!
进一步阅读
- 我们刚刚为 smolagents 赋予了“视力” - 描述视觉智能体功能的博客文章。
- 智能体与浏览器自动化 🤖🌐 - 使用视觉智能体进行网页浏览的示例。
- 网络浏览器视觉智能体示例 - 使用视觉智能体进行网页浏览的示例。