All files / src/benchmark index.ts

0.79% Statements 1/126
100% Branches 0/0
0% Functions 0/3
0.79% Lines 1/126

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                                    1x                                                                                                                                                                                                                                                                                                                                                                        
/**
 * AgentKits — Provider Speed Benchmark
 *
 * Benchmarks latency and throughput across providers.
 *
 * Usage:
 *   import { benchmark } from 'agentkits/benchmark';
 *   const results = await benchmark({
 *     providers: [
 *       { provider: 'deepseek', apiKey: 'sk-...' },
 *       { provider: 'dashscope', apiKey: 'sk-...' },
 *     ],
 *     prompt: 'Say hello in one word.',
 *     runs: 3,
 *   });
 *   console.table(results);
 */
 
import { createChat, createEmbedding } from '../index.js';
import type { ChatConfig } from '../llm/index.js';
import type { EmbeddingConfig } from '../embedding/index.js';
 
// ── Types ──────────────────────────────────────────────────────────
 
export interface BenchmarkConfig {
  providers: ChatConfig[];
  prompt?: string;
  runs?: number;
  warmup?: boolean;
}
 
export interface EmbeddingBenchmarkConfig {
  providers: EmbeddingConfig[];
  text?: string;
  runs?: number;
  warmup?: boolean;
}
 
export interface BenchmarkResult {
  provider: string;
  model: string;
  avgLatencyMs: number;
  minLatencyMs: number;
  maxLatencyMs: number;
  p50LatencyMs: number;
  p95LatencyMs: number;
  avgTokensPerSec: number;
  successRate: string;
  errors: number;
}
 
// ── Chat Benchmark ─────────────────────────────────────────────────
 
export async function benchmark(config: BenchmarkConfig): Promise<BenchmarkResult[]> {
  const {
    providers,
    prompt = 'Say hello in exactly one word.',
    runs = 3,
    warmup = true,
  } = config;
 
  const results: BenchmarkResult[] = [];
 
  for (const providerConfig of providers) {
    const client = createChat(providerConfig);
    const latencies: number[] = [];
    const tokensPerSec: number[] = [];
    let errors = 0;
 
    // Warmup run
    if (warmup) {
      try {
        await client.complete('Hi');
      } catch { /* ignore warmup errors */ }
    }
 
    for (let i = 0; i < runs; i++) {
      const start = performance.now();
      try {
        const response = await client.chat(
          [{ role: 'user', content: prompt }],
          { maxTokens: 50 },
        );
        const elapsed = performance.now() - start;
        latencies.push(elapsed);
 
        if (response.usage) {
          const tps = response.usage.completionTokens / (elapsed / 1000);
          tokensPerSec.push(tps);
        }
      } catch {
        errors++;
      }
    }
 
    if (latencies.length > 0) {
      latencies.sort((a, b) => a - b);
      results.push({
        provider: client.config.provider,
        model: client.config.model,
        avgLatencyMs: Math.round(latencies.reduce((a, b) => a + b, 0) / latencies.length),
        minLatencyMs: Math.round(latencies[0]),
        maxLatencyMs: Math.round(latencies[latencies.length - 1]),
        p50LatencyMs: Math.round(percentile(latencies, 50)),
        p95LatencyMs: Math.round(percentile(latencies, 95)),
        avgTokensPerSec: tokensPerSec.length > 0
          ? Math.round(tokensPerSec.reduce((a, b) => a + b, 0) / tokensPerSec.length)
          : 0,
        successRate: `${latencies.length}/${runs}`,
        errors,
      });
    } else {
      results.push({
        provider: client.config.provider,
        model: client.config.model,
        avgLatencyMs: -1,
        minLatencyMs: -1,
        maxLatencyMs: -1,
        p50LatencyMs: -1,
        p95LatencyMs: -1,
        avgTokensPerSec: 0,
        successRate: `0/${runs}`,
        errors,
      });
    }
  }
 
  return results.sort((a, b) => a.avgLatencyMs - b.avgLatencyMs);
}
 
// ── Embedding Benchmark ────────────────────────────────────────────
 
export async function benchmarkEmbedding(config: EmbeddingBenchmarkConfig): Promise<BenchmarkResult[]> {
  const {
    providers,
    text = 'The quick brown fox jumps over the lazy dog.',
    runs = 5,
    warmup = true,
  } = config;
 
  const results: BenchmarkResult[] = [];
 
  for (const providerConfig of providers) {
    const client = createEmbedding(providerConfig);
    const latencies: number[] = [];
    let errors = 0;
 
    if (warmup) {
      try { await client.embed('warmup'); } catch { /* ignore */ }
    }
 
    for (let i = 0; i < runs; i++) {
      const start = performance.now();
      try {
        await client.embed(text);
        latencies.push(performance.now() - start);
      } catch {
        errors++;
      }
    }
 
    if (latencies.length > 0) {
      latencies.sort((a, b) => a - b);
      results.push({
        provider: client.config.provider,
        model: client.config.model,
        avgLatencyMs: Math.round(latencies.reduce((a, b) => a + b, 0) / latencies.length),
        minLatencyMs: Math.round(latencies[0]),
        maxLatencyMs: Math.round(latencies[latencies.length - 1]),
        p50LatencyMs: Math.round(percentile(latencies, 50)),
        p95LatencyMs: Math.round(percentile(latencies, 95)),
        avgTokensPerSec: 0,
        successRate: `${latencies.length}/${runs}`,
        errors,
      });
    } else {
      results.push({
        provider: client.config.provider,
        model: client.config.model,
        avgLatencyMs: -1, minLatencyMs: -1, maxLatencyMs: -1,
        p50LatencyMs: -1, p95LatencyMs: -1, avgTokensPerSec: 0,
        successRate: `0/${runs}`, errors,
      });
    }
  }
 
  return results.sort((a, b) => a.avgLatencyMs - b.avgLatencyMs);
}
 
// ── Helpers ─────────────────────────────────────────────────────────
 
function percentile(sorted: number[], p: number): number {
  const idx = (p / 100) * (sorted.length - 1);
  const lower = Math.floor(idx);
  const upper = Math.ceil(idx);
  if (lower === upper) return sorted[lower];
  return sorted[lower] + (sorted[upper] - sorted[lower]) * (idx - lower);
}