# Ollama

MillionShort search for local models in Ollama, as a function tool in Python and TypeScript.

Recipe · Python and TypeScript · Nothing of ours to install · Checked 2026-11-19

> **For agents.** Read the API key from the `MILLIONSHORT_API_KEY` environment variable. Never print it; where a client needs it in a settings file, use a file that is not committed.
> The MCP address is https://mcp.millionshort.com/mcp (streamable HTTP; send `Authorization: Bearer <key>`, or no header for the no-key mode).
> On `INSUFFICIENT_CREDITS` stop and ask a person; on `RATE_LIMITED` or `CAPACITY` wait the `Retry-After` seconds, then retry once.
> Set-up steps written for agents: https://millionshort.com/docs/auth.md. Every integration: https://millionshort.com/docs/integrations.md.

Ollama's libraries take tools in `chat`: the model asks for a call, your code runs the search, and the loop sends the results back until the model answers. The model must support tools; Ollama's own examples use `qwen3`. The model runs on your machine, and only the search goes out to MillionShort.

## 1. Install

```bash Python
pip install ollama requests
export MILLIONSHORT_API_KEY=ms-YOUR_API_KEY
```

```bash TypeScript
npm install ollama
export MILLIONSHORT_API_KEY=ms-YOUR_API_KEY
```

Pull a model that supports tools before you start (`ollama pull qwen3`). Both libraries talk to your Ollama with their default settings, so the examples set no address. Get a MillionShort key in the [dashboard](https://millionshort.com/app/); an agent can ask for a [trial key](https://millionshort.com/docs/api-reference/agent-key) by itself.

## 2. Minimal example

```python Python
import json
import os

import requests
from ollama import chat


def millionshort_search(query: str) -> str:
    """Search the web with MillionShort, leaving out the 1,000 most popular sites.

    Args:
        query: What to search for.
    """
    r = requests.post(
        "https://api.millionshort.com/v1/search",
        headers={"Authorization": f"Bearer {os.environ['MILLIONSHORT_API_KEY']}"},
        json={"query": query, "remove_top_sites": 1000, "num_results": 5},
        timeout=30,
    )
    r.raise_for_status()
    return json.dumps([{"title": x["title"], "url": x["url"], "snippet": x.get("snippet")} for x in r.json()["data"]["results"]])


messages = [{"role": "user", "content": "Find independent blogs about home espresso."}]
while True:
    response = chat(model="qwen3", messages=messages, tools=[millionshort_search])
    messages.append(response.message)
    if not response.message.tool_calls:
        break
    for call in response.message.tool_calls:
        result = millionshort_search(**call.function.arguments)
        messages.append({"role": "tool", "tool_name": call.function.name, "content": result})
print(response.message.content)
```

```ts TypeScript
import ollama, { type Message } from 'ollama';

async function millionshortSearch(query: string): Promise<string> {
  const res = await fetch('https://api.millionshort.com/v1/search', {
    method: 'POST',
    headers: { Authorization: `Bearer ${process.env.MILLIONSHORT_API_KEY}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({ query, remove_top_sites: 1000, num_results: 5 }),
  });
  if (!res.ok) throw new Error(`search failed: ${res.status}`);
  const { data } = (await res.json()) as { data: { results: { title: string; url: string; snippet?: string }[] } };
  return JSON.stringify(data.results.map(({ title, url, snippet }) => ({ title, url, snippet })));
}

const tools = [{ type: 'function', function: {
  name: 'millionshort_search',
  description: 'Search the web with MillionShort, leaving out the 1,000 most popular sites.',
  parameters: { type: 'object', required: ['query'], properties: { query: { type: 'string', description: 'What to search for' } } },
} }];
const messages: Message[] = [{ role: 'user', content: 'Find independent blogs about home espresso.' }];
while (true) {
  const response = await ollama.chat({ model: 'qwen3', messages, tools });
  messages.push(response.message);
  const calls = response.message.tool_calls ?? [];
  if (calls.length === 0) {
    console.log(response.message.content);
    break;
  }
  for (const call of calls) {
    const content = await millionshortSearch(String(call.function.arguments.query));
    messages.push({ role: 'tool', tool_name: call.function.name, content });
  }
}
```

The Python library builds the tool's schema from the function's type hints and its docstring (with the `Args:` section), so keep both. A model can ask for several searches in one turn; the loop runs each of them. Models that think, such as `qwen3`, also take `think=True` (`think: true`), as in Ollama's examples.

## 3. Tell it when to search

Ollama searches nothing unless your code does, so there is no built-in search to turn off. Small models call tools less readily: add a system message with a line like this:

> Use the MillionShort `search` tool for anything recent, niche, or that needs a source. To reach lesser-known sites, set `remove_top_sites` (for example 1000). Cite the URLs it returns.

## 4. Check it works

Run the example, then ask:

> Search MillionShort for forum threads about restoring a cast iron skillet, with the 1,000 most popular sites removed. List the five most useful with their links.

After the first `chat` call, `response.message.tool_calls` should name `millionshort_search` with a `query`. If it is empty every time, the model probably does not support tools: try another.

## Tools

The function tool above is `search` alone. For the server's other tools as well ([the MCP page](https://millionshort.com/docs/mcp#tools) lists them), run Ollama behind an agent framework that speaks MCP and connect our [MCP server](https://millionshort.com/docs/mcp):

| Tool | What it does | Without a key | Cost |
|---|---|---|---|
| `search` | Searches the web and the specialist sources, with the popularity, domain, page-type, topic, site and date filters | Yes: one source, up to 5 results | 1 credit per source searched, first 10 results |
| `get_domain_info` | Popularity and risk for up to 25 sites | No | 1 credit |
| `list_sources` | The sources, page types and topics `search` accepts | Yes: source names | Free |
| The tools of the other endpoints | `extract`, `map`, `crawl`, `places` and more: [the MCP page](https://millionshort.com/docs/mcp#tools) lists them | A few, such as `places` | What the API call behind each costs |

## Settings

| Variable | Meaning |
|---|---|
| `MILLIONSHORT_API_KEY` | Your key, read by the examples above |

## Costs and limits

A tool call costs what the API call behind it costs: 1 credit per source searched for the first 10 results, 1 credit for a domain lookup, nothing for the list of sources, the price of the endpoint for the other tools, and nothing at all in the no-key mode. An agent that loops can make many calls: give it a step limit, and ask for fewer results when a few will do. [Credits and limits](https://millionshort.com/docs/credits-and-limits) has the numbers.

The model itself runs on your machine and costs nothing per call.

## When it fails

| What you see | Why | Fix |
|---|---|---|
| `401 AUTH_MISSING_KEY` or `AUTH_INVALID_KEY` | The key is missing or wrong | Set `MILLIONSHORT_API_KEY`; keys start with `ms-` |
| `400 INVALID_PARAM` | A field name or value the API does not take | The `message` names the field; the [search reference](https://millionshort.com/docs/search/parameters) lists them all |
| `429 RATE_LIMITED` or `CAPACITY` | Too many calls a minute, or no free capacity right now | Wait the `Retry-After` seconds, then retry |
| `429 INSUFFICIENT_CREDITS` | The plan's credits are used up | Stop and add credits; do not retry |
| The model never calls the tool | The model does not support tools, or nothing told it when to search | Pull a model that does, such as `qwen3` |
| The call to the model cannot connect | Ollama is not running, or runs somewhere other than the libraries' default | Start Ollama, or pass its address to the client as Ollama's library docs describe |

## Related

- [Agent tool use](https://millionshort.com/docs/search/guides/agent-tool-use): when to give a model tools, and what to tell it.
- Local models elsewhere: [LM Studio](https://millionshort.com/docs/integrations/lm-studio), [Open WebUI](https://millionshort.com/docs/integrations/open-webui), [AnythingLLM](https://millionshort.com/docs/integrations/anythingllm).
- Other model APIs: [OpenRouter](https://millionshort.com/docs/integrations/openrouter), [Gemini](https://millionshort.com/docs/integrations/gemini), [Mistral](https://millionshort.com/docs/integrations/mistral).
- [Search API reference](https://millionshort.com/docs/search/parameters) and [MCP server](https://millionshort.com/docs/mcp).
- Ollama's own documentation, read on 2026-11-19: [Tool calling](https://docs.ollama.com/capabilities/tool-calling).
