Connect to GPT-4o

Template
Function
45
Template
Function
by
Denys Linkov

Use Open AI’s latest model with a Voiceflow function. GPT-4o 50% cheaper, twice as fast and does better on a variety of tasks. Start building today!

Created:

Heading

Voiceflow APIs used:

Channels
No items found.
Created By
Denys Linkov
This is some text inside of a div block.

Function Code Snippet

 
export default async function main(args) {
// Extract input variables from args
const { last_utterance, openaiApiKey } = args.inputVars;

// Validate that the required input variables are provided
if (!last_utterance || !openaiApiKey) {
return {
next: { path: 'error' },
trace: [{ type: "debug", payload: { message: "Missing required input variable: last_utterance or openaiApiKey" } }]
};
}

// Define the URL for the OpenAI API
const url = `https://api.openai.com/v1/chat/completions`;

// Configure the request payload for the OpenAI API
const data = {
model: "gpt-4o",
messages: [
{
"role": "system",
"content": "You are an assistant. Please respond thoughtfully and informatively."
},
{
"role": "user",
"content": last_utterance
}
]
};

// Configure the fetch request headers and body
const config = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${openaiApiKey}`
},
body: JSON.stringify(data)
};

try {
// Make the API call
const response = await fetch(url, config);

// Check if the response status is OK
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

// Parse the JSON response
const responseBody = await response.json;

// Validate the responseBody structure as expected
if (!responseBody || typeof responseBody !== 'object') {
throw new Error("Invalid or missing response body from the API");
}

// Extract the response text from the completion
const completion = responseBody.choices[0].message.content;

// Create the success return object with extracted data
return {
outputVars: { completion },
next: { path: 'success' },
trace: [
{
type: "text",
payload: { message: `Received response from GPT-4: ${completion}` }
}
]
};
} catch (error) {
return {
next: { path: 'error' },
trace: [{ type: "debug", payload: { message: "Error: " + error.message } }]
};
}
}
copy-icon

Explore More Templates

Build and submit a Template to have it featured in the community.

ghraphic
No items found.
No items found.