跳转到内容

pydantic_ai.format_prompt

format_as_xml

format_as_xml(
    obj: Any,
    root_tag: str | None = None,
    item_tag: str = "item",
    none_str: str = "null",
    indent: str | None = "  ",
) -> str

将一个 Python 对象格式化为 XML。

这很有用,因为大型语言模型(LLM)通常更容易读取像 XML 这样的半结构化数据(例如示例),而不是 JSON 等格式。

支持:strbytesbytearrayboolintfloatdatedatetimeMappingIterabledataclassBaseModel

参数

名称 类型 描述 默认值
obj Any

要序列化为 XML 的 Python 对象。

必需
root_tag str | None

用于包裹 XML 的最外层标签,使用 None 可省略最外层标签。

None
item_tag str

用于可迭代对象(如列表)中每个项目的标签,对于数据类(dataclass)和 Pydantic 模型,此设置会被类名覆盖。

'item'
none_str str

用于表示 None 值的字符串。

'null'
indent str | None

用于美化打印的缩进字符串。

' '

返回

类型 描述
str

对象的 XML 表示形式。

示例

format_as_xml_example.py
from pydantic_ai import format_as_xml

print(format_as_xml({'name': 'John', 'height': 6, 'weight': 200}, root_tag='user'))
'''
<user>
  <name>John</name>
  <height>6</height>
  <weight>200</weight>
</user>
'''

源代码位于 pydantic_ai_slim/pydantic_ai/format_prompt.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def format_as_xml(
    obj: Any,
    root_tag: str | None = None,
    item_tag: str = 'item',
    none_str: str = 'null',
    indent: str | None = '  ',
) -> str:
    """Format a Python object as XML.

    This is useful since LLMs often find it easier to read semi-structured data (e.g. examples) as XML,
    rather than JSON etc.

    Supports: `str`, `bytes`, `bytearray`, `bool`, `int`, `float`, `date`, `datetime`, `Mapping`,
    `Iterable`, `dataclass`, and `BaseModel`.

    Args:
        obj: Python Object to serialize to XML.
        root_tag: Outer tag to wrap the XML in, use `None` to omit the outer tag.
        item_tag: Tag to use for each item in an iterable (e.g. list), this is overridden by the class name
            for dataclasses and Pydantic models.
        none_str: String to use for `None` values.
        indent: Indentation string to use for pretty printing.

    Returns:
        XML representation of the object.

    Example:
    ```python {title="format_as_xml_example.py" lint="skip"}
    from pydantic_ai import format_as_xml

    print(format_as_xml({'name': 'John', 'height': 6, 'weight': 200}, root_tag='user'))
    '''
    <user>
      <name>John</name>
      <height>6</height>
      <weight>200</weight>
    </user>
    '''
    ```
    """
    el = _ToXml(item_tag=item_tag, none_str=none_str).to_xml(obj, root_tag)
    if root_tag is None and el.text is None:
        join = '' if indent is None else '\n'
        return join.join(_rootless_xml_elements(el, indent))
    else:
        if indent is not None:
            ElementTree.indent(el, space=indent)
        return ElementTree.tostring(el, encoding='unicode')