Skip to main content
Open In Colab在 GitHub 上打开

Tavily 搜索

Tavily 的搜索 API 是专为 AI 代理 (LLM) 构建的搜索引擎,可快速提供实时、准确和真实的结果。

概述

集成详细信息

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

工具特点

返回 artifact本机异步返回数据定价
title, URL, content snippet, raw_content, answer, images1,000 free searches / month

设置

集成位于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
)

调用

使用 args 直接调用

Tavily 搜索工具在调用期间接受以下参数:

  • query(必需):自然语言搜索查询
  • 还可以在调用期间设置以下参数:include_images,search_depth,time_range,include_domains,exclude_domains,include_images
  • 出于可靠性和性能原因,在调用期间无法修改影响响应大小的某些参数:include_answerinclude_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

在代理内使用

通过将工具绑定到代理,我们可以直接与代理执行程序一起使用我们的工具。这使代理能够动态地将可用参数设置为 Tavily 搜索工具。

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

pip install -qU "langchain[openai]"
import getpass
import os

if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ")

from langchain.chat_models import init_chat_model

llm = init_chat_model("gpt-4o-mini", model_provider="openai")
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 参考: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