Generative AIby Dhruv Narang

Tavily is a ready-made web search tool. The model asks for a search, we run it, and the results go back into a slot in the prompt.

What is web search? A model knows only what it learned before its cutoff date. A web search tool searches the internet right now, and gives the model the text of the best pages.
Can we make our own search tool? Yes, but it is a big job. It must find the pages on the internet, read them, clean the text, and pick the best parts for the question. You will learn the pieces for this later, in the RAG unit.
What Tavily does. It does all of this in one call. For each result it gives only the useful part. In our test each result was between 653 and 3,445 characters.
The rule. If the data comes from one simple API, write your own tool, like the crypto price tool. If the job is big, like searching the web, use a ready-made tool.
Get your free key. Tavily is a web service, so it needs a key. It is free to start.
StepWhat to do
1Go to app.tavily.com and sign up
2The free plan gives you 1,000 credits every month. A basic search uses 1 credit, an advanced search uses 2. No credit card is needed.
3Open the dashboard and copy your API key. It starts with tvly-
4Paste it in your .env file, as shown below
5Install the package: langchain-tavily
TAVILY_API_KEY=tvly-your-key-here
Your key is private. Do not share it, and do not put the .env file on GitHub. The code reads the key by itself from .env. You do not write it in the code.
from langchain_tavily import TavilySearch

web_search_tool = TavilySearch(max_results=2)
tools = [web_search_tool]
tools_by_name = {t.name: t for t in tools}
It is already a tool. Before, we made our own tools with @tool. TavilySearch is already a tool, made by LangChain. So we do not write @tool here. It has a name, tavily_search, and arguments, like our own tools.
max_results. This is a setting. We give it when we create the tool. It says how many search results to bring back. max_results=2 gives two results. A bigger number gives the model more text to read.
What do we send? Like our own tools, the model sends arguments. The main one is query: the words to search for. The other arguments are optional.
ArgumentWhat it does
querythe words to search for. Always needed.
topicthe kind of search, like news
time_rangeonly results from the last day, week, month or year
include_domainssearch only on these websites
Call it yourself. A tool is run with .invoke(). The input is a dictionary with the arguments. The model does this for us, but we can also do it by hand.
result = web_search_tool.invoke({"query": "latest news about ISRO"})
print(result["results"][0]["title"])
What the tool returns. A dictionary. The part you need is results, a list. Each result has a title, a url and some content. max_results=2 asks for only two results.
A tool name. The model asks for the tool by the name tavily_search. It is in the dictionary tools_by_name like your own tools, so the same lookup works.
The prompt has a slot. The tool call and its result must go back to the model. We keep a slot for them in the prompt, MessagesPlaceholder, the same idea as chat history. The first time the slot is empty. The second time it holds the tool call and the tool result.
The rest is the same. bind_tools and the prompt and model joined with the pipe are the same as before. You can see all of it in the Code tab below.
The flow. It is the same three steps as before. Only the tool is different.
flowchart LR
  Q(["Question"]) --> M1["Model<br/>asks for a search"] --> T["We run<br/>Tavily"] --> S["Results go in the<br/>tool_messages slot"] --> M2["Model writes<br/>the answer"] --> A(["Final answer"])
  class Q,A term
  class M1,M2 step
  class T fn
  class S slot
classDef term fill:#0e3b3a,stroke:#0e3b3a,color:#ffffff,font-weight:bold
classDef step fill:#d4ecea,stroke:#2a7a79,color:#0e3b3a
classDef fn fill:#fbe5dc,stroke:#c9583a,color:#7a2e1a
classDef slot fill:#e3f5ee,stroke:#4aa58a,color:#14463a
StepExample
The questionWhat are the latest key features announced in Python 3.13 or 3.14?
The model asksfor the tool tavily_search, with a search query about Python 3.13
The tool returnstitles and links, like What's New In Python 3.13 from docs.python.org
The final answerPython 3.13 adds a better interactive interpreter, an experimental free-threaded mode without the GIL, and an experimental JIT compiler.
Example output. Your run will show different search results. You need your own free Tavily key.

Code
Tool calling with Tavily web search02_tool_calling_tavily.py · 86 linesShow code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import os
from dotenv import load_dotenv
load_dotenv()

from langchain.chat_models import init_chat_model
from langchain_tavily import TavilySearch
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.messages import ToolMessage


# ====================================================================
# 1. DEFINE TOOLS & REGISTRY
# ====================================================================
web_search_tool = TavilySearch(max_results=2)
tools = [web_search_tool]
tools_by_name = {t.name: t for t in tools}


# ====================================================================
# 2. DEFINE SYSTEM PROMPT TEMPLATE (Using MessagesPlaceholder)
# ====================================================================
prompt_template = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful AI research assistant with access to live internet search tools. Answer accurately based on verified search facts."),
    ("human", "{question}"),
    MessagesPlaceholder("tool_messages", optional=True)  # Dynamic slot for Tool Calls & Tool Results
])



# ====================================================================
# 3. BIND TOOLS TO LLM & CREATE FIRST CHAIN
# ====================================================================
llm = init_chat_model("groq:openai/gpt-oss-20b")
llm_with_tools = llm.bind_tools(tools)

# LCEL Chain: Formats Prompt -> Sends to Model with Tools
chain = prompt_template | llm_with_tools


# ====================================================================
# 4. STEP 1: ASK QUESTION (Chain formats prompt & model decides)
# ====================================================================
user_question = "What are the latest key features announced in Python 3.13 or 3.14?"

# Invoke initial chain
ai_response = chain.invoke({
    "question": user_question,
    "tool_messages": []
})

print(f"User Question: {user_question}\n")
print("1. LLM Tool Decision:", ai_response.tool_calls)


# ====================================================================
# 5. STEP 2: EXECUTE REQUESTED TOOL
# ====================================================================
tool_messages_history = [ai_response]

if ai_response.tool_calls:
    for tool_call in ai_response.tool_calls:
        # Dynamic Dictionary Dispatch
        selected_tool = tools_by_name[tool_call["name"]]
        tool_output = selected_tool.invoke(tool_call["args"])
        
        # Create ToolMessage
        tool_messages_history.append(
            ToolMessage(
                content=str(tool_output),
                tool_call_id=tool_call["id"]
            )
        )
    print("\n2. Tavily Tool Executed Successfully!")


# ====================================================================
# 6. STEP 3: FINAL GROUNDED ANSWER VIA PROMPT TEMPLATE
# ====================================================================
# Re-invoke chain with populated tool messages!
final_response = chain.invoke({
    "question": user_question,
    "tool_messages": tool_messages_history
})

print("\n3. Final Grounded Answer from LLM:")
print(final_response.content)