Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 75

Prompt Engineering Techniques

Recommended resources

Hello! Welcome to your third lesson in the "Large Language Models and Generative AI" module.

In our last lesson, you successfully learned how to communicate with an LLM by making calls to the OpenAI API. You now know how to set up your environment, structure a chat conversation, and use parameters like temperature to influence the style of the output.

Today, we shift our focus from the how to the what. While parameters give you some control, the most powerful tool for guiding an LLM is the content of the prompt itself. This lesson is dedicated to prompt engineering: the skill of designing inputs to elicit specific, accurate, and useful responses from a model. We'll cover three fundamental techniques that are essential for any AI developer:

  • Role-Playing (Persona Prompting): Assigning an identity to the model to shape its tone and expertise.
  • Zero-Shot Prompting: Giving direct instructions without examples.
  • Few-Shot Prompting: Providing examples to teach the model a desired pattern.

Mastering these techniques will allow you to move from simple Q&A to building sophisticated applications that leverage the full power of LLMs.

1. The Art and Science of Prompt Engineering

Before diving into specific techniques, it's crucial to understand the mental model behind prompting. It's easy to think of it as just asking questions, but it's much more.

You SUCK at Prompting AI (Here's the secret)

The video 'You SUCK at Prompting AI' provides an excellent, high-energy introduction to the core idea of prompting. It will help you shift your perspective from simply asking questions to actively programming the AI with words.

Watch from 01:49 to 04:08. Pay close attention to these key ideas: A prompt is not just a question; it's a program. LLMs are prediction engines or "super advanced auto-complete." You are not asking a question; you are starting a pattern and hacking the probability of the desired completion.

A well-structured prompt guides the model's prediction process. While prompts can be very complex, they generally contain four key components.

Prompt Engineering 2025 Full course | Prompt engineering course | ChatGPT Prompts

The video 'Prompt Engineering 2025 Full course' breaks down the structure of an effective prompt into four distinct parts.

Watch the section from 10:16 to 17:30. This segment explains the four components of a good prompt: context, instruction, input data, and output indicator. The sentiment analysis example clearly shows how these pieces fit together.


2. Technique 1: Role-Playing (Persona Prompting)

One of the easiest and most effective ways to improve an LLM's output is to give it a role. By assigning a persona, you narrow the model's focus and guide its tone, vocabulary, and style.

Think about it: asking a "senior site reliability engineer" for an apology email will yield a very different result than asking a generic AI.

You SUCK at Prompting AI (Here's the secret)

Let's return to the NetworkChuck video, which has a fantastic demonstration of the power of personas.

Watch the segment on Personas from 04:08 to 06:38. Notice how a simple instruction—'You're a senior site reliability engineer'—immediately makes the output more specific and professional. This technique is implemented using the system message in the OpenAI API.

Let's apply this in code. Building on our script from the previous lesson, we can add a system message to assign a role.

import os
from openai import OpenAI
from dotenv import load_dotenv

load_dotenv()
client = OpenAI()




# The system message assigns a persona to the model.
system_prompt = "You are a senior Python developer. Your role is to provide clear, concise, and expert-level advice on Python programming. You always provide code examples."

user_prompt = "Explain the difference between a list and a tuple in Python."

try:
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_prompt}
        ],
        temperature=0.7,
        max_tokens=250
    )

    answer = response.choices[0].message.content
    print(f"Expert Python Dev:\n{answer}")

except Exception as e:
    print(f"An error occurred: {e}")

By setting this persona, we guide the model to produce an answer that is technically accurate and includes code, which is exactly what a senior developer would do.


3. Technique 2: Zero-Shot Prompting

Zero-shot prompting is the most basic form of interaction: you give the model a task to perform without providing any examples of how to do it. You have already been doing this!

A prompt like "Translate 'hello' to French" is a zero-shot prompt. It relies entirely on the model's pre-existing knowledge to understand and execute the instruction.

Zero-shot and Few-shot Prompting Method
This slide visually contrasts zero-shot prompting (direct instruction) with few-shot prompting (instruction with examples). For zero-shot, the model performs the task based on its general training.

A Guide to Effective Prompt Engineering

The article 'A Guide to Effective Prompt Engineering' provides a clear definition of this fundamental technique.

Read 'Technique 1: Zero-Shot Prompting'. Note its advantages (efficiency, fewer tokens) and limitations (not suitable for tasks requiring specific or novel formats).

Zero-shot prompting is best for straightforward tasks that are well-represented in the model's training data, such as summarization, translation, or general knowledge questions.


4. Technique 3: Few-Shot Prompting

What if the task is novel, or you need the output in a very specific format that the model might not produce by default? This is where few-shot prompting shines.

In few-shot prompting, you provide one or more examples (shots) of the task being performed. This isn't fine-tuning the model; it's a form of in-context learning where the model uses the examples within the prompt to understand the pattern you want it to follow.

  • One-shot: Providing a single example.
  • Few-shot: Providing multiple examples.

Prompt Engineering 2025 Full course | Prompt engineering course | ChatGPT Prompts

Let's watch a practical demonstration of both zero-shot and few-shot prompting to see the difference in action.

Watch the section on 'Advanced prompt strategies' from 01:01:54 to 01:14:29. Focus on: The zero-shot example of generating text in Shakespeare's style. The few-shot example where providing examples helps the model perform the same task more accurately. The explanation of Chain-of-Thought (CoT) prompting. We won't implement this today, but it's a powerful related technique to be aware of.

Implementing Few-Shot Prompting in Code

Let's try a practical task: extracting structured data (JSON) from unstructured text. This is a common task in AI development. A zero-shot prompt might work, but a few-shot prompt will give us much more reliable and consistently formatted results.

We provide examples by structuring the messages list with user/assistant turn pairs.

import os
import json
from openai import OpenAI
from dotenv import load_dotenv

load_dotenv()
client = OpenAI()




# The system message sets the overall goal.
system_prompt = "You are an expert data extraction assistant. Your task is to extract user information from text and return it as a clean JSON object."




# The text we want to extract data from.
text_to_extract = "Michael Johnson is a 42-year-old software architect from Seattle."

try:
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "system", "content": system_prompt},
            



            # --- Example 1 (One-Shot) ---
            {"role": "user", "content": "Extract user info from: 'Sarah Lee is 29 and works as a product manager in San Francisco.'"},
            {"role": "assistant", "content": json.dumps({"name": "Sarah Lee", "age": 29, "occupation": "product manager", "city": "San Francisco"})},
            



            # --- Example 2 (makes it Few-Shot) ---
            {"role": "user", "content": "Extract user info from: 'David Chen, a 35-year-old doctor, resides in Boston.'"},
            {"role": "assistant", "content": json.dumps({"name": "David Chen", "age": 35, "occupation": "doctor", "city": "Boston"})},




            # --- Our actual request ---
            {"role": "user", "content": f"Extract user info from: '{text_to_extract}'"}
        ],
        temperature=0.1, # Low temperature for factual, consistent output
    )

    extracted_json = response.choices[0].message.content
    print("Extracted Data:")
    print(json.dumps(json.loads(extracted_json), indent=2))

except Exception as e:
    print(f"An error occurred: {e}")

By providing two complete examples, we teach the model the exact JSON structure we expect. It learns the keys (name, age, etc.) and the data types, making the output for our new text highly predictable and reliable.


5. Summary of Core Techniques

You've now learned the three most fundamental prompt engineering techniques.

Prompt Techniques for AI Code Assistants
This table, while focused on code assistants, provides excellent templates for role-playing, providing examples (few-shot), and other techniques. It's a great reference for how to structure your prompts for various tasks.

Key best practices to remember:

  • Be Specific: Ambiguity is your enemy. Clearly define the format, length, tone, and style you want.
  • Provide Context: Give the model the background information it needs to do the task well.
  • Show, Don't Just Tell: When the format is critical, use few-shot examples to demonstrate the desired output.

Prompt Engineering Best Practices: Tips, Tricks, and Tools

The article 'Prompt Engineering Best Practices' provides a great summary of universal habits that make any prompt more effective.

Quickly read through the best practices numbered 1, 2, 4, and 6 ('Be as specific as possible', 'Supply the AI with examples', 'Specify your desired output', 'Give the model a persona'). These directly correspond to the techniques we've covered today.


Conclusion

In this lesson, you've moved beyond simply calling an API to strategically guiding an LLM's behavior. You've learned that prompting is a form of programming and that by using specific techniques, you can elicit far more accurate and useful responses.

Key Takeaways:

  • Prompting as Programming: You should think of LLMs as prediction engines and your prompts as programs that guide their output.
  • Role-Playing: Assigning a persona via the system message is a simple yet powerful way to control the model's tone and expertise.
  • Zero-Shot Prompting: This is your go-to for simple, well-defined tasks where the model's general knowledge is sufficient.
  • Few-Shot Prompting: This is essential for tasks requiring a specific output format or style. By providing examples, you teach the model the desired pattern in-context.

Preview of the Next Lesson:
Prompt engineering is incredibly powerful, but even the best prompts are limited by the model's training data, which is static and can be outdated. What if you need the model to answer questions about very recent events or your company's private documents? In our next lesson, we will explore Retrieval-Augmented Generation (RAG), an architecture that allows you to provide the LLM with external, up-to-date information at the time of prompting.