Skip to content

Commit 2155e44

Browse files
authored
Generate llms.txt (#784)
1 parent 9dc86df commit 2155e44

File tree

4 files changed

+55
-3
lines changed

4 files changed

+55
-3
lines changed

docs/plugins/build_llms_txt.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
from __future__ import annotations as _annotations
2+
3+
import os
4+
5+
from bs4 import BeautifulSoup
6+
from markdownify import MarkdownConverter
7+
from mkdocs.config.defaults import MkDocsConfig
8+
from mkdocs.structure.files import Files
9+
from mkdocs.structure.pages import Page
10+
11+
12+
def on_config(config: MkDocsConfig):
13+
os.mkdir(config.site_dir)
14+
llms_path = os.path.join(config.site_dir, 'llms.txt')
15+
with open(llms_path, 'w') as f:
16+
f.write('')
17+
18+
19+
def on_page_content(html: str, page: Page, config: MkDocsConfig, files: Files) -> str:
20+
soup = BeautifulSoup(html, 'html.parser')
21+
22+
# Clean up presentational and UI elements
23+
for element in soup.find_all(
24+
['a', 'div', 'img'], attrs={'class': ['headerlink', 'tabbed-labels', 'twemoji lg middle', 'twemoji']}
25+
):
26+
element.decompose()
27+
28+
# The API reference generates HTML tables with line numbers, this strips the line numbers cell and goes back to a code block
29+
for extra in soup.find_all('table', attrs={'class': 'highlighttable'}):
30+
extra.replace_with(BeautifulSoup(f'<pre>{extra.find('code').get_text()}</pre>', 'html.parser'))
31+
32+
with open(os.path.join(config.site_dir, 'llms.txt'), 'a', encoding='utf-8') as f:
33+
f.write(MarkdownConverter().convert_soup(soup)) # type: ignore[reportUnknownMemberType]
34+
35+
return html

mkdocs.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,4 +308,5 @@ plugins:
308308
"get-started/traces.md": "concepts.md"
309309
hooks:
310310
- docs/plugins/main.py
311+
- docs/plugins/build_llms_txt.py
311312
- docs/plugins/build_index.py

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,7 @@ docs = [
174174
"griffe",
175175
"bs4>=0.0.2",
176176
"algoliasearch>=3,<4",
177+
"markdownify>=0.14.1",
177178
]
178179

179180
[tool.inline-snapshot]

uv.lock

Lines changed: 18 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)