---
title: xml source
---
<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

```python
from copy import deepcopy

from fastcore.test import *
```

## JSON to XML

[source](https://github.com/AnswerDotAI/toolslm/blob/main/toolslm/xml.py#L26)

### json\_to\_xml

```python
def json_to_xml(
    d:dict, # JSON dictionary to convert
    rnm:str, # Root name
)->str:
```

*Convert `d` to XML.*

JSON doesn't map as nicely to XML as the data structure used in `fastcore.xml`, but for simple XML trees it can be convenient -- for example:

```python
a = dict(surname='Howard', firstnames=['Jeremy','Peter'],
         address=dict(state='Queensland',country='Australia'))
hl_md(json_to_xml(a, 'person'))
```

```html
<person>
  <surname>Howard</surname>
  <firstnames>
    <item>Jeremy</item>
    <item>Peter</item>
  </firstnames>
  <address>
    <state>Queensland</state>
    <country>Australia</country>
  </address>
</person>
```

## Including documents

### Notebooks

```python
nbp = Path('00_xml.ipynb')
nb = read_nb(nbp)
cells = nb.cells
cell = cells[7]
cell
```

````python
{ 'cell_type': 'code',
  'execution_count': None,
  'id': '005a5be4',
  'metadata': {},
  'outputs': [{'data': {'text/markdown': ['```html\n', '<person>\n', '  <surname>Howard</surname>\n', '  <firstnames>\n', '    <item>Jeremy</item>\n', '    <item>Peter</item>\n', '  </firstnames>\n', '  <address>\n', '    <state>Queensland</state>\n', '    <country>Australia</country>\n', '  </address>\n', '</person>\n', '```'], 'text/plain': ['<IPython.core.display.Markdown object>']}, 'execution_count': None, 'metadata': {}, 'output_type': 'execute_result'}],
  'source': ["a = dict(surname='Howard', firstnames=['Jeremy','Peter'],\n", "         address=dict(state='Queensland',country='Australia'))\n", "hl_md(json_to_xml(a, 'person'))"]}
````

[source](https://github.com/AnswerDotAI/toolslm/blob/main/toolslm/xml.py#L38)

### cell2xml

```python
def cell2xml(
    cell, out:bool=True, ids:bool=True, nums:bool=False
):
```

*Convert notebook cell to concise XML format*

```python
hl_md(cell2xml(cell, out=False, nums=True))
```

```html
<code id="005a5be4">     1 │ a = dict(surname='Howard', firstnames=['Jeremy','Peter'],
     2 │          address=dict(state='Queensland',country='Australia'))
     3 │ hl_md(json_to_xml(a, 'person'))</code>
```

[source](https://github.com/AnswerDotAI/toolslm/blob/main/toolslm/xml.py#L53)

### nb2xml

```python
def nb2xml(
    fname=None, nb=None, *, out:bool=True, ids:bool=True, nums:bool=False
):
```

*Convert notebook to XML format*

[source](https://github.com/AnswerDotAI/toolslm/blob/main/toolslm/xml.py#L47)

### cells2xml

```python
def cells2xml(
    cells, wrap:functools.partial=functools.partial(<function ft at 0x799369d99da0>, 'notebook'), *, out:bool=True,
    ids:bool=True, nums:bool=False
):
```

*Convert notebook to XML format*

```python
nbsml = deepcopy(nb)
del(nbsml.cells[2:])

hl_md(nb2xml(nb=nbsml))
```

```html
<notebook><code id="efe78920"><source>#|default_exp xml</code><md id="87ea05a3"><source># xml source</md></notebook>
```

```python
hl_md(nb2xml(nb=nbsml, ids=False))
```

```html
<notebook><code><source>#|default_exp xml</code><md><source># xml source</md></notebook>
```

### Documents

According [to Anthropic](https://docs.anthropic.com/claude/docs/long-context-window-tips), "*it's essential to structure your prompts in a way that clearly separates the input data from the instructions*". They recommend using something like the following:

```xml
Here are some documents for you to reference for your task:
    
<documents>
<document index="1">
<source>
(URL, file name, hash, etc)
</source>
<document_content>
(the text content)
</document_content>
</document>
</documents>
```

We will create some small helper functions to make it easier to generate context in this format, although we're use `<src>` instead of `<source>` to avoid conflict with that HTML tag. Although it's based on Anthropic's recommendation, it's likely to work well with other models too.

We'll use `doctype` to store our pairs.

Since Anthropic's example shows newlines before and after each tag, we'll do the same.

```python
to_xml(Src('a'))
```

```output
'<src>a</src>'
```

```python
to_xml(Document('a'))
```

```output
'<document>a</document>'
```

[source](https://github.com/AnswerDotAI/toolslm/blob/main/toolslm/xml.py#L71)

### mk\_doctype

```python
def mk_doctype(
    content:str, # The document content
    src:Optional[str]=None, # URL, filename, etc; defaults to `md5(content)` if not provided
)-><function namedtuple at 0x79936b3d4540>:
```

*Create a `doctype` named tuple*

This is a convenience wrapper to ensure that a `doctype` has the needed information in the right format.

```python
doc = 'This is a "sample"'
mk_doctype(doc)
```

```output
doctype(src='\n47e19350\n', content='\nThis is a "sample"\n')
```

[source](https://github.com/AnswerDotAI/toolslm/blob/main/toolslm/xml.py#L80)

### mk\_doc

```python
def mk_doc(
    index:int, # The document index
    content:str, # The document content
    src:Optional[str]=None, # URL, filename, etc; defaults to `md5(content)` if not provided
    **kwargs
)->tuple:
```

*Create an `ft` format tuple for a single doc in Anthropic's recommended format*

We can now generate XML for one document in the suggested format:

```python
mk_doc(1, doc, title="test")
```

[source](https://github.com/AnswerDotAI/toolslm/blob/main/toolslm/xml.py#L93)

### docs\_xml

```python
def docs_xml(
    docs:list[str], # The content of each document
    srcs:Optional[list]=None, # URLs, filenames, etc; each one defaults to `md5(content)` if not provided
    prefix:bool=False, # Include Anthropic's suggested prose intro?
    details:Optional[list]=None, # Optional list of dicts with additional attrs for each doc
    title:str=None, # Optional title attr for Documents element
)->str:
```

*Create an XML string containing `docs` in Anthropic's recommended format*

Putting it all together, we have our final XML format:

```python
docs = [doc, 'And another one']
srcs = [None, 'doc.txt']
print(docs_xml(docs, srcs))
```

```output
<documents><document index="1"><src>
47e19350
</src><document-content>
This is a "sample"
</document-content></document><document index="2"><src>
doc.txt
</src><document-content>
And another one
</document-content></document></documents>
```

## Context creation

Now that we can generate Anthropic's XML format, let's make it easy for a few common cases.

### File list to context

For generating XML context from files, we'll just read them as text and use the file names as `src`.

[source](https://github.com/AnswerDotAI/toolslm/blob/main/toolslm/xml.py#L110)

### read\_file

```python
def read_file(
    fname, max_size=None, sigs_only:bool=False, *, nb=None, out:bool=True, ids:bool=True, nums:bool=False
):
```

*Read file content, converting notebooks to XML if needed*

[source](https://github.com/AnswerDotAI/toolslm/blob/main/toolslm/xml.py#L123)

### files2ctx

```python
def files2ctx(
    fnames:list[typing.Union[str, pathlib._local.Path]], # List of file names to add to context
    srcs:Optional[list]=None, # Use the labels instead of `fnames`
    max_size:int=None, # Skip files larger than this (bytes)
    out:bool=True, # Include notebook cell outputs?
    ids:bool=True, # Include cell ids in notebooks?
    nums:bool=False, # Include line numbers in notebook cell source?
    sigs_only:bool=False, # Only include signatures and docstrings (where supported by `codesigs` lib)
    *, prefix:bool=False, # Include Anthropic's suggested prose intro?
    details:Optional[list]=None, # Optional list of dicts with additional attrs for each doc
    title:str=None, # Optional title attr for Documents element
)->str: # XML for LM context
```

*Convert files to XML context, handling notebooks*

```python
fnames = ['samples/sample_core.py', 'samples/sample_styles.css']
hl_md(files2ctx(fnames, max_size=120))
```

```html
<documents><document index="1"><src>
samples/sample_core.py
</src><document-content>
[Skipped: sample_core.py exceeds 120 bytes]
</document-content></document><document index="2"><src>
samples/sample_styles.css
</src><document-content>
.cell { margin-bottom: 1rem; }
.cell > .sourceCode { margin-bottom: 0; }
.cell-output > pre { margin-bottom: 0; }
</document-content></document></documents>
```

### Folder to context

[source](https://github.com/AnswerDotAI/toolslm/blob/main/toolslm/xml.py#L141)

### folder2ctx

```python
def folder2ctx(
    path:Union[str, pathlib._local.Path]='.', # Folder to read
    prefix:bool=False, # Include Anthropic's suggested prose intro?
    out:bool=True, # Include notebook cell outputs?
    include_base:bool=True, # Include full path in src?
    title:str=None, # Optional title attr for Documents element
    max_size:int=100000, # Skip files larger than this (bytes)
    max_total:int=10000000, # Max total output size in bytes
    readme_first:bool=False, # Prioritize README files at start of context?
    files_only:bool=False, # Return dict of {filename: size} instead of context?
    sigs_only:bool=False, # Return signatures instead of full text? (where supported by `codesigs` lib)
    ids:bool=True, # Include cell ids in notebooks?
    *, recursive:bool=True, # search subfolders
    maxdepth:int=None, # max depth to descend (1=just immediate contents; None=unlimited)
    symlinks:bool=True, # follow symlinks?
    file_glob:str=None, # Only include files matching glob
    file_re:str=None, # Only include files matching regex
    path_glob:str=None, # Only include files whose full paths match glob (wildcards match separators)
    path_re:str=None, # Only include files whose full paths match regex
    folder_re:str=None, # Only enter folders matching regex
    skip_file_glob:str=None, # Skip files matching glob
    skip_file_re:str=None, # Skip files matching regex
    skip_folder_re:str=None, # Skip folders matching regex,
    ret_folders:bool=False, # return folders, not just files
    sort:bool=True, # sort files by name within each folder
    types:str | list=None, # list or comma-separated str of ext types from: py, js, java, c, cpp, rb, r, ex, sh, web, doc, cfg
    exts:str | list=None, # list or comma-separated str of exts to include
)->Union[str, dict]: # Paths to matched files
```

*Convert folder contents to XML context, handling notebooks; prints instead of returning when run as a CLI*

```python
print(folder2ctx('samples', prefix=True, types='py'))
```

```output
Here are some documents for you to reference for your task:

<documents><document index="1"><src>
samples/sample_core.py
</src><document-content>
import inspect
empty = inspect.Parameter.empty
models = 'claude-3-opus-20240229','claude-3-sonnet-20240229','claude-3-haiku-20240307'
</document-content></document></documents>
```

[source](https://github.com/AnswerDotAI/toolslm/blob/main/toolslm/xml.py#L169)

### sym2file

```python
def sym2file(
    sym
):
```

*Return md string with filepath and contents for a symbol's source file*

```python
# print(sym2file(Path))
```

[source](https://github.com/AnswerDotAI/toolslm/blob/main/toolslm/xml.py#L176)

### sym2folderctx

```python
def sym2folderctx(
    sym,
    types:str | list='py', # List or comma-separated str of ext types from: py, js, java, c, cpp, rb, r, ex, sh, web, doc, cfg
    skip_file_re:str='^_mod', # Skip files matching regex
    *, path:Union[str, pathlib._local.Path]='.', # Folder to read
    prefix:bool=False, # Include Anthropic's suggested prose intro?
    out:bool=True, # Include notebook cell outputs?
    include_base:bool=True, # Include full path in src?
    title:str=None, # Optional title attr for Documents element
    max_size:int=100000, # Skip files larger than this (bytes)
    max_total:int=10000000, # Max total output size in bytes
    readme_first:bool=False, # Prioritize README files at start of context?
    files_only:bool=False, # Return dict of {filename: size} instead of context?
    sigs_only:bool=False, # Return signatures instead of full text? (where supported by `codesigs` lib)
    ids:bool=True, # Include cell ids in notebooks?
    recursive:bool=True, # search subfolders
    maxdepth:int=None, # max depth to descend (1=just immediate contents; None=unlimited)
    symlinks:bool=True, # follow symlinks?
    file_glob:str=None, # Only include files matching glob
    file_re:str=None, # Only include files matching regex
    path_glob:str=None, # Only include files whose full paths match glob (wildcards match separators)
    path_re:str=None, # Only include files whose full paths match regex
    folder_re:str=None, # Only enter folders matching regex
    skip_file_glob:str=None, # Skip files matching glob
    skip_folder_re:str=None, # Skip folders matching regex,
    ret_folders:bool=False, # return folders, not just files
    sort:bool=True, # sort files by name within each folder
    exts:str | list=None, # list or comma-separated str of exts to include
): # Paths to matched files
```

*Return folder context for a symbol's source file location*

```python
# print(sym2folderctx(test_eq))
```

[source](https://github.com/AnswerDotAI/toolslm/blob/main/toolslm/xml.py#L186)

### sym2pkgpath

```python
def sym2pkgpath(
    sym
):
```

*Get root package path for a symbol*

```python
sym2pkgpath(test_eq)
```

```output
Path('/Users/jhoward/aai-ws/fastcore/fastcore')
```

[source](https://github.com/AnswerDotAI/toolslm/blob/main/toolslm/xml.py#L194)

### sym2pkgctx

```python
def sym2pkgctx(
    sym,
    types:str | list='py', # List or comma-separated str of ext types from: py, js, java, c, cpp, rb, r, ex, sh, web, doc, cfg
    skip_file_re:str='^_mod', # Skip files matching regex
    skip_folder_re:str='^(\\.|__)', # Skip folders matching regex
    *, path:Union[str, pathlib._local.Path]='.', # Folder to read
    prefix:bool=False, # Include Anthropic's suggested prose intro?
    out:bool=True, # Include notebook cell outputs?
    include_base:bool=True, # Include full path in src?
    title:str=None, # Optional title attr for Documents element
    max_size:int=100000, # Skip files larger than this (bytes)
    max_total:int=10000000, # Max total output size in bytes
    readme_first:bool=False, # Prioritize README files at start of context?
    files_only:bool=False, # Return dict of {filename: size} instead of context?
    sigs_only:bool=False, # Return signatures instead of full text? (where supported by `codesigs` lib)
    ids:bool=True, # Include cell ids in notebooks?
    recursive:bool=True, # search subfolders
    maxdepth:int=None, # max depth to descend (1=just immediate contents; None=unlimited)
    symlinks:bool=True, # follow symlinks?
    file_glob:str=None, # Only include files matching glob
    file_re:str=None, # Only include files matching regex
    path_glob:str=None, # Only include files whose full paths match glob (wildcards match separators)
    path_re:str=None, # Only include files whose full paths match regex
    folder_re:str=None, # Only enter folders matching regex
    skip_file_glob:str=None, # Skip files matching glob
    ret_folders:bool=False, # return folders, not just files
    sort:bool=True, # sort files by name within each folder
    exts:str | list=None, # list or comma-separated str of exts to include
): # Paths to matched files
```

*Return contents of files in a symbol's root package*

```python
# print(sym2pkgctx(test_eq))
```

> [!TIP]
> After you install `toolslm`, [`folder2ctx`](xml.md#folder2ctx) becomes available from the command line.

```python
!folder2ctx -h
```

```output
usage: folder2ctx [-h] [--path PATH] [--no-out] [--prefix] [--no-include-base]
                  [--title TITLE] [--max-size MAX_SIZE] [--max-total MAX_TOTAL]
                  [--readme-first] [--files-only] [--sigs-only] [--no-ids]
                  [--no-recursive] [--no-symlinks] [--file-glob FILE_GLOB]
                  [--file-re FILE_RE] [--folder-re FOLDER_RE]
                  [--skip-file-glob SKIP_FILE_GLOB]
                  [--skip-file-re SKIP_FILE_RE]
                  [--skip-folder-re SKIP_FOLDER_RE] [--ret-folders] [--no-sort]
                  [--types TYPES] [--exts EXTS]

CLI to convert folder contents to XML context, handling notebooks

options:
  -h, --help                       show this help message and exit
  --path PATH                      Folder name containing files to add to
                                   context (default: .)
  --no-out                         Include notebook cell outputs? (default:
                                   True)
  --prefix                         Include Anthropic's suggested prose intro?
                                   (default: False)
  --no-include-base                Include full path in src? (default: True)
  --title TITLE                    Optional title attr for Documents element
  --max-size MAX_SIZE              Skip files larger than this (bytes) (default:
                                   100000)
  --max-total MAX_TOTAL            Max total output size in bytes (default:
                                   10000000)
  --readme-first                   Prioritize README files at start of context?
                                   (default: False)
  --files-only                     Return dict of {filename: size} instead of
                                   context? (default: False)
  --sigs-only                      Return signatures instead of full text for
                                   python files? (default: False)
  --no-ids                         Include cell ids in notebooks? (default:
                                   True)
  --no-recursive                   search subfolders (default: True)
  --no-symlinks                    follow symlinks? (default: True)
  --file-glob FILE_GLOB            Only include files matching glob
  --file-re FILE_RE                Only include files matching regex
  --folder-re FOLDER_RE            Only enter folders matching regex
  --skip-file-glob SKIP_FILE_GLOB  Skip files matching glob
  --skip-file-re SKIP_FILE_RE      Skip files matching regex
  --skip-folder-re SKIP_FOLDER_RE  Skip folders matching regex,
  --ret-folders                    return folders, not just files (default:
                                   False)
  --no-sort                        sort files by name within each folder
                                   (default: True)
  --types TYPES                    list or comma-separated str of ext types
                                   from: py, js, java, c, cpp, rb, r, ex, sh,
                                   web, doc, cfg
  --exts EXTS                      list or comma-separated str of exts to
                                   include
```

[source](https://github.com/AnswerDotAI/toolslm/blob/main/toolslm/xml.py#L205)

### parse\_gh\_url

```python
def parse_gh_url(
    url
):
```

*Parse GitHub URL into (owner, repo, type, ref, path) or None*

[source](https://github.com/AnswerDotAI/toolslm/blob/main/toolslm/xml.py#L218)

### repo2ctx

```python
def repo2ctx(
    owner:str, # GitHub repo owner or "owner/repo" or a full github URL
    repo:str=None, # GitHub repo name (leave empty if using "owner/repo" or URL format for owner param)
    ref:str=None, # Git ref (branch/tag/sha) (get from URL not provided); defaults to repo's default branch
    folder:str=None, # Only include files under this path (get from URL not provided)
    show_filters:bool=True, # Include filter info in title?
    token:str=None, # GitHub token (uses GITHUB_TOKEN env var if None)
    *, prefix:bool=False, # Include Anthropic's suggested prose intro?
    out:bool=True, # Include notebook cell outputs?
    max_size:int=100000, # Skip files larger than this (bytes)
    max_total:int=10000000, # Max total output size in bytes
    files_only:bool=False, # Return dict of {filename: size} instead of context?
    sigs_only:bool=False, # Return signatures instead of full text? (where supported by `codesigs` lib)
    ids:bool=True, # Include cell ids in notebooks?
    recursive:bool=True, # search subfolders
    maxdepth:int=None, # max depth to descend (1=just immediate contents; None=unlimited)
    symlinks:bool=True, # follow symlinks?
    file_glob:str=None, # Only include files matching glob
    file_re:str=None, # Only include files matching regex
    path_glob:str=None, # Only include files whose full paths match glob (wildcards match separators)
    path_re:str=None, # Only include files whose full paths match regex
    folder_re:str=None, # Only enter folders matching regex
    skip_file_glob:str=None, # Skip files matching glob
    skip_file_re:str=None, # Skip files matching regex
    skip_folder_re:str=None, # Skip folders matching regex,
    ret_folders:bool=False, # return folders, not just files
    sort:bool=True, # sort files by name within each folder
    types:str | list=None, # list or comma-separated str of ext types from: py, js, java, c, cpp, rb, r, ex, sh, web, doc, cfg
    exts:str | list=None, # list or comma-separated str of exts to include
)->Union[str, dict]: # XML for LM context, or dict of file sizes
```

*Convert GitHub repo to XML context without cloning; prints instead of returning when run as a CLI*

```python
s = set(inspect.signature(repo2ctx).parameters)
test_eq(s & {'path','include_base','title','readme_first'}, set())
```

```python
print(await repo2ctx('answerdotai/toolslm', exts=('ipynb','py'), skip_file_re='^_', out=False, max_total=500))
```

```output
<documents title="GitHub repository contents from answerdotai/toolslm/main (filters applied -- exts: ipynb, py | skip_file_re: ^_ | max_total: 500)"><document index="1"><src>
00_xml.ipynb
</src><document-content>
<notebook><code id="efe78920">#|default_exp xml</code><md id="87ea05a3"># xml source</md><code id="033c76fd">#| export
import hashlib, inspect, xml.etree.ElementTree as ET, ast
from collections import namedtuple
from ghapi.all

[TRUNCATED: output size 106522 exceeded max size 500 bytes]
```

```python
print(await repo2ctx('answerdotai/toolslm', types='py', skip_file_re='^_', out=False, files_only=True))
```

```output
{'00_xml.ipynb': 39890, '01_funccall.ipynb': 66266, '02_shell.ipynb': 6295, '03_download.ipynb': 12178, '04_md_hier.ipynb': 8469, 'index.ipynb': 3089, 'setup.py': 2596, 'samples/sample_core.py': 134, 'toolslm/download.py': 4582, 'toolslm/funccall.py': 11650, 'toolslm/md_hier.py': 11010, 'toolslm/shell.py': 1617, 'toolslm/xml.py': 13718}
```

```python
print(await repo2ctx('https://github.com/AnswerDotAI/toolslm/tree/main/ship/samples'))
```

```output
<documents title="GitHub repository contents from AnswerDotAI/toolslm/main/samples"><document index="1"><src>
sample_core.py
</src><document-content>
import inspect
empty = inspect.Parameter.empty
models = 'claude-3-opus-20240229','claude-3-sonnet-20240229','claude-3-haiku-20240307'
</document-content></document><document index="2"><src>
sample_styles.css
</src><document-content>
.cell { margin-bottom: 1rem; }
.cell > .sourceCode { margin-bottom: 0; }
.cell-output > pre { margin-bottom: 0; }
</document-content></document></documents>
```
