Create a JSON format response from OpenAI in WhatsApp

Ana Updated by Ana

In this article, we will see how to generate a response in JSON format using Open AI.

Specifically, in this example, we will see how to classify a user request in WhatsApp. Imagine the bot collects user complaints and we need to get the user name, product name, and the summary of the complaint.

The flow will be as follow:

  1. The first block is the question we want to do to our customers:

"How can I help you? Please, provide your full name, the product or service about your inquiry, and a description of the issue."

  1. Create the message_object array variable, that will contain the customer answer.
[{"role": "user", "content": "@text"}]

  1. Add the functions_object array variable. This variable will contain the function that we will describe and that will return a specific JSON format.
[         
{
"name": "lead_data",
"description": "Extract product_name, issue_summary and user_name entities from the content",
"parameters": {
"type": "object",
"properties": {
"product_name": {
"type": "string",
"description": "The name of the product mentioned in content"
},
"issue_summary": {
"type": "string",
"description": "A summary of the problem mentioned in content"
},
"user_name": {
"type": "string",
"description": "The name of the user mentioned in content" }
},

"required": ["product_name", "issue_summary", "user_name"]

}
}
]

The function we are referring to is called "lead_data". However, it should be noted that this function does not currently exist. Nevertheless, you can provide a description for this function in the "description" field. This description will be helpful in providing context and improving the quality of responses.

Next, we need to define the "parameters" as an "object" type, including all the desired "properties" that were mentioned in the function's description. For each parameter, you should specify its name, type, and provide a description that accurately explains the purpose of the parameter.

Additionally, consider marking any parameters that should be included in the JSON format as mandatory by including them in the "required" field.

  1. In the Webhook we use the chat/completions URL and the OpenAI API Key as header of the request:

  1. In the body you must include the following:
{
"model": "gpt-3.5-turbo-0613",
"messages": "@message_object",
"functions": "@functions_object",
"function_call": {"name": "lead_data"}
}

The property "function_call" contains the name of the function we created before: "lead_data", and it will be called each time the Webhook is triggered.

  1. Add examples for the variables and test the request.

Save the variable as an array type:

  1. Then convert that array into a real JSON object using the Formula Block.
ToJSON(@lead_data)

See how the flow works and the object we receive:

How did we do?

Connect OpenAI Assistant with Landbot

Contact