LessTokens Logo
Integrations
Nodejs

Documentation

Getting Started

  • Overview
  • Account Setup
  • First API Key
  • First Request
  • Understanding Metrics

API Reference

  • Overview
  • Authentication
  • Compressionnew
  • MCP Servernew
  • Errors

Integrations

  • Node.js / TypeScript
  • Python
  • cURL

Resources

  • Best Practices

Need help?

Join our community or contact support for assistance.

Contact Support →

Node.js / TypeScript

Complete integration guide for using LessToken API with Node.js and TypeScript projects.

Installation

Install the required dependencies using npm or yarn:

terminal
# Using npm
npm install axios dotenv

# Using yarn
yarn add axios dotenv

# Using pnpm
pnpm add axios dotenv

TypeScript Users

If you're using TypeScript, also install type definitions:npm install -D @types/node

Environment Setup

Create a .env file in your project root to store your API key securely:

.env
LESSTOKEN_API_KEY=your_api_key_here
LESSTOKEN_BASE_URL=https://lesstokens.hive-hub.ai

Security Warning

Never commit .env files to version control. Add it to your .gitignore

Basic Usage

Here's a simple example of how to compress text using the LessToken API:

compress.ts
import axios from 'axios';
import 'dotenv/config';

interface CompressResponse {
  compressedText: string;
  metrics: {
    inputTokens: number;
    outputTokens: number;
    compressionRate: number;
    processingTimeMs: number;
  };
  requestId: string;
}

async function compressText(text: string): Promise<CompressResponse> {
  const apiKey = process.env.LESSTOKEN_API_KEY;
  const baseUrl = process.env.LESSTOKEN_BASE_URL || 'https://lesstokens.hive-hub.ai';

  if (!apiKey) {
    throw new Error('LESSTOKEN_API_KEY is not set');
  }

  try {
    const response = await axios.post<CompressResponse>(
      `${baseUrl}/api/compress`,
      {
        text,
        options: {
          algorithm: 'br',
          level: 6,
        },
      },
      {
        headers: {
          'X-API-Key': apiKey,
          'Content-Type': 'application/json',
        },
      }
    );

    return response.data;
  } catch (error) {
    if (axios.isAxiosError(error)) {
      throw new Error(`API Error: ${error.response?.data?.message || error.message}`);
    }
    throw error;
  }
}

// Example usage
const longText = `
  This is a very long text that needs compression to reduce token usage
  when sending to language models. The compression algorithm will
  intelligently reduce the size while maintaining semantic meaning.
`;

compressText(longText)
  .then((result) => {
    console.log('Original text:', longText);
    console.log('Compressed text:', result.compressedText);
    console.log('Token reduction:', `${result.metrics.compressionRate.toFixed(2)}%`);
    console.log('Tokens saved:', result.metrics.inputTokens - result.metrics.outputTokens);
  })
  .catch((error) => {
    console.error('Compression failed:', error.message);
  });

Advanced Usage

Create a reusable client class with error handling and retry logic:

lesstoken-client.ts
1import axios, { AxiosInstance, AxiosError } from 'axios';
2
3export interface CompressionOptions {
4  maxTimeMs?: number; // Maximum processing time in milliseconds
5}
6
7export interface CompressResponse {
8  compressedText: string;
9  metrics: {
10    inputTokens: number;
11    outputTokens: number;
12    compressionRate: number;
13    processingTimeMs: number;
14  };
15  requestId: string;
16}
17
18export class LessTokenClient {
19  private client: AxiosInstance;
20  private maxRetries: number = 3;
21  private retryDelay: number = 1000;
22
23  constructor(apiKey: string, baseUrl: string = 'https://lesstokens.hive-hub.ai') {
24    this.client = axios.create({
25      baseURL: baseUrl,
26      headers: {
27        'X-API-Key': apiKey,
28        'Content-Type': 'application/json',
29      },
30      timeout: 30000,
31    });
32  }
33
34  async compress(
35    text: string,
36    options: CompressionOptions = {}
37  ): Promise<CompressResponse> {
38    return this.retryRequest(async () => {
39      const response = await this.client.post<CompressResponse>('/compress', {
40        prompt: text,
41        options: {
42          maxTimeMs: options.maxTimeMs || 10000,
43        },
44      });
45      return response.data;
46    });
47  }
48
49  private async retryRequest<T>(
50    fn: () => Promise<T>,
51    attempt: number = 1
52  ): Promise<T> {
53    try {
54      return await fn();
55    } catch (error) {
56      if (attempt >= this.maxRetries) {
57        throw this.handleError(error);
58      }
59
60      // Retry on rate limit or server errors
61      if (axios.isAxiosError(error)) {
62        const status = error.response?.status;
63        if (status === 429 || (status && status >= 500)) {
64          await this.delay(this.retryDelay * attempt);
65          return this.retryRequest(fn, attempt + 1);
66        }
67      }
68
69      throw this.handleError(error);
70    }
71  }
72
73  private handleError(error: unknown): Error {
74    if (axios.isAxiosError(error)) {
75      const axiosError = error as AxiosError<{ message?: string }>;
76      const message = axiosError.response?.data?.message || axiosError.message;
77      const status = axiosError.response?.status;
78      
79      return new Error(`LessToken API Error (${status || 'Unknown'}): ${message}`);
80    }
81    
82    return error instanceof Error ? error : new Error('Unknown error');
83  }
84
85  private delay(ms: number): Promise<void> {
86    return new Promise((resolve) => setTimeout(resolve, ms));
87  }
88}
89
90// Example usage
91const client = new LessTokenClient(process.env.LESSTOKEN_API_KEY!);
92
93async function main() {
94  try {
95    const result = await client.compress(
96      'Your long text here...',
97      { maxTimeMs: 5000 } // Optional: faster response with good compression
98    );
99
100    console.log('Success:', {
101      compressionRate: `${result.metrics.compressionRate.toFixed(2)}%`,
102      tokensSaved: result.metrics.inputTokens - result.metrics.outputTokens,
103      processingTime: `${result.metrics.processingTimeMs}ms`,
104    });
105  } catch (error) {
106    console.error('Error:', error);
107  }
108}
109
110main();

Best Practices

Use Environment Variables

Always store API keys in environment variables, never hardcode them

Implement Retry Logic

Add exponential backoff for rate limits and transient errors

Cache Compressed Results

Cache frequently compressed texts to reduce API calls

Monitor Token Usage

Track compression rates and savings in your application

Next Steps