OpenAI API Hello World!¶
Getting started¶
To use the OpenAI API to create a simple "Hello World" program, you can follow these steps:
- Install the OpenAI Python library by running the command
pip install openaiin your terminal or command line. - Get your secret API key from your API Keys page and save it somewhere safe. Do not share it with anyone or expose it in any client-side code.
- Set up your API key in your Python code by importing the
osmodule and using theopenai.api_key = os.getenv("OPENAI_API_KEY")statement. Make sure to replace"OPENAI_API_KEY"with the name of the environment variable that stores your API key. - Send a request to the OpenAI API using the
openai.Completion.createmethod. You can specify the engine, the prompt, and other parameters to customize the request. For example, you can use the following code to generate a completion for the prompt "Hello, world!" using thegpt-3.5-turboengine and limiting the output to 10 tokens:
import openai
import os
# Set up your API key
openai.api_key = os.getenv("OPENAI_API_KEY")
# Send a request to the OpenAI API
response = openai.Completion.create(
engine="gpt-3.5-turbo",
prompt="Hello, world!",
max_tokens=10
)
# Print the response text
print(response.choices[0].text)
- Run the code by entering
python openai-test.pyin your terminal or command line, whereopenai-test.pyis the name of your Python file. You should get a response text that resembles the following: