LESSON 21 · PROMPT ENGINEERING

Role Prompting

Role prompting gives an LLM a useful perspective or job to perform before it handles the user's task. A good role can make the goal, audience, tone, and constraints clearer — but it does not magically give the model new knowledge or skills.

25 min readBeginnerGenerative AI

By the end of this lesson, you will be able to:

  • Explain what role prompting is and why it can help.
  • Separate a role from the actual task, context, and output requirements.
  • Write role prompts for different audiences and applications.
  • Test whether a role actually improves an LLM response.
  • Build a practical Python role-based assistant.
1

What Is Role Prompting?

Role prompting tells the model who it should act as or what professional perspective it should use while completing a task.

WITHOUT A ROLE

Task only

Explain why this Python code is slow.

The model knows the task, but the audience, depth, and perspective are unspecified.

WITH A ROLE

Role + task

You are a senior Python performance engineer. Explain why this code is slow to a junior developer. Give 3 fixes.

The role adds a perspective and helps define how the answer should be delivered.

Core idea:A role is a steering instruction. It works best when it is paired with a concrete task, relevant context, and explicit output requirements.
2

Role ≠ Task

Do not confuse who the model should act as with what the model should do.

ROLEPerspective / responsibilitySenior support agent
+
TASKAction to performClassify the ticket
+
CONTEXTUseful factsCompany policy
+
OUTPUTExpected resultJSON label

For example, “You are a technical support specialist” is a role. “Diagnose the customer's error and return the likely cause plus two next steps” is the task.

EXAMPLE ARole: Python tutor

Task: explain a list comprehension to a beginner using one analogy.

EXAMPLE BRole: product support agent

Task: classify the customer's issue into one allowed category.

3

Why Does a Role Help?

A role can reduce ambiguity by telling the model what perspective, audience, or responsibility should guide the response.

Perspective“Act as a security reviewer” encourages security-focused analysis.
Audience“You are a patient tutor” can encourage beginner-friendly explanations.
Priority“Act as a support triage agent” emphasizes routing and useful next steps.
Style“Act as a concise technical editor” encourages focused writing.
Important:The role is not a guarantee. A model can still make mistakes, invent facts, or ignore a poorly specified requirement. Evaluate the output instead of assuming the role makes it correct.
4

Example 1: Change the Audience

The same topic can need very different answers depending on who the assistant is serving.

BEGINNER TUTOR
You are a patient Python tutor teaching a beginner. Explain what a Python dictionary is. Use a simple real-world analogy and one short code example.
Goal:

Optimize for clarity and learning.

SENIOR REVIEWER
You are a senior Python reviewer. Explain the important design trade-offs of Python dictionaries for an experienced developer. Mention complexity and practical caveats.
Goal:

Optimize for technical depth and trade-offs.

Notice:The subject stays the same, but the role changes the perspective and expected depth. The task and output requirements still matter.
5

Example 2: Role + Context

A role becomes more useful when the model also receives the information it must use.

ROLECustomer support specialist
+
CONTEXTCurrent return policy
+
TASKDecide eligibility
+
OUTPUTYes / No + reason
ROLE:
You are a customer support specialist.

POLICY:
Returns are accepted within 30 days with proof of purchase. Final-sale items are not returnable.

TASK:
Decide whether the customer's request is eligible.

CUSTOMER:
“I bought this final-sale item 10 days ago. Can I return it?”

OUTPUT:
Return exactly: ELIGIBLE or NOT_ELIGIBLE, followed by one short reason.
Key connection:Role prompting and context solve different problems. The role sets the perspective; the context supplies the facts the answer should use.
6

Build a Strong Role Prompt

A useful pattern is Role → Task → Context → Constraints → Output. You do not always need every part, but the pattern makes missing information easy to spot.

01 · ROLEWho should the model act as?
02 · TASKWhat should it do?
03 · CONTEXTWhat facts should it use?
04 · CONSTRAINTSWhat rules apply?
05 · OUTPUTWhat format is required?
WEAK
Act as an expert and help me.

The role is vague and the task is missing.

STRONGER
You are a senior Python code reviewer. Review the function below for correctness and maintainability. Identify the 3 most important issues. Do not rewrite the whole function. Return a numbered list.

The responsibility, task, scope, and output are explicit.

7

Run a Real Role-Prompting Experiment in Python

Test a role against a baseline instead of assuming it helps. Use the same question and compare the responses.

</> Python
import os
from openai import OpenAI

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
question = "Why should I use a virtual environment in Python?"

prompts = {
    "baseline": "Answer the question clearly for a beginner.",
    "role": "You are a patient Python tutor. Explain the answer to a beginner, use one analogy, and give one short example.",
}

for name, instruction in prompts.items():
    response = client.responses.create(
        model="gpt-5-mini",
        input=[
            {"role": "system", "content": instruction},
            {"role": "user", "content": question},
        ],
    )
    print(f"\\n{name.upper()}:\\n{response.output_text}")

Experiment: Compare the answers for clarity, depth, tone, and usefulness. Then remove the analogy requirement and run it again. You are testing which instruction actually changes the behavior.

8

Role Prompting Does Not Create New Knowledge

This is one of the most important misconceptions. Saying “You are a database expert” does not install a database textbook into the model.

MISCONCEPTION

“The role makes it an expert.”

A role can steer perspective and behavior, but it does not guarantee expertise or factual accuracy.

BETTER MODEL

“The role focuses the response.”

Use the role to frame the task, then provide relevant context and evaluate the result.

Production rule:If the answer depends on current or private facts, provide trustworthy context or retrieve it. Do not rely on a role statement as a substitute for evidence.
9

API Message Roles vs. Role Prompting

These ideas are related but not identical. In an API, system, developer, and user are message roles defined by the interface. Role prompting is the instruction itself, such as “You are a patient Python tutor.”

API MESSAGE ROLEsystem / developer / user
contains
ROLE INSTRUCTION“You are a Python tutor…”
guides
TASKExplain the concept

For example, a system or developer message may contain the role instruction, while the user message contains the current question. The exact API semantics depend on the model and platform, so follow the provider's current documentation for message-role behavior.

10

When Role Prompting Is Useful

TutorsPython tutor, math tutor, writing coach.Example:“Explain this as a patient teacher to a beginner.”
ReviewersCode, security, UX, or document review.Example:“Act as a security reviewer and find risky assumptions.”
Support agentsCustomer support, triage, escalation.Example:“Act as a support triage agent and assign one queue.”
EditorsTechnical editor, recruiter, product writer.Example:“Act as a technical editor and remove unnecessary jargon.”
Use it when:The perspective or audience is important to the quality of the response. If the role adds no useful behavior, remove it and keep the prompt simpler.
11

Common Role Prompting Mistakes

01Vague role

“Act like an expert.”

Fix: name the responsibility and audience.
02Role without a task

“You are a doctor.”

Fix: state exactly what the model should do.
03Role as a knowledge shortcut

“You know our private policy.”

Fix: provide or retrieve the policy.
04Too much persona

Long fictional backstory before a simple task.

Fix: keep only instructions that change the output.
12

Mini-Project: Code Review Assistant

Build an assistant that reviews Python code from a specific perspective and returns actionable feedback.

1. Choose the roleSenior Python code reviewer.
2. Define the taskFind correctness and maintainability issues.
3. Add constraintsPrioritize the top 3 issues; do not rewrite everything.
4. Define outputNumbered findings with severity and fix.
5. Test examplesUse clean, buggy, and ambiguous code.
6. CompareRun with and without the role and evaluate usefulness.
You are a senior Python code reviewer helping a development team.

TASK:
Review the Python code below for correctness, maintainability, and obvious performance problems.

CONSTRAINTS:
- Identify the 3 most important issues.
- Explain why each issue matters.
- Suggest a small fix for each issue.
- Do not rewrite the entire program.

OUTPUT:
Return a numbered list. For each item include: severity, issue, why, fix.

CODE:
{python_code}
Challenge:Run the same code through a “security reviewer” role. Compare what changes. Which findings are genuinely more useful, and which are just different wording?
PRACTICE

Role Prompting Challenge

Improve this vague prompt: “Act as an expert and explain APIs.”

Choose a specific roleDefine the audienceState the taskSet the outputAdd useful constraints
QUICK QUIZ

Test yourself

What is the main purpose of role prompting?

30-Second Recap

  • Role prompting tells an LLM what perspective, responsibility, or audience to use.
  • A role is not the same thing as the task, context, constraints, or output format.
  • Good role prompts are specific: name the responsibility and audience instead of saying only “act like an expert.”
  • A role does not create new knowledge or guarantee accuracy.
  • For private or current facts, provide trustworthy context or retrieve the information.
  • Test role prompts against a baseline and keep the role only when it measurably improves the result.