Prompt engineering is the process of structuring text that can be interpreted and understood by a generative AI model. A prompt is natural language text describing the task that an AI should perform.
 A prompt for a text-to-text model can be a query such as "what is Fermat's little theorem?", a command such as "write a poem about leaves falling", a short statement of feedback (for example, "too verbose", "too formal", "rephrase again", "omit this word") or a longer statement including context, instructions, and input data. Prompt engineering may involve phrasing a query, specifying a style, providing relevant context or assigning a role to the AI such as "Act as a native French speaker". A prompt may include a few examples for a model to learn from, such as "maison -> house, chat -> cat, chien -> dog", an approach called few-shot learning.
 When communicating with a text-to-image or a text-to-audio model, a typical prompt is 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". Prompting a text-to-image model may involve adding, removing, emphasizing and re-ordering words to achieve a desired subject, style, layout, lighting, and aesthetic.
 Prompt engineering is enabled by in-context learning, defined as a model's ability to temporarily learn from prompts. The ability for in-context learning is an emergent ability of large language models. In-context learning itself is an emergent property of model scale, meaning breaks in downstream scaling laws occur such that its efficacy increases at a different rate in larger models than in smaller models.
 In contrast to training and fine tuning for each specific task, which are not temporary, what has been learnt during in-context learning is of a temporary nature. It does not carry the temporary contexts or biases, except the ones already present in the (pre)training dataset, from one conversation to the other. This result of "mesa-optimization" within transformer layers, is a form of meta-learning or "learning to learn".
 In 2021, researchers finetuned one generatively pretrained model (T0) on performing 12 NLP tasks (using 62 datasets, as each task can have multiple datasets) that showed good performance on new tasks, surpassing models trained directly on just performing one task (without pretraining). To solve a task, T0 is given the task in a structured prompt, for example If {{premise}} is true, is it also true that {{hypothesis}}? ||| {{entailed}}. is the prompt used for making T0 solve entailment.
 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 publicly available.
 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. 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. It allows large language models to overcome difficulties with some reasoning tasks that require logical thinking and multiple steps to solve, such as arithmetic or commonsense reasoning questions.
 For example, given the question "Q: The cafeteria had 23 apples. If they used 20 to make lunch and bought 6 more, how many apples do they have?", a CoT prompt might induce the LLM to answer "A: The cafeteria had 23 apples originally. They used 20 to make lunch. So they had 23 - 20 = 3. They bought 6 more apples, so they have 3 + 6 = 9. The answer is 9."
 As originally proposed, each CoT prompt included a few Q&A examples. This made it a few-shot prompting technique. However, simply appending the words "Let's think step-by-step", has also proven effective, which makes CoT a zero-shot prompting technique. This allows for better scaling as a user no longer needs to formulate many specific CoT Q&A examples.
 When applied to PaLM, a 540B parameter language model, CoT prompting significantly aided the model, allowing it to perform comparably with task-specific fine-tuned models on several tasks, even setting a new state of the art 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.
 Example:
 Chain-of-thought prompting is just one of many prompt-engineering techniques. Various other techniques have been proposed.
 Generated knowledge prompting first prompts the model to generate relevant facts for completing the prompt, then proceed to complete the prompt. The completion quality is usually higher, as the model can be conditioned on relevant facts.
 Example:
 Least-to-most prompting prompts a model to first list the sub-problems to a problem, then solve them in sequence, such that later sub-problems can be solved with the help of answers to previous sub-problems.
 Example:
 Self-consistency decoding performs several chain-of-thought rollouts, then selects the most commonly reached conclusion out of all the rollouts. If the rollouts disagree by a lot, a human can be queried for the correct chain of thought.
 Complexity-based prompting performs several CoT rollouts, then select the rollouts with the longest chains of thought, then select the most commonly reached conclusion out of those.
 Self-refine prompts the LLM to solve the problem, then prompts the LLM to critique its solution, then prompts the LLM to solve the problem again in view of the problem, solution, and critique. This process is repeated until stopped, either by running out of tokens, time, or by the LLM outputting a "stop" token.
 Example critique:
 Example refinement:
 Tree-of-thought prompting generalizes chain-of-thought by prompting the model to generate one or more "possible next steps", and then running the model on each of the possible next steps by breadth-first, beam, or some other method of tree search.
 Maieutic prompting is similar to tree-of-thought. The model is prompted to answer a question with an explanation. The model is then prompted to explain parts of the explanation, and so on. Inconsistent explanation trees are pruned or discarded. This improves performance on complex commonsense reasoning.
 Example:
 Directional-stimulus prompting includes a hint or cue, such as desired keywords, to guide a language model toward the desired output.
 Example:
 By default, the output of language models may not contain estimates of uncertainty. The model may output text that appears confident, though the underlying token predictions have low likelihood scores. Large language models like GPT-4 can have accurately calibrated likelihood scores in their token predictions, and so the model output uncertainty can be directly estimated by reading out the token prediction likelihood scores.
 But if one cannot access such scores (such as when one is accessing the model through a restrictive API), uncertainty can still be estimated and incorporated into the model output. One simple method is to prompt the model to use words to estimate uncertainty. Another is to prompt the model to refuse to answer in a standardized way if the input does not satisfy conditions.[citation needed]
 Prompts often contain a few examples (thus "few-shot"). Examples can be automatically retrieved from a database with document retrieval, sometimes using a vector database. Given a query, a document retriever is called to retrieve the most relevant (usually measured by first encoding the query and the documents into vectors, then finding the documents with vectors closest in Euclidean norm to the query vector). The LLM then generates an output based on both the query and the retrieved documents, this can be a useful technique for proprietary or dynamic information that was not included in the training or fine-tuning of the model.
 Large language models (LLM) themselves can be used to compose prompts for large language models.
 The automatic prompt engineer algorithm uses one LLM to beam search over prompts for another LLM:
 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 nearest to the centroids of each cluster are selected. An LLM does zero-shot CoT on each question. The resulting CoT examples are added to the dataset. When prompted with a new question, CoT examples to the nearest questions can be retrieved and added to the prompt.
 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 AI art images. Text-to-image models typically do not understand grammar and sentence structure in the same way as large language models, and require a different set of prompting techniques.
 A text-to-image prompt commonly includes a description of the subject of the art (such as bright orange poppies), 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.
 The Midjourney documentation encourages short, descriptive prompts: instead of "Show me a picture of lots of blooming California poppies, make them bright, vibrant orange, and draw them in an illustrated style with colored pencils", an effective prompt might be "Bright orange California poppies drawn with colored pencils".
 Word order affects the output of a text-to-image prompt. Words closer to the start of a prompt may be emphasized more heavily.
 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.
 Text-to-image models do not natively understand negation. The prompt "a party with no cake" is likely to produce an image including a cake. As an alternative, negative prompts allow a user to indicate, in a separate prompt, which terms should not appear in the resulting image. A common approach is to include generic undesired terms such as ugly, boring, bad anatomy in the negative prompt for an image.
 Some approaches augment or replace natural language text prompts with non-text input.
 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.
 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.
 In "prefix-tuning", "prompt tuning" or "soft prompting", floating-point-valued vectors are searched directly by gradient descent, to maximize the log-likelihood on outputs.
 Formally, let 
  
    
      
        
          E
        
        =
        {
        
          
            e
            
              1
            
          
        
        ,
        …
        ,
        
          
            e
            
              k
            
          
        
        }
      
    
    {\displaystyle \mathbf {E} =\{\mathbf {e_{1}} ,\dots ,\mathbf {e_{k}} \}}
  
 be a set of soft prompt tokens (tunable embeddings), while 
  
    
      
        
          X
        
        =
        {
        
          
            x
            
              1
            
          
        
        ,
        …
        ,
        
          
            x
            
              m
            
          
        
        }
      
    
    {\displaystyle \mathbf {X} =\{\mathbf {x_{1}} ,\dots ,\mathbf {x_{m}} \}}
  
 and 
  
    
      
        
          Y
        
        =
        {
        
          
            y
            
              1
            
          
        
        ,
        …
        ,
        
          
            y
            
              n
            
          
        
        }
      
    
    {\displaystyle \mathbf {Y} =\{\mathbf {y_{1}} ,\dots ,\mathbf {y_{n}} \}}
  
 be the token embeddings of the input and output respectively. During training, the tunable embeddings, input, and output tokens are concatenated into a single sequence 
  
    
      
        
          concat
        
        (
        
          E
        
        ;
        
          X
        
        ;
        
          Y
        
        )
      
    
    {\displaystyle {\text{concat}}(\mathbf {E} ;\mathbf {X} ;\mathbf {Y} )}
  
, and fed to the large language models (LLM). The losses are computed over the 
  
    
      
        
          Y
        
      
    
    {\displaystyle \mathbf {Y} }
  
 tokens; the gradients are backpropagated to prompt-specific parameters: in prefix-tuning, they are parameters associated with the prompt tokens at each layer;  in prompt tuning, they are merely the soft tokens added to the vocabulary.
 More formally, this is prompt tuning. Let an LLM be written as 
  
    
      
        L
        L
        M
        (
        X
        )
        =
        F
        (
        E
        (
        X
        )
        )
      
    
    {\displaystyle LLM(X)=F(E(X))}
  
, where 
  
    
      
        X
      
    
    {\displaystyle X}
  
 is a sequence of linguistic tokens, 
  
    
      
        E
      
    
    {\displaystyle E}
  
 is the token-to-vector function, and 
  
    
      
        F
      
    
    {\displaystyle F}
  
 is the rest of the model. In prefix-tuning, one provide a set of input-output pairs 
  
    
      
        {
        (
        
          X
          
            i
          
        
        ,
        
          Y
          
            i
          
        
        )
        
          }
          
            i
          
        
      
    
    {\displaystyle \{(X^{i},Y^{i})\}_{i}}
  
, and then use gradient descent to search for 
  
    
      
        arg
        ⁡
        
          max
          
            
              
                Z
                ~
              
            
          
        
        
          ∑
          
            i
          
        
        log
        ⁡
        P
        r
        [
        
          Y
          
            i
          
        
        
          |
        
        
          
            
              Z
              ~
            
          
        
        ∗
        E
        (
        
          X
          
            i
          
        
        )
        ]
      
    
    {\displaystyle \arg \max _{\tilde {Z}}\sum _{i}\log Pr[Y^{i}|{\tilde {Z}}\ast E(X^{i})]}
  
. In words, 
  
    
      
        log
        ⁡
        P
        r
        [
        
          Y
          
            i
          
        
        
          |
        
        
          
            
              Z
              ~
            
          
        
        ∗
        E
        (
        
          X
          
            i
          
        
        )
        ]
      
    
    {\displaystyle \log Pr[Y^{i}|{\tilde {Z}}\ast E(X^{i})]}
  
 is the log-likelihood of outputting 
  
    
      
        
          Y
          
            i
          
        
      
    
    {\displaystyle Y^{i}}
  
, if the model first encodes the input 
  
    
      
        
          X
          
            i
          
        
      
    
    {\displaystyle X^{i}}
  
 into the vector 
  
    
      
        E
        (
        
          X
          
            i
          
        
        )
      
    
    {\displaystyle E(X^{i})}
  
, then prepend the vector with the "prefix vector" 
  
    
      
        
          
            
              Z
              ~
            
          
        
      
    
    {\displaystyle {\tilde {Z}}}
  
, then apply 
  
    
      
        F
      
    
    {\displaystyle F}
  
.
 For prefix tuning, it is similar, but the "prefix vector" 
  
    
      
        
          
            
              Z
              ~
            
          
        
      
    
    {\displaystyle {\tilde {Z}}}
  
 is preappended to the hidden states in every layer of the model.
 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 
  
    
      
        arg
        ⁡
        
          max
          
            
              
                X
                ~
              
            
          
        
        
          ∑
          
            i
          
        
        log
        ⁡
        P
        r
        [
        
          Y
          
            i
          
        
        
          |
        
        
          
            
              X
              ~
            
          
        
        ∗
        
          X
          
            i
          
        
        ]
      
    
    {\displaystyle \arg \max _{\tilde {X}}\sum _{i}\log Pr[Y^{i}|{\tilde {X}}\ast X^{i}]}
  
 where 
  
    
      
        
          
            
              X
              ~
            
          
        
      
    
    {\displaystyle {\tilde {X}}}
  
 is ranges over token sequences of a specified length.
 Prompt injection is a family of related computer security exploits carried out by getting a machine learning model (such as an LLM) which was trained to follow human-given instructions to follow instructions provided by a malicious user. This stands in contrast to the intended operation of instruction-following systems, wherein the ML model is intended only to follow trusted instructions (prompts) provided by the ML model's operator.
 A language model can perform translation with the following prompt:
 followed by the text to be translated. A prompt injection can occur when that text contains instructions that change the behavior of the model:
 to which GPT-3 responds: "Haha pwned!!". This attack works because language model inputs contain instructions and data together in the same context, so the underlying engine cannot distinguish between them.
 Common types of prompt injection attacks are:
 Prompt injection can be viewed as a code injection attack using adversarial prompt engineering. In 2022, the NCC Group characterized prompt injection as a new class of vulnerability of AI/ML systems.
 In early 2023, prompt injection was seen "in the wild" in minor exploits against ChatGPT, Bard, and similar chatbots, for example to reveal the hidden initial prompts of the systems, or to trick the chatbot into participating in conversations that violate the chatbot's content policy. One of these prompts was known as "Do Anything Now" (DAN) by its practitioners.
 For LLM that can query online resources, such as websites, they can be targeted for prompt injection by placing the prompt on a website, then prompt the LLM to visit the website. Another security issue is in LLM generated code, which may import packages not previously existing. An attacker can first prompt the LLM with commonly used programming prompts, collect all packages imported by the generated programs, then find the ones not existing on the official registry. Then the attacker can create such packages with malicious payload and upload them to the official registry.
 Since the emergence of prompt injection attacks, a variety of mitigating countermeasures have been used to reduce the susceptibility of newer systems. These include input filtering, output filtering, Reinforcement learning from human feedback, and prompt engineering to separate user input from instructions.
 In October 2019, Junade Ali and Malgorzata Pikies of Cloudflare submitted a paper which showed that when a front-line good/bad classifier (using a neural network) was placed before a Natural Language Processing system, it would disproportionately reduce the number of false positive classifications at the cost of a reduction in some true positives. In 2023, this technique was adopted an open-source project Rebuff.ai to protect prompt injection attacks, with Arthur.ai announcing a commercial product - although such approaches do not mitigate the problem completely.
 By August 2023, leading Large Language Model developers were still unaware of how to stop such attacks. In September 2023, Junade Ali shared that he and Frances Liu had successfully been able to mitigate prompt injection attacks (including on attack vectors the models had not been exposed to before) through giving Large Language Models the ability to engage in metacognition (similar to having an inner monologue) and that they held a provisional United States patent for the technology - however, they decided to not enforce their intellectual property rights and not pursue this as a business venture as market conditions were not yet right (citing reasons including high GPU costs and a currently limited number of safety-critical use-cases for LLMs).
 Ali also noted that their market research had found that Machine Learning engineers were using alternative approaches like prompt engineering solutions and data isolation to work around this issue.