跳转到主要内容
TavilySearchTool 为 Tavily Search API 提供了一个接口,使 CrewAI 智能体能够执行全面的网络搜索。它允许指定搜索深度、主题、时间范围、包含/排除的域名,以及是否在结果中包含直接答案、原始内容或图片。

安装

要使用 TavilySearchTool,您需要安装 tavily-python
pip install 'crewai[tools]' tavily-python

环境变量

请确保您的 Tavily API 密钥已设置为环境变量
export TAVILY_API_KEY='your_tavily_api_key'
请在 https://app.tavily.com/ 获取 API 密钥(注册,然后创建一个密钥)。

用法示例

以下是如何在 CrewAI 智能体中初始化和使用 TavilySearchTool 的方法
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”], 可选): 搜索深度。默认为 "basic"
  • topic (Literal[“general”, “news”, “finance”], 可选): 搜索的重点主题。默认为 "general"
  • time_range (Literal[“day”, “week”, “month”, “year”], 可选): 搜索的时间范围。默认为 None
  • days (int, 可选): 搜索回溯的天数。如果未设置 time_range,则此参数相关。默认为 7
  • max_results (int, 可选): 返回的最大搜索结果数量。默认为 5
  • include_domains (Sequence[str], 可选): 在搜索中优先考虑的域名列表。默认为 None
  • exclude_domains (Sequence[str], 可选): 从搜索中排除的域名列表。默认为 None
  • include_answer (Union[bool, Literal[“basic”, “advanced”]], 可选): 是否包含从搜索结果中综合的直接答案。默认为 False
  • include_raw_content (bool, 可选): 是否包含搜索页面的原始 HTML 内容。默认为 False
  • include_images (bool, 可选): 是否包含图片结果。默认为 False
  • timeout (int, 可选): 请求超时时间(秒)。默认为 60

高级用法

您可以使用自定义参数配置该工具
# 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 内容(启用时)
每个结果的内容都会被自动截断,以防止上下文窗口问题,同时保留最相关的信息。