Skip to content
,

Ollama Web Search API: Give Local Models Live Internet Access (Python, JS, MCP)

7–10 minutes
Woman in a server room holding a tablet with the Ollama logo, hook live web for local AI

Local models know nothing after their training cutoff. Ask a Qwen3 or Gemma model about this week’s news and it will either admit it does not know or make something up.

Ollama’s web search API fixes that. It gives your model two tools, web_search and web_fetch, so it can look things up and read pages before it answers. The model still runs on your own PC. Only the search itself goes through ollama.com.

This guide shows how to get an API key, call both endpoints with curl, Python and JavaScript, build a small search agent, and plug web search into MCP clients like Cline and Codex.

TL;DR

  • Key: make a free Ollama account, create a key at ollama.com/settings/keys, then set OLLAMA_API_KEY.
  • Endpoints: POST https://ollama.com/api/web_search (query, max_results up to 10) and POST https://ollama.com/api/web_fetch (url).
  • Python: from ollama import web_search, web_fetch, and pass them as tools=[web_search, web_fetch] to chat().
  • Agents: use a tool-capable model (Qwen3, gpt-oss), loop until no more tool_calls, and raise context to about 32K tokens.
  • MCP: Ollama ships a Python MCP server so Cline, Codex, Goose and others can use the same search.

New to Ollama? My Ollama guide covers install, models, commands and fixes in one place.

What the Web Search API Does

It is a hosted REST API on ollama.com with two calls:

Call Input Returns
web_search query (required), max_results (optional, default 5, max 10) A results list, each with title, url and a content snippet
web_fetch url (required) The page title, its main content and a list of links

You can call them directly from any code. The real power comes when you hand them to a model as tools: the model decides when to search, reads the results, fetches a page if it needs more detail, and then answers with fresh facts.

Ollama says this helps reduce hallucinations and lets models like gpt-oss run longer research tasks. If tool calling is new to you, read my Ollama tool calling guide first.

Step 1: Get an API Key

  1. Sign in or create a free account on ollama.com.
  2. Open ollama.com/settings/keys and create a new key.
  3. Save it as an environment variable so your code and tools can read it.

Windows (PowerShell):

setx OLLAMA_API_KEY "your_api_key_here"

Open a new terminal afterwards, because setx only affects new windows.

macOS / Linux:

export OLLAMA_API_KEY="your_api_key_here"
# add the line to ~/.bashrc or ~/.zshrc to keep it

Treat the key like a password. Never paste it into code you share or commit to Git. Other Ollama variables are listed in my Ollama environment variables guide.

curl https://ollama.com/api/web_search \
  --header "Authorization: Bearer $OLLAMA_API_KEY" \
  -d '{"query": "what is ollama?", "max_results": 3}'

You get back something like:

{
  "results": [
    {
      "title": "Ollama",
      "url": "https://ollama.com/",
      "content": "Cloud models are now available..."
    },
    ...
  ]
}

On Windows PowerShell, use curl.exe and $env:OLLAMA_API_KEY instead of $OLLAMA_API_KEY.

Step 3: web_fetch with curl

curl https://ollama.com/api/web_fetch \
  --header "Authorization: Bearer $OLLAMA_API_KEY" \
  --header "Content-Type: application/json" \
  -d '{"url": "ollama.com"}'

The reply has the page title, the main content as text and a links array. That is much easier for a model to read than raw HTML.

Python

The official library has both calls built in. Install or update it first:

pip install -U ollama
from ollama import web_search, web_fetch

results = web_search("latest Ollama release", max_results=5)
for r in results.results:
    print(r.title, "-", r.url)

page = web_fetch("https://ollama.com")
print(page.title)
print(page.content[:500])

Two things to know:

  • The library reads OLLAMA_API_KEY from the environment and raises an error if it is not set.
  • In Python, web_search() returns 3 results by default. Pass max_results (up to 10) for more.

The rest of the library is covered in my Ollama Python library guide.

JavaScript

import { Ollama } from 'ollama'

const client = new Ollama()

const search = await client.webSearch({ query: 'what is ollama?', max_results: 3 })
console.log(JSON.stringify(search, null, 2))

const page = await client.webFetch({ url: 'https://ollama.com' })
console.log(page.title)

Install the package with npm i ollama, and set OLLAMA_API_KEY in the environment where Node runs.

Build a Search Agent

Here is a small agent that searches and reads pages until it can answer. It follows Ollama’s own example and uses Qwen3 4B, which runs on most GPUs:

ollama pull qwen3:4b
from ollama import chat, web_fetch, web_search

available_tools = {"web_search": web_search, "web_fetch": web_fetch}
messages = [{"role": "user", "content": "What changed in the latest Ollama release?"}]

while True:
    response = chat(
        model="qwen3:4b",
        messages=messages,
        tools=[web_search, web_fetch],
        think=True,
        options={"num_ctx": 32000},
    )
    if response.message.content:
        print(response.message.content)
    messages.append(response.message)

    if not response.message.tool_calls:
        break  # final answer reached

    for call in response.message.tool_calls:
        fn = available_tools.get(call.function.name)
        if fn:
            result = fn(**call.function.arguments)
            # trim long results so they fit in context
            messages.append({"role": "tool", "content": str(result)[:8000],
                             "tool_name": call.function.name})
        else:
            messages.append({"role": "tool", "content": f"Tool {call.function.name} not found",
                             "tool_name": call.function.name})

What happens:

  1. The model reads the question and decides to call web_search.
  2. Your loop runs the search and sends the results back as a tool message.
  3. The model may call web_fetch on the best link for more detail.
  4. When it has enough, it answers in plain text and the loop ends.

Because the Python functions have type hints and docstrings, you can pass them straight in as tools and the library builds the schema. think=True is optional. It helps the model plan its searches, and the reasoning stays in message.thinking (see my Ollama thinking guide).

For a bigger agent with memory and more tools, see how to create an AI agent.

Use It in Cline, Codex and Other MCP Clients

Ollama publishes a ready-made MCP server, web-search-mcp.py, in the ollama-python repo’s examples folder. Download it, then point your client at it. It runs with uv.

Cline (Manage MCP Servers, then Configure MCP Servers):

{
  "mcpServers": {
    "web_search_and_fetch": {
      "type": "stdio",
      "command": "uv",
      "args": ["run", "path/to/web-search-mcp.py"],
      "env": { "OLLAMA_API_KEY": "your_api_key_here" }
    }
  }
}

OpenAI Codex (~/.codex/config.toml):

[mcp_servers.web_search]
command = "uv"
args = ["run", "path/to/web-search-mcp.py"]
env = { "OLLAMA_API_KEY" = "your_api_key_here" }

Goose and other MCP clients work the same way: a stdio server run with uv, with the key in its environment. New to MCP? Start with best MCP servers and MCP security best practices.

Privacy and Limits

  • The model stays local. Your prompts and the model’s answers are processed on your PC.
  • The search does not. Each search query and fetched URL is sent to ollama.com. Do not let an agent search for private data such as customer names or internal project names.
  • Account needed. A free Ollama account is required. Ollama describes a free tier with higher limits on its paid cloud plans; check ollama.com for the current limits before you build something that searches a lot.
  • Results use tokens. A single search or page can be thousands of tokens.

Want a fully offline setup? You would need your own search backend, for example a self-hosted SearXNG instance wired up as a custom tool. That is more work, and the hosted API is the easy path.

Tips for Better Answers

  • Raise the context. Ollama recommends about 32,000 tokens for search agents. Set num_ctx as in my context length guide.
  • Trim tool results. Cut each result to a few thousand characters, as the agent above does, so the context does not overflow.
  • Use a capable model. Qwen3 and gpt-oss handle multi-step search well. Tiny models often skip the tool or loop. See best Ollama models.
  • Ask for sources. Add “cite the URLs you used” to the system prompt so you can check the answer.
  • Cap the loop. Stop after 5 to 8 tool rounds, so a confused model cannot search forever.

Troubleshooting

401 Unauthorized or “OLLAMA_API_KEY” error

The key is missing or wrong. Check it with echo $OLLAMA_API_KEY (or echo $env:OLLAMA_API_KEY on PowerShell). After setx on Windows, open a new terminal or restart your IDE so it sees the variable.

The model never calls web_search

Use a model with the tools tag, phrase the question so it obviously needs fresh data (“today”, “latest”, “this week”), and add a system message such as “Use web_search for anything after your training cutoff.”

Answers get cut off or the model forgets the question

The search results filled the context. Raise num_ctx, lower max_results, and trim each tool result.

“does not support tools”

The model has no tool template. Switch to Qwen3, gpt-oss, Llama 3.1+ or another tools-tagged model, or ollama pull it again to get an updated template.

Slow agent runs

Each round means a search, a model turn and often a page fetch. Make sure the model runs fully on the GPU (ollama ps), use a smaller thinking level, or turn thinking off for simple lookups.

FAQ

Is Ollama web search free?

You need a free Ollama account and an API key. Ollama offers a free tier and higher limits on its paid cloud plans. Check ollama.com for current numbers.

Does it work with local models or only cloud models?

Both. The search runs on ollama.com, but the model that reads the results can be any local model that supports tools.

Which search engine does it use?

Ollama’s docs do not name the backend. You get titles, URLs and text snippets in a standard format.

Can I use it from LM Studio or Open WebUI?

The REST API works from any code. Clients that support MCP can use Ollama’s MCP server. Open WebUI also has its own web search settings; see my Open WebUI setup guide.

How is this different from RAG?

RAG searches your own documents. Web search looks at the live internet. You can combine both; see my Open WebUI RAG guide.

Sources

Free weekly email

Get new AI guides every week

One short weekly email with our newest local AI, ComfyUI and AI tool guides. No spam, no pop-ups, just the good stuff.

Free. Unsubscribe anytime in one click. We only use your email to send this newsletter. See our privacy policy.

Woman in a server room holding a tablet with the Ollama logo, hook live web for local AI