Uamir commited on
Commit
2ab5d77
·
verified ·
1 Parent(s): 9f54bd3

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +101 -82
main.py CHANGED
@@ -1,82 +1,101 @@
1
- from langchain_google_genai import ChatGoogleGenerativeAI
2
- from langchain_community.document_loaders import TextLoader
3
- from langchain.text_splitter import RecursiveCharacterTextSplitter
4
- from langchain_google_genai import GoogleGenerativeAIEmbeddings
5
- from langchain_community.vectorstores import FAISS
6
- from dotenv import load_dotenv
7
-
8
- load_dotenv()
9
-
10
- llm = ChatGoogleGenerativeAI(model="gemini-1.5-flash")
11
-
12
- embeddings = GoogleGenerativeAIEmbeddings(model="models/text-embedding-004")
13
-
14
- # --- Load products ---
15
- loader = TextLoader("products.json")
16
- docs = loader.load()
17
- splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
18
- text = splitter.split_documents(docs)
19
- product_store = FAISS.from_documents(documents=text, embedding=embeddings)
20
-
21
- # --- Load FAQs ---
22
- loader = TextLoader("faqs.json")
23
- docs = loader.load()
24
- splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
25
- text = splitter.split_documents(docs)
26
- faq_store = FAISS.from_documents(documents=text, embedding=embeddings)
27
-
28
- # --- Retrievers ---
29
- product_retriever = product_store.as_retriever(search_kwargs={"k": 3})
30
- faq_retriever = faq_store.as_retriever(search_kwargs={"k": 3})
31
-
32
- # --- Keywords ---
33
- FAQ_KEYWORDS = {
34
- "delivery", "ship", "shipping", "return", "refund", "warranty",
35
- "payment", "pay", "exchange", "order", "track", "policy"
36
- }
37
- PRODUCT_KEYWORDS = {
38
- "price", "spec", "specs", "specifications", "feature", "features",
39
- "compare", "details", "model", "brand", "laptop", "mobile",
40
- "phone", "shoes", "camera", "ram", "ssd", "storage", "gpu", "cpu"
41
- }
42
-
43
- # --- Conversation history ---
44
- conversation_history = []
45
-
46
- # --- Functions ---
47
- def get_relevant_retriever(query: str):
48
- q = query.lower()
49
- if any(word in q for word in FAQ_KEYWORDS):
50
- return faq_retriever
51
- elif any(word in q for word in PRODUCT_KEYWORDS):
52
- return product_retriever
53
- else:
54
- return product_retriever # default
55
-
56
- def ask_bot(query: str):
57
- retriever = get_relevant_retriever(query)
58
- docs = retriever.get_relevant_documents(query)
59
- context = "\n".join([d.page_content for d in docs])
60
-
61
- # --- Add previous conversation history to context ---
62
- history_text = ""
63
- for turn in conversation_history[-6:]: # last 3 user-bot pairs
64
- history_text += f"User: {turn['user']}\nBot: {turn['bot']}\n"
65
-
66
- full_prompt = f"{history_text}\nContext:\n{context}\n\nUser question: {query}\nAnswer:"
67
- response = llm.invoke(full_prompt)
68
-
69
- # --- Save this turn to history ---
70
- conversation_history.append({"user": query, "bot": response.content})
71
-
72
- return response.content
73
-
74
- # --- Main Loop ---
75
- if __name__ == "__main__":
76
- print("Chatbot started. Type 'exit' or 'quit' to stop.\n")
77
- while True:
78
- query = input("You: ")
79
- if query.lower() in ["exit", "quit", "q"]:
80
- break
81
- answer = ask_bot(query)
82
- print("Bot:", answer)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_google_genai import ChatGoogleGenerativeAI
2
+ from langchain_community.document_loaders import TextLoader
3
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
4
+ from langchain_google_genai import GoogleGenerativeAIEmbeddings
5
+ from langchain_community.vectorstores import FAISS
6
+ from dotenv import load_dotenv
7
+
8
+ load_dotenv()
9
+
10
+ llm = ChatGoogleGenerativeAI(model="gemini-1.5-flash")
11
+
12
+ embeddings = GoogleGenerativeAIEmbeddings(model="models/text-embedding-004")
13
+
14
+ # --- Load products ---
15
+ loader = TextLoader("products.json")
16
+ docs = loader.load()
17
+ splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
18
+ text = splitter.split_documents(docs)
19
+ product_store = FAISS.from_documents(documents=text, embedding=embeddings)
20
+
21
+ # --- Load FAQs ---
22
+ loader = TextLoader("faqs.json")
23
+ docs = loader.load()
24
+ splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
25
+ text = splitter.split_documents(docs)
26
+ faq_store = FAISS.from_documents(documents=text, embedding=embeddings)
27
+
28
+ # --- Retrievers ---
29
+ product_retriever = product_store.as_retriever(search_kwargs={"k": 3})
30
+ faq_retriever = faq_store.as_retriever(search_kwargs={"k": 3})
31
+
32
+ # --- Keywords ---
33
+ FAQ_KEYWORDS = {
34
+ "delivery", "ship", "shipping", "return", "refund", "warranty",
35
+ "payment", "pay", "exchange", "order", "track", "policy"
36
+ }
37
+ PRODUCT_KEYWORDS = {
38
+ "price", "spec", "specs", "specifications", "feature", "features",
39
+ "compare", "details", "model", "brand", "laptop", "mobile",
40
+ "phone", "shoes", "camera", "ram", "ssd", "storage", "gpu", "cpu"
41
+ }
42
+
43
+ # --- Conversation history ---
44
+ conversation_history = []
45
+
46
+ # --- Functions ---
47
+ def get_relevant_retriever(query: str):
48
+ q = query.lower()
49
+ if any(word in q for word in FAQ_KEYWORDS):
50
+ return faq_retriever
51
+ elif any(word in q for word in PRODUCT_KEYWORDS):
52
+ return product_retriever
53
+ else:
54
+ return product_retriever # default
55
+
56
+ def ask_bot(query: str):
57
+ retriever = get_relevant_retriever(query)
58
+ docs = retriever.get_relevant_documents(query)
59
+ context = "\n".join([d.page_content for d in docs])
60
+
61
+ # --- Add previous conversation history to context ---
62
+ history_text = ""
63
+ for turn in conversation_history[-6:]: # last 3 user-bot pairs
64
+ history_text += f"User: {turn['user']}\nBot: {turn['bot']}\n"
65
+
66
+ full_prompt = f"""You are ShopMart's helpful e-commerce assistant.
67
+
68
+ IMPORTANT RULES:
69
+ - Answer the EXACT question asked by the user
70
+ - Use ONLY the information provided in the context below
71
+ - For product questions, show specific products with names and prices
72
+ - If user asks about products "under X PKR", show products within that budget
73
+ - Never give generic promotional responses or templates
74
+ - Be specific and helpful, not vague
75
+ - Include actual product details like prices, specs, availability
76
+
77
+ {history_text}
78
+
79
+ Context Information:
80
+ {context}
81
+
82
+ User question: {query}
83
+
84
+ Helpful Answer:"""
85
+
86
+ response = llm.invoke(full_prompt)
87
+
88
+ # --- Save this turn to history ---
89
+ conversation_history.append({"user": query, "bot": response.content})
90
+
91
+ return response.content
92
+
93
+ # --- Main Loop ---
94
+ if __name__ == "__main__":
95
+ print("Chatbot started. Type 'exit' or 'quit' to stop.\n")
96
+ while True:
97
+ query = input("You: ")
98
+ if query.lower() in ["exit", "quit", "q"]:
99
+ break
100
+ answer = ask_bot(query)
101
+ print("Bot:", answer)