All files / src/tokenizer token-manager.js

71.21% Statements 94/132
59.25% Branches 32/54
85.71% Functions 18/21
70.16% Lines 87/124

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 3902x             1x               1x 1x             1x   1x   1x   1x                       1887x       1887x 1887x 1887x                     173x 173x 173x   173x                           173x   173x 173x 173x   1x                                 1x   1x                   1x                 1x 1x 1x 1x 1x     1x   1x 173x 173x 173x     173x   24x               24x 24x       173x 4x 8x           169x 169x         1x 1x                   1x 33x     1x                                                                                                                               4x 4x 4x 4x 4x     4x   4x 1359x   1359x 4x 4x                       4x 4x     1359x 1359x       4x 4x 4x                           4x 8x     4x             1x 1x 1x   1x 10376x     10376x 349x   173x 172x               173x 173x           1x 1x             1x                                                             173x                     1x 1x         2x  
const { encoding_for_model, get_encoding } = require('tiktoken');
 
/**
 * Quản lý token counting và chunking
 */
class TokenManager {
  constructor(options = {}) {
    this.options = {
      model: options.model || 'gpt-4',
      maxTokens: options.maxTokens || 8000,
      chunkOverlap: options.chunkOverlap || 200,
      preserveStructure: options.preserveStructure !== false,
      ...options
    };
    
    this.encoding = null;
    this.initializeEncoding();
  }
 
  /**
   * Khởi tạo encoding
   */
  initializeEncoding() {
    try {
      // Thử sử dụng encoding cho model cụ thể
      this.encoding = encoding_for_model(this.options.model);
    } catch (error) {
      try {
        // Fallback to cl100k_base (GPT-4, GPT-3.5-turbo)
        this.encoding = get_encoding('cl100k_base');
      } catch (fallbackError) {
        // Fallback to p50k_base (GPT-3)
        this.encoding = get_encoding('p50k_base');
      }
    }
  }
 
  /**
   * Đếm tokens trong text
   */
  countTokens(text) {
    Iif (!text || typeof text !== 'string') {
      return 0;
    }
    
    try {
      const tokens = this.encoding.encode(text);
      return tokens.length;
    } catch (error) {
      // Fallback: estimate based on characters (rough approximation)
      return Math.ceil(text.length / 4);
    }
  }
 
  /**
   * Phân tích token usage cho một file
   */
  analyzeFile(file) {
    const headerTokens = this.countTokens(this.generateFileHeader(file));
    const contentTokens = this.countTokens(file.content);
    const totalTokens = headerTokens + contentTokens;
    
    return {
      file: file.relativePath,
      headerTokens,
      contentTokens,
      totalTokens,
      exceedsLimit: totalTokens > this.options.maxTokens,
      chunksNeeded: Math.ceil(totalTokens / this.options.maxTokens)
    };
  }
 
  /**
   * Phân tích token usage cho tất cả files
   */
  analyzeFiles(files) {
    const analyses = files.map(file => this.analyzeFile(file));
    
    const totalTokens = analyses.reduce((sum, analysis) => sum + analysis.totalTokens, 0);
    const filesExceedingLimit = analyses.filter(analysis => analysis.exceedsLimit);
    const totalChunks = analyses.reduce((sum, analysis) => sum + analysis.chunksNeeded, 0);
    
    return {
      files: analyses,
      summary: {
        totalFiles: files.length,
        totalTokens,
        averageTokensPerFile: Math.round(totalTokens / files.length),
        filesExceedingLimit: filesExceedingLimit.length,
        totalChunks,
        estimatedChunks: Math.ceil(totalTokens / this.options.maxTokens)
      }
    };
  }
 
  /**
   * Chia nhỏ content thành chunks
   */
  async chunkContent(content, metadata = {}) {
    const totalTokens = this.countTokens(content);
    
    Iif (totalTokens <= this.options.maxTokens) {
      return [{
        content,
        tokens: totalTokens,
        chunkIndex: 0,
        totalChunks: 1,
        metadata
      }];
    }
    
    return this.options.preserveStructure 
      ? await this.chunkByStructure(content, metadata)
      : await this.chunkByTokens(content, metadata);
  }
 
  /**
   * Chia nhỏ theo cấu trúc (ưu tiên giữ nguyên files)
   */
  async chunkByStructure(content, metadata = {}) {
    const chunks = [];
    const lines = content.split('\n');
    let currentChunk = '';
    let currentTokens = 0;
    let chunkIndex = 0;
    
    // Tìm file boundaries
    const fileBoundaries = this.findFileBoundaries(lines);
    
    for (let i = 0; i < fileBoundaries.length; i++) {
      const boundary = fileBoundaries[i];
      const fileContent = lines.slice(boundary.start, boundary.end).join('\n');
      const fileTokens = this.countTokens(fileContent);
      
      // Nếu file này làm chunk vượt quá limit
      if (currentTokens + fileTokens > this.options.maxTokens && currentChunk) {
        // Lưu chunk hiện tại
        chunks.push({
          content: currentChunk.trim(),
          tokens: currentTokens,
          chunkIndex: chunkIndex++,
          totalChunks: 0, // Sẽ update sau
          metadata: { ...metadata, type: 'structure' }
        });
        
        currentChunk = '';
        currentTokens = 0;
      }
      
      // Nếu file quá lớn, chia nhỏ file này
      if (fileTokens > this.options.maxTokens) {
        const fileChunks = await this.chunkLargeFile(fileContent, boundary.filePath);
        chunks.push(...fileChunks.map(chunk => ({
          ...chunk,
          chunkIndex: chunkIndex++,
          metadata: { ...metadata, ...chunk.metadata, type: 'large-file' }
        })));
      } else {
        currentChunk += fileContent + '\n';
        currentTokens += fileTokens;
      }
    }
    
    // Thêm chunk cuối cùng
    Eif (currentChunk.trim()) {
      chunks.push({
        content: currentChunk.trim(),
        tokens: currentTokens,
        chunkIndex: chunkIndex++,
        totalChunks: 0,
        metadata: { ...metadata, type: 'structure' }
      });
    }
    
    // Update totalChunks
    chunks.forEach(chunk => {
      chunk.totalChunks = chunks.length;
    });
    
    return chunks;
  }
 
  /**
   * Chia nhỏ theo tokens (simple splitting)
   */
  async chunkByTokens(content, metadata = {}) {
    const chunks = [];
    const lines = content.split('\n');
    let currentChunk = '';
    let currentTokens = 0;
    let chunkIndex = 0;
    
    for (const line of lines) {
      const lineTokens = this.countTokens(line + '\n');
      
      if (currentTokens + lineTokens > this.options.maxTokens && currentChunk) {
        // Lưu chunk hiện tại
        chunks.push({
          content: currentChunk.trim(),
          tokens: currentTokens,
          chunkIndex: chunkIndex++,
          totalChunks: 0,
          metadata: { ...metadata, type: 'token-based' }
        });
        
        // Bắt đầu chunk mới với overlap
        if (this.options.chunkOverlap > 0) {
          const overlapLines = this.getOverlapLines(currentChunk, this.options.chunkOverlap);
          currentChunk = overlapLines;
          currentTokens = this.countTokens(overlapLines);
        } else {
          currentChunk = '';
          currentTokens = 0;
        }
      }
      
      currentChunk += line + '\n';
      currentTokens += lineTokens;
    }
    
    // Thêm chunk cuối cùng
    if (currentChunk.trim()) {
      chunks.push({
        content: currentChunk.trim(),
        tokens: currentTokens,
        chunkIndex: chunkIndex++,
        totalChunks: 0,
        metadata: { ...metadata, type: 'token-based' }
      });
    }
    
    // Update totalChunks
    chunks.forEach(chunk => {
      chunk.totalChunks = chunks.length;
    });
    
    return chunks;
  }
 
  /**
   * Chia nhỏ file lớn
   */
  async chunkLargeFile(fileContent, filePath) {
    const lines = fileContent.split('\n');
    const chunks = [];
    let currentChunk = '';
    let currentTokens = 0;
    let chunkIndex = 0;
    
    // Thêm header cho file
    const header = `\n=== Large File: ${filePath} (Part {part}) ===\n`;
    
    for (const line of lines) {
      const lineTokens = this.countTokens(line + '\n');
      
      if (currentTokens + lineTokens > this.options.maxTokens - 100 && currentChunk) { // Reserve 100 tokens for header
        const partHeader = header.replace('{part}', (chunkIndex + 1).toString());
        chunks.push({
          content: partHeader + currentChunk.trim(),
          tokens: this.countTokens(partHeader + currentChunk.trim()),
          chunkIndex: chunkIndex++,
          totalChunks: 0,
          metadata: { 
            filePath,
            partNumber: chunkIndex + 1,
            type: 'large-file-part'
          }
        });
        
        currentChunk = '';
        currentTokens = 0;
      }
      
      currentChunk += line + '\n';
      currentTokens += lineTokens;
    }
    
    // Thêm chunk cuối cùng
    Eif (currentChunk.trim()) {
      const partHeader = header.replace('{part}', (chunkIndex + 1).toString());
      chunks.push({
        content: partHeader + currentChunk.trim(),
        tokens: this.countTokens(partHeader + currentChunk.trim()),
        chunkIndex: chunkIndex++,
        totalChunks: 0,
        metadata: { 
          filePath,
          partNumber: chunkIndex + 1,
          type: 'large-file-part'
        }
      });
    }
    
    // Update totalChunks
    chunks.forEach(chunk => {
      chunk.totalChunks = chunks.length;
    });
    
    return chunks;
  }
 
  /**
   * Tìm file boundaries trong content
   */
  findFileBoundaries(lines) {
    const boundaries = [];
    let currentStart = 0;
    let currentFilePath = null;
    
    for (let i = 0; i < lines.length; i++) {
      const line = lines[i];
      
      // Tìm file header pattern
      if (line.includes('================================================================================')) {
        if (i + 1 < lines.length && lines[i + 1].startsWith('File: ')) {
          // Lưu boundary trước đó
          if (currentFilePath) {
            boundaries.push({
              start: currentStart,
              end: i,
              filePath: currentFilePath
            });
          }
          
          // Bắt đầu file mới
          currentStart = i;
          currentFilePath = lines[i + 1].replace('File: ', '').trim();
        }
      }
    }
    
    // Thêm boundary cuối cùng
    Eif (currentFilePath) {
      boundaries.push({
        start: currentStart,
        end: lines.length,
        filePath: currentFilePath
      });
    }
    
    return boundaries;
  }
 
  /**
   * Lấy overlap lines
   */
  getOverlapLines(content, maxTokens) {
    const lines = content.split('\n');
    let overlapContent = '';
    let tokens = 0;
    
    // Lấy từ cuối lên
    for (let i = lines.length - 1; i >= 0; i--) {
      const line = lines[i] + '\n';
      const lineTokens = this.countTokens(line);
      
      if (tokens + lineTokens > maxTokens) {
        break;
      }
      
      overlapContent = line + overlapContent;
      tokens += lineTokens;
    }
    
    return overlapContent;
  }
 
  /**
   * Tạo file header
   */
  generateFileHeader(file) {
    return `
================================================================================
File: ${file.relativePath}
Size: ${file.size} bytes | Lines: ${file.lines}
================================================================================`;
  }
 
  /**
   * Cleanup encoding
   */
  cleanup() {
    Eif (this.encoding) {
      this.encoding.free();
    }
  }
}
 
module.exports = TokenManager;