Login Sign Up

Mastering Prompt Engineering for LLMs: Strategies and Tactics

Prompt engineering is a crucial skill when working with Large Language Models (LLMs). A well-structured prompt significantly improves response accuracy and relevance. While prompt design is still an evolving discipline, organizations like OpenAI have outlined effective strategies that enhance LLM interactions.

This guide will explore key prompt engineering tactics, provide code examples, and demonstrate how to implement them in a Python script.

Understanding Prompt Engineering

A prompt is the message or instruction given to an LLM to generate an accurate response. The art of crafting effective prompts is known as prompt engineering. This involves structuring the input in a way that maximizes the model’s understanding and output quality.

Here are some proven strategies for better prompting:

  1. Creating Detailed Queries
  2. Adopting Personas
  3. Using Delimiters
  4. Specifying Steps
  5. Providing Examples
  6. Specifying Output Length

We will explore each tactic in detail and demonstrate them using Python code.

Implementing a Prompt Tester in Python

Before diving into the tactics, let’s build a script that loads prompt examples from JSON files and submits them to an LLM.

import os
import json

def list_text_files_in_directory(directory):

    return [f for f in os.listdir(directory) if f.endswith(".json")]

def load_and_parse_json_file(file_path):

    with open(file_path, "r") as file:

        return json.load(file)

def prompt_llm(prompt):

    # Simulating an LLM response (replace with actual API call)

    return f"[LLM Response] {prompt}"

def main():

    directory = "prompts"

    text_files = list_text_files_in_directory(directory)

    if not text_files:

        print("No text files found in the directory.")

        return

    def print_available():

        print("Available prompt tactics:")

        for i, filename in enumerate(text_files, start=1):

            print(f"{i}. {filename}")

    while True:

        try:

            print_available()

            choice = int(input("Enter your choice (0 to exit): "))

            if choice == 0:

                break

            elif 1 <= choice <= len(text_files):

                selected_file = text_files[choice - 1]

                file_path = os.path.join(directory, selected_file)

                prompts = load_and_parse_json_file(file_path)

                print(f"Running prompts for {selected_file}")

                for i, prompt in enumerate(prompts):

                    print(f"PROMPT {i+1} --------------------")

                    print(prompt)

                    print("REPLY ---------------------------")

                    print(prompt_llm(prompt))

            else:

                print("Invalid choice. Please enter a valid number.")

        except ValueError:

            print("Invalid input. Please enter a number.")

if __name__ == "__main__":

    main()

Running Prompt Strategies

This script allows users to select different prompt tactics stored in JSON files and test them against an LLM.

Prompt Engineering Strategies

Now, let’s explore various prompt engineering techniques with examples.

Proven strategies for better prompting
Proven strategies for better prompting

2.1 Creating Detailed Queries

Providing detailed queries enhances the accuracy of responses. Compare the two approaches below:

[

    { "role": "system", "content": "You are a helpful assistant." },

    { "role": "user", "content": "What is an agent?" }

]

Vs. a more specific version:

[

    { "role": "system", "content": "You are a helpful assistant." },

    { "role": "user", "content": "What is a GPT Agent? Please provide three examples." }

]

2.2 Adopting Personas

Personas influence how an LLM responds. This can be useful for generating specialized responses.

[

    { "role": "system", "content": "You are a junior software developer." },

    { "role": "user", "content": "What programming language should I learn?" }

]

[

    { "role": "system", "content": "You are a senior medical professional." },

    { "role": "user", "content": "What are the best ways to stay healthy?" }

]

2.3 Using Delimiters

Delimiters help focus the LLM’s attention on specific text segments.

[

    { "role": "system", "content": "Summarize the text within triple quotes as a haiku." },

    { "role": "user", "content": "'''Mountains stand so tall,\nClouds embrace their lonely peaks,\nSilent world remains.'''" }

]

2.4 Specifying Steps

Breaking down responses into steps makes them structured and coherent.

[

    { "role": "system", "content": "Use the following step-by-step guide:\nStep 1 - Summarize the text.\nStep 2 - Translate it into Spanish." },

    { "role": "user", "content": "I love learning new languages." }

]

2.5 Providing Examples

Examples help guide the model toward structured and predictable responses.

[

    { "role": "system", "content": "Answer all replies in this format:\nUser: Teach me about Python.\nAssistant: Python is a popular programming language." },

    { "role": "user", "content": "Tell me about Java." }

]

2.6 Specifying Output Length

Constraining response length ensures concise answers.

[

    { "role": "system", "content": "Summarize replies in 10 words or less." },

    { "role": "user", "content": "Tell me an interesting fact about Paris." }

]

[

    { "role": "system", "content": "Summarize responses into three bullet points." },

    { "role": "user", "content": "Tell me about the Eiffel Tower." }

]

Mastering prompt engineering can significantly improve the interaction between users and LLMs. By implementing these strategies—such as writing clear instructions, structuring queries, using delimiters, and specifying output formats—you can optimize AI-generated responses for various applications.

Would you like to explore more advanced prompt techniques? you can check our Prompt Engineering tutorials!