What You'll Build
By the end of this tutorial, you'll have a working Python script that calls the OpenAI API, sends a prompt, and prints a response. From there, you'll have the foundation to build chatbots, document summarizers, code assistants, and more.
Prerequisites
- Python 3.8 or higher installed
- An OpenAI account (sign up at platform.openai.com)
- Basic familiarity with Python and the command line
Step 1: Install the OpenAI Python Library
Open your terminal and run:
pip install openai
This installs the official OpenAI Python client. It's well-maintained and handles authentication, retries, and response parsing for you.
Step 2: Get Your API Key
Log into your OpenAI account, navigate to API Keys under your profile settings, and create a new secret key. Copy it immediately — you won't be able to view it again.
Security tip: Never hardcode your API key directly in your source code. Instead, use an environment variable:
# On macOS/Linux
export OPENAI_API_KEY="your-key-here"
# On Windows (Command Prompt)
set OPENAI_API_KEY=your-key-here
Or store it in a .env file and load it with the python-dotenv package.
Step 3: Make Your First API Call
Create a new file called hello_ai.py and add the following code:
from openai import OpenAI
client = OpenAI() # Reads OPENAI_API_KEY from environment automatically
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Explain what a neural network is in two sentences."}
]
)
print(response.choices[0].message.content)
Run it with:
python hello_ai.py
You should see a concise explanation of neural networks printed to your terminal.
Understanding the Request Structure
The messages parameter is the heart of the API. It accepts a list of message objects, each with a role and content:
- system: Sets the assistant's behavior, persona, or instructions.
- user: Represents input from the human user.
- assistant: Previous responses from the model (used to maintain conversation history).
To build a multi-turn conversation, simply append each new message to the list and re-send the full history with each request.
Step 4: Build a Simple Chatbot Loop
from openai import OpenAI
client = OpenAI()
messages = [{"role": "system", "content": "You are a concise, helpful assistant."}]
print("Chat with GPT (type 'quit' to exit)")
while True:
user_input = input("You: ")
if user_input.lower() == "quit":
break
messages.append({"role": "user", "content": user_input})
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages
)
reply = response.choices[0].message.content
messages.append({"role": "assistant", "content": reply})
print(f"AI: {reply}\n")
Key Parameters to Know
- model: Which model to use.
gpt-4o-miniis fast and cost-effective;gpt-4ois more capable. - temperature: Controls randomness (0 = deterministic, 1 = creative). Default is 1.
- max_tokens: Caps the length of the response.
- top_p: An alternative to temperature for controlling output diversity.
Next Steps
With the basics working, you can extend this foundation to build document summarizers using file input, integrate the API into a Flask or FastAPI web app, use function calling to let the model trigger code execution, or experiment with streaming responses for a better user experience on longer outputs.