Code completion and Image generation using OpenAI API

This article is about how to write code for OpenAI API for code completion and image generation.

Steps before writing code.

OpenAI page

You can try the code generation in playground. OpenAI playground is a place where you can try code generation examples.

OpenAI API

https://beta.openai.com/docs/api-reference/introduction

Here you will find a link to API key page Account API Keys — OpenAI API where you can download the key (copy to clipboard) and later used in code.You may have to purchase through billing page. Pricing (openai.com)

For image generation the following code can be used as an example.

!pip install openai
import os
import openai
openai.organization = “your organization”
openai.api_key = “your key”
response = openai.Image.create(
prompt=”mountain with cloud”,
n=2,
size=”1024x1024"
)
image_url = response[‘data’][0][‘url’]

Your organization id can be found on the page Organization settings — OpenAI API.

The above code runs in Colab google. ‘os’ is imported if key is to be fetched from the environment variable. Organization name and key are to be assigned from the above organization page Organization settings — OpenAI API and key page Account API Keys — OpenAI API. Then openai.Image.create is called with:
‘prompt’ as the text to convert to image,
’n’ number of images to generate and
‘size’ is size of image to generate.

For code completion the following can be used:

import openai
openai.organization = “your organiztion”
openai.api_key = “paste your key”

import requests
headers = {
# Already added when you pass json=
# ‘Content-Type’: ‘application/json’,
‘Authorization’: ‘Bearer paste your key here’ }
json_data =
{
‘model’: ‘text-davinci-003’,
‘prompt’: ‘Say this is a test’,
‘temperature’: 0,
‘max_tokens’: 7,
}
response = requests.post(‘https://api.openai.com/v1/completions', headers=headers, json=json_data)
print(response.text)

Here response HTTP request is posted with headers and json data. The ‘model’ is the name of model to be used,
‘prompt’ is the text to be completed,
‘temperature’ is the measure of randomness and
‘max_tokens’ is the maximum number of tokens to generate.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store