search
HomeWeb Front-endJS Tutorialechniques for Effective Prompt Engineering

echniques for Effective Prompt Engineering

In Casino Royale (2006), James Bond specifies the precise ingredients for his Vesper martini: 3 measures of Gordons, 1 of Vodka, half a measure of Kina Lillet, shaken over ice with a thin slice of lemon peel.

By detailing the components, Bond ensures a superior drink. Similarly, in interacting with large language models (LLMs), the specificity and clarity of your prompts determine the quality of the output.

This process, known as prompt engineering, is essential for obtaining accurate and relevant responses from AI systems.

What is Prompt Engineering?

Prompt engineering involves crafting precise instructions to optimize LLM responses. The more detailed and specific the input prompt, the more relevant and aligned the output will be with your needs.

Example:
If you ask an LLM, “Summarize prompt engineering,” the response may be vague. However, by specifying the request like this:

Prompt: “Give a 100-word summary of prompt engineering, aimed at non-technical users.”

The LLM is now guided to give a concise, audience-specific answer.

Output:

"Prompt engineering is crafting effective instructions for AI systems like ChatGPT to get the best results. It involves being specific, providing context, and breaking down complex questions. By specifying formats, providing examples, or setting boundaries, prompt engineering ensures clear communication with an AI assistant."

This method of asking for specific outputs demonstrates how to "engineer" a prompt to get a desired, precise result.

Components of a Good LLM Prompt

1 Context: The context provides the LLM with additional information that helps it understand your request more fully. By embedding relevant context, the AI can generate more accurate and tailored responses.

Example:
Suppose you are working on a C# project and want to modify a class definition. The context here could be a code snippet.

Prompt with Context:
"Given this C# code:

public class User { public int UserId { get; set; } public string Name { get; set; } public string Email { get; set; } public string PhoneNumber { get; set; } }

Modify the class to make UserId and Name read-only and set them in the constructor."

Output:

public class User
{
    public int UserId { get; }
    public string Name { get; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }

    public User(int userId, string name)
    {
        UserId = userId;
        Name = name;
    }
}

This example illustrates the importance of providing relevant context to guide the LLM in generating the correct response.

  1. User Question: The question is the main part of the prompt. It should be single-purpose, specific, and concise.

Example:
If you want to create a user class in C# with certain fields, specify the required fields and behavior clearly.

Vague Question:

"Create a user class."

Specific Question:

"Create a C# user class with fields: UserId, Name, PhoneNumber. Make UserId read-only and add a constructor to set these fields."

Output:

public class User
{
    public int UserId { get; }
    public string Name { get; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }

    public User(int userId, string name)
    {
        UserId = userId;
        Name = name;
    }
}
  1. Output Guidance: You can guide the model’s output by providing examples of the format you want.

Example:
If you need to generate dummy data for a User class, provide an example of what the data should look like.

Prompt with Examples:
"Generate 5 instances of the User class with these fields: UserId, Name, Email, PhoneNumber. Use the following format for examples:

var user1 = new User(1, "John Doe", "john.doe@example.com", "555-555-5555");

Here are some examples:

var user2 = new User(2, "Jane Doe", "jane.doe@example.com", "555-555-5556");

Now generate 5 instances."

Output:

public class User
{
    public int UserId { get; }
    public string Name { get; set; }
    public string PhoneNumber { get; set; }

    public User(int userId, string name, string phoneNumber)
    {
        UserId = userId;
        Name = name;
        PhoneNumber = phoneNumber;
    }
}

Techniques for Effective Prompt Engineering

  1. Zero-shot Prompting: The LLM generates a response based on its training data without explicit examples. This is effective for generating generic solutions or answers based on established patterns.

Example:
Prompt: "Create a unit test for the User class using xUnit in C#."

Output:

var user1 = new User(1, "John Smith", "john.smith@example.com", "555-555-5555");
var user2 = new User(2, "Jane Doe", "jane.doe@example.com", "555-555-5556");
var user3 = new User(3, "Mary Johnson", "mary.johnson@example.com", "555-555-5557");
var user4 = new User(4, "David Lee", "david.lee@example.com", "555-555-5558");
var user5 = new User(5, "Linda White", "linda.white@example.com", "555-555-5559");
  1. Few-shot Prompting: Provide several examples to guide the model in generating the desired output format.

Example:
To generate data for a User class, you might use a few example data points to guide the output format.

Prompt with Few-shot Examples:
"Here are some instances of the User class:

var user1 = new User(1, "John Smith", "john.smith@example.com", "555-555-5555");

var user2 = new User(2, "Jane Doe", "jane.doe@example.com", "555-555-5556");

Now create 3 more instances following the same pattern."

Output:

public class UserTests
{
    [Fact]
    public void UserConstructor_SetsProperties()
    {
        // Arrange
        var user = new User(1, "John Doe", "john.doe@example.com", "555-555-5555");

        // Act & Assert
        Assert.Equal(1, user.UserId);
        Assert.Equal("John Doe", user.Name);
        Assert.Equal("john.doe@example.com", user.Email);
        Assert.Equal("555-555-5555", user.PhoneNumber);
    }
}
  1. Prompt Chaining: Iteratively refine your queries based on previous responses, allowing the model to build on earlier interactions.

Example:
Start with a simple prompt and progressively modify it.

First Prompt:

"Create a basic User class in Python."

Output:

public class User
{
    public int UserId { get; }
    public string Name { get; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }

    public User(int userId, string name)
    {
        UserId = userId;
        Name = name;
    }
}

Follow-up Prompt:

"Convert this class to C#."

Output:

public class User
{
    public int UserId { get; }
    public string Name { get; set; }
    public string PhoneNumber { get; set; }

    public User(int userId, string name, string phoneNumber)
    {
        UserId = userId;
        Name = name;
        PhoneNumber = phoneNumber;
    }
}

Final Prompt:

"Make the Password property private, and add a DateTime CreatedAt property initialized in the constructor."

Output:

var user1 = new User(1, "John Smith", "john.smith@example.com", "555-555-5555");
var user2 = new User(2, "Jane Doe", "jane.doe@example.com", "555-555-5556");
var user3 = new User(3, "Mary Johnson", "mary.johnson@example.com", "555-555-5557");
var user4 = new User(4, "David Lee", "david.lee@example.com", "555-555-5558");
var user5 = new User(5, "Linda White", "linda.white@example.com", "555-555-5559");
  1. Chain-of-Thought Prompting: Provide multi-step instructions, helping the LLM approach a complex problem step-by-step.

Example:
Prompt:

*"Create a set of unit tests for the following C# class:

public class User { public int UserId { get; set; } public string Name { get; set; } public string PhoneNumber { get; set; } }

Think step-by-step:

  1. Identify key scenarios to test.
  2. Write unit tests using xUnit.
  3. Consider edge cases."*

Output:

public class UserTests
{
    [Fact]
    public void UserConstructor_SetsProperties()
    {
        // Arrange
        var user = new User(1, "John Doe", "john.doe@example.com", "555-555-5555");

        // Act & Assert
        Assert.Equal(1, user.UserId);
        Assert.Equal("John Doe", user.Name);
        Assert.Equal("john.doe@example.com", user.Email);
        Assert.Equal("555-555-5555", user.PhoneNumber);
    }
}

The article was originally written by Jim, head of Devreal at Pieces for Developers. You can find more examples and nuances in this article https://pieces.app/blog/llm-prompt-engineering

The above is the detailed content of echniques for Effective Prompt Engineering. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.