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.
OpenAI
class that is being imported, using the API key from process.env['OPENAI_KEY']
.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
.gptResponse.choices[0].message.content
and return it in the result's body
field.