Tavily Search
Tavily's Search API is a search engine built specifically for AI agents (LLMs), delivering real-time, accurate, and factual results at speed.
Overview
Integration details
Class | Package | Serializable | JS support | Package latest |
---|---|---|---|---|
TavilySearch | langchain-tavily | ❌ | ❌ |
Tool features
Returns artifact | Native async | Return data | Pricing |
---|---|---|---|
❌ | ✅ | title, URL, content snippet, raw_content, answer, images | 1,000 free searches / month |
Setup
The integration lives in the langchain-tavily
package.
%pip install -qU langchain-tavily
Credentials
We also need to set our Tavily API key. You can get an API key by visiting this site and creating an account.
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 tools, with
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
Invoke directly with args
The Tavily search tool accepts the following arguments during invocation:
query
(required): A natural language search query- The following arguments can also be set during invokation :
include_images
,search_depth
,time_range
,include_domains
,exclude_domains
,include_images
- For reliability and performance reasons, certain parameters that affect response size cannot be modified during invocation:
include_answer
andinclude_raw_content
. These limitations prevent unexpected context window issues and ensure consistent results.
NOTE: The optional arguments are available for agents to dynamically set, if you set a argument during instantiation and then invoke the tool with a different value, the tool will use the value you passed during invokation.
tool.invoke({"query": "What happened at the last wimbledon"})
{'query': 'What happened at the last wimbledon',
'follow_up_questions': None,
'answer': None,
'images': [],
'results': [{'title': "Andy Murray pulls out of the men's singles draw at his last Wimbledon",
'url': 'https://www.nbcnews.com/news/sports/andy-murray-wimbledon-tennis-singles-draw-rcna159912',
'content': "NBC News Now LONDON — Andy Murray, one of the last decade's most successful male tennis players, has pulled out of the singles tournament at what is almost certain to be his last Wimbledon, his team confirmed Tuesday. Murray, 37, who has won the Wimbledon singles title twice and the U.S Open once, has been battling to be fit to play at the All England Club for weeks. “Unfortunately, despite working incredibly hard on his recovery since his operation just over a week ago, Andy has taken the very difficult decision not to play the singles this year,” his team said in a statement reported by Sky News. The news caps a glittering career on the ATP singles tour, which placed Murray at No. 1 in the world for 41 weeks.",
'score': 0.67527276,
'raw_content': None},
{'title': 'Andy Murray brought to tears by emotional ceremony as Wimbledon ...',
'url': 'https://edition.cnn.com/2024/07/05/sport/andy-murray-wimbledon-farewell-ceremony-spt-intl/index.html',
'content': 'Andy Murray brought to tears by emotional ceremony as Wimbledon farewell begins with doubles defeat | CNN Football Tennis Golf Motorsport US Sports Olympics Climbing Esports Hockey CNN10 About CNN Andy Murray became emotional when speaking on court following his Wimbledon defeat on Thursday. It was an emotional night for three-time grand slam champion Andy Murray on Thursday, as the 37-year-old’s Wimbledon farewell began with doubles defeat. Following a doubles defeat alongside his brother Jamie on Thursday, Murray was moved to tears after a short ceremony on Centre Court in which a montage of his career played out on big screens. Murray watches on as a video montage of his career highlights plays on the big screens at Wimbledon. CNN10 About CNN',
'score': 0.43482184,
'raw_content': None},
{'title': 'Wimbledon - Latest News, Headlines and Entertainment from the BBC',
'url': 'https://www.bbc.co.uk/news/topics/c1kr68g26j9t',
'content': "Wimbledon - Latest News, Headlines and Entertainment from the BBC BBC Homepage Search BBC Close menu BBC News BBC Verify World News TV Weather for Wimbledon London London Disabled people share experience of accessible homes London Man's pop-up urinal death may never be explained, family fears London London London London London London London Met PC jailed for assaulting man in hospital bed London London London Man jumped to his death in police station - inquest London Central London YMCA closes after failed injunction Kerr denies 'whiteness as insult' against police Man denies being getaway driver in £1m watch raid About the BBC Contact the BBC BBC emails for you The BBC is not responsible for the content of external sites.",
'score': 0.3916624,
'raw_content': None},
{'title': 'Wimbledon - latest news, breaking stories and comment - The Independent',
'url': 'https://www.independent.co.uk/topic/wimbledon',
'content': "Independent Australian Open champion Jannik Sinner's style draws comparisons to Novak Djokovic Patten wins second grand slam doubles title after Australian Open epic Australian Open: Madison Keys can win her first Slam title and stop Aryna Sabalenka's threepeat Novak Djokovic hits back to beat Carlos Alcaraz in Australian Open thriller Australian Open 2025: Carlos Alcaraz and Jannik Sinner have a real rivalry atop men's tennis Australian Open 2025: Carlos Alcaraz and Jannik Sinner have a real rivalry atop men's tennis Australian Open 2025: Cases involving Jannik Sinner and Iga Swiatek make doping a top topic Australian Open 2025: There really isn't much time off in the offseason for tennis players Jd Sports Discount Code",
'score': 0.3539422,
'raw_content': None},
{'title': 'Novak Djokovic loses to Carlos Alcaraz Wimbledon final',
'url': 'https://www.wimbledon.com/en_GB/news/articles/2023-07-16/alcaraz_ends_the_djokovic_run.html',
'content': 'Password* By joining myWimbledon you are confirming you are happy to receive news and information from The All England Lawn Tennis Club regarding The Club, The Championships and The Grounds via email By joining myWimbledon you are confirming you are happy to receive news and information from The All England Lawn Tennis Club regarding The Club, The Championships and The Grounds via email Please enter your email address to update your password: We have sent details on how to update your password to the email address you provided. A verification email with a link to verify your account has been sent to you. Please enter the code sent to your email address below and click SUBMIT to complete the verification.',
'score': 0.23453853,
'raw_content': None}],
'response_time': 1.43}
Invoke with ToolCall
We can also invoke the tool with a model-generated ToolCall, in which case a ToolMessage will be returned:
# 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
Use within an agent
We can use our tools directly with an agent executor by binding the tool to the agent. This gives the agent the ability to dynamically set the available arguments to the Tavily search tool.
In the below example when we ask the agent to find "What nation hosted the Euro 2024? Include only wikipedia sources." the agent will dynamically set the argments and invoke Tavily search tool : Invoking tavily_search
with {'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")
We will need to install 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()
================================[1m Human Message [0m=================================
What nation hosted the Euro 2024? Include only wikipedia sources.
==================================[1m Ai Message [0m==================================
Tool Calls:
tavily_search (call_yxmR4K2uadsQ8LKoyi8JyoLD)
Call ID: call_yxmR4K2uadsQ8LKoyi8JyoLD
Args:
query: Euro 2024 host nation
include_domains: ['wikipedia.org']
=================================[1m Tool Message [0m=================================
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}
==================================[1m Ai Message [0m==================================
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 reference
For detailed documentation of all Tavily Search API features and configurations head to the API reference: https://docs.tavily.com/documentation/api-reference/endpoint/search
Related
- Tool conceptual guide
- Tool how-to guides