智能体课程文档
使用 smolagents 的视觉代理
并获得增强的文档体验
开始使用
使用 smolagents 的视觉代理
赋予代理视觉能力对于解决超出文本处理范围的任务至关重要。许多现实世界的挑战,例如网页浏览或文档理解,都需要分析丰富的视觉内容。幸运的是,smolagents
提供了对视觉语言模型 (VLM) 的内置支持,使代理能够有效地处理和解释图像。
在这个例子中,想象一下韦恩庄园的管家阿尔弗雷德的任务是核实参加派对的客人的身份。你可以想象,阿尔弗雷德可能不熟悉所有来宾。为了帮助他,我们可以使用一个代理,通过使用 VLM 搜索他们的视觉信息来验证他们的身份。这将使阿尔弗雷德能够就谁可以进入做出明智的决定。让我们构建这个例子!
在代理执行开始时提供图像
在这种方法中,图像在代理执行开始时传递给代理,并与任务提示一起存储为 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.'
}
在这种情况下,输出显示此人正在冒充他人,因此我们可以阻止小丑进入派对!
通过动态检索提供图像
之前的方法很有价值,并且有许多潜在的用例。然而,在客人不在数据库中的情况下,我们需要探索其他识别他们的方法。一种可能的解决方案是动态地从外部源检索图像和信息,例如浏览网页以获取详细信息。
在这种方法中,图像在执行期间动态添加到代理的内存中。我们知道,smolagents
中的代理基于 MultiStepAgent
类,它是 ReAct 框架的抽象。此类以结构化循环运行,其中各种变量和知识在不同阶段被记录
- SystemPromptStep:存储系统提示。
- TaskStep:记录用户查询和任何提供的输入。
- ActionStep:捕获代理操作和结果的日志。
这种结构化方法允许代理动态地整合视觉信息并适应不断发展的任务。下面是我们已经看过的图表,它说明了动态工作流过程以及不同步骤如何融入代理生命周期。当浏览时,代理可以截屏并将其保存为 ActionStep
中的 observation_images
。
现在我们了解了需求,让我们构建完整的示例。在这种情况下,阿尔弗雷德希望完全控制客人验证过程,因此浏览详细信息成为一个可行的解决方案。为了完成此示例,我们需要一组新的代理工具。此外,我们将使用 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 视觉 - 描述视觉代理功能的博客。
- 使用代理进行网页浏览器自动化 🤖🌐 - 使用视觉代理进行网页浏览的示例。
- 网页浏览器视觉代理示例 - 使用视觉代理进行网页浏览的示例。