Skip to main content
Open In ColabOpen on GitHub

Tavily 搜索

Tavily 的 Search API 是一个专为 AI 代理 (LLMs) 构建的搜索引擎,能够快速提供实时、准确、事实性的结果。

概览

集成详情

可序列化JS 支持最新包
TavilySearchlangchain-tavilyPyPI - Version

工具特色

返回工件原生异步返回数据定价
title, URL, content snippet, raw_content, answer, images每月 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 的 Search 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 Search 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_answer”和“include_raw_content”。这些限制可以防止意外的上下文窗口问题并确保结果的一致性。

注意:可选参数供代理动态设置,如果您在实例化过程中设置了某个参数,然后在调用工具时使用不同的值,则该工具将使用您在调用过程中传递的值。

tool.invoke({"query": "What happened at the last wimbledon"})

使用 ToolCall 调用

我们也可以使用模型生成的 ToolCall 来调用工具,在这种情况下会返回一个 ToolMessage:

# This is usually generated by a model, but we'll create a tool call directly for demo purposes.
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)

# The content is a JSON string of results
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

在 Agent 中使用

我们可以通过将工具绑定到 Agent 来直接在 Agent Executor 中使用我们的工具。这使得 Agent 能够动态地为 Tavily 搜索工具设置可用参数。

在下面的示例中,当我们要求 Agent 查找“哪个国家主办了 2024 年欧洲杯?仅包括维基百科来源。”时,Agent 将动态设置参数并调用 Tavily 搜索工具:调用 tavily_search 并使用 {'query': 'Euro 2024 host nation', 'include_domains': ['wikipedia.org']

pip install -qU "langchain[google-genai]"
import getpass
import os

if not os.environ.get("GOOGLE_API_KEY"):
os.environ["GOOGLE_API_KEY"] = getpass.getpass("Enter API key for Google Gemini: ")

from langchain.chat_models import init_chat_model

llm = init_chat_model("gemini-2.0-flash", model_provider="google_genai")
if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("OPENAI_API_KEY:\n")

我们需要安装 langgraph:

%pip install -qU langgraph
from langchain_tavily import TavilySearch
from langgraph.prebuilt import create_react_agent

# Initialize Tavily Search Tool
tavily_search_tool = TavilySearch(
max_results=5,
topic="general",
)

agent = create_react_agent(llm, [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()
API Reference:create_react_agent
================================ 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 Search API 所有功能和配置的详细文档,请访问 API 参考:https://docs.tavily.com/documentation/api-reference/endpoint/search