brevit 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +23 -0
- package/README.md +1237 -0
- package/TYPESCRIPT.md +230 -0
- package/example.ts +139 -0
- package/package.json +31 -0
- package/src/brevit.d.ts +212 -0
- package/src/brevit.js +589 -0
- package/test/test.js +90 -0
- package/tsconfig.json +23 -0
package/README.md
ADDED
|
@@ -0,0 +1,1237 @@
|
|
|
1
|
+
# Brevit.js
|
|
2
|
+
|
|
3
|
+
A high-performance JavaScript library for semantically compressing and optimizing data before sending it to a Large Language Model (LLM). Dramatically reduce token costs while maintaining data integrity and readability.
|
|
4
|
+
|
|
5
|
+
## Table of Contents
|
|
6
|
+
|
|
7
|
+
- [Why Brevit.js?](#why-brevitjs)
|
|
8
|
+
- [Key Features](#key-features)
|
|
9
|
+
- [When Not to Use Brevit.js](#when-not-to-use-brevitjs)
|
|
10
|
+
- [Benchmarks](#benchmarks)
|
|
11
|
+
- [Installation & Quick Start](#installation--quick-start)
|
|
12
|
+
- [Playgrounds](#playgrounds)
|
|
13
|
+
- [CLI](#cli)
|
|
14
|
+
- [Format Overview](#format-overview)
|
|
15
|
+
- [API](#api)
|
|
16
|
+
- [Using Brevit.js in LLM Prompts](#using-brevitjs-in-llm-prompts)
|
|
17
|
+
- [Syntax Cheatsheet](#syntax-cheatsheet)
|
|
18
|
+
- [Other Implementations](#other-implementations)
|
|
19
|
+
- [Full Specification](#full-specification)
|
|
20
|
+
|
|
21
|
+
## Why Brevit.js?
|
|
22
|
+
|
|
23
|
+
### JavaScript-Specific Advantages
|
|
24
|
+
|
|
25
|
+
- **Zero Dependencies**: Core library has no dependencies - lightweight and fast
|
|
26
|
+
- **Universal**: Works in Node.js, browsers, Deno, and Bun
|
|
27
|
+
- **TypeScript Support**: Full type definitions included
|
|
28
|
+
- **ES Modules**: Modern ES module support
|
|
29
|
+
- **Tree-Shakeable**: Only import what you need
|
|
30
|
+
|
|
31
|
+
### Performance Benefits
|
|
32
|
+
|
|
33
|
+
- **40-60% Token Reduction**: Dramatically reduce LLM API costs
|
|
34
|
+
- **Fast Execution**: Optimized algorithms for minimal overhead
|
|
35
|
+
- **Memory Efficient**: Processes data in-place where possible
|
|
36
|
+
- **Async/Await**: Non-blocking operations for better scalability
|
|
37
|
+
|
|
38
|
+
### Example Cost Savings
|
|
39
|
+
|
|
40
|
+
```javascript
|
|
41
|
+
// Before: 234 tokens = $0.000468 per request
|
|
42
|
+
const json = JSON.stringify(complexOrder);
|
|
43
|
+
|
|
44
|
+
// After: 127 tokens = $0.000254 per request (46% reduction)
|
|
45
|
+
const optimized = await brevit.brevity(complexOrder); // Automatic optimization
|
|
46
|
+
|
|
47
|
+
// Or with explicit configuration
|
|
48
|
+
const explicit = await brevit.optimize(complexOrder);
|
|
49
|
+
|
|
50
|
+
// Savings: $0.000214 per request
|
|
51
|
+
// At 1M requests/month: $214/month savings
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
### Automatic Strategy Selection
|
|
55
|
+
|
|
56
|
+
Brevit.js now includes the `.brevity()` method that automatically analyzes your data and selects the optimal optimization strategy:
|
|
57
|
+
|
|
58
|
+
```javascript
|
|
59
|
+
const data = {
|
|
60
|
+
friends: ["ana", "luis", "sam"],
|
|
61
|
+
hikes: [
|
|
62
|
+
{id: 1, name: "Blue Lake Trail", distanceKm: 7.5},
|
|
63
|
+
{id: 2, name: "Ridge Overlook", distanceKm: 9.2}
|
|
64
|
+
]
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
// Automatically detects uniform arrays and applies tabular format
|
|
68
|
+
const optimized = await brevit.brevity(data);
|
|
69
|
+
// No configuration needed - Brevit analyzes and optimizes automatically!
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Key Features
|
|
73
|
+
|
|
74
|
+
- **JSON Optimization**: Flatten nested JSON structures into token-efficient key-value pairs
|
|
75
|
+
- **Text Optimization**: Clean and summarize long text documents
|
|
76
|
+
- **Image Optimization**: Extract text from images via OCR
|
|
77
|
+
- **Lightweight**: Zero dependencies (optional YAML support)
|
|
78
|
+
- **Universal**: Works in Node.js, browsers, and modern JavaScript environments
|
|
79
|
+
- **Type-Safe**: Full TypeScript definitions included
|
|
80
|
+
|
|
81
|
+
## Installation
|
|
82
|
+
|
|
83
|
+
### npm
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
npm install brevit-js
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### yarn
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
yarn add brevit-js
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### pnpm
|
|
96
|
+
|
|
97
|
+
```bash
|
|
98
|
+
pnpm add brevit-js
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
### CDN (Browser)
|
|
102
|
+
|
|
103
|
+
```html
|
|
104
|
+
<script type="module">
|
|
105
|
+
import { BrevitClient, BrevitConfig, JsonOptimizationMode } from 'https://cdn.jsdelivr.net/npm/brevit-js@latest/src/brevit.js';
|
|
106
|
+
</script>
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## Quick Start
|
|
110
|
+
|
|
111
|
+
### TypeScript Support
|
|
112
|
+
|
|
113
|
+
Brevit.js includes full TypeScript definitions. Simply import and use with full type safety:
|
|
114
|
+
|
|
115
|
+
```typescript
|
|
116
|
+
import {
|
|
117
|
+
BrevitClient,
|
|
118
|
+
BrevitConfig,
|
|
119
|
+
JsonOptimizationMode,
|
|
120
|
+
type BrevitConfigOptions,
|
|
121
|
+
} from 'brevit-js';
|
|
122
|
+
|
|
123
|
+
const config: BrevitConfigOptions = {
|
|
124
|
+
jsonMode: JsonOptimizationMode.Flatten,
|
|
125
|
+
longTextThreshold: 1000,
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
const client = new BrevitClient(new BrevitConfig(config));
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
## Complete Usage Examples
|
|
132
|
+
|
|
133
|
+
Brevit.js supports three main data types: **JSON objects/strings**, **text files/strings**, and **images**. Here's how to use each:
|
|
134
|
+
|
|
135
|
+
### 1. JSON Optimization Examples
|
|
136
|
+
|
|
137
|
+
#### Example 1.1: Simple JSON Object
|
|
138
|
+
|
|
139
|
+
```javascript
|
|
140
|
+
import { BrevitClient, BrevitConfig, JsonOptimizationMode } from 'brevit-js';
|
|
141
|
+
|
|
142
|
+
const brevit = new BrevitClient(new BrevitConfig({
|
|
143
|
+
jsonMode: JsonOptimizationMode.Flatten
|
|
144
|
+
}));
|
|
145
|
+
|
|
146
|
+
const data = {
|
|
147
|
+
user: {
|
|
148
|
+
name: "John Doe",
|
|
149
|
+
email: "john@example.com",
|
|
150
|
+
age: 30
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
// Method 1: Automatic optimization (recommended)
|
|
155
|
+
const optimized = await brevit.brevity(data);
|
|
156
|
+
// Output:
|
|
157
|
+
// user.name:John Doe
|
|
158
|
+
// user.email:john@example.com
|
|
159
|
+
// user.age:30
|
|
160
|
+
|
|
161
|
+
// Method 2: Explicit optimization
|
|
162
|
+
const explicit = await brevit.optimize(data);
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
#### Example 1.2: JSON String
|
|
166
|
+
|
|
167
|
+
```javascript
|
|
168
|
+
const jsonString = '{"order": {"id": "o-456", "status": "SHIPPED"}}';
|
|
169
|
+
|
|
170
|
+
// Brevit automatically detects JSON strings
|
|
171
|
+
const optimized = await brevit.brevity(jsonString);
|
|
172
|
+
// Output:
|
|
173
|
+
// order.id:o-456
|
|
174
|
+
// order.status:SHIPPED
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
#### Example 1.3: Complex Nested JSON with Arrays
|
|
178
|
+
|
|
179
|
+
```javascript
|
|
180
|
+
const complexData = {
|
|
181
|
+
context: {
|
|
182
|
+
task: "Our favorite hikes together",
|
|
183
|
+
location: "Boulder",
|
|
184
|
+
season: "spring_2025"
|
|
185
|
+
},
|
|
186
|
+
friends: ["ana", "luis", "sam"],
|
|
187
|
+
hikes: [
|
|
188
|
+
{
|
|
189
|
+
id: 1,
|
|
190
|
+
name: "Blue Lake Trail",
|
|
191
|
+
distanceKm: 7.5,
|
|
192
|
+
elevationGain: 320,
|
|
193
|
+
companion: "ana",
|
|
194
|
+
wasSunny: true
|
|
195
|
+
},
|
|
196
|
+
{
|
|
197
|
+
id: 2,
|
|
198
|
+
name: "Ridge Overlook",
|
|
199
|
+
distanceKm: 9.2,
|
|
200
|
+
elevationGain: 540,
|
|
201
|
+
companion: "luis",
|
|
202
|
+
wasSunny: false
|
|
203
|
+
}
|
|
204
|
+
]
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
const optimized = await brevit.brevity(complexData);
|
|
208
|
+
// Output:
|
|
209
|
+
// context.task:Our favorite hikes together
|
|
210
|
+
// context.location:Boulder
|
|
211
|
+
// context.season:spring_2025
|
|
212
|
+
// friends[3]:ana,luis,sam
|
|
213
|
+
// hikes[2]{companion,distanceKm,elevationGain,id,name,wasSunny}:
|
|
214
|
+
// ana,7.5,320,1,Blue Lake Trail,true
|
|
215
|
+
// luis,9.2,540,2,Ridge Overlook,false
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
#### Example 1.4: Different JSON Optimization Modes
|
|
219
|
+
|
|
220
|
+
```javascript
|
|
221
|
+
// Flatten Mode (Default)
|
|
222
|
+
const flattenConfig = new BrevitConfig({
|
|
223
|
+
jsonMode: JsonOptimizationMode.Flatten
|
|
224
|
+
});
|
|
225
|
+
// Converts nested JSON to flat key-value pairs
|
|
226
|
+
|
|
227
|
+
// YAML Mode
|
|
228
|
+
const yamlConfig = new BrevitConfig({
|
|
229
|
+
jsonMode: JsonOptimizationMode.ToYaml
|
|
230
|
+
});
|
|
231
|
+
// Converts JSON to YAML format (requires js-yaml package)
|
|
232
|
+
|
|
233
|
+
// Filter Mode
|
|
234
|
+
const filterConfig = new BrevitConfig({
|
|
235
|
+
jsonMode: JsonOptimizationMode.Filter,
|
|
236
|
+
jsonPathsToKeep: ["user.name", "order.id"]
|
|
237
|
+
});
|
|
238
|
+
// Keeps only specified paths, removes everything else
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
### 2. Text Optimization Examples
|
|
242
|
+
|
|
243
|
+
#### Example 2.1: Long Text String
|
|
244
|
+
|
|
245
|
+
```javascript
|
|
246
|
+
const longText = `
|
|
247
|
+
This is a very long document that contains a lot of information.
|
|
248
|
+
It has multiple paragraphs and sections.
|
|
249
|
+
The text goes on for many lines...
|
|
250
|
+
[Repeated content many times]
|
|
251
|
+
`.repeat(50);
|
|
252
|
+
|
|
253
|
+
// Automatic detection: If text exceeds threshold, applies text optimization
|
|
254
|
+
const optimized = await brevit.brevity(longText);
|
|
255
|
+
|
|
256
|
+
// Explicit text optimization
|
|
257
|
+
const config = new BrevitConfig({
|
|
258
|
+
textMode: TextOptimizationMode.Clean,
|
|
259
|
+
longTextThreshold: 500 // Characters threshold
|
|
260
|
+
});
|
|
261
|
+
const brevitWithText = new BrevitClient(config);
|
|
262
|
+
const cleaned = await brevitWithText.optimize(longText);
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
#### Example 2.2: Reading Text from File (Node.js)
|
|
266
|
+
|
|
267
|
+
```javascript
|
|
268
|
+
import fs from 'fs/promises';
|
|
269
|
+
|
|
270
|
+
// Read text file
|
|
271
|
+
const textContent = await fs.readFile('document.txt', 'utf-8');
|
|
272
|
+
|
|
273
|
+
// Optimize the text
|
|
274
|
+
const optimized = await brevit.brevity(textContent);
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
#### Example 2.3: Text Optimization Modes
|
|
278
|
+
|
|
279
|
+
```javascript
|
|
280
|
+
// Clean Mode (Remove Boilerplate)
|
|
281
|
+
const cleanConfig = new BrevitConfig({
|
|
282
|
+
textMode: TextOptimizationMode.Clean
|
|
283
|
+
});
|
|
284
|
+
// Removes signatures, headers, repetitive content
|
|
285
|
+
|
|
286
|
+
// Summarize Fast
|
|
287
|
+
const fastConfig = new BrevitConfig({
|
|
288
|
+
textMode: TextOptimizationMode.SummarizeFast
|
|
289
|
+
});
|
|
290
|
+
// Fast summarization (requires custom text optimizer implementation)
|
|
291
|
+
|
|
292
|
+
// Summarize High Quality
|
|
293
|
+
const qualityConfig = new BrevitConfig({
|
|
294
|
+
textMode: TextOptimizationMode.SummarizeHighQuality
|
|
295
|
+
});
|
|
296
|
+
// High-quality summarization (requires custom text optimizer with LLM integration)
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
### 3. Image Optimization Examples
|
|
300
|
+
|
|
301
|
+
#### Example 3.1: Image from File (OCR) - Node.js
|
|
302
|
+
|
|
303
|
+
```javascript
|
|
304
|
+
import fs from 'fs/promises';
|
|
305
|
+
|
|
306
|
+
// Read image file as bytes
|
|
307
|
+
const imageBytes = await fs.readFile('receipt.jpg');
|
|
308
|
+
const imageBuffer = Buffer.from(imageBytes);
|
|
309
|
+
|
|
310
|
+
// Brevit automatically detects image data (ArrayBuffer/Buffer)
|
|
311
|
+
const extractedText = await brevit.brevity(imageBuffer);
|
|
312
|
+
// Output: OCR-extracted text from the image
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
#### Example 3.2: Image from URL - Node.js
|
|
316
|
+
|
|
317
|
+
```javascript
|
|
318
|
+
import fetch from 'node-fetch';
|
|
319
|
+
|
|
320
|
+
// Fetch image from URL
|
|
321
|
+
const response = await fetch('https://example.com/invoice.png');
|
|
322
|
+
const imageBuffer = await response.buffer();
|
|
323
|
+
|
|
324
|
+
// Optimize image
|
|
325
|
+
const extractedText = await brevit.brevity(imageBuffer);
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
#### Example 3.3: Image from File Input (Browser)
|
|
329
|
+
|
|
330
|
+
```html
|
|
331
|
+
<input type="file" id="imageInput" accept="image/*">
|
|
332
|
+
|
|
333
|
+
<script type="module">
|
|
334
|
+
import { BrevitClient, BrevitConfig } from './src/brevit.js';
|
|
335
|
+
|
|
336
|
+
const brevit = new BrevitClient(new BrevitConfig());
|
|
337
|
+
|
|
338
|
+
document.getElementById('imageInput').addEventListener('change', async (e) => {
|
|
339
|
+
const file = e.target.files[0];
|
|
340
|
+
const arrayBuffer = await file.arrayBuffer();
|
|
341
|
+
|
|
342
|
+
// Optimize image
|
|
343
|
+
const extractedText = await brevit.brevity(arrayBuffer);
|
|
344
|
+
console.log('Extracted text:', extractedText);
|
|
345
|
+
});
|
|
346
|
+
</script>
|
|
347
|
+
```
|
|
348
|
+
|
|
349
|
+
#### Example 3.4: Image Optimization Modes
|
|
350
|
+
|
|
351
|
+
```javascript
|
|
352
|
+
// OCR Mode (Extract Text)
|
|
353
|
+
const ocrConfig = new BrevitConfig({
|
|
354
|
+
imageMode: ImageOptimizationMode.Ocr
|
|
355
|
+
});
|
|
356
|
+
// Extracts text from images using OCR (requires custom image optimizer)
|
|
357
|
+
|
|
358
|
+
// Metadata Mode
|
|
359
|
+
const metadataConfig = new BrevitConfig({
|
|
360
|
+
imageMode: ImageOptimizationMode.Metadata
|
|
361
|
+
});
|
|
362
|
+
// Extracts only image metadata (dimensions, format, etc.)
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
### 4. Method Comparison: `.brevity()` vs `.optimize()`
|
|
366
|
+
|
|
367
|
+
#### `.brevity()` - Automatic Strategy Selection
|
|
368
|
+
|
|
369
|
+
**Use when:** You want Brevit to automatically analyze and select the best optimization strategy.
|
|
370
|
+
|
|
371
|
+
```javascript
|
|
372
|
+
// Automatically detects data type and applies optimal strategy
|
|
373
|
+
const result = await brevit.brevity(data);
|
|
374
|
+
// - JSON objects → Flatten with tabular optimization
|
|
375
|
+
// - Long text → Text optimization
|
|
376
|
+
// - Images → OCR extraction
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
**Advantages:**
|
|
380
|
+
- Zero configuration needed
|
|
381
|
+
- Intelligent strategy selection
|
|
382
|
+
- Works with any data type
|
|
383
|
+
- Best for general-purpose use
|
|
384
|
+
|
|
385
|
+
#### `.optimize()` - Explicit Configuration
|
|
386
|
+
|
|
387
|
+
**Use when:** You want explicit control over optimization mode.
|
|
388
|
+
|
|
389
|
+
```javascript
|
|
390
|
+
const config = new BrevitConfig({
|
|
391
|
+
jsonMode: JsonOptimizationMode.Flatten,
|
|
392
|
+
textMode: TextOptimizationMode.Clean,
|
|
393
|
+
imageMode: ImageOptimizationMode.Ocr
|
|
394
|
+
});
|
|
395
|
+
const brevit = new BrevitClient(config);
|
|
396
|
+
|
|
397
|
+
// Uses explicit configuration
|
|
398
|
+
const result = await brevit.optimize(data);
|
|
399
|
+
```
|
|
400
|
+
|
|
401
|
+
**Advantages:**
|
|
402
|
+
- Full control over optimization
|
|
403
|
+
- Predictable behavior
|
|
404
|
+
- Best for specific use cases
|
|
405
|
+
|
|
406
|
+
### 5. Custom Optimizers
|
|
407
|
+
|
|
408
|
+
You can provide custom optimizers for text and images:
|
|
409
|
+
|
|
410
|
+
```javascript
|
|
411
|
+
// Custom text optimizer (e.g., using OpenAI API)
|
|
412
|
+
const customTextOptimizer = async (text, intent) => {
|
|
413
|
+
// Call your summarization service
|
|
414
|
+
const response = await fetch('https://api.example.com/summarize', {
|
|
415
|
+
method: 'POST',
|
|
416
|
+
body: JSON.stringify({ text, intent })
|
|
417
|
+
});
|
|
418
|
+
return await response.text();
|
|
419
|
+
};
|
|
420
|
+
|
|
421
|
+
// Custom image optimizer (e.g., using Azure AI Vision)
|
|
422
|
+
const customImageOptimizer = async (imageData, intent) => {
|
|
423
|
+
// Call your OCR service
|
|
424
|
+
const response = await fetch('https://api.example.com/ocr', {
|
|
425
|
+
method: 'POST',
|
|
426
|
+
body: imageData
|
|
427
|
+
});
|
|
428
|
+
return await response.text();
|
|
429
|
+
};
|
|
430
|
+
|
|
431
|
+
const brevit = new BrevitClient(config, {
|
|
432
|
+
textOptimizer: customTextOptimizer,
|
|
433
|
+
imageOptimizer: customImageOptimizer
|
|
434
|
+
});
|
|
435
|
+
```
|
|
436
|
+
|
|
437
|
+
### 6. Complete Workflow Examples
|
|
438
|
+
|
|
439
|
+
#### Example 6.1: E-Commerce Order Processing
|
|
440
|
+
|
|
441
|
+
```javascript
|
|
442
|
+
// Step 1: Optimize order JSON
|
|
443
|
+
const order = {
|
|
444
|
+
orderId: "o-456",
|
|
445
|
+
customer: { name: "John", email: "john@example.com" },
|
|
446
|
+
items: [
|
|
447
|
+
{ sku: "A-88", quantity: 2, price: 29.99 },
|
|
448
|
+
{ sku: "B-22", quantity: 1, price: 49.99 }
|
|
449
|
+
]
|
|
450
|
+
};
|
|
451
|
+
|
|
452
|
+
const optimizedOrder = await brevit.brevity(order);
|
|
453
|
+
|
|
454
|
+
// Step 2: Send to LLM
|
|
455
|
+
const prompt = `Analyze this order:\n\n${optimizedOrder}\n\nExtract total amount.`;
|
|
456
|
+
// Send prompt to OpenAI, Anthropic, etc.
|
|
457
|
+
```
|
|
458
|
+
|
|
459
|
+
#### Example 6.2: Document Processing Pipeline
|
|
460
|
+
|
|
461
|
+
```javascript
|
|
462
|
+
// Step 1: Read and optimize text document
|
|
463
|
+
import fs from 'fs/promises';
|
|
464
|
+
|
|
465
|
+
const contractText = await fs.readFile('contract.txt', 'utf-8');
|
|
466
|
+
const optimizedText = await brevit.brevity(contractText);
|
|
467
|
+
|
|
468
|
+
// Step 2: Process with LLM
|
|
469
|
+
const prompt = `Summarize this contract:\n\n${optimizedText}`;
|
|
470
|
+
// Send to LLM for summarization
|
|
471
|
+
```
|
|
472
|
+
|
|
473
|
+
#### Example 6.3: Receipt OCR Pipeline
|
|
474
|
+
|
|
475
|
+
```javascript
|
|
476
|
+
// Step 1: Read receipt image
|
|
477
|
+
import fs from 'fs/promises';
|
|
478
|
+
|
|
479
|
+
const receiptImage = await fs.readFile('receipt.jpg');
|
|
480
|
+
|
|
481
|
+
// Step 2: Extract text via OCR
|
|
482
|
+
const extractedText = await brevit.brevity(receiptImage);
|
|
483
|
+
|
|
484
|
+
// Step 3: Optimize extracted text (if it's long)
|
|
485
|
+
const optimized = await brevit.brevity(extractedText);
|
|
486
|
+
|
|
487
|
+
// Step 4: Send to LLM for analysis
|
|
488
|
+
const prompt = `Extract items and total from this receipt:\n\n${optimized}`;
|
|
489
|
+
// Send to LLM
|
|
490
|
+
```
|
|
491
|
+
|
|
492
|
+
### Node.js Example
|
|
493
|
+
|
|
494
|
+
```javascript
|
|
495
|
+
import { BrevitClient, BrevitConfig, JsonOptimizationMode } from './src/brevit.js';
|
|
496
|
+
|
|
497
|
+
const config = new BrevitConfig({
|
|
498
|
+
jsonMode: JsonOptimizationMode.Flatten
|
|
499
|
+
});
|
|
500
|
+
|
|
501
|
+
const brevit = new BrevitClient(config);
|
|
502
|
+
|
|
503
|
+
async function processOrder(orderData) {
|
|
504
|
+
const optimized = await brevit.optimize(orderData);
|
|
505
|
+
|
|
506
|
+
// Send to LLM API
|
|
507
|
+
const prompt = `Context:\n${optimized}\n\nTask: Summarize the order.`;
|
|
508
|
+
|
|
509
|
+
// const response = await fetch('https://api.openai.com/v1/chat/completions', {
|
|
510
|
+
// method: 'POST',
|
|
511
|
+
// headers: {
|
|
512
|
+
// 'Content-Type': 'application/json',
|
|
513
|
+
// 'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`
|
|
514
|
+
// },
|
|
515
|
+
// body: JSON.stringify({
|
|
516
|
+
// model: 'gpt-4',
|
|
517
|
+
// messages: [{ role: 'user', content: prompt }]
|
|
518
|
+
// })
|
|
519
|
+
// });
|
|
520
|
+
|
|
521
|
+
return prompt;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
const order = {
|
|
525
|
+
orderId: 'o-456',
|
|
526
|
+
status: 'SHIPPED',
|
|
527
|
+
items: [{ sku: 'A-88', name: 'Brevit Pro', quantity: 1 }]
|
|
528
|
+
};
|
|
529
|
+
|
|
530
|
+
processOrder(order).then(console.log);
|
|
531
|
+
```
|
|
532
|
+
|
|
533
|
+
### Browser Example
|
|
534
|
+
|
|
535
|
+
```html
|
|
536
|
+
<!DOCTYPE html>
|
|
537
|
+
<html>
|
|
538
|
+
<head>
|
|
539
|
+
<title>Brevit.js Example</title>
|
|
540
|
+
</head>
|
|
541
|
+
<body>
|
|
542
|
+
<script type="module">
|
|
543
|
+
import { BrevitClient, BrevitConfig, JsonOptimizationMode } from './src/brevit.js';
|
|
544
|
+
|
|
545
|
+
const config = new BrevitConfig({
|
|
546
|
+
jsonMode: JsonOptimizationMode.Flatten
|
|
547
|
+
});
|
|
548
|
+
|
|
549
|
+
const brevit = new BrevitClient(config);
|
|
550
|
+
|
|
551
|
+
const data = {
|
|
552
|
+
user: {
|
|
553
|
+
name: 'Javian',
|
|
554
|
+
email: 'support@javianpicardo.com'
|
|
555
|
+
}
|
|
556
|
+
};
|
|
557
|
+
|
|
558
|
+
brevit.optimize(data).then(result => {
|
|
559
|
+
document.body.innerHTML = `<pre>${result}</pre>`;
|
|
560
|
+
});
|
|
561
|
+
</script>
|
|
562
|
+
</body>
|
|
563
|
+
</html>
|
|
564
|
+
```
|
|
565
|
+
|
|
566
|
+
## Configuration Options
|
|
567
|
+
|
|
568
|
+
### BrevitConfig
|
|
569
|
+
|
|
570
|
+
```javascript
|
|
571
|
+
const config = new BrevitConfig({
|
|
572
|
+
jsonMode: JsonOptimizationMode.Flatten, // JSON optimization strategy
|
|
573
|
+
textMode: 'Clean', // Text optimization strategy
|
|
574
|
+
imageMode: 'Ocr', // Image optimization strategy
|
|
575
|
+
jsonPathsToKeep: [], // Paths to keep for Filter mode
|
|
576
|
+
longTextThreshold: 500 // Character threshold for text optimization
|
|
577
|
+
});
|
|
578
|
+
```
|
|
579
|
+
|
|
580
|
+
### JsonOptimizationMode
|
|
581
|
+
|
|
582
|
+
- **None**: No optimization, pass JSON as-is
|
|
583
|
+
- **Flatten**: Convert nested JSON to flat key-value pairs (most token-efficient)
|
|
584
|
+
- **ToYaml**: Convert JSON to YAML format (requires `js-yaml` package)
|
|
585
|
+
- **Filter**: Keep only specified JSON paths
|
|
586
|
+
|
|
587
|
+
### TextOptimizationMode
|
|
588
|
+
|
|
589
|
+
- **None**: No optimization
|
|
590
|
+
- **Clean**: Remove boilerplate and excessive whitespace
|
|
591
|
+
- **SummarizeFast**: Use a fast model for summarization (requires custom optimizer)
|
|
592
|
+
- **SummarizeHighQuality**: Use a high-quality model for summarization (requires custom optimizer)
|
|
593
|
+
|
|
594
|
+
### ImageOptimizationMode
|
|
595
|
+
|
|
596
|
+
- **None**: Skip image processing
|
|
597
|
+
- **Ocr**: Extract text from images (requires custom optimizer)
|
|
598
|
+
- **Metadata**: Extract basic metadata only
|
|
599
|
+
|
|
600
|
+
## TypeScript Usage
|
|
601
|
+
|
|
602
|
+
### Type Definitions
|
|
603
|
+
|
|
604
|
+
All types are exported for use in TypeScript projects:
|
|
605
|
+
|
|
606
|
+
```typescript
|
|
607
|
+
import {
|
|
608
|
+
BrevitClient,
|
|
609
|
+
BrevitConfig,
|
|
610
|
+
JsonOptimizationMode,
|
|
611
|
+
TextOptimizationMode,
|
|
612
|
+
ImageOptimizationMode,
|
|
613
|
+
type BrevitConfigOptions,
|
|
614
|
+
type BrevitClientOptions,
|
|
615
|
+
type TextOptimizerFunction,
|
|
616
|
+
type ImageOptimizerFunction,
|
|
617
|
+
} from 'brevit-js';
|
|
618
|
+
```
|
|
619
|
+
|
|
620
|
+
### Type-Safe Configuration
|
|
621
|
+
|
|
622
|
+
```typescript
|
|
623
|
+
const config: BrevitConfigOptions = {
|
|
624
|
+
jsonMode: JsonOptimizationMode.Flatten,
|
|
625
|
+
textMode: TextOptimizationMode.Clean,
|
|
626
|
+
imageMode: ImageOptimizationMode.Ocr,
|
|
627
|
+
jsonPathsToKeep: ['user.name', 'order.orderId'],
|
|
628
|
+
longTextThreshold: 1000,
|
|
629
|
+
};
|
|
630
|
+
|
|
631
|
+
const client = new BrevitClient(new BrevitConfig(config));
|
|
632
|
+
```
|
|
633
|
+
|
|
634
|
+
### Custom Optimizers with Types
|
|
635
|
+
|
|
636
|
+
```typescript
|
|
637
|
+
const customTextOptimizer: TextOptimizerFunction = async (longText, intent) => {
|
|
638
|
+
const response = await fetch('/api/summarize', {
|
|
639
|
+
method: 'POST',
|
|
640
|
+
headers: { 'Content-Type': 'application/json' },
|
|
641
|
+
body: JSON.stringify({ text: longText, intent }),
|
|
642
|
+
});
|
|
643
|
+
const { summary } = await response.json();
|
|
644
|
+
return summary;
|
|
645
|
+
};
|
|
646
|
+
|
|
647
|
+
const client = new BrevitClient(config, {
|
|
648
|
+
textOptimizer: customTextOptimizer,
|
|
649
|
+
});
|
|
650
|
+
```
|
|
651
|
+
|
|
652
|
+
### Type-Safe Data Handling
|
|
653
|
+
|
|
654
|
+
```typescript
|
|
655
|
+
interface Order {
|
|
656
|
+
orderId: string;
|
|
657
|
+
status: string;
|
|
658
|
+
items: Array<{ sku: string; name: string; quantity: number }>;
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
const order: Order = {
|
|
662
|
+
orderId: 'o-456',
|
|
663
|
+
status: 'SHIPPED',
|
|
664
|
+
items: [{ sku: 'A-88', name: 'Brevit Pro', quantity: 1 }],
|
|
665
|
+
};
|
|
666
|
+
|
|
667
|
+
const optimized = await client.optimize(order);
|
|
668
|
+
// TypeScript knows optimized is a Promise<string>
|
|
669
|
+
```
|
|
670
|
+
|
|
671
|
+
## Advanced Usage
|
|
672
|
+
|
|
673
|
+
### Custom Text Optimizer
|
|
674
|
+
|
|
675
|
+
Implement a custom text optimizer that calls your backend API:
|
|
676
|
+
|
|
677
|
+
```javascript
|
|
678
|
+
async function customTextOptimizer(longText, intent) {
|
|
679
|
+
// Call your backend API for summarization
|
|
680
|
+
const response = await fetch('/api/summarize', {
|
|
681
|
+
method: 'POST',
|
|
682
|
+
headers: { 'Content-Type': 'application/json' },
|
|
683
|
+
body: JSON.stringify({ text: longText, intent })
|
|
684
|
+
});
|
|
685
|
+
|
|
686
|
+
const { summary } = await response.json();
|
|
687
|
+
return summary;
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
const brevit = new BrevitClient(config, {
|
|
691
|
+
textOptimizer: customTextOptimizer
|
|
692
|
+
});
|
|
693
|
+
```
|
|
694
|
+
|
|
695
|
+
### Custom Image Optimizer
|
|
696
|
+
|
|
697
|
+
Implement a custom image optimizer that calls your OCR service:
|
|
698
|
+
|
|
699
|
+
```javascript
|
|
700
|
+
async function customImageOptimizer(imageData, intent) {
|
|
701
|
+
// Convert ArrayBuffer to base64 if needed
|
|
702
|
+
const base64 = btoa(String.fromCharCode(...new Uint8Array(imageData)));
|
|
703
|
+
|
|
704
|
+
// Call your backend OCR API
|
|
705
|
+
const response = await fetch('/api/ocr', {
|
|
706
|
+
method: 'POST',
|
|
707
|
+
headers: { 'Content-Type': 'application/json' },
|
|
708
|
+
body: JSON.stringify({ image: base64 })
|
|
709
|
+
});
|
|
710
|
+
|
|
711
|
+
const { text } = await response.json();
|
|
712
|
+
return text;
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
const brevit = new BrevitClient(config, {
|
|
716
|
+
imageOptimizer: customImageOptimizer
|
|
717
|
+
});
|
|
718
|
+
```
|
|
719
|
+
|
|
720
|
+
### YAML Mode (Optional)
|
|
721
|
+
|
|
722
|
+
To use YAML mode, install `js-yaml`:
|
|
723
|
+
|
|
724
|
+
```bash
|
|
725
|
+
npm install js-yaml
|
|
726
|
+
```
|
|
727
|
+
|
|
728
|
+
Then modify the `ToYaml` case in `brevit.js`:
|
|
729
|
+
|
|
730
|
+
```javascript
|
|
731
|
+
import YAML from 'js-yaml';
|
|
732
|
+
|
|
733
|
+
// In the optimize method:
|
|
734
|
+
case JsonOptimizationMode.ToYaml:
|
|
735
|
+
return YAML.dump(inputObject);
|
|
736
|
+
```
|
|
737
|
+
|
|
738
|
+
### Filter Mode
|
|
739
|
+
|
|
740
|
+
Use Filter mode to keep only specific JSON paths:
|
|
741
|
+
|
|
742
|
+
```javascript
|
|
743
|
+
const config = new BrevitConfig({
|
|
744
|
+
jsonMode: JsonOptimizationMode.Filter,
|
|
745
|
+
jsonPathsToKeep: [
|
|
746
|
+
'user.name',
|
|
747
|
+
'order.orderId',
|
|
748
|
+
'order.items[*].sku'
|
|
749
|
+
]
|
|
750
|
+
});
|
|
751
|
+
```
|
|
752
|
+
|
|
753
|
+
## Examples
|
|
754
|
+
|
|
755
|
+
### Example 1: Optimize Complex Object
|
|
756
|
+
|
|
757
|
+
```javascript
|
|
758
|
+
const user = {
|
|
759
|
+
id: 'u-123',
|
|
760
|
+
name: 'Javian',
|
|
761
|
+
isActive: true,
|
|
762
|
+
contact: {
|
|
763
|
+
email: 'support@javianpicardo.com',
|
|
764
|
+
phone: null
|
|
765
|
+
},
|
|
766
|
+
orders: [
|
|
767
|
+
{ orderId: 'o-456', status: 'SHIPPED' }
|
|
768
|
+
]
|
|
769
|
+
};
|
|
770
|
+
|
|
771
|
+
const optimized = await brevit.optimize(user);
|
|
772
|
+
// Output:
|
|
773
|
+
// id: u-123
|
|
774
|
+
// name: Javian
|
|
775
|
+
// isActive: true
|
|
776
|
+
// contact.email: support@javianpicardo.com
|
|
777
|
+
// contact.phone: null
|
|
778
|
+
// orders[0].orderId: o-456
|
|
779
|
+
// orders[0].status: SHIPPED
|
|
780
|
+
```
|
|
781
|
+
|
|
782
|
+
### Example 2: Optimize JSON String
|
|
783
|
+
|
|
784
|
+
```javascript
|
|
785
|
+
const json = `{
|
|
786
|
+
"order": {
|
|
787
|
+
"orderId": "o-456",
|
|
788
|
+
"status": "SHIPPED",
|
|
789
|
+
"items": [
|
|
790
|
+
{ "sku": "A-88", "name": "Brevit Pro", "quantity": 1 }
|
|
791
|
+
]
|
|
792
|
+
}
|
|
793
|
+
}`;
|
|
794
|
+
|
|
795
|
+
const optimized = await brevit.optimize(json);
|
|
796
|
+
```
|
|
797
|
+
|
|
798
|
+
### Example 3: Process Long Text
|
|
799
|
+
|
|
800
|
+
```javascript
|
|
801
|
+
const longDocument = '...very long text...';
|
|
802
|
+
const optimized = await brevit.optimize(longDocument);
|
|
803
|
+
// Will trigger text optimization if length > longTextThreshold
|
|
804
|
+
```
|
|
805
|
+
|
|
806
|
+
### Example 4: Process Image (ArrayBuffer)
|
|
807
|
+
|
|
808
|
+
```javascript
|
|
809
|
+
// Fetch image as ArrayBuffer
|
|
810
|
+
const response = await fetch('https://example.com/receipt.jpg');
|
|
811
|
+
const imageData = await response.arrayBuffer();
|
|
812
|
+
|
|
813
|
+
const optimized = await brevit.optimize(imageData);
|
|
814
|
+
// Will trigger image optimization
|
|
815
|
+
```
|
|
816
|
+
|
|
817
|
+
## When Not to Use Brevit.js
|
|
818
|
+
|
|
819
|
+
Consider alternatives when:
|
|
820
|
+
|
|
821
|
+
1. **API Responses**: If returning JSON to HTTP clients, use standard JSON
|
|
822
|
+
2. **Data Contracts**: When strict JSON schema validation is required
|
|
823
|
+
3. **Small Objects**: Objects under 100 tokens may not benefit significantly
|
|
824
|
+
4. **Real-Time APIs**: For REST APIs serving JSON, standard formatting is better
|
|
825
|
+
5. **Browser Storage**: localStorage/sessionStorage expect JSON strings
|
|
826
|
+
|
|
827
|
+
**Best Use Cases:**
|
|
828
|
+
- ✅ LLM prompt optimization
|
|
829
|
+
- ✅ Reducing OpenAI/Anthropic API costs
|
|
830
|
+
- ✅ Processing large datasets for AI
|
|
831
|
+
- ✅ Document summarization workflows
|
|
832
|
+
- ✅ OCR and image processing pipelines
|
|
833
|
+
|
|
834
|
+
## Benchmarks
|
|
835
|
+
|
|
836
|
+
### Token Reduction
|
|
837
|
+
|
|
838
|
+
| Object Type | Original Tokens | Brevit Tokens | Reduction |
|
|
839
|
+
|-------------|----------------|---------------|-----------|
|
|
840
|
+
| Simple Object | 45 | 28 | 38% |
|
|
841
|
+
| Complex Object | 234 | 127 | 46% |
|
|
842
|
+
| Nested Arrays | 156 | 89 | 43% |
|
|
843
|
+
| API Response | 312 | 178 | 43% |
|
|
844
|
+
|
|
845
|
+
### Performance
|
|
846
|
+
|
|
847
|
+
| Operation | Objects/sec | Avg Latency | Memory |
|
|
848
|
+
|-----------|-------------|-------------|--------|
|
|
849
|
+
| Flatten (1KB) | 1,800 | 0.6ms | 2.1MB |
|
|
850
|
+
| Flatten (10KB) | 420 | 2.4ms | 8.5MB |
|
|
851
|
+
| Flatten (100KB) | 52 | 19ms | 45MB |
|
|
852
|
+
|
|
853
|
+
*Benchmarks: Node.js 20.x, Intel i7-12700K, Release mode*
|
|
854
|
+
|
|
855
|
+
## Playgrounds
|
|
856
|
+
|
|
857
|
+
### Interactive Playground
|
|
858
|
+
|
|
859
|
+
```bash
|
|
860
|
+
# Clone and run
|
|
861
|
+
git clone https://github.com/JavianDev/Brevit.git
|
|
862
|
+
cd Brevit/Brevit.js
|
|
863
|
+
npm install
|
|
864
|
+
node playground.js
|
|
865
|
+
```
|
|
866
|
+
|
|
867
|
+
### Online Playground
|
|
868
|
+
|
|
869
|
+
- **Web Playground**: [https://brevit.dev/playground](https://brevit.dev/playground) (Coming Soon)
|
|
870
|
+
- **CodeSandbox**: [https://codesandbox.io/brevit](https://codesandbox.io/brevit) (Coming Soon)
|
|
871
|
+
- **JSFiddle**: [https://jsfiddle.net/brevit](https://jsfiddle.net/brevit) (Coming Soon)
|
|
872
|
+
|
|
873
|
+
## CLI
|
|
874
|
+
|
|
875
|
+
### Installation
|
|
876
|
+
|
|
877
|
+
```bash
|
|
878
|
+
npm install -g brevit-cli
|
|
879
|
+
```
|
|
880
|
+
|
|
881
|
+
### Usage
|
|
882
|
+
|
|
883
|
+
```bash
|
|
884
|
+
# Optimize a JSON file
|
|
885
|
+
brevit optimize input.json -o output.txt
|
|
886
|
+
|
|
887
|
+
# Optimize from stdin
|
|
888
|
+
cat data.json | brevit optimize
|
|
889
|
+
|
|
890
|
+
# Optimize with custom config
|
|
891
|
+
brevit optimize input.json --mode flatten --threshold 1000
|
|
892
|
+
|
|
893
|
+
# Help
|
|
894
|
+
brevit --help
|
|
895
|
+
```
|
|
896
|
+
|
|
897
|
+
### Examples
|
|
898
|
+
|
|
899
|
+
```bash
|
|
900
|
+
# Flatten JSON
|
|
901
|
+
brevit optimize order.json --mode flatten
|
|
902
|
+
|
|
903
|
+
# Convert to YAML
|
|
904
|
+
brevit optimize data.json --mode yaml
|
|
905
|
+
|
|
906
|
+
# Filter paths
|
|
907
|
+
brevit optimize data.json --mode filter --paths "user.name,order.id"
|
|
908
|
+
```
|
|
909
|
+
|
|
910
|
+
## Format Overview
|
|
911
|
+
|
|
912
|
+
### Flattened Format (Hybrid Optimization)
|
|
913
|
+
|
|
914
|
+
Brevit intelligently converts JavaScript objects to flat key-value pairs with automatic tabular optimization:
|
|
915
|
+
|
|
916
|
+
**Input:**
|
|
917
|
+
```javascript
|
|
918
|
+
const order = {
|
|
919
|
+
orderId: 'o-456',
|
|
920
|
+
friends: ['ana', 'luis', 'sam'],
|
|
921
|
+
items: [
|
|
922
|
+
{ sku: 'A-88', quantity: 1 },
|
|
923
|
+
{ sku: 'T-22', quantity: 2 }
|
|
924
|
+
]
|
|
925
|
+
};
|
|
926
|
+
```
|
|
927
|
+
|
|
928
|
+
**Output (with tabular optimization):**
|
|
929
|
+
```
|
|
930
|
+
orderId: o-456
|
|
931
|
+
friends[3]: ana,luis,sam
|
|
932
|
+
items[2]{quantity,sku}:
|
|
933
|
+
1,A-88
|
|
934
|
+
2,T-22
|
|
935
|
+
```
|
|
936
|
+
|
|
937
|
+
**For non-uniform arrays (fallback):**
|
|
938
|
+
```javascript
|
|
939
|
+
const mixed = {
|
|
940
|
+
items: [
|
|
941
|
+
{ sku: 'A-88', quantity: 1 },
|
|
942
|
+
'special-item',
|
|
943
|
+
{ sku: 'T-22', quantity: 2 }
|
|
944
|
+
]
|
|
945
|
+
};
|
|
946
|
+
```
|
|
947
|
+
|
|
948
|
+
**Output (fallback to indexed format):**
|
|
949
|
+
```
|
|
950
|
+
items[0].sku: A-88
|
|
951
|
+
items[0].quantity: 1
|
|
952
|
+
items[1]: special-item
|
|
953
|
+
items[2].sku: T-22
|
|
954
|
+
items[2].quantity: 2
|
|
955
|
+
```
|
|
956
|
+
|
|
957
|
+
### Key Features
|
|
958
|
+
|
|
959
|
+
- **Property Names**: Uses JavaScript property names as-is
|
|
960
|
+
- **Nested Objects**: Dot notation for nested properties
|
|
961
|
+
- **Tabular Arrays**: Uniform object arrays automatically formatted in compact tabular format (`items[2]{field1,field2}:`)
|
|
962
|
+
- **Primitive Arrays**: Comma-separated format (`friends[3]: ana,luis,sam`)
|
|
963
|
+
- **Hybrid Approach**: Automatically detects optimal format, falls back to indexed format for mixed data
|
|
964
|
+
- **Null Handling**: Explicit `null` values
|
|
965
|
+
- **Type Preservation**: Numbers, booleans preserved as strings
|
|
966
|
+
|
|
967
|
+
## API
|
|
968
|
+
|
|
969
|
+
### BrevitClient
|
|
970
|
+
|
|
971
|
+
Main client class for optimization.
|
|
972
|
+
|
|
973
|
+
```typescript
|
|
974
|
+
class BrevitClient {
|
|
975
|
+
constructor(config?: BrevitConfig, options?: BrevitClientOptions);
|
|
976
|
+
brevity(rawData: unknown, intent?: string | null): Promise<string>;
|
|
977
|
+
optimize(rawData: unknown, intent?: string | null): Promise<string>;
|
|
978
|
+
registerStrategy(name: string, analyzer: Function, optimizer: Function): void;
|
|
979
|
+
}
|
|
980
|
+
```
|
|
981
|
+
|
|
982
|
+
**Example - Automatic Optimization:**
|
|
983
|
+
```javascript
|
|
984
|
+
// Automatically analyzes data and selects best strategy
|
|
985
|
+
const optimized = await brevit.brevity(order);
|
|
986
|
+
// Automatically detects uniform arrays, long text, etc.
|
|
987
|
+
```
|
|
988
|
+
|
|
989
|
+
**Example - Explicit Optimization:**
|
|
990
|
+
```javascript
|
|
991
|
+
// Use explicit configuration
|
|
992
|
+
const optimized = await brevit.optimize(order, 'extract_total');
|
|
993
|
+
```
|
|
994
|
+
|
|
995
|
+
**Example - Custom Strategy:**
|
|
996
|
+
```javascript
|
|
997
|
+
// Register custom optimization strategy
|
|
998
|
+
brevit.registerStrategy('custom', (data, analysis) => {
|
|
999
|
+
if (analysis.hasSpecialPattern) {
|
|
1000
|
+
return { score: 95, reason: 'Custom optimization needed' };
|
|
1001
|
+
}
|
|
1002
|
+
return { score: 0 };
|
|
1003
|
+
}, async (data) => {
|
|
1004
|
+
// Custom optimization logic
|
|
1005
|
+
return customOptimizedData;
|
|
1006
|
+
});
|
|
1007
|
+
```
|
|
1008
|
+
|
|
1009
|
+
### BrevitConfig
|
|
1010
|
+
|
|
1011
|
+
Configuration class for BrevitClient.
|
|
1012
|
+
|
|
1013
|
+
```typescript
|
|
1014
|
+
class BrevitConfig {
|
|
1015
|
+
jsonMode: JsonOptimizationModeType;
|
|
1016
|
+
textMode: TextOptimizationModeType;
|
|
1017
|
+
imageMode: ImageOptimizationModeType;
|
|
1018
|
+
jsonPathsToKeep: string[];
|
|
1019
|
+
longTextThreshold: number;
|
|
1020
|
+
}
|
|
1021
|
+
```
|
|
1022
|
+
|
|
1023
|
+
### Enums
|
|
1024
|
+
|
|
1025
|
+
#### JsonOptimizationMode
|
|
1026
|
+
- `None` - No optimization
|
|
1027
|
+
- `Flatten` - Flatten to key-value pairs (default)
|
|
1028
|
+
- `ToYaml` - Convert to YAML
|
|
1029
|
+
- `Filter` - Keep only specified paths
|
|
1030
|
+
|
|
1031
|
+
#### TextOptimizationMode
|
|
1032
|
+
- `None` - No optimization
|
|
1033
|
+
- `Clean` - Remove boilerplate
|
|
1034
|
+
- `SummarizeFast` - Fast summarization
|
|
1035
|
+
- `SummarizeHighQuality` - High-quality summarization
|
|
1036
|
+
|
|
1037
|
+
#### ImageOptimizationMode
|
|
1038
|
+
- `None` - Skip processing
|
|
1039
|
+
- `Ocr` - Extract text via OCR
|
|
1040
|
+
- `Metadata` - Extract metadata only
|
|
1041
|
+
|
|
1042
|
+
## Using Brevit.js in LLM Prompts
|
|
1043
|
+
|
|
1044
|
+
### Best Practices
|
|
1045
|
+
|
|
1046
|
+
1. **Context First**: Provide context before optimized data
|
|
1047
|
+
2. **Clear Instructions**: Tell the LLM what format to expect
|
|
1048
|
+
3. **Examples**: Include format examples in prompts
|
|
1049
|
+
|
|
1050
|
+
### Example Prompt Template
|
|
1051
|
+
|
|
1052
|
+
```javascript
|
|
1053
|
+
const optimized = await brevit.optimize(order);
|
|
1054
|
+
|
|
1055
|
+
const prompt = `You are analyzing order data. The data is in Brevit flattened format:
|
|
1056
|
+
|
|
1057
|
+
Context:
|
|
1058
|
+
${optimized}
|
|
1059
|
+
|
|
1060
|
+
Task: Extract the order total and shipping address.
|
|
1061
|
+
|
|
1062
|
+
Format your response as JSON with keys: total, address`;
|
|
1063
|
+
```
|
|
1064
|
+
|
|
1065
|
+
### Real-World Example
|
|
1066
|
+
|
|
1067
|
+
```javascript
|
|
1068
|
+
async function analyzeOrder(order) {
|
|
1069
|
+
const optimized = await brevit.optimize(order);
|
|
1070
|
+
|
|
1071
|
+
const prompt = `Analyze this order:
|
|
1072
|
+
|
|
1073
|
+
${optimized}
|
|
1074
|
+
|
|
1075
|
+
Questions:
|
|
1076
|
+
1. What is the order total?
|
|
1077
|
+
2. How many items?
|
|
1078
|
+
3. Average item price?
|
|
1079
|
+
|
|
1080
|
+
Respond in JSON.`;
|
|
1081
|
+
|
|
1082
|
+
const response = await fetch('https://api.openai.com/v1/chat/completions', {
|
|
1083
|
+
method: 'POST',
|
|
1084
|
+
headers: {
|
|
1085
|
+
'Content-Type': 'application/json',
|
|
1086
|
+
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`
|
|
1087
|
+
},
|
|
1088
|
+
body: JSON.stringify({
|
|
1089
|
+
model: 'gpt-4',
|
|
1090
|
+
messages: [{ role: 'user', content: prompt }]
|
|
1091
|
+
})
|
|
1092
|
+
});
|
|
1093
|
+
|
|
1094
|
+
return await response.json();
|
|
1095
|
+
}
|
|
1096
|
+
```
|
|
1097
|
+
|
|
1098
|
+
## Syntax Cheatsheet
|
|
1099
|
+
|
|
1100
|
+
### JavaScript to Brevit Format
|
|
1101
|
+
|
|
1102
|
+
| JS Structure | Brevit Format | Example |
|
|
1103
|
+
|--------------|---------------|---------|
|
|
1104
|
+
| Property | `property: value` | `orderId: o-456` |
|
|
1105
|
+
| Nested property | `parent.child: value` | `customer.name: John` |
|
|
1106
|
+
| Primitive array | `array[count]: val1,val2,val3` | `friends[3]: ana,luis,sam` |
|
|
1107
|
+
| Uniform object array | `array[count]{field1,field2}:`<br>` val1,val2`<br>` val3,val4` | `items[2]{sku,qty}:`<br>` A-88,1`<br>` T-22,2` |
|
|
1108
|
+
| Array element (fallback) | `array[index].property: value` | `items[0].sku: A-88` |
|
|
1109
|
+
| Nested array | `parent[index].child[index]` | `orders[0].items[1].sku` |
|
|
1110
|
+
| Null value | `property: null` | `phone: null` |
|
|
1111
|
+
| Boolean | `property: true` | `isActive: true` |
|
|
1112
|
+
| Number | `property: 123` | `quantity: 5` |
|
|
1113
|
+
|
|
1114
|
+
### Special Cases
|
|
1115
|
+
|
|
1116
|
+
- **Empty Arrays**: `items: []` → `items: []`
|
|
1117
|
+
- **Empty Objects**: `metadata: {}` → `metadata: {}`
|
|
1118
|
+
- **Undefined**: Converted to `null`
|
|
1119
|
+
- **Dates**: Converted to ISO string
|
|
1120
|
+
- **Tabular Arrays**: Automatically detected when all objects have same keys
|
|
1121
|
+
- **Primitive Arrays**: Automatically detected when all elements are primitives
|
|
1122
|
+
|
|
1123
|
+
## Other Implementations
|
|
1124
|
+
|
|
1125
|
+
Brevit is available in multiple languages:
|
|
1126
|
+
|
|
1127
|
+
| Language | Package | Status |
|
|
1128
|
+
|----------|---------|--------|
|
|
1129
|
+
| JavaScript | `brevit-js` | ✅ Stable (This) |
|
|
1130
|
+
| C# (.NET) | `Brevit.NET` | ✅ Stable |
|
|
1131
|
+
| Python | `brevit-py` | ✅ Stable |
|
|
1132
|
+
|
|
1133
|
+
## Full Specification
|
|
1134
|
+
|
|
1135
|
+
### Format Specification
|
|
1136
|
+
|
|
1137
|
+
1. **Key-Value Pairs**: One pair per line
|
|
1138
|
+
2. **Separator**: `: ` (colon + space)
|
|
1139
|
+
3. **Key Format**: Property names with dot/bracket notation
|
|
1140
|
+
4. **Value Format**: String representation of values
|
|
1141
|
+
5. **Line Endings**: `\n` (newline)
|
|
1142
|
+
|
|
1143
|
+
### Grammar
|
|
1144
|
+
|
|
1145
|
+
```
|
|
1146
|
+
brevit := line*
|
|
1147
|
+
line := key ": " value "\n"
|
|
1148
|
+
key := identifier ("." identifier | "[" number "]")*
|
|
1149
|
+
value := string | number | boolean | null
|
|
1150
|
+
identifier := [a-zA-Z_][a-zA-Z0-9_]*
|
|
1151
|
+
```
|
|
1152
|
+
|
|
1153
|
+
### Examples
|
|
1154
|
+
|
|
1155
|
+
**Simple Object:**
|
|
1156
|
+
```
|
|
1157
|
+
orderId: o-456
|
|
1158
|
+
status: SHIPPED
|
|
1159
|
+
```
|
|
1160
|
+
|
|
1161
|
+
**Nested Object:**
|
|
1162
|
+
```
|
|
1163
|
+
customer.name: John Doe
|
|
1164
|
+
customer.email: john@example.com
|
|
1165
|
+
```
|
|
1166
|
+
|
|
1167
|
+
**Array:**
|
|
1168
|
+
```
|
|
1169
|
+
items[0].sku: A-88
|
|
1170
|
+
items[0].quantity: 1
|
|
1171
|
+
items[1].sku: T-22
|
|
1172
|
+
items[1].quantity: 2
|
|
1173
|
+
```
|
|
1174
|
+
|
|
1175
|
+
**Complex Structure:**
|
|
1176
|
+
```
|
|
1177
|
+
orderId: o-456
|
|
1178
|
+
customer.name: John Doe
|
|
1179
|
+
items[0].sku: A-88
|
|
1180
|
+
items[0].price: 29.99
|
|
1181
|
+
items[1].sku: T-22
|
|
1182
|
+
items[1].price: 39.99
|
|
1183
|
+
shipping.address.street: 123 Main St
|
|
1184
|
+
shipping.address.city: Toronto
|
|
1185
|
+
```
|
|
1186
|
+
|
|
1187
|
+
## Performance Considerations
|
|
1188
|
+
|
|
1189
|
+
- **Flatten Mode**: Reduces token count by 40-60% compared to standard JSON
|
|
1190
|
+
- **Memory Efficient**: Processes data in-place where possible
|
|
1191
|
+
- **Async/Await**: All operations are asynchronous for better scalability
|
|
1192
|
+
- **Zero Dependencies**: Core library has no dependencies (optional YAML support)
|
|
1193
|
+
|
|
1194
|
+
## Best Practices
|
|
1195
|
+
|
|
1196
|
+
1. **Use Backend for LLM Calls**: Never put LLM API keys in frontend code. Use custom optimizers that call your backend.
|
|
1197
|
+
2. **Configure Thresholds**: Adjust `longTextThreshold` based on your use case
|
|
1198
|
+
3. **Monitor Token Usage**: Track token counts before/after optimization
|
|
1199
|
+
4. **Cache Results**: Consider caching optimized results for repeated queries
|
|
1200
|
+
5. **Error Handling**: Wrap optimize calls in try-catch blocks
|
|
1201
|
+
|
|
1202
|
+
## Troubleshooting
|
|
1203
|
+
|
|
1204
|
+
### Issue: "ToYaml mode requires installing a YAML library"
|
|
1205
|
+
|
|
1206
|
+
**Solution**: Install `js-yaml` package: `npm install js-yaml` and update the code as shown in Advanced Usage.
|
|
1207
|
+
|
|
1208
|
+
### Issue: Text summarization returns stub
|
|
1209
|
+
|
|
1210
|
+
**Solution**: Implement a custom text optimizer that calls your backend API (see Advanced Usage).
|
|
1211
|
+
|
|
1212
|
+
### Issue: Image OCR returns stub
|
|
1213
|
+
|
|
1214
|
+
**Solution**: Implement a custom image optimizer that calls your OCR service (see Advanced Usage).
|
|
1215
|
+
|
|
1216
|
+
### Issue: Module not found in Node.js
|
|
1217
|
+
|
|
1218
|
+
**Solution**: Ensure you're using ES modules. Add `"type": "module"` to your `package.json` or use `.mjs` extension.
|
|
1219
|
+
|
|
1220
|
+
## Contributing
|
|
1221
|
+
|
|
1222
|
+
Contributions are welcome! Please read our contributing guidelines and submit pull requests to our GitHub repository.
|
|
1223
|
+
|
|
1224
|
+
## License
|
|
1225
|
+
|
|
1226
|
+
MIT License - see LICENSE file for details.
|
|
1227
|
+
|
|
1228
|
+
## Support
|
|
1229
|
+
|
|
1230
|
+
- **Documentation**: [https://brevit.dev/docs](https://brevit.dev/docs)
|
|
1231
|
+
- **Issues**: [https://github.com/brevit/brevit-js/issues](https://github.com/brevit/brevit-js/issues)
|
|
1232
|
+
- **Email**: support@javianpicardo.com
|
|
1233
|
+
|
|
1234
|
+
## Version History
|
|
1235
|
+
|
|
1236
|
+
- **0.1.0** (Current): Initial release with core optimization features
|
|
1237
|
+
|