Prompting Strategies and Tips: Role Assignment, Few-Shot Learning & Iteration Techniques

Michael BrenndoerferJune 13, 202512 min read

Master advanced prompting strategies for AI agents including role assignment, few-shot prompting with examples, and iterative refinement. Learn practical techniques to improve AI responses through context, demonstration, and systematic testing.

Prompting Strategies and Tips

In the previous chapter, you learned that clear, specific instructions help your AI agent understand what you want. But what happens when you need more than just clarity? Sometimes you want the AI to adopt a particular style, or you need it to handle a task it hasn't seen before. That's where prompting strategies come in.

Think of prompting strategies as different ways to frame your request. Just like you might explain something differently to a child versus a colleague, or show someone an example before asking them to try it themselves, you can guide your AI agent in similar ways. These techniques help you get better results without changing the underlying model.

In this chapter, we'll explore practical strategies that make prompting more effective. You'll learn how to give your agent context through roles, how to teach by example, and why treating prompt design as an iterative process leads to better outcomes.

Giving Your Agent a Role

One of the simplest yet most powerful prompting strategies is telling the AI who it should be. When you assign a role, you're giving the model context about how to approach the task. This shapes not just what it says, but how it says it.

Here's a basic example. If you ask:

Explain photosynthesis.

You'll get a reasonable explanation. But watch what happens when you add a role:

You are a biology teacher explaining concepts to high school students. 
Explain photosynthesis in a way that's easy to understand.

The second version will likely use simpler language, include helpful analogies, and avoid jargon. The role gives the model a framework for how to structure its response.

Why Roles Work

Language models are trained on vast amounts of text, including conversations, articles, and documents where people adopt different roles. When you specify a role, you're essentially activating patterns the model has learned about how that type of person communicates.

A few common roles that work well:

  • Teacher or tutor: Good for explanations that need to be clear and educational
  • Expert consultant: Useful when you want detailed, technical information
  • Friendly assistant: Helps when you want a conversational, approachable tone
  • Critical reviewer: Effective when you need the AI to analyze or critique something

The key is matching the role to your goal. If you want creative brainstorming, you might say "You are a creative director." If you need careful analysis, try "You are a data analyst reviewing this information."

Example (GPT-5)

Let's see how roles change the output. Here's a simple Python example using OpenAI's API:

In[3]:
Code
import os
from openai import OpenAI


## Initialize client with your API key
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

## Without a role
## GPT-5 excels at basic text generation tasks like explanations
response1 = client.chat.completions.create(
    model="gpt-5",
    messages=[
        {"role": "user", "content": "Explain machine learning."}
    ]
)

## With a teacher role
response2 = client.chat.completions.create(
    model="gpt-5",
    messages=[
        {"role": "system", "content": "You are a patient teacher explaining concepts to beginners."},
        {"role": "user", "content": "Explain machine learning."}
    ]
)

print("Without role:", response1.choices[0].message.content)
print("\nWith teacher role:", response2.choices[0].message.content)
Out[3]:
Console
Without role: Machine learning (ML) is a way of building systems that learn patterns from data to make predictions or decisions without being explicitly programmed for every rule.

How it differs from traditional programming
- Traditional: write rules + input data → program outputs answers.
- ML: provide examples (data) + desired outputs → algorithm learns rules (a model) that generalize to new data.

Why it’s useful
- Handles complex patterns and variability that are hard to encode by hand.
- Improves with more data and feedback.
- Powers personalization, automation, and insight extraction at scale.

Main types of ML
- Supervised learning: learn from labeled examples (e.g., predict price, classify spam).
- Unsupervised learning: find structure in unlabeled data (e.g., clustering customers, dimensionality reduction).
- Semi/self-supervised learning: leverage unlabeled data with limited labels or proxy tasks.
- Reinforcement learning: learn actions via trial-and-error to maximize reward (e.g., game-playing, robotics).
- Generative modeling: learn data distributions to generate or transform content (e.g., text, images, audio).

Core ideas and terms
- Features: input variables; Labels/targets: what you want to predict.
- Model: a mathematical function mapping inputs to outputs.
- Loss function: measures error; Training minimizes loss (often via gradient descent).
- Overfitting vs. underfitting: memorizing noise vs. missing signal; aim for generalization.
- Bias–variance trade-off: simplicity vs. flexibility.
- Evaluation: train/validation/test splits; metrics like accuracy, F1, AUC, RMSE, MAE.
- Regularization and early stopping: techniques to prevent overfitting.
- Feature engineering and representation learning: crafting or learning useful inputs.

Common methods
- Regression/classification: linear/logistic regression, decision trees, random forests, gradient boosting (XGBoost, LightGBM), SVMs, k-NN, Naive Bayes.
- Neural networks/deep learning: CNNs (vision), RNNs/Transformers (sequence, language), autoencoders, diffusion models.
- Clustering: k-means, hierarchical, DBSCAN.
- Dimensionality reduction: PCA, UMAP, t-SNE.
- Anomaly detection: isolation forests, one-class SVM, autoencoder-based methods.
- Reinforcement learning: Q-learning, policy gradients, actor–critic.

Typical workflow
1. Define the problem and success metric.
2. Gather and clean data; handle missing values and leakage.
3. Explore data; engineer features or choose architectures.
4. Split data; select baseline and candidate models.
5. Train and tune hyperparameters (e.g., with cross-validation).
6. Evaluate fairly; check calibration, fairness, robustness.
7. Deploy; monitor performance and drift; retrain as needed (MLOps).

Examples of use
- Email spam filtering, product recommendations, fraud detection.
- Forecasting demand, pricing, and maintenance.
- Computer vision: defect detection, medical imaging.
- NLP: search, chatbots, translation, summarization.
- Generative AI: create text, images, code, audio.

Limitations and risks
- Data quality and representativeness strongly affect results.
- Distribution shift: performance can degrade as the world changes.
- Interpretability: complex models can be opaque.
- Fairness, bias, and privacy concerns require care.
- Correlation ≠ causation; causal questions need special methods.
- Compute and energy costs for large models.

In short: ML learns from data to make predictions or decisions, excels when rules are complex or variable, and requires careful data handling, evaluation, and ongoing monitoring to be reliable.

With teacher role: Machine learning (ML) is a way for computers to learn patterns from data so they can make predictions or decisions without being explicitly programmed with step-by-step rules.

Simple analogy
- Imagine teaching a child to tell cats from dogs. You show many labeled photos (“cat,” “dog”). Over time, the child notices patterns (ears, snouts, fur) and can label new photos. ML does the same, but with math.

Why it’s useful
- Some tasks are too complex for hand-written rules (spam filtering, speech recognition).
- Data and patterns change over time (fraud tactics, product trends).
- ML can adapt by retraining on new data.

Core ideas
- Data: Examples the model learns from. Often split into training, validation, and test sets to check that learning generalizes to new, unseen data.
- Features and labels: Features are inputs (email text, image pixels); labels are the desired outputs (spam/not spam, price).
- Model: A flexible mathematical function with adjustable parameters (e.g., a decision tree, linear model, neural network).
- Training: Adjusting the model’s parameters to reduce error on the training data.
- Loss function: A score of “how wrong” the model is; training tries to minimize this.
- Generalization: Doing well on new data, not just memorizing the training set.
- Overfitting vs. underfitting: Overfitting = memorizing noise; underfitting = model too simple to capture patterns. Techniques like regularization, more data, or simpler models help.

Main types of ML
- Supervised learning: Learn from labeled examples.
  - Classification: Predict categories (spam vs. not spam, disease present vs. not).
  - Regression: Predict numbers (house price, temperature).
- Unsupervised learning: Find structure in unlabeled data.
  - Clustering: Group similar items (customer segments).
  - Dimensionality reduction: Compress data while keeping important structure (visualization, speed-up).
- Reinforcement learning: An agent learns by trial and error to maximize rewards (game-playing, robot control).

Deep learning vs. “traditional” ML
- Deep learning uses multi-layer neural networks. It excels at images, audio, and language, often needing lots of data and compute.
- Traditional methods (linear/logistic regression, decision trees, random forests, gradient boosting, k-NN) work well on many tabular problems and with less data.

Typical workflow
1. Define the problem and success metric (accuracy, F1, RMSE, etc.).
2. Collect and clean data; engineer features.
3. Split data into train/validation/test sets.
4. Choose a baseline model; train it.
5. Tune hyperparameters; compare models fairly on validation data.
6. Evaluate on the test set once at the end to estimate real-world performance.
7. Deploy; monitor for drift; retrain as needed.

Common pitfalls
- Data leakage: Accidentally letting future or test information influence training.
- Class imbalance: One class dominates; use appropriate metrics (precision/recall, ROC-AUC) and techniques (resampling, class weights).
- Bias and fairness: Models can reflect or amplify biases in data; audit and mitigate.
- Overfitting from too much tweaking on the test set; keep a clean, final test.
- Data drift: Real-world data changes; monitor and update.

When not to use ML
- If a simple set of rules solves the problem reliably.
- When you lack enough, relevant, and representative data.
- When decisions must be fully interpretable and stakes are high (unless you use interpretable models and proper validation).

Quick glossary
- Feature: An input variable.
- Label/target: What you want to predict.
- Model: The learned function mapping features to predictions.
- Training: Fitting the model to data.
- Validation: Tuning choices using held-out data.
- Test: Final, untouched evaluation.
- Overfitting: Doing great on training but poorly on new data.
- Neural network: A model composed of layers of simple units; basis of deep learning.

In short: ML learns patterns from examples to make predictions on new data. Pick the right problem, get good data, choose a suitable model, validate carefully, and keep an eye on real-world performance and ethics.

Notice how we use the system message to set the role. This tells the model to maintain that persona throughout the conversation. The system message acts like stage directions in a play, setting the scene before the dialogue begins.

Teaching by Example: Few-Shot Prompting

Sometimes the best way to explain what you want is to show examples. This technique, called few-shot prompting, involves giving the AI a few examples of the pattern you want it to follow. The model learns from these examples and applies the same pattern to new inputs.

Think about how you might train someone to format data. Instead of writing detailed rules, you'd probably just show them a few examples: "Here's how the first one should look, here's the second one, now you try the third." Few-shot prompting works the same way.

When to Use Few-Shot Prompting

This strategy shines in several situations:

Pattern matching: When you want the AI to follow a specific format or structure. For example, if you're extracting information from text and want it in a particular layout.

Classification tasks: When you need the AI to categorize things consistently. Show it a few examples of each category, and it will understand the distinctions.

Style matching: When you want the AI to write in a specific style or tone. A few examples help it capture the voice you're looking for.

Complex transformations: When the task involves multiple steps or subtle rules that are easier to demonstrate than explain.

Example (GPT-5)

Here's a practical example where we want the AI to categorize customer feedback as positive, negative, or neutral:

In[4]:
Code
import os
from openai import OpenAI


client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

## Few-shot prompt with examples
## GPT-5 handles pattern matching tasks like classification well
prompt = """Categorize the following customer feedback as positive, negative, or neutral.

Examples:
Feedback: "The product arrived quickly and works great!"
Category: positive

Feedback: "The item was damaged and customer service was unhelpful."
Category: negative

Feedback: "The product is okay, nothing special."
Category: neutral

Now categorize this:
Feedback: "I love the design but wish it had more features."
Category:"""

response = client.chat.completions.create(
    model="gpt-5",
    messages=[
        {"role": "user", "content": prompt}
    ]
)

print(response.choices[0].message.content)
Out[4]:
Console
Category: neutral

The model sees the pattern in the examples and applies it to the new feedback. It learns that positive feedback includes praise, negative includes complaints, and neutral is somewhere in between. Without these examples, the model might struggle with mixed feedback like "I love the design but wish it had more features."

How Many Examples Do You Need?

The name "few-shot" is literal. You typically need between 2 and 5 examples. More than that rarely helps and makes your prompt longer (which can slow things down and cost more). Start with 2-3 examples and add more only if the results aren't consistent.

Also, make sure your examples are diverse. If you're teaching the AI to categorize feedback, include examples that cover different types of positive, negative, and neutral responses. This helps the model generalize better.

Iteration: Your Secret Weapon

Here's something that might surprise you: even experienced practitioners rarely get the perfect prompt on the first try. Prompting is an iterative process. You start with something reasonable, see what happens, and then refine based on the results.

This isn't a flaw in the system. It's actually a feature. Because you can quickly test different prompts and see results, you can rapidly improve your approach. Think of it like adjusting a recipe while cooking. You taste, adjust the seasoning, taste again, and keep refining until it's right.

The Iteration Cycle

Here's a simple process that works well:

  1. Start with a clear, simple prompt: Don't overthink it. Write what you want in plain language.

  2. Run it and examine the output: Does it do what you wanted? Where does it fall short?

  3. Identify the gap: Is the output too vague? Too formal? Missing key information? Getting the format wrong?

  4. Adjust one thing: Add more specificity, include an example, change the role, or modify the instructions. Change one element at a time so you know what made the difference.

  5. Test again: See if the adjustment helped. If not, try a different approach.

Example: Refining a Prompt

Let's walk through a real iteration process. Suppose you're building a feature for your personal assistant to summarize articles.

First attempt:

Summarize this article.

Result: The summary is too long and includes minor details.

Second attempt:

Summarize this article in 3 sentences, focusing on the main points.

Result: Better, but the tone is too formal for your needs.

Third attempt:

You are a friendly assistant helping someone catch up on news. 
Summarize this article in 3 sentences, focusing on the main points. 
Use a conversational tone.

Result: Much better! The summary is concise, focused, and easy to read.

Notice how each iteration addressed a specific issue. We didn't try to fix everything at once. This methodical approach helps you understand what works and why.

Example (GPT-5)

Here's how you might implement this iteration in code:

In[5]:
Code
import os
from openai import OpenAI


client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

article = """[Your article text here...]"""

## Version 1: Basic prompt
## GPT-5 is ideal for summarization tasks with clear instructions
def summarize_v1(text):
    response = client.chat.completions.create(
        model="gpt-5",
        messages=[
            {"role": "user", "content": f"Summarize this article:\n\n{text}"}
        ]
    )
    return response.choices[0].message.content

## Version 2: Add constraints
def summarize_v2(text):
    response = client.chat.completions.create(
        model="gpt-5",
        messages=[
            {"role": "user", "content": f"Summarize this article in 3 sentences, focusing on the main points:\n\n{text}"}
        ]
    )
    return response.choices[0].message.content

## Version 3: Add role and tone
def summarize_v3(text):
    response = client.chat.completions.create(
        model="gpt-5",
        messages=[
            {"role": "system", "content": "You are a friendly assistant helping someone catch up on news."},
            {"role": "user", "content": f"Summarize this article in 3 sentences, focusing on the main points. Use a conversational tone:\n\n{text}"}
        ]
    )
    return response.choices[0].message.content

## Test each version
print("Version 1:", summarize_v1(article))
print("\nVersion 2:", summarize_v2(article))
print("\nVersion 3:", summarize_v3(article))
Out[5]:
Console
Version 1: I don’t see any article text yet. Please paste the article (or a link plus the relevant text) and tell me:

- Preferred length: TL;DR (1–2 sentences), short (3–5 bullets), or detailed (150–200 words).
- Audience: general, expert, or executive.
- Focus: key findings, takeaways, data/methods, controversies, or implications.

If it’s long, you can send it in parts and say “CONTINUE” between chunks.

Version 2: I’m happy to help. Please paste the article text (or a shareable excerpt) here so I can summarize it in 3 sentences. If it’s long, you can send it in parts and I’ll combine the summary.

Version 3: I’m happy to help! Please paste the article text or share a link, and I’ll summarize it in three conversational sentences. If you don’t have the text handy, tell me the headline, outlet, and date, and I can still give you a quick, accurate recap.

By keeping different versions, you can compare results and see which approach works best. In real development, you might save successful prompts in a file or database so you can reuse them later.

Combining Strategies

These strategies work even better together. You can give the AI a role AND provide examples AND iterate on the prompt. Each technique complements the others.

For instance, imagine you're building a feature where your personal assistant helps draft emails. You might combine strategies like this:

You are a professional assistant helping with business communication.

Here are examples of how to respond to meeting requests:

Request: "Can we meet next Tuesday?"
Response: "I'd be happy to meet next Tuesday. I have availability at 10am or 2pm. Which works better for you?"

Request: "Let's schedule a call sometime next week."
Response: "I'm available for a call next week. Would Monday at 3pm or Wednesday at 11am work for your schedule?"

Now draft a response to this request:
"We should catch up about the project. Are you free this week?"

This prompt combines a role (professional assistant), few-shot examples (two email responses), and clear instructions (draft a response). The result will be much better than using any single strategy alone.

Practical Tips for Better Prompting

As you develop your prompting skills, keep these guidelines in mind:

Be specific about format: If you want a list, say "Provide your answer as a numbered list." If you want JSON, show the structure you expect.

Set boundaries: Tell the AI what NOT to do if that's important. For example, "Explain this concept without using technical jargon" or "Summarize this without including personal opinions."

Use delimiters for clarity: When your prompt includes multiple parts (like examples or text to process), use clear separators. Triple quotes, XML-style tags, or section headers help the model understand the structure.

Consider token limits: Very long prompts can hit model limits or slow down responses. If your prompt is getting unwieldy, look for ways to be more concise.

Test edge cases: Once you have a prompt that works, try it with unusual inputs. This helps you find and fix weaknesses before they cause problems.

Building Your Prompting Intuition

As you practice these strategies, you'll develop intuition about what works. You'll start to recognize patterns: "This task needs examples" or "A role would help here." This intuition comes from experimentation.

Keep a collection of prompts that work well. When you find a good pattern for summarization, save it. When you discover a role that produces great results, note it down. Over time, you'll build a toolkit of proven approaches.

Remember that prompting is both an art and a science. The science is understanding the strategies and when to apply them. The art is crafting prompts that feel natural and produce results that match your vision. Both aspects improve with practice.

Looking Ahead

You now have several powerful strategies for communicating with your AI agent. You can give it roles to shape its responses, provide examples to teach patterns, and iterate to refine your results. These techniques work for simple tasks like summarization and complex challenges like multi-step reasoning.

In the next chapter, we'll explore how to get your agent to think through problems step by step. You'll learn about reasoning techniques that help the AI break down complex questions and arrive at better answers. The prompting strategies you've learned here will combine with these reasoning approaches to make your agent even more capable.

Glossary

Few-Shot Prompting: A technique where you provide the AI with a few examples of the pattern or task you want it to perform, allowing it to learn by demonstration rather than explicit instruction.

Role Assignment: The practice of giving the AI a specific persona or role (like "teacher" or "expert consultant") to guide how it approaches and responds to tasks.

System Message: A special type of prompt that sets the AI's behavior or role for an entire conversation, acting like stage directions that persist across multiple interactions.

Iteration: The process of repeatedly testing and refining prompts based on results, making incremental improvements until the output meets your needs.

Delimiter: A marker or separator (like triple quotes or XML tags) used in prompts to clearly distinguish different sections, such as examples, instructions, or content to be processed.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about prompting strategies and tips.

Loading component...

Reference

BIBTEXAcademic
@misc{promptingstrategiesandtipsroleassignmentfewshotlearningiterationtechniques, author = {Michael Brenndoerfer}, title = {Prompting Strategies and Tips: Role Assignment, Few-Shot Learning & Iteration Techniques}, year = {2025}, url = {https://mbrenndoerfer.com/writing/prompting-strategies-tips-role-assignment-few-shot-iteration}, organization = {mbrenndoerfer.com}, note = {Accessed: 2025-12-25} }
APAAcademic
Michael Brenndoerfer (2025). Prompting Strategies and Tips: Role Assignment, Few-Shot Learning & Iteration Techniques. Retrieved from https://mbrenndoerfer.com/writing/prompting-strategies-tips-role-assignment-few-shot-iteration
MLAAcademic
Michael Brenndoerfer. "Prompting Strategies and Tips: Role Assignment, Few-Shot Learning & Iteration Techniques." 2025. Web. 12/25/2025. <https://mbrenndoerfer.com/writing/prompting-strategies-tips-role-assignment-few-shot-iteration>.
CHICAGOAcademic
Michael Brenndoerfer. "Prompting Strategies and Tips: Role Assignment, Few-Shot Learning & Iteration Techniques." Accessed 12/25/2025. https://mbrenndoerfer.com/writing/prompting-strategies-tips-role-assignment-few-shot-iteration.
HARVARDAcademic
Michael Brenndoerfer (2025) 'Prompting Strategies and Tips: Role Assignment, Few-Shot Learning & Iteration Techniques'. Available at: https://mbrenndoerfer.com/writing/prompting-strategies-tips-role-assignment-few-shot-iteration (Accessed: 12/25/2025).
SimpleBasic
Michael Brenndoerfer (2025). Prompting Strategies and Tips: Role Assignment, Few-Shot Learning & Iteration Techniques. https://mbrenndoerfer.com/writing/prompting-strategies-tips-role-assignment-few-shot-iteration