traintocode

Calling OpenAI

To make the call to OpenAI you can use the OpenAI Node API Library which you can import and create a new instance of using:

import OpenAI from "openai";

const openai = new OpenAI({ apiKey: process.env['OPENAI_KEY'] });

The logic for your cloud function will be to pass a system prompt to OpenAI, followed by the messages array from the request body.

The system prompt will instruct OpenAI to talk like a pirate and looks like this:

const systemPrompt:OpenAI.Chat.Completions.ChatCompletionMessageParam = 
{
    role: "system",
    content: "You are a helpful assistant who talks like a pirate"
}

This ensure the response we get back from OpenAI will be in pirate speak! You can then return the response message back to the front end.

Exercise
1. Create a new instance of the OpenAI class that is being imported, using the API key from process.env['OPENAI_KEY'].

2. Call the method openai.chat.completions.create() passing in your system prompt and the array of chat messages from the previous exercise. Put the response into a variable called gptResponse.

3. Read the response message from gptResponse.choices[0].message.content and return it in the result's body field.
    You cannot do the coding exercises on this device, visit this page on a larger screen.
    handler.ts
    Loading...