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 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.
Instantiation The tool accepts various parameters during instantiation:
- max_results (optional, int): Maximum number of search results to return. Default is 5.
- topic (optional, str): Category of the search. Can be "general", "news", or "finance". Default is "general".
- include_answer (optional, bool): Include an answer to original query in results. Default is False.
- include_raw_content (optional, bool): Include cleaned and parsed HTML of each search result. Default is False.
- include_images (optional, bool): Include a list of query related images in the response. Default is False.
- include_image_descriptions (optional, bool): Include descriptive text for each image. Default is False.
- search_depth (optional, str): Depth of the search, either "basic" or "advanced". Default is "basic".
- time_range (optional, str): The time range back from the current date to filter results - "day", "week", "month", or "year". Default is None.
- include_domains (optional, List[str]): List of domains to specifically include. Default is None.
- exclude_domains (optional, List[str]): List of domains to specifically exclude. Default is None.
For a comprehensive overview of the available parameters, refer to the Tavily Search API documentation
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 invocation :
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 an argument during instantiation and then invoke the tool with a different value, the tool will use the value you passed during invocation.
tool.invoke({"query": "What happened at the last wimbledon"})
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