File size: 4,483 Bytes
eab2784
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import sys
import os
import traceback
from langchain_core.prompts import PromptTemplate

# --- IMPORT MODULES ---
from config import Config
from modules.dialog_manager.state import ChatState
from modules.dialog_manager.workflow import build_graph
from modules.dialog_manager.intent import IntentDetector

def handle_chitchat(llm, user_text):
    """
    Menangani percakapan ringan/basa-basi (Non-Transactional).
    """
    template = """
    Kamu adalah M2Proc, asisten pintar e-Procurement.
    User menyapa: "{text}"
    
    Tugas:
    1. Jawab dengan ramah, sopan, dan profesional.
    2. Tawarkan bantuan untuk mencari Barang, Jasa, atau Supplier.
    
    Jawab singkat saja.
    """
    prompt = PromptTemplate(input_variables=["text"], template=template)
    chain = prompt | llm
    
    try:
        response = chain.invoke({"text": user_text})
        return response.content.strip()
    except Exception as e:
        return "Halo! Ada yang bisa saya bantu untuk pencarian produk?"

def main():
    print("\n" + "="*60)
    print("   🤖 M2Proc - Conversational Recommender System   ")
    print("   Status: Production Mode (Real Data)             ")
    print("="*60)

    # 1. INITIALIZATION
    print("⏳ Sedang memuat modul dan database... (Mohon tunggu)")
    try:
        # Load Graph (DMS + RRE + UMS)
        app_graph = build_graph()
        
        # Load Helper Components
        intent_detector = IntentDetector()
        
        # Load LLM khusus untuk basa-basi (temperature agak tinggi biar luwes)
        llm_chitchat = Config.get_llm(temperature=0.6)
        
        print("✅ Sistem Siap! Silakan ketik 'exit' untuk berhenti.\n")
    except Exception as e:
        print(f"❌ Gagal memuat sistem: {e}")
        traceback.print_exc()
        return

    # 2. STATE INITIALIZATION
    # State ini akan terus dibawa selama percakapan berlangsung
    current_state = ChatState(
        user_text="",
        histories=[],              # Log percakapan
        intent="",
        topic_status="same",
        entities=[],
        collected_constraints={},  # Memori pencarian (Product, Price, dll)
        relaxed_query="",
        candidates=[],
        candidate_count=0,
        final_response="",
        done=False
    )

    # 3. MAIN CONVERSATION LOOP
    while True:
        try:
            # Input User
            user_input = input("\nUser : ").strip()
            
            # Cek Exit
            if user_input.lower() in ["exit", "quit", "stop", "keluar"]:
                print("Bot  : Terima kasih telah menggunakan M2Proc. Sampai jumpa!")
                break
            
            if not user_input:
                continue

            # Update State dengan Input Baru
            current_state["user_text"] = user_input
            
            # --- STEP A: DETEKSI INTENT ---
            intent = intent_detector.detect(current_state)
            current_state["intent"] = intent
            
            if intent == "basa_basi":
                # --- JALUR 1: BASA-BASI ---
                resp = handle_chitchat(llm_chitchat, user_input)
                print(f"Bot  : {resp}")
                
                # Update History (Manual untuk jalur ini)
                current_state["histories"].append(f"User: {user_input}")
                current_state["histories"].append(f"Bot: {resp}")
                
            else:
                # --- JALUR 2: SEARCH / TRANSAKSI ---
                # Masukkan input user ke history dulu agar Graph punya konteks lengkap
                current_state["histories"].append(f"User: {user_input}")
                
                # JALANKAN GRAPH (Topic -> Extract -> Relax -> RRE -> Generator)
                current_state = app_graph.invoke(current_state)
                
                # Ambil respon dari node terakhir (Generator)
                bot_resp = current_state.get("final_response", "Maaf, sistem tidak dapat memproses permintaan.")
                print(f"Bot  : {bot_resp}")
                
                # Note: History Bot sudah otomatis di-append oleh node generator di dalam graph

        except KeyboardInterrupt:
            print("\n\nBot  : Force Stop. Bye!")
            break
        except Exception as e:
            print(f"\n❌ Terjadi Kesalahan Runtime: {e}")
            traceback.print_exc()
            # Reset user text agar tidak looping error
            current_state["user_text"] = ""

if __name__ == "__main__":
    main()