#!/usr/bin/env python3 """Generate an llms.txt file for any website, with the Ujeebu Crawl API. Crawls the site as plain HTML (no JavaScript: the cheapest page), takes each page's title and meta description (or its first paragraph), groups the pages by their first path segment and writes llms.txt in the llmstxt.org format: the site name as an H1, a one-line summary, then one "## Section" list of links per group. pip install requests UJEEBU_API_KEY=your-key python3 generate_llms_txt.py """ import collections import os import time from html.parser import HTMLParser from urllib.parse import urlparse import requests API_KEY = os.environ.get("UJEEBU_API_KEY", "YOUR_API_KEY") API = "https://api.ujeebu.com" SITE = "https://ujeebu.com/" CRAWL = { "urls": [SITE], "scope": {"max_depth": 1, "max_pages": 60, "exclude": ["/signin", "/signup", "/forgot", "/privacy", "/terms"]}, # pages no reader needs "format": "html", "page": {"js": False}, } http = requests.Session() http.headers["ApiKey"] = API_KEY def api(method, path, **kwargs): """Call the Crawl API. A GET is tried again after a network error or a timeout.""" for attempt in range(1, 4): try: response = http.request(method, API + path, timeout=300, **kwargs) break except (requests.ConnectionError, requests.Timeout): if method != "GET" or attempt == 3: raise time.sleep(5 * attempt) if response.status_code >= 400: raise SystemExit(f"{method} {path}: {response.status_code} {response.text}") return response.json() class HeadParser(HTMLParser): """The , the <meta> name/property values and the first real paragraph of a page.""" def __init__(self): super().__init__() self.title, self.meta, self.paragraph = "", {}, "" self._in, self._text = None, "" def handle_starttag(self, tag, attrs): a = dict(attrs) if tag == "meta" and (a.get("name") or a.get("property")): self.meta[(a.get("name") or a.get("property")).lower()] = a.get("content") or "" elif tag in ("title", "p"): self._in, self._text = tag, "" def handle_endtag(self, tag): if tag == self._in: text = " ".join(self._text.split()) if tag == "title" and not self.title: self.title = text elif tag == "p" and not self.paragraph and len(text) >= 40: self.paragraph = text self._in = None def handle_data(self, data): if self._in: self._text += data def describe(html): page = HeadParser() page.feed(html) summary = page.meta.get("description") or page.meta.get("og:description") or page.paragraph return page.title, " ".join(summary.split()), page.meta.get("og:site_name", "") def section(url): """The group of a page: its first path segment when it has two or more, else "Pages".""" parts = urlparse(url).path.strip("/").split("/") return parts[0].replace("-", " ").capitalize() if len(parts) > 1 else "Pages" # 1. Price the crawl, cap it at the quote, and wait for it. quote = api("POST", "/crawl/quote", json=CRAWL) job = api("POST", "/crawl", json={**CRAWL, "max_credits": quote["credits_ceiling"]}) while not job.get("finished"): time.sleep(5) job = api("GET", f"/crawl/{job['job_id']}") # 2. Read every page with its HTML, 5 at a time (whole HTML pages make large answers). pages, after = [], 0 while True: batch = api("GET", f"/crawl/{job['job_id']}/pages", params={"after": after, "limit": 5, "content": "true"}) pages += [p for p in batch["pages"] if p["state"] == "done" and p.get("html")] if not batch["has_more"]: break after = batch["next_after"] # 3. One line per page, grouped by section, in the llms.txt format. home_title, home_summary, site_name = describe(pages[0]["html"]) site_name = site_name or urlparse(SITE).netloc groups = collections.defaultdict(list) for page in pages[1:]: title, summary, _ = describe(page["html"]) title = title.rsplit(" | ", 1)[0] or page["url"] # "Pricing | Ujeebu" -> "Pricing" groups[section(page["url"])].append(f"- [{title}]({page['url']})" + (f": {summary}" if summary else "")) lines = [f"# {site_name}", "", f"> {home_summary}", ""] for name in sorted(groups, key=lambda g: (g != "Pages", g)): lines += [f"## {name}", "", *groups[name], ""] with open("llms.txt", "w", encoding="utf-8") as f: f.write("\n".join(lines)) print(f"llms.txt: {len(pages)} pages in {len(groups)} sections; job {job['stop_reason']}, {job['credits_used']} credits")