10 min read 1 day ago

Use Function Calling

First, read the “Function Calling Overview” documentation to understand what Function Calling and Code Engine are. If you don’t, you won’t understand what happens next or how to customize things yourself.

Let’s get started by going to the Code Engine dashboard. Click the “+ Add” button to open a new code editor.

Notion Image

Now, for this tutorial, let’s create a function that sends an email notification when a new conversation starts on your chatbot. Of course, this can only work if your server is already configured to send emails, either through an SMTP server or a third-party service. In this example, we will use only built-in WordPress functions. As this code is sending a mail using WordPress we want this code to run the server, so let’s use PHP.

function send_mail_notifier( $first_message, $topic ) {
    // Get the website admin email
    $admin_email = "admin@website.com";
    // You can of course get your mail from an option if you have this setup already:
    // $admin_email = get_option( 'admin_email' );
    
    // Get the current date
    $current_date = date('Y-m-d H:i:s');

    // Check if user is logged in
    if ( is_user_logged_in() ) {
        $current_user = wp_get_current_user();
        $user_info = "User ID: " . $current_user->ID . "\n";
        $user_info .= "Username: " . $current_user->user_login . "\n";
        $user_info .= "Email: " . $current_user->user_email . "\n";
    } else {
        $user_info = "User: Guest\n";
    }

    // Prepare the email subject and message
    $subject = "Notification from your website";
    $message = "Date: " . $current_date . "\n";
    $message .= $user_info;
    $message .= "Message: " . $first_message . "\n";
    $message .= "Topic: " . $topic . "\n";

    // Send the email
    wp_mail( $admin_email, $subject, $message );
}

So the code above will effectively send you an email containing information about the user (if they are logged in), the content of the first message, and the initiated topic. If you are wondering how these parameters ($first_message, $topic) are going to be handled, don’t worry. The AI will determine these values for you, so you don’t have to do anything. Feel free to modify the code to fit your use case.

Now that the code is ready, we are going to paste it inside the Code Engine editor and make sure that we have selected the “Callable” type in the settings on the right panel.

Notion Image

In the image above, we also inserted a description of what the code is supposed to do. The AI has access to this information, so it will help it understand why and when to use this specific code. We can also add descriptions for the parameters, as their usage may not be obvious to the AI. Consider these descriptions as “little prompts” that tell the AI what to use for each parameter.

Notion Image

Here are the different descriptions used in this example:

  • “$first_message: The first message of the conversation, from the user.”
  • “$topic: If the first message evokes a certain specific topic, specify it.”

You can also see a “default value” setting here. This is used if, for some reason, the parameter is null ( empty ), allowing you to manually choose a default value.

You can also choose the type of the argument—in our case, a message would be a string. But for more advanced usage, you can create functions that have numbers, arrays, and all kinds of other argument types.

Before finalizing this code, you have the ability to test it to ensure everything is running smoothly and there are no mistakes in your code. This step is not mandatory, so you can skip it if you want, but it might be handy when you create your own snippets. What we are going to do is temporarily replace the function that sends us an email with an “echo” statement. This way, it won’t send anything, but we will have a chance to check the values that would have been sent in the “test console.” So, the last lines of our code should be replaced as shown below.

   	// Send the email
    // wp_mail($admin_email, $subject, $message);
    echo( json_encode( [ $subject, $message ] ) );

Now you can head to the “Test” tab. Here, you have the possibility to select all the parameters your function has and attribute them a test value. In the example below, the parameter “$first_message” has the test value “This is a message.” We don’t see it here, but the “$topic” has the value “This is a topic.” If you have previously inserted a “default value” for your parameters, you don’t even have to choose any test values; leaving them empty will cause the default value to be used. So, if we now run the test, we should see an output containing a preview of our email.

Notion Image

So far, so good! Don’t forget to replace that temporary “echo” statement back with the actual code to send an email, of course, because we are now ready to test it live with the chatbot. Go back to AI Engine, where you have your chatbot ready to use functions. You can now see in the “Functions” dropdown menu our newly created snippet. Just select it, and you’re done. Function Calling becomes that simple with AI Engine!

Notion Image

To make things extra clear for our Chatbot, let’s modify our instructions to specify that whenever a new conversation starts, it should use our function. Here’s the updated instruction for the current example:

“When a new conversation starts, use the send_mail_notifier function. This function will include the customer’s first message and the related topic. If there doesn’t seem to be a topic, such as only greetings or a simple question, ask the customer what specific topic they are inquiring about, and then use the function to send the mail. Once this function has been used, it should not be used again in the current discussion.”

Feel free to adjust this for your specific needs. Now, let’s see it in action.

Notion Image

It sounds like everything is running smoothly! While the chatbot is engaging in conversation as usual, let’s check our email to see what’s waiting for us.

Notion Image

Beautiful! Imagine all that you can achieve with Function Calling. Now, it’s your turn to give it a try! Here’s a little exercise to see if everything is clear for you: instead of using “Notification from your website” as the email title, let’s use our “Topic” which will convey more information. It’s just a little tweak to do in the snippet code, but I’m sure you can handle it.

You now understand how to use function calling. Of course, this requires a minimum of technical knowledge. You can always use ChatGPT to help you, but it’s not yet as adept as a real developer, as it doesn’t fully understand the context of more complex use cases. So, use it at your own risk. Don’t be afraid to reach out to a freelancer; we have some really talented people who work with AI Engine in our Discord community. They will gladly enhance your AI Engine experience if you reach out to them.

In this example, we didn’t return any value from this function. It just runs a process on our server. But of course, you can return a value.

The returned value lets the AI know the output of the function. For example, you could return a message like “the mail has been sent” or “the mail could not be sent” to let the AI know what happened during the function’s execution.

The return value must be readable. You can’t return an object or an array for instance, so make sure to use the json_encode() function whenever you return any value so make it bullet proof.

If your function call is something like a web search, you’ll of course need to return the search results so the AI model can use that information in its response. This return value becomes part of the context the model relies on to generate an informed reply.

Note that if the output of your function indicates an error and the type is dynamic, the AI might try to run the function a couple more times until it succeeds.

Front Function Calling ( JavaScript )

Of course, you can do the same things we just did with PHP, but on the front end—letting the AI run JavaScript snippets directly on your website.

Instead of selecting PHP, you just need to select JS as the callable type, and that’s it!

Imagine we have an element called “block” on our page. We’ll create a simple function to change its color to whatever the user wants.

const change_block_color = (color) => {
    const element = document.getElementById('block');
    if (element) {
        element.style.backgroundColor = color;
    } else {
        console.error(`Block not found.`);
    }
}

Once this is done, make sure you don’t forget to enable this function for your chatbot, or it won’t be able to trigger it. For this, like any other function, go into your chatbot settings and ensure you have checked the newly created function.

Notion Image

Then your chatbot will be able to execute this function as it will be declared in the DOM from Code Engine. Let’s see an example here:

Notion Image

Manual Function Calling

Part 1: Declaring Functions

There are two ways to declare functions for use with AI Engine:

Method 1: Register Functions Naturally

This filter allows functions to be selectable in the Chatbot’s settings, just like Snippet Vault registered functions.

add_filter( 'mwai_functions_list', function ( $functions ) {
  $functions[] = define_userInfo();
  $functions[] = define_sendEmail();
  return $functions;
}, 10, 1 );

To use this filter, you will need to have your function defined. Let’s have a look at how to define functions.

You can define your functions using Meow_MWAI_Query_Function::fromJson():

 return Meow_MWAI_Query_Function::fromJson( [
      'id' => 'userInfo',
      'type' => 'manual',
      'name' => 'getCurrentUserInfo',
      'desc' => 'Get the current user information.',
      'args' => [
        [
          'name' => 'license',
          'type' => 'string',
          'required' => true,
          'desc' => 'User serial key.',
        ],
      ],
    ] );

Method 2: Force-add Functions to the Query

This method adds functions directly to the query, but won’t work with OpenAI Assistants, since they need to be added to the Assistants before use.

add_filter( 'mwai_ai_query', function ( $query ) {
  $query->add_function( define_userInfo() );
  $query->add_function( define_sendEmail() );
  return $query;
}, 10, 1 );

Part 2: Handling Function Calls

Once functions are declared, you need to implement how they’re called. There are two approaches, depending on how you declared you functions. If you declared them with Method 1 you need handle them with Method 1 as well.

Method 1: Provide Feedback to the AI Model

This method allows the AI model to process the function’s output and incorporate it into the final answer.

add_filter( 'mwai_ai_feedback', function ( $value, $needFeedback ) {
  $function = $needFeedback['function'];
  if ( $function->id === 'userInfo' ) {
    return call_userInfo();
  }
  else if ( $function->id === 'sendEmail' ) {
    $subject = $needFeedback['arguments']['subject'];
    $message = $needFeedback['arguments']['message'];
    return call_sendEmail( $subject, $message );
  }
  return $value;
}, 10, 2 );

Method 2: Override the AI Reply

This method allows you to completely override the AI’s reply based on the function’s output.

add_filter( 'mwai_ai_reply', function ( $reply, $query ) {
  foreach ( $reply->needFeedbacks as $index => $needFeedback ) {
    $function = $needFeedback['function'];
    if ( $function->id === 'userInfo' ) {
      $value = call_userInfo();
      if ( !empty( $value ) ) {
        $reply->result = "Here is your data: " . $value;
        unset( $reply->needFeedbacks[$index] );
        return $reply;
      }
    }
  }
  return $reply;
}, 10, 2 );

Implementation Notes

  • You can add this code to your theme’s functions.php file or use a snippet tool like Snippet Vault.
  • When declaring functions, use Meow_MWAI_Query_Function::fromJson() to define the function’s properties.
  • For functions with arguments, define them in the args array of the function definition.
  • Choose either Method 1 or Method 2 for both declaring and handling function calls.