| |
| """ |
| Benchmark latency for multiple OpenAI-compatible API groups and models. |
| |
| Metrics: |
| - TTFT: time to first non-empty content/reasoning token |
| - Total latency: time until stream completion |
| - Output throughput: completion tokens per second when usage is available |
| - Success rate, median, mean, and p95 across repeated runs |
| |
| Install: |
| pip install -U openai |
| |
| Security: |
| You may store api_key directly in the JSON config, but do not commit |
| that config file to Git or share it publicly. |
| |
| Run: |
| python kimi_latency_benchmark.py --config kimi_groups.json --repeats 5 --warmup 1 |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import csv |
| import json |
| import math |
| import os |
| import statistics |
| import sys |
| import time |
| from dataclasses import dataclass, asdict |
| from pathlib import Path |
| from typing import Any, Iterable |
|
|
| from openai import OpenAI |
|
|
|
|
| @dataclass |
| class RunResult: |
| group: str |
| model: str |
| run_index: int |
| is_warmup: bool |
| success: bool |
| ttft_ms: float | None |
| total_ms: float | None |
| completion_tokens: int | None |
| tokens_per_second: float | None |
| output_chars: int |
| error: str |
|
|
|
|
| def percentile(values: list[float], p: float) -> float | None: |
| if not values: |
| return None |
| ordered = sorted(values) |
| index = max(0, min(len(ordered) - 1, math.ceil(p * len(ordered)) - 1)) |
| return ordered[index] |
|
|
|
|
| def mean_or_none(values: list[float]) -> float | None: |
| return statistics.mean(values) if values else None |
|
|
|
|
| def median_or_none(values: list[float]) -> float | None: |
| return statistics.median(values) if values else None |
|
|
|
|
| def fmt(value: float | None, digits: int = 1) -> str: |
| return "-" if value is None else f"{value:.{digits}f}" |
|
|
|
|
| def get_text_from_delta(delta: Any) -> str: |
| """Support both normal content and reasoning_content used by some models.""" |
| pieces: list[str] = [] |
|
|
| content = getattr(delta, "content", None) |
| if isinstance(content, str): |
| pieces.append(content) |
|
|
| reasoning = getattr(delta, "reasoning_content", None) |
| if isinstance(reasoning, str): |
| pieces.append(reasoning) |
|
|
| return "".join(pieces) |
|
|
|
|
| def create_stream( |
| client: OpenAI, |
| model: str, |
| prompt: str, |
| max_tokens: int, |
| temperature: float, |
| extra_body: dict[str, Any] | None, |
| include_usage: bool, |
| ): |
| kwargs: dict[str, Any] = { |
| "model": model, |
| "messages": [{"role": "user", "content": prompt}], |
| "stream": True, |
| "max_tokens": max_tokens, |
| "temperature": temperature, |
| } |
| if extra_body: |
| kwargs["extra_body"] = extra_body |
| if include_usage: |
| kwargs["stream_options"] = {"include_usage": True} |
| return client.chat.completions.create(**kwargs) |
|
|
|
|
| def benchmark_once( |
| client: OpenAI, |
| group_name: str, |
| model: str, |
| run_index: int, |
| is_warmup: bool, |
| prompt: str, |
| max_tokens: int, |
| temperature: float, |
| extra_body: dict[str, Any] | None, |
| ) -> RunResult: |
| start = time.perf_counter() |
| first_text_at: float | None = None |
| output_parts: list[str] = [] |
| completion_tokens: int | None = None |
|
|
| try: |
| |
| try: |
| stream = create_stream( |
| client=client, |
| model=model, |
| prompt=prompt, |
| max_tokens=max_tokens, |
| temperature=temperature, |
| extra_body=extra_body, |
| include_usage=True, |
| ) |
| except Exception: |
| |
| stream = create_stream( |
| client=client, |
| model=model, |
| prompt=prompt, |
| max_tokens=max_tokens, |
| temperature=temperature, |
| extra_body=extra_body, |
| include_usage=False, |
| ) |
|
|
| for chunk in stream: |
| now = time.perf_counter() |
|
|
| choices = getattr(chunk, "choices", None) or [] |
| if choices: |
| delta = getattr(choices[0], "delta", None) |
| if delta is not None: |
| text = get_text_from_delta(delta) |
| if text: |
| if first_text_at is None: |
| first_text_at = now |
| output_parts.append(text) |
|
|
| usage = getattr(chunk, "usage", None) |
| if usage is not None: |
| value = getattr(usage, "completion_tokens", None) |
| if isinstance(value, int): |
| completion_tokens = value |
|
|
| end = time.perf_counter() |
| total_s = end - start |
| ttft_ms = ( |
| (first_text_at - start) * 1000 |
| if first_text_at is not None |
| else None |
| ) |
| total_ms = total_s * 1000 |
| tokens_per_second = ( |
| completion_tokens / total_s |
| if completion_tokens is not None and total_s > 0 |
| else None |
| ) |
|
|
| return RunResult( |
| group=group_name, |
| model=model, |
| run_index=run_index, |
| is_warmup=is_warmup, |
| success=True, |
| ttft_ms=ttft_ms, |
| total_ms=total_ms, |
| completion_tokens=completion_tokens, |
| tokens_per_second=tokens_per_second, |
| output_chars=sum(len(x) for x in output_parts), |
| error="", |
| ) |
|
|
| except Exception as exc: |
| end = time.perf_counter() |
| return RunResult( |
| group=group_name, |
| model=model, |
| run_index=run_index, |
| is_warmup=is_warmup, |
| success=False, |
| ttft_ms=None, |
| total_ms=(end - start) * 1000, |
| completion_tokens=None, |
| tokens_per_second=None, |
| output_chars=0, |
| error=f"{type(exc).__name__}: {exc}", |
| ) |
|
|
|
|
| def load_groups(config_path: Path) -> list[dict[str, Any]]: |
| data = json.loads(config_path.read_text(encoding="utf-8")) |
| if not isinstance(data, list) or not data: |
| raise ValueError("配置文件顶层必须是非空 JSON 数组。") |
|
|
| required = {"name", "base_url", "models"} |
| for index, group in enumerate(data): |
| if not isinstance(group, dict): |
| raise ValueError(f"第 {index + 1} 个分组不是 JSON 对象。") |
|
|
| missing = required - set(group) |
| if missing: |
| raise ValueError( |
| f"分组 {group.get('name', index + 1)} 缺少字段:{sorted(missing)}" |
| ) |
|
|
| if not group.get("api_key") and not group.get("api_key_env"): |
| raise ValueError( |
| f"分组 {group.get('name', index + 1)} 必须提供 " |
| f"api_key 或 api_key_env。" |
| ) |
| return data |
|
|
|
|
| def resolve_models(client: OpenAI, value: Any) -> list[str]: |
| if value == "auto": |
| response = client.models.list() |
| return sorted(model.id for model in response.data) |
|
|
| if isinstance(value, list) and all(isinstance(x, str) for x in value): |
| return value |
|
|
| raise ValueError('models 必须是字符串数组,或字符串 "auto"。') |
|
|
|
|
| def write_raw_csv(path: Path, results: Iterable[RunResult]) -> None: |
| rows = [asdict(item) for item in results] |
| fieldnames = list(RunResult.__annotations__.keys()) |
| with path.open("w", newline="", encoding="utf-8-sig") as file: |
| writer = csv.DictWriter(file, fieldnames=fieldnames) |
| writer.writeheader() |
| writer.writerows(rows) |
|
|
|
|
| def build_summary(results: list[RunResult]) -> list[dict[str, Any]]: |
| keys = sorted({(r.group, r.model) for r in results if not r.is_warmup}) |
| summary: list[dict[str, Any]] = [] |
|
|
| for group, model in keys: |
| subset = [ |
| r for r in results |
| if r.group == group and r.model == model and not r.is_warmup |
| ] |
| successes = [r for r in subset if r.success] |
| ttfts = [r.ttft_ms for r in successes if r.ttft_ms is not None] |
| totals = [r.total_ms for r in successes if r.total_ms is not None] |
| tps_values = [ |
| r.tokens_per_second |
| for r in successes |
| if r.tokens_per_second is not None |
| ] |
|
|
| summary.append( |
| { |
| "group": group, |
| "model": model, |
| "runs": len(subset), |
| "successes": len(successes), |
| "success_rate": len(successes) / len(subset) if subset else 0.0, |
| "ttft_mean_ms": mean_or_none(ttfts), |
| "ttft_median_ms": median_or_none(ttfts), |
| "ttft_p95_ms": percentile(ttfts, 0.95), |
| "total_mean_ms": mean_or_none(totals), |
| "total_median_ms": median_or_none(totals), |
| "total_p95_ms": percentile(totals, 0.95), |
| "tokens_per_second_mean": mean_or_none(tps_values), |
| } |
| ) |
|
|
| return summary |
|
|
|
|
| def write_summary_csv(path: Path, summary: list[dict[str, Any]]) -> None: |
| if not summary: |
| return |
| with path.open("w", newline="", encoding="utf-8-sig") as file: |
| writer = csv.DictWriter(file, fieldnames=list(summary[0].keys())) |
| writer.writeheader() |
| writer.writerows(summary) |
|
|
|
|
| def print_summary(summary: list[dict[str, Any]]) -> None: |
| headers = [ |
| "Group", |
| "Model", |
| "Success", |
| "TTFT median", |
| "TTFT p95", |
| "Total median", |
| "Total p95", |
| "Tok/s", |
| ] |
|
|
| rows: list[list[str]] = [] |
| for row in summary: |
| rows.append( |
| [ |
| str(row["group"]), |
| str(row["model"]), |
| f'{row["successes"]}/{row["runs"]}', |
| f'{fmt(row["ttft_median_ms"])} ms', |
| f'{fmt(row["ttft_p95_ms"])} ms', |
| f'{fmt(row["total_median_ms"])} ms', |
| f'{fmt(row["total_p95_ms"])} ms', |
| fmt(row["tokens_per_second_mean"], 2), |
| ] |
| ) |
|
|
| widths = [ |
| max(len(headers[i]), *(len(row[i]) for row in rows)) |
| for i in range(len(headers)) |
| ] |
|
|
| line = " | ".join(headers[i].ljust(widths[i]) for i in range(len(headers))) |
| separator = "-+-".join("-" * width for width in widths) |
| print("\n" + line) |
| print(separator) |
| for row in rows: |
| print(" | ".join(row[i].ljust(widths[i]) for i in range(len(headers)))) |
|
|
|
|
| def parse_args() -> argparse.Namespace: |
| parser = argparse.ArgumentParser( |
| description="测试多个 API 分组及模型的 TTFT 和完整响应延迟。" |
| ) |
| parser.add_argument( |
| "--config", |
| default="kimi_groups.json", |
| help="分组配置文件路径,默认 kimi_groups.json", |
| ) |
| parser.add_argument( |
| "--repeats", |
| type=int, |
| default=5, |
| help="每个模型正式测试次数,默认 5", |
| ) |
| parser.add_argument( |
| "--warmup", |
| type=int, |
| default=1, |
| help="每个模型预热次数,不计入汇总,默认 1", |
| ) |
| parser.add_argument( |
| "--max-tokens", |
| type=int, |
| default=64, |
| help="最大输出 token 数,默认 64", |
| ) |
| parser.add_argument( |
| "--temperature", |
| type=float, |
| default=0.0, |
| help="temperature,默认 0", |
| ) |
| parser.add_argument( |
| "--timeout", |
| type=float, |
| default=120.0, |
| help="单次请求超时秒数,默认 120", |
| ) |
| parser.add_argument( |
| "--sleep", |
| type=float, |
| default=0.5, |
| help="两次请求间隔秒数,默认 0.5", |
| ) |
| parser.add_argument( |
| "--prompt", |
| default=( |
| "请用一句简短的中文说明什么是大语言模型。" |
| "不要使用项目符号,不要超过50个汉字。" |
| ), |
| help="所有模型使用的固定测试提示词", |
| ) |
| parser.add_argument( |
| "--output-prefix", |
| default="kimi_latency", |
| help="输出文件名前缀,默认 kimi_latency", |
| ) |
| return parser.parse_args() |
|
|
|
|
| def main() -> int: |
| args = parse_args() |
| if args.repeats <= 0 or args.warmup < 0: |
| print("repeats 必须大于 0,warmup 不能小于 0。", file=sys.stderr) |
| return 2 |
|
|
| config_path = Path(args.config) |
| groups = load_groups(config_path) |
| all_results: list[RunResult] = [] |
|
|
| for group in groups: |
| group_name = str(group["name"]) |
| api_key = str(group.get("api_key", "")).strip() |
| key_env = str(group.get("api_key_env", "")).strip() |
|
|
| if not api_key and key_env: |
| api_key = os.getenv(key_env, "").strip() |
|
|
| if not api_key: |
| source_hint = ( |
| f"配置中的 api_key 或环境变量 {key_env}" |
| if key_env |
| else "配置中的 api_key" |
| ) |
| print( |
| f"\n[跳过] 分组 {group_name}: 未找到有效 Key,请检查 {source_hint}。", |
| file=sys.stderr, |
| ) |
| continue |
|
|
| client = OpenAI( |
| api_key=api_key, |
| base_url=str(group["base_url"]).rstrip("/"), |
| timeout=args.timeout, |
| max_retries=0, |
| ) |
|
|
| try: |
| models = resolve_models(client, group["models"]) |
| except Exception as exc: |
| print( |
| f"\n[跳过] 分组 {group_name} 获取模型列表失败:" |
| f"{type(exc).__name__}: {exc}", |
| file=sys.stderr, |
| ) |
| continue |
|
|
| if not models: |
| print(f"\n[跳过] 分组 {group_name} 没有模型。", file=sys.stderr) |
| continue |
|
|
| print(f"\n=== 分组:{group_name},模型数:{len(models)} ===") |
| extra_body = group.get("extra_body") |
| total_runs = args.warmup + args.repeats |
|
|
| for model in models: |
| print(f"\n模型:{model}") |
| for index in range(total_runs): |
| is_warmup = index < args.warmup |
| label = "warmup" if is_warmup else f"run {index - args.warmup + 1}" |
|
|
| result = benchmark_once( |
| client=client, |
| group_name=group_name, |
| model=model, |
| run_index=index + 1, |
| is_warmup=is_warmup, |
| prompt=args.prompt, |
| max_tokens=args.max_tokens, |
| temperature=args.temperature, |
| extra_body=extra_body, |
| ) |
| all_results.append(result) |
|
|
| if result.success: |
| print( |
| f" {label:<8} " |
| f"TTFT={fmt(result.ttft_ms)} ms, " |
| f"Total={fmt(result.total_ms)} ms, " |
| f"Tok/s={fmt(result.tokens_per_second, 2)}" |
| ) |
| else: |
| print(f" {label:<8} ERROR: {result.error}") |
|
|
| if args.sleep > 0 and index + 1 < total_runs: |
| time.sleep(args.sleep) |
|
|
| if not all_results: |
| print("\n没有产生测试结果。请检查配置和 API Key。", file=sys.stderr) |
| return 1 |
|
|
| raw_path = Path(f"{args.output_prefix}_raw.csv") |
| summary_path = Path(f"{args.output_prefix}_summary.csv") |
|
|
| write_raw_csv(raw_path, all_results) |
| summary = build_summary(all_results) |
| write_summary_csv(summary_path, summary) |
| print_summary(summary) |
|
|
| print(f"\n原始结果:{raw_path.resolve()}") |
| print(f"汇总结果:{summary_path.resolve()}") |
| return 0 |
|
|
|
|
| if __name__ == "__main__": |
| raise SystemExit(main()) |