Priya has a simple rule at Shree Vidya Tuition Centre: if a student’s official balance is ₹0, send a thank-you; if it is greater than zero, send a fee reminder. A rushed prompt such as “write the usual reminder for Meera” can skip that check and nag a parent who has already paid. Chain-of-thought prompting asks the model to work through the official facts step by step before it chooses an action.
This lesson shows how to write that prompt, call an OpenAI-compatible chat API from Python, and then check the result in code. The reasoning is useful, but it is not a substitute for validation: amount_inr must still match the register, and the action must still follow the rule. You will read AI_API_KEY from an environment variable. We will not hardcode a key, and we will not let the model invent the balance. The prompt-engineering lesson covers clear instructions, examples, and JSON shape; today the new habit is the step-by-step reasoning.
Key takeaways
- Chain-of-thought prompting asks the model to reason step by step from official facts, then give the answer.
- Put names, months, and rupee amounts into the prompt from your own data — never ask the model to remember them.
- A useful shape is JSON with
reasoning,action, andamount_inr, so your code can check each field. - Reject a reply if the amount does not match the register, or if the action breaks your rule (for example, a reminder when the balance is ₹0).
- Keep
AI_API_KEYin the environment, never in the Python file.
What chain-of-thought prompting is
In a direct prompt, you ask for the final answer only: “Should we thank Meera or remind her?” The model may jump to a reminder because that is the more common message. A chain-of-thought prompt adds an instruction such as “Think step by step using only the official facts.” The model then writes a short reasoning trail — the balance is 0, the rule says thank-you — and only then chooses the action.
The HTTP call is still a POST to {base url}/v1/chat/completions, as in Your First AI Program in Python. The difference is the instruction, and the check you run afterwards.
def official_action(amount_inr):
if amount_inr < 0:
raise ValueError('A balance cannot be negative.')
return 'thank_you' if amount_inr == 0 else 'send_reminder'
def build_cot_messages(student, amount_inr, month):
formatted = f'{amount_inr:,}'
system = (
'You decide the next message for a tuition centre in India. '
'Think step by step using only the official facts in the user message. '
'Do not invent amounts, names, or dates. '
'If amount_inr is 0, the action is thank_you. If amount_inr is greater than 0, the action is send_reminder. '
'After your reasoning, reply with JSON only, no markdown, using this shape: '
'{"reasoning": "string", "action": "send_reminder or thank_you", "amount_inr": number}. '
'Copy amount_inr exactly from the official facts.'
)
user = (
f'Official facts:\n'
f'- student: {student}\n'
f'- amount_inr: {amount_inr}\n'
f'- month: {month}\n'
f'- displayed_balance: ₹{formatted}\n'
'Think step by step, then return the JSON object.'
)
return [
{'role': 'system', 'content': system},
{'role': 'user', 'content': user},
]
Notice that the rule and the figures live in your Python first. The prompt only repeats them. If Meera’s balance is 0, the user message says amount_inr: 0 and displayed_balance: ₹0. The model should not have to invent a number, and your later check will fail if it does.
A good reply looks like this (the reasoning will vary; the fields must not):
{
"reasoning": "The official amount_inr for Meera Patel is 0. The rule says thank_you when the balance is 0.",
"action": "thank_you",
"amount_inr": 0
}
For Ananya Sharma with an official balance of ₹1,200, action should be send_reminder and amount_inr should be 1200. Models sometimes wrap the object in a markdown fence; your parser should still recover the JSON, as in the PHP parsing lesson.
Validate the reasoning’s conclusion in code
Read choices[0].message.content, extract the JSON, and then apply the same official rule you already have in Python. Chain-of-thought text can look confident and still be wrong.
import json
ALLOWED_ACTIONS = frozenset({'send_reminder', 'thank_you'})
def extract_json_string(content):
trimmed = content.strip()
if trimmed.startswith('```'):
trimmed = trimmed.split('\n', 1)[-1]
if trimmed.endswith('```'):
trimmed = trimmed[:-3].strip()
if trimmed.startswith('json'):
trimmed = trimmed[4:].strip()
start = trimmed.find('{')
end = trimmed.rfind('}')
if start != -1 and end != -1 and end > start:
return trimmed[start:end + 1]
return trimmed
def parse_cot_reply(content, expected_amount):
data = json.loads(extract_json_string(content))
if not isinstance(data, dict):
raise RuntimeError('The model did not return a JSON object.')
for key in ('reasoning', 'action', 'amount_inr'):
if key not in data:
raise RuntimeError('Missing JSON key: ' + key)
if not isinstance(data['reasoning'], str) or not data['reasoning'].strip():
raise RuntimeError('reasoning must be a non-empty string.')
if data['action'] not in ALLOWED_ACTIONS:
raise RuntimeError('action must be send_reminder or thank_you.')
amount = data['amount_inr']
if isinstance(amount, str) and amount.isdigit():
amount = int(amount)
if not isinstance(amount, int) or isinstance(amount, bool):
raise RuntimeError('amount_inr must be a whole number of rupees.')
if amount != expected_amount:
raise RuntimeError('amount_inr did not match the official balance.')
if data['action'] != official_action(expected_amount):
raise RuntimeError('action did not match the official rule for this balance.')
return {
'reasoning': data['reasoning'].strip(),
'action': data['action'],
'amount_inr': amount,
}
If the model reasons fluently but returns amount_inr 1500 when the register says 1200, you reject the result. If it copies 0 correctly but still chooses send_reminder, you also reject it. The reasoning field is for your logs and for debugging the prompt; it is not a source of money facts.
Put it together with the API call
import os
import requests
def api_key_from_env(name='AI_API_KEY', env=None):
source = os.environ if env is None else env
key = source.get(name)
if not key:
raise RuntimeError(
f'Missing API key. Set the {name} environment variable. '
'Do not hardcode the key in Python files.'
)
return key
def call_chat_completions(base_url, api_key, payload, timeout=20):
url = base_url.rstrip('/') + '/v1/chat/completions'
response = requests.post(
url,
headers={
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + api_key,
},
json=payload,
timeout=timeout,
)
try:
decoded = response.json()
except ValueError:
raise RuntimeError('The API did not return valid JSON. HTTP ' + str(response.status_code))
if response.status_code < 200 or response.status_code >= 300:
message = (decoded.get('error') or {}).get('message') or ('HTTP ' + str(response.status_code))
raise RuntimeError('API error: ' + message)
text = (decoded.get('choices') or [{}])[0].get('message', {}).get('content')
if not isinstance(text, str) or text == '':
raise RuntimeError('The API response had no message content.')
return text
def decide_next_message(student, amount_inr, month, env=None):
source = os.environ if env is None else env
api_key = api_key_from_env('AI_API_KEY', source)
base_url = source.get('AI_API_BASE') or 'https://api.openai.com'
model = source.get('AI_MODEL') or 'gpt-4o-mini'
payload = {
'model': model,
'messages': build_cot_messages(student, amount_inr, month),
'max_tokens': 300,
}
content = call_chat_completions(base_url, api_key, payload)
return parse_cot_reply(content, amount_inr)
decision = decide_next_message('Ananya Sharma', 1200, 'November')
print(decision['action'], decision['amount_inr'])
print(decision['reasoning'])
For Ananya, a passing result has action send_reminder and amount_inr 1200. For a student whose official balance is 0, only thank_you and 0 should pass. After that, your own templates can write the actual email — the model’s job in this lesson is the decision, not untrusted HTML.
Try this
First run parse_cot_reply on the thank-you sample above, with expected_amount=0. It should succeed. Change action to send_reminder and run it again; you should get the rule error. Then parse a reminder object for ₹1,200, change amount_inr to 1500, and confirm it is rejected. If you have a local mock or a real compatible endpoint, set AI_API_KEY and AI_API_BASE, and call decide_next_message('Rahul Iyer', 2450, 'November'). Check that action is send_reminder and amount_inr is 2450.
How this was tested
On Python 3.13 with the requests library, an empty AI_API_KEY raised the missing-key error, the request messages included the official facts and the words “Think step by step,” and parse_cot_reply accepted a tidy JSON object and a fenced one, while rejecting a wrong amount and a reminder action when the official balance was 0. The chat call was pointed at a local mock of POST /v1/chat/completions: a matching Bearer token returned HTTP 200 and JSON that parsed to send_reminder for ₹1,200 and ₹2,450, and to thank_you for ₹0; a wrong token returned HTTP 401 and the function raised API error: Invalid API key. No paid API was called here, so run one live call against your own provider before you rely on it.
What you learned
- Chain-of-thought prompting asks the model to reason step by step from official facts before it answers.
- Put the rule and the rupee amount into the prompt from your own data, then ask for JSON with
reasoning,action, andamount_inr. - Validate the amount and the action in Python. Confident reasoning does not make an invented figure safe.
- The API key still belongs in an environment variable, never in the source file.
Quick quiz
-
1. What does a chain-of-thought prompt ask the model to do first?
- A) Reason step by step from the official facts, then give the answer
- B) Invent a balance if the prompt forgot to include one
- C) Return only a greeting, with no reasoning
Show answer
A. The extra instruction is to work through the facts before choosing an action. It does not replace official numbers from your register.
-
2. The official balance is ₹0. Which action should your code accept?
- A)
thank_you - B)
send_reminder - C) Whichever action the model prefers, as long as the reasoning is long
Show answer
A. Your rule is the source of truth. A reminder when the balance is zero should be rejected, even if the reasoning sounds polite.
- A)
-
3. The JSON has
amount_inr1500, but the register says 1200. What should Python do?- A) Trust the reasoning field and use 1500
- B) Reject the result
- C) Average the two figures
Show answer
B. Money is a fact you already have. If the JSON does not copy it exactly, do not use the reply.
-
4. Where should
AI_API_KEYbe stored?- A) In a string at the top of the Python file
- B) In the process environment, read with
os.environ - C) Inside the
reasoningfield, so you can debug the prompt
Show answer
B. A key in the source, or in model output you might log, can leak. Use an environment variable, and never print the key.
Related lessons
- Prompt Engineering for Developers: Clear Instructions, Examples and JSON Output — the role, facts, examples, and JSON shape this lesson builds on.
- How to Parse JSON from an AI API in PHP — the same habit of stripping fences and checking amounts, in PHP.
- Your First AI Program in Python: Send a Prompt and Read the Reply — the basic
requestscall and environment key used here.