Tavily 提取工具
TavilyExtractorTool 允许 CrewAI 智能体通过 Tavily API 从网页中提取结构化内容。它可以处理单个 URL 或 URL 列表,并提供控制提取深度和包含图片的选项。
要使用 TavilyExtractorTool,你需要安装 tavily-python 库:
uv add 'crewai[tools]' tavily-python你还需要将 Tavily API key 设置为环境变量:
export TAVILY_API_KEY='your-tavily-api-key'下面展示如何在 CrewAI 智能体中初始化并使用 TavilyExtractorTool:
import osfrom crewai import Agent, Task, Crewfrom crewai_tools import TavilyExtractorTool
# 确保环境中已设置 TAVILY_API_KEY# os.environ["TAVILY_API_KEY"] = "YOUR_API_KEY"
# 初始化工具tavily_tool = TavilyExtractorTool()
# 创建使用该工具的智能体extractor_agent = Agent( role='Web Content Extractor', goal='Extract key information from specified web pages', backstory='You are an expert at extracting relevant content from websites using the Tavily API.', tools=[tavily_tool], verbose=True)
# 为智能体定义任务extract_task = Task( description='Extract the main content from the URL https://example.com using basic extraction depth.', expected_output='A JSON string containing the extracted content from the URL.', agent=extractor_agent)
# 创建并运行 crewcrew = Crew( agents=[extractor_agent], tasks=[extract_task], verbose=2)
result = crew.kickoff()print(result)TavilyExtractorTool 接受以下参数:
urls(Union[List[str], str]):必需。要从中提取数据的单个 URL 字符串或 URL 字符串列表。include_images(Optional[bool]):是否在提取结果中包含图片。默认值为False。extract_depth(Literal[“basic”, “advanced”]):提取深度。使用"basic"可获得更快、表层的提取,使用"advanced"可获得更全面的提取。默认值为"basic"。timeout(int):等待提取请求完成的最长时间(秒)。默认值为60。
使用高级提取处理多个 URL
Section titled “使用高级提取处理多个 URL”# 多 URL + 高级提取示例multi_extract_task = Task( description='Extract content from https://example.com and https://anotherexample.org using advanced extraction.', expected_output='A JSON string containing the extracted content from both URLs.', agent=extractor_agent)
# 使用自定义参数配置工具custom_extractor = TavilyExtractorTool( extract_depth='advanced', include_images=True, timeout=120)
agent_with_custom_tool = Agent( role="Advanced Content Extractor", goal="Extract comprehensive content with images", tools=[custom_extractor])你可以在初始化时设置参数来自定义工具行为:
# 使用自定义配置初始化extractor_tool = TavilyExtractorTool( extract_depth='advanced', # 更全面的提取 include_images=True, # 包含图片结果 timeout=90 # 自定义超时)- 单个或多个 URL:从一个 URL 提取内容,或在单次请求中处理多个 URL
- 可配置深度:可在基础(快速)和高级(全面)提取模式之间选择
- 图片支持:可选择在提取结果中包含图片
- 结构化输出:返回包含提取内容的格式良好的 JSON
- 错误处理:对网络超时和提取错误提供稳健处理
工具会返回一个 JSON 字符串,表示从所提供 URL 中提取的结构化数据。具体结构取决于网页内容以及所使用的 extract_depth。
常见响应元素包括:
- Title:页面标题
- Content:页面主体文本内容
- Images:图片 URL 和元数据(当
include_images=True时) - Metadata:额外的页面信息,例如作者、描述等
- 内容分析:从竞争对手网站提取并分析内容
- 研究:从多个来源收集结构化数据用于分析
- 内容迁移:从现有网站提取内容用于迁移
- 监控:定期提取内容以检测变化
- 数据收集:系统地从网络来源提取信息
关于响应结构和可用选项的详细信息,请参阅 Tavily API 文档。