Prompt engineering

In the rapidly evolving world of artificial intelligence, interacting with powerful generative models requires a specific art and science: prompt engineering. It's the craft of guiding an AI with precise instructions to unlock its full potential, transforming vague ideas into stunning creations or accurate answers. Join us as we explore how mastering this dialogue is revolutionizing how we work, create, and even think with AI. Prompt engineering is the strategic art of crafting inputs to guide generative AI models toward desired, high-quality outputs. Techniques like Chain-of-Thought and Retrieval-Augmented Generation enable AIs to reason through complex problems and incorporate real-time information. While a vital skill today, prompt engineering is an evolving field, with future AI models potentially intuiting user intent more effectively.

Source: Wikipedia

AI Summary

In the rapidly evolving world of artificial intelligence, interacting with powerful generative models requires a specific art and science: prompt engineering. It's the craft of guiding an AI with precise instructions to unlock its full potential, transforming vague ideas into stunning creations or accurate answers. Join us as we explore how mastering this dialogue is revolutionizing how we work, create, and even think with AI.

The Art of Conversation with AI

Prompt engineering is essentially the process of structuring your instructions — your 'prompt' — to get the best possible output from a generative artificial intelligence model. Think of it as learning the AI's language to speak to it more effectively.

A prompt is typically a natural language text describing the task you want the AI to perform. For a text-to-text model, this could be a simple query, a direct command, or even a longer statement rich with context, specific instructions, and a history of your conversation.

When you're working with text-to-image or text-to-audio models, your prompt becomes a detailed description of the output you envision. Phrases like 'a high-quality photo of an astronaut riding a horse' or 'Lo-fi slow BPM electro chill with organic samples' are your canvas, guiding the AI to create specific visual or auditory worlds.

A Brief History of Guiding AI

The seeds of prompt engineering were sown around 2018. Researchers began to realize that many natural language processing tasks — like identifying sentiment or translating text — could be reframed as simple question-answering problems over a given context.

This led to the development of early multi-task models that could answer a variety of questions. But it was the AI boom of the early 2020s, especially with the release of models like ChatGPT in 2022, that truly propelled prompt engineering into the spotlight.

Suddenly, it became a crucial skill to coax desired outcomes from these powerful AIs, avoiding nonsensical or unhelpful responses through a process often involving trial-and-error. By 2023, prompt engineering was seen as an emerging business skill, with public databases and techniques like Chain-of-Thought prompting gaining traction.

Text-to-Text: Thinking Step-by-Step

Chain-of-Thought Prompting

One groundbreaking technique is Chain-of-Thought, or CoT, prompting. Proposed by Google researchers, CoT allows large language models (LLMs) to tackle complex problems not in a single leap, but by breaking them down into a series of intermediate, logical steps.

Imagine asking an AI: 'The cafeteria had 23 apples. If they used 20 for lunch and bought 6 more, how many apples do they have?' With CoT, the AI might reason aloud: 'They started with 23. Used 20, so 23 - 20 = 3. Bought 6 more, so 3 + 6 = 9. The answer is 9.' This mimics human thought, significantly improving accuracy on multi-step tasks like math or commonsense reasoning.

Initially, CoT prompts included a few examples to teach the model how to 'think step-by-step' — a technique called few-shot prompting. But remarkably, simply adding the phrase 'Let's think step-by-step' to a prompt can be just as effective, turning CoT into a powerful zero-shot technique that's easier for anyone to use.

In-Context Learning

Another fascinating ability is in-context learning. This refers to an LLM's temporary capacity to learn from examples provided directly within the prompt itself. For instance, you could provide a few translation pairs like 'maison→house, chat→cat, chien→dog' for the model to learn from.

In-context learning is considered an 'emergent ability' of large language models, meaning it becomes significantly more effective as models scale in size. Unlike permanent changes from training, this learning is temporary, fading once the interaction concludes. It's like the AI is 'learning to learn' on the fly.

Beyond Single Thoughts

To enhance accuracy further, 'self-consistency decoding' takes multiple Chain-of-Thought reasoning paths and selects the conclusion that appears most frequently among them. It's like asking several experts and going with the consensus.

Building on this, 'Tree-of-Thought' prompting generalizes CoT by generating not just one, but multiple parallel lines of reasoning. The AI can then backtrack, explore different paths, and use sophisticated search algorithms — much like navigating a decision tree — to find the optimal solution.

The Delicate Dance of Prompts

LLMs are incredibly sensitive to subtle variations in prompts. Even minor changes in formatting, word choice, or grammar can lead to vastly different — sometimes wildly different — outputs. Studies have shown accuracy swings of up to 76 points simply due to formatting changes!

This sensitivity highlights the need for robust prompting strategies. Tools like FormatSpread and PromptEval help by systematically analyzing a range of plausible prompt variations, allowing users to understand the model's performance boundaries and find more resilient ways to interact with it.

Automatic Prompt Generation

Retrieval-Augmented Generation (RAG)

To keep generative AIs current and factual, Retrieval-Augmented Generation, or RAG, is a game-changer. RAG allows LLMs to access and incorporate new, external information beyond their original training data, responding to queries by referencing specific documents, databases, or web sources.

This dynamic information retrieval helps significantly reduce 'AI hallucinations' — instances where models invent facts or confidently cite nonexistent sources. RAG helps AI 'stick to the facts' by blending the model's generation process with a real-time lookup, ensuring more accurate and reliable responses without constant retraining.

GraphRAG and Auto-CoT

Microsoft Research introduced GraphRAG, which enhances RAG by using knowledge graphs — often generated by LLMs themselves. These graphs allow the model to connect disparate pieces of information, synthesize insights, and holistically understand semantic concepts across vast datasets.

Even LLMs can be used to compose prompts for other LLMs, a technique called Automatic Prompt Engineer (APE). This involves one AI effectively 'beam searching' through potential prompts to find the most effective instructions for another AI, constantly refining the dialogue for optimal results.

Text-to-Image: Visualizing Your Words

The advent of text-to-image models like DALL-E 2, Stable Diffusion, and Midjourney in 2022 transformed how we create. These AIs take your descriptive text prompts and translate them into stunning visual art.

Crafting Visual Prompts

Early text-to-image models often struggled with negation or complex grammar; a prompt like 'a party with no cake' might still produce a cake! To address this, 'negative prompts' were introduced, allowing users to explicitly state what they don't want to see in the final image.

Effective image prompts usually include details about the subject, desired medium (e.g., digital painting, photography), artistic style (hyperrealistic, pop-art), lighting, color, and texture. The order of your words also matters, with terms closer to the beginning often receiving more emphasis.

Simplicity and specificity are key. Midjourney's documentation suggests concise prompts like 'Bright orange California poppies drawn with colored pencils' instead of lengthy, overly descriptive sentences. Less is often more when guiding a visual AI.

In the Style of...

Many text-to-image models can even mimic the style of famous artists. Adding phrases like 'in the style of Greg Rutkowski' or 'inspired by Vincent van Gogh' can instantly transform your image into a distinct artistic vision, showcasing the AI's ability to learn and apply complex aesthetic patterns.

Beyond Text: Non-Text Prompts

Textual Inversion and Image Prompts

Prompting isn't always about words. 'Textual inversion' for text-to-image models involves optimizing a new 'word embedding' — essentially a unique numerical representation — from a set of example images. This new embedding acts as a 'pseudo-word' you can use in prompts to instantly evoke the content or style of those examples.

In 2023, Meta's Segment Anything model showed how image prompts could work directly. Instead of text, you could provide bounding boxes, segmentation masks, or simple foreground/background points directly on an image to instruct the AI to perform precise image segmentation tasks.

Soft Prompts: Letting AI Find the Best Prompts

Even more abstractly, 'soft prompting' or 'prompt tuning' skips human-readable text altogether. Instead, the 'prompt' is a series of floating-point-valued vectors — continuous numerical representations — that are directly optimized by gradient descent. The AI itself effectively searches for the best prompt parameters to maximize desired outputs, without a human ever writing a word.

This powerful technique involves concatenating these tunable prompt embeddings with the input and output tokens. The model's training process then adjusts these 'soft tokens' or 'prefix vectors' to achieve the best performance, allowing the AI to essentially 'learn' the most effective internal prompt representation.

The Evolving Landscape

Limitations and Future

While powerful, prompt engineering today has limitations. The 'best practices' often depend heavily on the specific AI model being used, meaning skills aren't always generalizable. Prompt patterns can also be volatile, with tiny changes yielding significantly different results.

The role of a dedicated prompt engineer is constantly evolving. As AI models become more intuitive and better at understanding user intent, the need for highly specialized prompting might diminish, with companies focusing on training models to respond effectively out-of-the-box.

Article

Prompt engineering

Prompt engineering is the process of structuring natural language inputs (known as prompts) to produce specified outputs from a generative artificial intelligence (GenAI) model. Context engineering is the related area of software engineering that focuses on the management of non-prompt contexts supplied to the GenAI model, such as metadata, API tools, and tokens.

It can also be defined as the practice of designing and refining input instructions given to a generative AI model in order to produce more accurate, relevant, or useful outputs. Effective prompt engineering involves understanding how a model interprets language, and may include techniques such as few-shot prompting, chain-of-thought prompting, and role assignment. It is increasingly considered a key skill for working with large language models (LLMs) in both research and professional contexts.

During the 2020s AI boom, prompt engineering became regarded as an important business capability across corporations and industries. Employees with the title prompt engineer were hired to create prompts that would increase productivity and efficacy, although the individual title has since lost traction in light of AI models that produce better prompts than humans and corporate training in prompting for general employees.

Common prompting techniques include multi-shot, chain-of-thought, and tree-of-thought prompting, as well as the use of assigning roles to the model. Automated prompt generation methods, such as retrieval-augmented generation (RAG), provide for greater accuracy and a wider scope of functions for prompt engineers. Prompt injection is a type of cybersecurity attack that targets machine learning models through malicious prompts.

Terminology

Prompt engineering

The Oxford English Dictionary defines prompt engineering as "The action or process of formulating and refining prompts for an artificial intelligence program, algorithm, etc., in order to optimize its output or to achieve a desired outcome; the discipline or profession concerned with this." In 2023, prompt ("an instruction given to an artificial intelligence program, algorithm, etc., which determines or influences the content it generates") was the runner-up to Oxford's word of the year.

Prompt

A prompt is some natural language text that describes and prescribes the task that an artificial intelligence (AI) should perform. A prompt for a text-to-text language model can be a query, a command, or a longer statement referencing context, instructions, and conversation history. The process of prompt engineering may involve designing clear queries, refining wording, providing relevant context, specifying the style of output, and assigning a character for the AI to mimic in order to guide the model toward more accurate, useful, and consistent responses.

When communicating with a text-to-image or a text-to-audio model, a typical prompt contains a description of a desired output such as "a high-quality photo of an astronaut riding a horse" or "Lo-fi slow BPM electro chill with organic samples". Prompt engineering may be applied to text-to-image models to achieve a desired subject, style, layout, lighting, and aesthetic.

Techniques

Common terms used to describe various specific prompt engineering techniques include chain-of-thought, tree-of-thought, and retrieval-augmented generation (RAG). A 2024 survey of the field identified over 50 distinct text-based prompting techniques, 40 multimodal variants, and a vocabulary of 33 terms used across prompting research, highlighting a present lack of standardised terminology for prompt engineering.

Vibe coding is an AI-assisted software development method where a user prompts an LLM with a description of what they want and lets it generate or edit the code. In 2025, "vibe coding" was the Collins Dictionary word of the year.

Context engineering

Context engineering is a related process that focuses on the context elements that accompany user prompts, which include system instructions, retrieved knowledge, tool definitions, conversation summaries, and task metadata. Context engineering is performed to improve reliability, provenance and token efficiency in production LLM systems. The concept emphasises operational practices such as token budgeting, provenance tags, versioning of context artifacts, observability (logging which context was supplied), and context regression tests to ensure that changes to supplied context do not silently alter system behaviour.

Rationale

Prompt engineering

Research has found that the performance of large language models (LLMs) is highly sensitive to choices such as the ordering of examples, the quality of demonstration labels, and even small variations in phrasing. In some cases, reordering examples in a prompt produced accuracy shifts of more than 40 percent.

In-context learning

A model's ability to temporarily learn from prompts is known as in-context learning. In-context learning is an emergent ability of large language models. It is an emergent property of model scale, meaning that breaks in scaling laws occur, leading to its efficacy increasing at a different rate in larger models than in smaller models. Unlike training and fine-tuning, which produce lasting changes, in-context learning is temporary. Training models to perform in-context learning can be viewed as a form of meta-learning, or "learning to learn".

Prompting to estimate model sensitivity

Research consistently demonstrates that LLMs are highly sensitive to subtle variations in prompt formatting, structure, and linguistic properties. Some studies have shown up to 76 accuracy points across formatting changes in few-shot settings. Linguistic features significantly influence prompt effectiveness—such as morphology, syntax, and lexico-semantic changes—which meaningfully enhance task performance across a variety of tasks. Clausal syntax, for example, improves consistency and reduces uncertainty in knowledge retrieval. This sensitivity persists even with larger model sizes, additional few-shot examples, or instruction tuning.

To address sensitivity of models and make them more robust, several evaluative methods have been proposed. FormatSpread facilitates systematic analysis by evaluating a range of plausible prompt formats, offering a more comprehensive performance interval. Similarly, PromptEval estimates performance distributions across diverse prompts, enabling robust metrics such as performance quantiles and accurate evaluations under constrained budgets.

Prompting techniques

Multi-shot

A prompt may include a few examples for a model to learn from in context, an approach called few-shot learning. For example, the prompt may ask the model to complete "maison → house, chat → cat, chien →", with the expected response being dog.

Chain-of-thought

Chain-of-thought (CoT) prompting is a technique that allows large language models (LLMs) to solve a problem as a series of intermediate steps before giving a final answer. In 2022, Google Brain reported that chain-of-thought prompting improves reasoning ability by inducing the model to answer a multi-step problem with steps of reasoning that mimic a train of thought. Chain-of-thought techniques were developed to help LLMs handle multi-step reasoning tasks, such as arithmetic or commonsense reasoning questions.

When applied to PaLM, a 540 billion parameter language model, according to Google, CoT prompting significantly aided the model, allowing it to perform comparably with task-specific fine-tuned models on several tasks, achieving state-of-the-art results at the time on the GSM8K mathematical reasoning benchmark. It is possible to fine-tune models on CoT reasoning datasets to enhance this capability further and stimulate better interpretability.

As originally proposed by Google, each CoT prompt is accompanied by a set of input/output examples—called exemplars—to demonstrate the desired model output, making it a few-shot prompting technique. However, according to a later paper from researchers at Google and the University of Tokyo, simply appending the words "Let's think step-by-step" was also effective, which allowed for CoT to be employed as a zero-shot technique.

Self-consistency

Self-consistency performs several chain-of-thought rollouts, then selects the most commonly reached conclusion out of all the rollouts.

Tree-of-thought

Tree-of-thought prompting generalizes chain-of-thought by generating multiple lines of reasoning in parallel, with the ability to backtrack or explore other paths. It can use tree search algorithms like breadth-first, depth-first, or beam.

Text-to-image prompting

In 2022, text-to-image models like DALL-E 2, Stable Diffusion, and Midjourney were released to the public. These models take text prompts as input and use them to generate images. Early text-to-image models typically do not understand negation, grammar and sentence structure in the same way as large language models, and may thus require a different set of prompting techniques. The prompt "a party with no cake" may produce an image including a cake.

A text-to-image prompt commonly includes a description of the subject of the art, the desired medium (such as digital painting or photography), style (such as hyperrealistic or pop-art), lighting (such as rim lighting or crepuscular rays), color, and texture. Word order also affects the output of a text-to-image prompt. Words closer to the start of a prompt may be emphasized more heavily.

Artist styles

Some text-to-image models are capable of imitating the style of particular artists by name. For example, the phrase in the style of Greg Rutkowski has been used in Stable Diffusion and Midjourney prompts to generate images in the distinctive style of Polish digital artist Greg Rutkowski. Famous artists such as Vincent van Gogh and Salvador Dalí have also been used for styling and testing.

Textual inversion and embeddings

For text-to-image models, textual inversion performs an optimization process to create a new word embedding based on a set of example images. This embedding vector acts as a "pseudo-word" which can be included in a prompt to express the content or style of the examples.

Image prompting

In 2023, Meta's AI research released Segment Anything, a computer vision model that can perform image segmentation by prompting. As an alternative to text prompts, Segment Anything can accept bounding boxes, segmentation masks, and foreground/background points.

Limitations

The process of writing and refining a prompt for an LLM or generative AI shares some parallels with an iterative engineering design process, such as by discovering reusable best practices through reproducible experimentation. But the techniques that improve performance depend heavily on the specific model being used. Such patterns are also volatile and exhibit significantly different results from seemingly insignificant prompt changes.

Automated prompt generation

Prompt engineering

Recent research has explored automated prompt engineering, using optimization algorithms to generate or refine prompts without human intervention. These automated approaches aim to identify effective prompt patterns by analyzing model gradients, reinforcement feedback, or evolutionary processes, reducing the need for manual experimentation.

Retrieval-augmented generation (RAG)

Retrieval-augmented generation is a technique that enables GenAI models to retrieve and incorporate new information. It modifies interactions with an LLM so that the model responds to user queries with reference to a specified set of documents, using this information to supplement information from its pre-existing training data. This allows LLMs to use domain-specific and/or updated information.

RAG improves large language models by incorporating information retrieval before generating responses. Unlike traditional LLMs that rely on static training data, RAG pulls relevant text from databases, uploaded documents, or web sources. By dynamically retrieving information, RAG enables AI to generate more accurate responses and fewer AI hallucinations without frequent retraining.

Graph retrieval-augmented generation (GraphRAG)

GraphRAG with a knowledge graph combining access patterns for unstructured, structured, and mixed data

GraphRAG (coined by Microsoft Research) is a technique that extends RAG with the use of a knowledge graph to allow the model to connect disparate pieces of information, synthesize insights, and understand summarized semantic concepts over large data collections. It was shown to be effective on datasets like the Violent Incident Information from News Articles.

Using language models to generate prompts

LLMs themselves can be used to compose prompts for LLMs. The automatic prompt engineer algorithm uses one LLM to beam search over prompts for another LLM:

• There are two LLMs. One is the target LLM, and another is the prompting LLM. • Prompting LLM is presented with example input-output pairs, and asked to generate instructions that could have caused a model following the instructions to generate the outputs, given the inputs. • Each of the generated instructions is used to prompt the target LLM, followed by each of the inputs. The log-probabilities of the outputs are computed and added. This is the score of the instruction. • The highest-scored instructions are given to the prompting LLM for further variations. • Repeat until some stopping criteria is reached, then output the highest-scored instructions.

CoT examples can be generated by LLM themselves. In "auto-CoT", a library of questions are converted to vectors by a model such as BERT. The question vectors are clustered. Questions close to the centroid of each cluster are selected, in order to have a subset of diverse questions. An LLM does zero-shot CoT on each selected question. The question and the corresponding CoT answer are added to a dataset of demonstrations. These diverse demonstrations can then added to prompts for few-shot learning.

Automatic prompt optimization

Automatic prompt optimization techniques refine prompts for large language models by automatically searching over alternative prompt strings using evaluation datasets and task-specific metrics:

• MIPRO (Multi-prompt Instruction Proposal Optimizer) optimizes the instructions and few-shot demonstrations of multi-stage language model programs, proposing small changes to module prompts and retaining those that improve a downstream performance metric without access to module-level labels or gradients. • GEPA (Genetic-Pareto) is a reflective prompt optimizer for compound AI systems that combines language-model-based analysis of execution traces and textual feedback with a Pareto-based evolutionary search over a population of candidate systems; across four tasks, GEPA reports average gains of about 10% over reinforcement-learning-based Group Relative Policy Optimization (GRPO) and over 10% over the MIPROv2 prompt optimizer, while using up to 35 times fewer rollouts than GRPO. • Open-source frameworks such as DSPy and Opik expose these and related optimizers, allowing prompt search to be expressed as part of a programmatic pipeline rather than through manual trial and error.

Using gradient descent to search for prompts

In "prefix-tuning", "prompt tuning", or "soft prompting", floating-point vectors are searched directly by gradient descent to maximize the log-likelihood on outputs. An earlier result uses the same idea of gradient descent search, but is designed for masked language models like BERT, and searches only over token sequences, rather than numerical vectors. Formally, it searches for ${\displaystyle \arg \max {\tilde {X}}\sum {i}\log Pr[Y^{i}|{\tilde {X}}\ast X^{i}]}$ where ${\displaystyle {\tilde {X}}}$ ranges over token sequences of a specified length.

History

Prompt engineering

Early precedents of structured user interaction with ruled-based AI systems can be found in enterprise automation software from 1990s. For example, The Intelligent Filling Manager (1999), developed by Krishna C. Mukherjee, used a dynamic Q&A interface driven by rule-based expert system to collect user inputs for generating regulatory filings automatically across jurisdictions. While not involving neural networks, such systems featured prompt-like workflows that influenced later human-in-the-loop AI designs. In 2018, researchers first proposed that all previously separate tasks in natural language processing (NLP) could be cast as question-answer problems over a context. In addition, they trained a first single, joint, multi-task model that would answer any task-related question like "What is the sentiment" or "Translate this sentence to German" or "Who is the president?"

The AI boom saw an increased focus within academic literature and professional practice on applying prompting techniques to get the model to output the desired outcome and avoid nonsensical output, a process characterized by trial-and-error. After the release of ChatGPT in 2022, prompt engineering was soon seen as an important business skill; companies began hiring dedicated prompt engineers, although, given advances in AI's ability to generate prompts better than humans, the employment market for prompt engineers has faced uncertainty. According to The Wall Street Journal in 2025, the job of prompt engineer was one of the hottest in 2023, but has become obsolete due to models that better intuit user intent and to company trainings.

A repository for prompts reported that over 2,000 public prompts for around 170 datasets were available in February 2022. In 2022, the chain-of-thought prompting technique was proposed by Google researchers. In 2023, several text-to-text and text-to-image prompt databases were made publicly available. The Personalized Image-Prompt (PIP) dataset, a generated image-text dataset that has been categorized by 3,115 users, has also been made available publicly in 2024.

Prompt injection

Prompt engineering

Prompt injection is a cybersecurity exploit in which adversaries craft inputs that appear legitimate but are designed to cause unintended behavior in machine learning models, particularly large language models. This attack takes advantage of the model's inability to distinguish between developer-defined prompts and user inputs, allowing adversaries to bypass safeguards and influence model behaviour. While LLMs are designed to follow trusted instructions, they can be manipulated into carrying out unintended responses through carefully crafted inputs.