Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Connect To AI with API

Install The dotenv package

task

  1. Run this command in the terminalnpm install dotenv --save to download the dotenv package
  2. Import the .env file -> import 'dotenv/config'

Import the OpenAI API

info

  1. Install OpenAI by running this npm install openai
  2. We need the OpenAI library and our API key to make requests. The key is stored in a variable called process.env

tip

import OpenAI from "openai";
const apiKey = process.env.OPENAI_API_KEY

Create the Client

info

The client is how we talk to OpenAI.

tip

const client = new OpenAI({ apiKey });

Send a Request to OpenAI

info

  • client.chat.completions.create(...) sends a message to the AI.
  • We use the gpt-3.5-turbo model for the basic text responses. (More models you can try: (OpenAI Models)[https://platform.openai.com/docs/models])
  • The input message goes inside messages.

tip

const response = await client.chat.completions.create({
    model: "gpt-3.5-turbo",
    messages: [{ role: "user", content: <Insert prompt here> }]
});