OER·harvester

← Back to the library
GitHub NOTEBOOK resource

Introduction to Prompt Engineering

Inferred 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.

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

Introduction to Prompt Engineering

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

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 Microsoft Foundry Models Key Setup

Note: GitHub Models is retiring at the end of July 2026. This exercise uses Microsoft Foundry Models instead, which offers the same free-to-try model catalog and Azure AI Inference SDK experience.

Run the code below to verify that your Microsoft Foundry Models 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]
import os
from azure.ai.inference import ChatCompletionsClient
from azure.ai.inference.models import SystemMessage, UserMessage
from azure.core.credentials import AzureKeyCredential

# Get these from your Microsoft Foundry project's "Overview" page
token = os.environ["AZURE_INFERENCE_CREDENTIAL"]
endpoint = os.environ["AZURE_INFERENCE_ENDPOINT"]

# temperature/top_p need a non-reasoning model (gpt-5 rejects them), so use a Llama model here.
model_name = os.environ.get("AZURE_INFERENCE_CHAT_MODEL", "Llama-3.3-70B-Instruct")

client = ChatCompletionsClient(
    endpoint=endpoint,
    credential=AzureKeyCredential(token),
)

def get_completion(prompt, client, model_name, temperature=1.0, max_tokens=1000, top_p=1.0):
    response = client.complete(
        messages=[
            {
                "role": "system",
                "content": "You are a helpful assistant.",
            },
            {
                "role": "user",
                "content": prompt,
            },
        ],
        model=model_name,
        temperature=temperature,
        max_tokens=max_tokens,
        top_p=top_p
    )
    return response.choices[0].message.content

## ---------- 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, client, model_name)
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, client, model_name)
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, client, model_name)
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.complete(
    model=model_name,
    messages=[
        {"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?"}
    ]
)
print(response.choices[0].message.content)

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.