from llms_txt import *
Python模块 & 命令行界面
Read llms.txt files and create XML context documents for LLMs
给定一个 llms.txt
文件,这提供了一个CLI和Python API来解析该文件并从中创建一个XML上下文文件。输入文件应遵循以下格式:
# FastHTML
> FastHTML is a python library which...
When writing FastHTML apps remember to:
- Thing to remember
## Docs
- [Surreal](https://host/README.md): Tiny jQuery alternative with Locality of Behavior
- [FastHTML quick start](https://host/quickstart.html.md): An overview of FastHTML features
## Examples
- [Todo app](https://host/adv_app.py)
## Optional
- [Starlette docs](https://host/starlette-sml.md): A subset of the Starlette docs
安装
pip install llms-txt
如何使用
命令行界面
安装后,llms_txt2ctx
在您的终端中可用。
要获取CLI的帮助:
llms_txt2ctx -h
要将一个 llms.txt
文件转换为 XML 内容并保存为 llms.md
:
llms_txt2ctx llms.txt > llms.md
传递 --optional True
以添加输入文件的 "optional" 部分。
Python模块
= Path('llms-sample.txt').read_text() samp
使用 parse_llms_file
创建一个包含 llms.txt 文件部分的数据结构(如果需要,您也可以添加 optional=True
):
= parse_llms_file(samp)
parsed list(parsed)
['title', 'summary', 'info', 'sections']
parsed.title,parsed.summary
('FastHTML',
'FastHTML is a python library which brings together Starlette, Uvicorn, HTMX, and fastcore\'s `FT` "FastTags" into a library for creating server-rendered hypermedia applications.')
list(parsed.sections)
['Docs', 'Examples', 'Optional']
0] parsed.sections.Optional[
{ 'desc': 'A subset of the Starlette documentation useful for FastHTML '
'development.',
'title': 'Starlette full documentation',
'url': 'https://gist.githubusercontent.com/jph00/809e4a4808d4510be0e3dc9565e9cbd3/raw/9b717589ca44cedc8aaf00b2b8cacef922964c0f/starlette-sml.md'}
使用 create_ctx
创建一个包含XML部分的LLM上下文文件,适用于Claude等系统(这就是CLI在后台调用的内容)。
= create_ctx(samp) ctx
print(ctx[:300])
<project title="FastHTML" summary='FastHTML is a python library which brings together Starlette, Uvicorn, HTMX, and fastcore's `FT` "FastTags" into a library for creating server-rendered hypermedia applications.'>
Remember:
- Use `serve()` for running uvicorn (`if __name__ == "__main__"` is not
实现与测试
为了展示解析 llms.txt
文件是多么简单,这里有一个完整的解析器,少于20行代码且没有依赖:
from pathlib import Path
import re,itertools
def chunked(it, chunk_sz):
= iter(it)
it return iter(lambda: list(itertools.islice(it, chunk_sz)), [])
def parse_llms_txt(txt):
"Parse llms.txt file contents in `txt` to a `dict`"
def _p(links):
= '-\s*\[(?P<title>[^\]]+)\]\((?P<url>[^\)]+)\)(?::\s*(?P<desc>.*))?'
link_pat return [re.search(link_pat, l).groupdict()
for l in re.split(r'\n+', links.strip()) if l.strip()]
*rest = re.split(fr'^##\s*(.*?$)', txt, flags=re.MULTILINE)
start,= {k: _p(v) for k,v in dict(chunked(rest, 2)).items()}
sects = '^#\s*(?P<title>.+?$)\n+(?:^>\s*(?P<summary>.+?$)$)?\n+(?P<info>.*)'
pat = re.search(pat, start.strip(), (re.MULTILINE|re.DOTALL)).groupdict()
d 'sections'] = sects
d[return d
我们在 tests/test-parse.py
中提供了一个测试套件,并确认该实现通过了所有测试。