-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopilot_usage.py
More file actions
285 lines (238 loc) · 8.81 KB
/
copilot_usage.py
File metadata and controls
285 lines (238 loc) · 8.81 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
#!/usr/bin/env python3
"""Fetch GitHub Copilot per-user usage metrics and post a summary to Slack."""
import json
import os
import sys
from collections import defaultdict
from datetime import datetime, timedelta, timezone
import requests
GITHUB_API_BASE = "https://api.github.com"
API_VERSION = "2022-11-28"
def get_env(name: str) -> str:
value = os.environ.get(name)
if not value:
print(f"Error: {name} environment variable is required", file=sys.stderr)
sys.exit(1)
return value
def github_headers(token: str) -> dict:
return {
"Accept": "application/vnd.github+json",
"Authorization": f"Bearer {token}",
"X-GitHub-Api-Version": API_VERSION,
}
def fetch_user_report(token: str, org: str, day: str) -> list[dict]:
"""Fetch per-user usage metrics for a specific day.
Returns the parsed NDJSON records from the downloaded report files.
"""
url = f"{GITHUB_API_BASE}/orgs/{org}/copilot/metrics/reports/users-1-day"
resp = requests.get(
url, headers=github_headers(token), params={"day": day}, timeout=30
)
if resp.status_code == 204:
print(f"No data available for {day}")
return []
resp.raise_for_status()
data = resp.json()
download_links = data.get("download_links", [])
if not download_links:
print(f"No download links returned for {day}")
return []
records = []
for link in download_links:
dl_resp = requests.get(link, timeout=60)
dl_resp.raise_for_status()
# Reports are NDJSON (one JSON object per line)
for line in dl_resp.text.strip().splitlines():
line = line.strip()
if line:
records.append(json.loads(line))
return records
def build_user_summary(records: list[dict]) -> list[dict]:
"""Build a per-user summary from the raw NDJSON records."""
users = []
for record in records:
user_login = record.get("user_login", "unknown")
interactions = record.get("user_initiated_interaction_count", 0)
code_gen = record.get("code_generation_activity_count", 0)
code_accept = record.get("code_acceptance_activity_count", 0)
loc_added = record.get("loc_added_sum", 0)
loc_suggested = record.get("loc_suggested_to_add_sum", 0)
# Model breakdown from totals_by_model_feature
models = defaultdict(int)
for entry in record.get("totals_by_model_feature", []):
model_name = entry.get("model", "unknown")
count = entry.get("user_initiated_interaction_count", 0)
models[model_name] += count
# Also check totals_by_language_model
for entry in record.get("totals_by_language_model", []):
model_name = entry.get("model", "unknown")
count = entry.get("user_initiated_interaction_count", 0)
if model_name not in models:
models[model_name] += count
# CLI token usage
cli_tokens = 0
cli_data = record.get("totals_by_cli")
if cli_data:
token_usage = cli_data.get("token_usage", {})
cli_tokens = (
token_usage.get("output_tokens_sum", 0)
+ token_usage.get("prompt_tokens_sum", 0)
)
# Feature breakdown
features = {}
for entry in record.get("totals_by_feature", []):
feature_name = entry.get("feature", "unknown")
feat_interactions = entry.get("user_initiated_interaction_count", 0)
feat_code_gen = entry.get("code_generation_activity_count", 0)
features[feature_name] = {
"interactions": feat_interactions,
"code_generations": feat_code_gen,
}
used_agent = record.get("used_agent", False)
used_chat = record.get("used_chat", False)
used_cli = record.get("used_cli", False)
users.append(
{
"user": user_login,
"interactions": interactions,
"code_generations": code_gen,
"code_acceptances": code_accept,
"loc_added": loc_added,
"loc_suggested": loc_suggested,
"models": dict(models),
"features": features,
"cli_tokens": cli_tokens,
"used_agent": used_agent,
"used_chat": used_chat,
"used_cli": used_cli,
}
)
# Sort by interactions descending
users.sort(key=lambda u: u["interactions"], reverse=True)
return users
def format_slack_message(users: list[dict], org: str, day: str) -> dict:
"""Format the user summary as a Slack Block Kit message."""
blocks = [
{
"type": "header",
"text": {
"type": "plain_text",
"text": f"Copilot Usage Report — {day}",
},
},
{
"type": "context",
"elements": [
{
"type": "mrkdwn",
"text": f"Organization: *{org}* | Active users: *{len(users)}*",
}
],
},
{"type": "divider"},
]
if not users:
blocks.append(
{
"type": "section",
"text": {"type": "mrkdwn", "text": "_No usage data for this day._"},
}
)
return {"blocks": blocks}
# Summary table
lines = []
for u in users:
activity_flags = []
if u["used_chat"]:
activity_flags.append("chat")
if u["used_agent"]:
activity_flags.append("agent")
if u["used_cli"]:
activity_flags.append("cli")
activity_str = ", ".join(activity_flags) if activity_flags else "completions"
line = (
f"*{u['user']}* — "
f"{u['interactions']} interactions, "
f"{u['code_generations']} generations, "
f"{u['loc_added']} LoC added "
f"({activity_str})"
)
lines.append(line)
# Slack sections have a 3000 char limit; split if needed
chunk = []
chunk_len = 0
for line in lines:
if chunk_len + len(line) + 1 > 2900:
blocks.append(
{
"type": "section",
"text": {"type": "mrkdwn", "text": "\n".join(chunk)},
}
)
chunk = []
chunk_len = 0
chunk.append(line)
chunk_len += len(line) + 1
if chunk:
blocks.append(
{
"type": "section",
"text": {"type": "mrkdwn", "text": "\n".join(chunk)},
}
)
# Model breakdown (aggregate across all users)
model_totals = defaultdict(int)
for u in users:
for model, count in u["models"].items():
model_totals[model] += count
if model_totals:
blocks.append({"type": "divider"})
model_lines = ["*Model usage (interactions):*"]
for model, count in sorted(
model_totals.items(), key=lambda x: x[1], reverse=True
):
model_lines.append(f"• {model}: {count}")
blocks.append(
{
"type": "section",
"text": {"type": "mrkdwn", "text": "\n".join(model_lines)},
}
)
# CLI token totals
total_cli_tokens = sum(u["cli_tokens"] for u in users)
if total_cli_tokens > 0:
cli_users = [u for u in users if u["cli_tokens"] > 0]
cli_lines = [f"*CLI token usage (total: {total_cli_tokens:,}):*"]
for u in sorted(cli_users, key=lambda x: x["cli_tokens"], reverse=True):
cli_lines.append(f"• {u['user']}: {u['cli_tokens']:,} tokens")
blocks.append(
{
"type": "section",
"text": {"type": "mrkdwn", "text": "\n".join(cli_lines)},
}
)
return {"blocks": blocks}
def post_to_slack(webhook_url: str, message: dict) -> None:
resp = requests.post(webhook_url, json=message, timeout=15)
resp.raise_for_status()
if resp.text != "ok":
print(f"Slack response: {resp.text}", file=sys.stderr)
def main():
github_token = get_env("GH_TOKEN")
org = os.environ.get("GITHUB_ORG", "shadow-robot")
slack_webhook = get_env("SLACK_WEBHOOK_URL")
# Default to yesterday
day = os.environ.get("REPORT_DAY")
if not day:
yesterday = datetime.now(timezone.utc) - timedelta(days=1)
day = yesterday.strftime("%Y-%m-%d")
print(f"Fetching Copilot usage for {org} on {day}...")
records = fetch_user_report(github_token, org, day)
print(f"Retrieved {len(records)} user records")
users = build_user_summary(records)
message = format_slack_message(users, org, day)
print("Posting to Slack...")
post_to_slack(slack_webhook, message)
print("Done!")
if __name__ == "__main__":
main()