Skip to content

5. 自动压缩

5.1 压缩策略

typescript
class MemoryCompressor {
  // 压缩工具输出
  async compressToolOutput(output: string): Promise<string> {
    // 1. 检测输出类型
    const type = this.detectOutputType(output);

    // 2. 应用特定压缩策略
    switch (type) {
      case 'file_content':
        return this.compressFileContent(output);
      case 'command_output':
        return this.compressCommandOutput(output);
      case 'search_results':
        return this.compressSearchResults(output);
      default:
        return this.compressGeneric(output);
    }
  }

  // 压缩文件内容
  private async compressFileContent(content: string): Promise<string> {
    const prompt = `
Summarize this file content, preserving:
- Key functions and their purposes
- Important data structures
- Critical logic
- Notable patterns or issues

File content:
${content}

Provide a concise summary (max 500 tokens).
`;

    return await llm.complete(prompt);
  }

  // 压缩命令输出
  private compressCommandOutput(output: string): Promise<string> {
    // 提取关键信息
    const lines = output.split('\n');

    // 保留:
    // - 错误信息
    // - 警告
    // - 最终结果
    // - 重要统计

    const errors = lines.filter(l => /error|fail/i.test(l));
    const warnings = lines.filter(l => /warn/i.test(l));
    const summary = lines.slice(-5);  // 最后 5 行

    return [
      errors.length > 0 ? `Errors:\n${errors.join('\n')}` : '',
      warnings.length > 0 ? `Warnings:\n${warnings.join('\n')}` : '',
      `Summary:\n${summary.join('\n')}`
    ].filter(Boolean).join('\n\n');
  }

  // 压缩搜索结果
  private async compressSearchResults(results: string): Promise<string> {
    const prompt = `
Summarize these search results:
${results}

Focus on:
- Most relevant findings
- Key patterns
- Important file locations

Max 300 tokens.
`;

    return await llm.complete(prompt);
  }
}

5.2 增量压缩

typescript
class IncrementalCompressor {
  private compressionQueue: CompressTask[] = [];
  private isCompressing = false;

  // 添加到压缩队列
  enqueue(content: string, priority: number = 0) {
    this.compressionQueue.push({
      content,
      priority,
      timestamp: Date.now()
    });

    // 触发压缩
    this.processQueue();
  }

  // 处理压缩队列
  private async processQueue() {
    if (this.isCompressing) return;
    this.isCompressing = true;

    try {
      while (this.compressionQueue.length > 0) {
        // 按优先级排序
        this.compressionQueue.sort((a, b) => b.priority - a.priority);

        const task = this.compressionQueue.shift()!;

        // 压缩
        const compressed = await this.compress(task.content);

        // 保存
        await this.saveCompressed(compressed);

        // 避免过载
        await sleep(100);
      }
    } finally {
      this.isCompressing = false;
    }
  }

  // 批量压缩
  async compressBatch(contents: string[]): Promise<string[]> {
    const prompt = `
Compress these ${contents.length} pieces of information into concise summaries:

${contents.map((c, i) => `[${i + 1}]\n${c}`).join('\n\n---\n\n')}

Return a JSON array of summaries.
`;

    const response = await llm.complete(prompt);
    return JSON.parse(response);
  }
}

前端面试知识库