Menu

Build with

Python SDK

A small client with synchronous and asynchronous forms.

Copy as MarkdownOpen in ChatGPT (opens in a new tab)Open in Claude (opens in a new tab)

The Python SDK is a thin client for the REST API. It needs Python 3.9 or later.

Install

Shell
pip install millionshort

Not published yet. The package is not on the public package index yet, so this command finds nothing today; it works once the package is published. Until then, call the REST API directly: every method below is one request, and the reference pages show each one with curl.

Create a client

Python
import os

from millionshort import MillionShort

client = MillionShort(api_key=os.environ["MILLIONSHORT_API_KEY"])
ArgumentDefaultMeaning
api_keynoneYour key. Read it from the environment yourself; the client does not.
base_urlhttps://api.millionshort.comThe API address.
timeout60.0Seconds to wait for one request.
max_retries2How many times a request that is safe to repeat is retried.

The client holds a connection pool. Close it with client.close(), or use it in a with block.

Python
import os

from millionshort import MillionShort

client = MillionShort(api_key=os.environ["MILLIONSHORT_API_KEY"])

r = client.search(
    "sourdough starter hydration",
    sources=["web", "smallweb"],
    remove_top_sites=10000,
    num_results=20,
    exclude_domains=["example.com"],
    explain=True,
)

for hit in r.results:
    print(hit["position"], hit["site"], hit["popularity"]["bucket"])
    print("   ", hit["title"])
    print("   ", hit["url"])
    for reason in hit.get("why", []):
        print("    why:", reason)

print(r.summary["returned"], "returned;", r.summary["removed"]["popularity"], "removed by popularity")
print(r.usage.credits, "credits; request", r.request_id)
for warning in r.warnings:
    print("warning:", warning["code"], warning["message"])

search takes the query and these keyword arguments, which are the fields of the Search reference: sources, num_results, remove_top_sites, only_top_sites, include_domains, exclude_domains, boost_domains, bury_domains, page_types, topics, safe_search, max_chars_per_result and explain. The filters, highlights and page content are keyword arguments too, under the same names as in the reference: for example start_date, language, country, exclude_page_types, boost_topics, traffic_trend, popular_in, site_tech, exclude_risky, max_highlights and include_content. An argument you leave out uses the API's default.

What comes back

Every method returns a Result. The API wraps its answer as data, usage, warnings and request_id; the SDK unwraps it:

Each entry of r.results is a dictionary, so its fields are read with brackets: hit["title"].

Sources and domain info

Python
import os

from millionshort import MillionShort

client = MillionShort(api_key=os.environ["MILLIONSHORT_API_KEY"])

catalog = client.list_sources()
print([source["slug"] for source in catalog.sources])
print([page_type["slug"] for page_type in catalog.page_types])

info = client.get_domain_info(["example.com", "blog.example.org"])
for entry in info.domains:
    print(entry["domain"], entry["popularity"]["bucket"], entry["risk"])

Map and Crawl

map lists the URLs of a site. crawl starts a job that returns the site's pages as clean text:

Python
import os
import time

from millionshort import MillionShort

client = MillionShort(api_key=os.environ["MILLIONSHORT_API_KEY"])

found = client.map(url="https://example.org/", search="pricing", limit=20)
for u in found.urls:
    print(u["url"], u.get("title"))

job = client.crawl(url="https://example.org/docs", max_pages=50, include=["^/docs/"])
while job.status in ("queued", "running"):
    time.sleep(5)
    job = client.get_crawl(job.id)

for page in job.results:
    if page["status"] == "ok":
        print(page["depth"], page["url"], page["page_type"])
    else:
        print(page["url"], "failed:", page["error"]["code"])
print(job.completed, "pages,", job.credits_used, "credits")
MethodDoes
map(url, ...)Lists a site's URLs. url comes first; the keyword arguments are the other fields of a Map request: search, limit, include_subdomains, include, exclude, sources
crawl(url, ...)Starts a crawl and returns the job. url comes first; the keyword arguments are the other fields of a crawl request: max_pages, max_depth, include, exclude, mode and the rest
get_crawl(id, cursor=None)The crawl, with a page of its results. Pass next as cursor for the following page. Free
list_crawls(limit=None)Your team's crawls, newest first, without results. Free
cancel_crawl(id)Stops a crawl. The pages that came back are kept and stay charged
wait_crawl(id, poll_interval=5.0, timeout=600.0)Polls until the crawl ends, then returns it with every page of results. It gives up after timeout seconds (the crawl keeps running). A large crawl takes hours: give it a timeout to match, or poll get_crawl yourself

A map costs 1 credit per 10 URLs returned, and a crawled page 1 credit in live: see Map pricing and Crawl pricing. A page that fails is free.

Spaces

A Space is a saved scope for search. Create one, then pass its slug or id as space on search:

Python
import os

from millionshort import MillionShort

client = MillionShort(api_key=os.environ["MILLIONSHORT_API_KEY"])

baking = client.create_space(
    "Baking",
    sites=["example.org", "example.com/blog"],
    remove_top_sites=1000,
)

r = client.search("sourdough hydration", space=baking.slug)
print(len(r.results), "results from", r.space["sites_applied"], "sites")

listing = client.list_spaces(scope="all")
for entry in listing.spaces:
    print(entry["slug"], "curated" if entry["curated"] else "ours")

client.update_space(baking.id, remove_top_sites=10000)
client.delete_space(baking.id)
MethodDoes
create_space(name, ...)Creates a Space. The keyword arguments are the fields of the Space object: sites, mode, remove_top_sites, lens and the rest
list_spaces(scope=...)Lists Spaces: "own" (the default), "curated" or "all"
get_space(id)Reads one, by id, by your slug, or as "curated:<slug>"
update_space(id, ...)Changes the fields given; the others stay. lens is one field: a lens given replaces all three of its lists
delete_space(id)Deletes it
import_spaces(spaces)Loads Spaces exported from the MillionShort search site: the export file as a dictionary, or a list of entries
search(query, space=...)Searches with a Space. An argument you pass beside it replaces the Space's value for that setting

All of them are free; a search with a Space costs what the search costs. A Space that does not exist raises NotFoundError, with the code SPACE_NOT_FOUND. A curated Space cannot be changed: MillionShortError, with the code SPACE_READ_ONLY.

Places

Python
from millionshort import MillionShort

client = MillionShort(api_key=os.environ["MILLIONSHORT_API_KEY"])

r = client.places("coffee", near="Leslieville, Toronto", limit=5)
for place in r.results:
    print(place["name"], place["address"]["formatted"], place["phone"])
print(r.attribution["text"])

The keyword arguments are the fields of a Places request, under the same names: category, exclude_category, brand, near, lat, lng, bbox, ip, near_me, neighbourhood, city, region, country, radius_m, has_phone, has_website, has_hours, open_now, sort, fields and limit. If you show the places to people, show attribution with them.

Python
r = client.places(
    category="Coffee shop",
    neighbourhood="Leslieville",
    city="Toronto",
    has_website=True,
    sort="distance",
    fields=["name", "distance_m", "website"],
)

near_me=True searches around the city of the machine that runs this code. On a server, send the person's own address as ip, or a position they shared as lat and lng.

list_place_categories() returns the categories category takes, free: client.list_place_categories(q="sushi"), or parent="italian_restaurant" for what is directly under a category.

Agent

The methods of Agent.

A question in, an answer with a checked quote for every statement out. A run is a job: start it, then wait for it.

Python
import os

from millionshort import MillionShort

client = MillionShort(api_key=os.environ["MILLIONSHORT_API_KEY"])

run = client.start_agent(
    "What does a monthly adult pass cost on Northbridge Transit in 2026, and when did the price last change?",
    processor="lite",
    max_credits=40,
    idempotency_key="fares-2026-11-20",
)

done = client.wait_agent(run.id, poll_interval=2.0, timeout=600.0)
print(done.status, done.stop_reason)
print(done.answer)
for cite in done.citations:
    print(cite["n"], cite["url"], cite["quote"])
print(done.usage.credits, done.usage.steps)
MethodDoes
start_agent(prompt, ...)Starts a run and returns it, with its id. The keyword arguments are the fields of an Agent request, under the same names: urls, schema, sources, space, remove_top_sites, include_domains, exclude_domains, start_date, processor, model, max_credits and webhook_id. idempotency_key is sent as the Idempotency-Key header, and lets the client retry the call
get_agent(id)The run: status, progress and steps, and the result once it has ended. Free
get_agent_results(id)The result alone. ready is False while the run is going, which is not an error. Free
wait_agent(id, poll_interval=2.0, timeout=600.0)Polls until the run is completed, incomplete, failed or cancelled, and returns it. Past timeout it raises PollTimeoutError; the run goes on
stream_agent_events(id, after=None)Yields the steps as they happen, each a dictionary with event and data: agent.step for each step, then one agent.done. Free
cancel_agent(id)Cancels the run. The work already done is charged

citations[n-1] is the page behind the [n] marker of answer: n, url, title, source and quote. With schema, read output, field_citations and uncited_fields in place of answer. An incomplete run is not an exception: stop_reason says why it ended early.

Python
import os

from millionshort import MillionShort

client = MillionShort(api_key=os.environ["MILLIONSHORT_API_KEY"])

run = client.start_agent("What changed in Northbridge Transit fares in 2026?", processor="lite")
last = 0
for event in client.stream_agent_events(run.id):
    if event["event"] == "agent.step":
        last = event["data"]["seq"]
        print(last, event["data"]["type"])
    else:
        print("ended:", event["data"]["status"], event["data"]["stop_reason"])

A stream is closed after 5 minutes at most. If it ends with no agent.done, call again with after=last.

A run is metered, and never costs more than max_credits. Agent pricing and limits has the prices, and Agent errors what a start can be refused for.

Async

AsyncMillionShort has the same methods, awaited:

Python
import asyncio
import os

from millionshort import AsyncMillionShort


async def main():
    async with AsyncMillionShort(api_key=os.environ["MILLIONSHORT_API_KEY"]) as client:
        r = await client.search("harbour pilot schedules", num_results=5)
        for hit in r.results:
            print(hit["title"], hit["url"])


asyncio.run(main())

Errors

Every failure raises a subclass of MillionShortError:

ClassRaised for
ValidationErrorINVALID_PARAM
UnsupportedOptionErrorUNSUPPORTED_OPTION
AuthenticationErrorAUTH_INVALID_KEY, AUTH_MISSING_KEY
MillionShortErrorQUOTA_EXCEEDED, ACCOUNT_NOT_ELIGIBLE, ACCOUNT_SUSPENDED
NotFoundErrorNOT_FOUND
RateLimitErrorRATE_LIMITED
CapacityErrorCAPACITY
InsufficientCreditsErrorINSUFFICIENT_CREDITS
ServerErrorINTERNAL
SearchUnavailableErrorSEARCH_UNAVAILABLE
APIConnectionErrorThe request never reached the API (network failure or timeout).

Each error has code, message, request_id, details, retry_after_seconds and status_code.

Python
import os
import time

from millionshort import (
    CapacityError,
    InsufficientCreditsError,
    MillionShort,
    MillionShortError,
    RateLimitError,
    SearchUnavailableError,
)

client = MillionShort(api_key=os.environ["MILLIONSHORT_API_KEY"])

for attempt in range(4):
    try:
        r = client.search("tide tables", num_results=5)
        break
    except (RateLimitError, CapacityError, SearchUnavailableError) as error:
        time.sleep(error.retry_after_seconds or 2**attempt)
    except InsufficientCreditsError as no_credits:
        raise SystemExit("Out of credits.") from no_credits
    except MillionShortError as error:
        raise SystemExit(f"{error.code}: {error.message} (request {error.request_id})")
else:
    raise SystemExit("Still failing after four attempts.")

print(len(r.results), "results")

Retries

The client retries a GET, such as list_sources, on 429 and on a server error, waiting as long as the API asks. It does not repeat a POST on its own, so a failed search raises at once: retry it yourself, as in the example above. The Errors page says which codes are worth a retry.

A trial key

An agent with no key can get a short-lived one:

Python
from millionshort import MillionShort

key = MillionShort().create_agent_key("my-agent").api_key
client = MillionShort(api_key=key)

See Authentication.

This page as Markdown ยท llms.txt