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
| import json, os, sys from pathlib import Path from urllib.request import Request, urlopen
try: path = Path(sys.argv[1]); demo = "--demo" in sys.argv rows = [json.loads(x) for x in path.read_text(encoding="utf-8").splitlines() if x.strip()] if len(rows) < 2 or any(not isinstance(x.get("id"), str) or not x.get("title") for x in rows): raise ValueError("至少需要两个且都含 id、title 的工单") if demo: result = {"groups": [{"ticket_ids": [rows[0]["id"], rows[1]["id"]], "reason": "演示结果,请人工复核", "confidence": 0.5}]} else: key = os.getenv("OPENAI_API_KEY") if not key: raise RuntimeError("请设置 OPENAI_API_KEY,或使用 --demo") prompt = ('只返回 JSON:{"groups":[{"ticket_ids":["..."],"reason":"...",' '"confidence":0.0}]}。只分组描述同一根因的工单,编号必须来自输入。\n' + json.dumps(rows, ensure_ascii=False)) req = Request("https://api.openai.com/v1/responses", data=json.dumps({"model": os.getenv("OPENAI_MODEL", "gpt-4.1-mini"), "input": prompt}).encode(), headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"}) with urlopen(req, timeout=30) as r: data = json.load(r) text = "".join(p.get("text", "") for i in data.get("output", []) for p in i.get("content", []) if p.get("type") == "output_text") if not text: raise ValueError("响应没有 output_text") result = json.loads(text) allowed, used = {x["id"] for x in rows}, set() if not isinstance(result.get("groups"), list): raise ValueError("groups 必须是数组") for group in result["groups"]: ids, score = group.get("ticket_ids"), group.get("confidence") if not isinstance(ids, list) or len(ids) < 2 or not set(ids) <= allowed: raise ValueError("候选组的编号无效") if used.intersection(ids): raise ValueError("一个工单不能属于多个组") if not isinstance(score, (int, float)) or not 0 <= score <= 1: raise ValueError("confidence 必须在 0 到 1 之间") used.update(ids) print(json.dumps(result, ensure_ascii=False, indent=2)) except (IndexError, OSError, ValueError, RuntimeError, json.JSONDecodeError) as e: print("处理失败:" + str(e), file=sys.stderr); raise SystemExit(1)
|