Back to all functions

Connect to GPT-4o

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 By
Denys Linkov
Voiceflow
download-icon
INPUT VARIABLES
{
openaiApiKey
}
{
last_utterance
}
ID of the user.
{
}
{
}
{
}
{
}
share-icon
OUTPUT VARIABLES
{
completion
}
The first and last name of the user.
{
}
{
}
{
}
{
}
{
}
paths-icon
PATHS
{
Success
}
Success
{
Error
}
Error
{
}
{
}
{
}
{
}

Function Walkthrough

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

Have something to share?

Share your creation with over 250,000 other global Voiceflow users.

ghraphic