bindhu82 commited on
Commit
c0ed7e3
Β·
verified Β·
1 Parent(s): 65b8b67

Upload 6 files

Browse files
Files changed (6) hide show
  1. AgenticAI.ipynb +0 -0
  2. Dockerfile (2) +20 -0
  3. config.json +4 -0
  4. orders.db +0 -0
  5. requirements.txt +9 -0
  6. streamlit_app.py +951 -0
AgenticAI.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
Dockerfile (2) ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.13.5-slim
2
+
3
+ WORKDIR /app
4
+
5
+ RUN apt-get update && apt-get install -y \
6
+ build-essential \
7
+ curl \
8
+ git \
9
+ && rm -rf /var/lib/apt/lists/*
10
+
11
+ COPY requirements.txt ./
12
+ COPY src/ ./src/
13
+
14
+ RUN pip3 install -r requirements.txt
15
+
16
+ EXPOSE 8501
17
+
18
+ HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health
19
+
20
+ ENTRYPOINT ["streamlit", "run", "src/streamlit_app.py", "--server.port=8501", "--server.address=0.0.0.0"]
config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "API_KEY": "gl-U2FsdGVkX1/1NOWUI4wyEwezY57/W8ziUET7a0uXSkzjgGc0HqsBBnbguUykCrZQ",
3
+ "OPENAI_API_BASE": "https://aibe.mygreatlearning.com/openai/v1"
4
+ }
orders.db ADDED
Binary file (36.9 kB). View file
 
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ altair
2
+ pandas
3
+ streamlit
4
+ langgraph
5
+ langchain
6
+ langchain-openai
7
+ langchain-core
8
+ langchain-community
9
+ grandalf
streamlit_app.py ADDED
@@ -0,0 +1,951 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Kartify Order Query ChatBot - Multi-Agent System with SQL Agent
3
+ Uses SQLite database instead of mock data
4
+ """
5
+
6
+ # ============================================================================
7
+ # IMPORTS
8
+ # ============================================================================
9
+ from typing import TypedDict, Annotated, Sequence, Literal
10
+ from langgraph.graph import StateGraph, END
11
+ from langchain_core.messages import BaseMessage, HumanMessage, AIMessage
12
+ from langchain_openai import ChatOpenAI
13
+ from langchain_core.prompts import ChatPromptTemplate
14
+ from langchain_community.utilities import SQLDatabase
15
+ from langchain_community.agent_toolkits import create_sql_agent
16
+ from langgraph.errors import GraphRecursionError
17
+ from datetime import datetime, timedelta
18
+ import json
19
+ import os
20
+ import json
21
+ import sqlite3, operator
22
+ import streamlit as st
23
+
24
+
25
+
26
+ # Load the JSON file and extract values
27
+ file_name = 'src/config.json'
28
+ with open(file_name, 'r') as file:
29
+ config = json.load(file)
30
+ os.environ['OPENAI_API_KEY'] = config.get("API_KEY") # Loading the API Key
31
+ os.environ["OPENAI_API_BASE"] = config.get("OPENAI_API_BASE") # Loading the API Base Url
32
+ os.environ["OPENAI_API_TYPE"] = "openai"
33
+
34
+
35
+
36
+
37
+ # ============================================================================
38
+ # STATE DEFINITION
39
+ # ============================================================================
40
+ class ChatBotState(TypedDict):
41
+ """State shared across all agents"""
42
+ messages: Annotated[Sequence[BaseMessage], operator.add]
43
+ customer_query: str
44
+ customer_id: str | None
45
+ order_list: list[str] | None
46
+ order_id: str | None
47
+ order_data: dict | None
48
+ product_data: dict | None
49
+ quality_check_result: dict | None
50
+ replacement_result: dict | None
51
+ next_agent: str
52
+ final_response: str | None
53
+
54
+
55
+
56
+ # ============================================================================
57
+ # SQL DATABASE SERVICES
58
+ # ============================================================================
59
+ class SQLOrderService:
60
+ """Service for querying orders from SQLite database"""
61
+
62
+ def __init__(self, db_path='src/orders.db'):
63
+ self.db_path = db_path
64
+ self.db = SQLDatabase.from_uri(f"sqlite:///{db_path}")
65
+ self.llm = ChatOpenAI(model="gpt-4o", temperature=0)
66
+
67
+ def get_order(self, order_id: str) -> dict | None:
68
+ """Get order details using SQL query"""
69
+ try:
70
+ conn = sqlite3.connect(self.db_path)
71
+ conn.row_factory = sqlite3.Row
72
+ cursor = conn.cursor()
73
+
74
+ # Query order with customer info
75
+ cursor.execute('''
76
+ SELECT
77
+ o.order_id,
78
+ o.order_date,
79
+ o.status,
80
+ o.delivery_date,
81
+ o.total_amount,
82
+ o.shipping_address,
83
+ o.payment_method,
84
+ c.name as customer_name,
85
+ c.email as customer_email
86
+ FROM orders o
87
+ JOIN customers c ON o.customer_id = c.customer_id
88
+ WHERE o.order_id = ?
89
+ ''', (order_id,))
90
+
91
+ order_row = cursor.fetchone()
92
+
93
+ if not order_row:
94
+ conn.close()
95
+ return None
96
+
97
+ # Query order items
98
+ cursor.execute('''
99
+ SELECT
100
+ oi.product_id,
101
+ p.name,
102
+ oi.quantity,
103
+ oi.price_at_purchase
104
+ FROM order_items oi
105
+ JOIN products p ON oi.product_id = p.product_id
106
+ WHERE oi.order_id = ?
107
+ ''', (order_id,))
108
+
109
+ items_rows = cursor.fetchall()
110
+
111
+ # Build order dictionary
112
+ order_data = {
113
+ "order_id": order_row["order_id"],
114
+ "customer_name": order_row["customer_name"],
115
+ "customer_email": order_row["customer_email"],
116
+ "order_date": order_row["order_date"],
117
+ "status": order_row["status"],
118
+ "delivery_date": order_row["delivery_date"],
119
+ "total": order_row["total_amount"],
120
+ "shipping_address": order_row["shipping_address"],
121
+ "payment_method": order_row["payment_method"],
122
+ "items": [
123
+ {
124
+ "product_id": row["product_id"],
125
+ "name": row["name"],
126
+ "quantity": row["quantity"],
127
+ "price": row["price_at_purchase"]
128
+ }
129
+ for row in items_rows
130
+ ]
131
+ }
132
+
133
+ conn.close()
134
+ return order_data
135
+
136
+ except Exception as e:
137
+ print(f"Error querying order: {str(e)}")
138
+ return None
139
+
140
+ def search_orders_by_customer(self, customer_name: str) -> list:
141
+ """Search orders by customer name"""
142
+ try:
143
+ conn = sqlite3.connect(self.db_path)
144
+ conn.row_factory = sqlite3.Row
145
+ cursor = conn.cursor()
146
+
147
+ cursor.execute('''
148
+ SELECT o.order_id, o.status, o.order_date, o.total_amount
149
+ FROM orders o
150
+ JOIN customers c ON o.customer_id = c.customer_id
151
+ WHERE c.name LIKE ?
152
+ ORDER BY o.order_date DESC
153
+ ''', (f'%{customer_name}%',))
154
+
155
+ orders = [dict(row) for row in cursor.fetchall()]
156
+ conn.close()
157
+ return orders
158
+
159
+ except Exception as e:
160
+ print(f"Error searching orders: {str(e)}")
161
+ return []
162
+
163
+
164
+ class SQLProductService:
165
+ """Service for querying products from SQLite database"""
166
+
167
+ def __init__(self, db_path='src/orders.db'):
168
+ self.db_path = db_path
169
+
170
+ def get_product(self, product_id: str) -> dict | None:
171
+ """Get product details using SQL query"""
172
+ try:
173
+ conn = sqlite3.connect(self.db_path)
174
+ conn.row_factory = sqlite3.Row
175
+ cursor = conn.cursor()
176
+
177
+ cursor.execute('''
178
+ SELECT
179
+ product_id,
180
+ name,
181
+ description,
182
+ price,
183
+ warranty_period,
184
+ return_policy,
185
+ battery_life,
186
+ connectivity,
187
+ weight,
188
+ water_resistance,
189
+ display,
190
+ category,
191
+ stock_quantity
192
+ FROM products
193
+ WHERE product_id = ?
194
+ ''', (product_id,))
195
+
196
+ row = cursor.fetchone()
197
+ conn.close()
198
+
199
+ if not row:
200
+ return None
201
+
202
+ # Build specifications dict
203
+ specs = {}
204
+ if row["battery_life"]:
205
+ specs["battery_life"] = row["battery_life"]
206
+ if row["connectivity"]:
207
+ specs["connectivity"] = row["connectivity"]
208
+ if row["weight"]:
209
+ specs["weight"] = row["weight"]
210
+ if row["water_resistance"]:
211
+ specs["water_resistance"] = row["water_resistance"]
212
+ if row["display"]:
213
+ specs["display"] = row["display"]
214
+
215
+ return {
216
+ "product_id": row["product_id"],
217
+ "name": row["name"],
218
+ "description": row["description"],
219
+ "price": row["price"],
220
+ "warranty": row["warranty_period"],
221
+ "return_policy": row["return_policy"],
222
+ "category": row["category"],
223
+ "stock_quantity": row["stock_quantity"],
224
+ "specifications": specs
225
+ }
226
+
227
+ except Exception as e:
228
+ print(f"Error querying product: {str(e)}")
229
+ return None
230
+
231
+
232
+ class ReplacementService:
233
+ """Service for creating replacement orders"""
234
+
235
+ def __init__(self, db_path='src/orders.db'):
236
+ self.db_path = db_path
237
+
238
+ def create_replacement(self, order_id: str, reason: str) -> dict:
239
+ """Create a replacement order in the database"""
240
+ replacement_id = f"REP{order_id[3:]}"
241
+
242
+ try:
243
+ conn = sqlite3.connect(self.db_path)
244
+ cursor = conn.cursor()
245
+
246
+ # In a real system, you would:
247
+ # 1. Create a new order record
248
+ # 2. Link it to the original order
249
+ # 3. Update inventory
250
+ # 4. Send notifications
251
+
252
+ # For now, we'll just return the replacement info
253
+ conn.close()
254
+
255
+ return {
256
+ "replacement_id": replacement_id,
257
+ "original_order_id": order_id,
258
+ "status": "Initiated",
259
+ "estimated_delivery": (datetime.now() + timedelta(days=5)).strftime("%Y-%m-%d"),
260
+ "tracking_number": f"TRK{replacement_id}",
261
+ "reason": reason
262
+ }
263
+
264
+ except Exception as e:
265
+ print(f"Error creating replacement: {str(e)}")
266
+ return None
267
+
268
+
269
+
270
+ class OrchestratorAgent:
271
+ """LLM-driven orchestrator for Kartify support β€” handles customer ID + order ID."""
272
+
273
+ def __init__(self, llm):
274
+ self.llm = llm
275
+ self.prompt = ChatPromptTemplate.from_messages([
276
+ (
277
+ "system",
278
+ """You are the orchestrator for Kartify's support workflow.
279
+ Your job is to route queries to the correct agent.
280
+
281
+ Agents:
282
+ - customer_order_lookup β†’ Use when user provides or asks about customer ID
283
+ - order_retrieval β†’ Fetch SINGLE order info (only after customer chose order)
284
+ - product_info β†’ Fetch product details
285
+ - quality_check β†’ Check damage/replacement eligibility
286
+ - replacement_processing β†’ Create a replacement order
287
+ - response_generation β†’ Final response to customer
288
+
289
+ Rules:
290
+ - If message contains a customer ID (like "my customer id is 5", "id 3", "customer 10")
291
+ β†’ ALWAYS route to customer_order_lookup.
292
+ - Never call order_retrieval if order_data already exists.
293
+ - If order_data is present and the user's message is simple or not task-specific β†’ response_generation.
294
+ - Never call replacement_processing twice. Only call replacement_processing only when you are damn sure that the customer wants a replacement.
295
+ If only user confirms a replacement β†’ replacement_processing.
296
+ - If unsure or vague queries such as Thank you etc. β†’ response_generation.
297
+
298
+ Output ONLY the agent name.
299
+ """
300
+ ),
301
+ (
302
+ "human",
303
+ """Customer Query:
304
+ {query}
305
+
306
+ Context:
307
+ - Has order data: {has_order}
308
+ - Has product data: {has_product}
309
+ - Has quality: {has_quality}
310
+ - Has replacement: {has_replacement}
311
+
312
+ Next agent:"""
313
+ )
314
+ ])
315
+
316
+ def process(self, state: ChatBotState) -> ChatBotState:
317
+ query = state.get("customer_query", "").strip().lower()
318
+ has_order = state.get("order_data") is not None
319
+ has_product = state.get("product_data") is not None
320
+ has_quality = state.get("quality_check_result") is not None
321
+ has_replacement = state.get("replacement_result") is not None
322
+
323
+ # -----------------------------------------------------
324
+ # 1. Detect CUSTOMER ID
325
+ # -----------------------------------------------------
326
+ if any(kw in query for kw in ["customer id", "customerid", "customer", "cid", "cust id"]):
327
+ digits = "".join(ch for ch in query if ch.isdigit())
328
+ if digits:
329
+ state["customer_id"] = digits
330
+ state["order_data"] = None
331
+ state["order_list"] = None
332
+ state["order_id"] = None
333
+ state["next_agent"] = "customer_order_lookup"
334
+ return state
335
+
336
+ # -----------------------------------------------------
337
+ # 2. Detect ORDER ID selection (like "OR3001")
338
+ # -----------------------------------------------------
339
+ if query.startswith("or") and any(ch.isdigit() for ch in query):
340
+ state["order_id"] = query.upper()
341
+ state["next_agent"] = "order_retrieval"
342
+ return state
343
+
344
+ # -----------------------------------------------------
345
+ # 3. Confirmations
346
+ # -----------------------------------------------------
347
+ confirm_words = ["yes", "sure", "okay", "ok", "go ahead", "do it", "proceed"]
348
+ if any(word in query for word in confirm_words):
349
+ state["next_agent"] = "replacement_processing"
350
+ return state
351
+
352
+ # -----------------------------------------------------
353
+ # 4. Call LLM for everything else
354
+ # -----------------------------------------------------
355
+ chain = self.prompt | self.llm
356
+
357
+ try:
358
+ response = chain.invoke({
359
+ "query": query,
360
+ "has_order": has_order,
361
+ "has_product": has_product,
362
+ "has_quality": has_quality,
363
+ "has_replacement": has_replacement
364
+ })
365
+ next_agent = response.content.strip().lower().replace(" ", "_")
366
+ except Exception:
367
+ next_agent = "response_generation"
368
+
369
+ # -----------------------------------------------------
370
+ # 5. ALLOW customer_order_lookup in the list!
371
+ # -----------------------------------------------------
372
+ allowed_agents = [
373
+ "customer_order_lookup", # <-- fix
374
+ "order_retrieval",
375
+ "product_info",
376
+ "quality_check",
377
+ "replacement_processing",
378
+ "response_generation"
379
+ ]
380
+ if next_agent not in allowed_agents:
381
+ next_agent = "response_generation"
382
+
383
+ state["next_agent"] = next_agent
384
+ return state
385
+
386
+
387
+ class OrderRetrievalAgent:
388
+ """Retrieves order information from SQL database"""
389
+
390
+ def __init__(self, llm):
391
+ self.llm = llm
392
+ self.order_service = SQLOrderService()
393
+ self.prompt = ChatPromptTemplate.from_messages([
394
+ ("system", """Extract the order ID from the customer query.
395
+ Look for patterns like ORD followed by numbers (e.g., ORD12345).
396
+ Return ONLY the order ID in format ORDXXXXX or the word 'NOT_FOUND' if no order ID is present.
397
+ Do not include any other text."""),
398
+ ("human", "{query}")
399
+ ])
400
+
401
+ def process(self, state: ChatBotState) -> ChatBotState:
402
+ chain = self.prompt | self.llm
403
+ response = chain.invoke({"query": state["customer_query"]})
404
+ order_id = response.content.strip()
405
+
406
+ if order_id != "NOT_FOUND" and "ORD" in order_id.upper():
407
+ order_data = self.order_service.get_order(order_id.upper())
408
+ state["order_id"] = order_id.upper()
409
+ state["order_data"] = order_data
410
+
411
+ state["next_agent"] = "orchestrator"
412
+ return state
413
+
414
+
415
+ class ProductInfoAgent:
416
+ """Retrieves product information from SQL database"""
417
+
418
+ def __init__(self):
419
+ self.product_service = SQLProductService()
420
+
421
+ def process(self, state: ChatBotState) -> ChatBotState:
422
+ if state.get("order_data"):
423
+ items = state["order_data"].get("items", [])
424
+ product_data = []
425
+
426
+ for item in items:
427
+ product_id = item.get("product_id")
428
+ if product_id:
429
+ product = self.product_service.get_product(product_id)
430
+ if product:
431
+ product_data.append(product)
432
+
433
+ state["product_data"] = product_data
434
+
435
+ state["next_agent"] = "orchestrator"
436
+ return state
437
+
438
+
439
+
440
+
441
+ class QualityCheckAgent:
442
+ """Checks if order qualifies for replacement"""
443
+
444
+ def __init__(self, llm):
445
+ self.llm = llm
446
+ self.prompt = ChatPromptTemplate.from_messages([
447
+ ("system", """Analyze if the customer query mentions any product issues.
448
+ Look for keywords like: damaged, defective, broken, wrong item, not working, faulty, quality issues.
449
+ Respond with only 'YES' if issues are mentioned, or 'NO' if not."""),
450
+ ("human", "{query}")
451
+ ])
452
+
453
+ def process(self, state: ChatBotState) -> ChatBotState:
454
+ if not state.get("order_data"):
455
+ state["quality_check_result"] = {
456
+ "eligible": False,
457
+ "reason": "No order data available",
458
+ "issues": []
459
+ }
460
+ else:
461
+ order_data = state["order_data"]
462
+ is_delivered = order_data.get("status") == "Delivered"
463
+
464
+ delivery_date_str = order_data.get("delivery_date")
465
+ within_window = False
466
+ if delivery_date_str:
467
+ delivery_date = datetime.strptime(delivery_date_str, "%Y-%m-%d")
468
+ days_since_delivery = (datetime.now() - delivery_date).days
469
+ within_window = days_since_delivery <= 30
470
+
471
+ chain = self.prompt | self.llm
472
+ response = chain.invoke({"query": state["customer_query"]})
473
+ has_valid_reason = response.content.strip().upper() == "YES"
474
+
475
+ eligible = is_delivered and within_window and has_valid_reason
476
+
477
+ issues = []
478
+ if has_valid_reason:
479
+ query_lower = state["customer_query"].lower()
480
+ if "damaged" in query_lower or "damage" in query_lower:
481
+ issues.append("Product damaged")
482
+ if "defective" in query_lower or "broken" in query_lower:
483
+ issues.append("Product defective")
484
+ if "wrong" in query_lower:
485
+ issues.append("Wrong item received")
486
+ if not issues:
487
+ issues.append("Quality issue reported")
488
+
489
+ state["quality_check_result"] = {
490
+ "eligible": eligible,
491
+ "reason": f"Delivered: {is_delivered}, Within window: {within_window}, Valid reason: {has_valid_reason}",
492
+ "issues": issues,
493
+ "days_since_delivery": (datetime.now() - delivery_date).days if delivery_date_str else None
494
+ }
495
+
496
+ state["next_agent"] = "orchestrator"
497
+ return state
498
+
499
+
500
+ class ReplacementProcessingAgent:
501
+ """Processes replacement or reorder requests safely"""
502
+
503
+ def __init__(self):
504
+ self.replacement_service = ReplacementService()
505
+
506
+ def process(self, state: ChatBotState) -> ChatBotState:
507
+ # --- Retrieve current state data safely ---
508
+ quality_check = state.get("quality_check_result") or {}
509
+ order_data = state.get("order_data")
510
+ order_id = state.get("order_id")
511
+
512
+ # --- Guard: ensure order details exist ---
513
+ if not order_data or not order_id:
514
+ state["final_response"] = (
515
+ "I couldn’t find your order details. Could you please provide your order ID so I can help with the replacement?"
516
+ )
517
+ state["next_agent"] = "response_generation"
518
+ return state
519
+
520
+ # --- Determine reason and eligibility ---
521
+ eligible = isinstance(quality_check, dict) and quality_check.get("eligible", False)
522
+ reason = ", ".join(quality_check.get("issues", [])) if quality_check else "Customer requested reorder"
523
+
524
+ # --- Create replacement or reorder record ---
525
+ if eligible or "reorder" in state.get("customer_query", "").lower() or "assist" in state.get("customer_query", "").lower():
526
+ replacement_result = self.replacement_service.create_replacement(order_id, reason)
527
+ state["replacement_result"] = replacement_result
528
+ else:
529
+ # Not eligible β€” fallback message
530
+ state["replacement_result"] = {
531
+ "replacement_id": None,
532
+ "status": "Not Eligible",
533
+ "reason": reason
534
+ }
535
+ state["final_response"] = (
536
+ "It looks like this order may not be eligible for a replacement. "
537
+ "Could you please confirm if you'd like to reorder these items instead?"
538
+ )
539
+
540
+ # --- Always proceed to response generation ---
541
+ state["next_agent"] = "response_generation"
542
+ return state
543
+
544
+
545
+ class ResponseGenerationAgent:
546
+ """Generates the final customer-facing response for Kartify support.
547
+ Always produces a helpful, empathetic, and complete answer – even with minimal data.
548
+ """
549
+
550
+ def __init__(self, llm):
551
+ self.llm = llm
552
+ self.prompt = ChatPromptTemplate.from_messages([
553
+ (
554
+ "system",
555
+ """You are a warm, professional customer support representative for Kartify.
556
+ Your goal is to provide a clear, empathetic, and helpful response based on all available context.
557
+
558
+ Guidelines:
559
+ - Be natural, polite, and solution-oriented.
560
+ - Always acknowledge the customer's concern.
561
+ - If information is incomplete or unclear, politely ask for clarification.
562
+ - If the query is vague (e.g., greetings or thanks), respond appropriately and keep it brief.
563
+ - If the issue is resolved (replacement or confirmation given), close the conversation positively.
564
+ - NEVER say you are an AI – respond as a human Kartify support agent.
565
+ - Always end on a reassuring, customer-friendly note, but DO NOT include a personal name or signature line.
566
+
567
+ Information you can use:
568
+ - Customer Query: {query}
569
+ - Order Data: {order_data}
570
+ - Product Data: {product_data}
571
+ - Quality Check Result: {quality_check}
572
+ - Replacement Result: {replacement_result}
573
+ - Order List: {order_list}
574
+ """
575
+ ),
576
+ (
577
+ "human",
578
+ """Based on the above context, write a clear, kind, and helpful response for the customer.
579
+ The message should sound natural, empathetic, and directly address their concern."""
580
+ )
581
+ ])
582
+
583
+ def process(self, state: ChatBotState) -> ChatBotState:
584
+ """Generate a friendly, fallback-safe customer response."""
585
+
586
+ # Check if we already have a pre-formatted response (e.g., from CustomerOrderListAgent)
587
+ if state.get("final_response"):
588
+ # Already has a response, just return it
589
+ return state
590
+
591
+ query = state.get("customer_query", "").strip()
592
+ order_data = str(state.get("order_data", "No order data"))
593
+ product_data = str(state.get("product_data", "No product data"))
594
+ quality_check = str(state.get("quality_check_result", "No quality check performed"))
595
+ replacement_result = str(state.get("replacement_result", "No replacement created"))
596
+ order_list = state.get("order_list", [])
597
+
598
+ # πŸ›‘οΈ Handle vague or empty queries before calling LLM
599
+ vague_terms = ["hi", "hello", "hey", "thanks", "thank you", "ok", "okay","okay thanks","ok thanks!"]
600
+ if not query or query.lower().strip() in vague_terms:
601
+ response_text = "Hi there! 😊 How can I assist you with your Kartify order today?"
602
+ else:
603
+ try:
604
+ chain = self.prompt | self.llm
605
+ response = chain.invoke({
606
+ "query": query,
607
+ "order_data": order_data,
608
+ "product_data": product_data,
609
+ "quality_check": quality_check,
610
+ "replacement_result": replacement_result,
611
+ "order_list": order_list if order_list else "No order list"
612
+ })
613
+ response_text = response.content.strip()
614
+ except Exception as e:
615
+ # 🧩 Safe fallback if LLM call fails
616
+ response_text = (
617
+ "I'm sorry, something went wrong while preparing your response. "
618
+ "Could you please rephrase or provide a bit more detail about your concern?"
619
+ )
620
+
621
+ # 🧠 Ensure a final response always exists
622
+ if not response_text or response_text.strip() == "":
623
+ response_text = "I'm here to help with your Kartify order. Could you please clarify your request?"
624
+
625
+ # πŸ’¬ Save the final message and signal end of flow
626
+ state["final_response"] = response_text
627
+ state["next_agent"] = None # 'None' or 'end' β†’ terminate the graph safely
628
+
629
+ return state
630
+
631
+
632
+
633
+
634
+ class CustomerOrderListAgent:
635
+ """Retrieves all order IDs for a given customer ID."""
636
+
637
+ def __init__(self, llm):
638
+ self.llm = llm
639
+ self.order_service = SQLOrderService()
640
+
641
+ self.prompt = ChatPromptTemplate.from_messages([
642
+ (
643
+ "system",
644
+ """Extract the CUSTOMER ID from the message.
645
+ Customer IDs may look like:
646
+ - CUST123
647
+ - C123
648
+ - 123
649
+ - CID555
650
+ ALWAYS return ONLY the ID you detect.
651
+ If none found, return NOT_FOUND.
652
+ No explanations."""
653
+ ),
654
+ ("human", "{query}")
655
+ ])
656
+
657
+ def process(self, state: ChatBotState) -> ChatBotState:
658
+ query = state.get("customer_query", "")
659
+
660
+ # Extract customer ID using LLM
661
+ chain = self.prompt | self.llm
662
+ response = chain.invoke({"query": query})
663
+ detected_customer_id = response.content.strip()
664
+
665
+ if detected_customer_id == "NOT_FOUND":
666
+ state["final_response"] = (
667
+ "I couldn't detect a valid customer ID. Could you please provide your customer ID?"
668
+ )
669
+ state["next_agent"] = "response_generation"
670
+ return state
671
+
672
+ # Save customer ID
673
+ state["customer_id"] = detected_customer_id
674
+
675
+ # Query SQLite directly
676
+ try:
677
+ conn = sqlite3.connect(self.order_service.db_path)
678
+ cursor = conn.cursor()
679
+
680
+ cursor.execute("""
681
+ SELECT order_id
682
+ FROM orders
683
+ WHERE customer_id = ?
684
+ """, (detected_customer_id,))
685
+
686
+ order_rows = cursor.fetchall()
687
+ conn.close()
688
+
689
+ order_list = [row[0] for row in order_rows]
690
+
691
+ if not order_list:
692
+ state["final_response"] = (
693
+ f"No orders were found for customer ID {detected_customer_id}. "
694
+ "Please check the ID and try again."
695
+ )
696
+ state["order_list"] = []
697
+ state["next_agent"] = "response_generation"
698
+ return state
699
+
700
+ # βœ… FIX: Store order list and prepare response
701
+ state["order_list"] = order_list
702
+
703
+ # βœ… FIX: Create a formatted response showing the orders with clear selection prompt
704
+ if len(order_list) == 1:
705
+ # Only one order - still ask for confirmation
706
+ state["final_response"] = (
707
+ f"I found 1 order for customer ID {detected_customer_id}:\n\n"
708
+ f" πŸ“¦ {order_list[0]}\n\n"
709
+ f"Would you like to inquire about order {order_list[0]}? "
710
+ f"Please type the order ID to continue."
711
+ )
712
+ else:
713
+ # Multiple orders - numbered list for easy selection
714
+ order_list_str = "\n".join([f" {i+1}. πŸ“¦ {order_id}" for i, order_id in enumerate(order_list)])
715
+ state["final_response"] = (
716
+ f"I found {len(order_list)} orders for customer ID {detected_customer_id}:\n\n"
717
+ f"{order_list_str}\n\n"
718
+ f"Please select an order by typing the order ID (e.g., {order_list[0]}) "
719
+ f"to view its details or ask your question about it."
720
+ )
721
+
722
+ # βœ… FIX: Go directly to response_generation instead of orchestrator
723
+ state["next_agent"] = "response_generation"
724
+ return state
725
+
726
+ except Exception as e:
727
+ state["final_response"] = (
728
+ f"Something went wrong while retrieving orders for {detected_customer_id}. "
729
+ f"Error: {str(e)}"
730
+ )
731
+ state["next_agent"] = "response_generation"
732
+ return state
733
+
734
+
735
+
736
+
737
+ # ================================================================
738
+ # Initialize LLM and agents
739
+ # ================================================================
740
+ llm = ChatOpenAI(model="gpt-4o", temperature=0)
741
+
742
+ orchestrator = OrchestratorAgent(llm)
743
+ customer_order_list_agent = CustomerOrderListAgent(llm) # βœ… NEW
744
+ order_agent = OrderRetrievalAgent(llm)
745
+ product_agent = ProductInfoAgent()
746
+ quality_agent = QualityCheckAgent(llm)
747
+ replacement_agent = ReplacementProcessingAgent()
748
+ response_agent = ResponseGenerationAgent(llm)
749
+
750
+
751
+ # ================================================================
752
+ # Define node functions
753
+ # ================================================================
754
+ def orchestrator_node(state: ChatBotState):
755
+ return orchestrator.process(state)
756
+
757
+ def customer_order_list_node(state: ChatBotState):
758
+ return customer_order_list_agent.process(state)
759
+
760
+ def order_node(state: ChatBotState):
761
+ return order_agent.process(state)
762
+
763
+ def product_node(state: ChatBotState):
764
+ return product_agent.process(state)
765
+
766
+ def quality_node(state: ChatBotState):
767
+ return quality_agent.process(state)
768
+
769
+ def replacement_node(state: ChatBotState):
770
+ return replacement_agent.process(state)
771
+
772
+ def response_node(state: ChatBotState):
773
+ return response_agent.process(state)
774
+
775
+
776
+ # ================================================================
777
+ # Build the LangGraph workflow
778
+ # ================================================================
779
+ workflow = StateGraph(ChatBotState)
780
+
781
+ # -------- Nodes --------
782
+ workflow.add_node("orchestrator", orchestrator_node)
783
+ workflow.add_node("customer_order_lookup", customer_order_list_node)
784
+ workflow.add_node("order_retrieval", order_node)
785
+ workflow.add_node("product_info", product_node)
786
+ workflow.add_node("quality_check", quality_node)
787
+ workflow.add_node("replacement_processing", replacement_node)
788
+ workflow.add_node("response_generation", response_node)
789
+
790
+
791
+ # -------- Static Edges --------
792
+ workflow.add_edge("customer_order_lookup", "response_generation")
793
+ workflow.add_edge("order_retrieval", "response_generation")
794
+ workflow.add_edge("product_info", "response_generation")
795
+ workflow.add_edge("quality_check", "response_generation")
796
+ workflow.add_edge("replacement_processing", "response_generation")
797
+ workflow.add_edge("response_generation", END)
798
+
799
+
800
+ # -------- Dynamic Routing --------
801
+ def route_next(state: ChatBotState):
802
+ return state["next_agent"]
803
+
804
+ workflow.add_conditional_edges(
805
+ "orchestrator",
806
+ route_next,
807
+ {
808
+ "customer_order_lookup": "customer_order_lookup", # βœ… NEW
809
+ "order_retrieval": "order_retrieval",
810
+ "product_info": "product_info",
811
+ "quality_check": "quality_check",
812
+ "replacement_processing": "replacement_processing",
813
+ "response_generation": "response_generation",
814
+ "end": END
815
+ }
816
+ )
817
+
818
+
819
+ # -------- Entry Point --------
820
+ workflow.set_entry_point("orchestrator")
821
+
822
+ # -------- Compile Graph --------
823
+ graph = workflow.compile()
824
+
825
+
826
+
827
+
828
+
829
+ # -------------------------------------------------------------
830
+ # Create initial state using your ChatBotState definition
831
+ # -------------------------------------------------------------
832
+ def get_initial_state() -> ChatBotState:
833
+ return ChatBotState(
834
+ messages=[],
835
+ customer_query=None,
836
+ customer_id=None,
837
+ order_list=None,
838
+ order_id=None,
839
+ order_data=None,
840
+ product_data=None,
841
+ quality_check_result=None,
842
+ replacement_result=None,
843
+ next_agent="orchestrator",
844
+ final_response=None,
845
+ )
846
+
847
+
848
+ # -------------------------------------------------------------
849
+ # Initialize session state
850
+ # -------------------------------------------------------------
851
+ if "chatbot_state" not in st.session_state:
852
+ st.session_state.chatbot_state = get_initial_state()
853
+
854
+
855
+ # -------------------------------------------------------------
856
+ # Streamlit UI
857
+ # -------------------------------------------------------------
858
+ st.title("πŸ€– Kartify Support Chatbot")
859
+ st.markdown("""
860
+ Welcome to the Kartify AI Support Assistant!
861
+
862
+ πŸ’‘ **Tips**
863
+ β€’ Start by providing your customer ID (e.g., β€œMy customer id is 5”)
864
+ β€’ Then choose an order ID
865
+ β€’ Ask questions about your order
866
+ β€’ Type **quit**, **exit**, or **bye** to end the chat
867
+ """)
868
+ st.divider()
869
+
870
+
871
+ # -------------------------------------------------------------
872
+ # Display Chat History
873
+ # -------------------------------------------------------------
874
+ # Show ONLY the latest message, not the entire history
875
+ messages = st.session_state.chatbot_state["messages"]
876
+
877
+ # Find the last assistant message
878
+ last_assistant_msg = None
879
+ for m in reversed(messages):
880
+ if m["role"] == "assistant":
881
+ last_assistant_msg = m
882
+ break
883
+
884
+ if last_assistant_msg:
885
+ st.chat_message("assistant").write(last_assistant_msg["content"])
886
+
887
+
888
+ # -------------------------------------------------------------
889
+ # User Input
890
+ # -------------------------------------------------------------
891
+ customer_query = st.chat_input("Ask something about your order...")
892
+
893
+ if customer_query:
894
+ # Add user message
895
+ st.session_state.chatbot_state["messages"].append(
896
+ {"role": "user", "content": customer_query}
897
+ )
898
+
899
+ # Exit check
900
+ if customer_query.lower() in ["quit", "exit", "bye", "goodbye", "Okay Thanks", "Thanks", "Okay"]:
901
+ farewell = "πŸ‘‹ Thanks for contacting Kartify Support!"
902
+ st.session_state.chatbot_state["messages"].append(
903
+ {"role": "assistant", "content": farewell}
904
+ )
905
+ st.chat_message("assistant").write(farewell)
906
+ st.stop()
907
+
908
+ state = st.session_state.chatbot_state
909
+
910
+ # Update state before calling graph
911
+ state["customer_query"] = customer_query
912
+ state["next_agent"] = "orchestrator"
913
+ state["final_response"] = None
914
+
915
+ # ---------------------------------------------------------
916
+ # Invoke LangGraph
917
+ # ---------------------------------------------------------
918
+ try:
919
+ updated_state = graph.invoke(state)
920
+
921
+ st.session_state.chatbot_state = updated_state
922
+
923
+ bot_reply = updated_state.get("final_response", "I'm here to help.")
924
+ st.session_state.chatbot_state["messages"].append(
925
+ {"role": "assistant", "content": bot_reply}
926
+ )
927
+ st.chat_message("assistant").write(bot_reply)
928
+
929
+ except GraphRecursionError:
930
+ msg = (
931
+ "⚠️ The system got stuck in a loop. "
932
+ "Please rephrase your question."
933
+ )
934
+ st.session_state.chatbot_state["messages"].append(
935
+ {"role": "assistant", "content": msg}
936
+ )
937
+ st.chat_message("assistant").write(msg)
938
+
939
+ except Exception as e:
940
+ msg = f"❌ Error: {type(e).__name__}: {e}"
941
+ st.session_state.chatbot_state["messages"].append(
942
+ {"role": "assistant", "content": msg}
943
+ )
944
+ st.chat_message("assistant").write(msg)
945
+
946
+
947
+ # -------------------------------------------------------------
948
+ # Debug Panel (Optional)
949
+ # -------------------------------------------------------------
950
+ with st.expander("πŸ” Debug: Full ChatBotState"):
951
+ st.json(st.session_state.chatbot_state)