#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 簡化的 Dify 客戶端測試 - 不依賴資料庫 """ import sys import os import requests import time # Fix encoding for Windows console if sys.stdout.encoding != 'utf-8': sys.stdout.reconfigure(encoding='utf-8') if sys.stderr.encoding != 'utf-8': sys.stderr.reconfigure(encoding='utf-8') def test_dify_direct(): """直接測試 Dify API""" # 從環境變數或配置檔案讀取 Dify 配置 base_url = "https://dify.theaken.com/v1" api_key = "app-SmB3TwVMcp5OyQviYeAoTden" # 正確的API Key print("=== 簡化 Dify API 測試 ===") print(f"Base URL: {base_url}") print(f"API Key: {api_key[:10]}...{api_key[-4:]}") # 準備測試請求 test_text = "保证烤箱设备之稳定性及延长其使用寿命" print(f"\n測試翻譯文本: {test_text}") # 構建請求 - 使用修正後的格式 query = f"""Task: Translate ONLY into English from Chinese. Rules: - Output translation text ONLY (no source text, no notes, no questions, no language-detection remarks). - Preserve original line breaks. - Do NOT wrap in quotes or code blocks. - Maintain original formatting and structure. {test_text.strip()}""" request_data = { 'inputs': {}, 'response_mode': 'blocking', 'user': f"user_1", 'query': query } headers = { 'Authorization': f'Bearer {api_key}', 'Content-Type': 'application/json' } try: print(f"\n📡 發送請求到 Dify API...") start_time = time.time() response = requests.post( f"{base_url}/chat-messages", json=request_data, headers=headers, timeout=30 ) end_time = time.time() response_time = int((end_time - start_time) * 1000) print(f"⏱️ 回應時間: {response_time}ms") print(f"📈 狀態碼: {response.status_code}") if response.status_code == 200: result = response.json() # 提取翻譯結果 translated_text = result.get('answer', '').strip() print(f"\n✅ 翻譯成功!") print(f"🔤 原文: {test_text}") print(f"🌍 譯文: {translated_text}") # 檢查使用統計 metadata = result.get('metadata', {}) usage = metadata.get('usage', {}) if usage: print(f"\n📊 使用統計:") print(f" 提示 Token: {usage.get('prompt_tokens', 'N/A')}") print(f" 回應 Token: {usage.get('completion_tokens', 'N/A')}") print(f" 總 Token: {usage.get('total_tokens', 'N/A')}") print(f" 總成本: ${usage.get('total_price', 'N/A')}") return { 'success': True, 'translated_text': translated_text, 'response_time_ms': response_time, 'usage': usage } else: print(f"❌ API 請求失敗:") print(f" 狀態碼: {response.status_code}") print(f" 回應: {response.text}") return {'success': False, 'error': f"HTTP {response.status_code}"} except requests.exceptions.RequestException as e: print(f"❌ 網路請求錯誤: {e}") return {'success': False, 'error': str(e)} except Exception as e: print(f"❌ 未知錯誤: {e}") return {'success': False, 'error': str(e)} if __name__ == "__main__": result = test_dify_direct() print(f"\n🏁 測試結果: {'成功' if result['success'] else '失敗'}") if not result['success']: print(f"錯誤詳情: {result['error']}")