davanstrien HF Staff commited on
Commit
6d30676
·
0 Parent(s):

Initial release: agent-usage shares through 2026-06

Browse files
.gitattributes ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.avro filter=lfs diff=lfs merge=lfs -text
4
+ *.bin filter=lfs diff=lfs merge=lfs -text
5
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
6
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
7
+ *.ftz filter=lfs diff=lfs merge=lfs -text
8
+ *.gz filter=lfs diff=lfs merge=lfs -text
9
+ *.h5 filter=lfs diff=lfs merge=lfs -text
10
+ *.joblib filter=lfs diff=lfs merge=lfs -text
11
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
12
+ *.lz4 filter=lfs diff=lfs merge=lfs -text
13
+ *.mds filter=lfs diff=lfs merge=lfs -text
14
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
15
+ *.model filter=lfs diff=lfs merge=lfs -text
16
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
17
+ *.npy filter=lfs diff=lfs merge=lfs -text
18
+ *.npz filter=lfs diff=lfs merge=lfs -text
19
+ *.onnx filter=lfs diff=lfs merge=lfs -text
20
+ *.ot filter=lfs diff=lfs merge=lfs -text
21
+ *.parquet filter=lfs diff=lfs merge=lfs -text
22
+ *.pb filter=lfs diff=lfs merge=lfs -text
23
+ *.pickle filter=lfs diff=lfs merge=lfs -text
24
+ *.pkl filter=lfs diff=lfs merge=lfs -text
25
+ *.pt filter=lfs diff=lfs merge=lfs -text
26
+ *.pth filter=lfs diff=lfs merge=lfs -text
27
+ *.rar filter=lfs diff=lfs merge=lfs -text
28
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
29
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
30
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
31
+ *.tar filter=lfs diff=lfs merge=lfs -text
32
+ *.tflite filter=lfs diff=lfs merge=lfs -text
33
+ *.tgz filter=lfs diff=lfs merge=lfs -text
34
+ *.wasm filter=lfs diff=lfs merge=lfs -text
35
+ *.xz filter=lfs diff=lfs merge=lfs -text
36
+ *.zip filter=lfs diff=lfs merge=lfs -text
37
+ *.zst filter=lfs diff=lfs merge=lfs -text
38
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
39
+ # Audio files - uncompressed
40
+ *.pcm filter=lfs diff=lfs merge=lfs -text
41
+ *.sam filter=lfs diff=lfs merge=lfs -text
42
+ *.raw filter=lfs diff=lfs merge=lfs -text
43
+ # Audio files - compressed
44
+ *.aac filter=lfs diff=lfs merge=lfs -text
45
+ *.flac filter=lfs diff=lfs merge=lfs -text
46
+ *.mp3 filter=lfs diff=lfs merge=lfs -text
47
+ *.ogg filter=lfs diff=lfs merge=lfs -text
48
+ *.wav filter=lfs diff=lfs merge=lfs -text
49
+ # Image files - uncompressed
50
+ *.bmp filter=lfs diff=lfs merge=lfs -text
51
+ *.gif filter=lfs diff=lfs merge=lfs -text
52
+ *.png filter=lfs diff=lfs merge=lfs -text
53
+ *.tiff filter=lfs diff=lfs merge=lfs -text
54
+ # Image files - compressed
55
+ *.jpg filter=lfs diff=lfs merge=lfs -text
56
+ *.jpeg filter=lfs diff=lfs merge=lfs -text
57
+ *.webp filter=lfs diff=lfs merge=lfs -text
58
+ # Video files - compressed
59
+ *.mp4 filter=lfs diff=lfs merge=lfs -text
60
+ *.webm filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: Agent Usage on the Hugging Face Hub
3
+ tags:
4
+ - analytics
5
+ - agents
6
+ configs:
7
+ - config_name: monthly
8
+ default: true
9
+ data_files: data/monthly/*.parquet
10
+ - config_name: daily
11
+ data_files: data/daily/*.parquet
12
+ ---
13
+
14
+ # Agent Usage on the Hugging Face Hub
15
+
16
+ **Coding agents are real users of the Hugging Face Hub.** Claude Code, Codex, Cursor, and a growing list of harnesses are searching for models, building and pushing datasets, training models on [Jobs](https://huggingface.co/docs/hub/jobs), spinning up Spaces — tens of millions of requests so far ([hf CLI for agents](https://huggingface.co/blog/hf-cli-for-agents)). Now there's public data on which ones.
17
+
18
+ Requests made through the `huggingface_hub` library (including the `hf` CLI) carry an [`agent/<name>` User-Agent token](https://huggingface.co/docs/hub/agents-overview) identifying the harness. This dataset publishes **each harness's share of that agent-attributed traffic**, month by month and day by day, updated by a scheduled [HF Job](https://huggingface.co/docs/hub/jobs).
19
+
20
+ ![Current leaderboard](assets/leaderboard.png)
21
+
22
+ _Named harnesses ranked by share of requests, data through **2026-06** · updated 2026-07-02. The **Dataset Viewer** at the top of this page lets you browse, sort, and filter both tables — no code needed._
23
+
24
+ ## What you can see
25
+
26
+ - **Who's calling the Hub** — the monthly leaderboard of named harnesses, and how it shifts as new tools launch and register.
27
+ - **Usage styles** — compare request share with user share. An agent with 30% of requests but 8% of users is a small crowd running heavy automated pipelines; the reverse means many users, each doing a little.
28
+ - **Day-by-day detail** — the `daily` config picks up what monthly numbers smooth over: launch spikes, growth curves, weekday-vs-weekend patterns.
29
+
30
+ ## Get your harness on the board
31
+
32
+ If you build a harness, register it to make sure your agent isn't missed — unregistered tools are counted only as `unknown`.
33
+
34
+ Attribution is automatic: `huggingface_hub` detects registered harnesses from environment variables and reports them in the User-Agent. To register, follow [Register your agent harness](https://huggingface.co/docs/hub/agents-overview#register-your-agent-harness) — a Pull Request adding your tool to [`agent-harnesses.ts`](https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/src/agent-harnesses.ts). No release is needed on either side: installed clients refresh the registry within a day, and your harness appears from the next monthly snapshot.
35
+
36
+ Only traffic through the Python `huggingface_hub` library (including the `hf` CLI) is attributed; direct HTTP calls to the Hub API are not counted. To confirm detection works, run inside your harness:
37
+
38
+ ```bash
39
+ python -c "from huggingface_hub.utils import build_hf_headers; print(build_hf_headers()['user-agent'])"
40
+ # should contain agent/<your-id>
41
+ ```
42
+
43
+ ## Columns
44
+
45
+ | column | description |
46
+ | --------------- | ------------------------------------------------------------------------------------------------------------ |
47
+ | `month` / `day` | period the share is computed over |
48
+ | `agent` | harness name from the `agent/<name>` token; `unknown` = token present but no registered name |
49
+ | `pct_requests` | harness's share of agent-attributed `huggingface_hub` requests in the period (0–100; sums to 100 per period) |
50
+ | `pct_users` | same, for distinct authenticated users — someone using two harnesses counts once for each |
51
+
52
+ ## Loading programmatically
53
+
54
+ ```python
55
+ from datasets import load_dataset
56
+
57
+ monthly = load_dataset("huggingface/agent-usage", "monthly", split="train")
58
+ ```
59
+
60
+ ```sql
61
+ -- DuckDB: full monthly history in one query
62
+ SELECT month, agent, pct_requests
63
+ FROM 'hf://datasets/huggingface/agent-usage/data/monthly/*.parquet'
64
+ WHERE agent != 'unknown'
65
+ ORDER BY month, pct_requests DESC;
66
+ ```
67
+
68
+ ```python
69
+ import polars as pl
70
+
71
+ daily = pl.scan_parquet("hf://datasets/huggingface/agent-usage/data/daily/*.parquet")
72
+ ```
73
+
74
+ New months append as new parquet files, so these queries always return the full history unchanged.
75
+
76
+ ## Reading the data
77
+
78
+ - **This measures Hub usage, not overall agent popularity.** A widely used tool that rarely touches the Hugging Face Hub will rank low here.
79
+ - **Shares are zero-sum.** A falling share doesn't mean falling usage — total agent traffic is growing, so a harness can double its requests while its share shrinks.
80
+ - **Start month-over-month comparisons from May 2026.** The `agent/` token rolled out April 3 and harnesses added detection at different times, so April reflects the rollout, not relative usage.
81
+ - **Smooth daily shares** with a 7-day rolling mean — weekends and small denominators make single days noisy.
82
+ - **Attribution is self-declared** (a User-Agent token set by the client library) and covers Python-library traffic only.
83
+
84
+ _Built by [`build_local.py`](./build_local.py) (bundled in this repo) on a scheduled HF Job — only relative shares are published._
agent_usage.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Chart + table helpers for the Hub agent-usage leaderboard.
2
+
3
+ Used by build_local.py (the scheduled HF Job) to render the PNGs embedded in
4
+ the dataset card. This module only ever touches the *derived* public data
5
+ (relative shares); fetching + deriving from the private source lives in
6
+ build_local.py.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from pathlib import Path
12
+
13
+ import matplotlib.dates as mdates
14
+ import matplotlib.pyplot as plt
15
+ import pandas as pd
16
+ from matplotlib import rcParams
17
+ from matplotlib.figure import Figure
18
+
19
+ # --------------------------------------------------------------------------- #
20
+ # Constants
21
+ # --------------------------------------------------------------------------- #
22
+
23
+ # Published derived dataset (used when no local data dir is given).
24
+ DERIVED_REPO = "huggingface/agent-usage"
25
+
26
+ ROLLOUT_DATE = "2026-04-03" # agent/ UA token rollout — before this is noise
27
+
28
+ # HF brand palette — https://huggingface.co/brand
29
+ YELLOW = "#FFD21E" # primary accent — leader bar
30
+ ORANGE = "#FF9D00" # secondary accent
31
+ SLATE = "#1F2937" # near-black bars / first line
32
+ INK = "#111827" # body text
33
+ MUTED = "#6B7280" # HF gray — axes, footers
34
+ GRID = "#E5E7EB" # light gridline
35
+ BG = "#FFFFFF"
36
+
37
+ # Stable categorical line colours (assigned by agent order).
38
+ LINE_COLORS = [
39
+ SLATE, ORANGE, "#2563EB", "#059669", "#DC2626",
40
+ "#7C3AED", "#0891B2", "#CA8A04",
41
+ ]
42
+
43
+
44
+ def set_brand_style() -> None:
45
+ """Apply HF-flavoured matplotlib defaults (clean sans-serif, white bg)."""
46
+ rcParams.update(
47
+ {
48
+ "font.family": "sans-serif",
49
+ "font.sans-serif": [
50
+ "Source Sans Pro", "Source Sans 3",
51
+ "Helvetica Neue", "Helvetica", "Arial", "DejaVu Sans",
52
+ ],
53
+ "font.size": 11,
54
+ "text.color": INK,
55
+ "savefig.facecolor": BG,
56
+ "axes.facecolor": BG,
57
+ "figure.facecolor": BG,
58
+ }
59
+ )
60
+
61
+
62
+ # --------------------------------------------------------------------------- #
63
+ # Selectors
64
+ # --------------------------------------------------------------------------- #
65
+
66
+ def available_months(monthly: pd.DataFrame) -> list[str]:
67
+ return sorted(monthly["month"].dropna().unique().tolist())
68
+
69
+
70
+ def latest_month(monthly: pd.DataFrame) -> str:
71
+ return max(available_months(monthly))
72
+
73
+
74
+ def leaderboard_table(
75
+ monthly: pd.DataFrame,
76
+ month: str | None = None,
77
+ top_n: int = 10,
78
+ exclude_unknown: bool = True,
79
+ ) -> pd.DataFrame:
80
+ """Ranked top-N agents for a month, ready to display."""
81
+ month = month or latest_month(monthly)
82
+ df = monthly.query("month == @month")
83
+ if exclude_unknown:
84
+ df = df[df["agent"].str.lower() != "unknown"]
85
+ df = df.sort_values("pct_requests", ascending=False).head(top_n).reset_index(drop=True)
86
+ out = df[["agent", "pct_requests", "pct_users"]].copy()
87
+ out.insert(0, "rank", range(1, len(out) + 1))
88
+ out["pct_requests"] = out["pct_requests"].round(2)
89
+ out["pct_users"] = out["pct_users"].astype("Float64").round(2)
90
+ return out
91
+
92
+
93
+ def top_agents(
94
+ monthly: pd.DataFrame,
95
+ month: str | None = None,
96
+ n: int = 5,
97
+ exclude_unknown: bool = True,
98
+ ) -> list[str]:
99
+ """Top-N agent names by share in the given month (default: latest)."""
100
+ return leaderboard_table(monthly, month, n, exclude_unknown)["agent"].tolist()
101
+
102
+
103
+ # --------------------------------------------------------------------------- #
104
+ # Figures
105
+ # --------------------------------------------------------------------------- #
106
+
107
+ def leaderboard_figure(
108
+ monthly: pd.DataFrame,
109
+ month: str | None = None,
110
+ top_n: int = 10,
111
+ show_unknown: bool = True,
112
+ ) -> Figure:
113
+ """Horizontal-bar snapshot leaderboard, HF-brand register.
114
+
115
+ Named harnesses are ranked as usual; `unknown` (unregistered tools) sits as
116
+ a muted gray bar at the bottom — an honest part of the picture and the
117
+ reason to register a harness, without reading as part of the race.
118
+ """
119
+ set_brand_style()
120
+ month = month or latest_month(monthly)
121
+ table = leaderboard_table(monthly, month, top_n, exclude_unknown=True)
122
+
123
+ fig = Figure(figsize=(9.2, 9.2), facecolor=BG)
124
+ fig.text(0.06, 0.935, "Agents calling the Hugging Face Hub",
125
+ fontsize=22, color=INK, fontweight="bold")
126
+ fig.text(0.06, 0.895, f"Share of agent-attributed huggingface_hub requests, {month}",
127
+ fontsize=13, color=MUTED)
128
+
129
+ ax = fig.add_axes((0.06, 0.10, 0.88, 0.74))
130
+ # rows bottom-to-top: (label, pct, kind) with unknown pinned at the bottom
131
+ rows = [(r["agent"], float(r["pct_requests"]), "named")
132
+ for _, r in table.iloc[::-1].iterrows()]
133
+ if show_unknown:
134
+ unk = monthly.query("month == @month and agent == 'unknown'")
135
+ if len(unk):
136
+ rows.insert(0, ("unknown (unregistered)", float(unk["pct_requests"].iloc[0]), "unknown"))
137
+ if not rows:
138
+ ax.text(0.5, 0.5, "no data", ha="center", va="center", color=MUTED)
139
+ return fig
140
+ xmax = max(pct for _, pct, _ in rows)
141
+ ax.axvline(0, color=MUTED, linewidth=0.6, zorder=1)
142
+
143
+ top_idx = len(rows) - 1 # top *named* harness leads
144
+ for i, (label, pct, kind) in enumerate(rows):
145
+ is_unknown = kind == "unknown"
146
+ is_top = i == top_idx
147
+ bar_colour = GRID if is_unknown else (YELLOW if is_top else SLATE)
148
+ ax.barh(i, pct, color=bar_colour, height=0.62, zorder=2)
149
+ ax.text(-xmax * 0.022, i, label, va="center", ha="right",
150
+ fontsize=12 if is_unknown else 14,
151
+ fontstyle="italic" if is_unknown else "normal",
152
+ fontweight="bold" if is_top else "normal",
153
+ color=MUTED if is_unknown else INK)
154
+ ax.text(pct + xmax * 0.012, i, f"{pct:.1f}%", va="center", ha="left",
155
+ fontsize=14, fontweight="bold",
156
+ color=MUTED if is_unknown else (ORANGE if is_top else INK))
157
+
158
+ ax.set_yticks([]); ax.set_xticks([])
159
+ for s in ("top", "right", "left", "bottom"):
160
+ ax.spines[s].set_visible(False)
161
+ ax.set_xlim(-xmax * 0.50, xmax * 1.15)
162
+ ax.set_ylim(-0.7, len(rows) - 0.3)
163
+
164
+ fig.text(0.06, 0.040,
165
+ f"Source: hf.co/datasets/{DERIVED_REPO} · self-declared agent/ User-Agent tokens.",
166
+ fontsize=10, color=MUTED)
167
+ return fig
168
+
169
+
170
+ def trend_figure(
171
+ daily: pd.DataFrame,
172
+ agents: list[str],
173
+ smooth: bool = True,
174
+ since: str = ROLLOUT_DATE,
175
+ ) -> Figure:
176
+ """Daily share-over-time lines for the given agents, HF-brand register.
177
+
178
+ ``smooth`` applies a 7-day centred rolling mean (min_periods=3) to absorb
179
+ weekend dips and small-denominator noise in the early days.
180
+ """
181
+ set_brand_style()
182
+ df = daily[daily["day"] >= since].copy()
183
+ df = df[df["agent"].isin(agents)]
184
+ df["day"] = pd.to_datetime(df["day"])
185
+
186
+ fig = Figure(figsize=(11, 6.2), facecolor=BG)
187
+ fig.text(0.06, 0.93, "Agent share of Hub requests over time",
188
+ fontsize=20, color=INK, fontweight="bold")
189
+ sub = "7-day rolling mean" if smooth else "raw daily share"
190
+ fig.text(0.06, 0.885, f"huggingface_hub · {sub} · since {since}",
191
+ fontsize=12.5, color=MUTED)
192
+
193
+ ax = fig.add_axes((0.06, 0.13, 0.80, 0.70))
194
+ if df.empty:
195
+ ax.text(0.5, 0.5, "no data", ha="center", va="center", color=MUTED)
196
+ return fig
197
+
198
+ ymax = 0.0
199
+ labels = [] # (y_at_end, agent, colour) for de-collided right-hand labels
200
+ last_x = None
201
+ for idx, agent in enumerate(agents):
202
+ s = (
203
+ df[df["agent"] == agent]
204
+ .sort_values("day")
205
+ .set_index("day")["pct_requests"]
206
+ .astype(float)
207
+ )
208
+ if s.empty:
209
+ continue
210
+ if smooth:
211
+ s = s.rolling(7, center=True, min_periods=3).mean()
212
+ colour = LINE_COLORS[idx % len(LINE_COLORS)]
213
+ ax.plot(s.index, s.values, color=colour, linewidth=2.2, zorder=3)
214
+ valid = s.dropna()
215
+ if not valid.empty:
216
+ labels.append([float(valid.iloc[-1]), agent, colour])
217
+ last_x = valid.index[-1]
218
+ ymax = max(ymax, float(valid.max()))
219
+
220
+ ax.set_ylim(0, ymax * 1.12 if ymax else 1)
221
+
222
+ # De-collide right-hand direct labels: nudge apart by a min vertical gap
223
+ if labels and last_x is not None:
224
+ gap = (ymax * 1.12) * 0.045 # ~4.5% of axis height
225
+ labels.sort(key=lambda r: r[0])
226
+ for prev, cur in zip(labels, labels[1:]):
227
+ if cur[0] - prev[0] < gap:
228
+ cur[0] = prev[0] + gap
229
+ for y, agent, colour in labels:
230
+ ax.annotate(
231
+ f" {agent}",
232
+ xy=(last_x, y), xytext=(6, 0), textcoords="offset points",
233
+ va="center", ha="left", fontsize=11.5, color=colour,
234
+ fontweight="bold", annotation_clip=False,
235
+ )
236
+ ax.yaxis.set_major_formatter(lambda v, _: f"{v:.0f}%")
237
+ ax.grid(axis="y", color=GRID, linewidth=0.8)
238
+ ax.set_axisbelow(True)
239
+ for s in ("top", "right"):
240
+ ax.spines[s].set_visible(False)
241
+ for s in ("left", "bottom"):
242
+ ax.spines[s].set_color(MUTED)
243
+ ax.tick_params(colors=MUTED, labelsize=10)
244
+ ax.xaxis.set_major_locator(mdates.AutoDateLocator())
245
+ ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(ax.xaxis.get_major_locator()))
246
+ # room for the right-hand direct labels
247
+ ax.margins(x=0.02)
248
+
249
+ fig.text(0.06, 0.035,
250
+ f"Source: hf.co/datasets/{DERIVED_REPO} · share of agent-attributed huggingface_hub requests.",
251
+ fontsize=10, color=MUTED)
252
+ return fig
253
+
254
+
255
+ def save_png(fig: Figure, path: str | Path) -> Path:
256
+ path = Path(path)
257
+ path.parent.mkdir(parents=True, exist_ok=True)
258
+ fig.savefig(path, dpi=200, bbox_inches="tight", pad_inches=0.4, facecolor=BG)
259
+ plt.close(fig)
260
+ return path
assets/leaderboard.png ADDED

Git LFS Details

  • SHA256: 2ee0b5937f73e1639c2712f3a6775c5b7bf9f63172b13a70316b4a6431b79613
  • Pointer size: 131 Bytes
  • Size of remote file: 136 kB
assets/trend.png ADDED

Git LFS Details

  • SHA256: 2d59ee523350f2d3e6380fce2a5a79ab3e84013925ad1cb867f0bbea00fa2768
  • Pointer size: 131 Bytes
  • Size of remote file: 186 kB
build_local.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "huggingface_hub>=0.27",
5
+ # "pandas>=2.0",
6
+ # "pyarrow>=15",
7
+ # "matplotlib>=3.8",
8
+ # ]
9
+ # ///
10
+ """Build the public-safe derived view of the Hub's agent-usage telemetry.
11
+
12
+ The source dataset id is injected via the AGENT_USAGE_SRC env var (on Jobs:
13
+ `-e AGENT_USAGE_SRC=...`), so this public script never names it.
14
+
15
+ This is the scheduled HF Job body. It:
16
+ 1. fetches the private source (monthly + daily parquets)
17
+ 2. keeps only the public columns (relative shares; raw counts are never
18
+ published) and only registered harness rows (the rest fold into `unknown`)
19
+ 3. writes derived parquets, renders the card PNGs, and pushes everything
20
+ (data + charts + card + this script) to the public dataset repo
21
+ """
22
+
23
+ import os
24
+ from datetime import date
25
+ from pathlib import Path
26
+
27
+ import pandas as pd
28
+ from huggingface_hub import snapshot_download
29
+ from huggingface_hub.constants import ENDPOINT
30
+ from huggingface_hub.utils import get_session
31
+
32
+ import agent_usage as au
33
+
34
+ SRC = os.environ.get("AGENT_USAGE_SRC")
35
+ if not SRC:
36
+ raise SystemExit("Set AGENT_USAGE_SRC to the source dataset id (on Jobs: -e AGENT_USAGE_SRC=...)")
37
+ # Allowlist: only these columns are ever published. Anything else in the source
38
+ # (whatever it is, now or later) is dropped by construction.
39
+ KEEP = {"month", "day", "agent", "pct_requests", "pct_users"}
40
+ # Publish the library-level rows only: the CLI source is a strict subset of
41
+ # huggingface_hub (the CLI imports the library), so keeping both would double-count.
42
+ PUBLISH_SOURCE = "huggingface_hub"
43
+ ROLLOUT_MONTH = "2026-04" # skip pre-rollout monthly files (mostly empty)
44
+
45
+ # The `agent` value is extracted server-side from raw User-Agent strings, so it
46
+ # is arbitrary user-controlled input. Sanitize rows the same way KEEP sanitizes
47
+ # columns: only registered harness names are published; everything else folds
48
+ # into `unknown` (which is also what the card promises for unregistered tools).
49
+ # Fail loud if the registry is unreachable — never publish unfiltered tokens.
50
+ _resp = get_session().get(f"{ENDPOINT}/api/agent-harnesses", timeout=10)
51
+ _resp.raise_for_status()
52
+ PUBLISH_AGENTS = set(_resp.json()["harnesses"]) | {"unknown"}
53
+
54
+ HERE = Path(__file__).parent
55
+ OUT = HERE / "preview"
56
+ DATA = OUT / "data"
57
+
58
+
59
+ def derive(folder: str, key_col: str) -> pd.DataFrame:
60
+ """Pull one granularity from the source, drop totals, write derived parquets."""
61
+ src_root = Path(
62
+ snapshot_download(SRC, repo_type="dataset", allow_patterns=f"data/{folder}/*.parquet")
63
+ )
64
+ out_dir = DATA / folder
65
+ out_dir.mkdir(parents=True, exist_ok=True)
66
+
67
+ frames = []
68
+ for parquet in sorted((src_root / "data" / folder).glob("*.parquet")):
69
+ # monthly: skip files before rollout; daily: keep all (chart filters by day)
70
+ if folder == "monthly" and parquet.stem < ROLLOUT_MONTH:
71
+ continue
72
+ df = pd.read_parquet(parquet)
73
+ if key_col not in df.columns:
74
+ df[key_col] = parquet.stem
75
+ if "source" in df.columns:
76
+ df = df[df["source"] == PUBLISH_SOURCE]
77
+ df = df[[c for c in df.columns if c in KEEP]]
78
+ # Fold unregistered tokens into `unknown`, then merge the folded rows.
79
+ df.loc[~df["agent"].isin(PUBLISH_AGENTS), "agent"] = "unknown"
80
+ group_cols = [c for c in df.columns if not c.startswith("pct_")]
81
+ df = df.groupby(group_cols, as_index=False).sum()
82
+ df.to_parquet(out_dir / parquet.name, index=False)
83
+ frames.append(df)
84
+
85
+ if not frames:
86
+ raise SystemExit(f"No {folder} parquets found")
87
+ all_df = pd.concat(frames, ignore_index=True)
88
+
89
+ # Fail loud if the published frame somehow holds a non-allowlisted column,
90
+ # or if the source schema drifted away from the shares we expect.
91
+ extras = set(all_df.columns) - KEEP
92
+ if extras:
93
+ raise SystemExit(f"Leak: non-allowlisted columns survived in {folder}: {extras}")
94
+ if not {key_col, "agent", "pct_requests"} <= set(all_df.columns):
95
+ raise SystemExit(f"Source schema drift: expected share columns missing in {folder}")
96
+
97
+ print(f"✓ {folder}: {len(frames)} parquets → {out_dir}/ ({len(all_df)} rows)")
98
+ return all_df
99
+
100
+
101
+ # ---------------------------- derive both granularities ----------------------
102
+
103
+ monthly = derive("monthly", "month")
104
+ daily = derive("daily", "day")
105
+
106
+ # pct sanity check (already 0-100 in source)
107
+ gs = monthly.groupby("month")["pct_requests"].sum()
108
+ if not ((gs > 95) & (gs < 105)).all():
109
+ print(f"⚠ monthly pct_requests group sums look off: {gs.to_dict()}")
110
+
111
+ latest = au.latest_month(monthly)
112
+ leaders = au.top_agents(monthly, n=5)
113
+ print(f"\nLatest month: {latest}")
114
+ print(au.leaderboard_table(monthly).to_string(index=False))
115
+ print(f"\nTrend cohort (top 5, {latest}): {leaders}")
116
+
117
+ # ---------------------------- render PNGs (for tweet / card embedding) -------
118
+
119
+ au.save_png(au.leaderboard_figure(monthly), OUT / "leaderboard.png")
120
+ au.save_png(au.trend_figure(daily, agents=leaders), OUT / "trend.png")
121
+ print(f"\n✓ {OUT/'leaderboard.png'}")
122
+ print(f"✓ {OUT/'trend.png'}")
123
+
124
+ # ---------------------------- push to the public dataset repo ----------------
125
+ # Only when AGENT_USAGE_PUSH_REPO is set (on Jobs: -e AGENT_USAGE_PUSH_REPO=...).
126
+ # Everything above stays local otherwise. One commit per run: derived parquets,
127
+ # chart PNGs, the card, and this script + its module (the build is auditable
128
+ # from the dataset repo itself).
129
+
130
+ PUSH_REPO = os.environ.get("AGENT_USAGE_PUSH_REPO")
131
+ if PUSH_REPO:
132
+ from huggingface_hub import CommitOperationAdd, HfApi
133
+
134
+ ops = []
135
+ for parquet in sorted(DATA.rglob("*.parquet")):
136
+ ops.append(CommitOperationAdd(str(parquet.relative_to(OUT)), str(parquet)))
137
+ for png in ("leaderboard.png", "trend.png"):
138
+ ops.append(CommitOperationAdd(f"assets/{png}", str(OUT / png)))
139
+ for script in ("build_local.py", "agent_usage.py"):
140
+ ops.append(CommitOperationAdd(script, str(HERE / script)))
141
+
142
+ # Card template → README.md with the freshness stamp filled in.
143
+ card = (
144
+ (HERE / "card" / "README.md")
145
+ .read_text()
146
+ .replace("{{LATEST_MONTH}}", latest)
147
+ .replace("{{GENERATED}}", str(date.today()))
148
+ )
149
+ ops.append(CommitOperationAdd("README.md", card.encode()))
150
+
151
+ api = HfApi()
152
+ # Created private: review the rendered card/viewer, then flip to public in
153
+ # settings (or api.update_repo_settings). exist_ok means later scheduled
154
+ # runs never touch visibility.
155
+ api.create_repo(PUSH_REPO, repo_type="dataset", private=True, exist_ok=True)
156
+ commit = api.create_commit(
157
+ repo_id=PUSH_REPO,
158
+ repo_type="dataset",
159
+ operations=ops,
160
+ commit_message=f"Update derived agent-usage shares (latest month: {latest})",
161
+ )
162
+ print(f"\n✓ pushed {len(ops)} files → {commit.commit_url}")
163
+ else:
164
+ print("\n(no AGENT_USAGE_PUSH_REPO set — local build only, nothing pushed)")
data/daily/2026-04.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:27288556544e8183d1b85e05df1a8b637a34f32c5c22ed539ec23c21b2873e2d
3
+ size 7462
data/daily/2026-05.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d1a25ce2f4d5ba51af1b0ed01806c5dcc5eff6f45570972850168a94a576162d
3
+ size 10353
data/daily/2026-06.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a8a0bb70be761f8cc9e0c1c53c9da81704d70948f6c43f16e41576e02246d212
3
+ size 12064
data/monthly/2026-04.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:34cf3e4bf845570d0d83e4a8a8cfcf1790389351c2e56bc1dd23db25ff224188
3
+ size 3204
data/monthly/2026-05.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4f461fad44165bee59c99583eda7bf669ce24b737089038152654cc461aa33de
3
+ size 3251
data/monthly/2026-06.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7927534309233d1d631840aaae1f90b372fe1367efcf930bbbfb758e4e453ab4
3
+ size 3442