# Research agent

A model that searches as often as it needs, reads the best passages, and answers with numbered citations. One Python file.

Available · Python 3.9+ · One file · Any OpenAI-compatible model · Tested 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.

The model gets one tool, `search`, and decides what to look for and how many times (up to six rounds). Each search leaves out the 1,000 most popular sites unless the model asks for them, and returns the two passages of each page that best answer the query, so the model reads evidence rather than snippets.

## 1. Get the code

```python research_agent.py
"""Research agent: search with MillionShort, read the passages, answer with citations.

    pip install openai
    export MILLIONSHORT_API_KEY=ms-YOUR_API_KEY
    export OPENAI_API_KEY=...            # or any OpenAI-compatible API: also set OPENAI_BASE_URL
    python research_agent.py "How do repair cafes keep their volunteers?"

The model decides what to search for and how often (up to six rounds), with the most popular
sites left out unless it asks for them. MODEL picks the model (default gpt-5.4-mini).
"""
import json
import os
import sys
import urllib.error
import urllib.request

from openai import OpenAI

API = os.environ.get("MILLIONSHORT_BASE_URL", "https://api.millionshort.com").rstrip("/")
MODEL = os.environ.get("MODEL", "gpt-5.4-mini")
MAX_ROUNDS = 6

SYSTEM = """You are a careful researcher. Search before you answer anything that needs facts.
Search several times with different wording when the first results are thin. By default leave out
the 1,000 most popular sites (remove_top_sites 1000) to reach specialist and first-hand pages; use 0
when you need mainstream sources. Answer in a few short paragraphs. Cite every claim as [n], and end
with the numbered list of the URLs you cited. Say plainly when the results do not answer the question."""

TOOLS = [{
    "type": "function",
    "function": {
        "name": "search",
        "description": "Search the web and specialist sources with MillionShort. Returns titles, URLs, sites and the passages that best answer the query.",
        "parameters": {
            "type": "object",
            "properties": {
                "query": {"type": "string", "description": "What to search for."},
                "remove_top_sites": {"type": "integer", "description": "Leave out the N most popular sites: 1000 for the long tail, 0 for everything."},
                "sources": {"type": "array", "items": {"type": "string"}, "description": "Optional: web (default), news, discussions, academic, ..."},
            },
            "required": ["query"],
        },
    },
}]


class SearchError(Exception):
    """A search the API refused; `code` is the API's error code."""

    def __init__(self, code, message):
        super().__init__(f"{code}: {message}")
        self.code = code


def search(query, remove_top_sites=1000, sources=None):
    body = {"query": query, "remove_top_sites": remove_top_sites, "num_results": 6, "max_highlights": 2}
    if sources:
        body["sources"] = sources
    request = urllib.request.Request(
        f"{API}/v1/search",
        data=json.dumps(body).encode(),
        headers={"Authorization": "Bearer " + os.environ["MILLIONSHORT_API_KEY"], "Content-Type": "application/json"},
    )
    try:
        with urllib.request.urlopen(request, timeout=60) as response:
            data = json.load(response)["data"]
    except urllib.error.URLError as failure:
        if not isinstance(failure, urllib.error.HTTPError):  # no answer at all: the network, or a wrong address
            raise SearchError("NETWORK", str(failure.reason)) from None
        # a body that is not the API's JSON error (a proxy's page, say) leaves only the status
        try:
            problem = json.load(failure).get("error", {})
        except ValueError:
            problem = {}
        raise SearchError(problem.get("code", f"HTTP {failure.code}"), problem.get("message", "")) from None
    return [
        {"title": r["title"], "url": r["url"], "site": r["site"], "date": r.get("published_date"),
         "passages": r.get("highlights") or [r.get("snippet") or ""]}
        for r in data["results"]
    ]


def main(question):
    client = OpenAI()
    messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": question}]
    for _ in range(MAX_ROUNDS):
        message = client.chat.completions.create(model=MODEL, messages=messages, tools=TOOLS).choices[0].message
        if not message.tool_calls:
            print(message.content)
            return
        messages.append(message.model_dump(exclude_none=True))
        for call in message.tool_calls:
            try:
                args = json.loads(call.function.arguments or "{}")
                # only the arguments the tool declares; a model may add others
                args = {k: args[k] for k in ("query", "remove_top_sites", "sources") if k in args}
                print(f"searching: {args.get('query')!r} (remove_top_sites={args.get('remove_top_sites', 1000)})", file=sys.stderr)
                result = search(**args)
            except SearchError as error:
                if error.code == "INSUFFICIENT_CREDITS":
                    sys.exit("Out of credits: add credits in the dashboard, then run again.")
                result = {"error": str(error)}
            except (ValueError, TypeError, KeyError) as error:  # arguments that are not JSON or lack a query, or an odd answer
                result = {"error": f"the search could not be made: {error}"}
            messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})
    print(f"Stopped after {MAX_ROUNDS} rounds of searching without a final answer.")


if __name__ == "__main__":
    main(" ".join(sys.argv[1:]) or "How do repair cafes keep their volunteers?")
```

## 2. Run it

```bash
pip install openai
export MILLIONSHORT_API_KEY=ms-YOUR_API_KEY
export OPENAI_API_KEY=your-model-key
python research_agent.py "How do repair cafes keep their volunteers?"
```

For another OpenAI-compatible API, also set OPENAI_BASE_URL (for example `https://openrouter.ai/api/v1`) and MODEL to a model of that API that takes tools.

## 3. What you get

The searches it chose go to stderr, the answer to stdout:

```text Output (shortened)
searching: 'repair cafe volunteer retention how do repair cafes keep volunteers ...' (remove_top_sites=1000)
searching: 'repair cafe volunteers keep coming back why volunteer retention ...' (remove_top_sites=1000)
searching: 'repair café volunteer motivation community repair retention volunteers ...' (remove_top_sites=0)
Repair cafes seem to keep volunteers by making the work social, meaningful, and flexible. One
Repair Café page says volunteers are welcomed even if they are not handy, because the organization
needs many different skill sets, including admin and promotion roles ... [1]

Sources:
1. https://...
```

## 4. Change it

| To | Change |
|---|---|
| Search other sources | Tell the model in `SYSTEM`: the tool takes `sources`, such as `["news"]` or `["academic"]` |
| Search mainstream sites first | Change the default `remove_top_sites` in `search()` to `0` |
| Read more of each page | Add `"include_content": True` to the body (1 credit a call, for up to 10 results with text) |
| Allow more rounds | Raise MAX_ROUNDS at the top of the file |

## Costs and limits

Each round costs 1 credit per search the model makes, and a question usually takes two or three. The model's own cost is separate. [Credits and limits](https://millionshort.com/docs/credits-and-limits) has the numbers.

## 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 |
| "Out of credits" and the script stops | `INSUFFICIENT_CREDITS` | Add credits, then run it again |
| The model never searches | The model does not take tools | Pick a model of your API that supports tool calling |

## Related

- [RAG with fresh pages](https://millionshort.com/docs/integrations/cookbook-rag-fresh-pages): one search with page text, one answer.
- [Agent tool use](https://millionshort.com/docs/search/guides/agent-tool-use) and [Filters for agents](https://millionshort.com/docs/search/filters).
- The same loop in a framework: [OpenAI Agents SDK](https://millionshort.com/docs/integrations/openai-agents), [LangChain](https://millionshort.com/docs/integrations/langchain).
