We use cookies to enhance your experience on the site
CodeWorlds

Prompt Engineering - how to give AI its orders

Imagine, @name, that you have a brilliant intern on the team: they have read half the internet, but they cannot read your mind and will do exactly what you write - no more, no less. Prompt engineering is the skill of writing effective instructions for AI, the art of briefing that intern so they get it right the first time. It is not building servers, not creating databases and not programming in C++ - nothing here is ever compiled to machine code, because you write plain text and the model reads plain text. Three pillars: be specific, give context, set the format.

Pillar 1: be specific

A vague instruction earns a vague answer. The more narrowly you describe what you want, the closer the result lands. Compare:

1# Bad - the intern has to guess what you mean
2"Write something about animals"
3
4# Good - no room left for guessing
5"Write 3 paragraphs about the hunting behaviour of African lions,
6focusing on how the pride cooperates."

The difference is not the length, it is the precision: a number of paragraphs, a specific subject, a specific angle. A good rule of thumb: if a human could read your prompt and write ten different answers to it, the model will be guessing too. Precisely formulating instructions is what separates a working prompt from a lottery ticket.

Pillar 2: give context

The same intern helps far better once they know who you are and where you are standing. Context narrows the answer down to your situation instead of the average case.

1# Bad - what are we even talking about?
2"How do I fix this?"
3
4# Good - the model knows who is asking and what is going on
5"I am a junior Python developer. My FastAPI code returns a 422 error
6on a POST request. Here is the code: [code]. How do I fix it?"

Who is asking, which technology, which exact symptom - those three facts turn a generic lecture into a tailored answer. The model does not know your project, so anything you leave unsaid it will have to invent. Context has a twin sister you will meet a few sections below: the role you hand to the model.

Pillar 3: set the format

If the result is going straight into your program, do not ask for a "description" - show the exact shape you expect. The model mirrors the pattern you hand it.

1prompt = """
2Analyze the text and return the result in JSON format:
3{
4    "species": "species name",
5    "habitat": "where it lives",
6    "diet": "what it eats",
7    "threats": ["list of threats"]
8}
9
10Text: The African lion lives on the savannas...
11"""

By handing over a ready-made JSON skeleton you all but guarantee the answer can be loaded in code without manual cleanup. Notice the

threats
field: even a list is respected, as long as you show one. This is the simplest way to plug a model straight into an application.

Technique: few-shot, or teaching by example

When you need a repeatable answer pattern, do not explain it in words - show a couple of examples. Few-shot prompting means providing examples in the prompt so the model understands the pattern.

1prompt = """
2Classify the animals:
3
4Animal: Lion
5Classification: Predator
6
7Animal: Zebra
8Classification: Herbivore
9
10Animal: Elephant
11Classification:
12"""

Two solved examples tell the model more than a paragraph of instructions: it sees the format, the style and the level of detail. Leaving the last classification empty asks it to finish the pattern - that is the whole point of "few-shot". And notice what it is not: it is one single request that happens to carry examples, not several requests sent one after another, and it is certainly not a shorter prompt - examples make it longer. The "shot" has nothing to do with shooting; it just counts the examples you provide.

Technique: chain of thought, or thinking out loud

On tasks that need real reasoning, a model that answers instantly gets things wrong more often. The Chain of Thought (CoT) technique means asking the model to "think step by step" - like a student showing their working.

1prompt = """
2Solve the problem step by step:
3
4Problem: There are 15 lions and 23 elephants on the Safari.
5Each day 2 lions arrive and 1 elephant leaves.
6How many animals will there be after 5 days?
7
8Solution:
9Step 1: Count the initial number of animals...
10"""

The phrase "step by step" plus a "Solution:" you have already begun push the model to break the task into stages instead of firing off a number. On maths and logic this single trick noticeably raises accuracy. The chain here is a chain of reasoning - it is not blockchain for AI, not a chain of servers and not a type of database.

Technique: role prompting, or handing out a part

You can also fix the point of view the model answers from. You do it in the system message, which sets the tone for the whole conversation.

1system_prompt = """
2You are an experienced Safari guide with 20 years in the field.
3You answer enthusiastically and use anecdotes from the bush.
4You always put the safety of the tourists first.
5"""

Giving the model a role does not change the facts, it changes the style and priorities of the answer - the same model can sound like a dry encyclopedia one moment and like a storyteller round the campfire the next. Providing context and a role for the model is the fastest way to match the tone to your audience.

Templates - a repeatable prompt as a function

When you fire the same prompt at many different inputs, do not glue strings together by hand - use a template with placeholders, that is variables you fill in later. Python has one built in: the string

Template
class.

1from string import Template
2
3template = Template("""
4As an expert in $field, analyze the following $data_type:
5
6$data
7
8Return: 1. Observations  2. Issues  3. Recommendations
9""")
10
11prompt = template.substitute(
12    field="Safari ecology",
13    data_type="population report",
14    data="Lions: 45, Elephants: 120, Giraffes: 78"
15)

The string

Template
swaps
$field
,
$data_type
and
$data
for the values you pass to
substitute
- so you keep one prompt you already trust and feed it many inputs, instead of ten hand-glued variants of the same text.

From string Template to ChatPromptTemplate

Once your prompts move into an LLM framework, the same idea arrives with batteries included. LangChain ships its own template class, and you pull it in with one import line - the package name goes after

from
, the class you want goes after
import
:

1from langchain.prompts import ChatPromptTemplate
2
3prompt = ChatPromptTemplate.from_messages([
4    ("system", "You are an experienced Safari guide."),
5    ("human", "Tell me about {animal}.")
6])
7
8messages = prompt.format_messages(animal="elephants")

Read the construction from left to right, because that is the order you type it in:

ChatPromptTemplate
, then
.from_messages(
, then the list of message tuples
[(...)]
, and finally the closing
)
. Every tuple is a role plus its text, and the
{animal}
gap is filled in later by
format_messages
. Role prompting and templates packed into one object - we build on this in the next lesson.

Good habits to finish with

A few rules that will save you a lot of frustration - treat them as a checklist while you write a prompt.

1# 1. Separate the sections with delimiters so the model can parse the prompt
2prompt = """
3### Task ###
4Analyze the code below and find the bug.
5
6### Code ###
7def calculate(): pass
8
9### Response format ###
10- What the bug is
11- The corrected version
12"""
13
14# 2. Say what you do NOT want as well
15"Answer briefly. No preamble such as Sure, here is..."
16
17# 3. Match the temperature to the task:
18#    temperature=0   -> code and facts (repeatable)
19#    temperature=0.7 -> creative text (varied)
20
21# 4. Iterate: run the prompt, read the answer, tighten the wording

Headings like

### ... ###
help the model tell the instruction apart from the data, and saying what to avoid is often as important as saying what you want. Temperature steers the randomness: with code you want the same correct answer every single time, with a story you want a pinch of imagination. And do not expect a perfect prompt on the first attempt - iterating on the wording is part of the craft.

Remember this from the lesson: you are writing to a capable intern who cannot read your mind. Be specific, give context, set the format - and when the task is hard, add examples or ask for step-by-step thinking. Precisely formulating instructions, providing context and a role for the model, and using examples (few-shot) are what prompt engineering is made of - and not one line of it ever gets compiled to machine code.

Go to CodeWorlds