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