-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_keys.py
More file actions
222 lines (180 loc) · 6.29 KB
/
generate_keys.py
File metadata and controls
222 lines (180 loc) · 6.29 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
"""
OpenRouter API Key Generator for Apart AI Control Hackathon.
Usage:
python generate_keys.py generate "Participant Name"
python generate_keys.py list
python generate_keys.py cleanup
Requires OPENROUTER_MGMT_KEY env var (or .env file) set to your
OpenRouter Management API key. Get one at:
https://openrouter.ai/settings/management-keys
"""
import argparse
import csv
import os
import sys
from datetime import datetime, timezone, timedelta
from pathlib import Path
try:
import requests
except ImportError:
print("Missing dependency. Run: pip install requests")
sys.exit(1)
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass # python-dotenv is optional
BASE_URL = "https://openrouter.ai/api/v1/keys"
CREDIT_LIMIT = 100 # USD
KEY_LIFETIME_DAYS = 7
KEY_PREFIX = "hackathon" # prefix in key name for easy filtering
CSV_FILE = Path(__file__).parent / "keys.csv"
def get_headers():
key = os.environ.get("OPENROUTER_MGMT_KEY")
if not key:
print("Error: set OPENROUTER_MGMT_KEY in your environment or .env file.")
sys.exit(1)
return {
"Authorization": f"Bearer {key}",
"Content-Type": "application/json",
}
def generate_key(name: str):
"""Create a new hackathon key with a $100 cap."""
now = datetime.now(timezone.utc)
label = f"{KEY_PREFIX} | {name} | {now.strftime('%Y-%m-%d')}"
expires_at = (now + timedelta(days=KEY_LIFETIME_DAYS)).strftime("%Y-%m-%dT%H:%M:%SZ")
resp = requests.post(
BASE_URL,
headers=get_headers(),
json={
"name": label,
"limit": CREDIT_LIMIT,
"expires_at": expires_at,
},
)
if resp.status_code not in (200, 201):
print(f"Error creating key: {resp.status_code} — {resp.text}")
sys.exit(1)
data = resp.json()
key_str = data.get("key") or data.get("data", {}).get("key", "<not returned>")
print()
print("=== New Hackathon API Key ===")
print(f" Participant : {name}")
print(f" Key : {key_str}")
print(f" Credit cap : ${CREDIT_LIMIT}")
print(f" Created : {now.strftime('%Y-%m-%d %H:%M UTC')}")
print(f" Expires : {(now + timedelta(days=KEY_LIFETIME_DAYS)).strftime('%Y-%m-%d %H:%M UTC')} (automatic)")
print()
print("Give this key to the participant. It works as a normal OpenRouter API key.")
write_header = not CSV_FILE.exists()
with open(CSV_FILE, "a", newline="") as f:
w = csv.writer(f)
if write_header:
w.writerow(["participant", "key", "limit_usd", "created_utc", "expires_utc"])
w.writerow([
name,
key_str,
CREDIT_LIMIT,
now.strftime("%Y-%m-%d %H:%M"),
(now + timedelta(days=KEY_LIFETIME_DAYS)).strftime("%Y-%m-%d %H:%M"),
])
print(f" (saved to {CSV_FILE.name})")
return data
def list_keys():
"""List all hackathon keys and their status."""
all_keys = []
offset = 0
while True:
resp = requests.get(
f"{BASE_URL}?offset={offset}",
headers=get_headers(),
)
if resp.status_code != 200:
print(f"Error listing keys: {resp.status_code} — {resp.text}")
sys.exit(1)
page = resp.json().get("data", [])
if not page:
break
all_keys.extend(page)
if len(page) < 100:
break
offset += 100
hackathon_keys = [k for k in all_keys if k.get("name", "").startswith(KEY_PREFIX)]
if not hackathon_keys:
print("No hackathon keys found.")
return
now = datetime.now(timezone.utc)
print(f"\n{'Name':<45} {'Status':<12} {'Used':<10} {'Limit':<10} {'Age'}")
print("-" * 95)
for k in hackathon_keys:
created = datetime.fromisoformat(k["created_at"])
age = now - created
age_str = f"{age.days}d {age.seconds // 3600}h"
status = "disabled" if k.get("disabled") else ("expired" if age.days >= KEY_LIFETIME_DAYS else "active")
usage = k.get("usage", 0)
limit = k.get("limit", "none")
print(f" {k['name']:<43} {status:<12} ${usage:<9} ${limit:<9} {age_str}")
print()
def cleanup_keys():
"""Disable hackathon keys older than KEY_LIFETIME_DAYS."""
all_keys = []
offset = 0
while True:
resp = requests.get(
f"{BASE_URL}?offset={offset}",
headers=get_headers(),
)
if resp.status_code != 200:
print(f"Error listing keys: {resp.status_code} — {resp.text}")
sys.exit(1)
page = resp.json().get("data", [])
if not page:
break
all_keys.extend(page)
if len(page) < 100:
break
offset += 100
now = datetime.now(timezone.utc)
expired = [
k for k in all_keys
if k.get("name", "").startswith(KEY_PREFIX)
and not k.get("disabled")
and (now - datetime.fromisoformat(k["created_at"])).days >= KEY_LIFETIME_DAYS
]
if not expired:
print("No expired hackathon keys to clean up.")
return
print(f"Disabling {len(expired)} expired key(s)...")
for k in expired:
resp = requests.patch(
f"{BASE_URL}/{k['hash']}",
headers=get_headers(),
json={"disabled": True},
)
tag = "OK" if resp.status_code == 200 else f"FAILED ({resp.status_code})"
print(f" {k['name']} — {tag}")
print("Done.")
def batch_generate(names: list[str]):
"""Generate keys for multiple participants at once."""
for name in names:
generate_key(name.strip())
def main():
parser = argparse.ArgumentParser(
description="OpenRouter hackathon key manager"
)
sub = parser.add_subparsers(dest="command")
gen = sub.add_parser("generate", help="Create a key for a participant")
gen.add_argument("names", nargs="+", help="Participant name(s)")
sub.add_parser("list", help="List all hackathon keys")
sub.add_parser("cleanup", help="Disable keys older than 7 days")
args = parser.parse_args()
if args.command == "generate":
batch_generate(args.names)
elif args.command == "list":
list_keys()
elif args.command == "cleanup":
cleanup_keys()
else:
parser.print_help()
if __name__ == "__main__":
main()