跳转到主要内容
TavilySearchTool 提供了 Tavily 搜索 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”], 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

高级用法

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