forked from 1jehuang/jcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompare_token_usage.py
More file actions
executable file
·500 lines (424 loc) · 16.4 KB
/
compare_token_usage.py
File metadata and controls
executable file
·500 lines (424 loc) · 16.4 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
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
500
#!/usr/bin/env python3
"""
Compare token usage between jcode and Claude Code CLI.
This script runs the same prompts through both tools and compares their token usage.
The goal is to verify that jcode's token consumption is within expected bounds
compared to the official Claude Code CLI.
NOTE: jcode typically uses FEWER tokens than Claude CLI because:
1. jcode has a smaller/simpler system prompt
2. jcode registers fewer tools (Claude CLI has many built-in tools)
3. Different prompt caching behavior
The test PASSES if jcode uses fewer tokens OR at most 50% more tokens.
Using more tokens would indicate a problem with the system prompt or tool registration.
Usage:
python scripts/compare_token_usage.py [--verbose] [--runs N]
Requirements:
- jcode built and in PATH or at target/release/jcode
- claude CLI installed and authenticated
- Both should use the same model (claude-opus-4-5-20251101 by default)
"""
import argparse
import json
import os
import subprocess
import sys
import tempfile
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Optional
@dataclass
class TokenUsage:
"""Token usage from a single run."""
input_tokens: int
output_tokens: int
cache_read_tokens: int
cache_creation_tokens: int
total_cost_usd: Optional[float] = None
duration_ms: Optional[int] = None
@property
def total_input(self) -> int:
"""Total input tokens including cache."""
return self.input_tokens + self.cache_read_tokens + self.cache_creation_tokens
@property
def total(self) -> int:
"""Total tokens (input + output)."""
return self.total_input + self.output_tokens
@dataclass
class RunResult:
"""Result of a single tool run."""
tool: str
prompt: str
usage: TokenUsage
success: bool
output: str
error: Optional[str] = None
def find_jcode_binary() -> str:
"""Find the jcode binary."""
# Check target/release first
repo_root = Path(__file__).parent.parent
release_binary = repo_root / "target" / "release" / "jcode"
if release_binary.exists():
return str(release_binary)
# Check PATH
result = subprocess.run(["which", "jcode"], capture_output=True, text=True)
if result.returncode == 0:
return result.stdout.strip()
raise FileNotFoundError("jcode binary not found. Run 'cargo build --release' first.")
def run_claude_cli(prompt: str, workdir: str, model: str = "opus") -> RunResult:
"""Run the Claude Code CLI and capture token usage."""
try:
result = subprocess.run(
[
"claude",
"-p",
"--output-format", "json",
"--dangerously-skip-permissions",
"--model", model,
prompt,
],
capture_output=True,
text=True,
cwd=workdir,
timeout=120,
)
if result.returncode != 0 and not result.stdout:
return RunResult(
tool="claude",
prompt=prompt,
usage=TokenUsage(0, 0, 0, 0),
success=False,
output="",
error=result.stderr or f"Exit code {result.returncode}",
)
# Parse JSON output
data = json.loads(result.stdout)
usage = data.get("usage", {})
token_usage = TokenUsage(
input_tokens=usage.get("input_tokens", 0),
output_tokens=usage.get("output_tokens", 0),
cache_read_tokens=usage.get("cache_read_input_tokens", 0),
cache_creation_tokens=usage.get("cache_creation_input_tokens", 0),
total_cost_usd=data.get("total_cost_usd"),
duration_ms=data.get("duration_ms"),
)
return RunResult(
tool="claude",
prompt=prompt,
usage=token_usage,
success=not data.get("is_error", False),
output=data.get("result", ""),
)
except subprocess.TimeoutExpired:
return RunResult(
tool="claude",
prompt=prompt,
usage=TokenUsage(0, 0, 0, 0),
success=False,
output="",
error="Timeout after 120s",
)
except json.JSONDecodeError as e:
return RunResult(
tool="claude",
prompt=prompt,
usage=TokenUsage(0, 0, 0, 0),
success=False,
output=result.stdout if 'result' in dir() else "",
error=f"JSON parse error: {e}",
)
except Exception as e:
return RunResult(
tool="claude",
prompt=prompt,
usage=TokenUsage(0, 0, 0, 0),
success=False,
output="",
error=str(e),
)
def run_jcode(prompt: str, workdir: str, jcode_binary: str, model: str = "claude-opus-4-5-20251101") -> RunResult:
"""Run jcode and capture token usage from trace output."""
try:
# Create a temporary JCODE_HOME to avoid polluting user's sessions
with tempfile.TemporaryDirectory() as tmpdir:
env = os.environ.copy()
env["JCODE_HOME"] = tmpdir
env["JCODE_TRACE"] = "1"
result = subprocess.run(
[
jcode_binary,
"run",
"--no-update",
"--model", model,
prompt,
],
capture_output=True,
text=True,
cwd=workdir,
timeout=120,
env=env,
)
# Parse token usage from trace output in stderr
# Format: [trace] token_usage input=X output=Y cache_read=Z cache_write=W
input_tokens = 0
output_tokens = 0
cache_read = 0
cache_write = 0
for line in result.stderr.split("\n"):
if "[trace] token_usage" in line:
parts = line.split()
for part in parts:
if part.startswith("input="):
input_tokens = int(part.split("=")[1])
elif part.startswith("output="):
output_tokens = int(part.split("=")[1])
elif part.startswith("cache_read="):
cache_read = int(part.split("=")[1])
elif part.startswith("cache_write="):
cache_write = int(part.split("=")[1])
token_usage = TokenUsage(
input_tokens=input_tokens,
output_tokens=output_tokens,
cache_read_tokens=cache_read,
cache_creation_tokens=cache_write,
)
return RunResult(
tool="jcode",
prompt=prompt,
usage=token_usage,
success=result.returncode == 0,
output=result.stdout,
error=None if result.returncode == 0 else result.stderr,
)
except subprocess.TimeoutExpired:
return RunResult(
tool="jcode",
prompt=prompt,
usage=TokenUsage(0, 0, 0, 0),
success=False,
output="",
error="Timeout after 120s",
)
except Exception as e:
return RunResult(
tool="jcode",
prompt=prompt,
usage=TokenUsage(0, 0, 0, 0),
success=False,
output="",
error=str(e),
)
def compare_usage(claude_result: RunResult, jcode_result: RunResult, verbose: bool = False) -> dict:
"""Compare token usage between Claude CLI and jcode."""
c = claude_result.usage
j = jcode_result.usage
# Calculate differences
input_diff = j.input_tokens - c.input_tokens
output_diff = j.output_tokens - c.output_tokens
cache_read_diff = j.cache_read_tokens - c.cache_read_tokens
cache_write_diff = j.cache_creation_tokens - c.cache_creation_tokens
total_diff = j.total - c.total
# Calculate percentages (avoid division by zero)
def pct_diff(a: int, b: int) -> float:
if b == 0:
return 0.0 if a == 0 else float('inf')
return ((a - b) / b) * 100
input_pct = pct_diff(j.input_tokens, c.input_tokens)
output_pct = pct_diff(j.output_tokens, c.output_tokens)
total_pct = pct_diff(j.total, c.total)
return {
"claude": {
"input": c.input_tokens,
"output": c.output_tokens,
"cache_read": c.cache_read_tokens,
"cache_write": c.cache_creation_tokens,
"total": c.total,
"cost_usd": c.total_cost_usd,
"duration_ms": c.duration_ms,
},
"jcode": {
"input": j.input_tokens,
"output": j.output_tokens,
"cache_read": j.cache_read_tokens,
"cache_write": j.cache_creation_tokens,
"total": j.total,
},
"diff": {
"input": input_diff,
"output": output_diff,
"cache_read": cache_read_diff,
"cache_write": cache_write_diff,
"total": total_diff,
},
"pct_diff": {
"input": input_pct,
"output": output_pct,
"total": total_pct,
},
}
def print_comparison(comparison: dict, prompt: str, verbose: bool = False):
"""Print a formatted comparison."""
print(f"\n{'='*60}")
print(f"Prompt: {prompt[:50]}..." if len(prompt) > 50 else f"Prompt: {prompt}")
print(f"{'='*60}")
c = comparison["claude"]
j = comparison["jcode"]
d = comparison["diff"]
p = comparison["pct_diff"]
print(f"\n{'Metric':<20} {'Claude':<15} {'jcode':<15} {'Diff':<15} {'% Diff':<10}")
print("-" * 75)
print(f"{'Input tokens':<20} {c['input']:<15} {j['input']:<15} {d['input']:+<15} {p['input']:+.1f}%")
print(f"{'Output tokens':<20} {c['output']:<15} {j['output']:<15} {d['output']:+<15} {p['output']:+.1f}%")
print(f"{'Cache read':<20} {c['cache_read']:<15} {j['cache_read']:<15} {d['cache_read']:+<15}")
print(f"{'Cache write':<20} {c['cache_write']:<15} {j['cache_write']:<15} {d['cache_write']:+<15}")
print("-" * 75)
print(f"{'TOTAL':<20} {c['total']:<15} {j['total']:<15} {d['total']:+<15} {p['total']:+.1f}%")
if c.get("cost_usd"):
print(f"\nClaude CLI cost: ${c['cost_usd']:.6f}")
if c.get("duration_ms"):
print(f"Claude CLI duration: {c['duration_ms']}ms")
def run_test_suite(verbose: bool = False, runs: int = 1) -> list:
"""Run the full test suite."""
# Test prompts - simple ones that don't require tools
prompts = [
"Reply with a single word: test",
"What is 2 + 2? Reply with just the number.",
"List three primary colors, one per line.",
]
jcode_binary = find_jcode_binary()
print(f"Using jcode binary: {jcode_binary}")
print(f"Running {len(prompts)} prompts, {runs} run(s) each\n")
results = []
with tempfile.TemporaryDirectory() as workdir:
for prompt in prompts:
for run_num in range(runs):
print(f"\n[Run {run_num + 1}/{runs}] Testing: {prompt[:40]}...")
# Run both tools
print(" Running Claude CLI...", end=" ", flush=True)
claude_result = run_claude_cli(prompt, workdir)
if claude_result.success:
print(f"OK ({claude_result.usage.total} tokens)")
else:
print(f"FAILED: {claude_result.error}")
if verbose:
print(f" Output: {claude_result.output[:200]}")
# Small delay to avoid rate limiting
time.sleep(1)
print(" Running jcode...", end=" ", flush=True)
jcode_result = run_jcode(prompt, workdir, jcode_binary)
if jcode_result.success:
print(f"OK ({jcode_result.usage.total} tokens)")
else:
print(f"FAILED: {jcode_result.error}")
if verbose:
print(f" Output: {jcode_result.output[:200]}")
if claude_result.success and jcode_result.success:
comparison = compare_usage(claude_result, jcode_result, verbose)
results.append({
"prompt": prompt,
"run": run_num + 1,
"comparison": comparison,
})
if verbose:
print_comparison(comparison, prompt, verbose)
# Delay between prompts
time.sleep(2)
return results
def summarize_results(results: list) -> bool:
"""Print summary of all results. Returns True if test passed."""
if not results:
print("\nNo successful results to summarize.")
return False
print(f"\n{'='*60}")
print("SUMMARY")
print(f"{'='*60}")
total_claude = sum(r["comparison"]["claude"]["total"] for r in results)
total_jcode = sum(r["comparison"]["jcode"]["total"] for r in results)
total_diff = total_jcode - total_claude
# Also compare just input+output (excluding cache)
total_claude_io = sum(
r["comparison"]["claude"]["input"] + r["comparison"]["claude"]["output"]
for r in results
)
total_jcode_io = sum(
r["comparison"]["jcode"]["input"] + r["comparison"]["jcode"]["output"]
for r in results
)
if total_claude > 0:
pct_diff = ((total_jcode - total_claude) / total_claude) * 100
else:
pct_diff = 0
print(f"\nTotal runs: {len(results)}")
print(f"\n--- Total Tokens (including cache) ---")
print(f"Claude CLI: {total_claude}")
print(f"jcode: {total_jcode}")
print(f"Difference: {total_diff:+} ({pct_diff:+.1f}%)")
print(f"\n--- Input + Output only (excluding cache) ---")
print(f"Claude CLI: {total_claude_io}")
print(f"jcode: {total_jcode_io}")
if total_claude_io > 0:
io_pct_diff = ((total_jcode_io - total_claude_io) / total_claude_io) * 100
print(f"Difference: {total_jcode_io - total_claude_io:+} ({io_pct_diff:+.1f}%)")
# Check if within acceptable bounds
# jcode using fewer tokens is always good (negative diff)
# jcode using more tokens is acceptable up to MAX_OVERHEAD_PCT
MAX_OVERHEAD_PCT = 50 # Allow up to 50% more tokens (for different system prompts)
passed = True
if pct_diff <= 0:
print(f"\n✅ PASS: jcode uses {abs(pct_diff):.1f}% fewer tokens than Claude CLI")
elif pct_diff <= MAX_OVERHEAD_PCT:
print(f"\n✅ PASS: jcode uses {pct_diff:.1f}% more tokens (within {MAX_OVERHEAD_PCT}% threshold)")
else:
print(f"\n❌ FAIL: jcode uses {pct_diff:.1f}% more tokens (exceeds {MAX_OVERHEAD_PCT}% threshold)")
passed = False
# Per-prompt breakdown
print("\nPer-prompt breakdown:")
print(f"{'Prompt':<40} {'Claude':<10} {'jcode':<10} {'Diff':<10}")
print("-" * 70)
for r in results:
prompt = r["prompt"][:37] + "..." if len(r["prompt"]) > 40 else r["prompt"]
c_total = r["comparison"]["claude"]["total"]
j_total = r["comparison"]["jcode"]["total"]
diff = j_total - c_total
print(f"{prompt:<40} {c_total:<10} {j_total:<10} {diff:+<10}")
return passed
def main():
parser = argparse.ArgumentParser(
description="Compare token usage between jcode and Claude Code CLI"
)
parser.add_argument(
"--verbose", "-v",
action="store_true",
help="Show detailed output for each run",
)
parser.add_argument(
"--runs", "-n",
type=int,
default=1,
help="Number of runs per prompt (default: 1)",
)
parser.add_argument(
"--json",
action="store_true",
help="Output results as JSON",
)
args = parser.parse_args()
print("Token Usage Comparison: jcode vs Claude Code CLI")
print("=" * 50)
try:
results = run_test_suite(verbose=args.verbose, runs=args.runs)
if args.json:
print(json.dumps(results, indent=2))
# For JSON mode, check if all runs succeeded
sys.exit(0 if results else 1)
else:
passed = summarize_results(results)
sys.exit(0 if passed else 1)
except FileNotFoundError as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
except KeyboardInterrupt:
print("\nInterrupted by user")
sys.exit(130)
if __name__ == "__main__":
main()