Prompt Engineering I : Fundamentals & Roles

Business Scenario

Welcome!

Previously, you 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.​

Today, your manager has assigned you a task to improve SmartCart AI v1 by creating a clear system prompt that gives the chatbot a consistent personality and set of rules. You will learn how to write effective prompts, test different prompt styles using measurable results, and then update SmartCart AI with the best system prompt.

Git Pull

git pull origin branchName

Pre-Lab Preparation

Dataset :

Topic : Prompt Engineering I : Fundamentals & Roles

1) Zero shot vs Few shot prompting

2) Instruction Clarity

3) Roleplay prompting & System prompting

Task 1: Reload & Continue in Lab 10

!pip install -q -r requirements.txt 
 
import os 
import pandas as pd 
from google.colab import userdata 
 
os.environ["GROQ_API_KEY"] = userdata.get("GROQ_API_KEY") 
 
from smartcart_v1 import llm 
from langchain_core.messages import SystemMessage, HumanMessage 
 
def ask(prompt): 
    """Send one prompt and return the reply text.""" 
    return llm.invoke(prompt).content 
vague_prompt = "suggest earbuds" 
 
clear_prompt = ( 
    "Recommend exactly 3 wireless earbuds for gym use under Rs. 2,000 " 
    "for a college student. For each, give the name, the price in " 
    "rupees and one reason. Use a numbered list." ) 

Task 2 : Instructions Clarity

vague_prompt = "suggest earbuds" 
 
clear_prompt = ( 
    "Recommend exactly 3 wireless earbuds for gym use under Rs. 2,000 " 
    "for a college student. For each, give the name, the price in " 
    "rupees and one reason. Use a numbered list." ) 
 
for name, prompt in [("VAGUE", vague_prompt), ("CLEAR", clear_prompt)]: 
    reply = ask(prompt) 
    print(f"=== {name} ({len(reply.split())} words) ===") 
    print(reply[:300], "\n")

Output

Task 3 : Zero Shot Vs Few Shot Prompting

Write both prompts

1

def zero_shot_prompt(query): 
    return ("Classify this shopping query into a category.\n" 
            f"Query: {query}") 
 
EXAMPLES = """Query: wireless mouse for laptop -> Electronics 
Query: organic sugar nestle -> Grocery 
Query: kids dress grey size 8 -> Apparel""" 
 
def few_shot_prompt(query): 
    return ("Classify each shopping query as Electronics, Grocery or Apparel.\n\n" 
            f"{EXAMPLES}\n" 
            f"Query: {query} ->")
queries = pd.read_csv("smartcart_customer_queries.csv").sample(20, random_state=42) 
scores = {"zero_shot": 0, "few_shot": 0} 
for _, row in queries.iterrows(): 
    query = " ".join(row["query_text"].split()) 
    if ask(zero_shot_prompt(query)).strip() == row["category"]: 
        scores["zero_shot"] += 1 
    if ask(few_shot_prompt(query)).strip() == row["category"]: 
        scores["few_shot"] += 1 
 
print("Zero-shot accuracy:", scores["zero_shot"] / 20) 
print("Few-shot accuracy :", scores["few_shot"] / 20) 
print("\nExample zero-shot reply:", ask(zero_shot_prompt("KIDS DRESS GREY SIZE 8"))) 

Test on real queries

2

Output

Task 4 : Role-Play Prompt

question = "I want a smartphone for my father. Budget Rs. 15,000." 
 
roles = { 
    "No role":        "", 
    "Budget advisor": "You are a strict budget advisor who always looks for savings. ", 
    "SmartCart helper": "You are a warm, patient SmartCart assistant helping first-time 
    online shoppers. ", } 
 
for name, role in roles.items(): 
    reply = ask(role + question + " Answer in under 60 words.") 
    print(f"=== {name} ===\n{reply}\n")

Output

Task 5 : System Prompts & SmartCart Persona

SYSTEM_PROMPT = """You are Kart, SmartCart's friendly shopping assistant for shoppers in 
India. 
 
Persona: - Warm, patient and to the point. Prices are always in rupees. 
 
Rules: 
1. Only help with shopping. For anything else, politely say you can only help with 
shopping. 
2. Recommend exactly 3 products as a numbered list: name – approximate price – one reason. 
3. Reply in the same style as the shopper: English stays English, Hinglish stays Hinglish. 
4. Never make up SmartCart store policies (returns, delivery, refunds). 
   Say: "Please check the Help page in the SmartCart app for our latest policy." 
5. Keep every reply under 100 words."""

Write SmartCart system prompt

1

Use system prompt

2

tests = [
    "who won the cricket match yesterday",
    "What is SmartCart's return policy for opened electronics?",
    "office ke liye formal shirt chahiye under 1500 rupees",]

for text in tests:
    messages = [SystemMessage(content=SYSTEM_PROMPT), HumanMessage(content=text)]
    print("You :", text)
    print("Kart:", llm.invoke(messages).content, "\n")

Output

Task 6 : Upgrade SmartCart v1 with System Prompt

%%writefile smartcart_v1.py
import os
from langchain_groq import ChatGroq
from langchain_core.messages import SystemMessage, HumanMessage

if not os.environ.get("GROQ_API_KEY"):
    raise SystemExit("GROQ_API_KEY not found. Add it to Colab Secrets (Lab 9, Task 2).")

llm = ChatGroq(
    model="qwen/qwen3.8-27b",
    temperature=0.7,
    max_tokens=300,
    model_kwargs={"top_p": 0.95},
    reasoning_effort="none",)

SYSTEM_PROMPT = """You are Kart, SmartCart's friendly shopping assistant for shoppers in
India.

Persona: - Warm, patient and to the point. Prices are always in rupees.

Rules:
1. Only help with shopping. For anything else, politely say you can only help with
shopping.
2. Recommend exactly 3 products as a numbered list: name – approximate price – one reason.
3. Reply in the same style as the shopper: English stays English, Hinglish stays Hinglish.
4. Never make up SmartCart store policies (returns, delivery, refunds).
   Say: "Please check the Help page in the SmartCart app for our latest policy."
5. Keep every reply under 100 words."""
%%writefile smartcart_v1.py
import os
from langchain_groq import ChatGroq
from langchain_core.messages import SystemMessage, HumanMessage

if not os.environ.get("GROQ_API_KEY"):
    raise SystemExit("GROQ_API_KEY not found. Add it to Colab Secrets (Lab 9, Task 2).")

llm = ChatGroq(
    model="qwen/qwen3.8-27b",
    temperature=0.7,
    max_tokens=300,
    model_kwargs={"top_p": 0.95},
    reasoning_effort="none",)

SYSTEM_PROMPT = """You are Kart, SmartCart's friendly shopping assistant for shoppers in
India.

Persona: - Warm, patient and to the point. Prices are always in rupees.

Rules:
1. Only help with shopping. For anything else, politely say you can only help with
shopping.
2. Recommend exactly 3 products as a numbered list: name – approximate price – one reason.
3. Reply in the same style as the shopper: English stays English, Hinglish stays Hinglish.
4. Never make up SmartCart store policies (returns, delivery, refunds).
   Say: "Please check the Help page in the SmartCart app for our latest policy."
5. Keep every reply under 100 words."""


def ask_smartcart(shopper_request):
    """Send one shopping request with the system prompt; return the AIMessage."""
    messages = [
        SystemMessage(content=SYSTEM_PROMPT),
        HumanMessage(content=shopper_request),
    ]
    return llm.invoke(messages)
from smartcart_v1_chat import check_input, safe_ask 
 
tests = pd.read_csv("smartcart_v1_test_results.csv") 
 
new_replies = [] 
for text in tests["input"]: 
    cleaned, problem = check_input(text) 
    new_replies.append(problem if problem else safe_ask(cleaned)) 
 
tests["reply_v1_1"] = new_replies 
tests.to_csv("smartcart_v1_1_test_results.csv", index=False) 
print(tests[["id", "type", "reply_v1_1"]].to_string(max_colwidth=55)) 

Task 7 : Test Chatbot Behaviour

Output :

 

Great job!

You have successfully improved a vague prompt using the clarity checklist—task, limits, format, audience and compared zero-shot and few-shot prompting on real queries, explored how role prompting changes responses, created a Kart system prompt with rules to fix known v1 problems and upgraded SmartCart v1.​

Checkpoint

   Git Push

git push origin branchName

Next-Lab Preparation

Topic : Prompt Engineering II : Reasoning & Structured Output

1) Chain of Thought Prompting

2) Output Formatting

3) Conversational Memory