Kokil Thapa - Professional Web Developer in Nepal
Freelancer Web Developer in Nepal with 15+ Years of Experience

Kokil Thapa is an experienced full-stack web developer focused on building fast, secure, and scalable web applications. He helps businesses and individuals create SEO-friendly, user-focused digital platforms designed for long-term growth.

Few-Shot and Chain-of-Thought Prompting

By Kokil Thapa | Last reviewed: September 2026

Your model returns confident nonsense on structured tasks. Few-Shot and Chain-of-Thought Prompting fixes that pattern by showing the model what good output looks like and asking it to reason step by step before it answers. I use both techniques daily when wiring LLM APIs into Laravel apps, support bots, and document workflows. This guide covers the mechanics, copy-paste templates, and production guardrails that actually stick after deploy.

What is Few-Shot and Chain-of-Thought Prompting?

Large language models predict the next token from context. Few-Shot and Chain-of-Thought Prompting shapes that context so the model mimics a pattern you define instead of guessing from pretraining alone.

Few-shot prompting places one or more solved examples inside the prompt. Each example shows an input and the exact output you want. The model continues the pattern on the new input.

Chain-of-thought (CoT) prompting asks the model to write intermediate reasoning steps before the final answer. On arithmetic, classification with exceptions, and policy checks, CoT often beats direct answers.

Zero-shot means instructions only—no examples. One-shot uses a single example. Few-shot uses two or more. CoT can sit on top of any of those levels.

Prompting SpectrumZero-ShotInstructions onlyFast, cheapFew-ShotInput → output pairsTeaches formatChain-of-ThoughtSteps then answerBetter logicCombined: Few-Shot + CoTExamples show reasoning styleNew task follows same steps
Few-Shot and Chain-of-Thought Prompting layers: instructions, examples, and explicit reasoning before the final output.

The original chain-of-thought paper from Google Research showed large gains on math word problems when models wrote reasoning steps first. That pattern still holds on modern APIs from OpenAI and Anthropic. See the Chain-of-Thought Prompting paper (Wei et al.) for the baseline evidence.

Core terms in one line each

  • Demonstration: a single input/output pair in the prompt.
  • Exemplar: another name for a demonstration example.
  • Scratchpad: the model’s written reasoning before the answer.
  • Parse target: the structured field your app reads after the call.

How do you write effective few-shot examples for LLM prompts?

Few-shot quality beats quantity. Three sharp examples often beat ten noisy ones. Each example should teach one rule: format, edge case, or tone.

On a legal-tech portal I built, few-shot pairs taught the model how to classify user questions into booking, document, or general info buckets. The examples included one ambiguous query so the model learned to ask a clarifying question instead of guessing.

Rules for strong demonstrations

  1. Match production inputs in length, language, and messiness.
  2. Cover the hardest edge case you can afford in token budget.
  3. Keep labels and field names identical across all examples.
  4. Place the newest user input last, after all demonstrations.
  5. Separate examples with a clear delimiter the model can copy.
Classify the customer message. Reply with JSON only.

Example 1:
Message: "I need my marriage certificate attested by Tuesday."
Category: document_service
Confidence: high

Example 2:
Message: "How much for notary at your Lazimpat office?"
Category: pricing_inquiry
Confidence: high

Example 3:
Message: "asap help!!!"
Category: needs_clarification
Confidence: low

Now classify:
Message: "{{user_message}}"
Category:

Store exemplars in version-controlled JSON, not hard-coded strings scattered in controllers. A JSON formatter helps you validate structure before the prompt ships. Pair that with token and cost controls so few-shot growth does not blow the budget.

OpenAI’s prompt engineering guide recommends diverse, consistent examples. Anthropic’s docs stress clear delimiters and explicit output schemas. Both align with the template above.

How many shots should you use?

ScenarioTypical shot countTrade-off
Simple JSON extraction1–2Low token cost; may miss edge cases
Multi-label classification3–5Good accuracy; watch context window
Nepali + English mixed support4–6Needs dialect examples; higher cost
Strict schema (10+ fields)2–3 full + 1 partialFull examples are expensive

Start with two shots. Add one only when eval scores drop on a specific failure mode. That discipline keeps latency and spend predictable on API-backed features.

When should you use chain-of-thought prompting instead of zero-shot?

Reach for CoT when the task needs arithmetic, conditional logic, multi-hop lookup, or policy chains. Skip it when you need a single keyword, a boolean flag, or a short rewrite.

Zero-shot CoT is the famous “Let’s think step by step” suffix on an otherwise plain question. It helps on many models without custom examples. Few-shot CoT is stronger when your domain uses non-obvious steps.

Use Chain-of-Thought?New LLM taskMulti-step logic?Yes → CoTNeeds exact format?Few-shot firstLow latency?Skip long CoTFew-Shot + CoT for domain rulesShow steps in every example
Decision tree: use chain-of-thought when logic is multi-step; prefer few-shot when format matters most.

Zero-shot CoT example

Question: A trek deposit is Rs 15,000. The client pays 40% now and the rest in two equal instalments. How much is each instalment?

Let's think step by step.

Few-shot CoT example

Compute VAT-inclusive total. Show steps, then final JSON.

Input: Subtotal Rs 10,000, VAT 13%
Steps:
1. VAT = 10000 × 0.13 = 1300
2. Total = 10000 + 1300 = 11300
Output: {"subtotal":10000,"vat":1300,"total":11300}

Input: Subtotal Rs 4,500, VAT 13%
Steps:
1. VAT = 4500 × 0.13 = 585
2. Total = 4500 + 585 = 5085
Output: {"subtotal":4500,"vat":585,"total":5085}

Input: Subtotal Rs {{amount}}, VAT 13%
Steps:

For Nepali business math, cross-check totals with your own calculator layer. CoT reduces errors but does not replace server-side validation. The EMI calculator tool on this site follows the same principle: show the steps, then verify programmatically.

Read the OpenAI prompt engineering guide for vendor-specific tips on instruction hierarchy and system messages.

How do you combine few-shot and chain-of-thought prompting in production apps?

Production means reproducible prompts, parsed outputs, fallbacks, and evals—not one-off ChatGPT sessions. I treat prompts like API contracts and store them beside the code that parses responses.

Laravel service pattern

On production Laravel 12 or 13 apps, isolate prompt assembly in a dedicated class. Pass exemplars from config. Log prompt version hashes, not raw user PII.

<?php

namespace App\Services\Ai;

class BookingIntentPromptBuilder
{
    public function build(string $message, array $exemplars): string
    {
        $blocks = collect($exemplars)->map(function ($ex) {
            return <<<TXT
Message: {$ex['message']}
Steps: {$ex['steps']}
Intent: {$ex['intent']}
TXT;
        })->implode("\n\n");

        return <<<PROMPT
You classify booking intents. Think step by step, then output intent on the last line.

{$blocks}

Message: {$message}
Steps:
PROMPT;
    }
}

Wire this behind a queue job when latency allows. Return partial UI updates with Livewire or Alpine while the job runs. That pattern appears in booking flows like trek management platforms where misclassification sends bad supplier emails.

Production CoT PipelineUser inputPrompt builderFew-shot + CoTLLM APIParse steps+ final fieldServer-side validationSchema, ranges, auth rulesStore audit logSteps + decisionRetry or fallbackOn parse failure
Few-Shot and Chain-of-Thought Prompting in production: build, call, parse, validate, then log or retry.

Parsing chain-of-thought safely

Never trust free-form reasoning for permissions or payments. Extract a fixed final field with a delimiter or JSON schema mode.

  • Ask for FINAL_ANSWER: on its own line after steps.
  • Use structured outputs or JSON schema when the vendor supports it.
  • Reject responses missing required keys; retry with a shorter prompt.
  • Cap reasoning tokens; long scratchpads cost money and leak noise.

Combine this with AI-assisted debugging when prompts drift after model updates. Log failure cases into a golden set and re-run weekly evals.

Evaluation loop

Build a CSV of inputs, expected intents, and expected numeric results. Run it in CI with automated test hooks. Track accuracy, parse failure rate, and p95 latency. Swap exemplars only when scores move the right way.

For client portals like document-sharing law platforms, wrong classification is a support ticket. Few-shot CoT plus server validation beats either technique alone.

What are common mistakes with few-shot and CoT prompting?

Most failures I see are process problems, not model problems. Teams copy a demo prompt, ship it, and skip evals.

Mistake 1: Examples that disagree with each other

If Example 1 outputs pretty JSON and Example 2 adds markdown fences, the model picks randomly. Normalize every demonstration to the same skeleton.

Mistake 2: CoT without a parse target

A wall of reasoning is hard to test. Always define the machine-readable field your app reads. Hide steps from end users if they clutter the UI.

Mistake 3: Too many shots in Nepali-English mixed chat

Bilingual support needs exemplars in both scripts. One English-only shot teaches the wrong tone for Nepali queries. Use the Nepali Unicode converter to normalise text before it hits the prompt.

Mistake 4: Ignoring token economics

Each extra exemplar repeats on every request. Cache static prefixes where vendors allow prompt caching. Read Claude API integration notes and model-specific caching docs before you scale traffic.

Bad vs Good Prompt DesignBad10 random examplesNo step formatFree-form answerNo server checksPrompt in controllerFragile in prodGood3 targeted shotsFixed step labelsFINAL_ANSWER fieldSchema validationVersioned prompt classTested in CIFix
Few-Shot and Chain-of-Thought Prompting done wrong versus production-ready: fewer examples, fixed steps, parsed output, validation.

Align AI features with governance basics: log decisions, limit sensitive data in prompts, and document which prompt version approved a given action.

Comparison: prompting strategies at a glance

StrategyBest forToken costParse difficulty
Zero-shotSimple rewrite, summariesLowEasy
Few-shotFormat-heavy extractionMediumEasy
Zero-shot CoTQuick logic boostMediumMedium
Few-shot CoTDomain rules + logicHighMedium
RAG + few-shot CoTLong docs, fresh factsHighestHarder

When facts change often—product catalogs, fee schedules—pair retrieval with few-shot CoT. Static exemplars alone cannot know this week’s fuel price table or court fee updates. Fetch facts first, then ask the model to reason over grounded text.

For greenfield features, scope work under custom software development or extend existing apps via web development services. Prompt design belongs in the same discovery phase as schema design—not as a launch-week patch.

Related reading: prompting for image generation, AI-powered search in Laravel, content pipeline automation, and AI code review in CI. For quality gates, see testing and optimization services.

Key Takeaways

  • Few-shot teaches format and domain tone; chain-of-thought improves multi-step accuracy when you need shown work.
  • Use two or three tight exemplars first; add shots only when eval data proves a gap.
  • Always separate reasoning steps from the parsed FINAL_ANSWER your code consumes.
  • Validate outputs server-side—CoT reduces errors but does not replace business rules.
  • Version prompts, log hashes, and run golden-set evals in CI before you scale traffic.
  • Combine retrieval with few-shot CoT when answers depend on data that changes weekly.

People Also Ask

What is the difference between few-shot and chain-of-thought prompting?

Few-shot prompting supplies solved examples so the model copies structure and labels. Chain-of-thought prompting adds explicit reasoning steps before the answer. You can use either alone or together; combined few-shot CoT is the strongest pattern for domain-specific logic.

How many examples do you need for few-shot prompting?

Start with two or three demonstrations that cover normal cases and one edge case. More examples help until you hit diminishing returns or token limits. Measure accuracy on a fixed eval set instead of guessing the count.

Does chain-of-thought prompting work with all LLMs?

Most modern instruction-tuned models benefit from CoT, especially on math and logic. Smaller or heavily quantised models may skip steps or hallucinate reasoning. Test your target model on real inputs before shipping.

Should users see the chain-of-thought reasoning?

Show steps when transparency builds trust—support triage or educational tools, for example. Hide them when the UI needs a short answer or when steps might leak sensitive context. Always store reasoning in logs for auditors if the decision matters.

Ship Few-Shot and Chain-of-Thought Prompting with confidence

Few-Shot and Chain-of-Thought Prompting is not a party trick. It is how you turn general models into reliable workers for classification, quoting, and document intake. Treat exemplars as config, reasoning as auditable scratch space, and final fields as API contracts validated on the server.

If you are adding LLM features to a Laravel app, WooCommerce store, or client portal, start with a small golden set and one production prompt class. Expand shots only when metrics demand it. Need help wiring prompts, evals, and fallbacks into a live system? Contact us or explore AI integration and automation services—and browse the portfolio for platforms already running structured AI workflows.

Frequently Asked Questions

Few-shot shows solved input-to-output examples; chain-of-thought adds reasoning steps before the answer. Together they teach format and improve multi-step accuracy.

Few-shot prompting supplies solved examples so the model copies structure, labels, and domain tone. Chain-of-thought prompting adds explicit intermediate steps before the final answer, which helps on math, logic, and policy checks. They solve different problems and work best together: few-shot teaches what output should look like, while CoT forces the model to show its work. Either technique can run alone or layered on zero-shot, one-shot, or few-shot baselines.

Start with two or three sharp demonstrations covering normal cases plus one edge case. Add shots only when eval scores drop on a specific failure mode.

Use CoT for arithmetic, conditional logic, multi-hop lookups, or policy chains. Skip it for single keywords, boolean flags, or short rewrites.

Quality beats quantity: three sharp examples often outperform ten noisy ones. Match production inputs in length, language, and messiness. Cover your hardest affordable edge case within token budget. Keep labels and field names identical across every demonstration. Place the newest user input last, after all examples, and separate pairs with clear delimiters. On a legal-tech portal, I included one ambiguous query so the model learned to ask clarifying questions instead of guessing. Store exemplars in version-controlled JSON, not scattered hard-coded strings.

Zero-shot chain-of-thought means you add no solved examples, only instructions plus an explicit request to reason step by step. The well-known pattern is appending Let's think step by step to an otherwise plain question. It gives a quick logic boost on many modern instruction-tuned models without custom demonstrations. Few-shot CoT is stronger when your domain uses non-obvious steps, because exemplars teach both format and the reasoning pattern your business expects.

Production means reproducible prompts, parsed outputs, fallbacks, and evals, not one-off sessions. I isolate prompt assembly in a dedicated Laravel class on Laravel 12 or 13 apps, pass exemplars from config, and log prompt version hashes instead of raw user PII. The flow is build, call, parse, validate, then log or retry. Wire slow calls behind queue jobs when latency allows, returning partial UI updates with Livewire or Alpine. Treat prompts like API contracts stored beside the code that parses responses, and run golden-set evals in CI before scaling traffic.

Most modern instruction-tuned models benefit from CoT, especially on math and logic tasks. The original Google Research work by Wei et al. showed large gains on word problems when models wrote reasoning first, and that pattern still holds on current OpenAI and Anthropic APIs. Smaller or heavily quantised models may skip steps or hallucinate reasoning. Test your target model on real production inputs before shipping, and track parse failure rate alongside accuracy in weekly evals.

Show steps when transparency builds trust, such as support triage or educational tools. Hide them when the UI needs a short answer or when intermediate reasoning might leak sensitive context into the browser. Never trust free-form scratchpad text for permissions or payments regardless of visibility. Always define a machine-readable parse target your code extracts after the steps, and store full reasoning in server logs for auditors when the decision carries business weight.

Most failures are process problems, not model problems. Examples that disagree with each other, such as pretty JSON in one shot and markdown fences in another, make the model pick randomly. CoT without a parse target produces untestable walls of text. Too many English-only shots fail on Nepali-English mixed chat because tone and script differ. Teams also ignore token economics: each extra exemplar repeats on every request. Normalize every demonstration to the same skeleton, cap reasoning tokens, and run evals instead of copying demo prompts straight to production.

Never trust free-form reasoning for permissions or payments. Extract a fixed final field using a delimiter, JSON schema mode, or structured outputs when the vendor supports them. Ask for FINAL_ANSWER on its own line after steps, reject responses missing required keys, and retry with a shorter prompt. Cap reasoning token length because long scratchpads cost money and add parse noise. Combine parsing with server-side validation. CoT reduces errors but does not replace business rules or calculator layers for Nepali VAT and instalment math.

Pair retrieval with few-shot CoT when answers depend on facts that change often, such as product catalogs, fee schedules, court fee updates, or this week's price tables. Static exemplars alone cannot know current data. Fetch grounded text first, then ask the model to reason over it with your domain examples. This pattern costs the most tokens and is harder to parse than plain few-shot, but it beats stale demonstrations for dynamic knowledge. Scope prompt design during discovery, not as a launch-week patch.

A parse target is the structured field your application reads after the model finishes reasoning, the contract your code depends on, not the scratchpad text. On classification tasks it might be a JSON category and confidence score. On quoting workflows it could be numeric totals after shown VAT steps. Defining the parse target upfront lets you test prompts automatically, reject malformed responses, and hide verbose chain-of-thought from end users while still logging it for auditors.

Zero-shot is cheapest and suits simple rewrites. Few-shot sits in the middle for format-heavy extraction. Zero-shot CoT adds medium cost for quick logic boosts. Few-shot CoT is the highest among static prompting strategies because every exemplar repeats on each request and reasoning steps add length. RAG plus few-shot CoT costs the most. Cache static prompt prefixes where vendors allow prompt caching, start with two shots, and add examples only when eval data proves a gap to keep latency and spend predictable.

CoT sharply improves accuracy on math, logic, and multi-step business rules, but models still return confident nonsense on structured tasks. Server-side validation catches wrong totals, invalid JSON keys, and policy violations before they trigger bad supplier emails or support tickets. On Nepali business math, cross-check VAT-inclusive totals with your own calculator layer. Wrong classification on document-sharing client portals becomes a real support ticket. CoT plus few-shot beats either technique alone, yet final fields still need the same validation you would apply to any external API response.

Share this article

0 Comments

Leave a comment

Your email is not published. Comments appear once they have been read. Sign in to have your details filled in.

Quick Contact Options
Choose how you want to connect me: