2 min read 5 days ago

Provide users data

If you want the chatbot to know information about your user, there is only one way: add this information to the current context. When it is in the context, the AI model knows it; when it is not, it does not. It is as simple as that. There are many different ways to add information to the context, and since we want this to be user specific, we will need to add it dynamically.

Instructions

We can create some placeholders in our instructions which will get replaced with values dynamically when they are passed to the AI model. Here is an example:

Then we use a filter that will be called to modify the instructions at run time. You can add this in Code Engine or any snippet management plugin.

add_filter( 'mwai_ai_instructions', function( $instructions, $query ) {

    // Check if the user is logged in
    if ( !is_user_logged_in() ) { return $instructions; }

    // Get current user info
    $user = wp_get_current_user();
    $user_name = $user->display_name;
    $user_lastname = $user->user_lastname;
    $date = date_i18n( 'F j, Y' );

    // Replace placeholders in instructions
    $placeholders = [
        '{user_name}' => $user_name,
        '{user_lastname}' => $user_lastname,
        '{date}' => $date
    ];

    $instructions = str_replace( array_keys( $placeholders ), array_values( $placeholders ), $instructions );

    return $instructions;
}, 10, 2 );

Function Calling

If you prefer not to have placeholders in your instructions for each chatbot that would need this information, you can always make a function that fetches your users’ information, so whenever it needs it, the chatbots can fetch the information by itself. You can find an example explained here: Function Calling Example