[KongchangAI]
· 3 min read· 1,855 words

Prompt Engineering in Practice: From Basics to Advanced LLM Prompt Templates

Prompt Engineering in Practice: From Basics to Advanced LLM Prompt Templates

Prompt engineering is structured communication: use role, context, instruction, and constraints with layered patterns to systematically improve LLM output quality.

Based on a long-running Dev.to practice guide, this article systematically lays out the complete knowledge system of prompt engineering. The core framework is the four-component formula ROLE + CONTEXT + INSTRUCTION + CONSTRAINTS, none of which can be missing. Patterns are divided into three levels by complexity: Level 1 includes zero-shot, few-shot, and chain-of-thought; Level 2 covers role + context, task decomposition, and strict JSON output; Level 3 involves ReAct, self-consistency, tree of thoughts, and meta-prompting. The article emphasizes significant model differences—GPT-4 and Claude prefer explicit constraints, open-weight models need more examples and adapt better to XML tags, and models under 7B rely on few-shot and short prompts. The anti-pattern table shows specificity and measurability are core indicators, advocating managing prompts as code assets through template libraries, version control, and iteration to reach over 90% success rate.

Why Prompt Engineering Deserves Systematic Study

Prompt engineering isn't mysticism—it's structured communication. The performance gap between LLM outputs often has less to do with the model itself and more to do with how you organize the input. A long-running practice summary from Dev.to points out that a reusable set of prompt patterns can work consistently across models—whether you're using GPT-4, Claude, or Llama, the core logic is the same.

This article builds on that systematic guide to lay out the complete knowledge system—from zero-shot to tree of thoughts, from the prompt formula to an anti-pattern checklist—and provides templates you can copy and use directly.

rss source: Prompt Engineering Masterclass

The Prompt Formula: Four Components Determine Output Quality

Any effective prompt contains four basic elements:

ROLE + CONTEXT + INSTRUCTION + CONSTRAINTS = GOOD OUTPUT

Take a Python development scenario as an example:

ROLE: You are a senior Python developer
CONTEXT: Building a REST API for a todo app with FastAPI
INSTRUCTION: Create a POST /todos endpoint with validation
CONSTRAINTS: Use Pydantic models, return 201 on success, 422 on validation error

The role defines the scope of the model's knowledge to draw on, the context bounds the problem, the instruction specifies the target action, and the constraints control the output form. Miss any one of these, and the model will fill the gap with its own default assumptions—which is usually not what you want.

Level 1: Basic Patterns

Zero-Shot Instruction

The most direct approach, suitable for tasks that are simple and that the model has been sufficiently trained on. For example, to ask for a Python function that computes compound interest, you only need to specify the parameters and the return value definition. The limitation of zero-shot is that when a task is ambiguous, the model will choose one interpretation on its own.

Few-Shot Examples

Establish a pattern by providing input-output pairs. A typical application is natural language to SQL: after providing three or four examples, the model can more accurately understand the style and granularity of output you expect. Few-shot is especially critical for small models—practical advice is that models under 7B parameters almost always need to be used with examples.

Chain-of-Thought

Ask the model to show its reasoning steps. The classic case is solving the two-trains-meeting problem: the model sequentially calculates the combined speed, the time, and then gives the final answer. Chain-of-thought delivers the most significant improvement on math and logical reasoning tasks.

Level 2: Structured Patterns

Role + Context Pattern

Turning the prompt construction process into a function lets you dynamically assemble prompts in code. The guide provides a build_prompt function that accepts role, context, task, constraints, and examples:

def build_prompt(role, context, task, constraints=None, examples=None):
    parts = [
        f"ROLE: {role}",
        f"CONTEXT: {context}",
        f"TASK: {task}"
    ]
    if constraints:
        parts.append(f"CONSTRAINTS:\n" + "\n".join(f"- {c}" for c in constraints))
    if examples:
        parts.append("EXAMPLES:\n" + "\n\n".join(examples))
    return "\n\n".join(parts)

In actual use, the role is "Expert code reviewer," the context is "Reviewing a PR for a payment processing module," and the constraints include focusing on the OWASP Top 10, checking for injection and authorization bypass, flagging hardcoded secrets, and providing concrete fix code. This structured approach turns prompts themselves into maintainable code assets.

Task Decomposition and Output Format Specification

Break complex tasks into steps and execute them one at a time—for example, when building a complete authentication system, first design the database schema, then implement password hashing, registration endpoints, JWT login, token rotation, password reset, rate limiting, and integration tests. Only let the model execute one step at a time.

Output format specification requires the model to return a strict JSON structure, specifying an issues array and summary statistics, and explicitly stating "No markdown, no explanation — just the JSON object." This is essential in pipelines that need to programmatically parse LLM output.

Level 3: Advanced Patterns

ReAct (Reasoning + Acting)

The ReAct pattern has the model alternate between reasoning and tool calls. The format is a Thought → Action → Action Input → Observation loop, ultimately producing an answer. It is suitable for scenarios that require external information or computation, such as looking up Apple's current market cap and calculating 0.1% of it.

Self-Consistency, Tree of Thoughts, and Meta-Prompting

Self-Consistency asks the model to solve the same problem using three different methods, then compares the results to increase confidence. Tree of Thoughts lists multiple solution paths—for example, when designing a distributed rate limiter, compare five options such as token bucket, sliding window log, and fixed window counter, analyze the pros and cons of each, and then give a recommendation.

Meta-Prompting is using prompts to improve prompts. The original instruction "Write a blog post about AI," after adding target audience, word count, tone, structure, SEO keywords, and a call to action, becomes a creative brief that can be executed directly.

The engineering significance of ReAct: ReAct turns the LLM from a "one-shot generator" into a "loop controller"; in essence, it decouples the reasoning trajectory from external tool calls while alternating between them. The Thought phase produces natural language reasoning, the Action phase outputs structured tool calls (such as search, calculator, or database queries), and the Observation phase injects the tool's returned results into the next round of context. This pattern is the theoretical foundation of today's mainstream agent frameworks (LangChain Agent, LlamaIndex, AutoGPT). In engineering implementation, note that you must set a maximum number of loop steps to prevent infinite loops, Observations should be truncated or summarized to control context length, and you need a fallback strategy for when tool calls fail. Compared with chain-of-thought, ReAct's reasoning is no longer confined to the model's internal knowledge; it can use real data to correct each step's judgment, giving it a clear advantage on tasks that require real-time information, precise computation, or multi-hop retrieval.

The cost-benefit trade-off of the three patterns: Self-consistency, tree of thoughts, and meta-prompting are all strategies that "trade more tokens for higher accuracy," but their cost structures differ. Self-consistency typically samples 3-5 reasoning paths and takes a majority vote; the cost is several times that of a single call, making it suitable for math and logic problems with a unique correct answer. Tree of thoughts introduces explicit branching and pruning of solution options, possibly combined with BFS or DFS search, and the number of calls can reach dozens; it is suitable for open-ended design decisions, but requires a scoring function to judge which paths are better. Meta-prompting is a one-way, one-time enhancement with the lowest cost, and its benefit is concentrated in the step of "turning vague requirements into an executable brief." In practice, it is recommended to first use meta-prompting to clarify requirements, then use self-consistency for key calculations, and enable tree of thoughts only when exploratory decision-making is truly needed, to avoid unnecessary token consumption and latency.

Model Differences and Anti-Patterns

Different models respond to prompts in different ways. GPT-4 and Claude excel at following complex instructions and structured output, and prefer explicit constraints; open-weight models such as Llama and Mistral need more examples and clearer steps, sometimes ignore negative constraints ("don't do X"), and respond better to XML tags than Markdown; small models under 7B must rely on few-shot, short prompts, single tasks, and explicit output formats.

The guide also provides a set of anti-pattern comparisons:

Bad phrasingGood phrasing
"Write code""Write a FastAPI endpoint for user registration with Pydantic validation"
"Make it better""Optimize this query: reduce from 500ms to <50ms, add index suggestion"
"Fix bugs""Fix the race condition in lines 45-52 where concurrent writes corrupt state"
"Explain this""Explain this regex to a junior dev: break down each capture group"
No format requirements"Return ONLY valid JSON matching this schema: {...}"

The pattern is clear: specificity and measurability are the core indicators that distinguish good prompts from bad ones.

Why models respond differently to prompts: The differences mainly come from three layers. The first is training data composition—the instruction tuning and RLHF data for GPT-4 and Claude contains many tasks with structured constraints, so they comply strongly with hard requirements like "Return ONLY valid JSON"; open-weight models are often further trained on community corpora, where instruction-following coverage is narrower. The second is architecture and context window—Claude's long context and preference for XML tags are related to the annotation format used during training, while the Llama series is more easily confused by Markdown-like delimiters, and using explicit tags such as <context>...</context> can significantly improve parsing stability. The third is the trade-off between instruction following and generation capability—models under 7B have limited parameters, and handling long instructions and long outputs at the same time causes degradation, so they must be split into single tasks, short prompts, and forced few-shot examples. Understanding these causes is more transferable to new models than memorizing "model X requires phrasing Y."

Prompt Template Library and Iteration Process

The guide provides three templates you can use directly: code generation (specifying language, project context, requirements, style guide, and testing requirements), code review (including a seven-item checklist and output format), and a debugging assistant (requiring root cause, fix diff, and prevention recommendations).

Before use, it's worth going through an evaluation checklist: Is the role defined? Is context provided? Is the task specific and measurable? Are constraints explicit? Are examples included? Is the output format specified? Does a complex task require steps? Are edge cases mentioned?

The iteration loop is also straightforward: write a prompt → test on 3-5 samples → analyze failures → add constraints or examples → repeat until above 90% success rate → save as a template.

The core idea of this methodology is: manage prompts like code—build a prompt library, use version control, and share with your team. The essence of prompt engineering is clear thinking plus structured expression.

One-line Summary

Prompt engineering is structured communication: use the four elements of role, context, instruction, and constraints plus layered patterns to systematically improve LLM output quality.

Paragraph Summary

Based on a long-running practice guide from Dev.to, this article systematically lays out the complete knowledge system of prompt engineering. The core framework is the four-component formula ROLE + CONTEXT + INSTRUCTION + CONSTRAINTS, none of which can be missing; otherwise the model will fill the gap with its own default assumptions. The patterns are divided into three levels by complexity: Level 1 includes zero-shot, few-shot, and chain-of-thought; Level 2 covers the role + context pattern, task decomposition, and strict JSON output specifications; Level 3 involves ReAct, self-consistency, tree of thoughts, and meta-prompting. The article emphasizes that model responses differ significantly—GPT-4 and Claude prefer explicit constraints, open-weight models need more examples and adapt better to XML tags, and small models under 7B must rely on few-shot and short prompts. The anti-pattern comparison table reveals that specificity and measurability are the core indicators of prompt quality, and it advocates managing prompts as code assets, using a template library, version control, and iterative optimization to achieve above 90% success rate.

#prompt engineering#LLM prompt templates#chain-of-thought#ReAct#tree of thoughts#meta-prompting#few-shot learning
Share:

Related articles