Stackvora.tech

Prompt Engineering Patterns

The efficacy of large language models (LLMs) in various applications hinges significantly on the quality and structure of the input prompts. Crafting…

The efficacy of large language models (LLMs) in various applications hinges significantly on the quality and structure of the input prompts. Crafting effective prompts, known as prompt engineering, moves beyond simple natural language requests to a more systematic approach, often employing recurring patterns to achieve predictable and desired outputs. This article details several foundational prompt engineering patterns, illustrating their application with practical examples and discussing their impact on LLM behavior.

Understanding and applying these patterns allows engineers, consultants, and developers to leverage LLMs more predictably, reducing trial-and-error and improving output quality for tasks ranging from content generation and data extraction to complex reasoning and code generation.

The Role-Task-Constraints-Format Pattern

This pattern structures a prompt by clearly defining four key components: the LLM's designated Role, the specific Task it needs to perform, any Constraints or rules governing the task, and the desired Format for the output. This comprehensive structure guides the LLM precisely, minimizing ambiguity.

Role Definition

Assigning a role helps the LLM adopt a specific persona or knowledge domain, influencing its tone, vocabulary, and interpretation of the task. Examples include "You are a senior cybersecurity analyst," "Act as a Python developer," or "You are an expert technical writer."

Task Specification

The task describes what the LLM needs to accomplish. It should be explicit and avoid vague language. Instead of "Write something," use "Summarize the following technical document" or "Generate five different headlines for a blog post about serverless architecture."

Constraints and Rules

Constraints are critical for guiding the LLM's output within acceptable boundaries. These can include length limits, exclusion of certain topics, adherence to specific style guides, or factual requirements. For instance, "Summary must be under 150 words," "Do not use jargon," or "Ensure all facts are verifiable and cited from the provided text."

Output Format

Specifying the output format is crucial for downstream processing, especially when integrating LLM outputs into other systems or databases. Common formats include JSON, XML, markdown tables, bulleted lists, or specific natural language structures. Explicitly stating the format, e.g., "Output as a JSON object with keys 'title' and 'summary'," ensures parseability.


You are a senior network engineer.
Your task is to explain the difference between TCP and UDP.
Constraints:
- Explain it to a junior network technician.
- Focus on how it impacts application behavior and troubleshooting.
- Limit the explanation to approximately 200 words.
- Do not use complex mathematical formulas or overly academic language.
Format:
Provide the explanation as a bulleted list, with a brief introduction and conclusion.

Few-Shot and Multi-Shot Prompting for Tone and Style

While zero-shot prompting (providing no examples) is common, few-shot or multi-shot prompting significantly improves an LLM's ability to match a specific tone, style, or output pattern. This involves providing one or more examples of desired input-output pairs within the prompt itself.

Establishing Tone

To achieve a specific tone (e.g., formal, informal, humorous, authoritative), provide examples of text written in that tone. The LLM will then attempt to emulate this style in its response to the actual query.


Example 1 (Formal Tone):
Input: "Tell me about the new firewall appliance."
Output: "The recently deployed firewall appliance, model XFS-7000, offers advanced threat detection capabilities and enhanced throughput for enterprise-grade network security. Its comprehensive feature set includes stateful packet inspection, deep packet inspection, and intrusion prevention system functionalities, addressing a critical need for robust perimeter defense."

Example 2 (Informal Tone):
Input: "What's up with the new firewall?"
Output: "Hey! So, the new firewall, the XFS-7000, is pretty sweet. It's got all these fancy features like deep packet inspection and an IPS to really lock down our network. Should make things a lot safer and faster for us."

Now, using a similar formal tone, tell me about the recent firmware update for the core switch.

Emulating Output Patterns

Beyond tone, few-shot examples are invaluable for teaching the LLM complex output structures or logical reasoning patterns. This is particularly useful when the desired output isn't a standard format but follows a specific, non-obvious logic. For example, demonstrating how to extract specific entities from unstructured text and present them in a particular custom JSON structure.

Guiding with Chain-of-Thought (CoT)

The Chain-of-Thought (CoT) prompting pattern encourages the LLM to articulate its reasoning process before providing a final answer. This often leads to more accurate and robust outputs, particularly for complex reasoning tasks, by forcing the model to "think step-by-step."

Enabling Intermediate Steps

By adding phrases like "Let's think step by step," "Explain your reasoning," or "Walk me through your process," the LLM is prompted to generate intermediate thoughts that guide it to a more correct final answer. This is especially effective in mathematical problems, logical deductions, or multi-stage problem-solving.


Consider the following network topology:
Router A is connected to Switch B.
Switch B is connected to Server C and Firewall D.
Firewall D is connected to the Internet.
If the link between Router A and Switch B goes down, which devices lose connectivity to the Internet?

Let's think step by step.
1. Identify the path from Server C to the Internet: Server C -> Switch B -> Router A -> ... Wait, this path is incorrect.
2. Correct path: Server C -> Switch B -> Firewall D -> Internet.
3. Identify the path from Router A to the Internet: Router A -> Switch B -> Firewall D -> Internet.
4. If the link between Router A and Switch B goes down, Router A loses its connection to Switch B.
5. Consequently, Router A loses connectivity to Firewall D and thus the Internet.
6. Server C's path to the Internet (Server C -> Switch B -> Firewall D -> Internet) does not directly involve the link between Router A and Switch B.
7. Therefore, only Router A loses connectivity to the Internet.

Final Answer: Router A.

While the example above includes the CoT in the prompt itself, often the prompt is simply "Explain your reasoning before giving the final answer." or "Let's think step by step." appended to the question, and the LLM generates the CoT itself.

Strict Output Formatting with JSON

When the LLM's output needs to be programmatically consumed, strict adherence to a specific data format like JSON is paramount. LLMs can be encouraged, and often forced, to produce valid JSON by careful prompting.

Defining the Schema

Provide a clear JSON schema or an example of the desired JSON structure. Explicitly state that the output must be valid JSON. Emphasize key names, data types for values, and any nested structures.


Extract the following information from the provided text about a server rack:
- Rack Identifier (string)
- Number of Units (integer)
- Location (string, e.g., "Datacenter A, Row 5")
- Power Consumption (float, in Watts)
- Installed Devices (array of strings, listing device names)

Output the information as a valid JSON object.

Text:
"Rack-017 is located in Datacenter A, Row 5. It is a 42U rack currently consuming 1250.5 watts. Installed devices include Cisco Catalyst 9300, Dell PowerEdge R750, and a Palo Alto PA-440 firewall."

Expected Output Structure:


{
  "rack_identifier": "Rack-017",
  "number_of_units": 42,
  "location": "Datacenter A, Row 5",
  "power_consumption": 1250.5,
  "installed_devices": [
    "Cisco Catalyst 9300",
    "Dell PowerEdge R750",
    "Palo Alto PA-440 firewall"
  ]
}

Some LLM APIs (e.g., OpenAI's GPT-4o, Google's Gemini Pro 1.5) now offer dedicated JSON mode features that guarantee valid JSON output, significantly simplifying this pattern. When available, prefer using the API's native JSON mode over relying solely on prompt instructions for strict compliance.

Delimiters for Context Isolation

Using clear delimiters helps the LLM distinguish between instructions, context, and examples within a single prompt. This prevents the LLM from misinterpreting parts of the prompt as instructions or attempting to respond to the context itself.

Common Delimiters

  • Triple backticks: ```text```
  • Triple quotes: """text"""
  • XML tags: <context>text</context>
  • Specific keywords: ###START_CONTEXT### text ###END_CONTEXT###

You are an IT support specialist.
Analyze the following user problem and provide a solution.
The user problem is enclosed in triple backticks.

```
My VPN client (Cisco AnyConnect 4.10) keeps disconnecting after about 5 minutes,
even when my internet connection is stable. I'm running Windows 11.
I've tried restarting my computer and the VPN client multiple times.
```

Your solution should include:
1. Two common troubleshooting steps.
2. One advanced troubleshooting step.
3. A recommendation for further action if the issue persists.

This ensures the LLM understands that the text within the backticks is the problem description to be analyzed, not part of the instructions for its own output.

Troubleshooting and Common Pitfalls

  • Vague Instructions: LLMs will attempt to interpret ambiguous requests, often leading to undesirable or irrelevant outputs. Be as specific as possible with roles, tasks, constraints, and formats.
  • Conflicting Constraints: For example, asking for "a detailed explanation" and simultaneously "under 50 words." Such conflicts can lead to truncated or nonsensical responses.
  • Over-constraining: While constraints are good, too many rigid rules can stifle the LLM's creativity or ability to generate a coherent response, potentially leading to repetitive or overly simplistic outputs.
  • Ignoring API Features: Always check if the LLM API you're using offers specific features (e.g., JSON mode, tool calling) that can achieve your goal more robustly than prompt engineering alone.
  • Lack of Iteration: Prompt engineering is iterative. Rarely is the first prompt perfect. Test, evaluate outputs, and refine your prompts based on observed deficiencies.
  • Model Drift: LLM behavior can subtly change across different versions or even over time for the same version. What worked perfectly yesterday might be slightly off today. Regular re-evaluation of critical prompts is advisable.

Back to the knowledge base · Ask the AI assistant