Skip to main content

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.

  1. 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)
    ]
)
  1. 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]
        }
    }
]
  1. 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)
  1. 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

  1. Fork the repository.

  2. Create a feature branch (git checkout -b feat/amazing-feature).

  3. Commit your changes (git commit -m 'feat: Add amazing feature').

  4. Push to the branch (git push origin feat/amazing-feature).

  5. Open a Pull Request.

๐Ÿ“„ License

Distributed under the MIT License. See LICENSE for more information.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

llm_compact_serializer-0.1.0.tar.gz (6.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

llm_compact_serializer-0.1.0-py3-none-any.whl (8.1 kB view details)

Uploaded Python 3

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

Hashes for llm_compact_serializer-0.1.0.tar.gz
Algorithm Hash digest
SHA256 0bc4b295643948da4c27a94e7dc6e7d6c8f5561cc714c100005d146a0c970811
MD5 80c4486c2d9687e0def433a08512f8f4
BLAKE2b-256 f1294e14a5699c66053803850a8c1df5347faf71594e6f9081ef7a12c355aa13

See more details on using hashes here.

File details

Details for the file llm_compact_serializer-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for llm_compact_serializer-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f183d6e23ae7656ee1828d5c5b92acf4f0dda53dd2c1dd0d46e9ead9fb3d27fd
MD5 dd17c5133aa49563a4e758baeaabfefb
BLAKE2b-256 b4c0dbd9bc4fbc2c4a316d0934b512e33294c6f90feb2e592ec45b01b6876f05

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page