mickeywu520 commited on
Commit
184558c
·
1 Parent(s): 81a7334

add openrouter connection testing script

Browse files
Files changed (1) hide show
  1. test_openrouter_connection.py +223 -0
test_openrouter_connection.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ OpenRouter API 連線測試腳本
4
+ 測試 DeepSeek V3 是否能正常連接和回應
5
+ """
6
+
7
+ import requests
8
+ import json
9
+ import os
10
+ from datetime import datetime
11
+
12
+ # API 設定
13
+ OPENROUTER_API_KEY = "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"
14
+ OPENROUTER_MODEL = "deepseek/deepseek-chat-v3-0324:free"
15
+ OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions"
16
+
17
+ def test_openrouter_connection():
18
+ """測試 OpenRouter API 連線"""
19
+
20
+ print("🔧 OpenRouter API 連線測試")
21
+ print("=" * 50)
22
+ print(f"⏰ 測試時間: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
23
+ print(f"🔑 API Key: {OPENROUTER_API_KEY[:20]}...")
24
+ print(f"🤖 模型: {OPENROUTER_MODEL}")
25
+ print(f"🌐 API URL: {OPENROUTER_URL}")
26
+ print("=" * 50)
27
+
28
+ # 設定請求標頭
29
+ headers = {
30
+ "Authorization": f"Bearer {OPENROUTER_API_KEY}",
31
+ "Content-Type": "application/json",
32
+ "HTTP-Referer": "https://huggingface.co/spaces",
33
+ "X-Title": "OpenRouter Connection Test"
34
+ }
35
+
36
+ # 測試案例
37
+ test_cases = [
38
+ {
39
+ "name": "基本連線測試",
40
+ "message": "你好,請介紹一下自己"
41
+ },
42
+ {
43
+ "name": "中文理解測試",
44
+ "message": "請分析這句話的意圖:查詢iPhone庫存"
45
+ },
46
+ {
47
+ "name": "業務查詢測試",
48
+ "message": "如果用戶說「商品查詢」,這應該被歸類為什麼意圖?請用JSON格式回答"
49
+ }
50
+ ]
51
+
52
+ for i, test_case in enumerate(test_cases, 1):
53
+ print(f"\n📝 測試 {i}: {test_case['name']}")
54
+ print("-" * 30)
55
+
56
+ # 準備請求資料
57
+ data = {
58
+ "model": OPENROUTER_MODEL,
59
+ "messages": [
60
+ {
61
+ "role": "system",
62
+ "content": "你是 DeepSeek V3,一個強大的中文 AI 助手。請用繁體中文回應。"
63
+ },
64
+ {
65
+ "role": "user",
66
+ "content": test_case['message']
67
+ }
68
+ ],
69
+ "temperature": 0.7,
70
+ "max_tokens": 300
71
+ }
72
+
73
+ try:
74
+ print(f"📤 發送請求: {test_case['message']}")
75
+
76
+ # 發送 API 請求
77
+ response = requests.post(
78
+ OPENROUTER_URL,
79
+ headers=headers,
80
+ json=data,
81
+ timeout=30
82
+ )
83
+
84
+ print(f"📊 狀態碼: {response.status_code}")
85
+
86
+ if response.status_code == 200:
87
+ # 解析回應
88
+ result = response.json()
89
+ content = result["choices"][0]["message"]["content"]
90
+
91
+ print(f"✅ 請求成功!")
92
+ print(f"🤖 DeepSeek V3 回應:")
93
+ print(f" {content[:200]}{'...' if len(content) > 200 else ''}")
94
+
95
+ # 顯示使用統計
96
+ if "usage" in result:
97
+ usage = result["usage"]
98
+ print(f"📈 Token 使用: {usage.get('total_tokens', 'N/A')} tokens")
99
+
100
+ else:
101
+ print(f"❌ 請求失敗!")
102
+ print(f"錯誤回應: {response.text}")
103
+
104
+ except requests.exceptions.Timeout:
105
+ print("❌ 請求超時 (30秒)")
106
+
107
+ except requests.exceptions.ConnectionError:
108
+ print("❌ 網路連線錯誤")
109
+
110
+ except json.JSONDecodeError:
111
+ print("❌ JSON 解析錯誤")
112
+ print(f"原始回應: {response.text}")
113
+
114
+ except Exception as e:
115
+ print(f"❌ 未知錯誤: {str(e)}")
116
+
117
+ def test_api_key_validity():
118
+ """測試 API Key 有效性"""
119
+
120
+ print("\n🔐 API Key 有效性測試")
121
+ print("-" * 30)
122
+
123
+ headers = {
124
+ "Authorization": f"Bearer {OPENROUTER_API_KEY}",
125
+ "Content-Type": "application/json"
126
+ }
127
+
128
+ # 簡單的測試請求
129
+ data = {
130
+ "model": OPENROUTER_MODEL,
131
+ "messages": [{"role": "user", "content": "test"}],
132
+ "max_tokens": 1
133
+ }
134
+
135
+ try:
136
+ response = requests.post(OPENROUTER_URL, headers=headers, json=data, timeout=10)
137
+
138
+ if response.status_code == 200:
139
+ print("✅ API Key 有效")
140
+ return True
141
+ elif response.status_code == 401:
142
+ print("❌ API Key 無效或已過期")
143
+ return False
144
+ elif response.status_code == 402:
145
+ print("⚠️ 餘額不足")
146
+ return False
147
+ else:
148
+ print(f"⚠️ 未知狀態: {response.status_code}")
149
+ print(f"回應: {response.text}")
150
+ return False
151
+
152
+ except Exception as e:
153
+ print(f"❌ 測試失敗: {str(e)}")
154
+ return False
155
+
156
+ def check_model_availability():
157
+ """檢查模型可用性"""
158
+
159
+ print("\n🤖 模型可用性檢查")
160
+ print("-" * 30)
161
+
162
+ # 嘗試獲取可用模型列表
163
+ try:
164
+ headers = {
165
+ "Authorization": f"Bearer {OPENROUTER_API_KEY}",
166
+ }
167
+
168
+ response = requests.get("https://openrouter.ai/api/v1/models", headers=headers, timeout=10)
169
+
170
+ if response.status_code == 200:
171
+ models = response.json()
172
+
173
+ # 檢查 DeepSeek 模型
174
+ deepseek_models = [model for model in models.get('data', [])
175
+ if 'deepseek' in model.get('id', '').lower()]
176
+
177
+ print(f"✅ 找到 {len(deepseek_models)} 個 DeepSeek 模型:")
178
+ for model in deepseek_models[:5]: # 只顯示前5個
179
+ print(f" - {model.get('id', 'N/A')}")
180
+
181
+ # 檢查目標模型是否存在
182
+ target_model_exists = any(model.get('id') == OPENROUTER_MODEL
183
+ for model in models.get('data', []))
184
+
185
+ if target_model_exists:
186
+ print(f"✅ 目標模型 {OPENROUTER_MODEL} 可用")
187
+ else:
188
+ print(f"⚠️ 目標模型 {OPENROUTER_MODEL} 可能不可用")
189
+
190
+ else:
191
+ print(f"⚠️ 無法獲取模型列表: {response.status_code}")
192
+
193
+ except Exception as e:
194
+ print(f"❌ 檢查失敗: {str(e)}")
195
+
196
+ def main():
197
+ """主函數"""
198
+
199
+ print("🚀 開始 OpenRouter API 完整測試")
200
+ print("=" * 60)
201
+
202
+ # 1. 檢查 API Key 有效性
203
+ if not test_api_key_validity():
204
+ print("\n❌ API Key 測試失敗,停止後續測試")
205
+ return
206
+
207
+ # 2. 檢查模型可用性
208
+ check_model_availability()
209
+
210
+ # 3. 進行完整連線測試
211
+ test_openrouter_connection()
212
+
213
+ print("\n" + "=" * 60)
214
+ print("🎉 測試完成!")
215
+ print("\n💡 如果所有測試都成功,表示:")
216
+ print(" ✅ OpenRouter API Key 有效")
217
+ print(" ✅ DeepSeek V3 模型可用")
218
+ print(" ✅ 網路連線正常")
219
+ print(" ✅ API 回應正常")
220
+ print("\n🔧 如果業務查詢仍有問題,則確定是事件循環衝突導致的技術問題")
221
+
222
+ if __name__ == "__main__":
223
+ main()