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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LLM-judge labeling for GitHub issues: bug / feature / question / support.
|
| 2 |
+
|
| 3 |
+
Judge: openai/gpt-oss-120b via HF Inference Providers (novita), strict JSON schema,
|
| 4 |
+
reasoning_effort=low. Reads the FULL issue text (title + body) — no truncation.
|
| 5 |
+
|
| 6 |
+
Usage:
|
| 7 |
+
python judge_eval.py --n-per-class 1 # smoke: 4 issues, 1 per maintainer label
|
| 8 |
+
python judge_eval.py --n-per-class 50 # full eval set: 200 issues
|
| 9 |
+
Writes judge/review_<N>.jsonl + .csv to pngwn/github-issues-4class and prints summary.
|
| 10 |
+
|
| 11 |
+
References: hf://docs/inference-providers/guides/structured-output,
|
| 12 |
+
hf://docs/huggingface_hub/guides/inference.md, hf://docs/hub/jobs-configuration.md
|
| 13 |
+
"""
|
| 14 |
+
import argparse
|
| 15 |
+
import asyncio
|
| 16 |
+
import io
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
|
| 20 |
+
import pandas as pd
|
| 21 |
+
from huggingface_hub import AsyncInferenceClient, HfApi, hf_hub_download
|
| 22 |
+
|
| 23 |
+
MODEL = "openai/gpt-oss-120b"
|
| 24 |
+
PROVIDER = "novita"
|
| 25 |
+
DATASET_REPO = "pngwn/github-issues-4class"
|
| 26 |
+
LABELS = ["bug", "feature", "question", "support"]
|
| 27 |
+
CONCURRENCY = 8
|
| 28 |
+
MAX_RETRIES = 4
|
| 29 |
+
|
| 30 |
+
SCHEMA = {
|
| 31 |
+
"type": "json_schema",
|
| 32 |
+
"json_schema": {
|
| 33 |
+
"name": "IssueVerdict",
|
| 34 |
+
"schema": {
|
| 35 |
+
"type": "object",
|
| 36 |
+
"properties": {
|
| 37 |
+
"label": {"enum": LABELS},
|
| 38 |
+
"confidence": {"type": "number", "description": "0-1"},
|
| 39 |
+
"rationale": {"type": "string", "description": "at most 30 words"},
|
| 40 |
+
},
|
| 41 |
+
"required": ["label", "confidence", "rationale"],
|
| 42 |
+
"additionalProperties": False,
|
| 43 |
+
},
|
| 44 |
+
"strict": True,
|
| 45 |
+
},
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
SYSTEM = """You are an expert triage labeler for GitHub issues. Classify the issue into exactly \
|
| 49 |
+
one of four labels, judging the FULL text (title and body). Judge intent and context, not \
|
| 50 |
+
formatting: template headers and title prefixes like "[Bug]" are conventions, not evidence — \
|
| 51 |
+
some repos use them inconsistently or incorrectly.
|
| 52 |
+
|
| 53 |
+
Definitions and decision rules:
|
| 54 |
+
- bug: The software behaves incorrectly, crashes, regresses, or fails under usage that is \
|
| 55 |
+
correct according to its documented/intended behavior. There is a defect or gap in the library \
|
| 56 |
+
itself. Key test: would resolving this require a change to the library? A crash whose root \
|
| 57 |
+
cause is the user's misconfiguration, unsupported environment, or incorrect usage is NOT a bug.
|
| 58 |
+
- support: The user needs help getting something to work. Their usage, configuration, \
|
| 59 |
+
environment, or setup is likely wrong or unsupported, and the software is behaving as designed. \
|
| 60 |
+
The likely resolution is guidance, configuration, or environment changes on the user side.
|
| 61 |
+
- question: The user asks how something works, how to do something, whether something is \
|
| 62 |
+
possible, or requests information — without claiming the software misbehaves. Documentation \
|
| 63 |
+
gaps surfaced as "how do I...?" are questions, not bugs.
|
| 64 |
+
- feature: The user requests new functionality, an enhancement, or a behavior change they \
|
| 65 |
+
want — not a report that existing behavior is broken.
|
| 66 |
+
|
| 67 |
+
Ambiguity resolution (this is where most errors happen):
|
| 68 |
+
- "X crashes" alone is ambiguous. Decide from evidence: stack traces pointing into library \
|
| 69 |
+
code with correct/documented usage, or reproduction via documented APIs, indicate bug; \
|
| 70 |
+
evidence of user-side setup, version mismatch the user can fix, or misconfiguration indicates \
|
| 71 |
+
support.
|
| 72 |
+
- A carefully written report analyzing library internals to find a root cause is a bug even \
|
| 73 |
+
if it reads like a request for help.
|
| 74 |
+
- A request phrased as "help me" that describes a genuine defect is a bug.
|
| 75 |
+
- If a defect claim and a new-capability request both appear, follow the dominant intent.
|
| 76 |
+
- If the text is genuinely undecidable, pick the closest label and lower your confidence.
|
| 77 |
+
|
| 78 |
+
Respond with JSON only: label, confidence (0-1), rationale (max 30 words)."""
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def parse_args():
|
| 82 |
+
ap = argparse.ArgumentParser()
|
| 83 |
+
ap.add_argument("--n-per-class", type=int, default=50)
|
| 84 |
+
ap.add_argument("--split", default="test")
|
| 85 |
+
ap.add_argument("--seed", type=int, default=42)
|
| 86 |
+
ap.add_argument("--out-prefix", default=None)
|
| 87 |
+
return ap.parse_args()
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def load_split(split):
|
| 91 |
+
path = hf_hub_download(repo_id=DATASET_REPO, repo_type="dataset", filename=f"data/{split}-00000-of-00001.parquet")
|
| 92 |
+
return pd.read_parquet(path)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
async def judge_one(client, sem, row_id, text):
|
| 96 |
+
async with sem:
|
| 97 |
+
last_err = None
|
| 98 |
+
for attempt in range(MAX_RETRIES):
|
| 99 |
+
try:
|
| 100 |
+
resp = await client.chat_completion(
|
| 101 |
+
model=MODEL,
|
| 102 |
+
messages=[
|
| 103 |
+
{"role": "system", "content": SYSTEM},
|
| 104 |
+
{"role": "user", "content": text},
|
| 105 |
+
],
|
| 106 |
+
response_format=SCHEMA,
|
| 107 |
+
max_tokens=250,
|
| 108 |
+
)
|
| 109 |
+
content = resp.choices[0].message.content
|
| 110 |
+
verdict = json.loads(content)
|
| 111 |
+
if verdict.get("label") not in LABELS:
|
| 112 |
+
raise ValueError(f"bad label: {verdict.get('label')!r}")
|
| 113 |
+
usage = getattr(resp, "usage", None)
|
| 114 |
+
return {
|
| 115 |
+
"id": row_id,
|
| 116 |
+
"verdict": verdict,
|
| 117 |
+
"prompt_tokens": getattr(usage, "prompt_tokens", None),
|
| 118 |
+
"completion_tokens": getattr(usage, "completion_tokens", None),
|
| 119 |
+
}
|
| 120 |
+
except Exception as e: # noqa: BLE001 — retry any transient failure
|
| 121 |
+
last_err = e
|
| 122 |
+
await asyncio.sleep(min(2 ** attempt * 3, 30))
|
| 123 |
+
return {"id": row_id, "error": str(last_err)}
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
async def run(rows):
|
| 127 |
+
client = AsyncInferenceClient(provider=PROVIDER, api_key=os.environ["HF_TOKEN"])
|
| 128 |
+
sem = asyncio.Semaphore(CONCURRENCY)
|
| 129 |
+
tasks = [judge_one(client, sem, r["id"], r["text"]) for r in rows]
|
| 130 |
+
return await asyncio.gather(*tasks)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def main():
|
| 134 |
+
args = parse_args()
|
| 135 |
+
df = load_split(args.split)
|
| 136 |
+
assert {"text", "label"} <= set(df.columns)
|
| 137 |
+
|
| 138 |
+
df = df.reset_index(drop=False).rename(columns={"index": "row_id"})
|
| 139 |
+
parts = []
|
| 140 |
+
for lbl in LABELS:
|
| 141 |
+
sub = df[df["label"] == lbl]
|
| 142 |
+
if len(sub) > args.n_per_class:
|
| 143 |
+
sub = sub.sample(n=args.n_per_class, random_state=args.seed)
|
| 144 |
+
parts.append(sub)
|
| 145 |
+
strat = pd.concat(parts).reset_index(drop=True)
|
| 146 |
+
rows = [
|
| 147 |
+
{"id": int(r["row_id"]), "text": str(r["text"]), "maintainer_label": str(r["label"]), "repo": str(r["repo"])}
|
| 148 |
+
for _, r in strat.iterrows()
|
| 149 |
+
]
|
| 150 |
+
print(f"judging {len(rows)} issues ({args.n_per_class}/class from {args.split})...")
|
| 151 |
+
|
| 152 |
+
results = asyncio.run(run(rows))
|
| 153 |
+
|
| 154 |
+
by_id = {r["id"]: r for r in results}
|
| 155 |
+
out_rows, errs, ptok, ctok = [], 0, 0, 0
|
| 156 |
+
for row in rows:
|
| 157 |
+
res = by_id[row["id"]]
|
| 158 |
+
if "error" in res:
|
| 159 |
+
errs += 1
|
| 160 |
+
verdict = {"label": "ERROR", "confidence": 0.0, "rationale": res["error"][:200]}
|
| 161 |
+
else:
|
| 162 |
+
verdict = res["verdict"]
|
| 163 |
+
ptok += res["prompt_tokens"] or 0
|
| 164 |
+
ctok += res["completion_tokens"] or 0
|
| 165 |
+
out_rows.append({**row, "judge_label": verdict["label"], "judge_confidence": verdict["confidence"],
|
| 166 |
+
"judge_rationale": verdict["rationale"]})
|
| 167 |
+
|
| 168 |
+
out = pd.DataFrame(out_rows)
|
| 169 |
+
agree = (out["judge_label"] == out["maintainer_label"]).mean()
|
| 170 |
+
print(f"\nerrors: {errs}/{len(out)}")
|
| 171 |
+
print(f"judge agrees with maintainer label: {agree:.1%}")
|
| 172 |
+
print("\nconfusion (rows=maintainer, cols=judge):")
|
| 173 |
+
print(pd.crosstab(out["maintainer_label"], out["judge_label"]).to_string())
|
| 174 |
+
print(f"\ntokens: {ptok} in / {ctok} out (~${ptok * 0.05 / 1e6 + ctok * 0.25 / 1e6:.4f} at gpt-oss-120b novita rates)")
|
| 175 |
+
|
| 176 |
+
prefix = args.out_prefix or f"review_{len(out)}"
|
| 177 |
+
api = HfApi()
|
| 178 |
+
for name, data in [
|
| 179 |
+
(f"judge/{prefix}.jsonl", "\n".join(json.dumps(r) for r in out_rows)),
|
| 180 |
+
(f"judge/{prefix}.csv", out.to_csv(index=False)),
|
| 181 |
+
]:
|
| 182 |
+
api.upload_file(
|
| 183 |
+
path_or_fileobj=data.encode(),
|
| 184 |
+
path_in_repo=name,
|
| 185 |
+
repo_id=DATASET_REPO,
|
| 186 |
+
repo_type="dataset",
|
| 187 |
+
commit_message=f"judge labels: {prefix}",
|
| 188 |
+
)
|
| 189 |
+
print(f"uploaded {name}")
|
| 190 |
+
print("DONE")
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
if __name__ == "__main__":
|
| 194 |
+
main()
|