主题
Tavily 提取工具
使用 Tavily API 从网页中提取结构化内容
TavilyExtractorTool 让 CrewAI 智能体能够使用 Tavily API 从网页中提取结构化内容。它可以处理单个 URL 或 URL 列表,并提供控制提取深度和包含图片的选项。
安装
要使用 TavilyExtractorTool,你需要安装 tavily-python 库:
shell
uv add 'crewai[tools]' tavily-python你还需要将 Tavily API 密钥设置为环境变量:
bash
export TAVILY_API_KEY='your-tavily-api-key'用法示例
以下演示如何在 CrewAI 智能体中初始化并使用 TavilyExtractorTool:
python
import os
from crewai import Agent, Task, Crew
from crewai_tools import TavilyExtractorTool
# Ensure TAVILY_API_KEY is set in your environment
# os.environ["TAVILY_API_KEY"] = "YOUR_API_KEY"
# Initialize the tool
tavily_tool = TavilyExtractorTool()
# Create an agent that uses the tool
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
)
# Define a task for the agent
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
)
# Create and run the crew
crew = 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
python
# Example with multiple URLs and advanced extraction
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
)
# Configure the tool with custom parameters
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]
)工具参数
你可以在初始化时设置参数来自定义工具的行为:
python
# Initialize with custom configuration
extractor_tool = TavilyExtractorTool(
extract_depth='advanced', # More comprehensive extraction
include_images=True, # Include image results
timeout=90 # Custom timeout
)特性
- 单个或多个 URL:从单个 URL 提取内容,或在单个请求中处理多个 URL
- 可配置深度:在基础(快速)和高级(全面)提取模式之间选择
- 图片支持:可选择在提取结果中包含图片
- 结构化输出:返回格式良好的 JSON,包含提取的内容
- 错误处理:稳健地处理网络超时和提取错误
响应格式
该工具返回一个 JSON 字符串,表示从所提供 URL 中提取的结构化数据。具体结构取决于页面内容以及所使用的 extract_depth。
常见的响应元素包括:
- Title:页面标题
- Content:页面的正文内容
- Images:图片 URL 和元数据(当
include_images=True时) - Metadata:额外的页面信息,如作者、描述等
使用场景
- 内容分析:从竞品网站提取并分析内容
- 研究:从多个来源收集结构化数据用于分析
- 内容迁移:从现有网站提取内容以进行迁移
- 监控:定期提取内容以检测变更
- 数据收集:从网络来源系统地提取信息
有关响应结构和可用选项的详细信息,请参阅 Tavily API 文档。