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" ) )