Skip to main content
Open In ColabOpen on GitHub

Tavily 搜索

Tavily的Search API 是专门为AI代理(大型语言模型)构建的搜索引擎,提供实时、准确和可靠的结果。

概览

集成细节

Class序列化JS支持Package 最新版本
TavilySearchlangchain-tavilyPyPI - Version

Tool features

返回 artifacts原生异步Return Data定价
title, URL, content snippet, raw_content, answer, images1,000 free searches / month

设置

The integration lives in the langchain-tavily package.

%pip install -qU langchain-tavily

Credentials

我们还需要设置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")

Instantiation

Here we show how to instantiate an instance of the Tavily search tool. The tool accepts various parameters to customize the search. After instantiation we invoke the tool with a simple query. This tool allows you to complete search queries using Tavily's Search API endpoint.

实例化 该工具在初始化时接受多种参数:

  • max_results(可选,int): 返回的最大搜索结果数量。默认值为5。
  • topic (可选,str):搜索的类别。可以是“通用”、“新闻”或“财经”。默认为“通用”。
  • include_answer (可选,bool):在结果中包含原始查询的答案。默认值为 False。
  • include_raw_content(可选,bool): 包含每个搜索结果的清理和解析后的HTML内容。默认为False。
  • include_images(可选,bool): 在响应中包含与查询相关的图片列表。默认为False。
  • include_image_descriptions (可选,bool):为每个图片添加描述性文本。默认值为False。
  • search_depth(可选,str): 搜索深度,可以是"基本"或"高级"。默认为"基本"。
  • time_range (可选,str): 用于过滤结果的时间范围,从当前日期回溯——可以是"day", "week", "month", 或 "year"。默认值为 None。
  • include_domains(可选,List[str]): 特定包含的域名列表。默认值为None。
  • exlude_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
)

Invocation

使用参数直接调用

The Tavily 搜索工具在调用时接受以下参数:

  • query (必需): 一个自然语言搜索查询
  • The following arguments can also be set during invocation : include_images, search_depth , time_range, include_domains, exclude_domains, include_images
  • 由于可靠性及性能的原因,在调用时无法修改影响响应大小的某些参数:include_answerinclude_raw_content。这些限制防止了意外的上下文窗口问题,并确保了一致的结果。

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

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

使用工具调用启动

我们也可以通过模型生成的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搜索工具有效参数的能力。

在下面的示例中,当我们询问代理查找 "Euro 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()
================================ 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