Python 源代码

llms_txt Python 模块的源代码,包含用于创建和使用 llms.txt 文件的辅助工具

简介

llms.txt 文件规范适用于位于网站路径 llms.txt 下(或可选地,在子路径下)的文件。llms-sample.txt 是一个简单的示例。遵循该规范的文件按特定顺序包含以下 Markdown 格式的章节

  • 一个 H1 标题,包含项目或网站的名称。这是唯一必需的章节
  • 一个块引用,包含项目的简短摘要,其中包含理解文件其余部分所必需的关键信息
  • 零个或多个除标题外的任何类型的 Markdown 章节(例如段落、列表等),包含有关项目以及如何解释所提供文件的更详细信息
  • 零个或多个由 H2 标题分隔的 Markdown 章节,包含提供更多详细信息的 URL 的“文件列表”
    • 每个“文件列表”都是一个 Markdown 列表,包含一个必需的 Markdown 超链接 [名称](url),然后可选地跟着一个 : 和关于文件的注释。

以下是一个我们将用于测试的 llms.txt 示例文件的开头部分

samp = Path('llms-sample.txt').read_text()
print(samp[:480])
# 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.

Remember:

- Use `serve()` for running uvicorn (`if __name__ == "__main__"` is not needed since it's automatic)
- When a title is needed with a response, use `Titled`; note that that already wraps children in `Container`, and already includes both the meta title as well as the H1 element

读取

我们将实现 parse_llms_file 来将 llms.txt 的各个章节提取到一个简单的数据结构中。


源代码

named_re

 named_re (nm, pat)

在命名捕获组中匹配 pat 的模式


源代码

opt_re

 opt_re (s)

可选地匹配 s 的模式

我们将采用“由外到内”的方式,以便在进行过程中测试最内层的匹配。

解析章节

sections = '''First bit.

## S1

-[foo](http://foo)
- [foo2](http://foo2): stuff

## S2

- [foo3](http://foo3)'''
start,*rest = re.split(fr'^##\s*(.*?$)', sections, flags=re.MULTILINE)
start
'First bit.\n\n'
rest
['S1',
 '\n\n-[foo](http://foo)\n- [foo2](http://foo2): stuff\n\n',
 'S2',
 '\n\n- [foo3](http://foo3)']

rest 中的键值对简洁地创建一个字典。

d = dict(chunked(rest, 2))
d
{'S1': '\n\n-[foo](http://foo)\n- [foo2](http://foo2): stuff\n\n',
 'S2': '\n\n- [foo3](http://foo3)'}
links = d['S1']
links.strip()
'-[foo](http://foo)\n- [foo2](http://foo2): stuff'

links 解析为一个链接列表。它们之间可以有多个换行符。

_parse_links(links)
[{'title': 'foo', 'url': 'http://foo', 'desc': None},
 {'title': 'foo2', 'url': 'http://foo2', 'desc': 'stuff'}]

创建一个函数,使用上述步骤将 llms.txt 解析为 start 和一个字典,该字典的键类似于 d,值为解析后的链接列表。

start, sects = _parse_llms(samp)
start
'# FastHTML\n\n> 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.\n\nRemember:\n\n- Use `serve()` for running uvicorn (`if __name__ == "__main__"` is not needed since it\'s automatic)\n- When a title is needed with a response, use `Titled`; note that that already wraps children in `Container`, and already includes both the meta title as well as the H1 element.'
title = named_re('title', r'.+?$')
summ = named_re('summary', '.+?$')
summ_pat = opt_re(fr"^>\s*{summ}$")
info = named_re('info', '.*')
pat = fr'^#\s*{title}\n+{summ_pat}\n+{info}'
search(pat, start, (re.MULTILINE|re.DOTALL))
{'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.',
 'info': 'Remember:\n\n- Use `serve()` for running uvicorn (`if __name__ == "__main__"` is not needed since it\'s automatic)\n- When a title is needed with a response, use `Titled`; note that that already wraps children in `Container`, and already includes both the meta title as well as the H1 element.'}

让我们完成它!


源代码

parse_llms_file

 parse_llms_file (txt)

txt 中的 llms.txt 文件内容解析为一个 AttrDict

llmsd = parse_llms_file(samp)
llmsd.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.'
llmsd.sections.Examples
(#1) [{'title': 'Todo list application', 'url': 'https://raw.githubusercontent.com/AnswerDotAI/fasthtml/main/examples/adv_app.py', 'desc': 'Detailed walk-thru of a complete CRUD app in FastHTML showing idiomatic use of FastHTML and HTMX patterns.'}]

XML 转换

对于像 Claude 这样的某些 LLM,首选 XML 格式,因此我们将提供一个函数来创建该格式。


源代码

get_doc_content

 get_doc_content (url)

如果位于 nbdev 仓库中,则从本地文件获取内容。


源代码

mk_ctx

 mk_ctx (d, optional=True, n_workers=None)

d 中的每个 H2 部分创建一个带有 SectionProject,可以选择性地跳过“optional”部分。

ctx = mk_ctx(llmsd)
print(to_xml(ctx, do_escape=False)[:260]+'...')
<project title="FastHTML" summary='FastHTML is a python library which brings together Starlette, Uvicorn, HTMX, and fastcore&#39;s `FT` "FastTags" into a library for creating server-rendered hypermedia applications.'>Remember:

- Use `serve()` for running uvic...

源代码

get_sizes

 get_sizes (ctx)

获取 LLM 上下文每个部分的大小

get_sizes(ctx)
{'docs': {'internal docs - ed': 34464,
  'FastHTML quick start': 27383,
  'HTMX reference': 26812,
  'Starlette quick guide': 7936},
 'examples': {'Todo list application': 18558},
 'optional': {'Starlette full documentation': 48331}}
Path('../fasthtml.md').write_text(to_xml(ctx, do_escape=False))
164662

源代码

create_ctx

 create_ctx (txt, optional=False, n_workers=None)

一个 Project,其中为 txt 中的每个 H2 部分创建一个 Section,可以选择性地跳过“optional”部分。


源代码

llms_txt2ctx

 llms_txt2ctx (fname:str, optional:<function bool_arg>=False,
               n_workers:int=None, save_nbdev_fname:str=None)

打印一个 Project,其中为从 fname 读取的文件中的每个 H2 部分创建一个 Section,可以选择性地跳过“optional”部分。

类型 默认值 详情
fname str 要读取的文件名
optional bool_arg False 是否包含“optional”部分?
n_workers int None 用于并行下载的线程数
save_nbdev_fname str None 将输出保存到 nbdev 的 {docs_path} 而不是输出到 stdout
!llms_txt2ctx llms-sample.txt > ../fasthtml.md