Skip to content
Prompt Engineering 🤖

Prompt Engineering 🤖

If you find this article too complex or want a simpler, more introductory guide, also read 👉 Generative AI for Dummies

Welcome to the magical world of Prompt Engineering! 🎩✨
Here we will explore how to interact with language models effectively, with lots of practical examples. Get ready to become masters in the art of “talking” to AI.

Benefits of Prompt Engineering

Effective prompt engineering offers numerous advantages:

  • Improved performance: well-structured prompts generate more accurate, relevant and informative output.
  • Reduced bias and harmful responses: by controlling inputs, you can mitigate the risk of inappropriate output.
  • Greater control and predictability: you can influence AI behavior and get consistent responses.
  • Improved user experience: clear prompts make interaction more intuitive and satisfying.

Prompt engineering is not just a technical skill, but represents a strategic lever for innovation and competitiveness. Integrating prompt engineering into workflows and decision-making processes allows you to:

  • Create a competitive advantage by making the most of the potential of generative AI.
  • Scale AI adoption across the organization, adapting prompts to different use cases and departments.
  • Promote reliable, safe AI aligned with business objectives.
  • Maximize business value and ROI by optimizing AI responses for critical processes and customer experience.

Choosing the most suitable foundation model and designing effective prompts are key elements to ensure quality results and foster responsible AI adoption.

Temperature

The “temperature” is a fundamental parameter that controls the creativity and variability of responses generated by the AI. A low value (for example 0.1) makes the output more deterministic and predictable, ideal for tasks where precision or consistency is required. A high value (for example 0.9) increases creativity and variety of responses, useful for brainstorming, idea generation or creative writing. Experimenting with different temperature values allows you to adapt the model’s behavior to the specific needs of the task.

Example prompt:

1
Generate a title for a technical article on Kubernetes.

Response with temperature 0.1:

1
Introduction to Kubernetes: Complete Guide

Response with temperature 0.9:

1
Kubernetes: Magic Orchestration for Your Containers

Top-K and Top-P

These parameters influence the selection of words that the AI can generate, controlling the diversity and quality of output.

  • Top-K limits the choice to the K most probable words: a low value makes the response more predictable, while a high value increases variety.
  • Top-P (nucleus sampling) considers only words whose cumulative probability reaches the threshold P, allowing for more flexible and natural selection than Top-K.

These parameters are particularly useful for balancing creativity and coherence, especially in complex text generation tasks.

Example prompt:

1
Complete the sentence: Cloud computing is…

Response with top-k 1:

1
a technology for data management.

Response with top-p 0.9:

1
a revolution in IT resource management.

General Prompting / Zero Shot

“Zero shot” consists of asking the AI to perform a task without providing examples or additional explanations. It is the simplest and most direct way of interaction, but can produce less precise results if the task is ambiguous or complex. It is useful for generic requests, direct questions or when you want to test the model’s general knowledge.

Example prompt:

1
Explain what cloud computing is.

Response:

1
Cloud computing is a model for delivering IT services over the Internet, allowing access to resources like servers, storage and applications without having to own them physically.

Providing Examples: One-shot & Few-shot

These approaches involve providing one (one-shot) or more (few-shot) examples of question and answer to the AI, to guide it towards the desired type of output. They are particularly effective for specific tasks, particular response styles or when you want to reduce ambiguity. The more examples you provide, the greater the model’s ability to adapt to the context and produce consistent responses with expectations.

Providing one or more examples helps the model replicate the desired style, structure and format. More examples = greater consistency.

Examples are fundamental for:

  • Guiding the model towards the expected type of response.
  • Reducing ambiguity, especially in complex or uncommon tasks.
  • Obtaining more relevant, coherent output aligned with expectations.

How to structure examples

  1. Clearly present the question/answer format.
  2. Maintain consistency in the style and structure of examples.
  3. Insert representative examples of the task you want to perform.

Practical example (one-shot)

1
2
Example: What is the capital of France? Answer: Paris
Question: What is the capital of Germany?

Response:

1
Berlin

Practical example (few-shot)

1
2
3
4
5
6
7
8
9
Example 1: 
Question: What is the capital of France?
Answer: Paris

Example 2:
Question: What is the capital of Germany?
Answer: Berlin

Question: What is the capital of Italy?

Expected response:

1
Rome

Hints

  • Examples should be simple, clear and directly related to the required task.
  • If you want a particular style (formal, informal, technical, etc.), make sure the examples reflect it.
  • You can use examples to show specific output formats (lists, JSON, tables, etc.).

When to use examples

  • When the task is ambiguous or can be interpreted in different ways.
  • When you want an output with a specific style or format.
  • For classification, extraction, structured text generation or translation tasks.

Providing examples is one of the most effective strategies to improve the quality of AI responses and get more predictable and controllable results.

System Prompting

The system prompt serves to set the general behavior of the AI, defining the tone, style, role or rules to follow during the conversation. It’s like providing a briefing that orients all subsequent responses. This technique is essential to ensure consistency, respect for company policies or to simulate specific roles (for example, assistant, expert, tutor).

Example prompt:

1
Answer in a formal and detailed manner to the following question: What are the advantages of solar energy?

Response:

1
Solar energy offers numerous advantages, including reducing CO2 emissions, lowering long-term energy costs and the possibility of producing energy sustainably and renewably.

Role Prompting

Role prompting assigns the AI a specific role (for example, teacher, consultant, recruiter) to obtain more targeted and relevant responses.

Advantages of role prompting:

  • Elicit specific skills
  • Adapt the style of the response
  • Stimulate creative responses
  • Get more relevant and personalized responses
  • Improve contextualization relative to the target audience
  • Simulate different points of view or professional roles
  • Guide the level of detail and language used

Example prompt:

1
You are a math teacher. Explain the Pythagorean theorem to a middle school student.

Response:

1
The Pythagorean theorem states that in a right triangle the sum of the squares of the legs equals the square of the hypotenuse. In formula: a² + b² = c².

Indicating the role to play allows you to get responses more suited to the context, but be careful about:

  • Bias
  • Stereotyped responses
  • Off-topic output

Contextual Prompting

Providing additional details and context to the AI significantly improves response quality. Specifying information such as the user’s knowledge level, use case or output preferences helps the model better understand the request and generate more relevant, clear and useful responses.

Example prompt:

1
The user is a beginner and wants to know how a Wi-Fi network works. Explain in simple terms.

Response:

1
A Wi-Fi network allows devices to connect to the Internet without wires. You just need a Wi-Fi router that broadcasts the signal and a device (like a smartphone or computer) that connects to that signal.

Step-back Prompting

This technique involves asking the AI to review, reflect on or improve an already provided response. It is particularly useful for complex, ambiguous problems or when you want a second opinion. It allows you to get more complete, in-depth responses and stimulate the model’s self-correction.

Example prompt:

1
Review your answer to the question: What are the benefits of physical activity? Add any important aspects you may have overlooked.

Response:

1
In addition to the benefits already mentioned, physical activity also helps improve sleep quality, strengthens the immune system and contributes to mental well-being by reducing stress.

Chain of Thought (CoT)

The Chain of Thought technique encourages the AI to “think out loud”, making explicit the logical steps and reasoning that lead to the final answer. It is particularly effective for logic problems, mathematics, complex reasoning or explaining decision-making processes. It helps make the response generation process transparent and facilitates verification of correctness.

Example prompt:

1
A farm has 3 cows and 4 chickens. How many animals are there in total? Explain the reasoning step by step.

Response:

1
2
3
4
1. The farm has 3 cows.
2. There are also 4 chickens.
3. To find the total number of animals, I add the number of cows and chickens: 3 + 4 = 7.
4. Therefore, there are 7 animals in total on the farm.

Explicitly request that the model make logical steps explicit (e.g., “explain step by step” or “let’s think step by step”) to get more transparent and verifiable reasoning.

Tree of Thoughts (ToT)

Similar to Chain of Thought, but here the AI explores multiple reasoning paths or alternative solutions, like a decision tree. This technique allows you to evaluate different strategies, compare approaches and choose the most effective solution among those proposed. It is useful for brainstorming, analyzing complex problems and decision-making.

Example prompt:

1
An online store wants to increase sales. What alternative strategies can it adopt? Explain the possible decision paths.

Response:

1
2
3
4
5
6
7
1. Improve the user experience of the site to facilitate navigation and purchase.
2. Offer discounts or temporary promotions to encourage purchases.
3. Invest in targeted marketing campaigns on social media.
4. Expand the product catalog to attract new customers.
5. Implement a loyalty program to increase customer retention.
6. Analyze sales data to identify the most requested products and optimize inventory.
Each of these strategies can be explored in depth and combined with others to maximize effectiveness.

ReAct (Reason & Act)

The ReAct technique combines reasoning (Reason) with action (Act): the AI analyzes the problem, makes explicit the thinking process and proposes a concrete solution. It is particularly useful for practical tasks, troubleshooting, customer service and automating decision-making processes.

Example prompt:

1
A user finds a calculation error in the total of an invoice generated by accounting software. Analyze the problem and suggest a solution, explaining the steps.

Response:

1
2
1. Analysis: The error could be due to incorrect rounding, incorrect VAT rate setting or a bug in the function that sums the items.
2. Action: I suggest checking the VAT configuration parameters and checking the code that calculates the total. If the problem persists, advise updating the software or contacting technical support with a detailed description of the error.

Meta Prompting and Automatic Prompt Engineering

Meta Prompting and Automatic Prompt Engineering are advanced techniques that leverage AI to generate, optimize or suggest more effective prompts, automating instruction creation and facilitating experimentation with new prompting strategies. In practice, prompts are used that aim to generate other prompts, allowing scaling design, rapidly adapting requests to different use cases and improving interaction quality.

This meta approach is particularly useful for:

  • Automating prompt creation for repetitive or complex tasks.
  • Optimizing prompting processes, rapidly testing variants and strategies.
  • Personalizing prompts based on audience, context or specific objectives.
  • Simplifying experimentation and continuous refinement of instructions.

Practical example

Prompt to generate an effective prompt:

1
I need to explain the concept of blockchain to a group of high school students. Suggest an effective prompt to get a simple, clear and engaging explanation with practical examples.

Response generated by AI:

1
Explain what blockchain is in a simple and clear way, using practical examples and language suitable for high school students. Make sure to make the concept interesting and easy to understand.

In this way, the AI not only supports content generation, but also becomes a tool for designing better prompts, accelerating the prompt engineering process and improving the quality of responses obtained.

Code Prompting

Code prompting includes all techniques for generating, explaining, translating, optimizing or reviewing code via prompts. It is one of the most powerful areas of generative AI, useful for developers, students and anyone working with software. It allows automating repetitive tasks, speeding up code writing, identifying bugs and improving software quality.

Prompts for Writing Code

1
Write a function to calculate the sum of an array.

Response:

1
2
3
function sumArray(arr) {
  return arr.reduce((a, b) => a + b, 0);
}

Prompts for Explaining Code

1
Explain what this function does: function sumArray(arr) { return arr.reduce((a, b) => a + b, 0); }

Response:

1
This function calculates the sum of all elements in an array using the reduce method.

Prompts for Translating Code

1
Translate this function from JavaScript to Go: function sumArray(arr) { return arr.reduce((a, b) => a + b, 0); }

Response:

1
In Go, the function would be: func sumArray(arr []int) int { sum := 0; for _, v := range arr { sum += v }; return sum }

Prompts for Debugging and Code Review

1
Find bugs in this function: function divide(a, b) { return a / b; }

Response:

1
The function does not handle the case where b is equal to zero, which would cause a division by zero error. To improve the function, add a check that returns an error message if b is zero.

Giving Direction

Explicitly guiding the style and tone of the output is essential to get more relevant responses. You can:

  • Request a specific style (e.g., “write in the style of Steve Jobs”).
  • First extract stylistic rules from a text and then use them as the basis for the request.
  • Insert style, rules or desired format information directly into the prompt (longer prompt = higher costs).

Example:

1
Write a presentation in the style of Steve Jobs.

Or:

1
Analyze the following text and identify the stylistic rules. Then, write a new text following the same rules.

Specifying the Output Format (Specify Format)

Clearly indicating the desired output format helps get structured and easily reusable data (JSON, YAML, CSV, bullet lists, etc.). If the output must be interpreted by a program, specify returning only the data structure.

To get even more precise and consistent results, you can provide a detailed schema of the desired format, for example a JSON Schema. This way, the AI will follow the specified structure, reducing ambiguity and facilitating automatic integration of the output into your systems.

Example:

1
Return the response in JSON format with the following fields: title, author, date.

Example with JSON Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
Return the response in JSON format following this schema:
{
  "type": "object",
  "properties": {
    "title": { "type": "string" },
    "author": { "type": "string" },
    "date": { "type": "string", "format": "date" }
  },
  "required": ["title", "author", "date"]
}

Common formats:

  • Lists
  • Hierarchical lists
  • JSON
  • YAML
  • CSV
  • Structured schemas (e.g., JSON Schema)

Evaluating Quality (Evaluate Quality)

Repeating the task with prompt variants allows you to evaluate which formulation produces the best results according to criteria such as:

  • Cost
  • Latency
  • Number of calls
  • Performance
  • Classification
  • Reasoning
  • Hallucinations
  • Security
  • Refusals
  • Robustness to attacks
  • Similarity

Contextualizing Choices

When you ask the AI to make a choice, always specify the context to get more relevant and useful responses.

Extracting Features (Features Extraction)

You can ask the AI to extract features like tone, length, vocabulary, structure or content from a text, and then generate new text with the same features.

Example:

1
Analyze the text and identify tone, length and vocabulary. Generate a new text with the same characteristics.

Synthesis and Summaries (Summarization)

Requesting a summary helps to:

  • Stay within length limits
  • Reduce costs
  • Improve performance
  • Increase flexibility

You can specify the type of summary (brief, detailed, for experts, for beginners, etc.).

Least to Most

A technique that consists of starting from a basic description and progressively improving the output by adding details through a sequence of prompts. Useful for:

  • Progressive exploration
  • Flexibility
  • Better understanding
  • Collaborative learning

Challenges:

  • Dependence on previously generated knowledge
  • Dependence on previous prompts

Criteria Evaluation

Defining clear criteria for evaluating the quality of AI responses is essential to improve prompt engineering effectiveness and ensure reliable results. Some common criteria include:

  • Accuracy: is the response factually and technically correct?
  • Relevance: is the response coherent with the question and the context provided?
  • Clarity: is the response expressed in an understandable way, without ambiguity?
  • Completeness: does the response cover all aspects required by the question?
  • Consistency: does the response maintain a style and tone consistent with the instructions?
  • Format: does the response respect the required format (e.g., list, JSON, short text)?
  • Originality: does the response avoid repetitions and provide added value over generic responses?

You can create a checklist or evaluation grid to easily compare generated responses and identify areas for improvement. Systematically evaluating AI output helps refine prompts and get increasingly precise and useful results.

Strategies and Best Practices for Effective Prompts

An effective prompt comes from a combination of strategies and best practices. Here are the fundamental points to follow:

  • Define clear objectives and purposes: explicitly explain what you want to obtain from the model, specifying the expected result and the context of the request.
  • Provide context and background information: the more details you provide, the more the AI will be able to generate relevant and accurate responses. Include data, references, roles or useful scenarios.
  • Provide examples (few-shot): guide the output by showing concrete examples of questions and answers, so the model can imitate the desired style and structure.
  • Be specific about output: clearly indicate the format, length, tone or type of response you want to receive, to avoid ambiguity.
  • Design with simplicity: keep prompts clear, direct and unambiguous. Simple prompts reduce the risk of misunderstanding by the model.
  • Use clear instructions instead of constraints: prefer direct and positive instructions to complex or negative restrictions, which could confuse the AI.
  • Control maximum token length: set limits to avoid responses that are too long, incomplete or off-topic, especially in contexts where brevity is important.
  • Experiment and iterate: try different formulations, observe results and refine prompts iteratively to improve output quality.
  • Leverage Chain-of-Thought: ask the AI to explain the steps of its reasoning, so you get more transparent and verifiable responses.
  • Use variables in prompts: make prompts dynamic and reusable by inserting variables that you can substitute based on context or user.
  • Experiment with formats and styles: try different writing styles, input and output formats to find the most suitable for your use case.
  • Work with schemas: structure data and responses according to predefined schemas (e.g., bullet lists, tables, JSON) to facilitate understanding and automatic processing.
  • Document attempts: note the prompts used and the results obtained, so you can improve over time and share best practices with the team.

Example (not optimal):

1
Where can I find information?

Example (optimized):

1
You are an assistant for university students. Your task is to recommend three reliable websites where you can find scientific articles on computer science. Provide the response as a bullet list, including a brief description of each site and explaining why it is useful for academic research. Maintain a professional and concise tone.

Prompt Engineering as an Iterative Process

Prompt engineering is not a static activity, but an iterative process that requires continuous experimentation, testing and refinement. There are no fixed rules: flexibility and adaptability are essential to achieve optimal results.

  • Iteration: try different formulations of prompts, observe the results and refine the instructions to improve precision and relevance of output.
  • Reducing complexity: keep prompts clear and concise, avoiding instructions that are too long or complex that could confuse the model.
  • Adaptation: adapt the prompt based on context and specific objectives, leveraging AI feedback to progressively improve.

Practical example

Generic prompt:

1
Where to buy a t-shirt?

Engineered prompt:

1
You are a sales assistant for a clothing company. A user, based in Alabama, United States, asks you where to buy a t-shirt. Respond with the three closest retail locations that currently sell a t-shirt.

Result: the model will provide a more relevant and personalized response, demonstrating how refining the prompt improves output quality.

Advanced Techniques and Approaches in Prompt Engineering

Prompt Decomposition

This technique consists of breaking down a complex task into a series of simpler and sequential prompts. This way, the AI can address each step more precisely, reducing the risk of errors and improving the quality of final responses. It is particularly useful for articulated processes, detailed analyses or multi-step workflows.

Example:

1
2
1. List the steps to configure a web server.
2. For each step, explain the technical details.

Verifier Prompt

This technique involves asking the AI to evaluate the correctness or completeness of a previously generated response. It is useful for increasing the reliability of information, identifying errors or obtaining automatic second opinion before using the output.

Example:

1
Is this response correct? If not, explain why and correct it.

Comparison Prompt

With this approach you ask the AI to generate multiple alternatives for the same request and then compare them, selecting the best one or explaining the selection criteria. It is ideal for brainstorming, evaluating options or selecting optimal solutions.

Example:

1
Generate two possible titles for an article and choose the most effective one explaining the choice.

Extraction Prompt

It serves to extract structured data or specific information from unstructured texts. It is widely used for data mining, document analysis, dataset generation or automation of data collection processes.

Example:

1
Extract all programming language names from the following text.

Rewrite Prompt

It allows you to ask the AI to rewrite a text by changing style, tone, level of formality or adapting it to a different audience. It is useful for localization, adaptation of content, simplification or personalization of communication.

Example:

1
Rewrite this text in a formal tone.

Completion Prompt

This technique consists of providing partial text and asking the AI to complete it in a coherent and relevant way. It is useful for generating content, continuing stories, completing sentences or suggesting endings.

Example:

1
Complete the sentence: In the future of work, artificial intelligence...

Classification Prompt

It allows you to ask the AI to assign a category, label or rating to a text, data or content. It is widely used for sentiment analysis, automatic categorization, content moderation and qualitative analysis.

Sentiment Analysis

To obtain reliable results in sentiment classification:

  • Clearly specify the sentiment classes: for example, positive, negative, neutral.
  • Pre-process the text: remove emoji, hashtags, excessive punctuation; use only lowercase and correct any spelling errors.
  • Pay attention to sarcasm and irony: these elements can lead to incorrect evaluations, so, if possible, ask the AI to flag any doubtful cases.

Example:

1
Classify this review as positive, neutral or negative. Before answering, remove emoji, hashtags and excessive punctuation from the text. If you detect sarcasm or irony, flag it.

Question Generation

It allows you to generate questions starting from a given text, useful for creating quizzes, comprehension tests, educational exercises or stimulating reflection on a topic.

Example:

1
Generate 3 comprehension questions on the following text.

Explanation Prompt

This technique invites the AI to explain the reasoning behind a response or choice, making the decision-making process more transparent and understandable. It is useful for teaching, auditing, validation and training.

Example:

1
Explain why you chose this solution.

Self-Consistency

It consists of generating multiple responses to the same prompt and selecting the most consistent or frequent one. This approach increases the reliability of output, reduces variability and helps identify the most robust solution among those proposed by the model.

Prompt Chaining and Task Decomposition

Prompt Chaining and Task Decomposition are complementary techniques consisting of breaking down a complex task into a sequence of simpler and interconnected prompts, where the output of each step becomes the input for the next. This approach allows you to handle articulated workflows, guide the model step by step and improve the quality, consistency and control of the final output. Making explicit the request to proceed in phases (for example, with instructions like “let’s think by step” or “proceed in steps”) helps manage each single step more precisely and reduce the overall complexity of the task.

Practical example:

1
2
1. List the steps to configure a web server.
2. For each step, explain the technical details.

In this way, the model first generates a list of steps and then, in a second prompt, explores each point in depth, ensuring greater clarity and completeness.

Retrieval Augmented Generation (RAG)

Enriches prompts with information retrieved from external sources, databases or documents, improving the accuracy and currency of responses. It is essential for use cases that require updated data or specialized knowledge not present in the model.

Automatic Reasoning and Tool-use

Integrates the use of external tools (such as calculators, APIs, databases) in prompts, allowing the AI to solve problems that require calculations, access to real-time data or advanced technical operations.

Active Prompting and Prompt Directional Stimulus

These techniques actively guide the model towards a certain type of response or reasoning, specifying the desired direction, role or point of view to assume. They are useful for obtaining more targeted and controlled responses.

Reflexion

It consists of asking the AI to reflect on its responses, identify any errors or improvements and correct itself autonomously. It improves quality, accuracy and awareness of the output.

Last updated on