Prompting: zero-shot, few-shot, chain-of-thought, structured output
The cheapest and fastest way to improve LLM results is a better prompt. Learn the anatomy of a good prompt, zero- and few-shot prompting, chain-of-thought, system prompts, and how to get reliable JSON out of a model.
A Prompt is everything you send to the model: instructions, context, examples and the question. Prompt engineering is the practice of designing prompts that produce reliable results. It needs no training, no GPU and no dataset — just clear thinking — which makes it the first tool to reach for before fine-tuning or RAG.
Anatomy of a good prompt
- Role and context — who the model is acting as and for whom (“You are a support agent for an online bookstore; users are non-technical”).
- Task — one clear, specific instruction, stated positively (“Summarize in 3 bullet points” beats “Don’t write too much”).
- Input data, clearly delimited — wrap documents in tags or fences such as
<document>…</document>so instructions and data do not mix. - Constraints — length, language, tone, what to do when information is missing (“If the answer is not in the document, say you don’t know”).
- Output format — bullet list, table, JSON with a schema, or a fixed template.
- Examples — one to a few input→output pairs that show exactly what you mean.
| Weak prompt | Better prompt |
|---|---|
| “Write about LoRA.” | “Explain LoRA to a backend developer who knows Python but not ML, in 150 words, with one analogy and one code-free example. End with when *not* to use it.” |
| “Is this review good?” | “Classify the sentiment of the review inside <review> tags as positive, negative or mixed. Reply with one word only.” |
Zero-shot and few-shot prompting
[[zero-shot|Zero-shot]] prompting gives only instructions. [[few-shot|Few-shot]] prompting adds a handful of worked examples. GPT-3 showed that large models can pick up a task from such examples without any weight update — In-context learning[1]. Examples are the most powerful way to pin down format, label set and tone, but the model also copies their quirks: if all your examples are short and positive, outputs drift that way.
Classify each customer message as one of: shipping, refund, product_question, other.
Answer with the label only.
Message: "Paket saya belum sampai padahal sudah 5 hari."
Label: shipping
Message: "Can I get my money back? The shoes are too small."
Label: refund
Message: "Apakah buku ini tersedia dalam versi bahasa Inggris?"
Label: product_question
Message: "{new_message}"
Label:Chain-of-thought: let the model think first
Each generated token gets a fixed amount of computation, so asking for an answer immediately gives the model little “thinking room”. [[chain-of-thought|Chain-of-thought]] (CoT) prompting asks the model to write intermediate reasoning steps before the final answer, which substantially improves multi-step math and logic in large models[2]. Even the zero-shot phrase “Let’s think step by step” helps[3]. Self-consistency samples several reasoning paths at a moderate temperature and takes a majority vote on the final answer[4].
- mode{ a₁, a₂, …, a_n }
- the most frequent value in the list (majority vote)
- a_i
- final answer extracted from the i-th sampled Chain-of-thought (CoT)
- n
- number of samples (e.g. 5–40); cost grows linearly with n
- ∼
- “is sampled from”
- T > 0
- a non-zero Temperature, so the reasoning paths differ
▸Worked example
System prompts and chat roles
Chat APIs take a list of messages with roles: system (persistent instructions from the developer), user and assistant. The System prompt is where you put the persona, rules, tone and output conventions that apply to the whole conversation. Under the hood a chat template turns these messages into one token sequence with special markers. Remember: the system prompt steers behaviour but is not a security boundary — users and documents can try to override it (prompt injection), and its contents can leak.
from openai import OpenAI
from transformers import AutoTokenizer
messages = [
{"role": "system", "content": "You are a concise support agent for an Indonesian "
"online bookstore. Answer in Bahasa Indonesia, max 80 words. "
"If you are not sure, say so and suggest contacting support."},
{"role": "user", "content": "Bagaimana cara mengembalikan buku yang rusak?"},
]
client = OpenAI() # API key from env; pass base_url=... for any compatible server
resp = client.chat.completions.create(model="MODEL_NAME", messages=messages,
temperature=0.3, max_tokens=300)
print(resp.choices[0].message.content)
# For open models, the chat template renders the same messages into tokens:
tok = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
print(tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True))Structured output
When a program consumes the output, ask for JSON that follows an explicit schema, keep temperature low, and validate the result. Most providers offer a JSON mode, schema-constrained “structured outputs”, or tool/function schemas that make valid JSON far more reliable[5][6]. Still validate: fields can be missing or values wrong even when the syntax is valid.
import json
from pydantic import BaseModel, ValidationError
class Invoice(BaseModel):
vendor: str
total: float
currency: str # ISO code, e.g. "IDR"
schema = json.dumps(Invoice.model_json_schema())
prompt = ("Extract vendor, total and currency from the invoice in <doc> tags. "
"Reply with JSON only, matching this JSON schema: " + schema +
" <doc>Toko Maju Jaya ... TOTAL Rp 1.250.000</doc>")
resp = client.chat.completions.create(
model="MODEL_NAME", temperature=0,
messages=[{"role": "user", "content": prompt}],
response_format={"type": "json_object"}, # JSON mode, if the provider supports it
)
try:
invoice = Invoice.model_validate_json(resp.choices[0].message.content)
except ValidationError as err:
print("Invalid, ask the model to fix it:", err)- What it is
- How many input→output demonstrations you include in the prompt.
- ↑ If you increase it
- Clearer format and label boundaries, often higher accuracy on unusual tasks; but longer prompts (cost, latency) and gains flatten after a handful.
- ↓ If you decrease it
- Shorter and cheaper (zero-shot); the model relies on instructions alone and may guess the format wrong.
- Typical values
- 0 for simple tasks with strong models; 2–8 diverse, balanced examples otherwise.
- What it is
- Randomness of decoding (see the decoding lesson).
- ↑ If you increase it
- More varied phrasing and ideas — good for brainstorming and for self-consistency sampling.
- ↓ If you decrease it
- More repeatable answers — good for extraction, classification and JSON.
- Typical values
- 0–0.3 for structured tasks; 0.7–1.0 for creative tasks or self-consistency.
- What it is
- How many independent reasoning paths you sample before voting.
- ↑ If you increase it
- Higher accuracy on reasoning tasks, with diminishing returns; cost grows linearly with n.
- ↓ If you decrease it
- Cheaper; n = 1 is ordinary chain-of-thought.
- Typical values
- 5–20 when accuracy matters more than cost.
- What it is
- Strings that end generation as soon as they appear (e.g.
\nMessage:in the few-shot prompt above). - ↑ If you increase it
- More stop strings → the model is cut off earlier and more predictably (useful to stop it from inventing the next example).
- ↓ If you decrease it
- Fewer/no stops → relies on the model’s own end-of-turn token or max_tokens.
- Typical values
- Use with completion-style prompts and templates; rarely needed with chat models.
▸Go deeper: why does in-context learning work at all?
Nothing in the weights changes during few-shot prompting; the examples only change the activations. During pretraining, the model saw countless documents containing repeated patterns (lists of Q&A, tables, translations), so “continue this pattern” is exactly what next-token prediction rewards. Research has found that the format and label space of examples often matter as much as whether each example’s label is correct, and that example order can shift results — another reason to evaluate on a test set rather than on intuition. The official prompt-engineering guides from model providers collect many practical patterns[5][6].
Quiz
References
- [1]Language Models are Few-Shot Learners (GPT-3)PaperBrown et al.2020arxiv.org
- [2]Chain-of-Thought Prompting Elicits Reasoning in Large Language ModelsPaperWei et al.2022arxiv.org
- [3]Large Language Models are Zero-Shot ReasonersPaperKojima et al.2022arxiv.org
- [4]Self-Consistency Improves Chain of Thought Reasoning in Language ModelsPaperWang et al.2022arxiv.org
- [5]Prompt engineering overviewDocsAnthropicplatform.claude.com
- [6]Prompt engineering guideDocsOpenAIdevelopers.openai.com