By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
The first API call is trivial. The first safe API call is not: you need to control cost, capture what happened, and fail in a way you can debug. Here is the shape that survives contact with production.
import os, time
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
def ask(question: str, context: str, *, model="gpt-4.1-mini") -> dict:
started = time.perf_counter()
resp = client.chat.completions.create(
model=model,
temperature=0.2, # factual answers: keep it low
max_tokens=300, # hard budget per answer
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": f"CONTEXT:\n{context}\n\nQUESTION: {question}"},
],
)
latency_ms = int((time.perf_counter() - started) * 1000)
return {
"text": resp.choices[0].message.content or "",
"prompt_tokens": resp.usage.prompt_tokens,
"completion_tokens": resp.usage.completion_tokens,
"model": resp.model,
"latency_ms": latency_ms,
"finish_reason": resp.choices[0].finish_reason,
}| Field | Why you need it |
|---|---|
text | The answer under test |
finish_reason | length means the answer was truncated — a format failure waiting to happen |
usage | Tokens, which become cost |
latency_ms | Your first performance signal, free |
model / response id | Proves which model actually served the request |
finish_reason is the field everyone forgets. A truncated answer will fail your JSON parser, and without this field you will spend an afternoon blaming the prompt.
Keep prompt construction separate from the API call. It is the part you can unit-test with no network at all.
def build_messages(question: str, chunks: list[str], history: list[dict] | None = None):
"""Assemble a prompt. Pure function: testable without an API key."""
context = "\n\n".join(f"[{i+1}] {c}" for i, c in enumerate(chunks))
system = SYSTEM_PROMPT + "\n\nCONTEXT:\n" + context
return [{"role": "system", "content": system},
*(history or []),
{"role": "user", "content": question}]
def test_context_is_numbered():
msgs = build_messages("q", ["a", "b"])
assert "[1] a" in msgs[0]["content"]
assert "[2] b" in msgs[0]["content"]Streaming improves perceived speed but complicates testing: you now have partial output, a first-token timestamp, and a failure mode where the stream dies mid-sentence. Test three things: time to first token, whether the final concatenated text equals the non-streamed answer quality-wise, and whether a mid-stream error surfaces as an error rather than a silently short answer.
Key takeaways
Capture text, finish_reason, usage, latency and model on every call.
finish_reason == 'length' means truncation — a format bug in waiting.
Separate prompt assembly from the API call so most tests need no network.
Pin your SDK version; OpenAI-compatible endpoints make the same code portable.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.