Skip to main content
Tavily 搜索 API 是一款专为 AI 智能体(LLM)构建的搜索引擎,能够快速提供实时、准确且基于事实的结果。

概述

集成详情

可序列化JS 支持版本
TavilySearchlangchain-tavilyPyPI - Version

工具功能

返回构件原生异步返回数据定价
标题、URL、内容摘要、原始内容、答案、图片每月 1,000 次免费搜索

设置

该集成位于 langchain-tavily 包中。
pip install -qU langchain-tavily

凭据

我们还需要设置 Tavily API 密钥。您可以访问此网站注册账户后获取 API 密钥。
import getpass
import os

if not os.environ.get("TAVILY_API_KEY"):
    os.environ["TAVILY_API_KEY"] = getpass.getpass("Tavily API key:\n")

实例化

下面展示如何实例化 Tavily 搜索工具。该工具在实例化时接受各种参数以自定义搜索行为。实例化后,我们使用一个简单查询调用工具。此工具允许您使用 Tavily 搜索 API 端点完成搜索查询。 实例化参数:
  • max_results(可选,int):返回的最大搜索结果数。默认为 5。
  • topic(可选,str):搜索类别,可为 “general”(通用)、“news”(新闻)或 “finance”(财经)。默认为 “general”。
  • include_answer(可选,bool):在结果中包含原始查询的答案。默认为 False。
  • include_raw_content(可选,bool):包含每个搜索结果已清理和解析的 HTML。默认为 False。
  • include_images(可选,bool):在响应中包含与查询相关的图片列表。默认为 False。
  • include_image_descriptions(可选,bool):为每张图片包含描述文字。默认为 False。
  • search_depth(可选,str):搜索深度,可为 “basic”(基础)或 “advanced”(高级)。默认为 “basic”。
  • time_range(可选,str):从当前日期往前过滤结果的时间范围 - “day”(一天)、“week”(一周)、“month”(一个月)或 “year”(一年)。默认为 None。
  • include_domains(可选,List[str]):明确包含的域名列表。默认为 None。
  • exclude_domains(可选,List[str]):明确排除的域名列表。默认为 None。
有关可用参数的全面概述,请参阅 Tavily 搜索 API 文档
from langchain_tavily import TavilySearch

tool = TavilySearch(
    max_results=5,
    topic="general",
    # include_answer=False,
    # include_raw_content=False,
    # include_images=False,
    # include_image_descriptions=False,
    # search_depth="basic",
    # time_range="day",
    # include_domains=None,
    # exclude_domains=None
)

调用

直接使用参数调用

Tavily 搜索工具在调用时接受以下参数:
  • query(必填):自然语言搜索查询
  • 以下参数也可在调用时设置:include_imagessearch_depthtime_rangeinclude_domainsexclude_domainsinclude_images
  • 出于可靠性和性能原因,影响响应大小的某些参数在调用时不可修改:include_answerinclude_raw_content。这些限制可防止意外的上下文窗口问题并确保结果一致。
注意:可选参数供智能体动态设置。若您在实例化时设置了某个参数,再以不同值调用工具,工具将使用调用时传入的值。
tool.invoke({"query": "What happened at the last wimbledon"})

使用 ToolCall 调用

我们也可以使用模型生成的 ToolCall 来调用工具,此时将返回一条 ToolMessage:
# 通常由模型生成,此处为演示目的直接创建工具调用。
model_generated_tool_call = {
    "args": {"query": "euro 2024 host nation"},
    "id": "1",
    "name": "tavily",
    "type": "tool_call",
}
tool_msg = tool.invoke(model_generated_tool_call)

# 内容是 JSON 字符串格式的结果
print(tool_msg.content[:400])
{"query": "euro 2024 host nation", "follow_up_questions": null, "answer": null, "images": [], "results": [{"title": "UEFA Euro 2024 - Wikipedia", "url": "https://en.wikipedia.org/wiki/UEFA_Euro_2024", "content": "Tournament details Host country Germany Dates 14 June – 14 July Teams 24 Venue(s) 10 (in 10 host cities) Final positions Champions Spain (4th title) Runners-up England Tournament statisti

在智能体中使用

我们可以通过将工具绑定到智能体,直接在智能体执行器中使用工具。这使智能体能够动态设置 Tavily 搜索工具的可用参数。 在下面的示例中,当我们要求智能体查找”2024 年欧洲杯举办国?仅包含维基百科来源。“时,智能体将动态设置参数并调用 Tavily 搜索工具:使用 {'query': 'Euro 2024 host nation', 'include_domains': ['wikipedia.org']} 调用 tavily_search
if not os.environ.get("OPENAI_API_KEY"):
    os.environ["OPENAI_API_KEY"] = getpass.getpass("OPENAI_API_KEY:\n")
# | output: false
# | echo: false

# !pip install -qU langchain langchain-openai
from langchain.chat_models import init_chat_model

model = init_chat_model(model="gpt-4.1", model_provider="openai", temperature=0)
我们还需要安装 LangGraph:
pip install -qU langgraph
from langchain_tavily import TavilySearch
from langchain.agents import create_agent


# 初始化 Tavily 搜索工具
tavily_search_tool = TavilySearch(
    max_results=5,
    topic="general",
)

agent = create_agent(model, [tavily_search_tool])

user_input = "What nation hosted the Euro 2024? Include only wikipedia sources."

for step in agent.stream(
    {"messages": user_input},
    stream_mode="values",
):
    step["messages"][-1].pretty_print()
================================ Human Message =================================

What nation hosted the Euro 2024? Include only wikipedia sources.
================================== Ai Message ==================================
Tool Calls:
  tavily_search (call_yxmR4K2uadsQ8LKoyi8JyoLD)
 Call ID: call_yxmR4K2uadsQ8LKoyi8JyoLD
  Args:
    query: Euro 2024 host nation
    include_domains: ['wikipedia.org']
================================= Tool Message =================================
Name: tavily_search

{"query": "Euro 2024 host nation", "follow_up_questions": null, "answer": null, "images": [], "results": [{"title": "UEFA Euro 2024 - Wikipedia", "url": "https://en.wikipedia.org/wiki/UEFA_Euro_2024", "content": "Tournament details Host country Germany Dates 14 June – 14 July Teams 24 Venue(s) 10 (in 10 host cities) Final positions Champions Spain (4th title) Runners-up England Tournament statistics Matches played 51 Goals scored 117 (2.29 per match) Attendance 2,681,288 (52,574 per match) Top scorer(s) Harry Kane Georges Mikautadze Jamal Musiala Cody Gakpo Ivan Schranz Dani Olmo (3 goals each) Best player(s) Rodri Best young player Lamine Yamal ← 2020 2028 → The 2024 UEFA European Football Championship, commonly referred to as UEFA Euro 2024 (stylised as UEFA EURO 2024) or simply Euro 2024, was the 17th UEFA European Championship, the quadrennial international football championship organised by UEFA for the European men's national teams of their member associations. Germany hosted the tournament, which took place from 14 June to 14 July 2024. The tournament involved 24 teams, with Georgia making their European Championship debut. [4] Host nation Germany were eliminated by Spain in the quarter-finals; Spain went on to win the tournament for a record fourth time after defeating England 2–1 in the final.", "score": 0.9104262, "raw_content": null}, {"title": "UEFA Euro 2024 - Simple English Wikipedia, the free encyclopedia", "url": "https://simple.wikipedia.org/wiki/UEFA_Euro_2024", "content": "The 2024 UEFA European Football Championship, also known as UEFA Euro 2024 or simply Euro 2024, was the 17th edition of the UEFA European Championship. Germany was hosting the tournament. ... The UEFA Executive Committee voted for the host in a secret ballot, with only a simple majority (more than half of the valid votes) required to determine", "score": 0.81418616, "raw_content": null}, {"title": "Championnat d'Europe de football 2024 — Wikipédia", "url": "https://fr.wikipedia.org/wiki/Championnat_d'Europe_de_football_2024", "content": "Le Championnat d'Europe de l'UEFA de football 2024 est la 17 e édition du Championnat d'Europe de football, communément abrégé en Euro 2024, compétition organisée par l'UEFA et rassemblant les meilleures équipes nationales masculines européennes. L'Allemagne est désignée pays organisateur de la compétition le 27 septembre 2018. C'est la troisième fois que des matches du Championnat", "score": 0.8055255, "raw_content": null}, {"title": "UEFA Euro 2024 bids - Wikipedia", "url": "https://en.wikipedia.org/wiki/UEFA_Euro_2024_bids", "content": "The bidding process of UEFA Euro 2024 ended on 27 September 2018 in Nyon, Switzerland, when Germany was announced to be the host. [1] Two bids came before the deadline, 3 March 2017, which were Germany and Turkey as single bids. ... Press agencies revealed on 24 October 2013, that the European football governing body UEFA would have decided on", "score": 0.7882741, "raw_content": null}, {"title": "2024 UEFA European Under-19 Championship - Wikipedia", "url": "https://en.wikipedia.org/wiki/2024_UEFA_European_Under-19_Championship", "content": "The 2024 UEFA European Under-19 Championship (also known as UEFA Under-19 Euro 2024) was the 21st edition of the UEFA European Under-19 Championship (71st edition if the Under-18 and Junior eras are included), the annual international youth football championship organised by UEFA for the men's under-19 national teams of Europe. Northern Ireland hosted the tournament from 15 to 28 July 2024.", "score": 0.7783298, "raw_content": null}], "response_time": 1.67}
================================== Ai Message ==================================

The nation that hosted Euro 2024 was Germany. You can find more information on the [Wikipedia page for UEFA Euro 2024](https://en.wikipedia.org/wiki/UEFA_Euro_2024).

API 参考

有关 Tavily 搜索 API 所有功能和配置的详细文档,请访问 API 参考:docs.tavily.com/documentation/api-reference/endpoint/search