Coverage for app / util / document.py: 80%
15 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2Utility for building structured XML document context for LLM prompts.
4Uses the <documents> format recommended by Anthropic for multi-document
5context, which generalises well across providers and makes file boundaries
6unambiguous to the model.
7"""
10def build_document_context_xml(
11 files: list,
12 *,
13 name_attr: str = "name",
14 content_attr: str = "content",
15) -> str:
16 """
17 Return an XML block representing a set of attached documents.
19 ``files`` may be either objects with attributes or dicts — ``name_attr``
20 and ``content_attr`` control which field names to read.
22 Returns an empty string when no file has non-whitespace content.
24 Example output::
26 <documents>
27 <document index="1">
28 <source>report.pdf</source>
29 <document_content>
30 Full parsed text of the report...
31 </document_content>
32 </document>
33 <document index="2">
34 <source>data.csv</source>
35 <document_content>
36 col1,col2
37 1,2
38 </document_content>
39 </document>
40 </documents>
41 """
42 parts: list[str] = []
43 for i, fc in enumerate(files, 1):
44 if isinstance(fc, dict):
45 name = fc.get(name_attr, "file")
46 content = fc.get(content_attr, "")
47 else:
48 name = getattr(fc, name_attr, "file")
49 content = getattr(fc, content_attr, "")
51 content = (content or "").strip()
52 if not content:
53 continue
55 parts.append(
56 f'<document index="{i}">\n'
57 f"<source>{name}</source>\n"
58 f"<document_content>\n{content}\n</document_content>\n"
59 f"</document>"
60 )
62 if not parts:
63 return ""
64 return "<documents>\n" + "\n".join(parts) + "\n</documents>"