Dynamic serializer for LLM Compact Hierarchical Formats.
Project description
LLM Compact Serializer
A dynamic, schema-driven Python library designed to drastically reduce LLM token usage by compressing complex JSON objects into a strict, hierarchical format.
๐ Why Use This?
When building LLM applications (using GPT-4, Gemini, Claude, etc.), passing large JSON arrays in the system prompt consumes a massive amount of tokens due to repeated keys and whitespace.
Standard JSON (Heavy):
[
{"product": "Apple", "price": "1.20", "category": "Fruit"},
{"product": "Banana", "price": "0.80", "category": "Fruit"}
]
Compact Protocol (Efficient):
|{Apple, 1.20, Fruit}|;|{Banana, 0.80, Fruit}|
Impact:
Reduces token count from ~55 tokens (JSON) to ~18 tokens (Compact) for this example.
Key Benefits
Token Efficiency: Reduces input payload size by 40-60% for repetitive data structures.
Schema Enforcement: Generates strict instructions for the LLM, reducing hallucinations.
Dynamic: Works with any Python object or dictionary; just define the schema at runtime.
Recursive: Supports deeply nested objects and lists via the |{...}| syntax.
๐ฆ Installation
Clone the repository
git clone https://github.com/Ryujose/llm-compact-serializer.git
Install dependencies using Poetry
poetry install
โก Quick Start
This example demonstrates how to serialize a product list with nested destination data.
- Define Your Schema Tell the serializer what your data looks like. Order matters!
from llm_compact_serializer.domain.schema import CompactSchema, FieldConfig
from llm_compact_serializer.core.prompt_builder import PromptBuilder
# Define a nested schema for complex objects
destination_schema = CompactSchema(
name="Destination",
fields=[
FieldConfig(source_name="address"),
FieldConfig(source_name="phones", is_list=True) # Handles arrays [x, y]
]
)
# Define the root schema
product_schema = CompactSchema(
name="Product",
fields=[
FieldConfig(source_name="name"),
FieldConfig(source_name="price"),
FieldConfig(source_name="destination", nested_schema=destination_schema)
]
)
- Prepare Your Data You can use Dictionaries, Pydantic models, or Dataclasses.
data = [
{
"name": "MacBook Pro",
"price": "1200โฌ",
"destination": {
"address": "Silicon Valley, CA",
"phones": [5550199, 5550200]
}
}
]
- Generate the Prompt The PromptBuilder automatically generates the protocol instructions and injects your compressed data.
builder = PromptBuilder(product_schema)
base_prompt = "Analyze the following orders: [INPUT]"
final_prompt = builder.build(base_prompt, data, data_marker="[INPUT]")
print(final_prompt)
- Output (What the LLM Sees)
[COMPACT_HIERARCHICAL_PROTOCOL]
[INSTRUCTIONS]
1. Interpret input strictly as a Recursive Compact Hierarchy.
2. Syntax: Complex objects enclosed in |{ }|, separated by comma.
3. Structure Mapping:
# 1 = Product (Root)
# 1a = name
# 1b = price
# 1.1 = destination
# 1.1a = address
# 1.1b* = phones
[END_PROTOCOL]
Analyze the following orders: |{MacBook Pro, 1200โฌ, |{Silicon Valley, CA, [5550199, 5550200]}|}|
๐ Architecture
The project follows Clean Architecture principles to ensure modularity and ease of testing.
llm-compact-serializer/
โโโ .github/
โ โโโ workflows/
โ โโโ ci.yml # CI/CD: Tests & Linting
โ โโโ publish.yml # CD: Publish to PyPI
โโโ src/
โ โโโ llm_compact_serializer/
โ โโโ __init__.py
โ โโโ domain/ # Schema definitions (The "Rules")
โ โ โโโ __init__.py
โ โ โโโ schema.py
โ โโโ core/ # The Engine (Generic Logic)
โ โโโ __init__.py
โ โโโ serializer.py
โโโ tests/
โ โโโ/ # more tests
โโโ LICENSE # MIT
โโโ README.md
โโโ pyproject.toml # Poetry Config
โโโ poetry.lock
The Protocol Rules
Object Wrapping: All objects are wrapped in |{ ... }|.
Separators: Fields are separated by ,. Objects in a list are separated by ;.
Recursion: A field can contain another object, creating a nested structure: |{ val1, |{ val2 }| }|.
Arrays: Simple lists are wrapped in [...].
Missing Data: None or empty values are automatically replaced with - to maintain positional integrity.
Sanitization: Commas found within data values are automatically replaced (e.g., Doe, John -> Doe John) to prevent parsing errors.
๐งช Testing
We use pytest for comprehensive testing, covering unit logic and end-to-end integration.
# Run all tests
poetry run pytest
# Run with coverage report
poetry run pytest --cov=src
Key Test Scenarios
test_serializer.py: Verifies primitive handling, recursive nesting logic, and sanitization (handling commas in data).
test_integration.py: Validates the full workflow (Schema -> Data -> Prompt) using complex real-world examples.
๐ค Contributing
-
Fork the repository.
-
Create a feature branch (git checkout -b feat/amazing-feature).
-
Commit your changes (git commit -m 'feat: Add amazing feature').
-
Push to the branch (git push origin feat/amazing-feature).
-
Open a Pull Request.
๐ License
Distributed under the MIT License. See LICENSE for more information.
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_compact_serializer-0.1.0.tar.gz.
File metadata
- Download URL: llm_compact_serializer-0.1.0.tar.gz
- Upload date:
- Size: 6.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.2.1 CPython/3.10.19 Linux/6.11.0-1018-azure
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0bc4b295643948da4c27a94e7dc6e7d6c8f5561cc714c100005d146a0c970811
|
|
| MD5 |
80c4486c2d9687e0def433a08512f8f4
|
|
| BLAKE2b-256 |
f1294e14a5699c66053803850a8c1df5347faf71594e6f9081ef7a12c355aa13
|
File details
Details for the file llm_compact_serializer-0.1.0-py3-none-any.whl.
File metadata
- Download URL: llm_compact_serializer-0.1.0-py3-none-any.whl
- Upload date:
- Size: 8.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.2.1 CPython/3.10.19 Linux/6.11.0-1018-azure
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f183d6e23ae7656ee1828d5c5b92acf4f0dda53dd2c1dd0d46e9ead9fb3d27fd
|
|
| MD5 |
dd17c5133aa49563a4e758baeaabfefb
|
|
| BLAKE2b-256 |
b4c0dbd9bc4fbc2c4a316d0934b512e33294c6f90feb2e592ec45b01b6876f05
|