vinhnq29 commited on
Commit
9978ab4
1 Parent(s): b36d7c6

Update pipeline.py

Browse files
Files changed (1) hide show
  1. pipeline.py +155 -154
pipeline.py CHANGED
@@ -1,211 +1,212 @@
 
 
1
  from langchain.chat_models import ChatOpenAI
2
  from langchain.memory import ConversationBufferMemory
3
  from langchain.prompts import PromptTemplate
 
4
  from langchain.chains import LLMChain
5
  from langchain.utilities import SQLDatabase
6
- from sqlalchemy import create_engine # Import create_engine
 
7
 
8
- # --- Initialize Core Components ---
 
 
9
 
10
- # 1. Dialogue Context (Memory)
11
- memory = ConversationBufferMemory()
12
 
13
- # 2. LLM (for routing, service selection, state tracking, and response generation)
14
- llm = ChatOpenAI(temperature=0, model_name="gpt-3.5-turbo") # Or another suitable model
15
 
16
- # 3. Database (using SQLite in-memory for demonstration)
17
- engine = create_engine("sqlite:///:memory:") # Create an in-memory SQLite engine
18
- db = SQLDatabase(engine) # Pass the engine to SQLDatabase
19
-
20
- # --- Define Prompts ---
21
-
22
- # Router Prompt
23
  router_template = """
24
- You are a helpful assistant that classifies user input into two categories:
25
-
26
- 1. open-domain: General conversation, chit-chat, or questions not related to a specific task.
27
- 2. task-oriented: The user wants to perform a specific action or get information related to a predefined service.
28
-
29
- Based on the dialogue history, classify the latest user input:
30
 
31
- {chat_history}
 
32
 
33
- User: {user_input}
34
 
35
- Classification:
 
36
  """
37
  router_prompt = PromptTemplate(
38
- input_variables=["chat_history", "user_input"], template=router_template
39
  )
40
-
41
- # Service Selection Prompt
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  service_selection_template = """
43
- You are a helpful assistant that classifies user input into one of the following predefined services:
44
-
45
- Services:
46
- - book_flight: For booking flight tickets.
47
- - check_order_status: For checking the status of an order.
48
- - find_restaurants: For finding restaurants based on criteria.
49
 
50
- Based on the dialogue history, which service best matches the user's intent?
51
 
52
- {chat_history}
 
53
 
54
- User: {user_input}
55
 
56
- Selected Service:
 
57
  """
58
  service_selection_prompt = PromptTemplate(
59
- input_variables=["chat_history", "user_input"],
60
  template=service_selection_template,
61
  )
 
62
 
63
- # Dialogue State Tracking Prompt
64
- state_tracking_template = """
65
- You are a helpful assistant that extracts information from user input to fill in the slots for a specific service.
 
 
66
 
67
- Service: {service}
68
- Slots: {slots}
69
 
70
- Based on the dialogue history, extract the values for each slot from the conversation.
71
- Return the output in JSON format. If a slot is not filled, use null as the value.
72
 
73
- {chat_history}
74
 
75
- User: {user_input}
76
-
77
- Extracted Information (JSON):
78
  """
79
- state_tracking_prompt = PromptTemplate(
80
- input_variables=["service", "slots", "chat_history", "user_input"],
81
- template=state_tracking_template,
82
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
- # Response Generation Prompt
85
  response_generation_template = """
86
- You are a helpful assistant that generates natural language responses to the user.
 
 
 
 
 
87
 
88
- Dialogue History:
89
- {chat_history}
90
 
91
- User: {user_input}
 
92
 
93
- {slot_info}
94
 
95
- {db_results}
 
 
 
 
96
 
97
  Response:
98
  """
99
  response_generation_prompt = PromptTemplate(
100
- input_variables=["chat_history", "user_input", "slot_info", "db_results"],
101
  template=response_generation_template,
102
  )
 
103
 
104
- # --- Define Chains ---
105
-
106
- router_chain = LLMChain(llm=llm, prompt=router_prompt, output_key="classification")
107
- service_selection_chain = LLMChain(
108
- llm=llm, prompt=service_selection_prompt, output_key="service"
109
- )
110
- state_tracking_chain = LLMChain(
111
- llm=llm, prompt=state_tracking_prompt, output_key="slot_json"
112
- )
113
- response_generation_chain = LLMChain(
114
- llm=llm, prompt=response_generation_prompt, output_key="response"
115
- )
116
-
117
- # --- Define Service Slots ---
118
- # (In a real application, this would likely be loaded from a configuration file or database)
119
- service_slots = {
120
- "book_flight": ["destination", "departure_date", "num_passengers"],
121
- "check_order_status": ["order_id"],
122
- "find_restaurants": ["cuisine", "location", "price_range"],
123
- }
124
-
125
- # --- Main Dialogue Loop ---
126
-
127
  def process_user_input(user_input):
128
- # 1. Add user input to memory
129
  memory.chat_memory.add_user_message(user_input)
130
 
131
- # 2. Route the input
132
- router_output = router_chain(
133
- {"chat_history": memory.load_memory_variables({}), "user_input": user_input}
134
- )
135
- classification = router_output["classification"].strip()
136
-
137
- print(f"Router Classification: {classification}")
138
 
139
- if classification == "open-domain":
140
- # 3. Handle open-domain conversation
141
- llm_response = llm(memory.load_memory_variables({})["history"])
142
- response = llm_response.content
143
  else:
144
- # 4. Select the service
145
- service_output = service_selection_chain(
146
- {"chat_history": memory.load_memory_variables({}), "user_input": user_input}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  )
148
- service = service_output["service"].strip()
149
-
150
- print(f"Selected Service: {service}")
151
-
152
- if service not in service_slots:
153
- response = "I'm sorry, I cannot understand that service request yet. We currently support booking flights, checking order status and finding restaurants only."
154
- else:
155
- # 5. Track the dialogue state (slot filling)
156
- slots = service_slots[service]
157
- state_output = state_tracking_chain(
158
- {
159
- "service": service,
160
- "slots": ", ".join(slots),
161
- "chat_history": memory.load_memory_variables({}),
162
- "user_input": user_input,
163
- }
164
- )
165
- slot_json_str = state_output["slot_json"].strip()
166
-
167
- print(f"Slot Filling Output (JSON): {slot_json_str}")
168
 
 
 
 
 
 
 
 
 
 
 
 
 
169
  try:
170
- import json
171
- slot_values = json.loads(slot_json_str)
172
- except json.JSONDecodeError:
173
- slot_values = {} # Handle cases where JSON decoding fails
174
- response = "I'm sorry, there seems to be a problem understanding your request details."
175
-
176
- # (Optional) 6. Database interaction (based on service and filled slots)
177
- db_results = "" # Initialize db_results as an empty string
178
- if service == "check_order_status" and "order_id" in slot_values:
179
- try:
180
- order_id = slot_values["order_id"]
181
- # Basic query without table information
182
- db_results = db.run(f"SELECT * FROM orders WHERE order_id = '{order_id}'")
183
- db_results = f"Database Results: {db_results}"
184
- except Exception as e:
185
- print(f"Error during database query: {e}")
186
- db_results = ""
187
-
188
- # 7. Generate the response
189
- response_output = response_generation_chain(
190
- {
191
- "chat_history": memory.load_memory_variables({}),
192
- "user_input": user_input,
193
- "slot_info": f"Slots: {slot_json_str}",
194
- "db_results": db_results,
195
- }
196
- )
197
- response = response_output["response"]
198
-
199
- # 8. Add the system response to memory
200
- memory.chat_memory.add_ai_message(response)
201
 
202
  return response
203
 
204
  # --- Example Usage ---
205
-
206
- while True:
207
- user_input = input("You: ")
208
- if user_input.lower() == "exit":
209
- break
210
- response = process_user_input(user_input)
211
- print(f"AI: {response}")
 
1
+ import os
2
+ from langchain.chains import ConversationChain
3
  from langchain.chat_models import ChatOpenAI
4
  from langchain.memory import ConversationBufferMemory
5
  from langchain.prompts import PromptTemplate
6
+ from langchain.sql_database import SQLDatabase
7
  from langchain.chains import LLMChain
8
  from langchain.utilities import SQLDatabase
9
+ from langchain_experimental.sql import SQLDatabaseChain
10
+ from sqlalchemy import create_engine
11
 
12
+ # --- Environment Setup ---
13
+ # Set your OpenAI API key (replace with your actual key)
14
+ os.environ["OPENAI_API_KEY"] = "YOUR_API_KEY"
15
 
16
+ # --- 1. Dialogue Context (Memory) ---
17
+ memory = ConversationBufferMemory(return_messages=True)
18
 
19
+ # --- 2. Router (Intent Classifier) ---
20
+ llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo-0613") # Or another suitable model
21
 
 
 
 
 
 
 
 
22
  router_template = """
23
+ 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.
 
 
 
 
 
24
 
25
+ Conversation History:
26
+ {history}
27
 
28
+ User Input: {input}
29
 
30
+ Is the user input "open-domain" (general conversation) or "task-oriented" (specific service request)?
31
+ Answer with "open-domain" or "task-oriented".
32
  """
33
  router_prompt = PromptTemplate(
34
+ input_variables=["history", "input"], template=router_template
35
  )
36
+ router_chain = LLMChain(llm=llm, prompt=router_prompt)
37
+
38
+ # --- 3. LLM (Open-Domain Dialogue Handler) ---
39
+ # Assuming you have set up your ChatOpenAI instance as 'llm'
40
+ conversation_chain = ConversationChain(llm=llm, memory=memory)
41
+
42
+ # --- 4. Service Selection (Task Classifier) ---
43
+ services = [
44
+ "dịch vụ di động gói cước data của Viettel (data 3G/4G/5G)",
45
+ "dịch vụ di động gói cước combo của Viettel (combo)",
46
+ "dịch vụ di động gói cước thoại của Viettel (call)",
47
+ "dịch vụ di động gói cước tin nhắn SMS của Viettel (SMS)",
48
+ "dịch vụ di động gói cước ở nước ngoài ở Viettel (roaming)",
49
+ "dịch vụ lắp đặt Internet cố định (internet)",
50
+ ]
51
  service_selection_template = """
52
+ Given the following conversation and a follow-up user input, classify the user's request into one of the following Viettel services:
 
 
 
 
 
53
 
54
+ {services}
55
 
56
+ Conversation History:
57
+ {history}
58
 
59
+ User Input: {input}
60
 
61
+ Which service best matches the user's request?
62
+ Answer with the name of the service.
63
  """
64
  service_selection_prompt = PromptTemplate(
65
+ input_variables=["services", "history", "input"],
66
  template=service_selection_template,
67
  )
68
+ service_selection_chain = LLMChain(llm=llm, prompt=service_selection_prompt)
69
 
70
+ # --- 5. Dialogue State Tracking (Slot Filling) ---
71
+ slot_filling_template = """
72
+ You are an AI assistant helping users with Viettel's services.
73
+ Based on the conversation history and the selected service, extract the values for the following slots.
74
+ Return the extracted information in a JSON format. If a slot's value is not found, set it to null.
75
 
76
+ Selected Service: {service}
77
+ Required Slots: {slots}
78
 
79
+ Conversation History:
80
+ {history}
81
 
82
+ User Input: {input}
83
 
84
+ JSON Output:
 
 
85
  """
86
+ slot_filling_prompt = PromptTemplate(
87
+ input_variables=["service", "slots", "history", "input"],
88
+ template=slot_filling_template,
89
  )
90
+ slot_filling_chain = LLMChain(llm=llm, prompt=slot_filling_prompt)
91
+
92
+ # --- Define Slots for Each Service ---
93
+ service_slots = {
94
+ "data 3G/4G/5G": ["data_package", "duration"], # Example slots
95
+ "combo": ["data_amount", "call_minutes", "sms_count", "duration"],
96
+ "call": ["call_minutes", "duration"],
97
+ "SMS": ["sms_count", "duration"],
98
+ "roaming": ["destination_country", "duration", "data_package"],
99
+ "internet": ["internet_speed", "address"],
100
+ }
101
+
102
+ # --- 6. Database (Data Retrieval) ---
103
+ # Replace with your database connection details
104
+ engine = create_engine("mysql+mysqldb://user:password@host:port/database")
105
+ db = SQLDatabase(engine)
106
+ # db = SQLDatabase.from_uri("your_database_uri")
107
+
108
+ db_chain = SQLDatabaseChain.from_llm(llm, db, verbose=True)
109
 
110
+ # --- 8. Response Generation (System Response) ---
111
  response_generation_template = """
112
+ You are an AI assistant helping users with Viettel's services.
113
+ You have completed the following steps:
114
+ 1. Classified the user's intent.
115
+ 2. Identified the relevant service (if task-oriented).
116
+ 3. Extracted slot values (if task-oriented).
117
+ 4. Retrieved information from the database (if applicable).
118
 
119
+ Now, generate a natural language response to the user based on the following information:
 
120
 
121
+ Conversation History:
122
+ {history}
123
 
124
+ User Input: {input}
125
 
126
+ Selected Service: {service}
127
+
128
+ Slot Values: {slot_values}
129
+
130
+ Database Results: {db_results}
131
 
132
  Response:
133
  """
134
  response_generation_prompt = PromptTemplate(
135
+ input_variables=["history", "input", "service", "slot_values", "db_results"],
136
  template=response_generation_template,
137
  )
138
+ response_generation_chain = LLMChain(llm=llm, prompt=response_generation_prompt)
139
 
140
+ # --- Main Pipeline Function ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  def process_user_input(user_input):
142
+ # 1. Add input to memory (Dialogue Context)
143
  memory.chat_memory.add_user_message(user_input)
144
 
145
+ # 2. Route (Intent Classification)
146
+ intent = router_chain.run({"history": memory.load_memory_variables({})["history"], "input": user_input})
 
 
 
 
 
147
 
148
+ if intent == "open-domain":
149
+ # 3. Handle Open-Domain Conversation
150
+ response = conversation_chain.predict(input=user_input)
151
+ memory.chat_memory.add_ai_message(response)
152
  else:
153
+ # 4. Service Selection
154
+ selected_service = service_selection_chain.run(
155
+ {
156
+ "services": str(services),
157
+ "history": memory.load_memory_variables({})["history"],
158
+ "input": user_input,
159
+ }
160
+ )
161
+
162
+ # 5. Slot Filling
163
+ slots = service_slots.get(selected_service, [])
164
+ slot_values_json = slot_filling_chain.run(
165
+ {
166
+ "service": selected_service,
167
+ "slots": str(slots),
168
+ "history": memory.load_memory_variables({})["history"],
169
+ "input": user_input,
170
+ }
171
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
 
173
+ # Convert JSON string to dictionary
174
+ import json
175
+
176
+ try:
177
+ slot_values = json.loads(slot_values_json)
178
+ except json.JSONDecodeError:
179
+ slot_values = {} # Handle cases where JSON decoding fails
180
+
181
+ # 6. Database Interaction (if needed)
182
+ db_results = "N/A" # Default if no database interaction is needed
183
+ if selected_service == "data 3G/4G/5G" and slot_values.get("data_package"):
184
+ # Example: Query database for data package details
185
  try:
186
+ db_results = db_chain.run(
187
+ f"What are the details of the {slot_values['data_package']} data package?"
188
+ )
189
+ except Exception as e:
190
+ db_results = f"Error querying the database: {e}"
191
+
192
+ # 8. Response Generation
193
+ response = response_generation_chain.run(
194
+ {
195
+ "history": memory.load_memory_variables({})["history"],
196
+ "input": user_input,
197
+ "service": selected_service,
198
+ "slot_values": slot_values,
199
+ "db_results": db_results,
200
+ }
201
+ )
202
+ memory.chat_memory.add_ai_message(response)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
 
204
  return response
205
 
206
  # --- Example Usage ---
207
+ print(process_user_input("Hello, how are you?"))
208
+ print(
209
+ process_user_input(
210
+ "I want to buy a data package for my phone, what is the best option of data package in 30 days"
211
+ )
212
+ )