Connect To AI with API
Install The dotenv package
task
- Run this command in the terminal
npm install dotenv --save
to download the dotenv package - Import the
.env
file ->import 'dotenv/config'
Import the OpenAI API
info
- Install OpenAI by running this
npm install openai
- 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> }]
});