kzhu99 commited on
Commit
8a3e6b4
·
verified ·
1 Parent(s): 03e8406

Upload 2 files

Browse files
no_skill_trajectory_clustering.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Cluster trajectories that did not invoke/read ``skill.md``.
3
+
4
+ The preferred input is ``all_trajectories.json`` produced by
5
+ ``analyze_skill_trajectories.py``. JSONL with the same records is also accepted.
6
+ The reader streams both formats so the complete trajectory file is never loaded
7
+ into memory.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import csv
14
+ import hashlib
15
+ import json
16
+ import math
17
+ import re
18
+ from collections import Counter, defaultdict
19
+ from pathlib import Path
20
+ from typing import Any, Iterable, Iterator
21
+
22
+ import numpy as np
23
+ from scipy.sparse import csr_matrix, hstack
24
+ from sklearn.cluster import MiniBatchKMeans
25
+ from sklearn.feature_extraction.text import TfidfVectorizer
26
+ from sklearn.metrics import silhouette_score
27
+ from sklearn.preprocessing import normalize
28
+
29
+
30
+ WS_RE = re.compile(r"\s+")
31
+ UUID_RE = re.compile(r"\b[0-9a-f]{8}-[0-9a-f-]{27,}\b", re.I)
32
+ LONG_NUM_RE = re.compile(r"\b\d{4,}\b")
33
+ URL_RE = re.compile(r"https?://\S+", re.I)
34
+ PATH_RE = re.compile(r"(?:[A-Za-z]:)?(?:[/\\][^\s/\\]+){2,}")
35
+
36
+
37
+ def compact_text(value: Any, limit: int = 3000) -> str:
38
+ if not isinstance(value, str):
39
+ return ""
40
+ value = URL_RE.sub(" <URL> ", value)
41
+ value = UUID_RE.sub(" <UUID> ", value)
42
+ value = PATH_RE.sub(" <PATH> ", value)
43
+ value = LONG_NUM_RE.sub(" <NUM> ", value)
44
+ return WS_RE.sub(" ", value).strip()[:limit]
45
+
46
+
47
+ def iter_json_array(path: Path, chunk_size: int = 1024 * 1024) -> Iterator[Any]:
48
+ """Stream a top-level JSON array using the standard library."""
49
+ decoder = json.JSONDecoder()
50
+ with path.open("r", encoding="utf-8") as handle:
51
+ buffer = ""
52
+ pos = 0
53
+ started = False
54
+ eof = False
55
+ while True:
56
+ if pos >= len(buffer) and not eof:
57
+ buffer = handle.read(chunk_size)
58
+ pos = 0
59
+ eof = not buffer
60
+ while pos < len(buffer) and buffer[pos].isspace():
61
+ pos += 1
62
+ if not started:
63
+ if pos >= len(buffer) and not eof:
64
+ continue
65
+ if pos >= len(buffer) or buffer[pos] != "[":
66
+ raise ValueError(f"{path} is not a top-level JSON array")
67
+ pos += 1
68
+ started = True
69
+ while True:
70
+ while pos < len(buffer) and (buffer[pos].isspace() or buffer[pos] == ","):
71
+ pos += 1
72
+ if pos < len(buffer) and buffer[pos] == "]":
73
+ return
74
+ try:
75
+ obj, end = decoder.raw_decode(buffer, pos)
76
+ pos = end
77
+ yield obj
78
+ break
79
+ except json.JSONDecodeError:
80
+ if eof:
81
+ raise
82
+ buffer = buffer[pos:] + handle.read(chunk_size)
83
+ pos = 0
84
+ eof = len(buffer) == 0
85
+
86
+
87
+ def iter_records(path: Path) -> Iterator[dict[str, Any]]:
88
+ if path.suffix.lower() == ".jsonl":
89
+ with path.open("r", encoding="utf-8") as handle:
90
+ for line_no, line in enumerate(handle, 1):
91
+ if line.strip():
92
+ value = json.loads(line)
93
+ if not isinstance(value, dict):
94
+ raise ValueError(f"line {line_no} is not an object")
95
+ yield value
96
+ return
97
+ for value in iter_json_array(path):
98
+ if isinstance(value, dict):
99
+ yield value
100
+
101
+
102
+ def input_keys(value: Any, prefix: str = "", depth: int = 0) -> list[str]:
103
+ if not isinstance(value, dict) or depth > 2:
104
+ return []
105
+ result: list[str] = []
106
+ for key, child in value.items():
107
+ key = re.sub(r"[^\w.-]+", "_", str(key).lower())
108
+ full = f"{prefix}.{key}" if prefix else key
109
+ result.append(full)
110
+ if isinstance(child, dict):
111
+ result.extend(input_keys(child, full, depth + 1))
112
+ return result
113
+
114
+
115
+ def extract_features(record: dict[str, Any], include_assistant: bool) -> dict[str, Any]:
116
+ semantic: list[str] = []
117
+ tools: list[str] = []
118
+ tool_keys: list[str] = []
119
+ event_types: list[str] = []
120
+ events = record.get("events") or []
121
+ for event in events:
122
+ if not isinstance(event, dict):
123
+ continue
124
+ kind = str(event.get("event_type") or "unknown").lower()
125
+ event_types.append(kind)
126
+ if kind == "user" or (include_assistant and kind == "assistant_text"):
127
+ text = compact_text(event.get("text"))
128
+ if text:
129
+ semantic.append(text)
130
+ elif kind == "tool_use":
131
+ tool = re.sub(r"[^\w.-]+", "_", str(event.get("tool_name") or "unknown").lower())
132
+ tools.append(tool)
133
+ tool_keys.extend(f"{tool}:{key}" for key in input_keys(event.get("tool_input")))
134
+ sequence = [f"tool={name}" for name in tools]
135
+ sequence += [f"tool2={a}>{b}" for a, b in zip(tools, tools[1:])]
136
+ sequence += [f"event2={a}>{b}" for a, b in zip(event_types, event_types[1:])]
137
+ behavior = " ".join(sequence + [f"arg={key}" for key in tool_keys])
138
+ return {
139
+ "trajectory_id": str(record.get("trajectory_id") or ""),
140
+ "source_file": str(record.get("source_file") or ""),
141
+ "record_index": record.get("record_index"),
142
+ "semantic_text": " ".join(semantic),
143
+ "behavior_text": behavior,
144
+ "tool_sequence": tools,
145
+ "event_count": int(record.get("event_count") or len(events)),
146
+ }
147
+
148
+
149
+ def load_no_skill(path: Path, include_assistant: bool, min_events: int) -> tuple[list[dict[str, Any]], dict[str, int]]:
150
+ rows: list[dict[str, Any]] = []
151
+ stats = Counter()
152
+ for record in iter_records(path):
153
+ stats["all"] += 1
154
+ if record.get("contains_skill_md") is True or record.get("skill_sessions"):
155
+ stats["with_skill"] += 1
156
+ continue
157
+ stats["without_skill"] += 1
158
+ row = extract_features(record, include_assistant)
159
+ if row["event_count"] < min_events:
160
+ stats["too_short"] += 1
161
+ continue
162
+ if not row["semantic_text"] and not row["behavior_text"]:
163
+ stats["empty"] += 1
164
+ continue
165
+ rows.append(row)
166
+ stats["clustered"] = len(rows)
167
+ return rows, dict(stats)
168
+
169
+
170
+ def build_matrix(rows: list[dict[str, Any]], max_features: int) -> tuple[csr_matrix, TfidfVectorizer, TfidfVectorizer]:
171
+ semantic_vec = TfidfVectorizer(
172
+ analyzer="char_wb", ngram_range=(2, 5), min_df=2, max_df=0.98,
173
+ max_features=max_features, sublinear_tf=True,
174
+ )
175
+ behavior_vec = TfidfVectorizer(
176
+ token_pattern=r"(?u)\b\S+\b", ngram_range=(1, 2), min_df=2,
177
+ max_features=max(2000, max_features // 3), sublinear_tf=True,
178
+ )
179
+ try:
180
+ semantic = semantic_vec.fit_transform(row["semantic_text"] for row in rows)
181
+ except ValueError as exc:
182
+ if "empty vocabulary" not in str(exc):
183
+ raise
184
+ semantic_vec.set_params(min_df=1, max_df=1.0)
185
+ semantic = semantic_vec.fit_transform(row["semantic_text"] for row in rows)
186
+ try:
187
+ behavior = behavior_vec.fit_transform(row["behavior_text"] for row in rows)
188
+ except ValueError as exc:
189
+ if "empty vocabulary" not in str(exc):
190
+ raise
191
+ behavior_vec.set_params(min_df=1)
192
+ behavior = behavior_vec.fit_transform(row["behavior_text"] for row in rows)
193
+ # Equal L2 contribution when both channels are present.
194
+ matrix = hstack([normalize(semantic) * math.sqrt(0.65), normalize(behavior) * math.sqrt(0.35)]).tocsr()
195
+ return normalize(matrix), semantic_vec, behavior_vec
196
+
197
+
198
+ def choose_k(matrix: csr_matrix, requested: int, seed: int, sample_size: int) -> tuple[int, list[dict[str, float]]]:
199
+ n = matrix.shape[0]
200
+ if requested > 0:
201
+ return min(requested, n), []
202
+ upper = min(30, max(2, int(math.sqrt(n))), n - 1)
203
+ candidates = sorted(set([2, 3, 4, 5, 6, 8, 10, 12, 15, 20, upper]))
204
+ candidates = [k for k in candidates if 2 <= k <= upper]
205
+ rng = np.random.default_rng(seed)
206
+ idx = np.arange(n) if n <= sample_size else rng.choice(n, sample_size, replace=False)
207
+ scores = []
208
+ for k in candidates:
209
+ model = MiniBatchKMeans(n_clusters=k, random_state=seed, batch_size=min(2048, n), n_init=3)
210
+ labels = model.fit_predict(matrix)
211
+ sampled_labels = labels[idx]
212
+ if len(set(sampled_labels)) < 2:
213
+ score = -1.0
214
+ else:
215
+ score = float(silhouette_score(matrix[idx], sampled_labels, metric="cosine"))
216
+ scores.append({"k": k, "silhouette": score})
217
+ best = max(scores, key=lambda item: item["silhouette"])
218
+ return int(best["k"]), scores
219
+
220
+
221
+ def top_terms(center: np.ndarray, semantic_vec: TfidfVectorizer, behavior_vec: TfidfVectorizer, n: int = 10) -> tuple[list[str], list[str]]:
222
+ s_names = semantic_vec.get_feature_names_out()
223
+ b_names = behavior_vec.get_feature_names_out()
224
+ split = len(s_names)
225
+ s_idx = np.argsort(center[:split])[-n:][::-1]
226
+ b_idx = np.argsort(center[split:])[-n:][::-1]
227
+ return [str(s_names[i]) for i in s_idx if center[i] > 0], [str(b_names[i]) for i in b_idx if center[split + i] > 0]
228
+
229
+
230
+ def write_outputs(output: Path, rows: list[dict[str, Any]], matrix: csr_matrix, model: MiniBatchKMeans,
231
+ labels: np.ndarray, semantic_vec: TfidfVectorizer, behavior_vec: TfidfVectorizer,
232
+ stats: dict[str, int], k_scores: list[dict[str, float]]) -> None:
233
+ output.mkdir(parents=True, exist_ok=True)
234
+ distances = model.transform(matrix)
235
+ summaries = []
236
+ members = defaultdict(list)
237
+ for i, label in enumerate(labels):
238
+ rows[i]["cluster_id"] = int(label)
239
+ rows[i]["distance_to_centroid"] = float(distances[i, label])
240
+ members[int(label)].append(i)
241
+ with (output / "cluster_members.csv").open("w", encoding="utf-8-sig", newline="") as f:
242
+ writer = csv.DictWriter(f, fieldnames=["cluster_id", "trajectory_id", "source_file", "record_index", "event_count", "distance_to_centroid", "semantic_preview", "tool_sequence"])
243
+ writer.writeheader()
244
+ for row in sorted(rows, key=lambda x: (x["cluster_id"], x["distance_to_centroid"])):
245
+ writer.writerow({**{key: row.get(key) for key in writer.fieldnames}, "semantic_preview": row["semantic_text"][:300], "tool_sequence": " -> ".join(row["tool_sequence"])})
246
+ with (output / "cluster_assignments.jsonl").open("w", encoding="utf-8") as f:
247
+ for row in rows:
248
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
249
+ for label, indices in sorted(members.items()):
250
+ ranked = sorted(indices, key=lambda i: rows[i]["distance_to_centroid"])
251
+ semantic_terms, behavior_terms = top_terms(model.cluster_centers_[label], semantic_vec, behavior_vec)
252
+ summaries.append({
253
+ "cluster_id": label, "size": len(indices), "semantic_terms": semantic_terms,
254
+ "behavior_terms": behavior_terms,
255
+ "representatives": [{"trajectory_id": rows[i]["trajectory_id"], "source_file": rows[i]["source_file"], "preview": rows[i]["semantic_text"][:500], "tools": rows[i]["tool_sequence"]} for i in ranked[:5]],
256
+ })
257
+ report = {"statistics": stats, "selected_k": len(members), "k_selection": k_scores, "clusters": summaries}
258
+ (output / "cluster_summary.json").write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
259
+ lines = ["# 未调用 skill.md 的轨迹聚类", "", f"- 原始轨迹:{stats.get('all', 0)}", f"- 未调用 Skill:{stats.get('without_skill', 0)}", f"- 实际聚类:{stats.get('clustered', 0)}", f"- 聚类数量:{len(members)}", "", "## 聚类概览", "", "| Cluster | 数量 | 语义关键词 | 行为模式 | 代表轨迹 |", "|---:|---:|---|---|---|"]
260
+ for item in summaries:
261
+ rep = item["representatives"][0] if item["representatives"] else {}
262
+ preview = str(rep.get("preview", "")).replace("|", "\\|")[:120]
263
+ lines.append(f"| {item['cluster_id']} | {item['size']} | {', '.join(item['semantic_terms'][:6])} | {', '.join(item['behavior_terms'][:5])} | {preview} |")
264
+ lines += ["", "> `cluster_members.csv` 按“簇 → 距离中心由近到远”排列,建议优先检查每簇前 5 条代表轨迹。", ""]
265
+ (output / "cluster_report.md").write_text("\n".join(lines), encoding="utf-8")
266
+
267
+
268
+ def main() -> None:
269
+ parser = argparse.ArgumentParser(description=__doc__)
270
+ parser.add_argument("--input", required=True, type=Path, help="all_trajectories.json or equivalent JSONL")
271
+ parser.add_argument("--output-dir", required=True, type=Path)
272
+ parser.add_argument("--n-clusters", type=int, default=0, help="0: choose automatically")
273
+ parser.add_argument("--min-events", type=int, default=3)
274
+ parser.add_argument("--max-features", type=int, default=30000)
275
+ parser.add_argument("--silhouette-sample", type=int, default=5000)
276
+ parser.add_argument("--include-assistant", action="store_true")
277
+ parser.add_argument("--seed", type=int, default=42)
278
+ args = parser.parse_args()
279
+
280
+ args.output_dir.mkdir(parents=True, exist_ok=True)
281
+ cache_path = args.output_dir / "trajectory_features.jsonl"
282
+ cache_meta_path = args.output_dir / "trajectory_features.meta.json"
283
+ signature = {
284
+ "input": str(args.input.resolve()), "size": args.input.stat().st_size,
285
+ "mtime_ns": args.input.stat().st_mtime_ns, "min_events": args.min_events,
286
+ "include_assistant": args.include_assistant,
287
+ }
288
+ print("[1/4] Streaming and filtering trajectories ...", flush=True)
289
+ if cache_path.exists() and cache_meta_path.exists() and json.loads(cache_meta_path.read_text(encoding="utf-8")).get("signature") == signature:
290
+ rows = list(iter_records(cache_path))
291
+ stats = json.loads(cache_meta_path.read_text(encoding="utf-8"))["statistics"]
292
+ print(f" reused cache: {cache_path}", flush=True)
293
+ else:
294
+ rows, stats = load_no_skill(args.input, args.include_assistant, args.min_events)
295
+ with cache_path.open("w", encoding="utf-8") as handle:
296
+ for row in rows:
297
+ handle.write(json.dumps(row, ensure_ascii=False) + "\n")
298
+ cache_meta_path.write_text(json.dumps({"signature": signature, "statistics": stats}, ensure_ascii=False, indent=2), encoding="utf-8")
299
+ if len(rows) < 3:
300
+ raise SystemExit(f"Only {len(rows)} usable no-skill trajectories; at least 3 are required")
301
+ print(f" no-skill={stats.get('without_skill', 0)}, usable={len(rows)}", flush=True)
302
+ print("[2/4] Building semantic + behavior TF-IDF features ...", flush=True)
303
+ matrix, semantic_vec, behavior_vec = build_matrix(rows, args.max_features)
304
+ print(f" matrix={matrix.shape}, nnz={matrix.nnz}", flush=True)
305
+ print("[3/4] Selecting k and clustering ...", flush=True)
306
+ k, k_scores = choose_k(matrix, args.n_clusters, args.seed, args.silhouette_sample)
307
+ model = MiniBatchKMeans(n_clusters=k, random_state=args.seed, batch_size=min(2048, len(rows)), n_init=10)
308
+ labels = model.fit_predict(matrix)
309
+ print(f" selected_k={k}", flush=True)
310
+ print("[4/4] Writing review files ...", flush=True)
311
+ write_outputs(args.output_dir, rows, matrix, model, labels, semantic_vec, behavior_vec, stats, k_scores)
312
+ print(f"Done: {args.output_dir / 'cluster_report.md'}", flush=True)
313
+
314
+
315
+ if __name__ == "__main__":
316
+ main()
skill_evolution_pipeline_family_operator_v4_5.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:31455e7df2461800e8032bb298295a7ebce0f0c04807b507eb1fe4a7322c8213
3
+ size 260178