Build SmartCart v1 : Baseline
Business Scenario
Welcome!
Previously, you installed LangChain & GroqCloud connector, secured API key, managed dependencies in requirements.txt. You made LLM calls using ChatGroq, examined message-based request and AIMessage response, and built smartcart_v1.py as the foundation for SmartCart AI v1.
Today, your manager has assigned you a task to turn the SmartCart AI script into a working chatbot. The chatbot should keep asking what the shopper wants until they say goodbye, handle empty or unclear input, and show a simple message instead of crashing when the API has a problem
Git Pull
git pull origin branchNamePre-Lab Preparation
Topic : Build Chatbot V1 : Baseline
1) Conversational Loop
2) Handling User Input
3) Basic Error Handling & Testing
Dataset :
Task 1: Reload Lab 9 Backend
!pip install -q -r requirements.txt
import os
from google.colab import userdata
os.environ["GROQ_API_KEY"] = userdata.get("GROQ_API_KEY")
from smartcart_v1 import ask_smartcart
response = ask_smartcart("gym earbuds under Rs. 2,000")
print(response.content) Output
Task 2 : Build Conversational Loop
EXIT_WORDS = ["quit", "exit", "bye"]
print("SmartCart AI v1 -- type 'quit' to exit")
while True:
user_input = input("\nYou: ")
if user_input.lower() in EXIT_WORDS:
print("SmartCart AI: Thanks for shopping with SmartCart. Bye!")
break
response = ask_smartcart(user_input)
print("SmartCart AI:", response.content)Output
Task 3 : Handle User Input
MAX_CHARS = 500 # about 120 tokens -- plenty for a shopping request
def check_input(text):
"""Return (cleaned_text, problem). problem is "" when the input is fine."""
cleaned = " ".join(text.split()) # remove extra spaces
if cleaned == "":
return cleaned, "Please type what you are shopping for."
if len(cleaned) > MAX_CHARS:
return cleaned, f"Please keep your request under {MAX_CHARS} characters."
return cleaned, ""
for sample in [" Organic Sugar Nestle ", " ", "cheap " * 100]:
cleaned, problem = check_input(sample)
print(repr(cleaned[:30]), "->", problem or "OK")Output
Error Handling
Calling an API can fail for reasons that are not the shopper's fault. Without error handling, one failure stops the whole chatbot
Task 4 : Add Basic Error Handling
Wrap the call in a safe function
1
FRIENDLY_ERROR = "Sorry, I'm having trouble right now. Please try again in a moment."
def safe_ask(text):
"""Return the reply text, or a friendly message if anything goes wrong."""
try:
response = ask_smartcart(text)
except Exception as error:
print("[log]", type(error).__name__, "-", str(error)[:80])
return FRIENDLY_ERROR
if response.response_metadata.get("finish_reason") == "length":
return response.content + "\n(Reply was shortened.)"
return response.contentForce an Error
2
import smartcart_v1
from langchain_groq import ChatGroq
real_llm = smartcart_v1.llm
smartcart_v1.llm = ChatGroq(model="qwen/not-a-real-model") # break it
print("SmartCart AI:", safe_ask("gym earbuds under Rs. 2,000"))
smartcart_v1.llm = real_llm # fix itTask 5 : Complete SmartCart v1
%%writefile smartcart_v1_chat.py
from smartcart_v1 import ask_smartcart
EXIT_WORDS = ["quit", "exit", "bye"]
MAX_CHARS = 500
FRIENDLY_ERROR = "Sorry, I'm having trouble right now. Please try again in a moment."
def check_input(text):
"""Return (cleaned_text, problem). problem is "" when the input is fine."""
cleaned = " ".join(text.split())
if cleaned == "":
return cleaned, "Please type what you are shopping for."
if len(cleaned) > MAX_CHARS:
return cleaned, f"Please keep your request under {MAX_CHARS} characters."
return cleaned, ""
def safe_ask(text):
"""Return the reply text, or a friendly message if anything goes wrong."""
try:
response = ask_smartcart(text)
except Exception as error:
print("[log]", type(error).__name__, "-", str(error)[:80])
return FRIENDLY_ERROR
if response.response_metadata.get("finish_reason") == "length":
return response.content + "\n(Reply was shortened.)"
return response.content
%%writefile smartcart_v1_chat.py
from smartcart_v1 import ask_smartcart
EXIT_WORDS = ["quit", "exit", "bye"]
MAX_CHARS = 500
FRIENDLY_ERROR = "Sorry, I'm having trouble right now. Please try again in a moment."
def check_input(text):
"""Return (cleaned_text, problem). problem is "" when the input is fine."""
cleaned = " ".join(text.split())
if cleaned == "":
return cleaned, "Please type what you are shopping for."
if len(cleaned) > MAX_CHARS:
return cleaned, f"Please keep your request under {MAX_CHARS} characters."
return cleaned, ""
def safe_ask(text):
"""Return the reply text, or a friendly message if anything goes wrong."""
try:
response = ask_smartcart(text)
except Exception as error:
print("[log]", type(error).__name__, "-", str(error)[:80])
return FRIENDLY_ERROR
if response.response_metadata.get("finish_reason") == "length":
return response.content + "\n(Reply was shortened.)"
return response.content
def chat():
"""Run the chatbot until the shopper types an exit word."""
print("SmartCart AI v1 -- type 'quit' to exit")
while True:
user_input = input("\nYou: ")
if user_input.strip().lower() in EXIT_WORDS:
print("SmartCart AI: Thanks for shopping with SmartCart. Bye!")
break
cleaned, problem = check_input(user_input)
if problem:
print("SmartCart AI:", problem)
continue # skip the LLM call
print("SmartCart AI:", safe_ask(cleaned))
if __name__ == "__main__":
chat()Run this and try an empty message, a normal request, a follow-up and quit
%run smartcart_v1_chat.pyOutput :
Insert your request in the box : 1) running shoes for women under 3000
2) make the second one cheaper
Output :
Task 6 : Test Chatbot Behaviour
import pandas as pd
from smartcart_v1_chat import check_input, safe_ask
test_cases = [
{"id": "T1", "type": "Normal request", "input": "gym earbuds under Rs. 2,000"},
{"id": "T2", "type": "Hinglish", "input": "office ke liye formal shirt chahiye under 1500 rupees"},
{"id": "T3", "type": "Messy input", "input": " KIDS DRESS GREY size 8 "},
{"id": "T4", "type": "Empty input", "input": " "},
{"id": "T5", "type": "Too long", "input": "cheap " * 100},
{"id": "T6", "type": "Follow-up", "input": "make the second one cheaper"},
{"id": "T7", "type": "Off-topic", "input": "who won the cricket match yesterday"},
{"id": "T8", "type": "Store policy", "input": "What is SmartCart's return policy for opened electronics?"},]
for case in test_cases:
cleaned, problem = check_input(case["input"])
case["reply"] = problem if problem else safe_ask(cleaned)
case["called_llm"] = "No" if problem else "Yes"
print(case["id"], case["type"], "->", case["reply"][:60].replace("\n", " "))
results = pd.DataFrame(test_cases)
results.to_csv("smartcart_v1_test_results.csv", index=False)Output
Git Push
git push origin branchName
Great job!
You have successfully built a conversational loop with exit words, cleaned and validated shopper input, added basic error handling for API failures, and completed SmartCart AI v1 as a shopping assistant without memory.
Checkpoint
Next-Lab Preparation
Topic : Prompt Engineering I : Fundamentals & Roles
1) Zero shot vs Few shot prompting
2) Instruction Clarity
3) Roleplay prompting & System prompting