---
title: "Give an LLM Web Search: Tool Calling with Claude, OpenAI, Ollama"
description: "Define a web_search tool, let the model call it, run the search and send results back: complete Python loops for Claude and OpenAI-compatible APIs, local models via Ollama and LM Studio, and the common failure modes."
category: "guides"
url: https://keirolabs.cloud/blog/llm-web-search-tool-calling
published: 2026-11-24
updated: 2026-11-24
---

# How to give an LLM web search with tool calling (Claude, OpenAI, local models)

## The 60-second version

**To give an LLM web search, you define a `web_search` tool, the model decides when to call it, your code runs the search, and you send the results back.** The model then answers from those results. This is tool calling, also called function calling, and every major model API supports it.

| Step | Who does it |
|---|---|
| 1. Describe the tool: name, what it's for, its parameters | You, once |
| 2. Decide whether to search, and with what query | The model |
| 3. Run the search API call | Your code |
| 4. Send the results back as a tool result | Your code |
| 5. Answer, or search again | The model |

**There are two ways to wire it in:**

- **Bring your own search tool** (this guide). You control the search provider, what the model sees, caching and cost.
- **Use the model's built-in search.** Anthropic's server-side web search tool costs $10 per 1,000 searches plus tokens. Google's Grounding with Google Search gives 5,000 free searches a month on Gemini 3 models, then costs $14 per 1,000. Less code, less control.

## How do I describe a web search tool to the model?

**The description decides when the model searches, so write it like an instruction.** A vague description gets a model that never searches, or searches for "hello".

```python
WEB_SEARCH_TOOL = {
    "name": "web_search",
    "description": (
        "Search the live web. Use it for anything that may have changed after your training: "
        "prices, versions, release dates, news, current events, and facts about specific "
        "companies or products. Do not use it for general knowledge or for questions about "
        "the conversation itself. Returns up to 8 results with title, URL and snippet."
    ),
    "input_schema": {
        "type": "object",
        "properties": {
            "query": {"type": "string", "description": "A search engine query, 2-10 words. Include the year for time-sensitive topics."},
        },
        "required": ["query"],
    },
}
```

**Three rules worth copying:**

- **Say when to search, and when not to.** "Use it for prices, versions, news…" is what makes the model reach for it.
- **Say what comes back.** The model plans better when it knows it gets snippets rather than full pages.
- **Coach the query.** "2-10 words, include the year" prevents long, chatty queries and stale results.

## Web search tool calling with Claude

**This is the full loop with the Anthropic Python SDK.** The search provider here is Keirolabs (ours). Swap in any search API that returns titles, URLs and snippets.

```python
import os, requests, datetime
import anthropic

client = anthropic.Anthropic()

def web_search(query: str) -> str:
    r = requests.post(
        "https://api.keirolabs.cloud/api/v2/search/lite",
        headers={"Authorization": f"Bearer {os.environ['KEIRO_API_KEY']}"},
        json={"query": query, "count": 8},
        timeout=30,
    )
    r.raise_for_status()
    results = r.json()["results"]
    # Compact text, not raw JSON: fewer tokens, easier to cite
    return "\n".join(f"[{i+1}] {x['title']}\n{x['url']}\n{x.get('snippet', '')}" for i, x in enumerate(results))

messages = [{"role": "user", "content": "What changed in the latest Next.js release?"}]
system = f"Today is {datetime.date.today():%B %d, %Y}. Cite sources by URL when you use search results."

while True:
    response = client.messages.create(
        model="claude-opus-5-5",
        max_tokens=16000,
        system=system,
        tools=[WEB_SEARCH_TOOL],
        messages=messages,
    )
    if response.stop_reason == "pause_turn":          # long server-side turn: send it back to continue
        messages.append({"role": "assistant", "content": response.content})
        continue
    if response.stop_reason != "tool_use":            # end_turn, max_tokens or refusal: stop here
        break
    messages.append({"role": "assistant", "content": response.content})

    tool_results = []
    for block in response.content:
        if block.type == "tool_use" and block.name == "web_search":
            try:
                content, is_error = web_search(block.input["query"]), False
            except Exception as e:
                content, is_error = f"Search failed: {e}", True
            tool_results.append({"type": "tool_result", "tool_use_id": block.id,
                                 "content": content, "is_error": is_error})
    messages.append({"role": "user", "content": tool_results})   # all results in ONE message

print(next((b.text for b in response.content if b.type == "text"), response.stop_reason))
```

**Details that matter:**

- **Return all tool results in one user message.** Claude can call `web_search` several times in one turn, for example one query per product it is comparing. Run them, then send every `tool_result` back together.
- **Report failures as `is_error: True`, don't drop them.** The model can then retry with a different query, or tell the user search is down, instead of inventing an answer.
- **Put the date in the system prompt.** Without it, the model guesses the year, and its queries drift to old results.
- **Prefer a framework?** The Anthropic SDK's tool runner (`client.beta.messages.tool_runner` with the `@beta_tool` decorator) writes this loop for you.

## Web search tool calling with OpenAI-compatible APIs

**The same idea in OpenAI's Chat Completions format.** Local servers and many other providers accept this format too.

```python
import json
from openai import OpenAI

client = OpenAI()   # or OpenAI(base_url="http://localhost:11434/v1", api_key="ollama") for Ollama
tools = [{"type": "function", "function": {
    "name": "web_search",
    "description": WEB_SEARCH_TOOL["description"],
    "parameters": WEB_SEARCH_TOOL["input_schema"],
}}]
messages = [{"role": "user", "content": "What changed in the latest Next.js release?"}]

while True:
    resp = client.chat.completions.create(model="gpt-4.1-mini", messages=messages, tools=tools)
    msg = resp.choices[0].message
    if not msg.tool_calls:
        print(msg.content)
        break
    messages.append(msg)
    for call in msg.tool_calls:
        query = json.loads(call.function.arguments)["query"]
        messages.append({"role": "tool", "tool_call_id": call.id, "content": web_search(query)})
```

**The differences from the Claude version:**

- The schema sits under `function.parameters`.
- Tool calls arrive in `message.tool_calls`.
- Each result goes back as its own `"role": "tool"` message.

## Can local models use web search?

**Yes, if the model supports tool calling and you serve it through a tool-aware API.** Ollama serves an OpenAI-compatible API at `http://localhost:11434/v1`, and LM Studio at `http://localhost:1234/v1`. Point the OpenAI client above at either one and the same loop works.

**What decides whether it works well:**

- **The model, more than the server.** Smaller models call tools less reliably. They skip the tool, send malformed arguments, or loop. Pick a model whose card lists tool or function calling, and test it on 20 of your real questions before trusting it.
- **Keep the tool list short.** One `web_search` tool with a clear description works far better on a small model than ten overlapping tools.
- **Return less text.** A small local model with an 8k or 32k context fills up after two or three searches if each returns full pages. Return snippets and cap them.
- **An MCP server is another route.** Desktop apps that speak MCP can load a search server instead of you writing the loop. See [the best MCP servers for web search](/blog/best-mcp-servers-web-search-scraping-2026).

## Should the tool return snippets or full pages?

**Start with snippets, and add a second tool for full pages.** A result with title, URL and snippet is about 65 tokens: we measured 544 Google results at 54 tokens of title and snippet on average, plus the URL. A full page is often thousands of tokens, so ten full pages per search buries the model.

| Tool | Returns | Use when |
|---|---|---|
| `web_search` | Title, URL, snippet | Every search; deciding what to read |
| `read_page` (extract) | Clean page text for one URL | The model needs the details behind a snippet |
| `search_with_content` | Results plus page text in one call | RAG-style answers where you know you'll read the top results |

Keirolabs has all three: `/search/lite` for results ($0.03 to $0.10 per 1,000 on plans), `/extract` for page text (2 credits a page), and `/search/content` for both in one call (1.5 credits). There is more on budgets in [context engineering for search agents](/blog/context-engineering-web-search-agents).

## Common problems with web search tool calling

- **The model never searches.** Your description doesn't say when to. List the kinds of questions that need it, and add today's date.
- **It searches for everything.** Add "Do not use it for general knowledge" to the description.
- **The queries are full sentences.** Specify the format in the parameter description: "2-10 words".
- **It answers from memory after searching.** Tell it in the system prompt to answer from the results and cite them; see [grounding AI agents](/blog/grounding-ai-agents-web-search).
- **It loops on the same query.** Cap the tool calls per question in your loop, and deduplicate repeated queries before running them.
- **It hits rate limits during a burst.** Parallel tool calls can send several searches at once. Retry with backoff, and check your provider's per-minute limit ([rate limits compared](/blog/search-api-rate-limits-2026)).

New Keirolabs accounts get up to 2,000 free credits with no card (1,000 at signup, 1,000 more after setup), enough for about 2,000 test searches on `/search/lite` ([get a key](https://platform.keirolabs.cloud/register)).
