How to use an AI agent to search the web (Research, version 2)?
A web search is a service. You send Tavily a question, and it sends back ten results. Each result carries a title, a link, a short piece of the page, and a score that says how well the page matches the question.
In this version the search is a tool, and an agent decides to use it. Our code no longer calls Tavily itself. It hands the tool to a model, the model reads the question and chooses the tool, and Python runs it. The ten results come back exactly as the search service produced them.
The search becomes a tool
@tool(return_direct=True)
def search_internet(query: str):
"""
Search the internet for up-to-date information about the query
and return the full Tavily search response.
"""
response = tavily_client.search(query, max_results=10)
return response
@tool turns an ordinary function into something a model can
call. The sentence inside the triple quotes — the
docstring — is not decoration: it is what the model
reads when deciding whether this tool fits the request, and what it expects
back.
The body is one search: one call, ten results, each with a
title, url, content and
score.
Why the tool ends the run
@tool(return_direct=True)
return_direct=True means: when this tool answers, that answer
is the agent's final answer. The model does not write a reply after it.
The instructions: do not reword the question
agent = create_agent(
model=model,
tools=[search_internet],
system_prompt=(
"You are a helpful assistant. "
"Always call search_internet, using the user's message exactly as the query. "
"Do not rephrase, shorten, translate, or add anything to it."
),
)
The system prompt is read before the task. Here it does two jobs. It tells the model to call the one tool, and it tells the model not to touch the question on the way.
The second rule matters more than it looks. Search engines match words, so "What is the population of Hong Kong?" and "Hong Kong population" return different lists, and a helpful model will happily rewrite a question into something it thinks is clearer. Since we want to compare this series version by version, the question must go through as typed.
Running the agent
prompt = "What is the population of Hong Kong?"
result = agent.invoke({
"messages": [{"role": "user", "content": prompt}]
})
An agent does not take a sentence. It takes a list of messages, each with a
role, and here there is one: "user". .invoke()
runs the whole loop — the model reads the question, decides to call
search_internet, Python runs that function, and the result goes
back into the conversation. result keeps every message from
the run, not just the answer.
Reading the answer back
for message in result["messages"]:
if message.type == "tool":
response = json.loads(message.content)
The run holds three kinds of message: our question, the model's request to
call the tool, and the tool's result. The screen should show only the third
one, so the loop skips the other two with
message.type == "tool".
We need json.loads(message.content) for one reason. Tavily's
dictionary is written out in JSON inside message.content, and to
Python that is one long string. json.loads(message.content)
reads the text and rebuilds the dictionaries that the rest of the code can
use.
The printing lines are the same four as version 1, so version 1 explains them.
What comes out
Search result:
Query: What is the population of Hong Kong?
1. Hong Kong Population (2026) - Worldometer (score: 0.92)
https://www.worldometers.info/world-population/china-hong-kong-sar-population
The current population of the Hong Kong Special Administrative Region of the People's Republic of China is 7,371,564 as of Sunday, October 18, 2026, based on Worldometer's elaboration of the latest Un...
2. Hong Kong Population 2026 (score: 0.94)
https://worldpopulationreview.com/countries/hong-kong
### Request Data Please enter your email address to receive this data in your inbox. ## Hong Kong By the Numbers As of 2026, Hong Kong has a total populationof 7,378,602, ranking as the 107th most...
3. Hong Kong Map, History & Population | Study.com (score: 0.93)
https://study.com/academy/lesson/hong-kong-facts-population.html
The population of Hong Kong is 7.5 million. Two million people live in Kowloon, the southern part of the peninsula, and 1 million people live in the northern part of Hong Kong Island, called Victoria ...
...
No summary, no "based on the search results, the population is about 7.4 million". Ten results, exactly as Tavily returned them. The agent changed who made the request, not what came back.
The whole program
# RESEARCH, version 2: an AI agent does the search from version 1.
# The same Tavily call becomes a TOOL, and the agent decides to call it.
# return_direct=True means the tool's answer IS the final answer: the model
# does not summarise the results afterwards.
import os
import json
from dotenv import load_dotenv
from tavily import TavilyClient
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
from langchain.agents import create_agent
load_dotenv()
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")
tavily_client = TavilyClient(api_key=TAVILY_API_KEY)
@tool(return_direct=True)
def search_internet(query: str):
"""
Search the internet for up-to-date information about the query
and return the full Tavily search response.
"""
response = tavily_client.search(query, max_results=10)
return response
model = ChatOpenAI(
model="deepseek-flash",
api_key=DEEPSEEK_API_KEY,
base_url="https://api.deepseek.com",
temperature=0,
)
agent = create_agent(
model=model,
tools=[search_internet],
system_prompt=(
"You are a helpful assistant. "
"Always call search_internet, using the user's message exactly as the query. "
"Do not rephrase, shorten, translate, or add anything to it."
),
)
prompt = "What is the population of Hong Kong?"
result = agent.invoke({
"messages": [{"role": "user", "content": prompt}]
})
for message in result["messages"]:
if message.type == "tool":
response = json.loads(message.content)
print("Search result:")
print(f"Query: {response['query']}\n")
for i, r in enumerate(response["results"], start=1):
print(f"{i}. {r['title']} (score: {r['score']:.2f})")
print(f" {r['url']}")
print(f" {r['content'][:200].replace(chr(10), ' ')}...\n")
Running it on your own computer
Download the demo program
(Folder-AI-Research02.zip). The zip holds three files:
research02.py (the full script), pyproject.toml and
README.md. This version calls a language model once, so it
needs both a Tavily key and a DeepSeek key.
- Open the folder in Visual Studio Code.
-
Create a file named
.envin the folder with two lines:
A Tavily key is available from the Tavily dashboard, and a DeepSeek key from the DeepSeek console. Usage is billed by each provider, so check the current pricing terms there before you run it.TAVILY_API_KEY=your-tavily-key DEEPSEEK_API_KEY=your-deepseek-key - In the Terminal, run these three lines, one at a time:
uv python pin 3.12.10uv syncuv run research02.py - You should see the same ten results as version 1. One model call takes a few seconds.
If you have not set up uv yet, start with How to install Visual Studio Code? and then the uv note for Windows or Mac.
Limitations
- The agent adds a step, not an answer. The ten results are the same ten results. What is new is only that a model chose the tool, and that we can add more tools next.
-
The model can still reword. The instructions say to use
the question exactly, and
temperature=0makes the model steady, but a model can still depart from an instruction. Check that the query printed on screen is the one you typed. - Scores are relevance, not truth. The same caveat as version 1: a high score means the page matches the words, not that the page is right or current.
- Nothing is filtered. Ten results arrive and ten are printed, including the 0.11 one that barely mentions the population.
Further reading
- How to search the web from Python (Research, version 1)? — the search itself, with no agent.
- How to use LangChain in an AI agent (ReAct, version 7)? — where
create_agentfirst appeared. - LangChain documentation — tools,
create_agentandreturn_direct. - Tavily documentation — the
searchcall and its response fields.