Skip to content

docs_catalog

Finding things in the docs that ship with the package, for the docs agent SensAI answers "how do I use Mojo" with.

The pages are every .md file under docs/ of the docs source that ships in the package (DOCS_SOURCE_DIR): the user guides, the command line reference, the changelog and the rest. Each is known by its path under docs/, and is read as plain markdown (utils/docs_text.py removes the site's markup). This splits each at its headings into sections, and ranks sections against a question by word (BM25, with the words of a heading counting for more). There are no embeddings and nothing is downloaded, so it works offline and gives the same ranking every time.

SITE_URL module-attribute

Python
SITE_URL = 'https://hydrowelder.github.io/mujoco-mojo/'

Where the docs site is, which the docs links are built on.

STOP_WORDS module-attribute

Python
STOP_WORDS = frozenset(split())

Words too common to say what a question is about, which a search leaves out.

Section

Bases: BaseModel

The part of a page under one heading, up to the next heading of any level.

headings instance-attribute

Python
headings: tuple[str, ...]

The page's title, then each heading above this one, then this section's own.

Python
link: str

Where the section is on the docs site.

DocsPage

Bases: BaseModel

One bundled page of the docs.

path instance-attribute

Python
path: str

Its path under docs/, such as user-guides/workflow/getting-started.md, reference/cli.md or changelog.md.

Hit

Bases: BaseModel

A section that matched a search, with the line that matched best.

slugify

Python
slugify(heading: str) -> str

The anchor the docs site gives a heading: lowercase words joined by hyphens.

Source code in src/mujoco_mojo/utils/layers/dojo/sensai/docs_catalog.py
Python
def slugify(heading: str) -> str:
    """The anchor the docs site gives a heading: lowercase words joined by hyphens."""
    text = unicodedata.normalize("NFKD", heading).encode("ascii", "ignore").decode()
    text = re.sub(r"[^\w\s-]", "", text).strip().lower()
    return re.sub(r"[-\s]+", "-", text)

docs_url

Python
docs_url(path: str) -> str

The docs site address of the page at path (under docs/): user-guides/workflow/x.md is at user-guides/workflow/x/, and an index.md is the address of its folder.

Source code in src/mujoco_mojo/utils/layers/dojo/sensai/docs_catalog.py
Python
def docs_url(path: str) -> str:
    """The docs site address of the page at `path` (under `docs/`): `user-guides/workflow/x.md` is at `user-guides/workflow/x/`, and an `index.md` is the address of its folder."""
    page = path.removesuffix(".md")
    if page == "index":
        return SITE_URL
    return f"{SITE_URL}{page.removesuffix('/index')}/"

docs_pages cached

Python
docs_pages(
    directory: Path = DOCS_SOURCE_DIR,
) -> tuple[DocsPage, ...]

Every page of the docs source in directory, in path order.

Source code in src/mujoco_mojo/utils/layers/dojo/sensai/docs_catalog.py
Python
@cache
def docs_pages(directory: Path = DOCS_SOURCE_DIR) -> tuple[DocsPage, ...]:
    """Every page of the docs source in `directory`, in path order."""
    found: list[DocsPage] = []
    # sorted by the parts of the path, as the files were when they were read from a folder, so a page comes before the folder of the same name
    for path, file in sorted(
        _docs_files(directory).items(), key=lambda item: Path(item[0]).parts
    ):
        text = plain_text(file)
        title, sections = _split_sections(path, text)
        found.append(DocsPage(path=path, title=title, text=text, sections=sections))
    return tuple(found)

table_of_contents

Python
table_of_contents(directory: Path = DOCS_SOURCE_DIR) -> str

One line per page, its path and title, for the agent's instructions.

Source code in src/mujoco_mojo/utils/layers/dojo/sensai/docs_catalog.py
Python
def table_of_contents(directory: Path = DOCS_SOURCE_DIR) -> str:
    """One line per page, its path and title, for the agent's instructions."""
    return "\n".join(f"- {g.path}: {g.title}" for g in docs_pages(directory))

search_docs

Python
search_docs(
    query: str,
    limit: int = 5,
    directory: Path = DOCS_SOURCE_DIR,
) -> list[Hit]

The sections that best answer query, best first, at most two from any one page. Empty when no word of the query is in the docs.

Source code in src/mujoco_mojo/utils/layers/dojo/sensai/docs_catalog.py
Python
def search_docs(
    query: str, limit: int = 5, directory: Path = DOCS_SOURCE_DIR
) -> list[Hit]:
    """The sections that best answer `query`, best first, at most two from any one page. Empty when no word of the query is in the docs."""
    terms = set(_terms(query))
    if not terms:
        return []
    index = _index(directory)
    ranked = sorted(
        (
            (index.score(i, terms), i)
            for i in range(len(index.sections))
            if index.score(i, terms) > 0
        ),
        key=lambda pair: (-pair[0], pair[1]),
    )
    hits: list[Hit] = []
    per_page: Counter[str] = Counter()
    for score, i in ranked:
        section = index.sections[i]
        if per_page[section.path] >= _MAX_HITS_PER_PAGE:
            continue
        per_page[section.path] += 1
        hits.append(Hit(section=section, score=score, snippet=_snippet(section, terms)))
        if len(hits) == limit:
            break
    return hits

read_docs

Python
read_docs(
    path: str,
    section: str = "",
    limit: int = _READ_LIMIT,
    directory: Path = DOCS_SOURCE_DIR,
) -> str

A page, or one section of it, with its title and docs site link on top.

A page longer than limit characters is cut there with a note listing its sections, so a reader can ask for one. A path or section that is not there is answered with what is, not an error.

Source code in src/mujoco_mojo/utils/layers/dojo/sensai/docs_catalog.py
Python
def read_docs(
    path: str,
    section: str = "",
    limit: int = _READ_LIMIT,
    directory: Path = DOCS_SOURCE_DIR,
) -> str:
    """
    A page, or one section of it, with its title and docs site link on top.

    A page longer than `limit` characters is cut there with a note listing its sections, so a reader can ask for one. A path or section that is not there is answered with what is, not an error.
    """
    page = _find_docs_page(path, directory)
    if page is None:
        every = [g.path for g in docs_pages(directory)]
        close = difflib.get_close_matches(
            path.strip().strip("/"), every, n=3, cutoff=0.4
        )
        hint = f" Closest: {', '.join(close)}." if close else ""
        return f"There is no page at '{path}'.{hint} The pages are: {', '.join(every)}."
    top = f"{page.title} ({page.url})\n\n"
    if section:
        i = _find_section(page, section)
        if i is None:
            titles = ", ".join(s.title for s in page.sections)
            return f"{top}This page has no section called '{section}'. Its sections are: {titles}."
        text = _section_text(page, i)
        top = f"{page.title} > {page.sections[i].title} ({page.sections[i].link})\n\n"
    else:
        text = page.text.strip("\n")
    if len(text) <= limit:
        return top + text
    titles = ", ".join(s.title for s in page.sections)
    cut = text[:limit].rsplit("\n", 1)[0]
    return (
        f"{top}{cut}\n\n[Cut here. The page's sections are: {titles}. "
        "Call read_docs again with the path and section set to one of them.]"
    )