API & Filters

Server-Side API (PHP)

I would like to make AI Engine extremely customizable so that you can achieve really everything you want with it. Here are the current available filters in the plugin.

Filters

Interactions with AI

  • mwai_ai_query( $query ) => Modify a query before it’s made
  • mwai_ai_allowed( $allowed, $query, $limits ) => Allow a query to be made or not
  • mwai_ai_reply( $reply, $query ) => Modify the answer before it’s sent (or do something at that time)
  • mwai_ai_function( $value, $funcName, $funcArgs ) => Inject the result of your own function, if in the case the function has been registered (function calling) and called by the model
  • mwai_ai_exception( $message ) => Modify the error message
  • mwai_estimate_tokens( $tokens, $text ) => Modify the estimated number of tokens for the given text (you can modify the default algorithm) used to calculate the tokens usage estimation.

Chatbot

  • mwai_chatbot_params( $params ) => Modify the final params just before the query is made
  • mwai_chatbot_takeover( $takeoverText, $query, $params )
  • mwai_contentaware_content( $content ) => Handle extra use cases, like looking for content in specific fields, or handling page builders, etc
  • mwai_chatbot_reply( $rawText, $query, $params, $extra ) => Modify the answer before it’s sent.

Embeddings

  • mwai_pre_post_content( $content, $postId ): Get the raw content from the post. You can modify it to add your custom field, etc. AI Engine will clean that content further, and make sure it’s not too large for the AI model.
  • mwai_post_content( $content, $postId ): The final content that will be used. You can also modify this.
  • mwai_context_search( $query, $embeddingIndex = null ): Returns the embedding the most related to the query.

Forms

  • mwai_form_params( $params ) => Modify the final params
  • mwai_form_reply( $rawText ) => Modify the answer before it’s sent

Limits

  • mwai_stats_credits( $credits, $userId ) => Modify the number of credits (that allows you to create your own system)
  • mwai_stats_coins( $price, $stats, $atts ) => Modify the coins (that allows you to convert the price you personally pay to OpenAI to your own system of coins that you share with your users)

Others

  • mwai_languages( $languages ) => Modify the list of languages
  • mwai_allow_setup( $hasAccess ) => Allow access to the Settings of AI Engine in the Admin
  • mwai_allow_usage( $hasAccess ) => Allow access to the various screens of AI Engine in the Admin

PHP Functions

If you would like to access AI features easily through AI Engine, simply use the mwai global. There will be more and more functions available to use. The API uses the whole AI Engine system, so you’ll get the statistics and limitations features as well.

simpleTextQuery( $prompt, $options )

You can use this function to simply run a query against the default model (turbo, currently). It’s as simple as that!

add_filter( 'the_content', function ( $content ) {
  global $mwai;
  $extra = $mwai->simpleTextQuery( "Write an one-liner about a cat introducing itself." );
  return $extra . $content;
} );

simpleChatbotQuery( $botId, $message, $chatId )

You can use this to discuss with one of your chatbots. The chatId is optional, but allows you to create a conversation. All the messages exchanged under the same chatId will be stored as a conversation. For this to work, you will need the Discussions to be enabled in the Settings.

simpleJsonQuery( $message, $url = null, $path = null )

This is similar to simpleTextQuery, except that it will return an array directly, representing the JSON. You can describe the attributes that you would like in the JSON in the prompt.

simpleVisionQuery( $message, $url, $path = null )

This is used to transcribe an image to text, based on your needs stated in the prompt. It is recommended to use an URL that points to your image, otherwise the path can be used and should point to a local file in your WordPress.

moderationCheck( $text )

Simply return true if the message has been flagged as unsafe to use.

PHP Classes

Meow_MWAI_Query_Text

You will find this usually named as $query and this class is used mainly for completion and chat. By default, it uses the turbo model, and relatively safe parameters. But of course, you can override everything you like. Here is an example on how to use it manually:

$query = new Meow_MWAI_Query_Text( "Translate 'Hello World' into French." );
$query->set_model( 'gpt-4-turbo' ); // Override the default model
global $mwai_core;
$reply = $mwai_core->ai->run( $query );
echo $reply->result;

There are the main functions:

  • $query->set_message( $message ): Set the message (known previously as prompt).
  • $query->get_message( $message ): Get the message.
  • $query->set_messages( $messages ): Set the former messages.
  • $query->set_instructions( $instructions ): Set or override the instructions (known previously as context).
  • $query->set_model( $model ): Set the model.
  • $query->set_temperature( $temperature ): Set the temperature (0.8 by default).
  • $query->set_max_tokens( $maxTokens ): Set the max tokens (1024 by default).
  • $query->set_max_results( $maxResults ): Specific the number of results (1 by default).
  • $query->set_context( $context ): Add an additional context.
  • $query->replace( $search, $replace ): Replace a string by another string in the message.
  • $query->set_api_key( $apiKey ): Set it if you would like to override the API Key for this query.

Meow_MWAI_Reply

You will find it usually named as $reply. Here are the main functions:

  • $reply->result: Return simply the first (or only) result.
  • $reply->results: Return an array with all the results.
  • $reply->replace( $search, $replace ): Replace a string by another string.
  • $reply->get_in_tokens( $query = null )
  • $reply->get_out_tokens( $query = null )

Interactive Functions (Function Calling)

For the latest documentations about functions, click here. Here, we’ll only cover the basics of interactive functions, but static functions are also available. Interactive functions enhance AI replies by adding relevant data and can be chained based on the AI’s decision-making. For instance, to “send an email to me” the AI might sequentially invoke functions to retrieve your information and then send your email. Using interactive functions ensures that responses are naturally integrated and AI-generated. You can register these functions either through Snippet Vault or manually.

Download and install Snippet Vault. Add a new snippet with the type function. This snippet should only have one function, well-defined, and free of errors. Here is an example:

function custom_current_user_information() {
// Check if the user is logged in.
if ( ! is_user_logged_in() ) {
return json_encode( array( 'error' => 'User not logged in' ) );
}

// Get current user's data.
$user = wp_get_current_user();

// Prepare the user data array.
$user_data = array(
'ID' => $user->ID,
'username' => $user->user_login,
'email' => $user->user_email,
'roles' => $user->roles
);

// Return JSON-encoded user data.
return json_encode( $user_data );
}


In AI Engine, Access the “Functions” section in your chatbot settings. The function you added in Snippet vault should be available here, in the chosen model support function calling. Select that function, then it will be run when needed. For example, you could ask the AI “What’s my name?”.

Public REST API

Every function from the PHP Functions is accessible through the REST API (https://domains.com/wp-json/mwai/v1/function_name). Use the POST method, with the parameters passed as JSON in the body.

Simple Examples

If you would like to run a simple AI query, you can do this:

POST https://yoursite.com/wp-json/mwai/v1/simpleTextQuery
{
  "prompt": "Give me a few facts about Bordeaux. Concise answer."
}

You can also chat directly with one one your chatbots:

POST https://yoursite.com/wp-json/mwai/v1/simpleChatbotQuery
{
  "prompt": "Hi! Who are you, actually?",
  "botId": "default"
}

Access Control

By default, the Public REST API is disabled completely. If you enable it, only authentified API requests will actually go through, otherwise they will be rejected. You can override this behavior in many ways and we will see a few examples. The Public REST API is also limited by the Limits set in AI Engine (either as Users or Guests, and System).

Authentified API Request

With WordPress REST API, to authentify your requests (which means they will be ran under a specific user in WordPress), you need to use nonces. Basically, you create the nonce on the WordPress side, for the current user, this way:

$my_nonce = wp_create_nonce( 'wp_rest' );

This nonce should be shared with the client (on the JS side, typically), then it can be used to make the requests, this way:

let nonce = "THE_NONCE_VALUE";
fetch('http://yoursite.com/wp-json/mwai/v1/simpleChatbotQuery', { 
  method: 'POST',
  headers: { 
    'Content-Type': 'application/json',
    'X-WP-Nonce': nonce
  },
  body: JSON.stringify({
    botId: 'default',
    prompt: 'Hello, who are you? What's up?'
  })
}).then(res => res.json()).then(console.log);

For more details about this, check the official documentation.

Full-Access to a Specific Feature

I don’t recommend it, but let’s say you would like to completely open the simpleTextQuery to everyone, or maybe for testing purposes. You can use the mwai_allow_public_api filter, which allows you to do this easily:

add_filter( 'mwai_allow_public_api', function ( $allow, $feature, $extra ) {
  if ( $feature === 'simpleTextQuery' ) {
    return true;
  }
  return $allow;
}, 10, 3 );

In this case, since the request is not authentified, the limits applied by AI Engine would be the ones related to the Guests. That said, you could also authentify them by force by calling the wp_set_current_user function. Be really careful when doing this.

add_filter( 'mwai_allow_public_api', function ( $allow, $feature, $extra ) {
  if ( $feature === 'simpleTextQuery' ) {
    wp_set_current_user(1);
    return true;
  }
  return $allow;
}, 10, 3 );

Custom Authentification

Let’s say you are building an external app for mobile, or maybe calling AI Engine from a different website or system; you will need to create your own authentification. For this, I recommend using a Bearer Token. Don’t worry, it’s easy! Use the mwai_allow_public_api filter to authorize the request. The $extra argument contains actually all the data about the incoming request. You can retrieve the token from it, and check if it’s the right one. You can secure it further by checking the IP address, etc.

add_filter( 'mwai_allow_public_api', function ( $allow, $feature, $extra ) {
  if ( !empty( $extra ) && !empty( $extra->get_header( 'Authorization' ) ) ) {    
    $token = $extra->get_header( 'Authorization' );
    $token = str_replace( 'Bearer ', '', $token );
    if ( $token === "123456" ) {
      // You don't need to absolutely do this, but it's better to link a Bearer Token to an User.
      wp_set_current_user(1);
      return true;
    }
  }
  return $allow;
}, 10, 3 );

For a quick test using the Chrome Developers Tools, you could try this in the Console:

fetch('http://ai.nekod.net/wp-json/mwai/v1/simpleChatbotQuery', { 
    method: 'POST', 
    headers: { 
        'Content-Type': 'application/json', 
        'Authorization': 'Bearer 123456'
    }, 
    body: JSON.stringify({ 
        prompt: 'Hello, who are you?', 
        botId: 'default',
    }) 
}).then(res => res.json()).then(console.log);

Client-Side API (JS)

You can interact with the chatbots and conversations directly through JS. Have a look at the MwaiAPI object that it is available directly in your JS console. If you only use one chatbot, you can get the instance by using MwaiAPI.getChatbot(). If you have many, you can mention its ID as the first argument. For example, you could do:

let chatbot = MwaiAPI.getChatbot(); // Get the chatbot; if there are more than one on the same page, you'll need to pass the ID of the chatbot in argument
chatbot.open(); // Opens the chatbot if it's minimized
chatbot.ask("How are you?", false); // Sends a request (if true, the request will be send immediately)

JS Filters

Modify the reply: ai.reply

MwaiAPI.addFilter('ai.reply', function (reply) {
  return reply + ' For more information, visit [Meow Apps](https://meowapps.com).';
});