How to give an LLM live Google results with tool calling
Checked on 2026-11-24.
A language model knows nothing after its training date, so for anything current it has to look things up. Tool calling is how: you describe a search function, the model asks for it with a query, and your code runs the search and sends back the results. Use the search tool your provider runs, or define your own; both are below, with code for Anthropic's Python SDK, and the same tool works with other providers.
1. The provider's own search tool
The shortest route is a search tool the provider runs. With Anthropic's API you add one entry to tools, and the model searches as often as it needs, then answers with citations, as its web search tool page shows.
# pip install anthropic
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
messages=[{"role": "user", "content": "What changed in the latest Python release?"}],
tools=[{"type": "web_search_20260318", "name": "web_search", "max_uses": 5}],
)
for block in response.content:
if block.type == "text":
print(block.text, end="")
for citation in block.citations or []:
print(f" [{citation.title}]({citation.url})", end="")max_uses caps the searches in one turn. A long search turn can end with stop_reason "pause_turn"; you send the reply back unchanged to let it continue. OpenAI's Responses API has the same idea as a tool of type web_search, and Gemini has Grounding with Google Search.
Where it stops:
- You get an answer, not your own result list. The model decides what to search and which results to use. Each of Anthropic's results shows a URL, a title and a page age, but its text comes as
encrypted_content, which you pass back in later turns and cannot read. - Whose search. Neither Anthropic's nor OpenAI's web search page names the search engine behind it. Only Gemini's grounding says it is Google.
- Price. Anthropic charges $10 per 1,000 searches plus tokens, and search results count as input tokens in later turns too. For Gemini 3 and newer models Google bills each search query the model runs: the first 5,000 a month are free, then $14 per 1,000.
- Display rules. Anthropic's page says citations must be shown when you show the output to end users; OpenAI's says "you must show inline citations as prominent, clickable links". Google's Gemini API terms go further for grounding: the grounded results are shown with their Search Suggestions only "to the end user who submitted the prompt", and you may not "cache, frame, syndicate, resell, analyze, train on, or otherwise learn from Grounded Results".
- An organization admin can turn Anthropic's web search off in the Console; requests that include it then fail with a 400.
2. Your own search tool: the definition
A tool you define is a name, a description and a JSON Schema for its input, as Anthropic's tool use overview shows. The description is what the model reads to decide when to call it, so say what it returns and when to use it. Here are two tools: one that searches Google, and one that reads a result, because a snippet is rarely enough to answer from.
# pip install anthropic requests
import os
import anthropic
import requests
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
TOOLS = [
{
"name": "search_google",
"description": (
"Search Google and return the first page of organic results: position, title, URL "
"and snippet of each. Use it for anything recent, or anything you are not sure of."
),
"input_schema": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "The search, as a person would type it into Google."},
"country": {"type": "string", "description": "Two-letter code of the country whose results you want, such as US or DE."},
},
"required": ["query"],
},
},
{
"name": "read_page",
"description": "Read one web page and return its content as Markdown. Read a result before you rely on it.",
"input_schema": {
"type": "object",
"properties": {"url": {"type": "string", "description": "The full address of the page."}},
"required": ["url"],
},
},
]The model only asks; your code runs the function. Behind these two are Pipefetch endpoints, Google search and page content; any search API with a JSON answer fits the same place.
def pipefetch(path: str, params: dict) -> dict | None:
res = requests.get(
f"https://pipefetch.com{path}",
params=params,
headers={"x-api-key": os.environ["PIPEFETCH_API_KEY"]},
timeout=90,
)
if res.status_code == 404:
return None # nothing found: not charged
res.raise_for_status() # a 502 is a refused search: not charged, and it can be sent again
return res.json()["data"]
def search_google(query: str, country: str = "US") -> str:
data = pipefetch("/v1/google/search", {"q": query, "country": country})
if data is None:
return "Google has no results for this search."
return "\n\n".join(
f"{r['position']}. {r['title']}\n{r['url']}\n{r['description'] or ''}"
for r in data["results"]
)
def read_page(url: str) -> str:
page = pipefetch("/v1/web/content", {"url": url})
if page is None:
return "This page could not be read: it does not exist, robots.txt closes it, or it is built in the browser."
return f"# {page['title'] or url}\n\n{page['content']}"A search returns the first page of Google's organic results, about 10, with position, title, url, domain, description and, when Google shows one, a date. Ads, AI Overview, People also ask and the other blocks of the full results page are not included, and there are no further pages. The page endpoint returns a page's content as Markdown without its menus; it does not run JavaScript.
3. The loop
When the model wants a tool, the response has stop_reason "tool_use" and one tool_use block per call, each with an id, a name and an input. Anthropic's handle tool calls page gives the steps: send the response's content back unchanged as an assistant message, then one user message with a tool_result for every tool_use block, even a failed one, and repeat until the model stops asking.
FUNCTIONS = {"search_google": search_google, "read_page": read_page}
def answer(question: str, max_rounds: int = 8) -> str:
messages = [{"role": "user", "content": question}]
for _ in range(max_rounds):
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
tools=TOOLS,
messages=messages,
)
if response.stop_reason == "refusal":
return "The model declined this request."
if response.stop_reason != "tool_use":
return "".join(block.text for block in response.content if block.type == "text")
# Send the reply back unchanged, then one tool_result for every tool_use block
messages.append({"role": "assistant", "content": response.content})
results = []
for block in response.content:
if block.type != "tool_use":
continue
try:
output = FUNCTIONS[block.name](**block.input)
results.append({"type": "tool_result", "tool_use_id": block.id, "content": output})
except Exception as error: # tell the model instead of ending the loop
results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": f"The tool failed: {error}. You may try once more.",
"is_error": True,
})
messages.append({"role": "user", "content": results})
return "Stopped: too many tool calls for one question."
print(answer("Search Google for 'best crm software' and compare what the first three results recommend."))Three details come from that page. A failure goes back with is_error set and a message that says what to try next; the model may call the tool again, hence max_rounds. All results of one turn go back in one message. And search results are text written by strangers: the page warns about instructions hidden in them ("indirect prompt injection") and advises keeping such content inside tool_result blocks, as the loop does. The SDK's tool runner can write this loop for you.
The same tool with other providers
The functions do not change; only the wrapper does. OpenAI's function calling takes {"type": "function", "name", "description", "parameters"}, where parameters is the same JSON Schema as input_schema above. The model returns function_call items, and you answer each with a function_call_output that carries its call_id. Gemini's function calling page describes the same name, description and parameters, with results sent back as function_result.
If your app speaks MCP
An assistant that already speaks the Model Context Protocol, such as Claude Code, Claude Desktop or Cursor, needs none of this code: add an MCP server and its tools appear. The MCP guide sets up one with a tool for every Pipefetch endpoint, Google search and page content among them. Anthropic's Messages API can also connect to a remote MCP server itself, through its MCP connector, without an MCP client of your own.
Which one should you use?
| You need | Use |
|---|---|
| Answers with sources, the least code, any search engine | Your provider's built-in search tool |
| Google's own results in a Gemini app, within Google's display terms | Grounding with Google Search |
| Google's ranked results as data your code sees, with any model | Your own tool on a search API such as Pipefetch |
| An assistant such as Claude Code or Cursor | An MCP server |
Google's own JSON search API is not on the list: its overview says "The Custom Search JSON API is closed to new customers", and existing customers have until January 1, 2027. The guide to Google results in Python covers what is left.
What one answer costs
Tool definitions are input tokens on every request, and Anthropic adds a tool-use system prompt of its own, 286 tokens for Claude Opus 5.5 according to its overview. Every tool result is input too, and it stays in the conversation, so a long page read in the first round is sent again, and billed as input, with every later request. On the Pipefetch side, a search or a page is 1 credit; a search without results, a refused search (502) and a page that cannot be read cost nothing. One question can take a search and two or three pages; max_rounds bounds that. A new account has 100 free credits and needs no card, and most requests take 2 to 9 seconds. These are not official APIs of Google or of the sites read, and Pipefetch is not affiliated with them.
Try it with 100 free credits. No card needed. No scraper to build or maintain. Get an API key or read the docs.
APIs used in this guide
-
1 credit
Google Search API
The first page of Google results for a search: rank, title, link, domain, snippet and date of each result, plus related searches.
GET /v1/google/search -
1 credit
Web Page to Markdown API
The content of one web page as Markdown or text, without its menus, with title, headings and word and token counts.
GET /v1/web/content
More Google guides
- How to get Google search results in Python
- pytrends 429 TooManyRequestsError: what it means and what to do
- How to get Google Trends data in Python
- Why is Wyoming first in Google Trends?
- How to get Google search results in Node.js
- How to get Google search results into Google Sheets
Guides for other sources
Every source
YouTube
- How to get a YouTube transcript in Python
- How to get a YouTube transcript in Node.js
- YouTube API quota exceeded: what the error means and how to fix it
- How to find a YouTube channel ID from a handle or URL
- How to download YouTube subtitles as SRT or VTT
- youtube-transcript-api RequestBlocked or IpBlocked: why it happens and how to fix it
- How to get YouTube comments in Python
- How to search YouTube from Python
- How to list a YouTube channel's videos in Python
- How to summarize a YouTube video with an LLM in Python
- How to get YouTube transcripts and video stats in Google Sheets
- How to get YouTube video views and likes in Python
- How to get YouTube transcripts in n8n, Make and Zapier
- LangChain YoutubeLoader fails on a server: why, and a loader that works
- How to get a YouTube channel's subscriber count in Python
- How to give Claude or Cursor access to YouTube (MCP server)
- How to get YouTube comments in Node.js
- How to analyze YouTube comments with an LLM in Python
- How to list a YouTube channel's Shorts in Python
- How to search YouTube from JavaScript
- How to get an Instagram follower count in Python
- Instagram Basic Display API alternatives: what to use after the shutdown
- Instaloader 401 Unauthorized, 429 and "Login required": what to do
- How to calculate an Instagram engagement rate in Python
- How to get an Instagram follower count in Node.js
- How to get Instagram follower counts in Google Sheets
- How to get Instagram Reel views in Python
Websites
- Clearbit Logo API alternatives: get a company logo from its domain
- How to extract email addresses from a website in Python
- How to turn a web page into Markdown in Python
- How to detect what a website is built with, in Python
- How to get the contact emails and phone numbers of websites in Google Sheets
- How to build a LangChain tool that reads web pages and searches Google
- How to turn a web page into Markdown in JavaScript for RAG
- How to extract social media links from a website in Python
- How to get a website's favicon in Python
- How to check robots.txt in Python before you fetch a page
TikTok
- How to get a TikTok video's views and likes in Python
- How to get the comments of a TikTok video in Python
- How to get a TikTok follower count in Python
- TikTok Research API: who can get access, and what to do if you cannot
- How to get TikTok video views, likes and shares in Node.js
- How to get TikTok views, likes and follower counts in Google Sheets
- How to get a Facebook Page's posts without app review
- Is there a Facebook Marketplace API?
- Facebook Groups API alternatives after its removal in 2024
- How to get a Facebook Page's follower count and contact details in Python
Threads
- How to get LinkedIn company data in Python
- How to search LinkedIn jobs from Python
- How to get a LinkedIn company page's latest posts in Python