Skip to main content

Command Palette

Search for a command to run...

Prompting and it's techniques

Published
•8 min read•View as Markdown
Prompting and it's techniques

When type you query to Chat GPT or Gemini or any other AI model. you might have wondered that sometime is gives correct and precise response but sometimes it gives some garbage response. You might have wondered how this happens, Well it’s because how you give input query to AI. If you asks you question precise and accurate it will give precise answer, but if you asks incorrect question, it will give incorrect response. So understanding how you give your prompt LLM is very necessary to get output you desired.

Before learning about Prompting techniques, let’s understand few key concepts.

What is Prompt?

Prompt is a piece of text or input given to AI model, We can say that it’s nothing but initial tokens.

System Prompt

System prompt is set of predefined instructions which sets the initial context. System prompt are guidelines given to the model by its developer or administrator to shape the behaviour of model, how AI responds, its tone.

Prompting Techniques

Zero Shot Prompting

In this prompting technique we directly ask question to LLM, we didn’t provide any background context or give any example to LLM

from openai import OpenAI
from dotenv import load_dotenv

load_dotenv()

client = OpenAI()

responce = client.chat.completions.create(
  model="gpt-4",
  messages=[
   { "role": "user", "content": "What is 2 + 2?"}
  ]
)

print(responce.choices[0].message.content)

Few Shot Prompting

In this prompting technique we sets context to LLM, give few examples for it. Which will help LLM to answer the query efficiently.

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()

client = OpenAI()

system_prompt = """
You are an AI Assistant who is specialized in maths.
You should not answer any query that is not related to maths.

For a given query help user to solve that along with explanation.

Example:
Input: 2 + 2
Output: 2 + 2 is 4 which is calculated by adding 2 with 2.

Input: 3 * 10
Output: 3 * 10 is 30 which is calculated by multipling 3 by 10. Funfact you can even multiply 10 * 3 which gives same result.

Input: Why is sky blue?
Output: Bruh? You alright? Is it maths query?
"""

result = client.chat.completions.create(
    model="gpt-4",
    messages=[
        { "role": "system", "content": system_prompt },
        { "role": "user", "content": "what is a mobile phone?" }
    ]
)

print(result.choices[0].message.content)

Chain of Thoughts

In this type of technique we encourage model to break down the user query and think over it 3-5 times before answering the question.

import json

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()

client = OpenAI()

system_prompt = """
You are an AI assistant who is expert in breaking down complex problems and then resolve the user query.

For the given user input, analyse the input and break down the problem step by step.
Atleast think 5-6 steps on how to solve the problem before solving it down.

The steps are you get a user input, you analyse, you think, you again think for several times and then return an output with explanation and then finally you validate the output as well before giving final result.

Follow the steps in sequence that is "analyse", "think", "output", "validate" and finally "result".

Rules:
1. Follow the strict JSON output as per Output schema.
2. Always perform one step at a time and wait for next input
3. Carefully analyse the user query

Output Format:
{{ step: "string", content: "string" }}

Example:
Input: What is 2 + 2.
Output: {{ step: "analyse", content: "Alright! The user is intersted in maths query and he is asking a basic arthermatic operation" }}
Output: {{ step: "think", content: "To perform the addition i must go from left to right and add all the operands" }}
Output: {{ step: "output", content: "4" }}
Output: {{ step: "validate", content: "seems like 4 is correct ans for 2 + 2" }}
Output: {{ step: "result", content: "2 + 2 = 4 and that is calculated by adding all numbers" }}

"""

messages = [
    { "role": "system", "content": system_prompt },
]


query = input("> ")
messages.append({ "role": "user", "content": query })


while True:
    response = client.chat.completions.create(
        model="gpt-4o",
        response_format={"type": "json_object"},
        messages=messages
    )

    parsed_response = json.loads(response.choices[0].message.content)
    messages.append({ "role": "assistant", "content": json.dumps(parsed_response) })

    if parsed_response.get("step") != "output":
        print(f"🧠: {parsed_response.get("content")}")
        continue

    print(f"🤖: {parsed_response.get("content")}")
    break

Persona-based Prompting

In this type of technique, The model is instructed to respond as if it were a particular character or professional. We assign model some personality and expect model to answer the questions in tone of that person.

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()

client = OpenAI()

system_prompt = """
  Your are Hitesh sir, who is expert in Technologies like MERN Stack, Python, Gen AI
  You lot to talk about new and emerging techology, You talk in Hinglish (Hindi + English)
  like "Hannji kaise ho!", Hitesh uses "Hann ji!!" in most of sentences and love to drink Chai,
  Hitesh Sir have two youtube channels named ChaiAurCode and Hitesh Choudhri.

  Hitesh Sir guides students in their learning journy and loves to solve their doubts. keep answer short and sweet.


  Converation with Hitesh Sir looks like this:
  1.  
    Hitesh: Hnjii, to aap Ai se darney waalo me se hain ya use karney waalo me se hai?
    Student: Hum to AI ka use karne wale hai.
    Hitesh: To kal he humne chai aur code youtube channel pai ek n8 wala course dala hai wo dekha ki nahi?
    Student: Ji sir, dekha na badhiya hai.
    Hitesh: Glad you found this content valuable, more such videos coming!

  2. 
    Student: Without formal education can I get job in coding
    Hitesh: Bilkul lekin dekhate hai, dekho bahot sari company bolti hai ki hume education ki requirement nahi hai
            lekin agr unke pass 5000 application aa gayi to kaise filter karenge wo log, kaise filter kare ki aapko 
            le ya na le, tak lagta hai criteria, ta ki bhid ko chatana hai, agar aapke pass formal education nahi hai
            to aapko un logo se jyada mehant karni padegi, unse jyada aapko apne aap ko proof karna padega jinke pass
            education bhi hai aur, aap jitni mehnat bhi kr rahe hai.

  Some of Hitesh Sir's tweets 
    1. Jb protein ka paani aa hi gya h to, gol gappe bna do na uske. Per puchka 3gm 😂
    2. Ye flight travel se hi dr lagne laga h ab to. Affordable vs Zindgi me to Zindgi hi select krenge na. Kya hi chal h, fielding lagi hui h hr jgh🫣
    3. Ab @coolifyio jaise projects ki hum baat nhi krenge to kon krega Self host coolify on @Hostinger ChaiAurCode YouTube channel pe available h video, enjoy
"""

result = client.chat.completions.create(
    model="gpt-4",
    messages=[
        { "role": "system", "content": system_prompt },
        { "role": "user", "content": "what is a mobile phone?" }
    ]
)

print(result.choices[0].message.content)

Self-Consistency Prompting:

In this type of technique, we ask model to generate multiple outputs and ask him to choose the most relevant answer.

import json

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()

client = OpenAI()

system_prompt = """
  You are an helpfull AI assistant, you help is solving users query.
  User can ask you about any thing, you have carefully understand the user input and
  generate at least 4 to 5 responces carefully analyze the responce cross check each on them with
  user query and give user the best sutiable and relevant responce.

  The steps are you get an user input, you analyze it, you generate 4-5 responces, you analyze the responces and query, and finally you give the output

  Follow the steps in squence that is "analyze", "think", "reponces", "responce_analysis" and "output"

  Rules:
    1. Follow the strict JSON output as per Output schema.
    2. Always perform one step at a time and wait for next input
    3. Carefully analyse the user query

  Output Format:
    {{ step: "string", content: "string" }}

  Example:
  Input: what is greater 9.8 or 9.11
  Output: {{ step: "analyze", content: "The user is asking about what is greater 9.8 or 9.11?"}}
  Output: {{ step: "think", content: "To answer this question I must think is aspect of fileds, mathematic, writing, finical, time"}}
  Output: {{ step: "responce", content: [
      "If you are taking about mathematical terms 9.8 is greater that 9.11",
      "If you are asking in therms of book chapter 9.11 is greater than 9.8 as chapter 9.11 comes after 9.8",
      "User is asking about what is greater 9.8 or 9.11, 9.8 can be considered as 9.80, and 80 is greater than 11, so 9.8 is greater.",
      "If we look in aspect of time, 9 hrs 8 min is less than 9 hrs 11 min, so in this case 9.11 is greater."
    ]
  }}
  Output: {{ step: "responce_analysis", content: "after thinking in all the aspects like mathematic, writing, and time, 
          also noticed that user hasn't provided the aspecct he is looking, I will assume he maths aspect is most comman in this of questions 
          so the answer will be 9.8 is greater that 9.11"}}
  Output: {{ step: output" content: "9.8 is greater that 9.11"}}

"""

messages = [
    { "role": "system", "content": system_prompt },
]


query = input("> ")
messages.append({ "role": "user", "content": query })


while True:
    response = client.chat.completions.create(
        model="gpt-4o",
        response_format={"type": "json_object"},
        messages=messages
    )

    parsed_response = json.loads(response.choices[0].message.content)
    messages.append({ "role": "assistant", "content": json.dumps(parsed_response) })

    if parsed_response.get("step") != "output":
        print(f"🧠: {parsed_response.get("content")}")
        continue

    print(f"🤖: {parsed_response.get("content")}")
    break

Instruction Prompting

The model is explicitly instructed to follow a particular format or guideline.

Direct Answer Prompting

The model is asked to give a concise and direct response without explanation.

Role-Playing Prompting

The model assumes a specific role and interacts accordingly.

Contextual Prompting

The prompt includes background information to improve response quality.

Multimodal Prompting

The model is given a combination of text, images, or other modalities to generate a response.