File size: 7,424 Bytes
9978ab4
 
b36d7c6
 
 
9978ab4
b36d7c6
 
9978ab4
 
b36d7c6
9978ab4
 
 
b36d7c6
9978ab4
 
b36d7c6
9978ab4
 
b36d7c6
 
9978ab4
b36d7c6
9978ab4
 
b36d7c6
9978ab4
b36d7c6
9978ab4
 
b36d7c6
 
9978ab4
b36d7c6
9978ab4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b36d7c6
9978ab4
b36d7c6
9978ab4
b36d7c6
9978ab4
 
b36d7c6
9978ab4
b36d7c6
9978ab4
 
b36d7c6
 
9978ab4
b36d7c6
 
9978ab4
b36d7c6
9978ab4
 
 
 
 
b36d7c6
9978ab4
 
b36d7c6
9978ab4
 
b36d7c6
9978ab4
b36d7c6
9978ab4
b36d7c6
9978ab4
 
 
b36d7c6
9978ab4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b36d7c6
9978ab4
b36d7c6
9978ab4
 
 
 
 
 
b36d7c6
9978ab4
b36d7c6
9978ab4
 
b36d7c6
9978ab4
b36d7c6
9978ab4
 
 
 
 
b36d7c6
 
 
 
9978ab4
b36d7c6
 
9978ab4
b36d7c6
9978ab4
b36d7c6
9978ab4
b36d7c6
 
9978ab4
 
b36d7c6
9978ab4
 
 
 
b36d7c6
9978ab4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b36d7c6
 
9978ab4
 
 
 
 
 
 
 
 
 
 
 
b36d7c6
9978ab4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b36d7c6
 
 
 
9978ab4
 
 
 
 
 
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import os
from langchain.chains import ConversationChain
from langchain.chat_models import ChatOpenAI
from langchain.memory import ConversationBufferMemory
from langchain.prompts import PromptTemplate
from langchain.sql_database import SQLDatabase
from langchain.chains import LLMChain
from langchain.utilities import SQLDatabase
from langchain_experimental.sql import SQLDatabaseChain
from sqlalchemy import create_engine

# --- Environment Setup ---
# Set your OpenAI API key (replace with your actual key)
os.environ["OPENAI_API_KEY"] = "YOUR_API_KEY"

# --- 1. Dialogue Context (Memory) ---
memory = ConversationBufferMemory(return_messages=True)

# --- 2. Router (Intent Classifier) ---
llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo-0613")  # Or another suitable model

router_template = """
Given the following conversation and a follow-up user input, determine if the user is asking a general question or trying to perform a specific task related to Viettel's services.

Conversation History:
{history}

User Input: {input}

Is the user input "open-domain" (general conversation) or "task-oriented" (specific service request)?
Answer with "open-domain" or "task-oriented".
"""
router_prompt = PromptTemplate(
    input_variables=["history", "input"], template=router_template
)
router_chain = LLMChain(llm=llm, prompt=router_prompt)

# --- 3. LLM (Open-Domain Dialogue Handler) ---
# Assuming you have set up your ChatOpenAI instance as 'llm'
conversation_chain = ConversationChain(llm=llm, memory=memory)

# --- 4. Service Selection (Task Classifier) ---
services = [
    "dịch vụ di động gói cước data của Viettel (data 3G/4G/5G)",
    "dịch vụ di động gói cước combo của Viettel (combo)",
    "dịch vụ di động gói cước thoại của Viettel (call)",
    "dịch vụ di động gói cước tin nhắn SMS của Viettel (SMS)",
    "dịch vụ di động gói cước ở nước ngoài ở Viettel (roaming)",
    "dịch vụ lắp đặt Internet cố định (internet)",
]
service_selection_template = """
Given the following conversation and a follow-up user input, classify the user's request into one of the following Viettel services:

{services}

Conversation History:
{history}

User Input: {input}

Which service best matches the user's request?
Answer with the name of the service.
"""
service_selection_prompt = PromptTemplate(
    input_variables=["services", "history", "input"],
    template=service_selection_template,
)
service_selection_chain = LLMChain(llm=llm, prompt=service_selection_prompt)

# --- 5. Dialogue State Tracking (Slot Filling) ---
slot_filling_template = """
You are an AI assistant helping users with Viettel's services.
Based on the conversation history and the selected service, extract the values for the following slots.
Return the extracted information in a JSON format. If a slot's value is not found, set it to null.

Selected Service: {service}
Required Slots: {slots}

Conversation History:
{history}

User Input: {input}

JSON Output:
"""
slot_filling_prompt = PromptTemplate(
    input_variables=["service", "slots", "history", "input"],
    template=slot_filling_template,
)
slot_filling_chain = LLMChain(llm=llm, prompt=slot_filling_prompt)

# --- Define Slots for Each Service ---
service_slots = {
    "data 3G/4G/5G": ["data_package", "duration"],  # Example slots
    "combo": ["data_amount", "call_minutes", "sms_count", "duration"],
    "call": ["call_minutes", "duration"],
    "SMS": ["sms_count", "duration"],
    "roaming": ["destination_country", "duration", "data_package"],
    "internet": ["internet_speed", "address"],
}

# --- 6. Database (Data Retrieval) ---
# Replace with your database connection details
engine = create_engine("mysql+mysqldb://user:password@host:port/database")
db = SQLDatabase(engine)
# db = SQLDatabase.from_uri("your_database_uri")

db_chain = SQLDatabaseChain.from_llm(llm, db, verbose=True)

# --- 8. Response Generation (System Response) ---
response_generation_template = """
You are an AI assistant helping users with Viettel's services.
You have completed the following steps:
1. Classified the user's intent.
2. Identified the relevant service (if task-oriented).
3. Extracted slot values (if task-oriented).
4. Retrieved information from the database (if applicable).

Now, generate a natural language response to the user based on the following information:

Conversation History:
{history}

User Input: {input}

Selected Service: {service}

Slot Values: {slot_values}

Database Results: {db_results}

Response:
"""
response_generation_prompt = PromptTemplate(
    input_variables=["history", "input", "service", "slot_values", "db_results"],
    template=response_generation_template,
)
response_generation_chain = LLMChain(llm=llm, prompt=response_generation_prompt)

# --- Main Pipeline Function ---
def process_user_input(user_input):
    # 1. Add input to memory (Dialogue Context)
    memory.chat_memory.add_user_message(user_input)

    # 2. Route (Intent Classification)
    intent = router_chain.run({"history": memory.load_memory_variables({})["history"], "input": user_input})

    if intent == "open-domain":
        # 3. Handle Open-Domain Conversation
        response = conversation_chain.predict(input=user_input)
        memory.chat_memory.add_ai_message(response)
    else:
        # 4. Service Selection
        selected_service = service_selection_chain.run(
            {
                "services": str(services),
                "history": memory.load_memory_variables({})["history"],
                "input": user_input,
            }
        )

        # 5. Slot Filling
        slots = service_slots.get(selected_service, [])
        slot_values_json = slot_filling_chain.run(
            {
                "service": selected_service,
                "slots": str(slots),
                "history": memory.load_memory_variables({})["history"],
                "input": user_input,
            }
        )

        # Convert JSON string to dictionary
        import json

        try:
            slot_values = json.loads(slot_values_json)
        except json.JSONDecodeError:
            slot_values = {}  # Handle cases where JSON decoding fails

        # 6. Database Interaction (if needed)
        db_results = "N/A"  # Default if no database interaction is needed
        if selected_service == "data 3G/4G/5G" and slot_values.get("data_package"):
            # Example: Query database for data package details
            try:
                db_results = db_chain.run(
                    f"What are the details of the {slot_values['data_package']} data package?"
                )
            except Exception as e:
                db_results = f"Error querying the database: {e}"

        # 8. Response Generation
        response = response_generation_chain.run(
            {
                "history": memory.load_memory_variables({})["history"],
                "input": user_input,
                "service": selected_service,
                "slot_values": slot_values,
                "db_results": db_results,
            }
        )
        memory.chat_memory.add_ai_message(response)

    return response

# --- Example Usage ---
print(process_user_input("Hello, how are you?"))
print(
    process_user_input(
        "I want to buy a data package for my phone, what is the best option of data package in 30 days"
    )
)