Update pipeline.py
Browse files- 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
|
|
|
7 |
|
8 |
-
# ---
|
|
|
|
|
9 |
|
10 |
-
# 1. Dialogue Context (Memory)
|
11 |
-
memory = ConversationBufferMemory()
|
12 |
|
13 |
-
# 2.
|
14 |
-
llm = ChatOpenAI(temperature=0,
|
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 |
-
|
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 |
-
|
|
|
32 |
|
33 |
-
User: {
|
34 |
|
35 |
-
|
|
|
36 |
"""
|
37 |
router_prompt = PromptTemplate(
|
38 |
-
input_variables=["
|
39 |
)
|
40 |
-
|
41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
service_selection_template = """
|
43 |
-
|
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 |
-
|
51 |
|
52 |
-
|
|
|
53 |
|
54 |
-
User: {
|
55 |
|
56 |
-
|
|
|
57 |
"""
|
58 |
service_selection_prompt = PromptTemplate(
|
59 |
-
input_variables=["
|
60 |
template=service_selection_template,
|
61 |
)
|
|
|
62 |
|
63 |
-
# Dialogue State Tracking
|
64 |
-
|
65 |
-
You are
|
|
|
|
|
66 |
|
67 |
-
Service: {service}
|
68 |
-
Slots: {slots}
|
69 |
|
70 |
-
|
71 |
-
|
72 |
|
73 |
-
{
|
74 |
|
75 |
-
|
76 |
-
|
77 |
-
Extracted Information (JSON):
|
78 |
"""
|
79 |
-
|
80 |
-
input_variables=["service", "slots", "
|
81 |
-
template=
|
82 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
83 |
|
84 |
-
# Response Generation
|
85 |
response_generation_template = """
|
86 |
-
You are
|
|
|
|
|
|
|
|
|
|
|
87 |
|
88 |
-
|
89 |
-
{chat_history}
|
90 |
|
91 |
-
|
|
|
92 |
|
93 |
-
{
|
94 |
|
95 |
-
{
|
|
|
|
|
|
|
|
|
96 |
|
97 |
Response:
|
98 |
"""
|
99 |
response_generation_prompt = PromptTemplate(
|
100 |
-
input_variables=["
|
101 |
template=response_generation_template,
|
102 |
)
|
|
|
103 |
|
104 |
-
# ---
|
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
|
129 |
memory.chat_memory.add_user_message(user_input)
|
130 |
|
131 |
-
# 2. Route
|
132 |
-
|
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
|
140 |
-
# 3. Handle
|
141 |
-
|
142 |
-
response
|
143 |
else:
|
144 |
-
# 4.
|
145 |
-
|
146 |
-
{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
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 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
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 |
+
)
|
|