Sunday , November 29 2026
Use ChatGPT effectively and call OpenAI models from Python: API key, messages, temperature and a chatbot with memory.

ChatGPT Tutorial: Using ChatGPT and the OpenAI API with Python

Updated: 28 November 2026Level: BeginnerReading time: about 10 minutesopenai Python SDK 1.x

ChatGPT is OpenAI’s conversational AI assistant built on its GPT family of large language models. In this tutorial you learn to use ChatGPT well in the browser, and then call the same models from Python with the OpenAI API.

What You Will Learn

  • What ChatGPT can and cannot do
  • How to write better prompts in the ChatGPT app
  • How to get an API key and call the model from Python
  • How system, user and assistant messages work
  • How to build a simple chatbot that remembers the conversation

Prerequisites

Basic Python and Introduction to Generative AI.

What Can ChatGPT Do?

Use Example prompt
Explain concepts “Explain overfitting to a beginner with a cricket example.”
Write and fix code “Find the bug in this Python function and explain it.”
Summarise “Summarise this article in 5 bullet points.”
Draft content “Write a polite email asking for a deadline extension.”
Learn and practise “Give me 5 MCQs on Pandas with answers.”
Analyse data Upload a CSV and ask “Which month had the highest sales?”
Note: ChatGPT can make mistakes (“hallucinate”). Always check facts, numbers and code before using them.

Using the OpenAI API from Python

Step 1: Install and set your key

Install
pip install openai
Note: Never write your API key inside the code or share it on GitHub. Store it in an environment variable (for example setx OPENAI_API_KEY "..." on Windows or export OPENAI_API_KEY="..." on Linux/macOS). The SDK reads it automatically.

Step 2: Your first request

Example
from openai import OpenAI

client = OpenAI()          # reads OPENAI_API_KEY from the environment
MODEL = "gpt-4o-mini"      # replace with a current model name if needed

response = client.chat.completions.create(
    model=MODEL,
    messages=[
        {"role": "system", "content": "You are a friendly Python teacher."},
        {"role": "user", "content": "What is a Python list? Answer in 2 sentences."}
    ],
    temperature=0.3,
)
print(response.choices[0].message.content)
Part Meaning
system message Sets the assistant’s role and rules for the whole chat
user message The question or instruction
assistant message The model’s earlier replies (used to keep context)
temperature 0 = focused and repeatable, higher = more creative
choices[0].message.content The text of the reply
Output
A Python list is an ordered, changeable collection that can hold items of any type, written in square brackets like [1, "a", 3.5]. You can add, remove and change items using methods such as append() and remove().
Note: Model names change often. Check the provider’s documentation for the current list and replace the value of MODEL if needed. LLM answers also vary from run to run, so your output will not match the sample exactly.

Step 3: A chatbot with memory

Example
from openai import OpenAI
client = OpenAI()
MODEL = "gpt-4o-mini"

history = [{"role": "system", "content": "You are a helpful tutor for machinelearning.org.in."}]

while True:
    question = input("You: ")
    if question.lower() in ("exit", "quit"):
        break
    history.append({"role": "user", "content": question})
    reply = client.chat.completions.create(model=MODEL, messages=history)
    answer = reply.choices[0].message.content
    history.append({"role": "assistant", "content": answer})
    print("Bot:", answer)

Explanation: The API itself does not remember anything between calls. We keep a history list and send the whole conversation every time, so the model can answer follow-up questions like “give me an example of that”.

Tips for Better Results

  • Give a role: “You are a senior data scientist…”
  • Be specific about format: “Answer as a table with 3 columns.”
  • Give examples of the output you want.
  • Ask it to think step by step for maths and logic.
  • Break big tasks into smaller prompts.

More techniques are in the Prompt Engineering tutorial.

Common Errors

Problem Cause and fix
AuthenticationError The API key is missing or wrong. Check the environment variable and restart your terminal or notebook.
RateLimitError / insufficient quota You have hit a limit or have no credit on your API account.
NotFoundError for the model The model name is wrong or not available to your account.
Bot forgets earlier questions You are not sending the previous messages in history.

Series

Generative AI series: Introduction · ChatGPT · Google Gemini · Claude AI · Prompt Engineering · AI Agents · RAG · Fine-Tuning LLMs · Multimodal AI

Interview Questions

Q: What is the role of the system message?
It defines the assistant’s behaviour, persona and rules for the conversation.

Q: Is the API stateful?
No. Each request is independent; you must send the conversation history yourself.

Practice Exercises

  1. Change the system message so the bot answers only in Hinglish.
  2. Add a limit so history keeps only the last 10 messages.
  3. Ask the model to return JSON with keys “topic” and “summary” and parse it with json.loads.

Summary

ChatGPT is a GPT-based assistant you can use in the browser or through the OpenAI API. In code you send a list of messages (system, user, assistant) and read the reply; keeping the history gives your chatbot memory.

Next: Google Gemini · Claude AI

About Machine Learning

Check Also

Fine-Tuning LLMs: LoRA, QLoRA and Hugging Face

When and how to fine-tune large language models: data format, LoRA, QLoRA, Hugging Face TRL and evaluation.