File size: 12,488 Bytes
7c26280
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
"""Main flow controller for the barber booking system."""

import json
from typing import Dict, Any, Union, TypedDict
from langchain.schema import HumanMessage, SystemMessage
from langchain_core.messages import AIMessage
import os
from dotenv import load_dotenv
import google.generativeai as genai

from config.services import SERVICE_MAPPING
from config.prompts import BOOKING_FLOW
from config.validation import (
    validate_email, validate_phone, validate_name, format_phone,
    validate_booking_info, get_closest_service
)

# Load environment variables
load_dotenv()

# Initialize Gemini
def get_llm():
    api_key = os.getenv("GOOGLE_API_KEY")
    if not api_key:
        raise ValueError("GOOGLE_API_KEY environment variable is not set")
    
    try:
        genai.configure(api_key=api_key)
        model = genai.GenerativeModel('gemini-pro')
        return model
    except Exception as e:
        print(f"Error initializing Gemini: {str(e)}")
        raise

try:
    llm = get_llm()
except Exception as e:
    print(f"Error initializing LLM: {str(e)}")
    raise

# Type definition for booking state
class BookingState(TypedDict):
    current_node: str
    booking_info: Dict[str, Any]
    response: str
    messages: list

def handle_greeting(message: str, booking_info: Dict) -> Dict:
    """Handle the greeting state."""
    if validate_name(message):
        name = message.strip().title()
        return {
            "current_node": "ServiceSelection",
            "booking_info": {"name": name},
            "response": f"Hi {name}, welcome to our barbershop! Here are our services:"
        }
    return {
        "current_node": "Greeting",
        "booking_info": booking_info,
        "response": "Could you please tell me your name?"
    }

def handle_service_selection(message: str, booking_info: Dict) -> Dict:
    """Handle the service selection state."""
    message = message.lower().strip()
    
    # Check for cancellation
    if message in ["no", "cancel", "actually no", "nevermind"]:
        return {
            "current_node": "ServiceSelection",
            "booking_info": booking_info,
            "response": "No problem. Which service would you like to book? We offer haircut, beard trim, and full service."
        }
    
    # Check for multiple services
    if "and" in message or "," in message:
        return {
            "current_node": "ServiceSelection",
            "booking_info": booking_info,
            "response": "I see you're interested in multiple services. I recommend booking our full service which includes both haircut and beard trim. Would you like that?"
        }
    
    # Check for completion keywords
    if message in ["no", "nothing", "nothing else", "that's all"]:
        if "service" in booking_info:
            return {
                "current_node": "ShowTopSlots",
                "booking_info": booking_info,
                "response": "Great! Let me show you our available time slots."
            }
    
    # Try to match service
    service = get_closest_service(message)
    if service:
        booking_info["service"] = service
        return {
            "current_node": "ShowTopSlots",
            "booking_info": booking_info,
            "response": f"Perfect! Let me show you our available time slots for your {service}."
        }
    
    return {
        "current_node": "ServiceSelection",
        "booking_info": booking_info,
        "response": "Which service would you like to book? We offer haircut, beard trim, and full service."
    }

def handle_time_selection(message: str, booking_info: Dict) -> Dict:
    """Handle the time selection state."""
    time_slots = ["9:00 AM", "10:00 AM", "11:00 AM", "2:00 PM", "3:00 PM"]
    message = message.upper().strip()
    
    # Check for cancellation or change
    if message.lower() in ["cancel", "change", "different time", "other time"]:
        slots_text = "\n".join([f"- {slot}" for slot in time_slots])
        return {
            "current_node": "TimeSelection",
            "booking_info": booking_info,
            "response": f"Here are all our available times:\n{slots_text}\nWhich time works best for you?"
        }
    
    # Handle relative time references
    relative_times = {
        "MORNING": ["9:00 AM", "10:00 AM", "11:00 AM"],
        "AFTERNOON": ["2:00 PM", "3:00 PM"],
        "EARLY": ["9:00 AM", "10:00 AM"],
        "LATE": ["2:00 PM", "3:00 PM"],
        "FIRST": ["9:00 AM"],
        "LAST": ["3:00 PM"]
    }
    
    for keyword, options in relative_times.items():
        if keyword in message:
            slots_text = "\n".join([f"- {slot}" for slot in options])
            return {
                "current_node": "TimeSelection",
                "booking_info": booking_info,
                "response": f"Here are the {keyword.lower()} slots:\n{slots_text}\nWhich specific time would you prefer?"
            }
    
    # Normalize input
    message = message.replace(":", "").replace(" ", "")
    
    # Map variations to standard format
    time_map = {
        "9": "9:00 AM", "9AM": "9:00 AM", "900": "9:00 AM", "900AM": "9:00 AM", "NINE": "9:00 AM",
        "10": "10:00 AM", "10AM": "10:00 AM", "1000": "10:00 AM", "1000AM": "10:00 AM", "TEN": "10:00 AM",
        "11": "11:00 AM", "11AM": "11:00 AM", "1100": "11:00 AM", "1100AM": "11:00 AM", "ELEVEN": "11:00 AM",
        "2": "2:00 PM", "2PM": "2:00 PM", "200": "2:00 PM", "200PM": "2:00 PM", "TWO": "2:00 PM",
        "3": "3:00 PM", "3PM": "3:00 PM", "300": "3:00 PM", "300PM": "3:00 PM", "THREE": "3:00 PM"
    }
    
    selected_time = time_map.get(message)
    if selected_time and selected_time in time_slots:
        booking_info["time_slot"] = selected_time
        return {
            "current_node": "CustomerInfo",
            "booking_info": booking_info,
            "response": f"Perfect! I'll book you for {selected_time}. What's your email address?"
        }
    
    # If time not found, show all slots
    slots_text = "\n".join([f"- {slot}" for slot in time_slots])
    return {
        "current_node": "TimeSelection",
        "booking_info": booking_info,
        "response": f"I couldn't understand that time. Please select from these available times:\n{slots_text}"
    }

def handle_customer_info(message: str, booking_info: Dict) -> Dict:
    """Handle the customer information state."""
    if "email" not in booking_info:
        if validate_email(message):
            booking_info["email"] = message
            return {
                "current_node": "CustomerInfo",
                "booking_info": booking_info,
                "response": "Great! Now, what's your phone number for appointment reminders?"
            }
        return {
            "current_node": "CustomerInfo",
            "booking_info": booking_info,
            "response": "Please provide a valid email address (e.g., name@example.com)."
        }
    
    if "phone" not in booking_info:
        if validate_phone(message):
            booking_info["phone"] = format_phone(message)
            return {
                "current_node": "Confirmation",
                "booking_info": booking_info,
                "response": "Perfect! Let me confirm your booking details..."
            }
        return {
            "current_node": "CustomerInfo",
            "booking_info": booking_info,
            "response": "Please provide a valid phone number (e.g., 1234567890)."
        }
    
    return {
        "current_node": "CustomerInfo",
        "booking_info": booking_info,
        "response": "I need your contact information. What's your email address?"
    }

def handle_confirmation(message: str, booking_info: Dict) -> Dict:
    """Handle the confirmation state."""
    message = message.lower().strip()
    
    # Format booking summary
    service = booking_info.get("service", "")
    price = SERVICE_MAPPING[service]["price"] if service else 0
    duration = SERVICE_MAPPING[service]["duration"] if service else 0
    
    summary = f"""Here's your booking summary:
- Name: {booking_info.get('name', '')}
- Service: {service.title()} (${price}, {duration} min)
- Time: {booking_info.get('time_slot', '')}
- Email: {booking_info.get('email', '')}
- Phone: {booking_info.get('phone', '')}

Is this correct? Please confirm (yes/no)."""
    
    if message in ["yes", "correct", "confirm", "y"]:
        return {
            "current_node": "BookingComplete",
            "booking_info": {**booking_info, "confirmation": True},
            "response": "Great! Your appointment has been confirmed. We'll send you a confirmation email shortly."
        }
    
    if message in ["no", "wrong", "incorrect", "n"]:
        return {
            "current_node": "ServiceSelection",
            "booking_info": {"name": booking_info.get("name", "")},
            "response": "I understand. Let's start over with the service selection."
        }
    
    return {
        "current_node": "Confirmation",
        "booking_info": booking_info,
        "response": summary
    }

def process_node(state: Dict) -> Dict:
    """Process the current node in the booking flow."""
    try:
        current_node = state["current_node"]
        booking_info = state.get("booking_info", {})
        messages = state.get("messages", [])
        
        # Get the last user message
        last_message = ""
        if messages:
            last_msg = messages[-1]
            if isinstance(last_msg, dict):
                last_message = last_msg.get("content", "")
            elif isinstance(last_msg, (HumanMessage, AIMessage, SystemMessage)):
                last_message = last_msg.content
            else:
                last_message = str(last_msg)
        
        # Handle each state
        if current_node == "Greeting":
            new_state = handle_greeting(last_message, booking_info)
        elif current_node == "ServiceSelection":
            new_state = handle_service_selection(last_message, booking_info)
        elif current_node == "ShowTopSlots":
            time_slots = ["9:00 AM", "10:00 AM", "11:00 AM", "2:00 PM", "3:00 PM"]
            slots_text = "\n".join([f"- {slot}" for slot in time_slots])
            new_state = {
                "current_node": "TimeSelection",
                "booking_info": booking_info,
                "response": f"Here are our available time slots:\n{slots_text}\n\nWhich time works best for you?"
            }
        elif current_node == "TimeSelection":
            new_state = handle_time_selection(last_message, booking_info)
        elif current_node == "CustomerInfo":
            new_state = handle_customer_info(last_message, booking_info)
        elif current_node == "Confirmation":
            new_state = handle_confirmation(last_message, booking_info)
        elif current_node == "BookingComplete":
            new_state = {
                "current_node": "Farewell",
                "booking_info": booking_info,
                "response": "Thank you for booking with us! We look forward to seeing you soon."
            }
        else:
            new_state = {
                "current_node": "Greeting",
                "booking_info": {},
                "response": "Hello! Welcome to our barber shop. Could you please tell me your name?"
            }
        
        return {**new_state, "messages": messages}
    
    except Exception as e:
        print(f"Error in process_node: {str(e)}")
        return {
            "current_node": state.get("current_node", "Greeting"),
            "booking_info": state.get("booking_info", {}),
            "response": "I encountered an error. Could you please rephrase that?",
            "messages": messages
        }

def run_booking_flow(user_input: str, state: Dict[str, Any] = None) -> Dict[str, Any]:
    """Run the booking workflow."""
    if state is None:
        state = {
            "current_node": "Greeting",
            "booking_info": {},
            "response": "",
            "messages": []
        }
    
    try:
        # Process the current node
        new_state = process_node(state)
        return new_state
    
    except Exception as e:
        print(f"Error in run_booking_flow: {str(e)}")
        return {
            "current_node": "Greeting",
            "booking_info": {},
            "response": "I encountered an error. Let's start over.",
            "messages": []
        }

# Export necessary components
__all__ = ['run_booking_flow', 'SERVICE_MAPPING']