Open AI GPT-3 API Tutorial JS
How to use the GPT-3 API in Node JS to generate text for any use.
Installation
1npm install openai
Authentication
The OpenAI API uses API keys for authentication, the best practice is to store the key in an environment variable to prevent accidental exposure to the web. You can get your API key from the API keys page on OpenAI's website.
The code below show's the basics of authenticating with the JS SDK, the API key is pulled from the environment variable set using process.env
. Then the configuration object if passed to the OpenAIApi
class.
1import { Configuration, OpenAIApi } from "openai";
2const configuration = new Configuration({
3 apiKey: process.env.OPENAI_API_KEY,
4});
5const openai = new OpenAIApi(configuration);
Creating a Request
GPT-3 is a General Purpose Text model designed to complete chunks of text, to use it with the JS SDK call the OpenAIAPI
classes method createCompletion
. The createCompletion
method has a configuration object where you can pass in arguments.
The code below is an example of a completion, type the text you want to be completed to generate a runnable code snippet.
Input
@[text]{Say this is a test}
1const response = await openai.createCompletion({
2 model: "text-davinci-003",
3 prompt: "@{text}",
4 max_tokens: 7,
5 temperature: 0,
6});
Response
This is an example response of a completion with a prompt of Say this is a test
. The result is stored in the choices
array with other meta data in the object.
1{
2 "id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7",
3 "object": "text_completion",
4 "created": 1589478378,
5 "model": "text-davinci-003",
6 "choices": [
7 {
8 "text": "\n\nThis is indeed a test",
9 "index": 0,
10 "logprobs": null,
11 "finish_reason": "length"
12 }
13 ],
14 "usage": {
15 "prompt_tokens": 5,
16 "completion_tokens": 7,
17 "total_tokens": 12
18 }
19}
20
This is just the basics of getting started with the GPT-3 API, in the next post we will talk about how to generate images using DALLE-2 using the JS SDK.