use openai api in javascript

To use the OpenAI API in JavaScript, you can use the fetch method or the axios library to make HTTP requests and interact with the API.

Here's an example using fetch:

index.tsx
const API_KEY = "INSERT_YOUR_API_KEY_HERE"
const prompt = "Hello, my name is"
fetch("https://api.openai.com/v1/engines/davinci-codex/completions", {
    method: "POST",
    headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${API_KEY}`
    },
    body: JSON.stringify({
        prompt: prompt,
        max_tokens: 5,
        temperature: 0.5
    })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error))
493 chars
18 lines

In this example, we're using the Davinci Codex engine to generate text completions based on the prompt "Hello, my name is". We're setting the max_tokens to 5 and the temperature to 0.5 to control the length and randomness of the generated text. We're also including an Authorization header with our API key.

Here's an example using axios:

index.tsx
const API_KEY = "INSERT_YOUR_API_KEY_HERE"
const prompt = "Hello, my name is"
axios.post("https://api.openai.com/v1/engines/davinci-codex/completions", {
    prompt: prompt,
    max_tokens: 5,
    temperature: 0.5
}, {
    headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${API_KEY}`
    }
})
.then(response => console.log(response.data))
.catch(error => console.log(error))
414 chars
15 lines

This example is similar to the previous one, but we're using axios to make the HTTP request. We're again including an Authorization header with our API key. Note that axios.post takes the request body as its second argument rather than as part of the body property.

gistlibby LogSnag