Token-efficient code compression for Dart/Flutter and LLM contexts
Project description
COON: Code-Oriented Object Notation
Token-efficient code compression format for Dart/Flutter and LLM contexts
Overview
COON is a compression format designed to reduce token count in Dart/Flutter code by 60-70% while maintaining semantic meaning and reversibility. It addresses the token inefficiency problem in code transmission and storage for LLM-based applications.
Inspired by TOON (Token-Oriented Object Notation), COON applies similar compression principles to source code.
Problem
When working with Large Language Models in code generation:
- Raw code contains excessive whitespace and boilerplate
- Multi-agent systems transfer large amounts of code between agents
- Context windows fill quickly with uncompressed code
- API costs scale with token count
Solution
COON compresses code through:
- Keyword abbreviation
- Widget name shortening
- Property name compression
- Whitespace optimization
- Structure simplification
Example:
Before (150 tokens):
class LoginScreen extends StatelessWidget {
final TextEditingController emailController = TextEditingController();
final TextEditingController passwordController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Login"),
),
body: SafeArea(
child: Padding(
padding: EdgeInsets.all(24.0),
child: Column(
children: [
Text("Welcome Back"),
Text("Login to continue"),
],
),
),
),
);
}
}
After (45 tokens, 70% reduction):
c:LoginScreen<StatelessWidget>;f:emailController=X,passwordController=X;m:b S{a:B{t:T"Login"},b:A{c:P{p:@24,c:C{h:[T"Welcome Back",T"Login to continue"]}}}}
Installation
pip install coon-compress
Or install from source:
git clone https://github.com/affanshaikhsurab/COON.git
cd COON
pip install -e .
Usage
Python API
from coon import compress_dart, decompress_coon
# Compress code
dart_code = """
class MyWidget extends StatelessWidget {
Widget build(BuildContext context) {
return Text("Hello");
}
}
"""
compressed = compress_dart(dart_code)
print(compressed)
# Output: c:MyWidget<StatelessWidget>;m:b T"Hello"
# Decompress
original = decompress_coon(compressed)
Advanced Usage
from coon import Compressor
# Initialize with options
compressor = Compressor(
component_registry="components.json",
enable_metrics=True
)
# Compress with analysis
result = compressor.compress(
dart_code,
strategy="auto",
analyze_code=True,
validate=True
)
print(f"Tokens saved: {result.token_savings}")
print(f"Reduction: {result.percentage_saved:.1f}%")
Command Line
# Compress a file
coon compress input.dart -o output.coon
# Decompress
coon decompress output.coon -o generated.dart
# Show statistics
coon stats input.dart
Compression Methods
Keyword Abbreviation
class→c:final→f:return→retoverride→ removed
Widget Abbreviation
Scaffold→SColumn→CSafeArea→APadding→PText→T
Property Abbreviation
appBar:→a:body:→b:children:→h:padding:→p:
Special Notation
EdgeInsets.all(24)→@24Type()→~Typetrue/false→1/0
Compression Strategies
COON provides 6 compression strategies:
- AUTO - Automatic strategy selection based on code analysis
- BASIC - Simple abbreviations (40-50% reduction)
- AGGRESSIVE - Maximum compression (60-70% reduction)
- COMPONENT_REF - Uses component registry for reusable widgets
- AST_BASED - Abstract syntax tree analysis
- SEMANTIC - Preserves semantic meaning with optimization
Performance
Results from real benchmarks on Dart/Flutter code:
| Test Case | Original Tokens | Compressed Tokens | Reduction |
|---|---|---|---|
| Simple Widget | 33 | 13 | 60.6% |
| Login Screen | 405 | 121 | 70.1% |
| List View | 165 | 78 | 52.7% |
| Counter | 303 | 116 | 61.7% |
| Average | - | - | 61.3% |
For multi-agent systems:
- Uncompressed: 1,500 tokens (10 screens)
- Compressed: 580 tokens (10 screens)
- Savings: 920 tokens (61%)
Cost impact at GPT-4 pricing ($0.03/1K input, $0.06/1K output):
- Savings per 100K tokens: ~$5.50
Use Cases
Multi-Agent Code Generation
Pass compressed code between agents to reduce context usage:
# Agent 1 generates screen
screen_code = generate_screen("LoginScreen")
compressed = compress_dart(screen_code)
# Agent 2 receives compressed version
context_manager.store("LoginScreen", compressed)
LLM Context Optimization
Fit more code examples in prompts:
prompt = f"""
Example screens in COON format:
{compress_dart(screen1)}
{compress_dart(screen2)}
Generate similar screen for: {user_request}
"""
Code Storage
Store code artifacts efficiently:
db.save("artifact", compress_dart(code), {"format": "coon"})
API Reference
Core Functions
compress_dart(code, strategy="auto")
- Compresses Dart code
- Returns compressed string
decompress_coon(compressed_code)
- Decompresses COON format
- Returns original Dart code
Compressor Class
Compressor(component_registry=None, enable_metrics=False)
- Advanced compression with options
- Supports metrics collection and validation
Analysis Tools
CodeAnalyzer.analyze(code)
- Analyzes code for compression opportunities
- Returns analysis results
MetricsCollector
- Tracks compression performance
- Generates reports and statistics
Full API documentation: docs/API.md
Advanced Features
Component Registry
Register reusable components:
from coon import ComponentRegistry
registry = ComponentRegistry()
registry.register_component(
id="email_input",
code=email_field_code,
parameters=["controller", "label"]
)
Metrics Collection
Track compression performance:
compressor = Compressor(enable_metrics=True)
# ... perform compressions ...
print(compressor.metrics.generate_report())
Validation
Verify compression reversibility:
from coon import CompressionValidator
validator = CompressionValidator()
result = validator.validate_compression(
original_code,
compressed_code,
decompressed_code
)
Architecture
COON/
├── coon/
│ ├── __init__.py # Package entry point
│ ├── compressor.py # Core compression engine
│ ├── strategy.py # Compression strategies
│ ├── parser.py # Dart code parser
│ ├── analyzer.py # Code analysis
│ ├── registry.py # Component registry
│ ├── metrics.py # Performance metrics
│ ├── formatter.py # Code formatting
│ ├── validator.py # Validation tools
│ └── cli.py # Command-line interface
├── docs/ # Documentation
├── tests/ # Test suite
├── benchmarks/ # Performance benchmarks
└── examples/ # Usage examples
Requirements
- Python 3.8 or higher
- click >= 8.0.0 (for CLI)
Development
Setup Development Environment
git clone https://github.com/affanshaikhsurab/COON.git
cd COON
pip install -e ".[dev]"
Run Tests
pytest tests/
Run Benchmarks
cd benchmarks
python benchmark.py
Limitations
- Designed for Dart/Flutter code (other languages not supported)
- Comments are removed during compression
- Code formatting is not preserved (can be restored with formatter)
- Requires valid Dart syntax
Roadmap
- VS Code extension
- Multi-language support (Kotlin, Swift)
- npm package for JavaScript/TypeScript
- Web-based demo
Contributing
Contributions are welcome. Please read CONTRIBUTING.md for guidelines.
License
This project is licensed under the MIT License. See LICENSE for details.
Contact
- Author: Affan Shaikhsurab
- Email: affanshaikhsurabofficial@gmail.com
- GitHub: @AffanShaikhsurab
- Twitter: @AffanShaikhsurab
Acknowledgments
Inspired by TOON by Context7.
Statistics
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 coon-0.1.0.tar.gz.
File metadata
- Download URL: coon-0.1.0.tar.gz
- Upload date:
- Size: 32.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
8dbb089e09c1d7dfeead82b68768ea23af06a6bc6be7d48a385f4644e8d898e8
|
|
| MD5 |
a78430e23f89c7c70888fd17fb383ce2
|
|
| BLAKE2b-256 |
a2b2d4b14eed03241a5dbaa3758ddb64ab8c529b9794c0dedd66dc8cfcb21c51
|
File details
Details for the file coon-0.1.0-py3-none-any.whl.
File metadata
- Download URL: coon-0.1.0-py3-none-any.whl
- Upload date:
- Size: 32.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5402637cd82f95b004fc4b8eba97bf7df8f3412a38cab2a105507b91df533cb4
|
|
| MD5 |
12f1bfe02386559c752327f5e0755cfa
|
|
| BLAKE2b-256 |
c5e81a6c95b2185a3f2364ff16a1eaa50a29dbbf093ce223bd5dbae13409fa89
|