A dataclass interface for llms
Project description
llm-dataclass
A Python library that provides a dataclass interface for working with XML schemas, specifically designed for LLM (Large Language Model) interactions. This library allows you to define structured data using Python dataclasses and automatically generate XML schemas or parse XML responses into strongly-typed Python objects.
Table of Contents
Features
- 🔗 Seamless XML-Dataclass Integration: Convert between Python dataclasses and XML effortlessly
- 📝 Schema Generation: Automatically generate XML schemas from dataclass definitions
- 🔄 Bidirectional Conversion: Parse XML into dataclass instances and serialize dataclass instances to XML
- 🏗️ Nested Structure Support: Handle complex nested dataclass structures
- 📋 List/Array Support: Work with lists of primitive types and dataclass objects
- ⚡ Type Safety: Leverages Python's type hints for validation and parsing
- 🎯 LLM-Friendly: Designed specifically for LLM prompt engineering and response parsing
Installation
pip install llm-dataclass
Quick Start
Parsing XML to Dataclass Objects
Parse XML responses from LLMs into strongly-typed Python objects:
from dataclasses import dataclass
import llm_dataclass
@dataclass
class Person:
name: str
age: int
# Create a schema with custom root element name
schema = llm_dataclass.Schema(Person, root="user")
# Parse XML response from LLM
xml_response = """
This is your response:
<user>
<name>John Doe</name>
<age>30</age>
</user>
Let me know if you need anything else.
"""
person = schema.loads(xml_response)
print(person) # Person(name='John Doe', age=30)
Generating XML Templates for Prompts
Generate XML templates to include in LLM prompts as response format examples:
from dataclasses import dataclass
import llm_dataclass
@dataclass
class Person:
name: str
age: int
# Create schema with custom root - useful when you want specific XML tag names
schema = llm_dataclass.Schema(Person, root="employee")
# Generate empty XML template for LLM prompts
xml_template = schema.dumps()
print(xml_template)
# Output:
# <employee>
# <name>...</name>
# <age>...</age>
# </employee>
Serializing Dataclass Instances to XML
Convert Python dataclass instances into XML format:
from dataclasses import dataclass
import llm_dataclass
@dataclass
class Person:
name: str
age: int
# Use default root (dataclass name) or specify custom root
schema = llm_dataclass.Schema(Person, root="contact")
# Create a dataclass instance
person = Person(name="Alice Smith", age=25)
# Serialize to XML
xml_output = schema.dumps(person)
print(xml_output)
# Output:
# <contact>
# <name>Alice Smith</name>
# <age>25</age>
# </contact>
Usage
Basic Dataclass Schema
Define your data structure using Python dataclasses:
from dataclasses import dataclass
import llm_dataclass
@dataclass
class Product:
name: str
price: float
in_stock: bool
schema = llm_dataclass.Schema(Product)
Generating XML Schemas
Generate XML templates for LLM prompts:
# Generate empty template
template = schema.dumps()
# Generate template with example data
example_product = Product(name="Widget", price=19.99, in_stock=True)
template_with_data = schema.dumps(example_product)
Parsing XML Responses
Parse XML responses from LLMs into typed Python objects:
xml_response = """<Product>
<name>Super Widget</name>
<price>29.99</price>
<in_stock>true</in_stock>
</Product>"""
product = schema.loads(xml_response)
# Returns: Product(name='Super Widget', price=29.99, in_stock=True)
Working with Lists
Handle lists of primitive types or objects:
from dataclasses import dataclass, field
@dataclass
class ShoppingList:
items: list[str] = field(metadata={"xml": {"name": "item"}})
schema = llm_dataclass.Schema(ShoppingList)
# Parsing XML with multiple items
xml_data = """<ShoppingList>
<item>Apples</item>
<item>Bananas</item>
<item>Cherries</item>
</ShoppingList>"""
shopping_list = schema.loads(xml_data)
# Returns: ShoppingList(items=['Apples', 'Bananas', 'Cherries'])
Nested Dataclasses
Support for complex nested structures:
@dataclass
class Address:
street: str
city: str
zipcode: str
@dataclass
class Person:
name: str
address: Address
schema = llm_dataclass.Schema(Person)
xml_data = """<Person>
<name>Jane Smith</name>
<address>
<street>123 Main St</street>
<city>Anytown</city>
<zipcode>12345</zipcode>
</address>
</Person>"""
person = schema.loads(xml_data)
Optional Fields
Handle optional fields with proper type annotations:
from typing import Optional
@dataclass
class User:
username: str
email: Optional[str] = None
age: Optional[int] = None
schema = llm_dataclass.Schema(User)
Custom XML Field Names
Customize XML element names using field metadata:
@dataclass
class Book:
title: str
author_name: str = field(metadata={"xml": {"name": "author"}})
schema = llm_dataclass.Schema(Book)
# Will use <author> instead of <author_name> in XML
Handling Extra Data
The library is designed to be robust when working with LLM responses:
- Extra text before/after XML: Automatically extracts XML from responses containing additional explanatory text
- Extra XML elements: Ignores XML elements that don't correspond to dataclass fields
- Flexible parsing: Only extracts the specific data defined in your dataclass schema
Type Support
The library supports the following Python types:
- Primitive types:
str,int,float,bool - Optional types:
Optional[T]orUnion[T, None] - Lists:
list[T]orList[T] - Nested dataclasses: Any dataclass type
- Custom types: Any type with a constructor that accepts a string
Convenience Wrappers: The library also provides simple wrapper dataclasses (StrWrapper, IntWrapper, FloatWrapper, BoolWrapper) for scenarios where you need to wrap primitive values in a root XML element.
Limitations
To ensure robust XML parsing, the library has some intentional limitations:
- No XML attributes: XML attributes are not supported - only XML elements are parsed
- No nested lists:
List[List[T]]is not supported - No optional lists:
Optional[List[T]]is not supported (useList[T]with empty list handling) - No list of optionals:
List[Optional[T]]is not supported - Union types: Only
Optional[T](Union with None) is supported
These limitations help prevent ambiguous XML structures and parsing edge cases.
Examples
You can find more examples in the examples section of the repository, demonstrating various use cases and features of the llm-dataclass library.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
License
llm-dataclass is distributed under the terms of the MIT license.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file llm_dataclass-1.0.0.post1.tar.gz.
File metadata
- Download URL: llm_dataclass-1.0.0.post1.tar.gz
- Upload date:
- Size: 46.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1cafe37f51f15309c94836e578087824a74b36c26a8db0cd2e00bf07846d5707
|
|
| MD5 |
20c0b0277125c8005e19e42124379af4
|
|
| BLAKE2b-256 |
f7c3b225e37f30ca678e2d05e47fcde8043296767dd514890e74be318bb53e67
|
Provenance
The following attestation bundles were made for llm_dataclass-1.0.0.post1.tar.gz:
Publisher:
release.yml on bytehexe/llm-dataclass
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
llm_dataclass-1.0.0.post1.tar.gz -
Subject digest:
1cafe37f51f15309c94836e578087824a74b36c26a8db0cd2e00bf07846d5707 - Sigstore transparency entry: 668004671
- Sigstore integration time:
-
Permalink:
bytehexe/llm-dataclass@b6b464b9cd08e8f553ef5a56c47d095feb740448 -
Branch / Tag:
refs/tags/1.0.0post1 - Owner: https://github.com/bytehexe
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@b6b464b9cd08e8f553ef5a56c47d095feb740448 -
Trigger Event:
push
-
Statement type:
File details
Details for the file llm_dataclass-1.0.0.post1-py3-none-any.whl.
File metadata
- Download URL: llm_dataclass-1.0.0.post1-py3-none-any.whl
- Upload date:
- Size: 8.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
edbdf7036a957331f765b395e8ed0f6251b8fe94c23285a0da9b780888edc3e2
|
|
| MD5 |
418c8cbfc2c2877a51fb04991381e64d
|
|
| BLAKE2b-256 |
59b05218681bb32381994abc7b3d3096098ba7061aed92efbdef388fbe63ad4e
|
Provenance
The following attestation bundles were made for llm_dataclass-1.0.0.post1-py3-none-any.whl:
Publisher:
release.yml on bytehexe/llm-dataclass
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
llm_dataclass-1.0.0.post1-py3-none-any.whl -
Subject digest:
edbdf7036a957331f765b395e8ed0f6251b8fe94c23285a0da9b780888edc3e2 - Sigstore transparency entry: 668004675
- Sigstore integration time:
-
Permalink:
bytehexe/llm-dataclass@b6b464b9cd08e8f553ef5a56c47d095feb740448 -
Branch / Tag:
refs/tags/1.0.0post1 - Owner: https://github.com/bytehexe
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@b6b464b9cd08e8f553ef5a56c47d095feb740448 -
Trigger Event:
push
-
Statement type: