Tavily 的搜索 API 是一个专为 AI 代理(LLM)构建的搜索引擎,提供实时、准确和真实的结果,速度极快。
概述
集成详情
| 类 | 包 | 可序列化 | JS 支持 | 版本 |
|---|---|---|---|---|
TavilySearch | langchain-tavily | ✅ | ✅ | !PyPI - 版本 |
工具特性
| 返回产物 | 原生异步 | 返回数据 | 定价 |
|---|---|---|---|
| ❌ | ✅ | 标题、URL、内容片段、原始内容_content, answer, images | 1,000 free searches / month |
设置
该集成位于 langchain-tavily package.
pip install -qU langchain-tavily
凭证
我们还需要设置我们的 Tavily API 密钥。您可以通过访问 此网站 并创建一个账户来获取 API 密钥。
if not os.environ.get("TAVILY_API_KEY"):
os.environ["TAVILY_API_KEY"] = getpass.getpass("Tavily API key:\n")
实例化
这里我们展示如何实例化 Tavily 搜索工具。该工具在实例化时接受各种参数:
- - max_results(可选,整数):返回的最大搜索结果数量。默认值为 5。
- - topic(可选,字符串):搜索类别。可以是 "general"、"news" 或 "finance"。默认值为 "general"。
- - include_answer(可选,布尔值):在结果中包含对原始查询的回答。默认值为 False。
- - include_raw_content(可选,布尔值):包含每个搜索结果的清理和解析后的 HTML。默认值为 False。
- - include_images(可选,布尔值):在响应中包含与查询相关的图片列表。默认值为 False。
- - include_image_descriptions(可选,布尔值):为每张图片包含描述性文本。默认值为 False。
- - search_depth(可选,字符串):搜索深度,可以是 "basic" 或 "advanced"。默认值为 "basic"。
- - time_range(可选,字符串):从当前日期往回的时间范围,用于过滤结果 - "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_images,search_depth,time_range,include_domains,exclude_domains - - 出于可靠性和性能原因,某些影响响应大小的参数无法在调用期间修改:
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
在代理中使用
我们可以通过将工具绑定到代理来直接与代理执行器一起使用我们的工具。这使代理能够动态设置 Tavily 搜索工具的可用参数。
在下面的示例中,当我们要求代理查找"哪个国家举办了 2024 年欧洲杯?仅包含维基百科来源。"时,代理将动态设置参数并调用 Tavily 搜索工具:调用 tavily_search 使用 {'query': 'Euro 2024 host nation', 'include_domains': ['wikipedia.org']
if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("OPENAI_API_KEY:\n")
from langchain.chat_models import init_chat_model
model = init_chat_model(model="gpt-5.5", model_provider="openai", temperature=0)
我们需要安装 langgraph:
pip install -qU langgraph
from langchain_tavily import TavilySearch
from langchain.agents import create_agent
# Initialize Tavily Search Tool
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."
stream = agent.stream_events({"messages": user_input}, version="v3")
for snapshot in stream.values:
snapshot["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 参考: docs.tavily.com/documentation/api-reference/endpoint/search