Parse the frontmatter of a memory doc into a dict, or None if it has none. Returns the recognised fields (``type``, ``date``, ``question``, ``outcome``, ``correction``, ``source_nodes``). ``source_nodes`` is always a list.
(text: str)
| 102 | |
| 103 | |
| 104 | def parse_memory_doc(text: str) -> dict[str, Any] | None: |
| 105 | """Parse the frontmatter of a memory doc into a dict, or None if it has none. |
| 106 | |
| 107 | Returns the recognised fields (``type``, ``date``, ``question``, ``outcome``, |
| 108 | ``correction``, ``source_nodes``). ``source_nodes`` is always a list. |
| 109 | """ |
| 110 | if not text.startswith("---"): |
| 111 | return None |
| 112 | lines = text.splitlines() |
| 113 | if not lines or lines[0].strip() != "---": |
| 114 | return None |
| 115 | fields: dict[str, Any] = {"source_nodes": []} |
| 116 | for line in lines[1:]: |
| 117 | if line.strip() == "---": |
| 118 | break |
| 119 | m = _LIST_RE.match(line) |
| 120 | if m and m.group(1) == "source_nodes": |
| 121 | fields["source_nodes"] = [ |
| 122 | _yaml_unescape(item) for item in _DQ_ITEM_RE.findall(m.group(2)) |
| 123 | ] |
| 124 | continue |
| 125 | m = _SCALAR_RE.match(line) |
| 126 | if m: |
| 127 | key, val = m.group(1), _yaml_unescape(m.group(2)) |
| 128 | if key in ("type", "date", "question", "outcome", "correction", "contributor"): |
| 129 | fields[key] = val |
| 130 | return fields |
| 131 | |
| 132 | |
| 133 | def load_memory_docs(memory_dir: Path) -> list[dict[str, Any]]: |