Back to all functions

Connect to GPT-o1

Use Open AI’s latest model with a Voiceflow function. GPT-o1 improved logic and reasoning. Start building today!

Created By
Daniel D'Souza
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: "o1-preview",
    messages: [
      {
        "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 o1: ${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
No items found.