This tutorial will guide you on how to access and use the OpenAI API in Python in just a few simple and fast steps. OpenAI offers an API that provides access to its AI models, ranging from GPT-3.5, and GPT-4 to Dall-e-3 and Whisper. This allows you to enjoy benefits like content generation, language translation, code generation and even building your own customized AI tools. In this tutorial, we will show the basics, so you can immediately start with making your first API request in Python by calling the GPT-3.5 model.
For a beginner’s guide on how to access the OpenAI API within R, check out our tutorial HERE.
Requirements:
- Python is installed on your computer. Check out this article from Tilburg Science Hub for a tutorial on this.
- An IDE, such as VSCode, is installed on your computer. Again, look at this tutorial from Tilburg Science Hub.
Setting up your environment
- Create or Log Into Your OpenAI Account:
- Visit OpenAI’s API documentation website and either sign in with an existing account or create a new one. This step is crucial as it grants you access to the API keys required for authentication.
- Generate an API Key:
- Navigate to the API keys section within your OpenAI account dashboard.
- Create a new API key. Remember to copy this key immediately, as it won’t be visible again once you navigate away from the page.
- Secure Your API Key Using Environmental Variables:
MacOS
- Open your terminal or command prompt.
- Run the command
nano ~/.zshrc
to open your bash profile in the nano editor. (Note: for older MacOS versions, you might need to run nano~/.bash_profile
instead). - You can edit the file by pressing control + O and then enter.
- Add the line
export OPENAI_API_KEY='your-api-key'
at the end of the file, replacingyour-api-key
with the actual key you obtained earlier. - Save the file by pressing
Ctrl + X
,y
and then hitEnter
. - Apply the changes by running
source ~/.zshrc
or restart your terminal.
Windows
- Right-click on ‘This PC’ or ‘My Computer’ on your desktop or in File Explorer, and select ‘Properties’.
- Click on ‘Advanced system settings’ on the left side of the System window.
- In the System Properties window, click the ‘Environment Variables’ button near the bottom of the Advanced tab.
- In the Environment Variables window, under the ‘System variables’ section, click ‘New…’ to create a new system variable.
- In the New System Variable dialog, enter
OPENAI_API_KEY
as the variable name and your actual API key as the variable value. - Click ‘OK’ to close the New System Variable dialog. Then, click ‘OK’ again to close the Environment Variables window, and click ‘OK’ once more to close the System Properties window.
4. Verifying Your API Key:
- In the terminal, run
echo $OPENAI_API_KEY
when using a Mac, andecho %OPENAI_API_KEY%
when using Windows. - This command should return your API key, confirming it has been correctly set up as an environmental variable.
Integrating OpenAI API with Python
- Install the OpenAI Python library
install the OpenAI Python package. You can do so by runningpip install --upgrade openai
in your terminal. - Import Required Packages
Start by opening your IDE and creating a new Python file. At the top of the file, import the necessary packages for interacting with the OpenAI API:
from openai import OpenAI
import os
- Initialize the OpenAI Client:
Use the following code snippet to initialize the OpenAI client with your API key:
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
- Generate Text with the OpenAI API
You can now generate text completions by calling theclient.chat.completions.create()
function. This function specifies the model (gpt-3.5-turbo
in this case) and simulates a conversation between a user and the assistant. Here’s what’s happening inside thecreate()
method:model="gpt-3.5-turbo"
: Specifies the model to use for the text generation. In this case, “gpt-3.5-turbo” is chosen. For more alternative models you can check this overview.messages
: This is a list of messages that simulate a conversation between a user and the assistant. Each message is a dictionary with two keys: role and content. The role can be either “system”, “user”, or “assistant”, indicating the sender of the message.
Here’s a basic example:
completion = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": "Tell a good joke in the form of a question. Do not yet give the answer."}
]
)
- Display the Generated Text:
To view the text generated by the API, print the content of the message:
print(completion.choices[0].message.content)
Here is the full Python code to be able to copy it all at once:
from openai import OpenAI # Import the OpenAI package
import os # Import the os package
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
completion = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": "tell a good joke in the form of a question. Do not yet give the answer."}
]
)
print(completion.choices[0].message.content)
Conclusion
In summary, this guide has walked you through the necessary steps to access and use the OpenAI API, particularly focusing on generating text with the GPT-3.5 model. While this guide focuses on text generation with GPT-3.5, OpenAI’s API encompasses a wide range of models, including those for image generation (DALL-E) and audio transcription (Whisper). The examples and code provided here serve as a starting point.