Skip to content

Connecting to OpenAI GPT-4o Using Python

πŸš€ Connecting to OpenAI GPT-4o Using Python

This guide explains how to connect to OpenAI’s GPT-4o model using Python, pass user roles and questions, and retrieve responses. It also includes steps to check existing API tokens and generate a new one if required.


πŸ”Ή Prerequisites

1️⃣ Check If You Have an OpenAI API Key

Before making API requests, check if you already have an OpenAI API Key:

  1. Go to OpenAI Platform.
  2. Click on your profile (top right corner) β†’ View API Keys.
  3. If you see an existing key, copy it.
  4. If no key exists, proceed to the next step.

2️⃣ Generate a New OpenAI API Key

If you don’t have an API key:

  1. Log in to OpenAI API Keys.
  2. Click β€œCreate new secret key”.
  3. Copy the generated key (it won’t be visible again).
  4. Store it securely in a .env file, environment variable, or directly in your Python script (if necessary).

πŸ”Ή Step-by-Step: Connecting to OpenAI GPT-4o

1️⃣ Install Required Python Packages

Ensure you have the openai package installed:

Terminal window
pip install openai python-dotenv

2️⃣ Setting Up the API Key

You can store the API key in two different ways:

Set your API key in your terminal (recommended for security):

Terminal window
export OPENAI_API_KEY="your-api-key-here" # Linux/macOS
set OPENAI_API_KEY="your-api-key-here" # Windows (CMD)
$env:OPENAI_API_KEY="your-api-key-here" # Windows (PowerShell)

Then, retrieve it in Python:

import os
api_key = os.getenv("OPENAI_API_KEY")

Option 2: Use a .env File

Create a .env file in your project folder and add:

OPENAI_API_KEY=your-api-key-here

Then load it in Python:

from dotenv import load_dotenv
import os
load_dotenv()
api_key = os.getenv("OPENAI_API_KEY")

If you don’t want to use environment variables or a .env file, you can hardcode the API key in your script:

api_key = "your-api-key-here" # Hardcoded API Key (Avoid for security reasons)

⚠ Warning: Hardcoding API keys in scripts is insecure and should be avoided in production.


3️⃣ Write Python Code to Connect to OpenAI API

Create a Python file (openai_chat.py) and add the following:

import openai
import os
from dotenv import load_dotenv
# Load API Key (Choose One of the Three Methods Above)
load_dotenv() # Only needed if using .env file
api_key = os.getenv("OPENAI_API_KEY") or "your-api-key-here" # Fallback to hardcoded key if needed
# Function to interact with GPT-4o
def chat_with_gpt(user_role, user_question):
client = openai.OpenAI(api_key=api_key)
response = client.chat.completions.create(
model="gpt-4o", # You can use 'gpt-4' or 'gpt-3.5-turbo'
messages=[
{"role": "system", "content": "You are a helpful AI assistant."},
{"role": user_role, "content": user_question}
]
)
return response.choices[0].message.content
# Example Usage
user_role = "user"
user_question = "What is the capital of France?"
response = chat_with_gpt(user_role, user_question)
print("AI Response:", response)

4️⃣ Run the Script

Execute the Python script:

Terminal window
python openai_chat.py

βœ… Expected Output:

AI Response: The capital of France is Paris.

πŸ”Ή Additional Configurations

Change the Model Version

Modify the model parameter in the chat_with_gpt() function to use different models:

model="gpt-4o" # GPT-4 Omni
model="gpt-4" # Standard GPT-4
model="gpt-3.5-turbo" # Cheaper & faster option

Modify Temperature for Creativity

The temperature parameter controls randomness:

temperature=0.7 # Higher values (0.7-1) make responses more creative

Use System Messages for Custom Behavior

Modify the system message to adjust the assistant’s personality:

messages=[
{"role": "system", "content": "You are a Python expert. Answer coding-related queries only."}
]

πŸš€ Conclusion

You have successfully: βœ” Verified and generated an OpenAI API key
βœ” Installed necessary dependencies
βœ” Written Python code to connect to OpenAI’s GPT-4o
βœ” Sent user roles & questions and received responses
βœ” Learned different ways to manage API keys (Environment Variable, .env file, Hardcoded - last one not recommended)

Now, you can build chatbots, AI-powered apps, and more using OpenAI’s powerful LLM models! πŸš€


References: