Accessing GPT-4.1 with the OpenAI API
This step-by-step guide will help you access GPT-4.1 (or GPT-4o) using Python and the OpenAI API.
Prerequisites
- An OpenAI account
- Your OpenAI API key (get it here)
- Python 3 installed on your computer
1. Install the OpenAI Python Library
Open your terminal or command prompt and run:
pip install openai
2. Set Your OpenAI API Key
Recommended:
Set your API key as an environment variable for better security.
Mac/Linux:
export OPENAI_API_KEY="your-api-key-here"
Windows CMD:
set OPENAI_API_KEY=your-api-key-here
Or you can paste the API key directly in your code (not recommended for production).
3. Example Python Script
Create a new file called gpt4_example.py and add the following code:
import os
import openai
# Set your API key
openai.api_key = os.getenv("OPENAI_API_KEY") # Or paste directly: "sk-..."
# Choose the GPT-4.1 model name (as of May 2024, use 'gpt-4-1106-preview' or 'gpt-4o')
model_name = "gpt-4-1106-preview" # Try "gpt-4o" if you have access
response = openai.ChatCompletion.create(
model=model_name,
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Write me a Python function that reverses a string."}
],
max_tokens=200,
temperature=0.7,
)
print(response.choices[0].message["content"])
4. Run Your Script
Save the script and run it in your terminal:
python gpt4_example.py
You should see the GPT-4.1 response printed out.
5. Explanation
openai.ChatCompletion.createcalls GPT-4.1 in a conversational context using a list ofmessages.modelshould match the GPT-4.1 model name (gpt-4-1106-preview,gpt-4o, orgpt-4-turbo).- The assistant replies to the prompt in the
"content"field.
Extra Tips
- Change the prompt to experiment with different tasks.
- Try the OpenAI Playground for quick testing.
- For commercial or high-volume use, review OpenAI's pricing.
- Model names may change as new versions are released. See the latest models here.
References
If you need an example in another language (JavaScript, Node.js, etc.) or want to learn about advanced features, just ask!