跳转到内容

使用多模态智能体

CrewAI 支持能够同时处理文本和非文本内容(如图像)的多模态智能体。本指南将演示如何为你的智能体启用并使用多模态能力。

要创建多模态智能体,只需在初始化智能体时把 multimodal 参数设为 True

from crewai import Agent
agent = Agent(
role="Image Analyst",
goal="Analyze and extract insights from images",
backstory="An expert in visual content interpretation with years of experience in image analysis",
multimodal=True # This enables multimodal capabilities
)

当你设置 multimodal=True 时,智能体会自动配置处理非文本内容所需的工具,包括 AddImageTool

多模态智能体会预先配置 AddImageTool,从而可以处理图像。你无需手动添加这个工具——只要启用多模态能力,它就会自动包含进来。

下面是一个完整示例,展示如何使用多模态智能体分析图像:

from crewai import Agent, Task, Crew
# Create a multimodal agent
image_analyst = Agent(
role="Product Analyst",
goal="Analyze product images and provide detailed descriptions",
backstory="Expert in visual product analysis with deep knowledge of design and features",
multimodal=True
)
# Create a task for image analysis
task = Task(
description="Analyze the product image at https://example.com/product.jpg and provide a detailed description",
expected_output="A detailed description of the product image",
agent=image_analyst
)
# Create and run the crew
crew = Crew(
agents=[image_analyst],
tasks=[task]
)
result = crew.kickoff()

你可以在为多模态智能体创建任务时提供额外上下文,或者针对图像提出具体问题。任务描述可以包含你希望智能体重点关注的方面:

from crewai import Agent, Task, Crew
# Create a multimodal agent for detailed analysis
expert_analyst = Agent(
role="Visual Quality Inspector",
goal="Perform detailed quality analysis of product images",
backstory="Senior quality control expert with expertise in visual inspection",
multimodal=True # AddImageTool is automatically included
)
# Create a task with specific analysis requirements
inspection_task = Task(
description="""
Analyze the product image at https://example.com/product.jpg with focus on:
1. Quality of materials
2. Manufacturing defects
3. Compliance with standards
Provide a detailed report highlighting any issues found.
""",
expected_output="A detailed report highlighting any issues found",
agent=expert_analyst
)
# Create and run the crew
crew = Crew(
agents=[expert_analyst],
tasks=[inspection_task]
)
result = crew.kickoff()

在与多模态智能体协作时,AddImageTool 会按以下模式自动配置:

class AddImageToolSchema:
image_url: str # Required: The URL or path of the image to process
action: Optional[str] = None # Optional: Additional context or specific questions about the image

多模态智能体会通过其内置工具自动处理图像,支持它:

  • 通过 URL 或本地文件路径访问图像
  • 在可选上下文或具体问题下处理图像内容
  • 基于视觉信息和任务要求提供分析与洞见

在使用多模态智能体时,请牢记以下最佳实践:

  1. 图像访问

    • 确保你的图像可通过智能体能够访问的 URL 读取
    • 对于本地图像,可考虑临时托管或使用绝对文件路径
    • 在运行任务前验证图像 URL 是否有效且可访问
  2. 任务描述

    • 明确说明你希望智能体分析图像的哪些方面
    • 在任务描述中加入清晰的问题或要求
    • 如需聚焦分析,可考虑使用可选的 action 参数
  3. 资源管理

    • 图像处理通常比纯文本任务需要更多计算资源
    • 某些语言模型可能需要对图像数据进行 base64 编码
    • 多张图像时可考虑批量处理以优化性能
  4. 环境准备

    • 验证环境是否具备图像处理所需依赖
    • 确认你的语言模型支持多模态能力
    • 先用小图像做测试以验证配置
  5. 错误处理

    • 为图像加载失败实现适当的错误处理
    • 准备图像处理失败时的回退策略
    • 监控并记录图像处理操作,便于调试