llm-bench 0.4.0

Compare LLM providers on your own prompts: OpenAI, Anthropic, OpenRouter, Groq, Together, Fireworks, DeepSeek, Gemini, Ollama or any OpenAI-compatible URL; time to first token, p50/p95 latency, tokens per second, error rate and cost, as a table, Markdown or JSON
Documentation
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//! # Module: Types
//!
//! ## Responsibility
//! Core domain types shared across all modules.  These are plain data structs  -
//! no business logic lives here.
//!
//! ## Guarantees
//! - All types are `Clone` + `Debug` + `serde::{Serialize, Deserialize}`.
//! - No panics; no fallible operations.

use serde::{Deserialize, Serialize};

//  Individual run result

/// The complete result of a single inference call against one model.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BenchResult {
    /// Provider name, e.g. `"openai"` or `"anthropic"`.
    pub provider: String,

    /// Model identifier, e.g. `"gpt-4o-mini"`.
    pub model: String,

    /// The prompt that was sent.
    pub prompt: String,

    /// Latency in ms: with `--stream`, the time from sending the request to
    /// the first piece of answer text (time to first token); without it, the
    /// time to the full response (equal to `total_ms`).
    pub latency_ms: u64,

    /// Wall time from request dispatch to full response received (ms).
    pub total_ms: u64,

    /// Number of prompt tokens billed by the provider.
    pub prompt_tokens: u32,

    /// Number of completion tokens billed by the provider.
    pub completion_tokens: u32,

    /// Estimated cost in USD for this request.
    pub cost_usd: f64,

    /// `completion_tokens / (total_ms / 1000.0)`  -  tokens generated per second.
    pub tokens_per_second: f64,

    /// The full text of the model's response.
    pub response_text: String,

    /// Zero-based index of this run within the prompt's run batch.
    pub run_index: u32,

    /// Time to first token in ms, only set for streamed requests
    /// (`--stream`). Absent from the JSON otherwise.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ttft_ms: Option<u64>,

    /// Retries this request needed before it succeeded (`--retries`).
    /// Absent from the JSON when zero.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub retries: u32,

    /// Time per output token after the first, in ms:
    /// `(total_ms - ttft_ms) / (completion_tokens - 1)`. Streamed requests
    /// with at least two completion tokens only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tpot_ms: Option<f64>,

    /// Prompt tokens served from the provider's prompt cache (OpenAI
    /// `prompt_tokens_details.cached_tokens`, DeepSeek
    /// `prompt_cache_hit_tokens`, Anthropic `cache_read_input_tokens`).
    /// Included in `prompt_tokens` for OpenAI-compatible APIs. Absent from
    /// the JSON when zero.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub cached_prompt_tokens: u32,

    /// Prompt tokens written to the provider's prompt cache (Anthropic
    /// `cache_creation_input_tokens`; not part of `prompt_tokens`). Absent
    /// from the JSON when zero.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub cache_write_prompt_tokens: u32,

    /// Where `cost_usd` came from. Absent when the model has no known price
    /// (`cost_usd` is then 0 and the table shows `n/a`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cost_source: Option<CostSource>,
}

/// Where a request's cost came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum CostSource {
    /// The provider reported the cost in the response (OpenRouter).
    Provider,
    /// A `[prices]` entry in the `--config` file.
    Config,
    /// List prices from the `llm-prices` crate.
    LlmPrices,
}

fn is_zero(n: &u32) -> bool {
    *n == 0
}

/// One request that failed, kept so the report can show real success rates
/// and tell the user why requests failed.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BenchFailure {
    /// Provider name.
    pub provider: String,
    /// Model identifier.
    pub model: String,
    /// Human-readable error message.
    pub error: String,
}

//  Benchmark configuration

/// Top-level configuration for a benchmark run.
#[derive(Debug, Clone)]
pub struct BenchConfig {
    /// The set of prompts to send to every configured provider/model.
    pub prompts: Vec<String>,

    /// How many times each prompt is sent to each provider (for statistical stability).
    pub runs_per_prompt: u32,

    /// Maximum number of in-flight API calls at any one time.
    pub concurrency: usize,

    /// One entry per provider+model combination to benchmark.
    pub providers: Vec<ProviderConfig>,

    /// Stream responses (server-sent events) to measure time to first token.
    pub stream: bool,

    /// Retries per request on HTTP 408, 429, 5xx and connection failures.
    pub retries: u32,

    /// Requests sent to each model before measuring, and discarded (cold
    /// starts, model loading on local servers).
    pub warmup: u32,
}

/// Configuration for a single provider+model combination.
#[derive(Debug, Clone)]
pub struct ProviderConfig {
    /// Provider: a built-in one (`"openai"`, `"anthropic"`, `"ollama"`,
    /// `"openrouter"`, `"gemini"`, `"groq"`, `"together"`, `"fireworks"`,
    /// `"deepseek"`) or a name from the `--config` file. Everything except
    /// `"anthropic"` speaks the OpenAI Chat Completions format. A name that
    /// is not built in needs a `base_url`.
    pub name: String,

    /// Model identifier string sent verbatim to the API.
    pub model: String,

    /// Bearer API key for this provider. May be empty for local
    /// OpenAI-compatible servers that do not check keys.
    pub api_key: String,

    /// API base URL without the `/v1` suffix, e.g. `https://api.openai.com`
    /// or `http://localhost:11434`. Empty means the provider's default URL.
    /// A URL that already ends in a version segment (`/v1beta/openai` for
    /// Gemini) is used as is.
    pub base_url: String,

    /// Maximum completion tokens to request.
    pub max_tokens: u32,
}

//  Aggregated summary

/// Aggregated statistics across all runs for a provider+model pair.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BenchSummary {
    /// Provider name.
    pub provider: String,

    /// Model identifier.
    pub model: String,

    /// Median (p50) latency across all runs (ms).
    pub p50_latency_ms: u64,

    /// 99th-percentile latency across all runs (ms).
    pub p99_latency_ms: u64,

    /// Average tokens-per-second across successful runs.
    pub avg_tokens_per_sec: f64,

    /// Average per-request cost in USD.
    pub avg_cost_usd: f64,

    /// Sum of cost across all runs in USD.
    pub total_cost_usd: f64,

    /// Fraction of runs that completed without error (0.0 - 1.0).
    pub success_rate: f64,
}

//  Tests

#[cfg(test)]
mod tests {
    use super::*;

    //  BenchResult

    fn sample_result(provider: &str, model: &str, latency: u64, cost: f64) -> BenchResult {
        BenchResult {
            provider: provider.into(),
            model: model.into(),
            prompt: "hello world".into(),
            latency_ms: latency,
            total_ms: latency + 50,
            prompt_tokens: 10,
            completion_tokens: 20,
            cost_usd: cost,
            tokens_per_second: 40.0,
            response_text: "Hi!".into(),
            run_index: 0,
            ttft_ms: None,
            retries: 0,
            tpot_ms: None,
            cached_prompt_tokens: 0,
            cache_write_prompt_tokens: 0,
            cost_source: None,
        }
    }

    #[test]
    fn test_bench_result_fields_are_accessible() {
        let r = sample_result("openai", "gpt-4o-mini", 120, 0.0001);
        assert_eq!(r.provider, "openai");
        assert_eq!(r.model, "gpt-4o-mini");
        assert_eq!(r.latency_ms, 120);
        assert_eq!(r.total_ms, 170);
        assert_eq!(r.prompt_tokens, 10);
        assert_eq!(r.completion_tokens, 20);
        assert!((r.cost_usd - 0.0001).abs() < 1e-10);
        assert!((r.tokens_per_second - 40.0).abs() < 1e-10);
    }

    #[test]
    fn test_bench_result_serialises_and_deserialises() {
        let r = sample_result("anthropic", "claude-haiku-4-5", 200, 0.0002);
        let json = serde_json::to_string(&r).unwrap_or_default();
        assert!(!json.is_empty(), "serialised JSON should not be empty");
        let restored: Result<BenchResult, _> = serde_json::from_str(&json);
        assert!(restored.is_ok(), "should deserialise cleanly");
        let restored = restored.unwrap_or_else(|_| sample_result("x", "y", 0, 0.0));
        assert_eq!(restored.provider, r.provider);
        assert_eq!(restored.model, r.model);
        assert_eq!(restored.latency_ms, r.latency_ms);
    }

    #[test]
    fn test_bench_result_is_clone() {
        let r = sample_result("openai", "gpt-4o", 300, 0.001);
        let cloned = r.clone();
        assert_eq!(cloned.provider, r.provider);
        assert_eq!(cloned.latency_ms, r.latency_ms);
    }

    #[test]
    fn test_bench_result_run_index_preserved() {
        let mut r = sample_result("openai", "gpt-4o", 100, 0.0);
        r.run_index = 7;
        assert_eq!(r.run_index, 7);
    }

    #[test]
    fn test_bench_result_tokens_per_second_zero_edge_case() {
        let mut r = sample_result("openai", "gpt-4o", 0, 0.0);
        r.tokens_per_second = 0.0;
        assert_eq!(r.tokens_per_second, 0.0);
    }

    //  BenchConfig

    fn sample_config() -> BenchConfig {
        BenchConfig {
            prompts: vec!["Say hi".into(), "Explain Rust".into()],
            runs_per_prompt: 3,
            concurrency: 4,
            providers: vec![ProviderConfig {
                name: "openai".into(),
                model: "gpt-4o-mini".into(),
                api_key: "sk-test".into(),
                base_url: String::new(),
                max_tokens: 512,
            }],
            stream: false,
            retries: 0,
            warmup: 0,
        }
    }

    #[test]
    fn test_bench_config_prompts_accessible() {
        let c = sample_config();
        assert_eq!(c.prompts.len(), 2);
        assert_eq!(c.prompts[0], "Say hi");
    }

    #[test]
    fn test_bench_config_runs_per_prompt() {
        let c = sample_config();
        assert_eq!(c.runs_per_prompt, 3);
    }

    #[test]
    fn test_bench_config_concurrency() {
        let c = sample_config();
        assert_eq!(c.concurrency, 4);
    }

    #[test]
    fn test_bench_config_providers_accessible() {
        let c = sample_config();
        assert_eq!(c.providers.len(), 1);
        assert_eq!(c.providers[0].name, "openai");
        assert_eq!(c.providers[0].model, "gpt-4o-mini");
        assert_eq!(c.providers[0].max_tokens, 512);
    }

    #[test]
    fn test_bench_config_is_clone() {
        let c = sample_config();
        let cloned = c.clone();
        assert_eq!(cloned.prompts.len(), c.prompts.len());
        assert_eq!(cloned.runs_per_prompt, c.runs_per_prompt);
    }

    #[test]
    fn test_provider_config_fields() {
        let p = ProviderConfig {
            name: "anthropic".into(),
            model: "claude-sonnet-5".into(),
            api_key: "sk-ant-test".into(),
            base_url: String::new(),
            max_tokens: 1024,
        };
        assert_eq!(p.name, "anthropic");
        assert_eq!(p.model, "claude-sonnet-5");
        assert_eq!(p.api_key, "sk-ant-test");
        assert_eq!(p.max_tokens, 1024);
    }

    //  BenchSummary

    fn sample_summary() -> BenchSummary {
        BenchSummary {
            provider: "openai".into(),
            model: "gpt-4o-mini".into(),
            p50_latency_ms: 150,
            p99_latency_ms: 400,
            avg_tokens_per_sec: 55.0,
            avg_cost_usd: 0.0003,
            total_cost_usd: 0.0009,
            success_rate: 1.0,
        }
    }

    #[test]
    fn test_bench_summary_p50_less_than_p99() {
        let s = sample_summary();
        assert!(
            s.p50_latency_ms <= s.p99_latency_ms,
            "p50 should not exceed p99"
        );
    }

    #[test]
    fn test_bench_summary_success_rate_in_range() {
        let s = sample_summary();
        assert!(
            (0.0..=1.0).contains(&s.success_rate),
            "success rate must be in [0,1]"
        );
    }

    #[test]
    fn test_bench_summary_total_cost_gte_avg() {
        let s = sample_summary();
        assert!(
            s.total_cost_usd >= s.avg_cost_usd,
            "total cost should be >= average cost"
        );
    }

    #[test]
    fn test_bench_summary_serialises() {
        let s = sample_summary();
        let json = serde_json::to_string(&s).unwrap_or_default();
        assert!(json.contains("openai"), "JSON should contain provider");
        assert!(
            json.contains("p50_latency_ms"),
            "JSON should contain field name"
        );
    }

    #[test]
    fn test_bench_summary_is_clone() {
        let s = sample_summary();
        let cloned = s.clone();
        assert_eq!(cloned.model, s.model);
        assert_eq!(cloned.p50_latency_ms, s.p50_latency_ms);
    }

    #[test]
    fn test_bench_summary_zero_success_rate() {
        let mut s = sample_summary();
        s.success_rate = 0.0;
        assert_eq!(s.success_rate, 0.0);
    }

    #[test]
    fn test_bench_summary_avg_tokens_per_sec_positive() {
        let s = sample_summary();
        assert!(s.avg_tokens_per_sec > 0.0, "avg tps should be positive");
    }

    #[test]
    fn test_bench_summary_provider_non_empty() {
        let s = sample_summary();
        assert!(!s.provider.is_empty());
    }

    #[test]
    fn test_bench_summary_model_non_empty() {
        let s = sample_summary();
        assert!(!s.model.is_empty());
    }

    #[test]
    fn test_bench_result_prompt_stored() {
        let r = sample_result("openai", "gpt-4o", 200, 0.001);
        assert_eq!(r.prompt, "hello world");
    }

    #[test]
    fn test_bench_result_total_ms_gte_latency() {
        let r = sample_result("openai", "gpt-4o", 100, 0.001);
        assert!(r.total_ms >= r.latency_ms);
    }

    #[test]
    fn test_bench_config_empty_prompts_allowed() {
        let c = BenchConfig {
            prompts: vec![],
            runs_per_prompt: 1,
            concurrency: 1,
            providers: vec![],
            stream: false,
            retries: 0,
            warmup: 0,
        };
        assert!(c.prompts.is_empty());
    }

    #[test]
    fn test_bench_config_zero_runs_allowed() {
        let c = BenchConfig {
            prompts: vec!["hi".into()],
            runs_per_prompt: 0,
            concurrency: 1,
            providers: vec![],
            stream: false,
            retries: 0,
            warmup: 0,
        };
        assert_eq!(c.runs_per_prompt, 0);
    }

    #[test]
    fn test_bench_result_deserialise_missing_field_fails() {
        // A JSON object with a missing required field should fail to deserialise
        let bad_json = r#"{"provider":"openai"}"#;
        let result: Result<BenchResult, _> = serde_json::from_str(bad_json);
        assert!(
            result.is_err(),
            "incomplete JSON should fail to deserialise"
        );
    }

    #[test]
    fn test_bench_summary_avg_cost_non_negative() {
        let s = sample_summary();
        assert!(s.avg_cost_usd >= 0.0);
    }

    #[test]
    fn test_bench_summary_total_cost_non_negative() {
        let s = sample_summary();
        assert!(s.total_cost_usd >= 0.0);
    }
}