iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🌎

Systematically Learning LLM Prompt Engineering with the Prompt Engineering Guide (Part 2)

に公開

Overview

Continuing from last time, this is a (personal) memo to systematically study the techniques of Prompt Engineering, based on the publicly available Prompt Engineering Guide.
https://github.com/dair-ai/Prompt-Engineering-Guide

This time, I will organize the remaining techniques, excluding Meta prompting. Please refer to the previous article for earlier content.
https://zenn.dev/akitek/articles/36b8bf5ba4af4b

For Busy People

For those who want a quick understanding, here is a table summarizing the techniques introduced this time.
(The content is organized from the original text using ChatGPT)

Technique Features Reference / Link
Automatic Prompt Engineer (APE) - Automatically generates and scores instructions using LLMs
- Treats instruction search as black-box optimization
- Uses Monte Carlo method for semantically preserved reconstruction
Zhou et al., 2022
Active-Prompt - Focuses on selecting effective CoT examples
- Estimates uncertainty of problems to decide annotation targets
- Aims to improve accuracy with only a few effective examples
Diao et al., 2023
Directional Stimulus Prompting (DSP) - Small LM generates hints → augments LLM input
- Trains a hint-generation model (Policy LM) via SFT + RL
- Usable without modifying the LLM itself
Li et al., 2023
PAL (Program-Aided Language Models) - Describes intermediate reasoning in code instead of natural language
- Solves problems using executable code like Python
- Enables coding-like reasoning
Gao et al., 2022
GitHub: PAL
ReAct - Integrates reasoning (Thought) and action (Action)
- Deepens thinking while interacting with external APIs/tools
- Excellent balance of interpretability, flexibility, and performance
Yao et al., 2022
Qiita article
Reflexion - ReAct + self-reflection + memory model
- Three components: Actor, Evaluator, Self-reflection
- Evaluates trajectories to inform next thought
- High interpretability and generality
Shinn et al., 2023
Multimodal CoT - Chain-of-thought integrating text + images
- Two-stage: rationale generation → answer inference
- Small models achieve performance comparable to large LLMs
Zhang et al., 2023
arXiv:2302.14045
Graph Prompting - Introduces the concept of prompting to GNNs
- Formalizes tasks consistently using similarity prediction
- Facilitates leveraging pre-trained knowledge for downstream tasks
Liu et al., 2023
Follow-up: Generalized Graph Prompt

Prompt Engineering

Automatic Prompt Engineer

Numerous studies have shown that including appropriate instructions in prompts is effective for obtaining better responses from LLMs. However, those "appropriate instructions" often rely on the knowledge of the human operator and are created manually.

Zhou et al., 2022 proposed Automatic Prompt Engineer (APE), a framework for automatic instruction generation and selection.
https://arxiv.org/abs/2211.01910

This paper performs automatic generation of appropriate instructions through the following steps. The automatic generation of instructions is called "natural language program synthesis" and is treated as a black-box optimization problem.

Continuing with the explanation following the figure:

  1. First, use an LLM as an inference model to enumerate candidate instructions from a few demonstrations. (In Figure (A), given input-output pairs, the model tries to infer what instruction the teacher might have given. It first lists possible instruction candidates by referring to the input-output pairs. (①))
  2. Next, score each candidate instruction using the LLM. (Each instruction is inserted into the original teacher statement (②), the input from the demonstration is used to generate output, and the log-probability of the generated prediction compared to the true output is calculated as the "plausibility" of each candidate. (③))
  3. Finally, following the Monte Carlo method, the best-scoring instruction from step 2 is varied while preserving its meaning, and the scoring process is repeated. This ultimately yields the best instruction. (In the example, the best-scoring instruction from step 2, "write the antonym of the word", is rephrased as "write the opposite of the word given", and these variations are also scored.)

In other words, this approach is based on the idea that a good instruction is one that captures the essence and maintains its superiority even when the wording changes.

In a previous article, I introduced a study showing that simply adding the phrase "Let's think step by step" to a prompt enables solving complex reasoning tasks.

APE discovered a zero-shot CoT prompt that outperforms this prompt: ("Let's work this out in a step by step way to be sure we have the right answer").

This demonstrates its effectiveness as a framework for generating instructions that lead to more efficient and accurate responses than manual searching.

Active-Prompt

This technique also relates to what constitutes a good example in prompting.
Chain-of-Thought (CoT) is a technique that enables handling complex reasoning processes by creating prompts that explicitly show intermediate reasoning steps.

However, as previously noted, it relies on human-annotated example sets, and there is a risk that these may not be good example sets for different tasks.

Diao et al., 2023 proposed Active Prompt as a method to adapt LLMs to different tasks while using task-specific example prompts.

https://arxiv.org/abs/2302.12246

The main goal is to determine which questions in a pre-defined problem set are important and beneficial for annotation. In other words, in Chain-of-Thought (CoT) Prompting, which incorporates manual intermediate reasoning steps, the motivation is to automatically select problem examples that improve LLM response accuracy even with a small number of examples. Ultimately, it aims to reduce the effort of creating examples.

Roughly, the approach is as follows:

  1. Score questions in the pool (unlabeled)
    • For each question, measure the uncertainty of multiple CoT reasonings generated by the LLM.
    • Questions with high uncertainty are considered difficult for the model.
  2. Active selection of examples
    • Select questions with the highest uncertainty and manually annotate them with CoT steps and answers.
  3. Build example set and infer
    • Use the selected example set as a few-shot prompt.
    • Combine with self-consistency (a type of majority voting labeling) to further improve performance.

Let's organize the specific flow using the figure from the paper.
First, assume a problem set is prepared in advance (Unlabeled Questions). These questions are not yet annotated by humans; they are in a raw state.

The ultimate goal is that, for the task the LLM is about to solve, we want to extract only the truly useful questions from this problem set and instruct humans to annotate them.

Next, integrate Unlabeled Questions with a small number of pre-annotated examples and have the LLM solve them. Here, the LLM answers k times, and the uncertainty of each answer is calculated ((1) Uncertainty Estimation). Then, select questions with high overall average uncertainty ((2) Selection), and instruct humans to provide additional annotations for those questions ((3) Annotation). Finally, use the selected questions and their annotations as examples to evaluate the LLM's responses on the original task ((4) Inference).

Active Prompt is novel in that it applies the idea of active learning to CoT prompting. It is a method that visualizes "what the model is struggling with" and dynamically reinforces examples accordingly.
This way of thinking could provide powerful insights for future prompt design. Moreover, example selection based on uncertainty is also promising in terms of cost efficiency.

Directional Stimulus Prompting

As another approach to the problem of what instructions to include to obtain good responses from LLMs, Li et al., 2023 introduced a small tunable policy language model (e.g., T5) that generates a directional stimulus prompt to guide the output for each input.

https://arxiv.org/abs/2302.11520


The first figure above shows a directional stimulus prompt that includes a Hint in the prompt to obtain a desired summary in a text summarization task.
The second figure shows a framework where a Policy LM is separately prepared to automatically create such stimulus prompts.

Thus, the characteristics of the DSP (Directional Stimulus Prompting) proposed in this paper are:

  1. Stimulus generation by a policy LM
    • Generates discrete stimuli (e.g., keywords, hint words) for the original input, which are used to augment the input to the LLM.
  2. Training method
    • Supervised fine-tuning (SFT): Initially train the stimulus generation model with known labeled data.
    • Reinforcement learning (RL): Fine-tune the policy model using evaluation of the LLM's final output (e.g., ROUGE score, human evaluation) as rewards.
  3. End-to-end design
    • Only the policy model is tuned; the LLM itself remains unchanged as a black box, preserving generality.

This approach appears versatile because it prepares an independent model separate from the LLM to create better instructions, without depending on the LLM's characteristics or capabilities.

https://github.com/reasoning-machines/pal/tree/main

ReAct

LLMs possess both Chain-of-thought (CoT) reasoning ability and the ability to output actions, but these have often been treated separately. Reasoning brings out internal thoughts, while actions require interaction with external tools or APIs. However, there is a limitation: reasoning alone cannot acquire knowledge or correct errors, and actions alone struggle to maintain a consistent thought process.

The proposed method to address this issue is the well-known ReAct (Reason + Act) (Yao et al., 2022). ReAct is a novel method that integrates reasoning (Thought) and action (Action) at the prompt level.

A key feature is that it compensates for the fabrications or errors that traditional CoT tends to fall into by leveraging API interactions, enabling dynamic task handling even in interactive environments. The balance of "few-shot," "high performance," and "visualizable thinking" excels in explainability, practicality, and operational efficiency, making it a potential pillar for future agent design.

As shown in the figure, ReAct involves a cyclic process for a given question: visualizing specific reasoning steps (e.g., "Search") and executing them (e.g., searching for information on Google), repeatedly improving answer accuracy.

Since it's already a well-known technique, I'll leave the detailed explanation to other articles.
https://qiita.com/kzkymn/items/de4e3a17db6e5363705d
https://zenn.dev/yusu29/articles/azure_react_llm

Reflexion

ReAct was a framework for generating better answers by simultaneously repeating reasoning and action processes. However, because it does not consider refining these processes themselves, computational costs increase unnecessarily. Humans, on the other hand, can learn from failures, improve plans, and generate more efficient plans and actions. In other words, LLM agents lack this "self-reflection" capability.

Reflexion, proposed by Shinn et al., 2023, is a framework for enhancing language-based agents through linguistic feedback.

As shown in the figure, Reflexion consists of three different models (LMs):

  1. Actor

    • Generates text and actions based on state observations, thereby producing trajectories.
    • Chain-of-Thought (CoT) and ReAct are used as Actor models.
    • It also includes memory components (short-term memory, long-term memory) to provide additional context to the agent.
  2. Evaluator

    • Scores the output generated by the Actor. Specifically, it takes the generated trajectory (also referred to as short-term memory) as input and outputs a reward score.
    • Different reward functions are used depending on the task.
  3. Self-reflection

    • Generates linguistic reinforcement cues to support self-improvement.
    • This role is fulfilled by an LLM, providing valuable feedback for future trials.
    • To generate specific and relevant feedback, the self-reflection model utilizes reward signals, current trajectories, and persistent memory.
    • These experiences (long-term memory) are used by the agent to quickly improve decision-making.

Reflexion extends the ReAct framework by introducing self-evaluation, self-reflection, and memory components. The figure below shows an example of how a reflexion agent iteratively optimizes its actions to solve various tasks such as decision-making, programming, and reasoning.

For a given Task (a), first generate a trajectory of reasoning and action processes (b). Evaluate the generated trajectory internally (Evaluator) or externally (human) (c). Based on the evaluation, self-reflect on the generated trajectory (d). Store that experience, then generate a new trajectory (e), and so on.

Since all models are LMs (language models), it is considered a highly versatile framework. It also has the following features:

  1. Lightweight and non-fine-tuning: Can be applied quickly without modifying the LLM weights.
  2. Interpretability and transparency: Linguistic reflection makes failure reasons and improvement suggestions explicit, and the learning process is visible.
  3. Flexible feedback forms: Can accommodate various signals such as numerical evaluation, heuristics, and self-tests.

https://arxiv.org/abs/2303.11366

https://arxiv.org/abs/2302.00923
https://arxiv.org/abs/2302.14045

Graph Prompting

Graphs are powerful tools for representing various data abstractly, and with the advent of Graph Neural Networks (GNNs), it has become possible to obtain meaningful latent representations from complex graph structures.

In the context of LLMs, there is a movement to apply the CoT framework to modalities beyond natural language, such as Multi-modal CoT.

An approach targeting graph structures is the Graph Prompt by Liu et al., 2023. This is a new prompting framework for graphs that improves downstream task performance.

Previously, a gap existed between pre-trained general models and their use in specific downstream tasks.

  1. Scarcity of labeled data
    • Downstream tasks like node classification or graph classification require a large amount of task-specific labeled data.
    • However, creating labels involves high expertise and cost (e.g., requiring expert annotation in medical/chemistry fields).
  2. Retraining models for each task
    • Current GNNs need to be retrained for each task by changing the model's output structure and loss function.
    • This leads to a structural mismatch where the architecture and training method differ between pre-training and downstream tasks.

Thinking further, in natural language processing, prompting has been used to bridge the gap between pre-training and downstream tasks. For example, using a pre-trained LLM, various tasks like word prediction or summarization can be solved simply by changing the prompt.

However, for GNNs, prompting cannot yet handle it as well as in NLP, due to the following points:

  • Structures like nodes and subgraphs are different from sequential inputs in NLP, making it difficult to design input formats suitable for prompts.
  • Additionally, since readout functions (pooling) and classifiers need to be changed for each task, it is difficult to directly leverage pre-trained knowledge for downstream tasks.

Consequently, knowledge (representations) gained from pre-training is hard to reuse.

Based on this, the research started from the following question:

"Could we introduce a unified prompt template for GNNs, similar to NLP, to handle pre-training and downstream tasks in a consistent manner?"

The proposed solution consists of two points:

  1. Formulate similarity prediction using subgraph pairs as a common task
    • Both pre-training and downstream tasks can be handled in the same format: "Are these two graphs similar?"
  2. Introduce task-specific prompts to control information extraction
    • Use different prompt vectors for each task in the Readout layer to extract optimal information from the learned representation according to the purpose.

In other words, GraphPrompt bridges the gap between pre-training and task adaptation in GNNs by introducing a "unified template based on structural similarity" + "learnable prompt vectors".

Summarizing the key points, the features are as follows:

  1. Achieves a unified interface by conditioning downstream tasks with prompts.
  2. Ingeniously designs the input format (prompted graph) to flexibly handle multiple tasks.

The proposed method is further extended in the follow-up paper, "Generalized Graph Prompt". Please refer to it as well.
https://arxiv.org/abs/2311.15317

Summary

This article continued from the previous one, aiming to systematically learn about Prompt Engineering techniques based on the publicly available Prompt Engineering Guide.

The techniques covered this time were more advanced than before, including perspectives on "how to generate good prompts" and applications to data beyond natural language.

Some techniques, like ReAct and Reflexion, are now very well-known, while others like Graph Prompt and Multi-modal CoT are gaining attention. Especially for the latter half, since the original Prompt Engineering Guide contains little content on them, I also revisited the papers.

Now, only Meta Prompting remains. This is a type of soft prompting, which is different from the conventional hard prompting that adds prompts in language.

Regarding Meta Prompting, I believe it is necessary to organize the background knowledge separately, so I will explain it in a separate article.

Discussion