Prompt engineering

From FerroxLabs/wayland · View interactive version

Prompt engineering is an AI agent skill from the GitHub repository FerroxLabs/wayland. Guides expert-level prompt engineering implementation: ai-ml and best-practices decision frameworks, production-ready patterns, and concrete templates for prompt engineering workflows. Use when the user asks about prompt engineering, prompt engineering configuration, or ai-ml best practices for prom

How to use this skill

Skill file

Prompt Engineering

When to Use

Use this skill when:

Do NOT use this skill when:


Process

1. Clarify the Task Taxonomy and Success Criteria

Before writing a single token of a prompt, establish what kind of task the LLM must perform and what "correct" looks like.

2. Select the Prompting Strategy

The choice of prompting technique should be driven by task complexity and available examples, not by default habit.

3. Design the Prompt Architecture

Structure the prompt as a hierarchy of components. Each component has a specific role.

4. Handle Context Window Management

Context window overflow is the most common production failure mode for prompt engineering systems.

5. Set Model Parameters Deliberately

Model parameters are part of the prompt engineering decision space, not afterthoughts.

6. Build a Prompt Evaluation Framework

A prompt that "seems to work" on 3 examples is not a production-ready prompt. Systematic evaluation is non-negotiable.

7. Implement Prompt Versioning and Management

Prompts are code. They require the same versioning, review, and deployment discipline as application code.

8. Harden for Production

Prompts in production face adversarial inputs, model API changes, and edge cases that evaluation sets do not cover.


Output Format

Deliver prompt engineering guidance in the following structure, adapted to the user's specific task:


Prompt Design Document

Task Classification: [extraction | classification | generation | reasoning | transformation | code]

Model Target: [e.g., GPT-4o, Claude 3.5 Sonnet, Llama 3.1 70B]

Prompting Strategy: [zero-shot | few-shot (N examples) | chain-of-thought | structured output | ReAct]

Estimated Token Cost per Request: [prompt tokens] + [completion tokens] = [total tokens]


System Prompt:

[Full system prompt text, ready to use]

User Message Template:

[Full user message template with {{variable}} placeholders marked]

Few-Shot Examples (if applicable):

Example 1:
Input: [realistic example input]
Output: [exact expected output]

Example 2:
Input: [realistic example input]
Output: [exact expected output]

Output Schema (if structured output):

{
  "field_name": "string -- description of field",
  "field_name_2": "number -- description of field",
  "field_name_3": ["array", "of", "strings"]
}

Model Parameters:

| Parameter | Value | Rationale |

|-----------|-------|-----------|

| temperature | 0.0 | Extraction task -- determinism required |

| max_tokens | 500 | 2x expected output length |

| top_p | 1.0 | Not needed at temperature 0 |

| stop sequences | ["\n\n"] | Prevent runaway generation |

Evaluation Criteria:

| Criterion | Metric | Target Threshold |

|-----------|--------|-----------------|

| Format compliance | JSON parse success rate | > 99% |

| Field extraction accuracy | Exact match per field | > 90% |

| Latency | p95 response time | < 3 seconds |

Known Failure Modes:

Prompt Version: v1.0.0

Evaluation Dataset Size: [N] examples

Baseline Score: [metric] = [value]

This Prompt Score: [metric] = [value]


Rules

  1. Never write a production prompt without a golden evaluation dataset. A prompt that "looks good" on 3 hand-picked examples has unknown real-world performance. Minimum viable evaluation set is 30 examples; 100+ is production-ready. Intuition about LLM behavior is unreliable -- measure everything.
  1. Never mix instructions with data without explicit delimiters. Undelimited user content can override system instructions (prompt injection). Always wrap dynamic content in XML tags (<document>, <user_input>) or triple-quoted blocks. Validate that user content does not contain your delimiter tokens.
  1. Always specify the output format in the system prompt AND demonstrate it with an example. Telling the model "respond in JSON" without showing the exact schema produces inconsistent field names, nesting depth, and data types. Schema documentation reduces format errors by 60-80% in practice.
  1. Never use temperature > 0.2 for extraction, classification, or structured output tasks. High temperature introduces unnecessary variability and increases format compliance failure rates. Reserve high temperature for creative tasks where diversity is the goal.
  1. Always version-control prompts as code artifacts. A prompt changed without documentation is a deployment without version control. Within 3 months, teams consistently lose track of which prompt version is in production and why changes were made. Use a prompts/ directory in the repository with changelogs.
  1. Never rely on negative instructions as the primary constraint. "Do not include personal opinions" is weaker than "Respond only with facts sourced from the provided document." LLMs respond better to positive action directives. Use negative instructions only as secondary reinforcement of a positive instruction.
  1. Always calculate token budgets before deployment. For every prompt template, compute: (system prompt tokens) + (max few-shot tokens) + (max input tokens) + (reserved output tokens). This sum must be below the model's context limit. Alert if production inputs approach 80% of the available input budget.
  1. Never change more than one significant prompt element at a time during optimization. Changing the role definition, few-shot examples, and output format simultaneously makes it impossible to attribute performance changes. Iterate one element at a time, measuring against the evaluation set after each change.
  1. Always implement output validation before the output reaches application logic. Parse JSON before using it. Assert classification labels are in the allowed set. Check generation length constraints. Treat LLM output as untrusted external data, not as guaranteed structured data from an internal system.
  1. Never assume a prompt that works on one model will work identically on another. GPT-4o, Claude 3.5 Sonnet, and Llama 3.1 70B have different instruction-following behaviors, JSON formatting tendencies, refusal patterns, and sensitivity to prompt phrasing. When switching models, re-evaluate on the full golden dataset and expect to make prompt adjustments.

Edge Cases

Inconsistent Output Format Despite Format Instructions

The model intermittently produces valid JSON for 90% of requests but returns markdown-wrapped JSON or partial JSON for the remaining 10%. This is one of the most common production issues.

Handling:

Long Documents Exceeding Context Window

The user wants to extract information from a 50-page contract (approximately 40,000 tokens) using a model with a 16,384-token context window.

Handling:

Model Refusals on Legitimate Business Content

The model refuses to process content or returns a safety refusal on legitimate business content -- for example, declining to summarize a legal document mentioning criminal activity, or refusing to analyze medical records for legitimate clinical applications.

Handling:

Prompt Performance Degrades After Model Update

A prompt that scored 94% accuracy in March scores 87% accuracy in June after the model provider pushed an undisclosed update.

Handling:

Multi-Language or International Inputs

The application receives inputs in Spanish, Portuguese, German, and English. The prompt was written in English and performs well on English inputs but degrades on other languages.

Handling:

Hallucination in Factual Extraction Tasks

The model extracts plausible-but-incorrect data -- fabricating a date, inventing a company name, or generating a revenue figure that does not appear in the source document.

Handling:

Token Cost Exceeding Budget at Scale

A prompt with a 2,000-token system prompt + 500-token input + 300-token output runs fine in development, but at 100,000 daily requests, the GPT-4o cost is $280/day, exceeding the budget.

Handling:


Example

Input from user: "I need to build a production prompt that extracts structured data from customer support emails. The emails arrive in English and Spanish, contain customer complaints, and I need to extract: the product mentioned, the issue category (billing, shipping, technical, other), the urgency level (low, medium, high), and whether the customer explicitly requested a refund. We're using GPT-4o. Our team processes 5,000 emails per day."


Prompt Design Document

Task Classification: Extraction + Classification

Model Target: GPT-4o (recommended: gpt-4o-2024-08-06 for version pinning)

Prompting Strategy: Few-shot (3 examples) + structured output (JSON mode)

Estimated Token Cost per Request: ~400 tokens prompt + ~80 tokens completion = ~480 tokens

Estimated Daily Cost at 5,000 emails: ~2.4M tokens/day ≈ $6.00/day at GPT-4o pricing (as of mid-2024)


System Prompt:

You are a customer support data analyst. Your job is to extract structured information from customer support emails.

Extract the following fields from each email:
- product: The specific product or service mentioned by the customer. Use the exact name as written in the email. If no product is mentioned, use null.
- issue_category: Classify the primary issue into exactly one of: "billing", "shipping", "technical", "other". Use the customer's primary complaint to determine the category.
- urgency: Classify urgency as "high", "medium", or "low" based on the following criteria:
  - high: Customer uses urgent language ("immediately", "ASAP", "urgent"), mentions legal action, or indicates a time-sensitive situation
  - medium: Customer expresses frustration or has been waiting more than one week
  - low: Customer is inquiring or reporting a non-urgent issue
- refund_requested: true if the customer explicitly asks for a refund, chargeback, or their money back. false otherwise. Do not infer -- only mark true if the customer explicitly requests it.

Rules:
- You will receive emails in English and Spanish. Process both languages identically.
- Output only a raw JSON object. Do not include explanations, markdown formatting, or any text outside the JSON.
- If a field cannot be determined from the email content, use null.
- Base all extractions only on the email content provided. Do not infer information not present in the email.

User Message Template:

Extract the structured data from the following customer email.

<email>
{{email_body}}
</email>

Output only the JSON object with fields: product, issue_category, urgency, refund_requested.

Few-Shot Examples:

Include these examples in the user message, before the live input, to anchor output format and classification behavior:

Example 1:
<email>
Hi, I ordered the ProDesk Keyboard three weeks ago and it still hasn't arrived. 
My order number is #44821. This is unacceptable -- I needed it for a presentation last week. 
Please tell me where my order is.
</email>
Output: {"product": "ProDesk Keyboard", "issue_category": "shipping", "urgency": "high", "refund_requested": false}

Example 2:
<email>
Hola, me cobraron dos veces por mi suscripción al plan Premium este mes. 
Pueden revisar mi cuenta? Mi correo es maria@example.com. 
Me gustaría que me devolvieran el cargo duplicado.
</email>
Output: {"product": "plan Premium", "issue_category": "billing", "urgency": "medium", "refund_requested": true}

Example 3:
<email>
The mobile app keeps crashing when I try to open my account settings. 
I'm using an iPhone 14. It's been happening for two days. Not a huge rush but 
wanted to let you know.
</email>
Output: {"product": "mobile app", "issue_category": "technical", "urgency": "low", "refund_requested": false}

Output Schema:

{
  "product": "string or null -- exact product name as mentioned in email",
  "issue_category": "billing | shipping | technical | other",
  "urgency": "high | medium | low",
  "refund_requested": "boolean -- true only if explicitly requested"
}

Model Parameters:

| Parameter | Value | Rationale |

|-----------|-------|-----------|

| temperature | 0.0 | Classification/extraction -- determinism required |

| max_tokens | 120 | JSON output is ~60-80 tokens; 120 provides headroom |

| top_p | 1.0 | Not tuned alongside temperature = 0 |

| response_format | {"type": "json_object"} | Use GPT-4o JSON mode to guarantee valid JSON |

| stop sequences | None needed | JSON mode handles output termination |

| model | gpt-4o-2024-08-06 | Pin to specific version to prevent drift |

Evaluation Criteria:

| Criterion | Metric | Target Threshold |

|-----------|--------|-----------------|

| JSON parse success rate | Successful parses / total requests | > 99.5% |

| Product extraction accuracy | Exact or near-exact match | > 92% |

| Issue category accuracy | Exact match vs. human label | > 90% |

| Urgency classification accuracy | Exact match vs. human label | > 85% |

| Refund field precision | Precision (avoid false positives) | > 97% |

| Latency p95 | API response time | < 4 seconds |

Known Failure Modes:

Prompt Version: v1.0.0

Evaluation Dataset Size: 120 labeled emails (80 English, 40 Spanish) across all four issue categories

Target Baseline (naive prompt, no few-shot): issue_category accuracy = 78%, refund precision = 91%

This Prompt Target: issue_category accuracy = 91%+, refund precision = 97%+


Implementation Note -- Python Integration:

import openai
import json
from typing import Optional

SYSTEM_PROMPT = open("prompts/email_extraction/v1.0.0/system.txt").read()
USER_TEMPLATE = open("prompts/email_extraction/v1.0.0/user_template.txt").read()

def extract_email_data(email_body: str, client: openai.OpenAI) -> Optional[dict]:
    """
    Extract structured data from a customer support email.
    Returns parsed dict on success, None on unrecoverable failure.
    """
    user_message = USER_TEMPLATE.replace("{{email_body}}", email_body)

    try:
        response = client.chat.completions.create(
            model="gpt-4o-2024-08-06",
            messages=[
                {"role": "system", "content": SYSTEM_PROMPT},
                {"role": "user", "content": user_message}
            ],
            temperature=0.0,
            max_tokens=120,
            response_format={"type": "json_object"}
        )
        raw_output = response.choices[0].message.content
        result = json.loads(raw_output)

        # Output validation
        assert result.get("issue_category") in {"billing", "shipping", "technical", "other", None}
        assert result.get("urgency") in {"high", "medium", "low", None}
        assert isinstance(result.get("refund_requested"), bool)

        return result

    except (json.JSONDecodeError, AssertionError, KeyError) as e:
        # Log failure with raw output for debugging
        # logger.error(f"Extraction failed: {e}, raw_output: {raw_output}")
        return None  # Caller routes to fallback processing queue

This implementation stores prompts as files (enabling version control diffs), validates output before returning it, and returns None on failure rather than raising -- allowing the caller to route failed extractions to a human review queue without crashing the pipeline.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.