File size: 2,549 Bytes
b2c86fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import os, json, datetime, urllib.request, urllib.error

key = os.getenv("ANTHROPIC_API_KEY", "").strip()
if not key:
    print("❌ 未设置 ANTHROPIC_API_KEY")
    raise SystemExit(1)

print("✅ KEY已设置:", key[:8] + "..." + key[-4:])

headers = {
    "x-api-key": key,
    "anthropic-version": "2023-06-01",
    "content-type": "application/json",
}

# 1) 验证 key 可用
msg_payload = {
    "model": "claude-opus-4-7",
    "max_tokens": 8,
    "messages": [{"role": "user", "content": "ping"}]
}
req = urllib.request.Request(
    "https://api.anthropic.com/v1/messages",
    data=json.dumps(msg_payload).encode(),
    headers=headers,
    method="POST",
)
try:
    with urllib.request.urlopen(req, timeout=30) as r:
        body = json.loads(r.read().decode())
        print("✅ messages 接口可用")
        print("usage:", body.get("usage", {}))
except urllib.error.HTTPError as e:
    print("❌ messages 接口失败:", e.code, e.read().decode(errors="ignore")[:500])

# 2) 查询最近7天花费(组织管理员 key 才可能成功)
end = datetime.date.today()
start = end - datetime.timedelta(days=7)
cost_payload = {
    "starting_at": f"{start.isoformat()}T00:00:00Z",
    "ending_at": f"{end.isoformat()}T23:59:59Z",
    "bucket_width": "1d"
}
req2 = urllib.request.Request(
    "https://api.anthropic.com/v1/organizations/cost_report",
    data=json.dumps(cost_payload).encode(),
    headers=headers,
    method="POST",
)
try:
    with urllib.request.urlopen(req2, timeout=30) as r:
        body = json.loads(r.read().decode())
        print("✅ cost_report 返回成功")
        print(json.dumps(body, ensure_ascii=False)[:2000])
except urllib.error.HTTPError as e:
    print("ℹ️ cost_report 不可用(常见于非管理员key):", e.code, e.read().decode(errors="ignore")[:500])

# 3) 查询可用模型列表
models_req = urllib.request.Request(
    "https://api.anthropic.com/v1/models",
    headers=headers,
    method="GET",
)
try:
    with urllib.request.urlopen(models_req, timeout=30) as r:
        body = json.loads(r.read().decode())
        models = body.get("data", [])
        print(f"✅ models 接口可用,共 {len(models)} 个模型")
        for m in models[:20]:
            model_id = m.get("id", "")
            display_name = m.get("display_name", "")
            created_at = m.get("created_at", "")
            print(f"- {model_id} | {display_name} | {created_at}")
except urllib.error.HTTPError as e:
    print("❌ models 接口失败:", e.code, e.read().decode(errors="ignore")[:500])