OpenAI allows its users to use these models with their comprehensive API documentation. In this tutorial, you will learn how to use the Completions API provided by OpenAI.
Note: If you are intending to use this API for large company-sized applications, check out the OpenAI pricing.
Install OpenAI for python
pip install openai
For macOS and Linux systems, use pip3 install openai
Create a file main.py
import openai
openai.api_key = "PASTE_YOUR_API_KEY_HERE"
This completes authorization to access the API. Check here on how to get an API Key
question = "What are the five top programming languages in 2023"
response = openai.Completions.create(model="text-davinci-003", prompt=question)
print(response)
The model is set to text-davinci-003
in this example but can be customized to meet other choices. This allows us to interact with the API to get the answer to the prompt provided.
The Response
{
"id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7",
"object": "text_completion",
"created": 1589478378,
"model": "text-davinci-003",
"choices": [
{
"text": "\n\nThis is indeed a test",
"index": 0,
"logprobs": null,
"finish_reason": "length"
}
],
"usage": {
"prompt_tokens": 5,
"completion_tokens": 7,
"total_tokens": 12
}
}
The response shown above is how it will come from OpenAI. The created
variable stands for the time in Unix time that the response was created. The list of choices
returned stand for the output variations from the API. The number of variations can be set by adding the variable n
in the create()
function to create more variations.
response = openai.Completions.create(model="text-davinci-003", prompt=question, n=3)
Other values from the response are self-explanatory.
This is just scratching the surface. OpenAI API can allow you to do a lot of other things like Text Editing, Text completion and others. Check out the full API reference