Prompting and structured output
Rewriting the assistant’s instructions as a specification, teaching a boundary with examples, and getting decisions that code can validate, plus the one-line edit that broke fraud handling.
The pilot’s first system prompt was two sentences: “You are the support assistant for a stock-broking app. Answer customers’ questions helpfully and accurately.” In the first week the team read 200 transcripts and sorted the problems they found. A customer asked whether to sell a stock before its quarterly results, and the assistant offered a view on it. Another complained about a charge, and the assistant promised to reverse it, which it has no power to do. A third asked about a pending withdrawal and was told it “should arrive within 24 hours”, a figure that appears nowhere in the help centre. And the code that decided whether to look up an order or raise a ticket, which searched the reply for phrases like “raise a ticket”, broke every time the model worded things differently.
None of these needed a new model or more data. They needed the instructions and the output format to be designed with the same care as any other interface. This chapter rewrites the prompt as a specification, uses examples to teach a boundary that rules describe badly, gets replies the code can parse safely, and walks through how a one-line prompt edit broke the assistant’s handling of fraud reports.
Write the system prompt as a specification
The model reads the system prompt at the start of every conversation and has nothing else to tell it what this deployment is for. Everything the team expects (what it may discuss, where its facts come from, what it must not do, which actions exist, what replies look like) has to be written there, in words specific enough that two engineers would agree on whether a given reply follows them. Here is the core of the rewritten prompt.
You are the support assistant for a stock-broking app. You help customers
with their accounts, orders, funds and charges.
Sources
- Answer only from the help-centre articles inside <articles>. Each has an id.
- Cite the id of every article you relied on, like [HC-1042].
- If the articles do not answer the question, say so plainly and offer to
raise a ticket. Do not fill gaps from general knowledge: policies differ
between brokers and change often.
What not to do
- Do not say whether to buy, sell or hold any security, or predict prices.
Support is not permitted to give investment advice, and customers act on
what we say. Explain how the relevant feature works instead.
- Do not promise refunds, reversals or exceptions. Only the operations team
can grant them. Offer to raise a ticket instead.
Actions
- To check an order, call get_order_status with the order id.
- To hand over to a person, call raise_ticket with a one-line summary.
- If the customer reports activity they did not authorise, call raise_ticket
with priority "urgent" before doing anything else.
Style
- Reply in the customer's language (English, Hindi, or a mix of both).
- Two to five sentences for most answers. Plain words, no headings.Each section answers a failure from the transcripts, and a few choices in it are worth explaining. The prohibitions carry their reasons. A model told only “do not give investment advice” has to guess where advice begins. A model told that customers act on what it says, and that support is not permitted to advise, can extend the rule to cases the list never mentions, such as “is this new share issue worth applying for?” Reasons generalise; bare rules get applied literally.
Each prohibition also says what to do instead. “Do not promise refunds” alone leaves the model with a customer who wants a refund and no permitted move, and it tends to produce something evasive. “Offer to raise a ticket instead” gives it a move. The sources section licenses an honest “I don’t know”, which matters more than it looks. The model’s training rewarded helpful-sounding answers, and without explicit permission to decline, it will usually fill a gap with something plausible, as the model chapter showed.
Finally, the prompt is code. It lives in version control, changes go through review, and, as we will see, every change is tested against recorded conversations before it ships. The model reads it on every call, so a one-word edit changes the behaviour of every conversation at once.
Instructions that can be checked
A useful test for each instruction is whether someone could look at a reply and say if it was followed. “Be accurate” fails the test: the model already tries to produce likely text, and the instruction gives it nothing new to act on. “Cite the id of every article you relied on” passes: code can check that every reply contains at least one id, and that each id was among the articles supplied. Checkable instructions are also the ones the team can later turn into automated evaluations.
Even an instruction that looks precise can hide a choice. “Reply in the customer’s language” seemed clear until the team read replies to customers who write Hindi in Latin script, as in “mera withdrawal abhi tak nahi aaya”. The model often replied in Hindi written in Devanagari, which is the same language and a different script, and several customers said they found it hard to read on a phone. The instruction did not say which of the two it meant, so the model chose. The rewritten line says “Match the language and the script the customer used; if they mix Hindi and English in Latin script, do the same.” Each time a reply surprises the team, the question to ask is whether the prompt actually specified the behaviour they expected, or only implied it.
The tool descriptions are part of the prompt too, though they are easy to forget because they live in a different field of the API call. The first description of raise_ticket was “Raise a support ticket”. The model, keen to be helpful, raised tickets for questions the articles already answered. Rewritten to say when to use it (“when the articles do not answer the question, when the customer asks for a person, or when an action is needed that only the operations team can take”) and when not to (“not for questions the supplied articles answer”), unnecessary tickets fell by more than half. The model reads these descriptions as carefully as the system prompt, and they deserve the same review.
Instructions can also conflict without anyone noticing. “Two to five sentences” and “explain every line of the contract note when asked” cannot both hold for a customer who asks about a contract note with nine charges on it. The model resolves such conflicts silently, and not always the same way twice. When the team finds a conflict, the fix is to state which wins in which situation, as the urgent-ticket rule does with “before doing anything else”.
Where things sit in the prompt matters too. The system prompt goes first, which also suits caching, as the previous chapter showed. Long reference material, the retrieved articles, goes after the history and before the customer’s question, so that the question and the most relevant material are the last things the model reads before it starts writing. Articles and customer text are wrapped in clearly named tags so the model can tell instructions from material. That helps with ordinary confusion, but it is not a security boundary: text inside an article or a customer message can still attempt to issue instructions, and the security chapter treats that separately.
Examples teach the boundary that rules describe badly
Even with reasons attached, the line between explaining a feature and giving advice was drawn inconsistently. “How does a stop-loss order work?” is a product question. “Where should I put my stop-loss on this stock?” is advice. “Why did my stop-loss sell below the price I set?” is a product question about the difference between stop-loss orders that become market orders and those that become limit orders. All three mention stop-losses, and a written rule that separates them cleanly is hard to compose.
Showing the model a few worked examples, called few-shot prompting, often does better than more description, because the model is good at continuing patterns. The team added three short examples to the prompt, one for each of those questions, each showing the ideal reply. The advice example declines in one sentence and then explains how stop-loss orders work with a citation, so it demonstrates the alternative move as well as the refusal. After the change, the share of advice-seeking questions answered with an opinion, measured on 80 such questions from the transcripts, fell from about one in four to one in forty.
All three examples happen to end with the sentence “Would you like me to raise a ticket for this?” A customer asks what the depository charge on their contract note is, and the retrieved article answers it fully. What does the assistant’s reply probably look like?
Show the worked answer
A correct explanation of the charge, followed by “Would you like me to raise a ticket for this?”, though there is nothing to raise a ticket about.
Models copy the surface of examples as eagerly as the substance: length, structure, opening phrases, closing phrases. Here the team saw the ticket offer on most replies within a day, and enough customers accepted it to add several hundred pointless tickets to the queue. The fix was to vary the examples: one ends with the ticket offer because the case needs it, one ends with a citation, one ends after answering. When examples are chosen, check what they have in common that you did not intend to teach.
A few examples go a long way, and they are expensive to keep in the prompt (each one costs tokens on every call) and easy to overfit to. The team keeps three to five, chosen for the cases that rules handled worst, and treats them like test fixtures: when one is changed, the recorded conversations are rerun.
Structured output, where code reads the answer
The phrase-matching code had to go. Before writing a reply, the assistant now makes a separate decision call, whose output is not shown to the customer but read by the orchestration code: which intent this is, which action to take, which order id is involved, whether it is urgent. Code cannot act reliably on prose, so that output must be structured data with a fixed shape.
There are three ways to get it, with different guarantees.
| Method | What is guaranteed | What still goes wrong |
|---|---|---|
| Ask for JSON in the prompt, with an example | nothing; usually valid | stray text around the JSON, missing fields, a few percent of the time |
| Provider structured output against a schema | the output parses and matches the schema | values can be wrong; schema features supported vary by provider |
| Tool calling | tool arguments match the declared schema | the model may not call the tool, or call the wrong one |
Schema-enforced output works through the sampling step from the model chapter. At each token, the server works out which tokens could legally come next given the schema and the text so far, sets the probability of every other token to zero, and samples from what remains. If the schema says the next thing must be one of “answer”, “lookup_order” or “raise_ticket”, the model cannot write “escalate”. This guarantees shape and nothing more. A field typed as a string will accept “my last order” as an order id, because that is a valid string.
So the orchestration code validates meaning as well as shape, and gives the model one chance to correct itself.
const Decision = z.object({
reason: z.string().max(300),
intent: z.enum(['order_status', 'funds', 'account', 'charges',
'app_issue', 'unauthorised', 'other']),
action: z.enum(['answer', 'lookup_order', 'raise_ticket']),
order_id: z.string().regex(/^ORD-\d{5,}$/).nullable(),
urgent: z.boolean(),
})
let result = Decision.safeParse(await decide(conversation))
if (!result.success) {
// one retry, with the validator's complaint appended
result = Decision.safeParse(
await decide(conversation, { error: result.error.message }))
}
if (!result.success) return handOverToHuman(conversation)
if (result.data.action === 'lookup_order' && !result.data.order_id) {
return askCustomerForOrderId()
}Three design choices in that schema matter. The intent list includes “other”, so a question that fits nowhere has a legal answer and the model is not forced to pick the nearest wrong category. The order id must match the format of real ids, so “my last order” fails validation and triggers the retry with a message the model can act on. And the reason field comes first. The model writes fields in order, one token at a time, and each token is conditioned on everything before it. Putting a short reason before the decision gives the model a few sentences to work through the case before it commits to an action; putting it after would only produce a justification of a choice already made.
When both attempts fail, the conversation goes to a person. That path is rare, and having it means a malformed output degrades into a slower answer rather than an unhandled exception.
The two-sentence edit that broke fraud handling
By the third week, replies were accurate but long, averaging about 180 words. On a Friday afternoon an engineer added one line to the Style section: “Keep every answer to at most two sentences.” It was reviewed as a style change and shipped the same day. Here is what happened over the weekend.
Most replies got shorter and better. But for customers reporting trades they had not made, the assistant now often wrote two sentences that told them to “contact support” and stopped. In about a third of those conversations it did not call raise_ticket at all. The urgent-ticket rule was still in the Actions section, but the new line was absolute (“every answer”) and sat later in the prompt, and the model resolved the conflict between them by sometimes keeping its reply short and skipping the action that would have led to a longer explanation. Replies also began dropping citations, which made answers harder to check. On Monday the fraud desk noticed that urgent tickets from the assistant had fallen by about a third, while fraud reports reaching the classifier from the first chapter had not.
The immediate fix was to revert the line. The lasting fixes were two. The instruction was rewritten to state its scope: “Two to five sentences for most answers. For reports of unauthorised activity, raise the urgent ticket first, then explain what happens next in as much detail as needed.” And the process changed. The team built a set of 150 recorded conversations, including 20 fraud reports, 20 advice-seeking questions and 20 questions the help centre cannot answer. Every prompt change now reruns those conversations and checks, mostly with simple code, that urgent tickets were raised, that no reply offered an opinion on a security, that every reply cited a supplied article or said it could not answer, and that the decision output parsed.
That costs something. Each prompt change takes about twenty minutes and a few dollars of tokens to test, and small style tweaks no longer ship in five minutes. The team accepted the cost because the alternative was learning about regressions from the fraud desk. The evaluation chapter later in the pathway builds this practice out properly.
Letting the model work before it answers
Some questions require several steps. “I sold 100 shares at 3:25, 60 got executed, I cancelled the rest at 3:29. Why do my funds show less than 60 times the price?” The answer depends on the charges deducted, on whether the 40 unexecuted shares were released back to holdings, and on when the sale proceeds become available. A model that starts writing the answer immediately must get every step right in the order it writes them. A model that first works through the steps has the intermediate results in its context when it writes the reply, because each token can attend to the earlier ones.
This is the reason step-by-step reasoning helps on multi-step problems, and it is also why it does little for simple lookups: there are no intermediate results to compute. Current models often offer a reasoning mode that does this internally before the visible answer, and the decision becomes one of cost. From the previous chapter, 500 reasoning tokens per turn cost about $0.0025 at $5 per million output tokens and add roughly eight seconds at 60 tokens per second. The team enables reasoning only when the decision call’s intent is order status or charges and the conversation involves a partial execution, a cancellation or several charges, and answers simple policy questions directly.
When the prompt is not the fix
The prompt changes what the model does with what it reads. It cannot supply facts that are not there. When the assistant gave the wrong cut-off time for same-day withdrawals, the cause was that the relevant article had not been retrieved. No instruction could fix that, and attempts to (“be especially careful about withdrawal times”) only made replies more hedged. Missing knowledge is the next chapter’s problem.
Two other limits are worth knowing. When the prompt grows past several thousand tokens of rules and examples, each new rule interacts with all the others, every call pays for all of them, and behaviour becomes hard to predict. That is the point to consider moving stable behaviour into the model’s weights, which the fine-tuning chapter covers. And instructions are not enforcement. For rules with regulatory weight, such as the ban on advice, the prompt makes violations rare, and code makes them rarer still: the team runs a separate check on every outgoing reply and holds back any reply it flags for human review. A prompt lowers the rate of a failure; it does not take it to zero.
The next chapter, Context and retrieval, deals with the articles inside the <articles> tag: how the assistant finds the right three to five passages among the help centre’s 1,200 articles, how many tokens to spend on them, and what happens when it finds the wrong ones.