主题
Tavily 搜索工具
使用 Tavily Search API 执行全面的网络搜索
TavilySearchTool 提供了 Tavily Search API 的接口,使 CrewAI 智能体能够执行全面的网络搜索。它允许指定搜索深度、主题、时间范围、包含/排除的域名,以及是否在结果中包含直接答案、原始内容或图片。
安装
要使用 TavilySearchTool,你需要安装 tavily-python 库:
shell
uv add 'crewai[tools]' tavily-python环境变量
确保已将你的 Tavily API 密钥设置为环境变量:
bash
export TAVILY_API_KEY='your_tavily_api_key'在 https://app.tavily.com/ 获取 API 密钥(注册后创建一个密钥)。
用法示例
以下演示如何在 CrewAI 智能体中初始化并使用 TavilySearchTool:
python
import os
from crewai import Agent, Task, Crew
from crewai_tools import TavilySearchTool
# Ensure the TAVILY_API_KEY environment variable is set
# os.environ["TAVILY_API_KEY"] = "YOUR_TAVILY_API_KEY"
# Initialize the tool
tavily_tool = TavilySearchTool()
# Create an agent that uses the tool
researcher = Agent(
role='Market Researcher',
goal='Find information about the latest AI trends',
backstory='An expert market researcher specializing in technology.',
tools=[tavily_tool],
verbose=True
)
# Create a task for the agent
research_task = Task(
description='Search for the top 3 AI trends in 2024.',
expected_output='A JSON report summarizing the top 3 AI trends found.',
agent=researcher
)
# Form the crew and kick it off
crew = Crew(
agents=[researcher],
tasks=[research_task],
verbose=2
)
result = crew.kickoff()
print(result)配置选项
TavilySearchTool 在初始化时或调用 run 方法时接受以下参数:
query(str):必填。搜索查询字符串。search_depth(Literal["basic", "advanced"], optional):搜索深度。默认为"basic"。topic(Literal["general", "news", "finance"], optional):搜索聚焦的主题。默认为"general"。time_range(Literal["day", "week", "month", "year"], optional):搜索的时间范围。默认为None。days(int, optional):向前搜索的天数。在未设置time_range时相关。默认为7。max_results(int, optional):要返回的搜索结果最大数量。默认为5。include_domains(Sequence[str], optional):搜索中优先考虑的域名列表。默认为None。exclude_domains(Sequence[str], optional):要从搜索中排除的域名列表。默认为None。include_answer(Union[bool, Literal["basic", "advanced"]], optional):是否包含根据搜索结果综合生成的直接答案。默认为False。include_raw_content(bool, optional):是否包含所搜索页面的原始 HTML 内容。默认为False。include_images(bool, optional):是否包含图片结果。默认为False。timeout(int, optional):请求超时时间(秒)。默认为60。
高级用法
你可以使用自定义参数配置该工具:
python
# Example: Initialize with specific parameters
custom_tavily_tool = TavilySearchTool(
search_depth='advanced',
max_results=10,
include_answer=True
)
# The agent will use these defaults
agent_with_custom_tool = Agent(
role="Advanced Researcher",
goal="Conduct detailed research with comprehensive results",
tools=[custom_tavily_tool]
)特性
- 全面搜索:访问 Tavily 强大的搜索索引
- 可配置深度:在基础与高级搜索模式之间选择
- 主题过滤:将搜索聚焦于通用、新闻或金融主题
- 时间范围控制:将结果限制在特定时间段内
- 域名控制:包含或排除特定域名
- 直接答案:从搜索结果中获取综合生成的答案
- 内容过滤:通过自动截断内容来避免上下文窗口问题
响应格式
该工具以 JSON 字符串形式返回搜索结果,其中包含:
- 包含标题、URL 和内容片段的搜索结果
- 可选的查询直接答案
- 可选的图片结果
- 可选的原始 HTML 内容(启用时)
每条结果的内容都会被自动截断,以在保留最相关信息的同时避免上下文窗口问题。