LangChain LangGraph
Module 1 Module 2 Module 3
Module 1 · Basic abilities
1 1.1a Foundation Model
2 1.1b Prompting
3 1.2a Tools
4 1.2b Web Search
5 1.3 Memory
6 1.4 Multimodal
7 1.5 Personal Chef
SUM Module Summary
HomeLangChainModule 1 · Basic abilities1.2b Web Search
📓 Notebook 📖 Explained
LANGCHAIN MODULE 1 · LESSON 1.2b

Web Search Tool
Tavily · Real-time Networking · Information Retrieval Agent

LLM knowledge has an expiration date. Through the Tavily search tool, Agent can retrieve web content in real time, allowing the model to answer questions based on the latest information - "Who is the principal of XX?" "What is the stock price today?"

1Why do you need a web search? Fundamental Limitations of LLM Knowledge Cutoff

All LLMs have a fundamental limitation:Training data has a deadline (Knowledge Cutoff). GPT-4, DeepSeek, Claude - they only know the knowledge in the training set and cannot know new events and new data that occur after training.

For this type of question, relying solely on LLM will yield answers that may be out of date or wrong.Web search toolsSolve this problem - it allows the Agent to "go out and look it up" during reasoning and bring back the latest information.

Real-time version of Retrieval Augmented Generation (RAG)

Web search tools are essentiallyReal-time RAG (Retrieval-Augmented Generation)A form of: first retrieve (Retrieve) relevant content, and then let the model generate (Generate) answers based on the retrieval results. The difference is: RAG is usually retrieved from a private knowledge base, while web search is retrieved from the public Internet.

2Tavily: Search API designed for AI Agents

Tavily is a search service optimized for LLM/Agent scenarios. Compared with crawling web pages directly, it has several key advantages:

characteristicTavilyCrawl the web yourself
Return format Clean JSON with URL, title, content summary Raw HTML, needs to be parsed and cleaned
Content quality Intelligent filtering to filter out ads and irrelevant content Contains a lot of noise
Search depth supportbasicandadvancedTwo gears Need to implement deep search yourself
Integration difficulty One line of code directly returns the content available to LLM Need to deal with robots.txt, current limiting, encoding and other issues
Get Tavily API Key

existtavily.comRegister to get a free API Key (with monthly quota) and set it as an environment variableTAVILY_API_KEY, TavilyClient will automatically read it.

3Define web_search tool: @tool + TavilyClient

from langchain.tools import tool
from typing import Dict, Any
from tavily import TavilyClient

tavily_client = TavilyClient()  # 自动读取 TAVILY_API_KEY 环境变量

@tool("web_search", description="Search web")
def web_search(query: str) -> Dict[str, any]:
    return tavily_client.search(query, search_depth="basic")

Key parameters of this tool:

description should be descriptive enough

In the above codedescription="Search web"Very brief. In actual projects, it is recommended to write in more detail, for example:"Search the web for real-time information. Use when you need current data, recent events, or facts that may have changed after your training cutoff."This way the model can more accurately determine when to call.

4Without search tools: Demonstration of the limitations of LLM

Build one firstno toolsA common Agent to see how it answers real-time questions:

agent_no_tools = create_agent(model=deepseek_model())

question = {
    "role": "user",
    "content": "Who is the principal of Birralee Primary School?"
}

response = agent_no_tools.invoke({"messages": question})
Toolless Agent's answer (unreliable)
I don't have specific information about the current principal of Birralee Primary School. School leadership can change over time, and I may not have up-to-date information. I recommend checking the school's official website or contacting the school directly for accurate information.

The model honestly admits not knowing – which is the best case scenario. A worse case scenario is that the modelConfidently give a wrong answer(hallucination).

5After binding the search tool: answer real questions in real time

Scenario 1: Find the school principal

# 给 Agent 绑定 web_search 工具
agent = create_agent(
    deepseek_model(),
    tools=[web_search]
)

question = {
    "role": "user",
    "content": "Who is the principal of Birralee Primary School?"
}

response = agent.invoke({"messages": question})
print(response['messages'][-1].content)
Answers from tool Agent (from real web pages)
The principal of Birralee Primary School is **Ashley Ryan**.

The model is called this timeweb_search("Birralee Primary School principal"), I found the answer from real web pages instead of making it up out of thin air.

Scenario 2: Find mayor information

agent = create_agent(
    model=deepseek_model(),
    tools=[web_search]
)

question = HumanMessage(content="Who is the current mayor of San Francisco?")
response = agent.invoke({"messages": [question]})
print(response['messages'][-1].content)
Execution output (from live web)
Based on the search results, the current mayor of San Francisco is **Daniel Lurie**, who took office in January 2025...

6Parsing search results: JSON data in ToolMessage

Tavily returns a JSON string, encapsulated asToolMessage.content. If you need to extract specific information from the search results, you can parse this JSON:

import json

# messages[2] 是 ToolMessage(工具执行结果)
content = response['messages'][2].content
data = json.loads(content)   # 字符串 → dict

from pprint import pprint
pprint(data)
The JSON structure returned by Tavily
{
  "query": "Who is the current mayor of San Francisco?",
  "results": [
    {
      "url": "https://sfmayor.org/...",
      "title": "Mayor Daniel Lurie - City and County of San Francisco",
      "content": "Daniel Lurie is the 46th Mayor of San Francisco...",
      "score": 0.9521
    },
    { ... }, // more results
  ],
  "response_time": 0.87
}

Key fields for Tavily search results

Fieldmeaning
query Actual search query terms executed
results Search result list, each item includes url, title, content, score
results[i].content Web page summary content (cleaned, suitable for LLM reading)
results[i].score Relevance score (0-1), the higher the more relevant
answer Direct answers automatically generated by Tavily (not always available)
response_time Search time (seconds)

7Advanced usage and precautions for search tools

Test the tool independently first, then bind the Agent

# 先独立测试 web_search,确认可以正常工作
web_results = web_search.invoke("Who is the current mayor of San Francisco?")
print(web_results['results'][0]['content'])  # 第一条结果的内容

Complete tool list example

# 可以同时绑定多个工具
agent = create_agent(
    model=deepseek_model(),
    tools=[web_search, square_root, another_tool],
    system_prompt="You have access to web search and math tools. Use them when needed."
)
Potential issues with search tools

Things to note when using web search tools:
cost: Tavily has API call fees, and high-frequency calls require monitoring of usage.
Delay: Web searches increase response time (usually 1-3 seconds)
information quality: Search results may contain incorrect or biased web content, and the model needs to determine credibility
Infinite loop risk: If the system prompt is not designed properly, the model may search infinitely. LangGraph Agent has a built-in maximum step limit

Lesson 1.2b Core Points
Tavily search tool
  • TavilyClient()Automatically read API Key
  • • Returns clean JSON containing a list of results
  • search_depth="basic"Quick application
real-time information capabilities
  • • Break LLM knowledge deadline limits
  • • Agent automatically decides when to search
  • • ToolMessage saves search results