Don't understand how to add enum validation to function call

Hi! I’m new to scripting and am hoping someone can help answer my questions :sweat_smile: I’m using a script in Google Sheets (App Scripts) for function calling. I’ve used enum in my prompt to ask GPT to categorize something from a list of values, but it occasionally returns a response outside of the list. I know from digging around that I can add a validation, but I just don’t understand where in my script it’s supposed to go.

// Function to call the OpenAI API, formatted as the function call below. 
function feedback_func(prompt, temperature = DEFAULT_TEMPERATURE, model = DEFAULT_MODEL, maxTokens = DEFAULT_MAXTOKENS) {
  // Setting up the data for the API call
 var data = {
    temperature: temperature,
    model: model,
    messages:[
      {"role":"system","content":"You are CodingGPT, a large language model trained to categorize content. You are a researcher in a customer service context. You are specialized in customer experience and product research."},
      {"role":"user","content":prompt}
    ],
    max_tokens: maxTokens,
    functions: [
        {
          //SYSTEM PROMPT - edit the description if you need the model to adapt to what you are prompting e.g. if you have a particular text and need to teach the model how to interpret it
      "name": "feedback",
      "parameters": {
        "type": "object",
        "properties": {
          "complaint": {
            "type": "string",
              "enum": [
                "Value 1",
                "Value 2",
                "Value 3"
],
            "description": "Assign only if the user explicitly expresses a complaint. Only assign ONE."
          },
},
        required: [
          "complaint"
        ],
      },
    },
  ],
    function_call: { name: "feedback" },
  };

  // Options for the API call 
  var options = {
    method: "post",
    contentType: "application/json",
    payload: JSON.stringify(data),
    headers: {
      "Authorization": `Bearer ${OPENAI_API_KEY}`,
      //"OpenAI-Organization": `${ORG_ID}`,
      "Content-Type": "application/json",
    },
  };
 
  // Making the API call
  var response = UrlFetchApp.fetch(
    OPENAI_API_URL,
    options
  );
  response = JSON.parse(response.getContentText());

  // Extracting relevant information from the response
  const functionArguments = response.choices[0].message.function_call.arguments;
  const promptTokens = response.usage.prompt_tokens;
  const completionTokens = response.usage.completion_tokens;
  const totalTokens = response.usage.total_tokens;
  
  // Returning the relevant information
  return { functionArguments, promptTokens, completionTokens, totalTokens };
}

//An example wrapper function that combines all the above for easy calling in the sheet
/**
 *awesome script
 * @customfunction
 */
function feedback(dataArray, prompt, temperature, model, maxTokens) {
   // Placeholder B) where you add prompts functions in the results
  return egFullGeneric(feedback_func, dataArray, prompt, ['complaint'], temperature, model, maxTokens);
}

Hope that helps! Thanks in advance

Welcome @pine.cadet

You can simply look at the function call object within the response. Here’s how it looks before json parsing it:

"function_call": {
          "arguments": "{\n  \"location\": \"Boston, MA\"\n}",
          "name": "get_current_weather"
        },

Corresponding to the function definition:

"functions": [
    {
      "name": "get_current_weather",
      "description": "Get the current weather in a given location",
      "parameters": {
        "type": "object",
        "properties": {
          "location": {
            "type": "string",
            "description": "The city and state, e.g. San Francisco, CA"
          },
          "unit": {
            "type": "string",
            "enum": ["celsius", "fahrenheit"]
          }
        },
        "required": ["location"]
      }
    }
  ]

One you parse the function_call object, simply validate the value of complaints argument.

const complaint = functionArguments["complaint"];
const validComplaints = ["Value 1", "Value 2", "Value 3"];
  if (!validComplaints.includes(complaint)) {
    // Handle the invalid complaint here
    return { error: "Invalid complaint received" };
  }
1 Like

Thank you so much! Your instructions were very clear. I was able to implement this and it appears to be working.

1 Like