Published on

How to integrate with ChatGPT API in Python or Node and Typescript applications?

Authors

ChatGPT is a powerful language model developed by OpenAI, capable of generating human-like responses to natural language inputs. If you're looking to integrate ChatGPT into your application, this guide will help you get started.

Step 1: Sign Up for an OpenAI API Key

To use the ChatGPT API, you will need to sign up for an OpenAI API key. This can be done on the OpenAI website by following these steps:

  1. Go to the OpenAI website and create an account.
  2. Navigate to the API keys page.
  3. Create a new API key by following the instructions provided.
  4. Add billing information to your OpenAI account (without that requests to the endpoint tend to fail)

Once you have your API key, you can use it to authenticate requests to the ChatGPT API.

Step 2: Install the OpenAI SDK

The OpenAI SDK is a Python package that provides a convenient interface for working with the ChatGPT API. To install the SDK, run the following command:

pip install openai

For Node applications you'd add something like this to your package.json

  "dependencies": {
    "openai": "^3.0.0"
  },

Step 3: Initialize the OpenAI API Client

To start using the ChatGPT API, you will need to initialize an instance of the OpenAI API client. This can be done as follows:

import openai
openai.api_key = "YOUR_API_KEY"
import OpenAI from 'openai';
const openai = new OpenAI('YOUR_API_KEY');

Replace "YOUR_API_KEY" with your actual API key.

Step 4: Generate Text with the ChatGPT API

Once you have initialized the OpenAI API client, you can use it to generate text with the ChatGPT API. The following code generates a response to the prompt "Hello, how are you?" using the GPT-3 model:

response = openai.Completion.create(
    engine="davinci",
    prompt="Hello, how are you?",
    temperature=0.5,
    max_tokens=60,
    n=1,
    stop=None,
    frequency_penalty=0,
    presence_penalty=0
)

print(response.choices[0].text)

Here is the Typecsript code for the same integration:


const prompt = 'Hello, how are you?';
const engine = 'davinci';
const temperature = 0.5;
const maxTokens = 60;

async function generateResponse(prompt: string, engine: string, temperature: number, maxTokens: number) {
  try {
    const response = await openai.complete({
      engine,
      prompt,
      maxTokens,
      temperature,
    });

    console.log(response.data.choices[0].text);
  } catch (error) {
    console.log(error);
  }
}

generateResponse(prompt, engine, temperature, maxTokens);

This code sends a request to the ChatGPT API using the GPT-3 engine, with a temperature of 0.5 and a maximum length of 60 tokens. The API returns a response that includes a generated text response to the prompt.

Update

Note that davinci is an older model, you may want to use "gpt-turbo-3.5" which is cheaper and what the latest ChatGPT application as of date of this post, is based on.