Sub topic 10
Guide Reasoning and Handle Uncertainty
This chapter assumes you can call a chat API, read basic Python, and work with JSON. It also assumes you have read the chapters on writing constraints and specifying output format. Here you decide how much the model should reason before it answers, and what it should do when it cannot answer with confidence.
Why reasoning and uncertainty belong in the prompt
A model produces an answer whether or not it has grounds for one. Without guidance it will often guess, and the guess reads as fluently as a correct answer. Two decisions in your system prompt reduce this problem:
- Reasoning guidance tells the model how to work toward an answer: which steps to take, and in what order.
- Uncertainty handling tells the model what to do when the steps do not lead to a supported answer: say so, ask, or hand off.
Both are constraints in the sense of the previous chapters. They need the same treatment: concrete wording, a defined output slot, and a test that checks them.
When step-by-step reasoning helps
Asking a model to reason before answering helps with tasks that have intermediate steps. Examples are comparing several documents, doing arithmetic on invoice lines, applying a multi-part policy, or deciding which of several rules applies. It helps little with lookups, classification into obvious labels, or rewriting text.
Reasoning has costs:
- It adds output tokens, so latency and price go up.
- It can leak into the final answer and break your output format.
- A fluent explanation can make a wrong answer look justified.
Many current models have a built-in reasoning mode that you switch on through an API setting. If you use one, do not also write "think step by step" in the prompt. Describe what a good answer must check instead. If you use a model without such a mode, you can ask for visible reasoning in the prompt.
| Situation | Suggested approach |
|---|---|
| Simple lookup or extraction | No reasoning instruction. Keep output short. |
| Multi-step comparison or calculation | Ask for reasoning before the answer, in a separate section. |
| Model with built-in reasoning mode | Use the API setting. State the checks that matter, not "think harder". |
| Output must be machine-parsed | Separate reasoning from the final answer with delimiters, or discard reasoning before parsing. |
Guide the steps, not just the effort
"Think carefully" is vague. A better instruction names the checks you want, in order. Compare these two:
- Weak: "Think step by step before answering."
- Stronger: "First list which documents mention the invoice number. Then check whether any document gives the amount. Then answer."
The stronger version encodes the procedure a careful human would follow, and you can test whether the model followed it. Keep the list short. Five or six steps is a practical upper limit, because long procedures get skipped or reordered.
Keep reasoning separate from the answer
If your application parses the reply, put reasoning in its own section and the final answer in another. Tags work well because you can extract them with a regular expression. Here is an extended version of the Acme Billing prompt from earlier chapters:
You are a support assistant for Acme Billing.
# Task
Answer customer questions about invoices and payments using only the documents provided in <documents>.
# Reasoning
Before answering, write your working inside <analysis> tags:
1. List the documents that mention the invoice or payment the customer asks about.
2. Quote the exact lines that support an answer.
3. Decide the status: "answered", "needs_clarification", or "not_in_documents".
# Uncertainty
- If the question could refer to more than one invoice, use "needs_clarification" and ask one specific question.
- If no document supports an answer, use "not_in_documents". Do not guess or use general knowledge about billing.
- If the documents disagree, report the disagreement and use "needs_clarification".
- Do not give legal or tax advice. Use "not_in_documents" and offer a human agent.
# Output
After </analysis>, write one JSON object inside <answer> tags:
{"status": string, "answer": string, "sources": [integer]}
Write nothing after </answer>.Three details matter here. The reasoning comes before the answer, because a model writes tokens in order and an answer written first cannot benefit from the analysis. The statuses are a closed list, so your code can branch on them. And step 2 asks for quotes, which ties the reasoning to the supplied text and makes unsupported claims easier to spot.
Handle uncertainty explicitly
Models rarely volunteer "I am not sure." You have to define what uncertainty looks like and give the model an acceptable exit for each case. These cases come up most often:
- Missing information. The answer is not in the provided context. The exit is a defined status such as
not_in_documents. - Ambiguous request. The question has more than one reasonable reading. The exit is one clarifying question.
- Conflicting sources. Two documents disagree. The exit is to report both and not pick one silently.
- Out-of-scope request. The question is legitimate but outside the app's job. The exit is a refusal plus a pointer to where help is available.
- Low-stakes ambiguity. The ambiguity does not change the answer much. The exit is to state the assumption and continue.
Case 5 matters because over-asking is also a failure. A model told "ask when unsure" will interrupt users over trivia. Give a threshold, for example: "Ask a question only if the possible readings would lead to different answers. Otherwise state your assumption in one sentence and answer."
Avoid confidence numbers unless you can check them
It is tempting to add "include a confidence score from 0 to 100." Models can produce such a number, but it is usually poorly calibrated: it clusters around high values and does not reliably track correctness. If you need a signal for routing, prefer categorical statuses tied to observable conditions, such as "a quoted line supports the answer" versus "no quote found". If you do add a numeric score, measure it against your test set before any logic depends on it.
Consume the result in code
The prompt only pays off if your application acts on the statuses. This code parses the reply from the prompt above, discards the reasoning, validates the status, and routes the result:
import json
import re
ALLOWED_STATUS = {"answered", "needs_clarification", "not_in_documents"}
def parse_reply(raw: str) -> dict:
"""Extract and validate the JSON inside <answer> tags; ignore <analysis>."""
match = re.search(r"<answer>(.*?)</answer>", raw, flags=re.DOTALL)
if match is None:
raise ValueError("no <answer> block in reply")
data = json.loads(match.group(1))
if data.get("status") not in ALLOWED_STATUS:
raise ValueError(f"unexpected status: {data.get('status')!r}")
if not isinstance(data.get("answer"), str):
raise ValueError("'answer' must be a string")
return data
def route(reply: dict) -> str:
if reply["status"] == "answered":
return reply["answer"]
if reply["status"] == "needs_clarification":
return "Question for customer: " + reply["answer"]
return "Handing off to a human agent."
raw = """<analysis>
1. Document 2 mentions invoice 1042.
2. Quote: "Invoice 1042: paid on 2026-03-02".
3. Status: answered.
</analysis>
<answer>{"status": "answered", "answer": "Invoice 1042 was paid on 2 March 2026.", "sources": [2]}</answer>"""
print(route(parse_reply(raw)))Running it prints Invoice 1042 was paid on 2 March 2026. Note that the regular expression takes only the <answer> block, so reasoning text can never corrupt the JSON parser. Never show the <analysis> section to end users by default. It may contain quoted internal documents or reasoning that is wrong in ways the final answer is not.
Common failure modes
| Symptom | Likely cause | Fix |
|---|---|---|
| Model guesses when documents are silent | No explicit exit for missing information | Add a `not_in_documents` status and say "do not use general knowledge". |
| Model asks a question on every request | Ask-when-unsure rule has no threshold | Ask only when readings change the answer; otherwise state the assumption. |
| Reasoning text appears inside the JSON | Reasoning and answer share one section | Use separate tags and parse only the answer block. |
| Answer contradicts the analysis | Answer was written before the reasoning, or the reasoning was too long | Put reasoning first and shorten the step list. |
| Model skips the steps | Steps are vague or too many | Name concrete checks, keep to about six. |
| Latency or cost too high | Reasoning added to simple tasks | Remove it for lookups, or route simple requests to a cheaper path. |
Summary of the working rules
- Request reasoning only for tasks with intermediate steps, and name the checks instead of saying "think carefully".
- Put reasoning before the answer, in its own delimited section, and parse only the answer.
- Define a closed set of statuses so uncertainty becomes something your code can branch on.
- Give a threshold for asking questions so the model neither guesses nor over-asks.
- Prefer categorical signals over self-reported confidence numbers unless you have measured them.
Exercise
A colleague's prompt says "Think step by step, then output JSON." In production, about 5% of replies fail JSON parsing because the reasoning text appears before the opening brace. Describe two changes that fix this, and name one additional uncertainty case the prompt should handle.
Show answer
First, put the reasoning in <analysis> tags and the JSON in <answer> tags, then extract only the <answer> block with a regular expression before calling json.loads. Second, tell the model to write nothing after the closing </answer> tag, and keep the reply format identical in every case so parsing never depends on free text. As an additional uncertainty case, add a needsclarification status for ambiguous questions (for example, a customer with several open invoices who does not say which one), with a rule to ask one specific question only when the possible readings would give different answers. A notin_documents status for missing information, or a rule for conflicting documents, is also an acceptable answer.
Exercise
Why is "include a confidence score from 0 to 100" a weaker way to handle uncertainty than a fixed list of statuses, and what would you do before relying on such a score?
Show answer
Self-reported scores tend to be poorly calibrated, often clustering at high values regardless of correctness, and they give your code no clear action to take at a given number. A fixed status list ties each case to an observable condition and a defined next step. Before relying on a numeric score, run it over a labeled test set and check whether higher scores correspond to higher accuracy, then choose a routing threshold from that data.