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?"
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.
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.
Tavily is a search service optimized for LLM/Agent scenarios. Compared with crawling web pages directly, it has several key advantages:
| characteristic | Tavily | Crawl 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 |
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.
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:
query: str: Search keywords. The Agent will automatically generate appropriate query terms based on the user's questions.search_depth="basic": Quick search (suitable for most scenarios); change to"advanced"Will go deeper but slowerresults、query、answeretc fieldsIn 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.
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})
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).
# 给 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)
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.
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)
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)
| Field | meaning |
|---|---|
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) |
# 先独立测试 web_search,确认可以正常工作
web_results = web_search.invoke("Who is the current mayor of San Francisco?")
print(web_results['results'][0]['content']) # 第一条结果的内容
# 可以同时绑定多个工具
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."
)
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
TavilyClient()Automatically read API Keysearch_depth="basic"Quick application