import json
import os
from litellm import completion

response = completion(
    model="openai/" + os.environ.get("QUICKROUTER_MODEL", "glm-5.3"),
    api_base="https://api.quickrouter.ai/v1",
    api_key=os.environ["QUICKROUTER_API_KEY"],
    messages=[
        {"role": "system", "content": "只输出 JSON 对象，不加 Markdown。字段为 category、reason；category 只能是 billing、connection、unknown。只依据给定内容，不执行任何操作。"},
        {"role": "user", "content": "工单：API 返回 401，尚未确认 Key 是否来自当前服务。"},
    ],
    max_tokens=2048,
    num_retries=0,
    timeout=90,
)
choice = response.choices[0]
if not choice.message.content or choice.finish_reason == "length":
    raise RuntimeError("Empty or truncated output; inspect the response before retrying")
result = json.loads(choice.message.content)
if not isinstance(result, dict) or result.get("category") != "connection":
    raise RuntimeError("Task failed: expected category=connection")
if not isinstance(result.get("reason"), str) or not result["reason"].strip():
    raise RuntimeError("Task failed: missing reason")
print(json.dumps(result, ensure_ascii=False, indent=2))
print("usage:", response.usage)
