-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path__main__.py
More file actions
307 lines (259 loc) · 8.93 KB
/
Copy path__main__.py
File metadata and controls
307 lines (259 loc) · 8.93 KB
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
"""
CLI entry point for LLM API Relay Authentication Benchmark.
Usage:
# Official mode: run against official API to record baseline
python -m llm_benchmark official --api-type openai --api-key $KEY --model gpt-4o -o baseline.json
# Test mode: run against relay service and compare
python -m llm_benchmark test --api-type openai --api-key $KEY --model gpt-4o \\
--base-url https://relay.test/v1 --baseline baseline.json -o results.json
# With config file:
python -m llm_benchmark --config config.json official
"""
import argparse
import json
import os
import sys
from typing import Optional
from llm_benchmark.runner import BenchmarkRunner
from llm_benchmark.reporter import BenchmarkReporter
def load_config(path: str) -> dict:
"""Load configuration from a JSON file."""
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="LLM API Relay Authentication Benchmark",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Official baseline recording
python -m llm_benchmark official --api-type openai --api-key sk-xxx --model gpt-4o -o baseline.json
# Test a relay service
python -m llm_benchmark test --api-type openai --api-key sk-yyy --model gpt-4o \\
--base-url https://relay.example.com/v1 --baseline baseline.json -o results.json
# Using config file
python -m llm_benchmark --config config.json official
""",
)
parser.add_argument(
"--config",
type=str,
help="Path to JSON config file. When provided, config values are used as defaults.",
)
# Shared arguments
parser.add_argument(
"--api-type",
type=str,
choices=["openai", "anthropic"],
default=None,
help='API type: "openai" (OpenAI-compatible) or "anthropic"',
)
parser.add_argument(
"--api-key",
type=str,
default=None,
help="API key. Can also be set via OPENAI_API_KEY or ANTHROPIC_API_KEY env vars.",
)
parser.add_argument(
"--model",
type=str,
default=None,
help="Model name (e.g., gpt-4o, claude-3-5-sonnet-20241022)",
)
parser.add_argument(
"--base-url",
type=str,
default=None,
help="Base URL for the API endpoint (required for relay services)",
)
parser.add_argument(
"--temperature",
type=float,
default=0.0,
help="Temperature setting (default: 0.0)",
)
parser.add_argument(
"--top-p",
type=float,
default=1.0,
help="Top-p setting (default: 1.0)",
)
parser.add_argument(
"--max-tokens",
type=int,
default=4096,
help="Max tokens for generation (default: 4096)",
)
parser.add_argument(
"--timeout",
type=float,
default=120.0,
help="API timeout in seconds (default: 120)",
)
parser.add_argument(
"--output", "-o",
type=str,
default=None,
help="Output file path for results",
)
# Subcommands
subparsers = parser.add_subparsers(dest="mode", help="Operation mode")
# Official mode
official_parser = subparsers.add_parser(
"official",
help="Run in official mode to record baseline results",
)
official_parser.add_argument(
"--output", "-o",
type=str,
default=None,
help="Output file for baseline results",
)
# Test mode
test_parser = subparsers.add_parser(
"test",
help="Run in test mode against a relay service",
)
test_parser.add_argument(
"--baseline", "-b",
type=str,
required=True,
help="Path to baseline JSON from official mode",
)
test_parser.add_argument(
"--output", "-o",
type=str,
default=None,
help="Output file for test results",
)
return parser
def resolve_args(args, config: Optional[dict] = None):
"""Resolve arguments, using config file values as defaults, then CLI args as overrides."""
env = os.environ
resolved = {}
if config:
resolved.update(config)
# Override with CLI args (only if explicitly set)
cli_args = vars(args)
# Map CLI arg names to expected keys
key_map = {
"api_type": "api_type",
"api_key": "api_key",
"model": "model",
"base_url": "base_url",
"temperature": "temperature",
"top_p": "top_p",
"max_tokens": "max_tokens",
"timeout": "timeout",
}
for cli_key, config_key in key_map.items():
val = cli_args.get(cli_key)
if val is not None:
resolved[config_key] = val
# Resolve API key from env if not set
if "api_key" not in resolved or not resolved["api_key"]:
api_type = resolved.get("api_type", "openai")
if api_type == "openai":
resolved["api_key"] = env.get("OPENAI_API_KEY", "")
elif api_type == "anthropic":
resolved["api_key"] = env.get("ANTHROPIC_API_KEY", "")
return resolved
def main():
parser = build_parser()
cli_args = parser.parse_args()
if not cli_args.mode:
parser.print_help()
sys.exit(1)
# Load config if provided
config = None
if cli_args.config:
if not os.path.exists(cli_args.config):
print(f"Error: Config file not found: {cli_args.config}")
sys.exit(1)
config = load_config(cli_args.config)
print(f" Loaded config from: {cli_args.config}")
resolved = resolve_args(cli_args, config)
# Validate required fields
api_type = resolved.get("api_type", "")
if not api_type:
print("Error: --api-type is required (openai or anthropic)")
sys.exit(1)
api_key = resolved.get("api_key", "")
if not api_key:
print(
"Error: --api-key is required. Set it directly or via "
"OPENAI_API_KEY / ANTHROPIC_API_KEY environment variable."
)
sys.exit(1)
model = resolved.get("model", "")
if not model:
print("Error: --model is required")
sys.exit(1)
base_url = resolved.get("base_url")
temperature = resolved.get("temperature", 0.0)
top_p = resolved.get("top_p", 1.0)
max_tokens = resolved.get("max_tokens", 4096)
timeout = resolved.get("timeout", 120.0)
# Determine output file
output_file = cli_args.output
if not output_file:
output_file = resolved.get("output")
if not output_file:
suffix = "baseline" if cli_args.mode == "official" else "results"
output_file = f"llm_benchmark_{suffix}_{model.replace('/', '_')}_{api_type}.json"
# Create runner
runner = BenchmarkRunner(
api_type=api_type,
api_key=api_key,
model=model,
base_url=base_url,
temperature=temperature,
top_p=top_p,
max_tokens=max_tokens,
timeout=timeout,
)
try:
if cli_args.mode == "official":
# Official mode: record baseline
run = runner.run_all()
BenchmarkReporter.print_summary(run)
BenchmarkReporter.save_json(run.to_dict(), output_file)
elif cli_args.mode == "test":
# Test mode: compare with baseline
baseline_file = cli_args.baseline
if not os.path.exists(baseline_file):
print(f"Error: Baseline file not found: {baseline_file}")
sys.exit(1)
run = runner.run_all(baseline_file=baseline_file)
BenchmarkReporter.print_summary(run)
# Load official run for comparison
with open(baseline_file, "r", encoding="utf-8") as f:
official_data = json.load(f)
# Reconstruct official run
from llm_benchmark.runner import BenchmarkRun, TestResult
official_results = []
for r_data in official_data.get("results", []):
official_results.append(TestResult(**r_data))
official_run = BenchmarkRun(
mode="official",
api_type=official_data.get("api_type", api_type),
model=official_data.get("model", model),
base_url=official_data.get("base_url"),
timestamp=official_data.get("timestamp", ""),
results=official_results,
temperature=official_data.get("temperature", temperature),
)
official_run.calculate_summary()
# Generate comparison
comparison = BenchmarkReporter.compare_runs(official_run, run)
BenchmarkReporter.print_comparison(comparison)
# Save results
output_data = {
"test_run": run.to_dict(),
"comparison": comparison,
}
BenchmarkReporter.save_json(output_data, output_file)
finally:
runner.close()
if __name__ == "__main__":
main()