|
|
|
""" |
|
OpenRouter API 連線測試腳本 |
|
測試 DeepSeek V3 是否能正常連接和回應 |
|
""" |
|
|
|
import requests |
|
import json |
|
import os |
|
from datetime import datetime |
|
|
|
|
|
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']}") |
|
|
|
|
|
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_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]: |
|
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) |
|
|
|
|
|
if not test_api_key_validity(): |
|
print("\n❌ API Key 測試失敗,停止後續測試") |
|
return |
|
|
|
|
|
check_model_availability() |
|
|
|
|
|
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() |