django-agent-search logo

django-agent-search

akarca/django-agent-search by us

Search for agents: a /.well-known/search endpoint and agent:* discovery tags for Django sites, backed by PostgreSQL full-text search

0stars Python MIT last commit 9 hours ago
README.md

django-agent-search

Make your Django site searchable by AI agents. You get the same contract as Cloudflare's Search for Agents, but on your own server, with your own database, and with no Cloudflare in front.

  • /.well-known/search?q=…: agents send keywords or a plain-language question. They get back the most relevant passages of your pages as Markdown, each with its URL. The result is not a generated answer, so agents use the passages with their own model. Requests can be GET or HTTP QUERY (RFC 10008).
  • Discovery tags: every HTML page gets the agent:* meta tags that agents look for, so they find the endpoint on their own instead of crawling page by page.
  • Index from your sitemap: a management command reads sitemap.xml and fetches each page the way a visitor sees it. It keeps the main content as Markdown passages and stores them in your database. It works with any template engine, any caching and any i18n setup.
  • PostgreSQL full-text search with the stemmer of each page's language (english, turkish, german, … and simple for the rest). On SQLite it falls back to a substring match, for tests and very small sites. It needs no extra services, embeddings or API keys.
$ curl --get https://nameocean.net/.well-known/search --data-urlencode "q=How do I verify webhook signatures?"
# Search results for: "How do I verify webhook signatures?"

5 passages from this site, best match first. Each one shows its page URL.

## 1. Webhooks: domain, DNS and SSL events, signed | NameOcean — Verify the signature

URL: https://nameocean.net/developers/webhooks/
Score: 0.867 · Language: en

t is the Unix time of the request, v1 the hex HMAC-SHA256 of t, a dot and the raw body …

Used by

Using it too? Open a pull request and add your site here.

Install

pip install git+https://github.com/akarca/django-agent-search.git@v0.1.1
# settings.py
INSTALLED_APPS = [..., "agent_search"]

MIDDLEWARE = [
    # below GZipMiddleware and anything else that compresses responses
    ...,
    "agent_search.middleware.AgentSearchMetaMiddleware",
]

AGENT_SEARCH = {
    "BASE_URL": "https://example.com",
}
# urls.py: at the root, outside i18n_patterns()
urlpatterns = [
    path("", include("agent_search.urls")),
    ...
]

If the site has its own full-page cache (a middleware that stores whole responses), leave /.well-known/ out of it. The endpoint has its own result cache, and its answer depends on Accept and Accept-Language.

python manage.py migrate agent_search
python manage.py agent_search_index -v 2      # first run; then from cron
python manage.py agent_search_query "how do I …"   # try it from the shell

Run agent_search_index from cron, for example every few hours. Each run does three things:

  • It reads the sitemaps.
  • It forgets URLs that are no longer listed.
  • It fetches the pages that are due, at most MAX_FETCH_PER_RUN of them. A page is due when it was never fetched, when its lastmod changed, or when it is older than REFRESH_DAYS.

A large site is indexed over several runs. A PostgreSQL advisory lock keeps two runs from overlapping. If you run the site on several servers that share one database, run the command on one server only.

The search API

GET /.well-known/search?q=… q (required, max. 500 characters), limit (1–50, default 10), lang (e.g. en or en,de: only pages in these languages), format=json
QUERY /.well-known/search Body: the query as text/plain, or application/json {"q": "…", "limit": 5, "lang": "en"}. POST is accepted the same way.
Response text/markdown; charset=utf-8 by default. With Accept: application/json or format=json it is {"query": "…", "results": [{"url", "title", "heading", "lang", "score", "content"}]}.
Headers Access-Control-Allow-Origin: *, X-Robots-Tag: noindex (search engines do not index result lists), Cache-Control: public, max-age=300.
Errors 400 when q is missing (the body explains how to use the API), 405 for other methods.

Matching is word-based and stemmed per language. A passage matches when it shares a word with the query, and passages that contain all the words rank first. Passages from pages in the caller's Accept-Language rank higher; without that header the site's DEFAULT_LANGUAGE does, so a site with translations answers in its main language unless asked otherwise (lang= restricts the results to languages). At most CHUNKS_PER_PAGE passages of one page are returned, and identical passages (such as a call-to-action repeated on every page) are returned only once.

What is indexed

  • Only URLs listed in the sitemaps, on the sitemaps' own host, filtered by INCLUDE and EXCLUDE.
  • From each page, the content of <main>. Without <main> it uses the <article> elements, and without those the <body>. nav, header, footer, aside, form, script, style and hidden elements are dropped.
  • Pages with <meta name="robots" content="noindex"> are skipped. So are pages whose canonical URL is another URL, and pages that redirect.
  • The page is split into passages at its headings, at most MAX_CHUNK_CHARS characters each.
  • The language comes from <html lang>, else DEFAULT_LANGUAGE.

You can see each page's status in the Django admin under Agent search → Pages.

Settings

All keys go in AGENT_SEARCH and all are optional.

| Key | Default | | |---|---|---| | BASE_URL | "" | Public origin, e.g. https://example.com. Used for the endpoint URL in the tags and for the default sitemap. When empty, it is taken from the request. | | SITEMAPS | [BASE_URL + "/sitemap.xml"] | Sitemaps or sitemap indexes to crawl. | | INCLUDE / EXCLUDE | [] | Regexes on the URL path. Example: "EXCLUDE": [r"^/(de|fr)/"]. | | DEFAULT_LANGUAGE | LANGUAGE_CODE | Language for pages without <html lang>. | | MAX_PAGES | 20000 | Never index more URLs than this. | | MAX_FETCH_PER_RUN | 1000 | Pages fetched per run. | | REFRESH_DAYS | 7 | Refetch a page at least this often. | | CONCURRENCY / DELAY / TIMEOUT | 2 / 0.25 / 20 | Politeness towards your own server. | | USER_AGENT | django-agent-search/<version> (+repo URL) | | | MAX_CHUNK_CHARS | 2400 | Passage size. | | MAX_RESULTS / MAX_RESULTS_LIMIT | 10 / 50 | Default and maximum limit. | | CHUNKS_PER_PAGE | 2 | Passages per page in one result list. | | CACHE_SECONDS | 300 | Result cache (Django's default cache) and Cache-Control. | | INJECT_META | True | Turn the discovery tags off. | | INSTRUCTIONS / DOCUMENTATION | see conf.py | Contents of agent:instructions and agent:documentation. |

Discovery tags

<meta name="agent:instructions" content="This site has a search API for agents. …">
<meta name="agent:endpoint" content="https://example.com/.well-known/search?q={query}">
<meta name="agent:method" content="GET">
<meta name="agent:documentation" content="https://github.com/akarca/django-agent-search#the-search-api">

These are the tags Cloudflare's Search for Agents adds. The middleware adds them only to uncompressed text/html 200 responses, and only once per page. It is also a good idea to mention the endpoint in your llms.txt.

Will it help SEO?

Not in the classic sense: Google and Bing do not use /.well-known/search. Its job is to let AI agents, such as coding agents and research agents that browse on a user's behalf, find the right page on your site cheaply and quote it correctly. The agent:* tags and the endpoint are a convention started by Cloudflare, not a standard yet. The endpoint sends X-Robots-Tag: noindex, so it cannot create thin or duplicate pages in search engines.

Development

python runtests.py                       # SQLite
PG_DATABASE=agent_search_test python runtests.py   # PostgreSQL (database must exist)

MIT licensed.