Skip to content
SparkTime, home
AI From Zero to Productive
Lessons
1 · Understanding Modern AI
2 · Talking to AI Effectively
3 · AI for Learning
4 · AI for Work and Productivity
5 · AI for Developers
6 · AI for Career Growth
7 · Research, Verification and Responsible AI
8 · Automation and AI Agents
9 · Build Your Personal AI System
Lesson 8 of 35

Lesson 8 · Talking to AI Effectively

Examples, Output Formats and Structured Output

Showing the AI one or two examples often beats three paragraphs of description. This article covers example-based prompting, choosing an output format, and requesting structured output such as JSON that a program or spreadsheet can use, with the checks that make it safe.

On this page

Key takeaways

  • An example shows what you want more precisely than a description, especially for tone, structure and edge cases.
  • Use a small number of varied, consistently formatted examples, including at least one tricky case, and label them clearly as examples.
  • Choose the output format for how you will use the answer: a table to compare, steps to follow, JSON to feed a program.
  • Never trust structured output blindly. Validate shape, types and allowed values in code, and handle the failure case.
  • Models are imprecise with exact counts and lengths, so ask for approximate limits and measure yourself.

You have a spreadsheet of 300 customer comments and want each one tagged "billing", "delivery", "product" or "other". You write a careful description of each tag. The AI tags the first ten reasonably, but it labels "my parcel arrived but the item was broken" as "delivery" and you wanted "product". You add a sentence to the description. It fixes that case and breaks another.

There is a faster route: show it three tagged comments, including the tricky one. One example often carries more information than a paragraph of rules.

What you will learn

#
  • When and how to prompt with examples.
  • How to write examples that teach rather than mislead.
  • How to choose an output format for the job.
  • How to request structured output, and a small program that validates it.
  • Why length and count instructions need your own checking.

Prompting with examples

#

Giving the model sample inputs and the outputs you want is often called few-shot prompting, with "zero-shot" meaning no examples. Provider guidance is consistently in favour. Google's prompt design guide recommends including examples and notes that you can sometimes remove instructions if the examples are clear enough, while warning that too many examples can lead the model to overfit to them. OpenAI's guide describes providing diverse input and output examples as a way to show a pattern without further training. GitHub's advice for coding prompts says unit tests and sample inputs and outputs are a good way to show what you want.

Why examples work

#

A description tells the model about the pattern. An example is the pattern. It carries tone, length, structure and handling of awkward cases all at once, and you do not have to put these into words.

How to write good examples

#
  1. Keep the format identical across examples. If one uses "Label: billing" and another uses "billing", the model gets mixed signals about the format.
  2. Make them varied. Pick examples that differ in length and content, so the model learns the pattern, not a single case.
  3. Include a tricky example. The broken-item comment is worth more than three easy ones.
  4. Add a short rule where the logic is not obvious. "If a message mentions both delivery and damage, use 'product'."
  5. Mark the boundary. Say clearly where examples end and the real input begins.
  6. Use three to five at most to start. More is not always better. Add one only when you see a specific failure.

A worked example

#

Goal. Tag customer comments.

First attempt (zero-shot).

Code
Tag each comment as billing, delivery, product or other: "my parcel arrived but the item was broken"

It may well answer "delivery". The description of the tags never said what to do with mixed cases.

Better: add examples and a rule.

Code
Tag each customer comment with exactly one of: billing, delivery, product, other.Rule: if a comment is about damage or quality, use "product", even if it alsomentions delivery.Examples:Comment: "I was charged twice this month"Tag: billingComment: "Courier has not come for six days"Tag: deliveryComment: "The parcel came on time but the screen was cracked"Tag: productComment: "Do you have a store in Chennai?"Tag: otherNow tag this comment. Reply with the tag only.Comment: "my parcel arrived but the item was broken"Tag:

Example response (illustrative).

Code
product

What to check. Run it on twenty comments you tag yourself first, and compare. If it disagrees on a pattern, you have found a missing example or a missing rule. Add that case, not a hundred more. This is the loop in action: describe, test, check, refine.

Negative examples and style

#

You can also show what you do not want: "Bad: 'We are thrilled to announce...' Good: 'We have changed the opening hours.'" This works well for tone, since many people can recognise bad corporate prose faster than they can describe good prose.

For style transfer, such as "write in the style of my previous emails", paste two or three of your own samples. Do not ask it to copy a specific living author's distinctive voice for something you will publish as your own. Bias, Copyright and Human Judgment returns to this.

A worked example: from messy text to a clean table

#

Examples also help with data extraction. Suppose a shop owner pastes three messy lines from a notes app and wants a table with date, vendor and amount.

Code
Extract date, vendor and amount (in rupees) from each line. Reply as a table withthose three columns. If a field is missing or unclear, write "unclear" and do not guess.Example:Line: "paid 2300 to Sharma Traders on 3 Oct"Row: 2026-10-03 | Sharma Traders | 2300Lines:1. "bought chairs from Anand Furniture rs 8,500 on 5th oct"2. "Gupta store 1200 last friday"3. "Rs. 450 cab, 7/10"

Example response (illustrative).

Date

Vendor

Amount

2026-10-05

Anand Furniture

8500

unclear

Gupta store

1200

2026-10-07

unclear

450

What to check. The "unclear" values are the example working as intended: line 2 says "last Friday", which needs today's date to resolve, and line 3 gives no vendor (a cab). Without the instruction not to guess, a model would probably have filled both in. The remaining risk is line 3's date: "7/10" could mean 7 October or 10 July depending on the convention, and the year was assumed. Check any date format that could be read two ways, and make the assumption explicit in the prompt next time ("dates are day/month; the year is 2026").

The example row did three jobs at once: it set the column order, showed how to format dates and showed that amounts are plain numbers. That is why it replaced several sentences of instruction.

Choosing an output format

#

The format should follow how you will use the answer.

You will...

Ask for

Why

Compare options

A table with named columns

Side-by-side makes differences visible

Follow a procedure

Numbered steps, one action each

Easy to track and to tick off

Skim before a meeting

Three bullet points and one question to raise

Forces a priority

Send a message

The message itself, in the channel's format

No editing from "essay" to "chat message"

Reuse in a spreadsheet

CSV or a table with fixed columns

Pastes cleanly

Feed a program

JSON with a defined structure

Machines need exact shapes

Review for mistakes

A checklist with pass or fail

Makes gaps obvious

Some formats also improve thinking. Asking for "assumptions you made" and "what would change your answer" at the end makes the model state what it guessed. "A table of claims and the supporting quote" turns grounding into a checkable layout.

Structured output

#

When the result goes into a program, a spreadsheet or another step in a workflow, you need structured output: a fixed shape such as JSON. This is the first step towards the reliable AI workflows of Module 8.

A prompt for it names the fields, their types and the allowed values:

Code
Extract a task from the message below. Reply with only a JSON object withexactly these keys:- "title": string- "priority": one of "low", "medium", "high"- "due_in_days": integerNo other text.Message: "Please send the invoice to the client by tomorrow, it's urgent."

An illustrative reply:

Code
{"title": "Send invoice to client", "priority": "high", "due_in_days": 1}

That looks right. But a program that consumes it must not assume it is. Real replies sometimes include a friendly sentence before the JSON, a field with a wrong type, a missing key or a made-up value such as "priority": "urgent". Some developer interfaces can enforce a schema on the model's output, which is worth using where available (check the current documentation of the service), but you should still validate in your own code, because the content can be well-formed and still wrong.

A small validator

#

This program checks five replies against the rules. The replies are written by hand to show typical failures. Nothing here calls an AI service, so the output is the same every time.

Python
# File: validate_output.pyimport jsonREQUIRED = {"title": str, "priority": str, "due_in_days": int}ALLOWED_PRIORITY = {"low", "medium", "high"}def check(raw):    try:        data = json.loads(raw)    except json.JSONDecodeError as err:        return f"rejected: not valid JSON ({err.msg})"    if not isinstance(data, dict):        return "rejected: expected a JSON object"    for key, kind in REQUIRED.items():        if key not in data:            return f"rejected: missing '{key}'"        value = data[key]        if not isinstance(value, kind) or isinstance(value, bool):            return f"rejected: '{key}' must be {kind.__name__}"    if data["priority"] not in ALLOWED_PRIORITY:        return f"rejected: priority '{data['priority']}' is not allowed"    return "accepted"replies = [    '{"title": "Book dentist", "priority": "low", "due_in_days": 14}',    '{"title": "Send invoice", "priority": "urgent", "due_in_days": 1}',    '{"title": "Prepare slides", "priority": "high"}',    'Sure! Here is the task: {"title": "Call bank"}',    '{"title": "Renew passport", "priority": "medium", "due_in_days": "30"}',]for number, reply in enumerate(replies, start=1):    print(number, check(reply))
Code
1 accepted2 rejected: priority 'urgent' is not allowed3 rejected: missing 'due_in_days'4 rejected: not valid JSON (Expecting value)5 rejected: 'due_in_days' must be int

Four out of five failed, each in a different way. That is deliberate: it shows why the check belongs in code. A real workflow also needs a plan for rejections: retry once with the error message, then send the item to a person. A silent failure is the worst outcome.

Length, counts and exact wording

#

Models are imprecise at exact counts. "Exactly 100 words" or "exactly 12 bullets" can be off by several, because they work in tokens, not words. Practical advice:

  • Ask for a range or limit ("about 100 words, at most 120") rather than an exact figure.
  • Count yourself with a word counter, or ask for the format that makes counting easy ("a numbered list").
  • For hard limits, such as an application form character limit, paste the result into a counter and then ask the model to shorten it.
  • Prefer structure over length: "three bullets" is easier to meet than "75 words".

Common mistakes

#
  • Examples that all look the same, leading the model to copy accidental features.
  • Too many examples, which can lock in the pattern too tightly.
  • Examples that contradict your rules. The model often follows the examples.
  • Asking for JSON but allowing chatter. Say "only the JSON, no other text", and still strip and validate.
  • Trusting well-formed output. Valid JSON is not correct JSON.
  • Asking for an exact length and not checking.
  • Using a table for a task that needs reasoning, or a bullet list for a task that needs nuance. Match the format to the thinking.

Exercises

#

Exercise 1

Build a few-shot prompt

#

You want an assistant to rewrite casual messages into a polite workplace tone, in one sentence. Write a prompt with a one-line rule and three examples (including one that is rude), then a placeholder for the new message.

Exercise 2: Choose a format

#

Pick a format for each need and justify it: (a) comparing three laptops on price, weight and battery, (b) steps to set up a shared drive, (c) data you will paste into a spreadsheet, (d) a fast brief before a meeting.

Exercise 3: Extend the validator

#

In the program above, reply number 1 is accepted. What extra check would you add so that a due_in_days of -5 or 9999 is rejected? State your rule and say what you would do with a rejected reply.

Exercise 4: Find the weakness

#

Your classifier prompt has four examples, all tagged "billing", and the model now tags most comments as "billing". Explain why, and fix it.

Show solutionHide solution
Code
Rewrite the message as one polite, professional sentence for a colleague.Keep the meaning. Do not add facts. Do not use exclamation marks.Message: "send me the file now"Rewrite: Could you please send me the file when you have a moment today?Message: "your report is full of mistakes"Rewrite: I noticed a few errors in the report, so could we go through them together?Message: "can't make the 3 pm"Rewrite: I'm unable to join the 3 pm meeting, so could we find another time?Message: "{new message}"Rewrite:

Why it works: a one-line rule sets the limits, the examples vary in meaning and in difficulty (the second is a rude one), and the format is identical. A check to run: does the rewrite keep the meaning, and did it add any "facts" such as a time? Compare against your own rewrite on five messages.

Exercise 2

Show solutionHide solution

(a) A table, with one row per laptop and columns for price, weight and battery. It is a comparison across several dimensions. (b) Numbered steps, one action per step, because you will follow them in order. (c) CSV or a table with fixed column names, so it pastes cleanly and every row has the same shape. (d) Three bullets plus one question to raise, because brevity and priority matter more than completeness.

The general rule: ask yourself what you will do with the answer next, and request that shape.

Exercise 3

Show solutionHide solution

A simple rule: due_in_days must be an integer between 0 and 365. Add after the type check:

Code
if not 0 <= data["due_in_days"] <= 365:    return "rejected: due_in_days out of range"

Choose the range to match your real situation. For a rejected reply, retry once, including the validation error in your next message ("Your last reply was rejected because due_in_days was out of range. Reply again with a valid JSON object."). If the second reply is also rejected, do not guess. Put the item in a "needs a person" list. This pattern, retry then escalate, returns in Module 8.

Exercise 4

Show solutionHide solution

All examples have the same label, so the model learns that "billing" is the common answer, a form of bias towards the examples. It also never sees the other tags demonstrated.

Fix: use a balanced set with at least one example per tag, vary lengths and wording, and include a tricky case with the rule that resolves it. Then test on twenty comments you tagged yourself. If it still errs on a pattern, add one example of that pattern.

Where to go next

#

Sources & further reading

  1. ai.google.dev
  2. developers.openai.com
  3. docs.github.com
  • Guide · Technology

    Writing Better AI Prompts: A Practical Guide

  • Guide · Technology

    Using AI Tools at Work Without Getting Into Trouble

  • Course · Career

    Off-Campus Placements With AI: From Zero to Offer