Spaces:
Build error
Build error
File size: 4,668 Bytes
3195421 | 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 | from langchain_openai import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.memory import ConversationBufferMemory, SimpleMemory
import logging
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Global variables
llm = None
chat_memory = None
query_memory = None
prompt = None
def initialize_router_agent(llm_instance, chat_memory_instance):
global llm, chat_memory, prompt
llm = llm_instance
chat_memory = chat_memory_instance
system_prompt = """You are an intelligent query classification system for an e-commerce platform.
Your role is to accurately categorize incoming customer queries into one of two categories:
1. product_review:
- Queries about product features, specifications, or capabilities
- Questions about product prices and availability
- Requests for product reviews or comparisons
- Questions about product warranties or guarantees
- Inquiries about product shipping or delivery
- Questions about product compatibility or dimensions
- Requests for recommendations between products
2. generic:
- General customer service inquiries
- Account-related questions
- Technical support issues not related to specific products
- Website navigation help
- Payment or billing queries
- Return policy questions
- Company information requests
- Non-product related shipping questions
- Any other queries not directly related to specific products
INSTRUCTIONS:
- Analyze the input query carefully
- Respond ONLY with either "product_review" or "generic"
- Do not include any other text in your response
- If unsure, classify as "generic"
EXAMPLES:
User: "What are the features of the Samsung Galaxy S21?"
Assistant: product_review
User: "How much does the iPhone 13 Pro Max cost?"
Assistant: product_review
User: "Can you compare the Dell XPS 15 with the MacBook Pro?"
Assistant: product_review
User: "Is the Sony WH-1000XM4 headphone available in black?"
Assistant: product_review
User: "What's the battery life of the iPad Pro?"
Assistant: product_review
User: "I need help resetting my password"
Assistant: generic
User: "Where can I view my order history?"
Assistant: generic
User: "How do I update my shipping address?"
Assistant: generic
User: "What are your return policies?"
Assistant: generic
User: "I haven't received my refund yet"
Assistant: generic
User: "Do you ship internationally?"
Assistant: generic
User: "Can you recommend a good gaming laptop under $1000?"
Assistant: product_review
User: "What's the warranty period for electronics?"
Assistant: generic
User: "Is the Instant Pot dishwasher safe?"
Assistant: product_review
User: "How do I track my order?"
Assistant: generic
"""
prompt = ChatPromptTemplate.from_messages([
("system", system_prompt),
("human", "{input}")
])
logger.info("Router agent initialized successfully")
def classify_query(query):
try:
# Create chain with memory
chain = prompt | llm
# Add query to chat history before classification
if chat_memory and hasattr(chat_memory, 'chat_memory'):
chat_memory.chat_memory.add_user_message(query)
# Classify the query
response = chain.invoke({"input": query})
category = response.content.strip().lower()
# Validate category
if category not in ["product_review", "generic"]:
category = "generic" # Default fallback
# Add classification result to chat history
if chat_memory and hasattr(chat_memory, 'chat_memory'):
chat_memory.chat_memory.add_ai_message(f"Query classified as: {category}")
logger.info(f"Query: {query}")
logger.info(f"Classification: {category}")
print("**** in router agent****")
print("query :", query)
print("category :", category)
return category
except Exception as e:
print(f"Error in routing: {str(e)}")
return "generic" # Default fallback on error
def get_classification_history():
"""Retrieve classification history from memory"""
if chat_memory and hasattr(chat_memory, 'chat_memory'):
return chat_memory.chat_memory.messages
return []
def clear_context():
"""Clear all memory contexts"""
if chat_memory:
chat_memory.clear()
logger.info("Router agent context cleared") |