New cohort: Agentic AI & LLM Engineering remote internship. Limited seats.Apply now
Lesson 05 of 21 22 minFree

Creating Advanced Prompts

Chain-of-thought, task decomposition, self-critique and reliable JSON output: prompting techniques that make LLMs reason better and plug safely into your code.

By the end of this lesson you will be able to:

  • Use chain-of-thought prompting to improve reasoning on multi-step problems.
  • Break big tasks into smaller prompts (least-to-most and prompt chaining).
  • Make a model check and improve its own answer.
  • Ask for structured JSON and parse it safely in Python.

When basic prompts aren't enough

In Lesson 4 we wrote clear prompts with a role, task, context, examples and format. That handles most everyday tasks. But our study buddy also gets questions like: "A train leaves Hyderabad at 6:40 am at 60 km/h. Another leaves 40 minutes later at 80 km/h on the same track. When does it catch up?" Questions like this have several steps, and a model that jumps straight to an answer often gets them wrong.

Advanced prompting techniques help the model work through problems, and help your code use the results reliably.

1. Chain-of-thought: let it show its work

Remember that each token is predicted from the tokens before it. If the model writes its reasoning steps first, those steps become context for the final answer, so the answer is far more likely to be right. Asking for this is called chain-of-thought (CoT) prompting. Often it's as simple as adding "Think step by step, then give the final answer."

Direct answer

Q: Riya buys 3 notebooks at ₹45 each and
2 pens at ₹12 each. She pays with ₹200.
How much change does she get?
A: ₹65

Wrong: it skipped the pens. Jumping straight to a number invites mistakes like this.

Chain-of-thought

Think step by step.
Notebooks: 3 × 45 = ₹135
Pens: 2 × 12 = ₹24
Total: 135 + 24 = ₹159
Change: 200 − 159 = ₹41
Final answer: ₹41

Same numbers, every step visible and checkable.

Why it works: with chain-of-thought every step is written down, so it can be checked by you, a teacher or your code, and the final answer is predicted from correct intermediate results instead of a guess. Many newer "reasoning" models now do this thinking internally before they reply.

Watch the model reason through the train problem one step at a time:

  1. Train A starts at 6:40 am at 60 km/h. Train B starts 40 minutes later, at 7:20 am, at 80 km/h.
  2. In those 40 minutes Train A covers 60 × (40/60) = 40 km. That's B's gap to close.
  3. B gains on A at 80 − 60 = 20 km/h.
  4. Time to close 40 km at 20 km/h = 40 ÷ 20 = 2 hours after B starts.
  5. Final answer: 7:20 am + 2 hours = 9:20 am.

Few-shot chain-of-thought

You can combine CoT with few-shot prompting: show one or two worked examples with their reasoning, then ask the new question. The model copies the reasoning style as well as the format. For a study buddy this doubles as good teaching, because students see the method, not just the answer.

2. Break it down: least-to-most and prompt chaining

Some tasks are too big for one prompt. Least-to-most prompting asks the model to first list the sub-problems, then solve them in order. Prompt chaining does the same in code: the output of one prompt becomes the input of the next.

Each step is simpler, easier to test and easier to fix than one giant prompt. When something goes wrong you can see exactly which step failed.

3. Self-critique: ask it to check its work

Models are often better at reviewing an answer than producing a perfect one on the first try. A second prompt can ask the model to find mistakes in its own draft and fix them. This is sometimes called self-refine. A related trick is generated knowledge: first ask the model to list relevant facts, then answer using only those facts.

  1. Write 2 MCQs on the water cycle for Class 5.
  2. 1) What is it called when water turns into vapour? A) Condensation B) Evaporation C) Precipitation. Answer: B. 2) Clouds are formed by… A) Evaporation B) Precipitation C) Collection. Answer: A.
  3. Review your MCQs as a strict teacher. Fix any wrong answer keys or confusing options.
  4. Fix: in Q2, clouds form by condensation, which wasn't even an option. Corrected Q2: Clouds are formed by… A) Evaporation B) Condensation C) Precipitation. Answer: B.

4. Structured output: JSON your code can trust

When an app uses the model's answer (to save it, show it in a UI or grade a quiz) you need a predictable structure. Ask for JSON and describe the exact shape:

Create 3 MCQs about the solar system for Class 6.
Reply ONLY with JSON in this exact shape, no other text:
{"questions": [{"q": string, "options": [string, string, string, string], "answer": 0-3}]}

Many APIs also offer a JSON mode or structured outputs setting that forces valid JSON matching a schema. Use it when available. Still, always validate in code. Models sometimes wrap JSON in ```json fences, add a sentence before it, or miss a field.

5. Tuning settings

  • temperature: as in Lesson 1. Use low values for facts, grading and JSON, higher for brainstorming.
  • top_p: another way to limit randomness, by sampling only from the most likely tokens that together make up probability p. Usually you adjust temperature or top_p, not both.
  • max tokens: caps the length of the reply, and the cost.

Hands-on: parse model output safely

Your task: the model's reply below is wrapped in a ```json fence with a friendly sentence in front. That breaks json.loads. Complete extract_json() to cut out just the part from the first { to the last }. Then the validation runs and should print Parsed 3 valid questions.

import json

model_reply = """Sure! Here are your questions:
```json
{"questions": [
  {"q": "Which planet is closest to the Sun?", "options": ["Venus", "Mercury", "Earth", "Mars"], "answer": 1},
  {"q": "Which planet is called the Red Planet?", "options": ["Mars", "Jupiter", "Saturn", "Venus"], "answer": 0},
  {"q": "What is the largest planet?", "options": ["Earth", "Saturn", "Jupiter", "Neptune"], "answer": 2}
]}
```
Good luck with your test!"""

def extract_json(text):
    # TODO: return the substring from the first "{" to the last "}" (inclusive)
    return text

def valid(q):
    return isinstance(q.get("q"), str) and len(q.get("options", [])) == 4 and q.get("answer") in range(4)

try:
    data = json.loads(extract_json(model_reply))
    questions = [q for q in data["questions"] if valid(q)]
    print(f"Parsed {len(questions)} valid questions")
    for q in questions:
        print("-", q["q"], "→", q["options"][q["answer"]])
except json.JSONDecodeError as err:
    print("Could not parse JSON:", err)
Show solution
def extract_json(text):
    return text[text.find("{"): text.rfind("}") + 1]

Your task: with chain-of-thought, your app shows the steps but also needs the final answer on its own, for example to grade it. Use a regular expression to find the text after Final answer: and print Final answer: 9:20 am.

import re

reply = """Train A starts at 6:40 am at 60 km/h; Train B starts at 7:20 am at 80 km/h.
In 40 minutes Train A covers 40 km.
B closes the gap at 20 km/h, so it needs 2 hours.
Final answer: 9:20 am"""

# TODO: search for "Final answer:" followed by the rest of the line
match = None

if match:
    print("Final answer:", match.group(1).strip())
else:
    print("No final answer found. Ask the model to end with 'Final answer: ...'")
Show solution
match = re.search(r"Final answer:\s*(.+)", reply)

Check your understanding

Why does chain-of-thought often improve answers to multi-step problems?

  1. It makes the model use a bigger context window
  2. The written steps become context that the final answer is predicted from
  3. It switches the model to a different, smarter model
  4. It lowers the temperature automatically

Each token is predicted from what came before, so explicit reasoning steps guide the final answer.

You need a revision sheet from a 20-page chapter, and one huge prompt gives messy results. What should you try?

  1. Raise the temperature
  2. Ask the same prompt again
  3. Chain smaller prompts: concepts → explanations → MCQs → review
  4. Remove all instructions

Prompt chaining splits the job into simpler steps you can test and fix one by one.

The API returned "Sure! ```json {...} ``` Hope this helps". What's the right approach?

  1. Extract the JSON part, parse it, then validate every field
  2. Show the raw text to users
  3. Assume it is always perfect JSON
  4. Increase max tokens

Always extract, parse and validate. Never trust model output blindly in code.

Key takeaways

  • Chain-of-thought makes reasoning visible and usually more accurate.
  • Break big tasks into chains of smaller prompts.
  • A second "review your answer" pass catches many mistakes.
  • Ask for exact JSON, use structured-output features, and always validate in code.

You now have the core prompting toolkit. In Lesson 6 we start building real applications: a text generation app using an LLM API.

Your progress is saved in this browser.

Adapted from Lesson 5 of Microsoft's "Generative AI for Beginners" (MIT License), rewritten and extended by Aiprojects4U. View source