GeekHub Learn
Module
Lesson 5.33 of 8 in this module2 min read Module 5: Using AI APIs (OpenAI, Gemini, Anthropic)

Your first OpenAI call

The single most-asked-about line of Python in 2026: how do I actually call ChatGPT from code? This lesson answers it.

You are sending a polite letter to a smart pen friend. You include who you are, what you want, and where to send the reply. The API call is the envelope.

Three things every API call needs:

  1. The model id (e.g. gpt-4o-mini)
  2. The messages array (see Module 3.2)
  3. Optional parameters (temperature, max_tokens, response_format)

The provider returns a structured response with the assistant message, token usage, and finish reason.

from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()

client = OpenAI()

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "system", "content": "You are a tutor. Reply in 2 sentences."},
        {"role": "user", "content": "Explain RAG to a beginner."},
    ],
    temperature=0.4,
    max_tokens=200,
)

print(response.choices[0].message.content)
print("Usage:", response.usage.total_tokens)

That is a complete, runnable program.

Visualize it

A request-response diagram: Python script -> HTTP POST with model + messages -> OpenAI -> JSON response -> Python prints.

Try it now

Run the above script. Change temperature to 0, 1, and 1.5. Note differences.

Hands-on lab

Build a ask(question) function that wraps the API call. Use it in a 1-line CLI: python ask.py "What is a transformer?". 20 lines max.

Try it now

How many tokens did your request use? Where is that printed?

Common mistakes

  • Using the wrong model id (typos are silent failures)
  • Forgetting max_tokens and getting truncated responses
  • Logging the full response object in production (it is big)

Debugging tip

If you see AuthenticationError, your env var is missing or wrong. If RateLimitError, back off. If BadRequestError, your message format is malformed.

Challenge

Build a compare_models(question) function that calls 3 different OpenAI models on the same question and prints the answers and token costs side by side.

Where this shows up

  • Backend AI endpoints
  • Scripts for data enrichment
  • Quick experimentation in notebooks

From the field

In 2026 production, almost no one calls the API directly inside request handlers. They wrap it in a service with retries, caching, and logging. Module 5.7 will show this.

Recap

Three lines: import, client, create. You now ship code that calls ChatGPT.


Quick recall

3 prompts · think before you flip

Prompt 1 of 3

What three inputs does every chat completion need?

Quiz time

1 question · tap an answer to check it

  1. 1. The assistant's text is at

Finished lesson 5.3?

Mark complete to update your module progress and unlock the streak.

Loading