File size: 4,307 Bytes
17131ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
from langchain_core.prompts import PromptTemplate
from config import Config

class ResponseGenerator:
    def __init__(self):
        self.llm = Config.get_llm(temperature=0.4)

    def generate(self, state: dict) -> dict:
        count = state.get("candidate_count", 0)
        candidates = state.get("candidates", [])
        constraints = state.get("collected_constraints", {})
        
        # Cek apakah constraints benar-benar kosong atau isinya null semua
        is_constraints_empty = not constraints or all(v is None for v in constraints.values())
        
        # --- KONDISI 0: CONSTRAINT KOSONG (User mau cari, tapi belum bilang apa) ---
        if is_constraints_empty:
            msg = "Tentu, saya bisa bantu carikan Supplier atau Produk. Barang atau jasa apa spesifiknya yang sedang Anda butuhkan?"
            state["final_response"] = msg
            state["histories"].append(f"Bot: {msg}")
            return state

        # --- KONDISI 1: TIDAK ADA HASIL (Tapi user sudah kasih keyword) ---
        if count == 0:
            # Format constraints jadi string yang enak dibaca user
            criteria_str = ", ".join([f"{k}: {v}" for k, v in constraints.items() if v])
            
            msg = (f"Mohon maaf, saya belum menemukan produk yang pas untuk kriteria [{criteria_str}]. "
                   "Mungkin bisa dicoba dengan kata kunci yang lebih umum?")
            state["final_response"] = msg
            state["histories"].append(f"Bot: {msg}")
            return state

        # --- KONDISI 2: HASIL BANYAK (> 10) -> NAVIGATION BY ASKING ---
        if count > 10:
            locs = set()
            for c in candidates[:15]: # Ambil sampel agak banyak
                val = c.get('supplier_detail', {}).get('kota')
                if val: locs.add(val)
            
            sample_locs = ", ".join(list(locs)[:3])
            
            template = """
            Kamu adalah asisten e-Procurement.
            Ditemukan {count} produk untuk kriteria: {constraints}.
            
            Dominasi lokasi data: {locs} dll.
            
            Tugas:
            Infokan jumlah temuan, lalu ajukan 1 PERTANYAAN sopan untuk mempersempit pencarian (misal tanya preferensi Harga atau Lokasi).
            JANGAN tampilkan list produk.
            """
            
            prompt = PromptTemplate(input_variables=["count", "constraints", "locs"], template=template)
            chain = prompt | self.llm
            
            response = chain.invoke({
                "count": count, 
                "constraints": json.dumps(constraints, ensure_ascii=False),
                "locs": sample_locs
            })
            state["final_response"] = response.content.strip()

        # --- KONDISI 3: HASIL SPESIFIK (<= 10) -> RECOMMENDATION ---
        else:
            items_str = ""
            for idx, item in enumerate(candidates):
                title = item.get('title', 'Produk Tanpa Nama')
                price = item.get('price', 0)
                try:
                    price_fmt = f"Rp {int(price):,}".replace(",", ".")
                except:
                    price_fmt = str(price)
                    
                toko = item.get('supplier_detail', {}).get('nama_toko', 'Unknown')
                kota = item.get('supplier_detail', {}).get('kota', '')
                
                items_str += f"{idx+1}. {title}\n   Harga: {price_fmt}\n   Penjual: {toko} ({kota})\n\n"
            
            template = """
            Kamu adalah asisten e-Procurement.
            Berikut adalah {count} produk rekomendasi terbaik.
            
            Data Produk:
            {items}
            
            Tugas:
            1. Berikan pengantar singkat.
            2. Tampilkan daftar di atas.
            3. Tawarkan bantuan lanjutan (Detail spek / Kontak Supplier).
            """
            
            prompt = PromptTemplate(input_variables=["count", "items"], template=template)
            chain = prompt | self.llm
            
            response = chain.invoke({"count": count, "items": items_str})
            state["final_response"] = response.content.strip()
            state["done"] = True

        state["histories"].append(f"Bot: {state['final_response']}")
        return state