OER·harvester

← Back to the library
GitHub NOTEBOOK resource

Introduction to Prompt Engineering

Repository 21 Lessons, Get Started Building with Generative AI

Licence
OPEN MIT
Authors
Microsoft (microsoft)
Updated
2026-07-16 · GitHub
Language
en
Length
486 words
Open original ↗
{ }
Jupyter notebook Converted to a read-only view · code is not executed

Source: Oai Assignment · GitHub · microsoft/generative-ai-for-beginners Authors: Microsoft (microsoft) Licence: MIT — https://spdx.org/licenses/MIT.html

The following notebook was auto-generated by GitHub Copilot Chat and is meant for initial setup only

Introduction to Prompt Engineering

Prompt engineering is the process of designing and optimizing prompts for natural language processing tasks. It involves selecting the right prompts, tuning their parameters, and evaluating their performance. Prompt engineering is crucial for achieving high accuracy and efficiency in NLP models. In this section, we will explore the basics of prompt engineering using the OpenAI models for exploration.

Exercise 1: Tokenization

Explore Tokenization using tiktoken, an open-source fast tokenizer from OpenAI See OpenAI Cookbook for more examples.

In [1]
# EXERCISE:
# 1. Run the exercise as is first
# 2. Change the text to any prompt input you want to use & re-run to see tokens

import tiktoken

# Define the prompt you want tokenized
text = f"""
Jupiter is the fifth planet from the Sun and the \
largest in the Solar System. It is a gas giant with \
a mass one-thousandth that of the Sun, but two-and-a-half \
times that of all the other planets in the Solar System combined. \
Jupiter is one of the brightest objects visible to the naked eye \
in the night sky, and has been known to ancient civilizations since \
before recorded history. It is named after the Roman god Jupiter.[19] \
When viewed from Earth, Jupiter can be bright enough for its reflected \
light to cast visible shadows,[20] and is on average the third-brightest \
natural object in the night sky after the Moon and Venus.
"""

# Set the model you want encoding for
encoding = tiktoken.encoding_for_model("gpt-4o")

# Encode the text - gives you the tokens in integer form
tokens = encoding.encode(text)
print(tokens);

# Decode the integers to see what the text versions look like
[encoding.decode_single_token_bytes(token) for token in tokens]

Exercise 2: Validate OpenAI API Key Setup

Run the code below to verify that your OpenAI endpoint is set up correctly. The code just tries a simple basic prompt and validates the completion. Input oh say can you see should complete along the lines of by the dawn's early light..

In [2]
# Uses the OpenAI client with the Responses API.
# See https://platform.openai.com/docs/api-reference/responses

import os
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()

client = OpenAI()

deployment="gpt-5-mini"

def get_completion(prompt):
    response = client.responses.create(
        model=deployment,
        input=prompt,
        max_output_tokens=1024,
        store=False,
    )
    return response.output_text

## ---------- Call the helper method

### 1. Set primary content or prompt text
text = f"""
oh say can you see
"""

### 2. Use that in the prompt template below
prompt = f"""
```
```{text}```
"""

## 3. Run the prompt
response = get_completion(prompt)
print(response)

Exercise 3: Fabrications

Explore what happens when you ask the LLM to return completions for a prompt about a topic that may not exist, or about topics that it may not know about because it was outside its pre-trained dataset (more recent). See how the response changes if you try a different prompt, or a different model.

In [3]
## Set the text for simple prompt or primary content
## Prompt shows a template format with text in it - add cues, commands etc if needed
## Run the completion 
text = f"""
generate a lesson plan on the Martian War of 2076.
"""

prompt = f"""
```
```{text}```
"""

response = get_completion(prompt)
print(response)

Exercise 4: Instruction Based

Use the "text" variable to set the primary content and the "prompt" variable to provide an instruction related to that primary content.

Here we ask the model to summarize the text for a second-grade student

In [4]
# Test Example
# https://platform.openai.com/playground/p/default-summarize

## Example text
text = f"""
Jupiter is the fifth planet from the Sun and the \
largest in the Solar System. It is a gas giant with \
a mass one-thousandth that of the Sun, but two-and-a-half \
times that of all the other planets in the Solar System combined. \
Jupiter is one of the brightest objects visible to the naked eye \
in the night sky, and has been known to ancient civilizations since \
before recorded history. It is named after the Roman god Jupiter.[19] \
When viewed from Earth, Jupiter can be bright enough for its reflected \
light to cast visible shadows,[20] and is on average the third-brightest \
natural object in the night sky after the Moon and Venus.
"""

## Set the prompt
prompt = f"""
Summarize content you are provided with for a second-grade student.
```
```{text}```
"""

## Run the prompt
response = get_completion(prompt)
print(response)

Exercise 5: Complex Prompt

Try a request that has system, user and assistant messages System sets assistant context User & Assistant messages provide multi-turn conversation context

Note how the assistant personality is set to "sarcastic" in the system context. Try using a different personality context. Or try a different series of input/output messages

In [5]
response = client.responses.create(
    model=deployment,
    input=[
        {"role": "system", "content": "You are a sarcastic assistant."},
        {"role": "user", "content": "Who won the world series in 2020?"},
        {"role": "assistant", "content": "Who do you think won? The Los Angeles Dodgers of course."},
        {"role": "user", "content": "Where was it played?"}
    ],
    store=False,
)
print(response.output_text)

Exercise: Explore Your Intuition

The above examples give you patterns that you can use to create new prompts (simple, complex, instruction etc.) - try creating other exercises to explore some of the other ideas we've talked about like examples, cues and more.


Disclaimer: This document has been translated using AI translation service Co-op Translator. While we strive for accuracy, please be aware that automated translations may contain errors or inaccuracies. The original document in its native language should be considered the authoritative source. For critical information, professional human translation is recommended. We are not liable for any misunderstandings or misinterpretations arising from the use of this translation.