JavaScript / TypeScript SDK
Brevit for JavaScript / TypeScript — compress JSON, text, and binary data before sending to LLMs. Reduce token costs by 40–60% with zero configuration.
Getting Started
Brevit is a drop-in library that transforms your data into a token-efficient format before it reaches your LLM. It works on JSON structures, plain text, and binary image data — and it's completely lossless by default.
Installation
$ npm install brevitRequires Node.js 18+ or a modern browser. ESM and CommonJS both supported.
import { BrevitClient, BrevitConfig } from 'brevit';const brevit = new BrevitClient();// Auto mode — Brevit picks the best strategyconst result = await brevit.brevity({ user: { name: 'Jane', email: 'jane@example.com' }, orders: [ { id: 'ORD-001', status: 'SHIPPED', total: 79.98 }, { id: 'ORD-002', status: 'PENDING', total: 29.99 } ]});console.log(result);// user.name:Jane// user.email:jane@example.com// orders[2]{id,status,total}:// ORD-001,SHIPPED,79.98// ORD-002,PENDING,29.99Configuration
Pass a config object to BrevitConfig to customize optimization behavior. All fields have sensible defaults — zero config is required for most use cases.
import { BrevitClient, BrevitConfig, JsonOptimizationMode, TextOptimizationMode } from 'brevit';const config = new BrevitConfig({ // JSON optimization strategy jsonMode: JsonOptimizationMode.Flatten, "color:#546e7a">// Flatten | ToYaml | Filter | None // Text optimization strategy textMode: TextOptimizationMode.Clean, "color:#546e7a">// None | Clean | SummarizeFast | SummarizeHighQuality // For Filter mode: paths to keep jsonPathsToKeep: [], // Minimum characters before text optimization triggers longTextThreshold: 500, // Enable @alias=prefix abbreviations (v0.1.2+) enableAbbreviations: true, // Min times a prefix must repeat before getting an alias abbreviationThreshold: 2,});const brevit = new BrevitClient(config);| Option | Default | Description |
|---|---|---|
jsonMode | Flatten | How to optimize JSON. Flatten produces dot-notation key-value pairs. |
textMode | Clean | How to handle long text strings in JSON values. |
imageMode | Ocr | Image optimization — OCR extracts text from images. |
enableAbbreviations | true | Auto-abbreviate repeated key prefixes with @alias syntax. |
abbreviationThreshold | 2 | Min times a prefix must repeat before it gets an alias. |
longTextThreshold | 500 | Char count threshold before text optimization triggers. |
JSON Optimization
Brevit's JSON optimizer uses a smart detection pipeline: nested objects become dot-notation paths, uniform object arrays become compact tabular format, and primitive arrays become comma-separated.
Nested Objects
user: { name: "J" }user.name:J
Primitive Arrays
["a", "b", "c"]
arr[3]:a,b,c
Object Arrays
[{ id:1 }, { id:2 }]arr[2]{id}:
1
2const brevit = new BrevitClient();// Nested object → dot notationconst flat = await brevit.optimize({ user: { id: "u-123", name: "Javian", contact: { email: "hi@example.com", phone: "+1-555-0123" } }});// user.id:u-123// user.name:Javian// user.contact.email:hi@example.com// user.contact.phone:+1-555-0123// Primitive array → comma-separatedconst arr = await brevit.optimize({ tags: ["json", "llm", "api"] });// tags[3]:json,llm,api// Uniform object array → tabular formatconst table = await brevit.optimize({ products: [ { sku: "A1", qty: 3, price: 9.99 }, { sku: "B2", qty: 1, price: 24.99 }, ]});// products[2]{sku,qty,price}:// A1,3,9.99// B2,1,24.99Abbreviation Engine
When the same key prefix appears ≥ abbreviationThreshold times, Brevit creates a short alias and replaces the prefix throughout — saving an additional 10–25% on top of flattening.
const config = new BrevitConfig({ enableAbbreviations: true, abbreviationThreshold: 2 });const brevit = new BrevitClient(config);const result = await brevit.optimize({ user: { name: "John", email: "john@example.com", role: "admin" }, order: { id: "o-456", status: "SHIPPED", total: 99.99 }});// Output with abbreviations:// @u=user// @o=order// @u.name:John// @u.email:john@example.com// @u.role:admin// @o.id:o-456// @o.status:SHIPPED// @o.total:99.99// Without abbreviations (disabled):const noAbbrevConfig = new BrevitConfig({ enableAbbreviations: false });const result2 = await new BrevitClient(noAbbrevConfig).optimize({ ... });// user.name:John// user.email:john@example.com// ...Alias Generation Strategy
- 1. First letter of root segment:
user → u - 2. First letter of each dot-segment:
order.items → oi - 3. Counter-based fallback:
a, b, c … z, aa, ab…
Text Optimization
Brevit uses a deterministic TextRank / PageRank-style algorithm over sentence similarity graphs. No LLM is required — it's purely extractive and always produces the same output for the same input.
AUTO Mode
With autoThresholdMultiplier = 0.0, all sentences pass the threshold → lossless by default.
RATIO Mode
Pass a ratio 0.0–1.0 to keep the top N% of sentences ranked by TextRank graph score.
const brevit = new BrevitClient();// compressText() — AUTO mode (lossless by default)// Runs TextRank analysis; with autoThresholdMultiplier=0, all sentences are kept.const compressed = await brevit.compressText(longDocument);// optimizeText() — RATIO mode (0.0 to 1.0)// Keeps the top-ranked N% of sentences by TextRank scoreconst summary = await brevit.optimizeText(longDocument, 0.5); "color:#546e7a">// keeps 50%// Through optimize() with ratioconst result = await brevit.optimize(longDocument, 0.3); "color:#546e7a">// keeps 30%// Through brevity() — auto-detects text and routes to compressTextconst auto = await brevit.brevity("This is a long article about AI...");Image Optimization
Pass a Uint8Array (JS),bytes (Python), orbyte[] (.NET) to the client and Brevit will route it through the configured image optimizer.
Custom Strategies
Extend Brevit with your own optimization logic. Register a strategy with an analyzer that scores how well it fits the data, and an optimizer that performs the transformation.
const brevit = new BrevitClient();// Register a custom strategybrevit.registerStrategy( 'my-strategy', // Analyzer: returns score 0-100 for how well this strategy fits the data (data) => ({ score: typeof data === 'object' && data.type === 'invoice' ? 95 : 0, reason: 'Invoice-specific optimization' }), // Optimizer: the actual transformation async (data) => { return `INV#${data.id} ${data.vendor} $${data.total}`; });API Reference
Core methods available on BrevitClient. All async methods return Promise<string> (JS/Python) or Task<string> (.NET).
| Method | Purpose |
|---|---|
brevity(data) | Auto-selects best strategy based on data analysis. Recommended entry point. |
optimize(data, ratio?) | Main pipeline: routes by type (JSON/text/image/POCO). Optional ratio for text. |
compressText(text) | Explicit TextRank AUTO mode — lossless by default. |
optimizeText(text, ratio) | Explicit TextRank RATIO mode — keeps top N% of sentences. |
registerStrategy(name, analyzer, optimizer) | Register a custom optimization strategy for use in brevity(). |
Real-World Examples
E-Commerce Orders
Compress customer orders and product data for LLM analysis.
Document Processing
Summarize legal documents and contracts before LLM review.
RAG Pipelines
Optimize retrieval chunks before injecting into LLM context.
Customer Support
Compress ticket history and chat logs for agent context.