File size: 6,118 Bytes
89879a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
測試貓砂查詢功能 - 驗證修復後的智能路由和商品查詢
"""

import sys
import os

# 添加專案根目錄到 Python 路徑
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from backend.services.message_router import MessageRouter
from backend.services.pydantic_ai_service import ProductQueryService
from backend.services.enhanced_product_service import EnhancedProductService
from backend.database.connection import test_database_connection

def test_database_connection_first():
    """首先測試資料庫連接"""
    print("🗄️ 測試資料庫連接...")
    
    if test_database_connection():
        print("✅ 資料庫連接正常")
        return True
    else:
        print("❌ 資料庫連接失敗")
        return False

def test_product_search_directly():
    """直接測試商品搜尋功能"""
    print("\n🔍 直接測試商品搜尋...")
    
    try:
        service = EnhancedProductService()
        
        # 測試不同的搜尋關鍵字
        test_keywords = ["貓砂", "貓", "寵物", "cat", "litter"]
        
        for keyword in test_keywords:
            print(f"\n--- 搜尋關鍵字: '{keyword}' ---")
            
            # 測試推薦功能
            result = service.get_product_recommendations(keyword, limit=3)
            print(f"推薦查詢 - 成功: {result.success}, 數量: {result.count}")
            
            if result.success and result.data:
                for i, product in enumerate(result.data, 1):
                    print(f"  {i}. {product.get('product_name', 'N/A')} (庫存: {product.get('current_stock', 0)})")
            elif result.error:
                print(f"  錯誤: {result.error}")
            
            # 測試進階搜尋
            result2 = service.search_products_advanced(keyword, include_stock_info=True, limit=3)
            print(f"進階搜尋 - 成功: {result2.success}, 數量: {result2.count}")
            
            if result2.success and result2.data:
                for i, product in enumerate(result2.data, 1):
                    print(f"  {i}. {product.get('product_name', 'N/A')} (庫存: {product.get('current_stock', 0)})")
            elif result2.error:
                print(f"  錯誤: {result2.error}")
                
    except Exception as e:
        print(f"❌ 直接搜尋測試錯誤: {str(e)}")

def test_pydantic_ai_intent():
    """測試 Pydantic AI 意圖識別"""
    print("\n🤖 測試 Pydantic AI 意圖識別...")
    
    try:
        service = ProductQueryService()
        
        if not service.is_available():
            print("❌ Pydantic AI 服務不可用")
            return
        
        test_messages = [
            "你好, 請問有沒有貓砂相關產品?",
            "是否有推薦貓砂?",
            "有什麼寵物用品?",
            "今天天氣如何?"  # 非商品查詢
        ]
        
        for message in test_messages:
            print(f"\n--- 測試訊息: '{message}' ---")
            intent = service.analyze_query_intent(message)
            print(f"商品查詢: {intent['is_product_query']}")
            print(f"推薦查詢: {intent['is_recommendation']}")
            print(f"庫存查詢: {intent['is_inventory_check']}")
            print(f"信心度: {intent['confidence']:.2f}")
            print(f"意圖: {intent['intent']}")
            
    except Exception as e:
        print(f"❌ Pydantic AI 測試錯誤: {str(e)}")

def test_message_router():
    """測試修復後的訊息路由器"""
    print("\n🔄 測試修復後的訊息路由器...")
    
    try:
        router = MessageRouter()
        
        test_messages = [
            "你好, 請問有沒有貓砂相關產品?",
            "是否有推薦貓砂?",
            "有什麼狗糧推薦?",
            "查詢寵物用品庫存",
            "你好!今天天氣如何?",  # 應該路由到聊天模式
            "/help",  # 應該顯示幫助
        ]
        
        for message in test_messages:
            print(f"\n--- 路由測試: '{message}' ---")
            try:
                result = router.route_message(message, "test_user")
                print(f"模式: {result.get('mode', 'unknown')}")
                print(f"成功: {result.get('success', False)}")
                
                # 顯示回應的前100個字符
                response_text = result.get('text', 'No response')
                if len(response_text) > 100:
                    print(f"回應: {response_text[:100]}...")
                else:
                    print(f"回應: {response_text}")
                
                if result.get('products_found'):
                    print(f"找到商品數量: {result['products_found']}")
                    
            except Exception as e:
                print(f"❌ 路由錯誤: {str(e)}")
        
        # 顯示路由統計
        print(f"\n📊 路由統計:")
        stats = router.get_route_statistics()
        for mode, count in stats['stats'].items():
            if count > 0:
                print(f"  {mode}: {count}")
                
    except Exception as e:
        print(f"❌ 路由器測試錯誤: {str(e)}")

def main():
    """主測試函數"""
    print("🚀 開始貓砂查詢功能測試\n")
    
    # 1. 測試資料庫連接
    if not test_database_connection_first():
        print("❌ 資料庫連接失敗,無法繼續測試")
        return
    
    # 2. 直接測試商品搜尋
    test_product_search_directly()
    
    # 3. 測試 Pydantic AI 意圖識別
    test_pydantic_ai_intent()
    
    # 4. 測試訊息路由器
    test_message_router()
    
    print("\n✅ 測試完成!")
    print("\n💡 如果商品查詢仍然沒有結果,可能的原因:")
    print("   1. 資料庫中確實沒有貓砂相關商品")
    print("   2. 商品名稱不包含 '貓砂'、'貓'、'寵物' 等關鍵字")
    print("   3. 商品被標記為已刪除 (is_deleted=True)")
    print("   4. 需要檢查實際的商品資料內容")

if __name__ == "__main__":
    main()