Priya already keeps fees and marks at Shree Vidya Tuition Centre in Pune. What she still types by hand is a short parent message: “Ananya Sharma has a balance of ₹1,200 for November tuition.” That sentence is a good first job for a Python script. Your program will hold the facts; the model will only turn them into polite prose.
This lesson shows how to call an OpenAI-compatible chat-completions endpoint with the requests library. You will read the API key from an environment variable, send a JSON body, handle failures, and pick the message text out of the reply. We will not hardcode a key, and we will not let the model invent the rupee amount.
Key takeaways
- A chat call is an HTTP POST of JSON to
/v1/chat/completions. - Store the key in
AI_API_KEY, never in the Python file or in a notebook you might share. - The assistant text is usually at
choices[0].message.content. - Put official names and amounts into the prompt from your own data.
- Treat timeouts, bad JSON, HTTP errors, and an empty content string as separate failures.
What you need
You need Python 3, the requests package (pip install requests), and a terminal. The same JSON shape works with many providers that expose /v1/chat/completions. While you practise, you can point the script at a local mock instead of a paid account.
The request you will send
A typical call is POST {base url}/v1/chat/completions with a JSON body:
{
"model": "gpt-4o-mini",
"messages": [
{
"role": "system",
"content": "You write short, polite messages for a tuition centre in India. Use rupees when mentioning fees. Do not invent amounts."
},
{
"role": "user",
"content": "Write a 2-sentence reminder that Ananya Sharma has a balance of ₹1,200 for November tuition."
}
],
"max_tokens": 200
}
The system message sets the tone. The user message holds the task and the facts. Put ₹1,200 in that user text yourself. If you only say “remind them about the pending fee,” the model may guess a number, which is not acceptable for money.
A successful reply includes a choices array. The text you want is usually choices[0].message.content.
Keep the API key out of your code
import os
def api_key_from_env(name: str = "AI_API_KEY") -> str:
key = os.environ.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
In a shell, export the variable before you run the script:
export AI_API_KEY="paste-the-key-here"
python reminder.py
On a server, set it in the process environment or in a file outside the web root. Never print the key, and never bake it into a git commit. You can also read a base URL from the environment so the same script can point at a real provider or a local mock:
base_url = os.environ.get("AI_API_BASE", "https://api.openai.com")
model = os.environ.get("AI_MODEL", "gpt-4o-mini")
Send the prompt with requests
import json
import requests
def build_chat_request(model, messages, max_tokens=200):
body = {"model": model, "messages": messages}
if max_tokens is not None:
body["max_tokens"] = max_tokens
return body
def call_chat_completions(base_url, api_key, payload, timeout=20):
url = base_url.rstrip("/") + "/v1/chat/completions"
try:
response = requests.post(
url,
headers={
"Content-Type": "application/json",
"Authorization": "Bearer " + api_key,
},
json=payload,
timeout=timeout,
)
except requests.RequestException as exc:
raise RuntimeError(f"Request failed: {exc}") from exc
try:
decoded = response.json()
except json.JSONDecodeError as exc:
raise RuntimeError(
"The API did not return valid JSON. HTTP " + str(response.status_code)
) from exc
if not (200 <= response.status_code < 300):
message = (
decoded.get("error", {}).get("message")
if isinstance(decoded, dict)
else "HTTP " + str(response.status_code)
)
raise RuntimeError("API error: " + message)
text = (
decoded.get("choices", [{}])[0]
.get("message", {})
.get("content")
)
if not isinstance(text, str) or text == "":
raise RuntimeError("The API response had no message content.")
return {"status": response.status_code, "content": text, "raw": decoded}
requests can encode the JSON for you when you pass json=payload. A timeout stops a hung call from sitting forever; twenty seconds is a starting point. Error handling comes in layers: the request itself failed (DNS, timeout, TLS); the server answered without JSON; JSON arrived with a 4xx or 5xx status; or a 200 response had no content. Keep those cases separate so you can log a useful message without dumping the key.
Put it together
api_key = api_key_from_env()
base_url = os.environ.get("AI_API_BASE", "https://api.openai.com")
student = "Ananya Sharma"
balance = 1200 # rupees; this value comes from your records, not from the model
month = "November"
payload = build_chat_request(
os.environ.get("AI_MODEL", "gpt-4o-mini"),
[
{
"role": "system",
"content": "You write short, polite messages for a tuition centre in India. Use rupees when mentioning fees. Do not invent amounts or dates.",
},
{
"role": "user",
"content": (
f"Write a 2-sentence reminder that {student} "
f"has a balance of ₹{balance:,} for {month} tuition."
),
},
],
)
try:
result = call_chat_completions(base_url, api_key, payload)
print(result["content"])
except RuntimeError as exc:
print("Could not write the reminder just now.")
# Log the error somewhere private, not into a public web page.
The rupee figure is formatted in Python, then placed in the prompt. If you later print the model’s text into a web page, escape it the same way you would escape any untrusted string.
Try this
First run the script without setting AI_API_KEY. You should get the missing-key error, not a network request. Then set a fake key and point AI_API_BASE at a local mock, or at a real compatible endpoint if you already have an account. Change the user message so the balance is ₹2,450 and the student is Rahul Iyer. Confirm that the reply mentions ₹2,450 and does not invent a different amount.
How this was tested
On this machine, the request builder produced valid JSON, an empty AI_API_KEY raised the missing-key error, and a sample success body parsed to the reminder text. The requests call was then pointed at a local mock of POST /v1/chat/completions: a matching Bearer token returned HTTP 200 and a ₹1,200 message; a wrong token returned HTTP 401 and the function raised API error: Invalid API key. No paid API was called, so run one live call against your own provider before you rely on it.
What you learned
- An OpenAI-compatible chat call is a POST of JSON to
/v1/chat/completions. - The API key belongs in an environment variable, never in the source file.
- The
requestslibrary can send the call, apply a timeout, and return JSON for you to parse. - Official amounts and names go into the prompt from your own data.
Quick quiz
-
1. Where should
AI_API_KEYlive?- A) In a string at the top of
reminder.py - B) In the process environment, read with
os.environ - C) In a public GitHub gist, so every machine can share it
Show answer
B. A key in the file can leak through backups or git history. The environment keeps it off the disk that you commit.
- A) In a string at the top of
-
2. After a 200 JSON response, where is the assistant text usually found?
- A)
choices[0].message.content - B) The HTTP reason phrase
- C)
error.message
Show answer
A. Treat a missing or empty content string as a failure so you do not send a blank note to a parent.
- A)
-
3. Who should decide that Ananya’s balance is ₹1,200?
- A) The model, if you write “whatever is outstanding”
- B) Your script or database, which then places ₹1,200 in the user message
- C) A default in the system prompt
Show answer
B. Money and names are facts you already have. The model’s job is the wording.
-
4.
requests.postraises a timeout. What is the right first step?- A) Call
response.json()anyway - B) Treat it as a transport failure — there is no trustworthy body
- C) Print the API key to confirm it was sent
Show answer
B. A connection or timeout error is different from an HTTP 401 with a JSON error message. Do not log the key.
- A) Call
Next lesson
Next in this study path, practise prompt engineering: clearer instructions, examples, and JSON output that your Python (or PHP) can validate before you use it. After that you can connect this script to a real fee balance from a file or a database.